Skip to main content
The simple-examples directory contains over 30 runnable examples demonstrating various Koog framework capabilities. Each example is a complete, working implementation you can run and modify.

Getting Started

Setup

1

Clone the Repository

git clone https://github.com/koogio/koog.git
cd koog/examples/simple-examples
2

Set API Keys

Create an env.properties file or export environment variables:
export OPENAI_API_KEY="your_openai_key"
export ANTHROPIC_API_KEY="your_anthropic_key"
3

Run an Example

Use Gradle tasks to run any example:
./gradlew runExampleCalculator

Core Examples

Calculator Agent

A fundamental example demonstrating tool calling, event handling, and agent strategies.
package ai.koog.agents.example.calculator

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.tool.AskUser
import ai.koog.agents.ext.tool.SayToUser
import ai.koog.agents.features.eventHandler.feature.handleEvents
import ai.koog.prompt.dsl.prompt
import ai.koog.prompt.executor.clients.openai.OpenAIModels
import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor

suspend fun main() {
    // Create a tool registry with calculator tools
    val toolRegistry = ToolRegistry {
        tool(AskUser)
        tool(SayToUser)
        tools(CalculatorTools().asTools())
    }

    // Create agent config with proper prompt
    val agentConfig = AIAgentConfig(
        prompt = prompt("test") {
            system("You are a calculator.")
        },
        model = OpenAIModels.Chat.GPT4o,
        maxAgentIterations = 50
    )

    simpleOpenAIExecutor(ApiKeyService.openAIApiKey).use { executor ->
        val agent = AIAgent(
            promptExecutor = executor,
            strategy = CalculatorStrategy.strategy,
            agentConfig = agentConfig,
            toolRegistry = toolRegistry
        ) {
            handleEvents {
                onToolCallStarting { eventContext ->
                    println("Tool called: ${eventContext.toolName}")
                }
                onAgentCompleted { eventContext ->
                    println("Result: ${eventContext.result}")
                }
            }
        }

        val result = agent.run("(10 + 20) * (5 + 5) / (2 - 11)")
        println("Agent result: $result")
    }
}
Key Concepts:
  • Tool Registry: Type-safe tool registration using annotations
  • Agent Strategy: Graph-based execution flow with nodes and edges
  • Event Handling: Observing tool calls and agent lifecycle events
  • History Compression: Automatic compression when token usage exceeds threshold
Run it:
./gradlew runExampleCalculator

Banking Agent with Routing

Demonstrates complex routing between specialized sub-agents for different banking operations. Features:
  • Classifies user requests (balance inquiry, money transfer, transaction analysis)
  • Routes to specialized agents based on classification
  • Uses graph-based strategy for routing logic
Run it:
./gradlew runExampleRoutingViaGraph

Advanced Features

Streaming Responses

Stream LLM responses in real-time while executing tools:
./gradlew runExampleStreamingWithTools
Key Features:
  • Real-time token streaming
  • Tool execution during streaming
  • HTTP server integration with Ktor

Structured Output

Generate type-safe, schema-validated output from agents:
./gradlew runExampleStructuredOutputAdvancedWithStandardSchema
Supports:
  • JSON schemas for validation
  • Kotlin data class mapping
  • Streaming structured data
  • Markdown formatting with schemas

Memory and Persistence

Agents that remember previous interactions:
./gradlew runExampleFilePersistentAgent
Saves agent state to local files for session continuity.

Observability with OpenTelemetry

Integrate comprehensive tracing and monitoring:
AIAgent(...) {
    install(OpenTelemetry) {
        setVerbose(true)
        addLangfuseExporter(
            traceAttributes = listOf(
                CustomAttribute("langfuse.session.id", sessionId)
            )
        )
    }
}
Run it:
./gradlew runExampleFeatureOpenTelemetry
Supported Integrations:
  • Langfuse for trace visualization
  • Weights & Biases Weave
  • Custom OpenTelemetry exporters

External API Integration

AWS Bedrock

Use AWS Bedrock models with Koog:
./gradlew runExampleBedrockAgent
Agent with web search capabilities:
./gradlew runExampleWebSearchAgent

Available Examples

Here’s a quick reference of all available Gradle tasks:
  • runExampleCalculator - Basic calculator agent
  • runExampleCalculatorV2 - Enhanced calculator
  • runExampleCalculatorLocal - Calculator with local LLM
  • runExampleGuesser - Number guessing game
  • runExampleEssay - Essay writing agent
  • runExampleRoutingViaGraph - Banking with graph routing
  • runExampleRoutingViaAgentsAsTools - Banking with agents as tools
  • runExampleStructuredOutputSimple - Basic structured output
  • runExampleStructuredOutputAdvancedWithBasicSchema - Advanced basic schema
  • runExampleStructuredOutputAdvancedWithStandardSchema - Advanced standard schema
  • runExampleMarkdownStreaming - Streaming Markdown
  • runExampleMarkdownStreamingWithTool - Streaming with tools
  • runExampleStreamingWithTools - Streaming responses with tools
  • runExampleStreamingKtorServer - HTTP server streaming
  • runExampleFilePersistentAgent - File-based persistence
  • runExampleSQLPersistentAgent - SQL database persistence
  • runExampleFeatureOpenTelemetry - OpenTelemetry tracing
  • runExampleBedrockAgent - AWS Bedrock
  • runExampleWebSearchAgent - Web search
  • runExampleInstagramPostDescriber - Image attachments
  • runExampleJokesWithModeration - Content moderation
  • runExampleExecSandbox - Code execution sandbox
  • runExampleLoopComponent - Loop-based generation
  • runExampleFleetProjectTemplateGeneration - Fleet templates
  • runExampleRiderProjectTemplate - Rider templates

Interactive Notebooks

Many examples have corresponding Jupyter notebooks for interactive exploration:
  • Calculator.ipynb - Basic calculator with explanations
  • Banking.ipynb - Banking routing patterns
  • Chess.ipynb - Chess-playing agent
  • OpenTelemetry.ipynb - Observability setup
  • Langfuse.ipynb - Langfuse integration
  • Weave.ipynb - W&B Weave integration
Find them in examples/notebooks/ directory.

Source Code

All examples are available on GitHub:

View on GitHub

Browse the complete source code for all simple examples

Next Steps

Code Agent Tutorial

Build a complete coding agent step-by-step

Core Concepts

Learn more about Koog’s architecture

Build docs developers (and LLMs) love