### Usage Example: Install Chat Memory Feature Source: https://docs.koog.ai/spring-ai-integration Install the ChatMemory feature on your agent using the auto-configured ChatHistoryProvider. Ensure you have the necessary imports. ```kotlin import ai.koog.agents.chatMemory.feature.ChatMemory import ai.koog.agents.chatMemory.feature.ChatHistoryProvider import ai.koog.agents.core.agent.AIAgent import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.executor.model.PromptExecutor import org.springframework.stereotype.Service @Service class MyAgentService( private val promptExecutor: PromptExecutor, private val chatStorage: ChatHistoryProvider, ) { suspend fun askAgent(userMessage: String, sessionId: String): String { val agent = AIAgent( promptExecutor = promptExecutor, llmModel = OpenAIModels.Chat.GPT5Nano, systemPrompt = "You are a helpful assistant.", ) { install(ChatMemory) { chatHistoryProvider = chatStorage } } return agent.run(userMessage, sessionId) } } ``` -------------------------------- ### Example Tool Call Output Source: https://docs.koog.ai/agents/basic-agents This is an example of the output generated when an agent calls the `askUser` tool, showing the tool name and its arguments. ```text Tool called: askUser with args {"question":"Which meme would you like me to explain?"} ``` -------------------------------- ### Define Example Weather Forecasts Source: https://docs.koog.ai/structured-output Provide a list of WeatherForecast objects as examples to guide the LLM in generating structured output. ```kotlin val exampleForecasts = listOf( WeatherForecast( news = listOf(WeatherNews(0.0), WeatherNews(5.0)), sources = mutableMapOf( "openweathermap" to WeatherSource(Url("https://api.openweathermap.org/data/2.5/weather")), "googleweather" to WeatherSource(Url("https://weather.google.com")) ) // Other fields ), WeatherForecast( news = listOf(WeatherNews(25.0), WeatherNews(35.0)), sources = mutableMapOf( "openweathermap" to WeatherSource(Url("https://api.openweathermap.org/data/2.5/weather")), "googleweather" to WeatherSource(Url("https://weather.google.com")) ) ) ) ``` -------------------------------- ### Start A2A Server Source: https://docs.koog.ai/a2a-koog-integration Set up and start an A2A server using `A2AServer`, `HttpJSONRPCServerTransport`, and `Netty`. The server will be discoverable via the A2A protocol. ```kotlin val agentCard = AgentCard( name = "Koog Agent", url = "http://localhost:9999/koog", description = "Simple universal agent powered by Koog", version = "1.0.0", protocolVersion = "0.3.0", preferredTransport = TransportProtocol.JSONRPC, capabilities = AgentCapabilities(streaming = true), defaultInputModes = listOf("text"), defaultOutputModes = listOf("text"), skills = listOf( AgentSkill( id = "koog", name = "Koog Agent", description = "Universal agent powered by Koog. Supports tool calling.", tags = listOf("chat", "tool"), ) ) ) // Server setup val server = A2AServer(agentExecutor = KoogAgentExecutor(), agentCard = agentCard) val transport = HttpJSONRPCServerTransport(server) transport.start(engineFactory = Netty, port = 8080, path = "/chat", wait = true) ``` -------------------------------- ### Basic Kotlin Example with Weave Exporter Source: https://docs.koog.ai/features/open-telemetry/opentelemetry-weave-exporter Demonstrates how to install the OpenTelemetry feature and add the Weave exporter to an AIAgent in Kotlin. It retrieves W&B configuration from environment variables. ```kotlin fun main() = runBlocking { val entity = System.getenv()["WEAVE_ENTITY"] ?: throw IllegalArgumentException("WEAVE_ENTITY is not set") val projectName = System.getenv()["WEAVE_PROJECT_NAME"] ?: "koog-tracing" val agent = AIAgent( promptExecutor = promptExecutor, llmModel = OpenAIModels.Chat.GPT4oMini, systemPrompt = "You are a code assistant. Provide concise code examples." ) { install(OpenTelemetry) { addWeaveExporter() } } println("Running agent with Weave tracing") val result = agent.run("Tell me a joke about programming") println("Result: $result\nSee traces on https://wandb.ai/$entity/$projectName/weave/traces") } ``` -------------------------------- ### Install Agent Persistence in Java Source: https://docs.koog.ai/features/agent-persistence Add the Persistence feature to your agent's configuration using Java. This example demonstrates using in-memory storage for snapshots. ```java AIAgent agent = AIAgent.builder() .promptExecutor(executor) .llmModel(OllamaModels.Meta.LLAMA_3_2) .install(Persistence.Feature, cfg -> { // Use in-memory storage for snapshots cfg.setStorage(new InMemoryPersistenceStorageProvider()); }) .build(); ``` -------------------------------- ### Basic Java Example with Weave Exporter Source: https://docs.koog.ai/features/open-telemetry/opentelemetry-weave-exporter Illustrates how to configure and install the OpenTelemetry feature with the Weave exporter for an AIAgent in Java. It handles environment variable retrieval and provides default values. ```java public static void main(String[] args) { var entity = Optional.ofNullable(System.getenv("WEAVE_ENTITY")) .filter(env -> !env.isBlank()) .orElseThrow(() -> new IllegalArgumentException("WEAVE_ENTITY is not set")); var projectName = Optional.ofNullable(System.getenv("WEAVE_PROJECT_NAME")) .filter(env -> !env.isBlank()) .orElse("koog-tracing"); var agent = AIAgent.builder() .promptExecutor(promptExecutor) .llmModel(OpenAIModels.Chat.GPT4oMini) .systemPrompt("You are a helpful assistant.") .install(OpenTelemetry.Feature, config -> WeaveKt.addWeaveExporter( config, null, // weaveOtelBaseUrl: falls back to WEAVE_URL, defaults to https://trace.wandb.ai entity, projectName // remaining params (apiKey, timeout) use defaults ) ) .build(); System.out.println("Running agent with Weave tracing"); var result = agent.run("Tell me a joke about programming"); System.out.println("Result: " + result + "\nSee traces on https://wandb.ai/" + entity + "/" + projectName + "/weave/traces"); } ``` -------------------------------- ### Example Usage of Chat Agent Strategy (Kotlin) Source: https://docs.koog.ai/predefined-agent-strategies Demonstrates running an AI agent configured with the chatAgentStrategy and specific tools for a user query. ```kotlin val chatAgent = AIAgent( promptExecutor = promptExecutor, llmModel = model, // Use chatAgentStrategy as the agent strategy strategy = chatAgentStrategy(), // Add tools the agent can use toolRegistry = ToolRegistry { tool(searchTool) tool(weatherTool) } ) suspend fun main() { // Run the agent with a user query val result = chatAgent.run("What's the weather like today and should I bring an umbrella?") } ``` -------------------------------- ### Quick Start: Long-Term Memory with In-Memory Storage Source: https://docs.koog.ai/features/long-term-memory Initializes an AI agent with Long-Term Memory enabled, using an in-memory storage for retrieval. Suitable for quick setup and testing. ```kotlin val myStorage = InMemoryRecordStorage() // or your vector DB adapter val agent = AIAgent( promptExecutor = executor, strategy = singleRunStrategy(), agentConfig = agentConfig, toolRegistry = ToolRegistry.EMPTY ) { install(LongTermMemory) { retrieval { storage = myStorage searchStrategy = SimilaritySearchStrategy(topK = 5) } } } agent.run("What did we discuss yesterday?") ``` ```java InMemoryRecordStorage myStorage = new InMemoryRecordStorage(); AIAgent agent = AIAgent.builder() .promptExecutor(executor) .llmModel(OpenAIModels.Chat.GPT4o) .systemPrompt("You are a helpful assistant.") .install(LongTermMemory.Feature, config -> { config.retrieval( new LongTermMemory.RetrievalSettingsBuilder() .withStorage(myStorage) .withSearchStrategy( SearchStrategy.builder().similarity().withTopK(5).build() ) .build() ); }) .build(); Object result = agent.run("What did we discuss yesterday?"); ``` -------------------------------- ### Example Output of Sequential LLM Calls Source: https://docs.koog.ai/agents/functional-agents This is an example of the output produced by the sequential LLM calls, demonstrating formatted text. ```text To calculate the product of 12 and 9, we multiply these two numbers together. 12 × 9 = **108** ``` -------------------------------- ### Define Agent Strategy with Subgraphs (Java) Source: https://docs.koog.ai/custom-subgraphs Demonstrates defining an agent strategy using Java, outlining the structure for subgraphs and node interactions. This example focuses on the initial setup and the research subgraph. ```java // Define the agent strategy var strategyBuilder = AIAgentGraphStrategy.builder("assistant") .withInput(String.class) .withOutput(String.class); // A subgraph that includes a tool call var nodeCallLLM = AIAgentNode.llmRequest(null); var nodeExecuteTool = AIAgentNode.executeTools(null); var nodeSendToolResult = AIAgentNode.llmSendToolResults(null); var researchSubgraph = AIAgentSubgraph.builder("research_subgraph") .limitedTools(new WebSearchToolSet()) .withInput(String.class) .withOutput(String.class) .define(subgraph -> { subgraph .edge(AIAgentEdge.builder() .from(subgraph.nodeStart) .to(nodeCallLLM) .build() ) .edge(AIAgentEdge.builder() .from(nodeCallLLM) .to(nodeExecuteTool) .onToolCalls() .build() ) .edge(nodeExecuteTool, nodeSendToolResult) .edge(AIAgentEdge.builder() .from(nodeSendToolResult) .to(nodeExecuteTool) .onToolCalls() .build() ) .edge(AIAgentEdge.builder() .from(nodeCallLLM) .to(subgraph.nodeFinish) .onTextMessage() .build() ) .build(); }) .build(); var nodeUpdatePrompt = AIAgentNode.builder() .withInput(String.class) .withOutput(String.class) .withAction((research, ctx) -> { ctx.getLlm().writeSession(session -> { ``` -------------------------------- ### Configuring Custom Storage Provider (Java) Source: https://docs.koog.ai/features/agent-persistence Install the Persistence feature and set a custom storage provider using `cfg.setStorage()` during agent configuration. ```java AIAgent agent = AIAgent.builder() .promptExecutor(executor) .llmModel(OllamaModels.Meta.LLAMA_3_2) .install(Persistence.Feature, cfg -> { cfg.setStorage(new MyCustomStorageProvider()); }) .build(); ``` -------------------------------- ### Create Pre-defined OpenAI Executor (Kotlin) Source: https://docs.koog.ai/prompts/prompt-executors Use this for a quick setup of an OpenAI prompt executor. It wraps an OpenAILLMClient. ```kotlin // Create an OpenAI executor val promptExecutor = simpleOpenAIExecutor("OPENAI_API_KEY") ``` -------------------------------- ### Create Pre-defined OpenAI Executor (Java) Source: https://docs.koog.ai/prompts/prompt-executors Use this for a quick setup of an OpenAI prompt executor. It wraps an OpenAILLMClient. ```java // Create an OpenAI executor PromptExecutor openAIExecutor = simpleOpenAIExecutor("OPENAI_API_KEY"); ``` -------------------------------- ### Example Chat Session Source: https://docs.koog.ai/features/chat-memory/chat-agent-with-memory This example demonstrates a typical chat interaction where the agent remembers previous user inputs and uses them to answer subsequent questions. It highlights the effectiveness of chat memory in maintaining conversational context. ```text You: My name is Alice. Assistant: Nice to meet you, Alice! How can I help you today? You: What's my favorite color? It's blue. Assistant: Got it — your favorite color is blue! You: What's my name? Assistant: Your name is Alice! ``` -------------------------------- ### Full Example: Structured Output API with SimpleWeatherForecast Source: https://docs.koog.ai/structured-output Demonstrates the complete usage of the Structured Output API, including data class definition, schema generation, agent strategy configuration, and agent execution. ```kotlin // Note: Import statements are omitted for brevity @Serializable @SerialName("SimpleWeatherForecast") @LLMDescription("Simple weather forecast for a location") data class SimpleWeatherForecast( @property:LLMDescription("Location name") val location: String, @property:LLMDescription("Temperature in Celsius") val temperature: Int, @property:LLMDescription("Weather conditions (e.g., sunny, cloudy, rainy)") val conditions: String ) val token = System.getenv("OPENAI_KEY") ?: error("Environment variable OPENAI_KEY is not set") fun main(): Unit = runBlocking { // Create sample forecasts val exampleForecasts = listOf( SimpleWeatherForecast( location = "New York", temperature = 25, conditions = "Sunny" ), SimpleWeatherForecast( location = "London", temperature = 18, conditions = "Cloudy" ) ) // Generate JSON Schema val forecastStructure = JsonStructure.create( schemaGenerator = BasicJsonSchemaGenerator.Default, examples = exampleForecasts ) // Define the agent strategy val agentStrategy = strategy("weather-forecast") { val setup by nodeLLMRequest() val getStructuredForecast by node { _ -> val structuredResponse = llm.writeSession { requestLLMStructured() } """ Response structure: $structuredResponse """.trimIndent() } edge(nodeStart forwardTo setup) edge(setup forwardTo getStructuredForecast) edge(getStructuredForecast forwardTo nodeFinish) } // Configure and run the agent val agentConfig = AIAgentConfig( prompt = prompt("weather-forecast-prompt") { system( """ You are a weather forecasting assistant. When asked for a weather forecast, provide a realistic but fictional forecast. """.trimIndent() ) }, model = OpenAIModels.Chat.GPT4o, maxAgentIterations = 5 ) val runner = AIAgent( promptExecutor = simpleOpenAIExecutor(token), toolRegistry = ToolRegistry.EMPTY, strategy = agentStrategy, agentConfig = agentConfig ) runner.run("Get weather forecast for Paris") } ``` -------------------------------- ### Filter Agent Events with EventFilter Source: https://docs.koog.ai/features/custom-features Apply filters to specific agent events within a feature's installation. This example allows only LLM call start and end events. ```kotlin install(MyFeature) { setEventFilter { context -> context.eventType is AgentLifecycleEventType.LLMCallStarting || context.eventType is AgentLifecycleEventType.LLMCallCompleted } } ``` -------------------------------- ### Create Simple LLM Planner Agent (Java) Source: https://docs.koog.ai/agents/planner-agents/llm-based-planners Example of creating a simple planner agent using SimpleLLMPlanner in Java. Ensure the OPENAI_API_KEY environment variable is set. ```java // Create the planner strategy with LLM-based planner AIAgentPlannerStrategy strategy = Planners.llmBased("simple-planner") .build(); // Create the OpenAI executor var promptExecutor = PromptExecutor.builder() .openAI("OPENAI_API_KEY") .build(); // Create the planner agent using AIAgent builder AIAgent agent = AIAgent.builder() .plannerStrategy(strategy) .promptExecutor(promptExecutor) .llmModel(OpenAIModels.Chat.GPT4o) .systemPrompt("You are a helpful planning assistant.") .maxIterations(50) .build(); // Run the agent with a task String result = agent.run("Create a plan to organize a team meeting"); System.out.println(result); ``` -------------------------------- ### Create Simple LLM Planner Agent (Kotlin) Source: https://docs.koog.ai/agents/planner-agents/llm-based-planners Example of creating a simple planner agent using SimpleLLMPlanner in Kotlin. Ensure the OPENAI_API_KEY environment variable is set. ```kotlin // Create the planner val planner = SimpleLLMPlanner() // Wrap it in a planner strategy val strategy = AIAgentPlannerStrategy( name = "simple-planner", planner = planner ) // Configure the agent val agentConfig = AIAgentConfig( prompt = prompt("planner") { system("You are a helpful planning assistant.") }, model = OpenAIModels.Chat.GPT4o, maxAgentIterations = 50 ) // Create the planner agent val agent = PlannerAIAgent( promptExecutor = simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")), strategy = strategy, agentConfig = agentConfig ) suspend fun main() { // Run the agent with a task val result = agent.run("Create a plan to organize a team meeting") println(result) } ``` -------------------------------- ### Install Custom Logging Feature in Agent Source: https://docs.koog.ai/features/custom-features Install the custom logging feature into an AI agent. This example demonstrates setting a custom logger name using the `loggerName` configuration property. ```kotlin val agent = AIAgent( promptExecutor = simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")), systemPrompt = "You are a helpful assistant. Answer user questions concisely.", llmModel = OpenAIModels.Chat.GPT4o ) { install(LoggingFeature) { loggerName = "my-custom-logger" } } agent.run("What is Kotlin?") ``` -------------------------------- ### Run Prompt with OpenAILLMClient in Java Source: https://docs.koog.ai/prompts/llm-clients Shows how to initialize an `OpenAILLMClient`, build a prompt with system and user messages, execute it using a specified model, and display the output. Ensure the `OPENAI_API_KEY` is set in the environment. ```java // Create an OpenAI client String apiKey = System.getenv("OPENAI_API_KEY"); OpenAILLMClient client = openAIClient(apiKey); // Create a prompt Prompt prompt = Prompt.builder("prompt_name") // Add a system message to set the context .system("You are a helpful assistant.") // Add a user message .user("Tell me about Kotlin") // You can also add assistant messages for few-shot examples .assistant("Kotlin is a modern programming language...") // Add another user message .user("What are its key features?") .build(); // Run the prompt List response = client.execute(prompt, OpenAIModels.Chat.GPT4o, Collections.emptyList()); // Print the response System.out.println(response); client.close(); ``` -------------------------------- ### FactRetrievalHistoryCompressionStrategy Example Source: https://docs.koog.ai/history-compression Illustrates the setup for a FactRetrievalHistoryCompressionStrategy, defining facts to extract and their types. This strategy is useful for identifying specific pieces of information within a conversation. ```typescript new FactRetrievalHistoryCompressionStrategy([ new Fact( "issue_solved", // Description to the LLM -- what specifically to search for "Was the initial user's issue resolved?", // LLM would search for a single answer to the question: FactType.SINGLE ) ])); ``` -------------------------------- ### Start Unity MCP Server Process Source: https://docs.koog.ai/examples/UnityMcp Launches the Unity MCP server executable from a specified project path and port. The server communicates over stdio. ```kotlin // https://github.com/IvanMurzak/Unity-MCP val pathToUnityProject = "path/to/unity/project" val process = ProcessBuilder( "$pathToUnityProject/com.ivanmurzak.unity.mcp.server/bin~/Release/net9.0/com.IvanMurzak.Unity.MCP.Server", "60606" ).start() ``` -------------------------------- ### Install Agent Persistence in Kotlin Source: https://docs.koog.ai/features/agent-persistence Add the Persistence feature to your agent's configuration using Kotlin. This example demonstrates using in-memory storage for snapshots. ```kotlin val agent = AIAgent( promptExecutor = executor, llmModel = OllamaModels.Meta.LLAMA_3_2, ) { install(Persistence) { // Use in-memory storage for snapshots storage = InMemoryPersistenceStorageProvider() } } ``` -------------------------------- ### Create a Banking Agent with Money Transfer Tools Source: https://docs.koog.ai/examples/Banking This snippet demonstrates how to initialize an AI agent service with money transfer tools and a system prompt for banking operations. It uses OpenAI's GPT-4o-mini model and includes the AskUser tool for interactive clarification. Use this for creating conversational AI agents that can perform financial transactions. ```kotlin import ai.koog.agents.core.agent.AIAgent import ai.koog.agents.core.agent.AIAgentService import ai.koog.agents.core.tools.ToolRegistry import ai.koog.agents.core.tools.reflect.asTools import ai.koog.agents.ext.tool.AskUser import ai.koog.prompt.executor.clients.openai.OpenAIModels import kotlinx.coroutines.runBlocking val transferAgentService = AIAgentService( executor = openAIExecutor, llmModel = OpenAIModels.Chat.GPT4oMini, systemPrompt = bankingAssistantSystemPrompt, temperature = 0.0, // Use deterministic responses for financial operations toolRegistry = ToolRegistry { tool(AskUser) tools(MoneyTransferTools().asTools()) } ) // Test the agent with various scenarios println("Banking Assistant started") val message = "Send 25 euros to Daniel for dinner at the restaurant." // Other test messages you can try: // - "Send 50 euros to Alice for the concert tickets" // - "What's my current balance?" // - "Transfer 100 euros to Bob for the shared vacation expenses" runBlocking { val result = transferAgentService.createAgentAndRun(message) result } ``` -------------------------------- ### Basic Datadog Exporter Setup in Java Source: https://docs.koog.ai/features/open-telemetry/opentelemetry-datadog-exporter Installs the OpenTelemetry feature and adds the Datadog exporter to an AIAgent. Ensure your Datadog API key is set as an environment variable. ```java public static void main(String[] args) { var agent = AIAgent.builder() .promptExecutor(promptExecutor) .llmModel(OpenAIModels.Chat.GPT4oMini) .systemPrompt("You are a code assistant. Provide concise code examples.") .install(OpenTelemetry.Feature, config -> DatadogKt.addDatadogExporter(config) ) .build(); System.out.println("Running agent with Datadog tracing"); var result = agent.run("Tell me a joke about programming"); System.out.println("Result: " + result + "\nSee traces in Datadog LLM Observability"); } ``` -------------------------------- ### Basic Datadog Exporter Setup in Kotlin Source: https://docs.koog.ai/features/open-telemetry/opentelemetry-datadog-exporter Installs the OpenTelemetry feature and adds the Datadog exporter to an AIAgent. Ensure your Datadog API key is set as an environment variable. ```kotlin fun main() = runBlocking { val agent = AIAgent( promptExecutor = promptExecutor, llmModel = OpenAIModels.Chat.GPT4oMini, systemPrompt = "You are a code assistant. Provide concise code examples." ) { install(OpenTelemetry) { addDatadogExporter() } } println("Running agent with Datadog tracing") val result = agent.run("Tell me a joke about programming") println("Result: $result\nSee traces in Datadog LLM Observability") } ``` -------------------------------- ### Initialize and Run Chess Game Source: https://docs.koog.ai/examples/Chess Initializes the chess game, prints the starting board, and runs the agent to make the first move. This code requires a pre-configured agent and game object. ```kotlin println("Chess Game started!") val initialMessage = "Starting position is ${game.getBoard()}. White to move!" runBlocking { agent.run(initialMessage) } ``` -------------------------------- ### Configure and Initialize Banking Assistant Agent Source: https://docs.koog.ai/examples/Banking Sets up the agent configuration, including prompt, model, and iteration limits. Initializes the AI agent with the strategy, executor, and tool registry. ```kotlin import ai.koog.agents.core.agent.config.AIAgentConfig import ai.koog.prompt.dsl.prompt val agentConfig = AIAgentConfig( prompt = prompt(id = "banking assistant") { system("$bankingAssistantSystemPrompt\n$transactionAnalysisPrompt") }, model = OpenAIModels.Chat.GPT4o, maxAgentIterations = 50 // Allow for complex multi-step operations ) val agent = AIAgent( promptExecutor = openAIExecutor, strategy = strategy, agentConfig = agentConfig, toolRegistry = toolRegistry, ) ``` -------------------------------- ### Integrating Chat Memory and Persistence Source: https://docs.koog.ai/features/chat-memory Example of installing both `ChatMemory` and `Persistence` features for an agent. This configuration includes a custom chat history provider and persistence storage, with automatic persistence enabled. ```kotlin val agent = AIAgent( promptExecutor = executor, llmModel = OpenAIModels.Chat.GPT4oMini, systemPrompt = "You are a helpful assistant.", ) { install(ChatMemory) { chatHistoryProvider = MyDatabaseProvider() windowSize(50) } install(Persistence) { storage = MyPersistenceStorageProvider() enableAutomaticPersistence = true } } ``` -------------------------------- ### Initialize and Run an AI Agent with Kotlin Source: https://docs.koog.ai/prompts Set up an AI agent with a system prompt and LLM model, then run it with a user message. The agent automatically converts text prompts to Prompt objects. ```kotlin // Create an agent val agent = AIAgent( promptExecutor = simpleOpenAIExecutor(apiKey), systemPrompt = "You are a helpful assistant.", llmModel = OpenAIModels.Chat.GPT4o ) // Run the agent val result = agent.run("What is Koog?") ``` -------------------------------- ### Discover MCP Tools Source: https://docs.koog.ai/examples/GoogleMapsMcp Connects to the MCP server over stdio, creates a tool registry, and prints the discovered tools and their descriptors. ```kotlin val toolRegistry = McpToolRegistryProvider.fromTransport( transport = McpToolRegistryProvider.defaultStdioTransport(process) ) toolRegistry.tools.forEach { println(it.name) println(it.descriptor) } ``` -------------------------------- ### Create GOAP Planner for Content Creation Source: https://docs.koog.ai/agents/planner-agents/goap-agents Instantiate a GOAP planner using the `goap()` function, defining actions for creating an article. This example demonstrates actions for creating an outline, writing a draft, reviewing content, and publishing. ```kotlin // Create GOAP planner with LLM-powered actions val planner = goap("content-planner", ::ContentState) { // Define actions with preconditions and beliefs action( name = "Create outline", precondition = { state -> !state.hasOutline }, belief = { state -> state.copy(hasOutline = true, outline = "Outline") }, cost = { 1.0 } ) { ctx, state -> // Use LLM to create the outline val response = ctx.llm.writeSession { appendPrompt { user("Create a detailed outline for an article about: ${state.topic}") } requestLLM() } state.copy(hasOutline = true, outline = response.parts.filterIsInstance().joinToString("\n") { it.text }) } action( name = "Write draft", precondition = { state -> state.hasOutline && !state.hasDraft }, belief = { state -> state.copy(hasDraft = true, draft = "Draft") }, cost = { 2.0 } ) { ctx, state -> // Use LLM to write the draft val response = ctx.llm.writeSession { appendPrompt { user("Write an article based on this outline:\n${state.outline}") } requestLLM() } state.copy(hasDraft = true, draft = response.parts.filterIsInstance().joinToString("\n") { it.text }) } action( name = "Review content", precondition = { state -> state.hasDraft && !state.hasReview }, belief = { state -> state.copy(hasReview = true) }, cost = { 1.0 } ) { ctx, state -> // Use LLM to review the draft val response = ctx.llm.writeSession { appendPrompt { user("Review this article and suggest improvements:\n${state.draft}") } requestLLM() } println("Review feedback: ${response.parts.filterIsInstance().joinToString("\n") { it.text }}") state.copy(hasReview = true) } action( name = "Publish", precondition = { state -> state.hasReview && !state.isPublished }, ``` -------------------------------- ### FromLastNMessages Strategy in Compression Node (Java) Source: https://docs.koog.ai/history-compression Configure a compression node in Java to use the `FromLastNMessages` strategy, specifying the number of messages to retain (e.g., 5). This example shows node creation; graph completion requires additional setup. ```java // Using FromLastNMessages strategy to compress only the last 5 messages var compressHistory = AIAgentNode .llmCompressHistory("compressHistory") .withInput(String.class) .compressionStrategy(HistoryCompressionStrategy.FromLastNMessages(5)) .build(); // Note: This example only shows the node creation. // You would need to add edges and other nodes to complete the graph. ``` -------------------------------- ### Install Custom Feature in Agent Source: https://docs.koog.ai/features/custom-features This code demonstrates how to install a custom feature, 'MyFeature', when creating an AI agent. It shows the usage of the `install` method with a lambda to configure the feature. ```kotlin val agent = AIAgent( promptExecutor = simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")), systemPrompt = "You are a helpful assistant. Answer user questions concisely.", llmModel = OpenAIModels.Chat.GPT4o ) { install(MyFeature) { configProperty = "value" } } ``` -------------------------------- ### Configure and Create AI Agent Source: https://docs.koog.ai/examples/VaccumAgent Set up the AI agent by defining its environment, connecting to an LLM, registering tools, and specifying the system prompt and configuration. Ensure the OPENAI_API_KEY environment variable is set. ```kotlin import ai.koog.agents.core.agent.AIAgent import ai.koog.agents.core.agent.config.AIAgentConfig import ai.koog.agents.core.tools.ToolRegistry import ai.koog.agents.core.tools.reflect.asTools import ai.koog.agents.ext.agent.chatAgentStrategy import ai.koog.agents.ext.tool.AskUser import ai.koog.agents.ext.tool.SayToUser import ai.koog.prompt.dsl.prompt import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor import ai.koog.prompt.params.LLMParams val env = VacuumEnv() val apiToken = System.getenv("OPENAI_API_KEY") ?: error("OPENAI_API_KEY environment variable not set") val executor = simpleOpenAIExecutor(apiToken = apiToken) val toolRegistry = ToolRegistry { tool(SayToUser) tool(AskUser) tools(VacuumTools(env).asTools()) } val systemVacuumPrompt = """ You are a reflex vacuum-cleaner agent living in a two-cell world labelled A and B. Your goal: make both cells clean, using the provided tools. First, call sense() to inspect where you are. Then decide: if dirty → clean(); else moveLeft()/moveRight(). Continue until both cells are clean, then tell the user "done". Use sayToUser to inform the user about each step. """.trimIndent() val agentConfig = AIAgentConfig( prompt = prompt("chat", params = LLMParams(temperature = 1.0)) { system(systemVacuumPrompt) }, model = OpenAIModels.Chat.GPT4o, maxAgentIterations = 50, ) val agent = AIAgent( promptExecutor = executor, strategy = chatAgentStrategy(), agentConfig = agentConfig, toolRegistry = toolRegistry ) ``` -------------------------------- ### Install A2AAgentServer Feature Source: https://docs.koog.ai/a2a-koog-integration Install the A2AAgentServer feature on a Koog agent. Requires the `context` and `eventProcessor` to be provided. ```kotlin // Install the feature install(A2AAgentServer) { this.context = context this.eventProcessor = eventProcessor } ``` -------------------------------- ### Start HTTP JSON-RPC Server Transport Source: https://docs.koog.ai/a2a-server Starts the A2A server's HTTP JSON-RPC transport layer. Configurable with Ktor engine, port, and API path. The `wait` parameter controls whether the server start blocks execution. ```kotlin val transport = HttpJSONRPCServerTransport(server) transport.start( engineFactory = CIO, // Ktor engine (CIO, Netty, Jetty) port = 8080, // Server port path = "/a2a", // API endpoint path wait = true // Block until server stops ) ``` -------------------------------- ### Full MCP Client with OpenTelemetry Source: https://docs.koog.ai/features/open-telemetry Set up an MCP agent with OpenTelemetry enabled. This example shows how to configure service information and add a logging span exporter. MCP tool calls will be automatically instrumented. ```kotlin val toolRegistry = McpToolRegistryProvider.fromSseUrl("http://localhost:3000") val agent = AIAgent( promptExecutor = promptExecutor, llmModel = OpenAIModels.Chat.GPT4o, systemPrompt = "You are a helpful assistant.", toolRegistry = toolRegistry ) { install(OpenTelemetry) { setServiceInfo("mcp-agent-service", "1.0.0") addSpanExporter(LoggingSpanExporter.create()) } } agent.use { it.run("Use the search tool to find information") } ``` -------------------------------- ### Initialize and Run Transaction Analysis Agent Source: https://docs.koog.ai/examples/Banking Sets up an AI agent service with transaction analysis tools and executes a query. The agent is configured with a specific LLM model and system prompt. ```kotlin val analysisAgentService = AIAgentService( executor = openAIExecutor, llmModel = OpenAIModels.Chat.GPT4oMini, systemPrompt = "$bankingAssistantSystemPrompt\n$transactionAnalysisPrompt", temperature = 0.0, toolRegistry = ToolRegistry { tools(TransactionAnalysisTools().asTools()) } ) println("Transaction Analysis Assistant started") val analysisMessage = "How much have I spent on restaurants this month?" // Other queries to try: // - "What's my maximum check at a restaurant this month?" // - "How much did I spend on groceries in the first week of May?" // - "What's my total spending on entertainment in May?" // - "Show me all transactions from last week" runBlocking { val result = analysisAgentService.createAgentAndRun(analysisMessage) result } ``` -------------------------------- ### Start Jaeger All-in-One Source: https://docs.koog.ai/features/open-telemetry Start the Jaeger OpenTelemetry all-in-one process using Docker Compose to enable tracing. ```bash docker compose up -d ``` -------------------------------- ### Pass-through Node Example Source: https://docs.koog.ai/nodes-and-components Implement a pass-through node that forwards its input without modification. Useful for creating placeholders or connection points in a graph. The Kotlin example shows graph construction, while the Java example focuses on node building and strategy integration. ```kotlin val passthrough by nodeDoNothing("passthrough") edge(nodeStart forwardTo passthrough) edge(passthrough forwardTo nodeFinish) ``` ```java var passthrough = AIAgentNode.builder("passthrough") .withInput(String.class) .withOutput(String.class) .withAction((input, ctx) -> input) .build(); strategy.edge(strategy.nodeStart, passthrough); strategy.edge(passthrough, strategy.nodeFinish); ``` -------------------------------- ### Configure Simple Agent with Constructor Source: https://docs.koog.ai/agents For simple agents, specify initial system prompt, language model, and iteration limits directly in the agent constructor. Requires an API key for the prompt executor. ```kotlin val agent = AIAgent( promptExecutor = simpleOpenAIExecutor(System.getenv("YOUR_API_KEY")), llmModel = OpenAIModels.Chat.GPT4o, systemPrompt = "You are a helpful assistant.", temperature = 0.7, maxIterations = 10 ) ``` ```java AIAgent agent = AIAgent.builder() .promptExecutor(simpleOpenAIExecutor(System.getenv("YOUR_API_KEY"))) .llmModel(OpenAIModels.Chat.GPT4o) .systemPrompt("You are a helpful assistant.") .temperature(0.7) .maxIterations(10) .build(); ``` -------------------------------- ### Initialize and Run Chess Agent Source: https://docs.koog.ai/examples/Chess Initializes the chess game and runs the agent with an initial message. This sets up the game's starting position and prompts the agent to begin. ```kotlin println("Chess Game started!") val initialMessage = "Starting position is ${game.getBoard()}. White to move!" runBlocking { agent.run(initialMessage) } ``` -------------------------------- ### Setup ReAct Agent in Java Source: https://docs.koog.ai/predefined-agent-strategies This Java snippet demonstrates how to configure an AI agent with the ReAct strategy using the builder pattern. It requires setting up `PromptExecutor`, `llmModel`, and `toolRegistry`. ```java AIAgent reActAgent = AIAgent.builder() .promptExecutor(PromptExecutor.builder().openAI("OPENAI_API_KEY").build()) .llmModel(OpenAIModels.Chat.O4Mini) .toolRegistry(ToolRegistry.builder().build()) // Set reActStrategy as the agent strategy .graphStrategy(AIAgentStrategies.reActStrategy( // Set optional parameter values 1, // reasoningInterval "react_agent" // name )) .build(); ``` -------------------------------- ### Build Prompt with Attachments Source: https://docs.koog.ai/examples/Attachments Builds a prompt that asks the model to generate a short, blog-style "content card" and attaches two images from the local `images/` directory. Requires importing `ai.koog.prompt.markdown.markdown` and `kotlinx.io.files.Path`. ```kotlin import ai.koog.prompt.markdown.markdown import kotlinx.io.files.Path val prompt = prompt("images-prompt") { system("You are professional assistant that can write cool and funny descriptions for Instagram posts.") user { markdown { +"I want to create a new post on Instagram." br() +"Can you write something creative under my instagram post with the following photos?" br() h2("Requirements") bulleted { item("It must be very funny and creative") item("It must increase my chance of becoming an ultra-famous blogger!!!!") item("It not contain explicit content, harassment or bullying") item("It must be a short catching phrase") item("You must include relevant hashtags that would increase the visibility of my post") } } attachments { image(Path("images/kodee-loving.png")) image(Path("images/kodee-electrified.png")) } } } ``` -------------------------------- ### Start OpenTelemetry Stack Source: https://docs.koog.ai/examples/OpenTelemetry Start the local OpenTelemetry Collector and Jaeger services using Docker Compose. Ensure this is running before executing the agent. ```bash ./docker-compose up -d ``` -------------------------------- ### LLM Response Example (Temperature 0.7) Source: https://docs.koog.ai/agents/basic-agents Example of an LLM response generated with a moderate temperature setting (0.7), balancing focus with a degree of creativity. ```text I'm here to help you navigate the wild world of internet memes! What's on your mind? Need help understanding a specific meme, finding a popular joke or trend, or maybe even creating your own meme? Let's get this meme party started! ``` -------------------------------- ### Initialize Agent with Tool Registry (Java) Source: https://docs.koog.ai/tools-overview This Java snippet shows how to initialize an AIAgent, providing a tool registry that contains the necessary tools for the agent's operation. Replace 'secondSampleTool' with your actual tool set. ```java AIAgent agent = AIAgent.builder() .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY"))) .systemPrompt("You are a helpful assistant with strong mathematical skills.") .llmModel(OpenAIModels.Chat.GPT4o) .toolRegistry(ToolRegistry.builder() .tools(secondSampleTool) .build() ) .build(); ``` -------------------------------- ### LLM Response Example (Temperature 0.4) Source: https://docs.koog.ai/agents/basic-agents Example of an LLM response generated with a low temperature setting (0.4), resulting in a more focused and predictable output. ```text I'm here to help you navigate the wild world of internet memes! Whether you're looking for explanations, examples, or just want to share a meme with someone, I'm your go-to expert. What's on your mind? Got a specific meme in mind that's got you curious? Or maybe you need some meme-related advice? Fire away! ``` -------------------------------- ### Execute a Prompt with OpenAI GPT-4o (Kotlin) Source: https://docs.koog.ai/prompts/prompt-executors Demonstrates how to execute a prompt using a pre-defined OpenAI executor and a specific model. The response will be generated by the GPT-4o model. ```kotlin // Create an OpenAI executor val promptExecutor = simpleOpenAIExecutor("OPENAI_API_KEY") // Execute a prompt val response = promptExecutor.execute( prompt = prompt("demo") { user("Summarize this.") }, model = OpenAIModels.Chat.GPT4o ) ``` -------------------------------- ### LLM Response Example (Temperature 1.0) Source: https://docs.koog.ai/agents/basic-agents Example of an LLM response generated with a high temperature setting (1.0), leading to more diverse and potentially unexpected output. ```text I'd be happy to help you navigate the wild world of internet memes! Whether you're looking for explanations of classic memes, suggestions for new ones to try out, or just want to discuss your favorite meme culture trends, I'm here to assist. What's on your mind? Do you have a specific question about memes (e.g., "What does this meme mean?"), or are you looking for some meme-related recommendations (e.g., "Can you recommend a funny meme to share with friends?"). Let me know how I can help! ``` -------------------------------- ### Setup Koog and Dependencies Source: https://docs.koog.ai/examples/Banking Configure the Kotlin Notebook environment and ensure Koog artifacts are resolvable. Uncomment the Koog dependency if not using the latest descriptors. ```kotlin %useLatestDescriptors %use datetime // uncomment this for using koog from Maven Central // %use koog ``` -------------------------------- ### Start HTTP JSON-RPC Transport Source: https://docs.koog.ai/a2a-server Configures and starts the HTTP JSON-RPC transport layer for the A2A server. Specify the engine factory, port, and path for the server endpoint. ```kotlin // HTTP JSON-RPC transport val transport = HttpJSONRPCServerTransport(server) transport.start( engineFactory = CIO, port = 8080, path = "/agent", wait = true ) ``` -------------------------------- ### Prompt Preparation Node Example Source: https://docs.koog.ai/nodes-and-components Use a prompt preparation node to add system and user messages to the LLM prompt. This node modifies the conversation context before LLM requests, useful for setting instructions or user queries. The Kotlin example uses a concise DSL, while the Java example uses a builder pattern with an appendPrompt method. ```kotlin val firstNode by node { // Transform input to output } val secondNode by node { // Transform output to output } // Node will get the value of type Output as input from the previous node and path through it to the next node val setupContext by nodeAppendPrompt("setupContext") { system("You are a helpful assistant specialized in Kotlin programming.") user("I need help with Kotlin coroutines.") } edge(firstNode forwardTo setupContext) edge(setupContext forwardTo secondNode) ``` ```java var firstNode = AIAgentNode.builder() .withInput(Input.class) .withOutput(Output.class) .withAction((input, ctx) -> { // Transform input to output return input; }) .build(); var secondNode = AIAgentNode.builder() .withInput(Output.class) .withOutput(Output.class) .withAction((output, ctx) -> { // Transform output to output return output; }) .build(); var setupContext = AIAgentNode.builder() .withInput(Output.class) .appendPrompt(prompt -> { prompt.system("You are a helpful assistant specialized in Kotlin programming."); prompt.user("I need help with Kotlin coroutines."); }); strategy.edge(firstNode, setupContext); strategy.edge(setupContext, secondNode); ``` -------------------------------- ### Run Prompt with OpenAILLMClient in Kotlin Source: https://docs.koog.ai/prompts/llm-clients Demonstrates creating an `OpenAILLMClient`, constructing a prompt with system and user messages, executing it with a specific model, and printing the response. Requires the `OPENAI_API_KEY` environment variable. ```kotlin fun main() = runBlocking { // Create an OpenAI client val apiKey = System.getenv("OPENAI_API_KEY") val client = OpenAILLMClient(apiKey) // Create a prompt val prompt = prompt("prompt_name", LLMParams()) { // Add a system message to set the context system("You are a helpful assistant.") // Add a user message user("Tell me about Kotlin") // You can also add assistant messages for few-shot examples assistant("Kotlin is a modern programming language...") // Add another user message user("What are its key features?") } // Run the prompt val response = client.execute(prompt, OpenAIModels.Chat.GPT4o) // Print the response println(response) } ``` -------------------------------- ### Initialize and Run an AI Agent with Java Source: https://docs.koog.ai/prompts Configure an AI agent using the builder pattern in Java, specifying the prompt executor, system prompt, and LLM model before running a user query. ```java AIAgent agent = AIAgent.builder() .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY"))) .systemPrompt("You are a helpful assistant. Answer user questions concisely.") .llmModel(OpenAIModels.Chat.GPT4o) .build(); var result = agent.run("What is Koog?"); ``` -------------------------------- ### Start Number Guessing Game Source: https://docs.koog.ai/examples/Guesser Initiates the number guessing game. The agent prompts the user to think of a number and then starts the game by reading user input. Requires `runBlocking` from `kotlinx.coroutines`. ```kotlin import kotlinx.coroutines.runBlocking println("Number Guessing Game started!") println("Think of a number between 1 and 100, and I'll try to guess it.") println("Type 'start' to begin the game.") val initialMessage = readln() runBlocking { agent.run(initialMessage) } ```