0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlin AI Framework - Koog

Last updated at Posted at 2025-07-08

概要

(自分メモ)
Kotlin KoogでAI Agentを試す。

環境

  • Ubuntu 24.04

  • Kotlin 2.1.21

  • Koog Agent 0.2.1

  • Node.js v24.3.0 (MCPサービス用)

  • LLM: Google Gemini 2.5
    Google AI StudioからAPI Key取得。要Google アカウント

export GOOGLE_API_KEY=********

例: シンプルな一問一答

build.gradle.kts
dependencies {
    implementation("ai.koog:koog-agents:0.2.1")
}

app/src/main/kotlin/Main1.kt
val promptExecutor = simpleGoogleAIExecutor(System.getenv("GOOGLE_API_KEY"))

fun main() = runBlocking {
    val prompt = prompt("prompt1") { user("kotlinで補完して fun fib(x)=") }
    val reply = promptExecutor.execute(prompt, GoogleModels.Gemini2_5FlashPreview0417)
    println(reply.content)
}
sh gradlew run

コード➔GitHub

例: Kotlinの関数をAIが実行

Koogから使用可能な機能(関数)をアノテーションで定義。
もちろん通信することで外部との相互作用も可。

app/src/main/kotlin/Main2.kt
@Suppress("unused")
@LLMDescription("OSのFile system 操作")
class MyTools : ToolSet {
    @Tool
    @LLMDescription("pathで指定されたディレクトリ内のファイルを列挙。ファイル名,タイプ(D:Directory,F:File),サイズ, の配列を返す。")
    fun listFiles(
        @LLMDescription("列挙するディレクトリを指定") path: String
    ) = with(SystemFileSystem) {
        list(Path(path)).filter { it.name != "." && it.name != ".." }.joinToString("\n") {
            "${it.name}, ${if (metadataOrNull(it)?.isDirectory == true) "D" else "F"}, ${metadataOrNull(it)?.size}"
        }
    }

    @Tool
    @LLMDescription("pathで指定したファイルの内容を返す")
    suspend fun readFile(
        @LLMDescription("対象ファイルを指定") path: String
    ) = with(SystemFileSystem) { source(Path(path)).buffered().readString() }
}

val agent = AIAgent(
    executor = simpleGoogleAIExecutor(System.getenv("GOOGLE_API_KEY")),
    llmModel = GoogleModels.Gemini2_0Flash,
    toolRegistry = ToolRegistry { tools(MyTools().asTools()) },
)

fun main() = runBlocking {
    val result = agent.runAndGetResult("ディレクトリapp/src/main/kotlin以下にあるすべてのファイルの内容からファイル操作を行うものを列挙")
    println(result)
}

例: MCPを使う

前例のような機能モデルを定義したパッケージをAI向けに提供するプロトコルがModel Context Protocol(MCP)。
Playwright(ブラウザを制御するライブラリ)用のMCPを試してみる

app/src/main/kotlin/Main2.kt
fun main() = runBlocking {
    val toolRegistry = McpToolRegistryProvider.fromTransport(
        transport = McpToolRegistryProvider.defaultSseTransport("http://localhost:8931/sse")
    )
    val agent = AIAgent(
        executor = simpleGoogleAIExecutor(System.getenv("GOOGLE_API_KEY")),
        llmModel = GoogleModels.Gemini2_0Flash,
        toolRegistry = toolRegistry,
    )

    agent.runAndGetResult("https://www.google.com で'Koog Kotlin'を検索。最初の検索結果を開く")
    generateSequence { print("> ");readlnOrNull() }.forEach { query ->
        agent.runAndGetResult(query)
    }
}
MCPサーバ起動後実行
npx -y @playwright/mcp@latest --port 8931
sh gradlew run

DockerHub/mcp:hub

例: フレームワーク

[TODO]

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?