### Quickstart AI Agent Example Source: https://github.com/jetbrains/koog/blob/develop/README.md This example demonstrates how to initialize and run a basic AI agent using the Koog framework with OpenAI's GPT-4o model. Ensure you set the OPENAI_API_KEY environment variable before running. ```kotlin fun main() = runBlocking { // Before you run the example, assign a corresponding API key as an environment variable. val apiKey = System.getenv("OPENAI_API_KEY") // or Anthropic, Google, OpenRouter, etc. val agent = AIAgent( promptExecutor = MultiLLMPromptExecutor(OpenAILLMClient(apiKey)), // or Anthropic, Google, OpenRouter, etc. systemPrompt = "You are a helpful assistant. Answer user questions concisely.", llmModel = OpenAIModels.Chat.GPT4o ) val result = agent.run("Hello! How can you help me?") println(result) } ``` -------------------------------- ### Start PostgreSQL with Docker Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Launches a PostgreSQL container named `koog-pg` for use with JDBC examples. It maps port 5432 and sets up the `koog` database with default credentials. ```bash docker run -d --name koog-pg \ -e POSTGRES_DB=koog \ -e POSTGRES_PASSWORD=postgres \ -p 5432:5432 \ postgres:16 ``` -------------------------------- ### Run Functional Agent Chat Example (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Starts an interactive functional strategy chat loop using Gradle. The chat can be exited by typing '/bye'. ```bash ./gradlew runExampleFunctionalAgentChat ``` -------------------------------- ### Install and Start Web Application Source: https://github.com/jetbrains/koog/blob/develop/examples/koog-js-example/README.md These commands are used to install the necessary Node.js dependencies and start the development server for the web application. After execution, the application can be accessed via a link provided in the terminal. ```shell npm install npm run start ``` -------------------------------- ### Start Databases with Docker Compose Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples/src/main/kotlin/ai/koog/agents/example/snapshot/sql/README.md Starts the necessary database services (PostgreSQL, MySQL) using Docker Compose. This is a prerequisite for running the PostgreSQL and MySQL examples. ```bash docker-compose up -d ``` -------------------------------- ### Run a Specific Example with Gradle Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples/README.md Execute a particular example using Gradle's `runExample` task. Refer to the project's tasks for available examples. ```bash ./gradlew runExampleCalculator ``` -------------------------------- ### Basic Weave Exporter Setup in Kotlin Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/features/open-telemetry/opentelemetry-weave-exporter.md This example demonstrates how to install the OpenTelemetry feature and add the Weave exporter to an AIAgent. It reads W&B entity and project name from environment variables. ```kotlin import ai.koog.agents.core.agent.AIAgent import ai.koog.agents.features.opentelemetry.feature.OpenTelemetry import ai.koog.agents.features.opentelemetry.integration.weave.addWeaveExporter import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor import kotlinx.coroutines.runBlocking val promptExecutor = simpleOpenAIExecutor("openai-api-key") 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") } ``` -------------------------------- ### AI Agent Service Setup for Transaction Analysis Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/examples/Banking.md Configures an AI agent service using OpenAI's GPT-4o-mini model, incorporating transaction analysis tools. The agent is initialized with a system prompt and a tool registry. The example demonstrates running a query to get monthly restaurant spending. ```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 } ``` -------------------------------- ### Run GOAP Strategy Example (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Executes the GOAP (Goal-Oriented Action Planning) strategy example using Gradle. This demonstrates a planner-based agent with actions and state transitions. ```bash ./gradlew runExampleGoapStrategy ``` -------------------------------- ### Run Graph Strategy Example (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Executes the graph strategy example using Gradle. This involves an identify/solve/verify/fix loop for agent problem-solving. ```bash ./gradlew runExampleGraphStrategy ``` -------------------------------- ### Run Calculator Example with Gradle (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Executes the graph-based calculator agent example using Gradle. This task typically uses OpenAI by default for its operations. ```bash ./gradlew runExampleCalculator ``` -------------------------------- ### Run Functional Strategy Example (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Executes a multi-step functional workflow example with typed subtasks and a verification loop using Gradle. ```bash ./gradlew runExampleFunctionalStrategy ``` -------------------------------- ### Create and Run a Simple Single-Run AI Agent in Kotlin Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-core/QuickstartGuide.md Demonstrates how to create a basic single-run AI agent using SimpleAPI in Kotlin. It initializes an AIAgent with an executor and system prompt, then runs it with a specific query. This agent does not have tools by default. ```kotlin import ai.koog.agents.AIAgent import ai.koog.agents.executors.simpleOpenAIExecutor import kotlinx.coroutines.runBlocking fun main() = runBlocking { val apiToken = "YOUR_API_TOKEN" val agent = AIAgent( executor = simpleOpenAIExecutor(apiToken), systemPrompt = "You are a code assistant. Provide concise code examples." ) agent.run("Write a Kotlin function to calculate factorial") } ``` -------------------------------- ### Run JDBC Persistence Example (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Executes the agent persistence example backed by PostgreSQL using Gradle. This showcases saving and loading agent states or checkpoints via JDBC. ```bash ./gradlew runExamplePersistenceJdbc ``` -------------------------------- ### Define and Use Multiple Tools with a Registry Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-tools/Module.md Define a `ToolSet` with multiple tools, convert them to a list, and build a `ToolRegistry`. This example demonstrates finding a tool by name and executing it, including serialization of arguments and results. This setup is typical for agent integration. ```kotlin // Define a tool set class MathTools : ToolSet { @Tool @LLMDescription("Adds two numbers") fun add( @LLMDescription("First number") a: Int, @LLMDescription("Second number") b: Int ): Int = a + b @Tool @LLMDescription("Multiplies two numbers") fun multiply( @LLMDescription("First number") a: Int, @LLMDescription("Second number") b: Int ): Int = a * b } // Use the tools fun main() { val mathTools = MathTools() val tools = mathTools.asTools() // Create a tool registry val registry = ToolRegistry.Builder().apply { tools }.build() // Find and use a tool (in a real scenario, this would be done through an agent) val enabler = object : DirectToolCallsEnabler {} val addTool = registry.findTool("add") val args = addTool.decodeArgsFromString("{\"a\": 10, \"b\": 20}") runBlocking { val (result, stringResult) = addTool.executeAndSerialize(args, enabler) println("Result: $stringResult") // Output: Result: 30 } } ``` -------------------------------- ### Run JDBC Chat Memory Example (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Executes the chat memory example backed by PostgreSQL using Gradle. This demonstrates storing chat history in a JDBC-compliant database. ```bash ./gradlew runExampleChatMemoryJdbc ``` -------------------------------- ### Kotlin Usage Example for Chat Memory Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/spring-ai-integration.md Install the ChatMemory feature on an AIAgent using the auto-configured ChatHistoryProvider. Requires PromptExecutor and ChatHistoryProvider beans. ```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) } } ``` -------------------------------- ### Run Calculator Example with Local Ollama (Bash) Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples-java/README.md Executes the calculator agent example using a local Ollama model, specifically `llama3.2`. This allows for running the example without external API dependencies. ```bash ./gradlew runExampleCalculatorLocal ``` -------------------------------- ### Basic Weave Exporter Setup in Java Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/features/open-telemetry/opentelemetry-weave-exporter.md This Java example shows how to configure an AIAgent with the OpenTelemetry feature and the Weave exporter. It retrieves W&B entity and project name from environment variables. ```java import ai.koog.agents.core.agent.AIAgent; import ai.koog.agents.features.opentelemetry.feature.OpenTelemetry; import ai.koog.agents.features.opentelemetry.integration.weave.WeaveKt; import ai.koog.prompt.executor.clients.openai.OpenAIModels; import ai.koog.prompt.executor.model.PromptExecutor; import java.util.Optional; public class exampleWeaveExporterJava01 { static PromptExecutor promptExecutor = PromptExecutor.builder() .openAI("openai-api-key") .build(); 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"); } } ``` -------------------------------- ### Run SQL Persistence Examples Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples/src/main/kotlin/ai/koog/agents/example/snapshot/sql/README.md Executes the SQL persistence example using Gradle. It supports different database backends by passing arguments to the Gradle task. ```bash # PostgreSQL example ./gradlew :examples:runExampleSQLPersistentAgent --args="postgres" # MySQL example ./gradlew :examples:runExampleSQLPersistentAgent --args="mysql" # H2 example (embedded database) ./gradlew :examples:runExampleSQLPersistentAgent --args="h2" ``` -------------------------------- ### Registering Event Handlers in Kotlin Agent Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/agents/basic-agents.md Install the EventHandler feature and register handlers within the agent constructor lambda. This example shows how to log tool call start events. ```kotlin val agent = AIAgent( promptExecutor = simpleOpenAIExecutor(System.getenv("YOUR_API_KEY")), systemPrompt = "You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.", llmModel = OpenAIModels.Chat.GPT4o, temperature = 0.7, toolRegistry = ToolRegistry { tool(::askUser) }, maxIterations = 10 ){ handleEvents { // Handle tool calls onToolCallStarting { eventContext -> println("Tool called: ${eventContext.toolName} with args ${eventContext.toolArgs}") } } } ``` -------------------------------- ### Java @Tool Annotation Usage Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/tools/annotation-based-tools.md Demonstrates how to use the @Tool annotation in Java to expose methods as tools. Includes examples with and without a custom tool name. ```java import ai.koog.agents.core.tools.annotations.Tool; import ai.koog.agents.core.tools.reflect.ToolSet; public class MyToolSet implements ToolSet { @Tool public String myTool() { // Tool implementation return "Result"; } @Tool(customName = "customToolName") public String anotherTool() { // Tool implementation return "Result"; } } ``` -------------------------------- ### Run Gradle Task Example Source: https://github.com/jetbrains/koog/blob/develop/examples/simple-examples/README.md Execute any example using the provided Gradle wrapper command. This is the primary method for running the demonstrations. ```bash ./gradlew [task-name] ``` -------------------------------- ### Java Diagnostic ToolSet Example Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/tools/annotation-based-tools.md Defines a set of diagnostic tools for device troubleshooting using Java annotations. Includes functions for running diagnostics and analyzing error codes, with an overload for convenience. ```Java import ai.koog.agents.core.tools.reflect.ToolSet; import ai.koog.agents.core.tools.annotations.LLMDescription; import ai.koog.agents.core.tools.annotations.Tool; /** */ @LLMDescription(description = "Tools for performing diagnostics and troubleshooting on devices") public class DiagnosticToolSet implements ToolSet { // Convenience overload (not exposed as a tool) public String runDiagnostic(String deviceId) { return runDiagnostic(deviceId, ""); } @Tool @LLMDescription(description = "Run diagnostic on a device to check its status and identify any issues") public String runDiagnostic( @LLMDescription(description = "The ID of the device to diagnose") String deviceId, @LLMDescription(description = "Additional information for the diagnostic (optional)") String additionalInfo ) { // Implementation return "Diagnostic results for device " + deviceId; } @Tool @LLMDescription(description = "Analyze an error code to determine its meaning and possible solutions") public String analyzeError( @LLMDescription(description = "The error code to analyze (e.g., 'E1001')") String errorCode ) { // Implementation return "Analysis of error code " + errorCode; } } ``` -------------------------------- ### Kotlin Diagnostic ToolSet Example Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/tools/annotation-based-tools.md Defines a set of diagnostic tools for device troubleshooting using Kotlin annotations. Includes functions for running diagnostics and analyzing error codes. ```Kotlin import ai.koog.agents.core.tools.reflect.ToolSet import ai.koog.agents.core.tools.annotations.LLMDescription import ai.koog.agents.core.tools.annotations.Tool @LLMDescription("Tools for performing diagnostics and troubleshooting on devices") class DiagnosticToolSet : ToolSet { @Tool @LLMDescription("Run diagnostic on a device to check its status and identify any issues") fun runDiagnostic( @LLMDescription("The ID of the device to diagnose") deviceId: String, @LLMDescription("Additional information for the diagnostic (optional)") additionalInfo: String = "" ): String { // Implementation return "Diagnostic results for device $deviceId" } @Tool @LLMDescription("Analyze an error code to determine its meaning and possible solutions") fun analyzeError( @LLMDescription("The error code to analyze (e.g., 'E1001')") errorCode: String ): String { // Implementation return "Analysis of error code $errorCode" } } ``` -------------------------------- ### Create and Run a Simple LLM Planner Agent Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/agents/planner-agents/llm-based-planners.md Demonstrates how to initialize a SimpleLLMPlanner, configure an AIAgent with it, and run the agent with a task. Assumes OPENAI_API_KEY is set. ```kotlin import ai.koog.agents.core.agent.config.AIAgentConfig import ai.koog.agents.core.planner.AIAgentPlannerStrategy import ai.koog.agents.core.planner.PlannerAIAgent import ai.koog.agents.planner.llm.SimpleLLMPlanner import ai.koog.prompt.dsl.prompt import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor import kotlinx.coroutines.runBlocking // 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) } ``` -------------------------------- ### Start Jaeger Container Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-features/agents-features-opentelemetry/README.md Example docker-compose configuration to start a Jaeger all-in-one container with OTLP enabled. ```yaml # docker-compose.yaml services: jaeger-all-in-one: image: jaegertracing/all-in-one:1.39 container_name: jaeger-all-in-one environment: - COLLECTOR_OTLP_ENABLED=true ports: - "4317:4317" # OTLP gRPC port - "16686:16686" # Jaeger UI port ``` -------------------------------- ### Kotlin @Tool Annotation Usage Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/tools/annotation-based-tools.md Shows how to apply the @Tool annotation to Kotlin functions within a class implementing ToolSet. Includes examples with and without a custom tool name. ```kotlin import ai.koog.agents.core.tools.annotations.Tool import ai.koog.agents.core.tools.reflect.ToolSet class MyToolSet : ToolSet { @Tool fun myTool(): String { // Tool implementation return "Result" } @Tool(customName = "customToolName") fun anotherTool(): String { // Tool implementation return "Result" } } ``` -------------------------------- ### Setup and Teardown for RedisPromptCache in Tests (Kotlin) Source: https://github.com/jetbrains/koog/blob/develop/prompt/prompt-cache/prompt-cache-redis/Module.md Provides a complete example for setting up and tearing down a RedisPromptCache within a test class. It includes starting an embedded Redis server, creating the cache, and ensuring proper cleanup by closing the cache connection and stopping the server. ```kotlin class MyTest { private lateinit var redisServer: RedisServer private lateinit var cache: RedisPromptCache @BeforeTest fun setup() { // Start an embedded Redis server redisServer = RedisServer.builder().port(6379).build() redisServer.start() // Create a Redis client val client = RedisClient.create("redis://localhost:6379") // Create a Redis-based cache with a prefix and TTL cache = RedisPromptCache(client, "test-cache:", 1.hours) } @AfterTest fun cleanup() { // Close the cache connection cache.close() // Stop the embedded Redis server redisServer.stop() } // Your tests here } ``` -------------------------------- ### Spring Boot Kotlin RestController with Anthropic Executor Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/spring-boot.md Example of a Kotlin RestController using an auto-configured Anthropic PromptExecutor. Requires spring-boot-starter-web, kotlinx-coroutines-core, and kotlinx-coroutines-reactor dependencies. Ensure Anthropic is enabled via properties. ```kotlin import ai.koog.prompt.dsl.prompt import ai.koog.prompt.executor.clients.anthropic.AnthropicModels import ai.koog.prompt.executor.model.PromptExecutor import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/chat") class ChatController(private val anthropicExecutor: PromptExecutor) { @PostMapping suspend fun chat(@RequestBody request: ChatRequest): ResponseEntity { return try { val prompt = prompt("chat") { system("You are a helpful assistant") user(request.message) } val result = anthropicExecutor.execute(prompt, AnthropicModels.Haiku_45) ResponseEntity.ok(ChatResponse(result.first().content)) } catch (e: Exception) { ResponseEntity.internalServerError() .body(ChatResponse("Error processing request")) } } } data class ChatRequest(val message: String) data class ChatResponse(val response: String) ``` -------------------------------- ### Java Usage of LLMEmbeddingProvider Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/spring-ai-integration.md Inject and use the LLMEmbeddingProvider in a Spring service to perform embedding operations. This example uses OpenAI's TextEmbedding3Small model. ```java import ai.koog.prompt.executor.clients.LLMEmbeddingProvider; import ai.koog.prompt.executor.clients.openai.OpenAIModels; import org.springframework.stereotype.Service; import java.util.List; @Service public class MyEmbeddingService { private final LLMEmbeddingProvider embeddingProvider; public MyEmbeddingService(LLMEmbeddingProvider embeddingProvider) { this.embeddingProvider = embeddingProvider; } public List getEmbedding(String text) { return embeddingProvider.embed( text, OpenAIModels.Embeddings.TextEmbedding3Small ); } } ``` -------------------------------- ### Initialize and Serve Documentation Locally Source: https://github.com/jetbrains/koog/blob/develop/docs/README.md Commands to synchronize project dependencies and launch the local MkDocs development server. Requires the uv package manager. ```bash uv sync --frozen --all-extras uv run mkdocs serve ``` -------------------------------- ### Kotlin Usage of LLMEmbeddingProvider Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/spring-ai-integration.md Inject and use the LLMEmbeddingProvider in a Spring service to perform embedding operations. This example uses OpenAI's TextEmbedding3Small model. ```kotlin import ai.koog.prompt.executor.clients.LLMEmbeddingProvider import ai.koog.prompt.executor.clients.openai.OpenAIModels import org.springframework.stereotype.Service @Service class MyEmbeddingService(private val embeddingProvider: LLMEmbeddingProvider) { suspend fun getEmbedding(text: String): List { return embeddingProvider.embed( text, OpenAIModels.Embeddings.TextEmbedding3Small ) } } ``` -------------------------------- ### Spring Boot Java RestController with Anthropic Executor Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/spring-boot.md Example of a Java RestController using an auto-configured Anthropic PromptExecutor. Requires spring-boot-starter-web dependency. Ensure Anthropic is enabled via properties. ```java import ai.koog.prompt.Prompt; import ai.koog.prompt.executor.clients.anthropic.AnthropicModels; import ai.koog.prompt.executor.model.PromptExecutor; import ai.koog.prompt.message.Message; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/api/chat") public class ChatController { private final PromptExecutor anthropicExecutor; public ChatController(PromptExecutor anthropicExecutor) { this.anthropicExecutor = anthropicExecutor; } @PostMapping public ResponseEntity chat(@RequestBody ChatRequest request) { try { Prompt prompt = Prompt.builder("chat") .system("You are a helpful assistant") .user(request.message()) .build(); List result = anthropicExecutor.execute(prompt, AnthropicModels.Haiku_45); return ResponseEntity.ok(new ChatResponse(result.get(0).getContent())); } catch (Exception e) { return ResponseEntity.internalServerError() .body(new ChatResponse("Error processing request")); } } } record ChatRequest(String message) { } record ChatResponse(String response) { } ``` -------------------------------- ### Kotlin Agent Installation with Custom Feature Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/features/custom-features.md Shows how to install a custom feature, like `MyFeature`, into an `AIAgent` during its creation. This example demonstrates setting a configuration property for the installed feature. ```kotlin import ai.koog.agents.core.agent.AIAgent import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor import ai.koog.agents.features.tracing.feature.Tracing val MyFeature = Tracing var configProperty = "" 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" } } ``` -------------------------------- ### Kotlin Code Generation Tool and Agent Setup Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-core/QuickstartGuide.md Defines a 'GenerateCodeTool' for generating code and sets up an 'AIAgent' to use this tool. The tool takes 'language' and 'task' as arguments and returns a string indicating generated code. The agent is configured with an OpenAI executor and a system prompt to use the 'generate_code' tool. ```kotlin object GenerateCodeTool : SimpleTool() { @Serializable data class Args(val language: String, val task: String) override val argsSerializer = Args.serializer() override val descriptor = ToolDescriptor( name = "generate_code", description = "Generates code in the specified language for the given task", requiredParameters = listOf( ToolParameterDescriptor( name = "language", description = "Programming language (e.g., Kotlin, Java, Python)", type = ToolParameterType.String ), ToolParameterDescriptor( name = "task", description = "Description of the coding task", type = ToolParameterType.String ) ) ) override suspend fun doExecute(args: Args): String { // In a real implementation, this might call another API or service return "Generated code for ${args.task} in ${args.language}" } } fun main() = runBlocking { val apiToken = System.getenv("LLM_API_TOKEN") val coroutineScope = CoroutineScope(Dispatchers.Default) val toolRegistry = ToolRegistry { tool(GenerateCodeTool) } val agent = AIAgent( executor = simpleOpenAIExecutor("API_TOKEN"), systemPrompt = "You are a code assistant. Use the generate_code tool to create code examples.", toolRegistry = toolRegistry ) agent.run("I need help creating a function to sort a list in Kotlin") // Wait for the agent to complete delay(Long.MAX_VALUE) } ``` -------------------------------- ### Install EventHandler Feature in AIAgent (Kotlin) Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-features/agents-features-event-handler/Module.md Demonstrates how to install and configure the EventHandler feature when creating an AIAgent. It shows basic event handlers for agent starting and completion. ```kotlin val myAgent = AIAgent( // other configuration parameters ) { handleEvents { // Configure event handlers here onAgentStarting { eventContext -> println("Agent starting: ${eventContext.agent.id}") } onAgentCompleted { eventContext -> println("Agent finished with result: ${eventContext.result}") } } } ``` -------------------------------- ### Run Prompt with OpenAI Client (Java) Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/prompts/llm-clients.md Shows how to set up an OpenAI client in Java, construct a prompt with system and user messages, and execute it. Ensure the OPENAI_API_KEY environment variable is set. ```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(); ``` -------------------------------- ### Run Prompt with OpenAI Client Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/prompts/llm-clients.md Demonstrates how to create an OpenAI client, define a prompt with system and user messages, and execute it using the `execute()` method. Requires the OPENAI_API_KEY environment variable. ```Kotlin import ai.koog.prompt.dsl.prompt import ai.koog.prompt.executor.clients.openai.OpenAILLMClient import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.params.LLMParams import kotlinx.coroutines.runBlocking 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) } ``` -------------------------------- ### Kotlin Unit Test Example for Koog Project Source: https://github.com/jetbrains/koog/blob/develop/a2a/CLAUDE.md An example of a unit test for the InMemoryTaskStorage in the Koog project, demonstrating setup, task creation, storage, retrieval, and assertion using Kotlin. ```kotlin class InMemoryTaskStorageTest { private lateinit var storage: InMemoryTaskStorage @BeforeTest fun setUp() { storage = InMemoryTaskStorage() } @Test fun testStoreAndRetrieveTask() = runTest { val task = createTask(id = "task-1", contextId = "context-1") storage.update(task) val retrieved = storage.get("task-1") assertNotNull(retrieved) assertEquals(task, retrieved) // Whole object assertion } } ``` -------------------------------- ### Install ChatMemory feature on an agent Source: https://github.com/jetbrains/koog/blob/develop/koog-spring-ai/koog-spring-ai-starter-chat-memory/Module.md Example of using the auto-configured ChatHistoryProvider within a Spring service to enable agent memory. ```kotlin @Service class MyAgentService( private val promptExecutor: PromptExecutor, private val chatHistoryProvider: ChatHistoryProvider, ) { suspend fun askAgent(userMessage: String): String { val agent = AIAgent( promptExecutor = promptExecutor, llmModel = OllamaModels.Meta.LLAMA_3_2, systemPrompt = "You are a helpful assistant.", ) { install(ChatMemory) { historyProvider = chatHistoryProvider } } return agent.run(userMessage) } } ``` -------------------------------- ### Basic OpenTelemetry Configuration Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-features/agents-features-opentelemetry/README.md Example of installing the OpenTelemetry feature with essential configuration like service info and a span exporter. ```APIDOC ## Basic OpenTelemetry Configuration ### Description Installs the OpenTelemetry feature with basic configuration. ### Method `install(OpenTelemetry)` ### Parameters #### Configuration Block - `setServiceInfo(serviceName: String, serviceVersion: String)`: Sets the information about the service being instrumented. - `addSpanExporter(exporter: SpanExporter)`: Registers an exporter wrapped in a `batchSpanProcessor`. ### Request Example ```kotlin import ai.koog.agents.features.opentelemetry.feature.OpenTelemetry import io.opentelemetry.exporter.logging.LoggingSpanExporter install(OpenTelemetry) { setServiceInfo("my-agent-service", "1.0.0") addSpanExporter(LoggingSpanExporter.create()) } ``` ``` -------------------------------- ### Create and Run a Simple LLM Planner Agent in Java Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/agents/planner-agents/llm-based-planners.md Shows how to set up a planner strategy using `Planners.llmBased`, configure an OpenAI executor, and build an AIAgent for planning tasks. Requires the OPENAI_API_KEY environment variable. ```java import ai.koog.agents.core.agent.AIAgent; import ai.koog.agents.core.planner.AIAgentPlannerStrategy; import ai.koog.agents.planner.Planners; import ai.koog.prompt.executor.clients.openai.OpenAIModels; import ai.koog.prompt.executor.model.PromptExecutor; class exampleLLMBasedPlanner01 { public static void main(String[] args) { // 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); } } ``` -------------------------------- ### Install MessageTokenizer in AI Agent (Kotlin) Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-features/agents-features-tokenizer/Module.md Demonstrates how to install and configure the MessageTokenizer feature within an AI Agent using Kotlin. It shows the basic setup and how to provide a custom tokenizer implementation and control caching. ```kotlin val agent = AIAgent( promptExecutor = executor, strategy = strategy, // other parameters... ) { install(MessageTokenizer) { // Configure the tokenizer implementation tokenizer = YourTokenizerImplementation() // Enable or disable caching (enabled by default) enableCaching = true } } ``` -------------------------------- ### Configure and Initialize Banking Assistant Agent Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/examples/Banking.md Sets up the agent's configuration, including system prompts, model selection, and iteration limits. Initializes the agent with a prompt executor, strategy, configuration, 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, ) ``` -------------------------------- ### Setup Koog Environment Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/examples/Chess.md Import the Koog framework and set up the development environment. This is a prerequisite for using Koog functionalities. ```kotlin %useLatestDescriptors %use koog ``` -------------------------------- ### Example Usage of Koog Debugger Feature Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-core/src/commonMain/kotlin/ai/koog/agents/core/feature/FEATURES.md This snippet provides a complete example of using the Koog Debugger feature in a real-world scenario. It includes creating an agent with a strategy, tool registry, and the Debugger feature installed, then running the agent with a user prompt. ```kotlin // Create a strategy for the agent val strategy = strategy("example-strategy") { val nodeLLMRequest by nodeLLMRequest("llm-request-node") val nodeToolCall by nodeExecuteTool("tool-call-node") val nodeSendToolResult by nodeLLMSendToolResult("send-tool-result-node") edge(nodeStart forwardTo nodeLLMRequest) edge(nodeLLMRequest forwardTo nodeToolCall onToolCall { true }) edge(nodeLLMRequest forwardTo nodeFinish onAssistantMessage { true }) edge(nodeToolCall forwardTo nodeSendToolResult) edge(nodeSendToolResult forwardTo nodeFinish onAssistantMessage { true }) edge(nodeSendToolResult forwardTo nodeToolCall onToolCall { true }) } // Create a tool registry val toolRegistry = ToolRegistry { tool(SearchTool()) tool(CalculatorTool()) } // Create an agent with the Debugger feature val agent = createAgent( agentId = "example-agent", strategy = strategy, promptId = "example-prompt", systemPrompt = "You are a helpful assistant.", toolRegistry = toolRegistry, model = myLLModel ) { // Install and configure the Debugger feature install(Debugger) { // Use a specific port or let it use the default // setPort(8080) } } // Use the agent agent.use { // Run the agent with a user prompt val result = agent.run("Calculate 25 * 16 and then search for information about the result.") // Process the result println("Agent result: $result") } ``` -------------------------------- ### Few-Shot Example for Sentiment Classification Source: https://github.com/jetbrains/koog/blob/develop/docs/prompt/models/gemini_flash_2_0.md Demonstrates how to use few-shot examples to guide Gemini Flash 2.0 for a specific task like sentiment classification. This helps the model understand the desired output format when it's not immediately obvious. ```text Text: "I am thrilled with the service." Sentiment: joy Text: "I am disappointed with the product." Sentiment: sadness Text: "The experience was average." Sentiment: ``` -------------------------------- ### Configure and Create AI Agent in Kotlin Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/examples/VaccumAgent.md This snippet demonstrates how to set up and instantiate an AI agent using Koog. It involves initializing the environment, configuring the OpenAI API executor, registering available tools, defining the agent's system prompt and configuration, and finally creating the AIAgent instance. ```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 ) ``` -------------------------------- ### Basic OpenTelemetry Agent Setup Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-features/agents-features-opentelemetry/README.md Sets up an AI agent with OpenTelemetry, configuring service info and adding a logging exporter. Includes a delay to allow telemetry data export. ```kotlin suspend fun main() { val apiKey = "your-api-key" val agent = AIAgent( executor = simpleGoogleAIExecutor(apiKey), llmModel = GoogleModels.Gemini2_0Flash, systemPrompt = "You are a code assistant. Provide concise code examples.", installFeatures = { install(OpenTelemetry) { setServiceInfo("my-otlp-agent", "1.0.0") addSpanExporter(LoggingSpanExporter.create()) } } ) val result = agent.run("Create python function that prints hello world") println(result) // Wait for telemetry data to be exported TimeUnit.SECONDS.sleep(10) } ``` -------------------------------- ### Filter Agent Events with setEventFilter Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/features/custom-features.md Use setEventFilter to specify which AgentLifecycleEventType events a feature should respond to. 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 Custom Message Processor in Kotlin Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/agent-events.md Implement the FeatureMessageProcessor interface to create a custom message processor. This example shows how to handle NodeExecutionStartingEvent and LLMCallCompletedEvent, and how to install it with the Tracing feature. ```Kotlin class CustomTraceProcessor : FeatureMessageProcessor() { override suspend fun processMessage(message: FeatureMessage) { // Custom processing logic if (message is NodeExecutionStartingEvent) { // Process node start event } else if (message is LLMCallCompletedEvent) { // Process LLM call end event } else { // Handle other event types } } override suspend fun close() { // Close connections if established } } val agent = AIAgent( promptExecutor = simpleOllamaAIExecutor(), llmModel = OllamaModels.Meta.LLAMA_3_2, ) { install(Tracing) { // Use your custom processor addMessageProcessor(CustomTraceProcessor()) } } ``` -------------------------------- ### Initialize Java Agent with System Prompt Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/agents/basic-agents.md This Java snippet shows how to build an agent with a system prompt, similar to the Kotlin example. It requires the `OPENAI_API_KEY` environment variable to be configured. ```java import ai.koog.agents.core.agent.AIAgent; import ai.koog.prompt.executor.clients.openai.OpenAIModels; import static ai.koog.prompt.executor.llms.all.SimplePromptExecutors.simpleOpenAIExecutor; class exampleBasicJava02 { public static void main(String[] args) { AIAgent agent = AIAgent.builder() .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY"))) .systemPrompt("You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.") .llmModel(OpenAIModels.Chat.GPT4o) .build(); } } ``` -------------------------------- ### Create and execute an AIAgent Source: https://github.com/jetbrains/koog/blob/develop/agents/agents-core/Module.md Demonstrates the process of setting up a tool registry, configuring an agent, and executing a task. ```kotlin // Create a tool registry val toolRegistry = ToolRegistry { } // Register tools toolRegistry.register(CalculatorTool) toolRegistry.register(SearchTool) // Configure the agent val agentConfig = AgentConfig( maxAgentIterations = 10, // other configuration parameters ) // Create the agent val agent = AIAgent( promptExecutor = llmExecutor, toolRegistry = toolRegistry, strategy = simpleSingleRunStrategy(), eventHandler = eventHandler, agentConfig = agentConfig ) // Run the agent val result = agent.execute("Calculate the square root of 16") ``` -------------------------------- ### Registering Event Handlers in Java Agent Source: https://github.com/jetbrains/koog/blob/develop/docs/docs/agents/basic-agents.md Use the `.install()` method on the agent builder to register event handlers with EventHandler.Feature. This example logs tool call start events. ```java // Create a ToolSet class class UserConversationTools implements ToolSet { @Tool @LLMDescription("Ask the user a question by sending it to stdout and return the answer from stdin") public String askUser( @LLMDescription("Question from the agent") String question ) { System.out.println(question); Scanner scanner = new Scanner(System.in); return scanner.nextLine(); } } // In main method: UserConversationTools askUser = new UserConversationTools(); ToolRegistry toolRegistry = ToolRegistry.builder() .tools(askUser) .build(); AIAgent agent = AIAgent.builder() .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY"))) .systemPrompt("You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.") .llmModel(OpenAIModels.Chat.GPT4o) .temperature(0.7) .toolRegistry(toolRegistry) .maxIterations(10) .install(EventHandler.Feature, config -> { config.onToolCallStarting(eventContext -> { System.out.println("Tool called: " + eventContext.getToolName() + " with args " + eventContext.getToolArgs()); }); }) .build(); ```