最近人工智慧非常的流行,Kotlin 自然也有對應的 AI 框架 Koog
參考 https://openaidoc.org/zh-Hant/koog/
Koog 是一個基於 Kotlin 的框架,旨在完全以慣用 Kotlin 語法建立並執行 AI 代理。它讓您能夠建立可與工具互動、處理複雜工作流程並與使用者溝通的代理。
我們可以在 https://start.ktor.io 勾選,或者在專案內調整 build.gradle.kts
dependencies {
implementation("ai.koog:koog-ktor:0.4.0")
}
安裝好之後,我們可以在安裝套件時設置對應的 API KEY
install(Koog) {
llm {
openAI(apiKey = "your-openai-api-key")
anthropic(apiKey = "your-anthropic-api-key")
ollama { baseUrl = "http://localhost:11434" }
google(apiKey = "your-google-api-key")
openRouter(apiKey = "your-openrouter-api-key")
deepSeek(apiKey = "your-deepseek-api-key")
}
}
這邊的api-key 建議不要直接寫在程式碼內,要透過 System.getenv
取用
System.getenv("GOOGLE_API_KEY")
建立好之後,我們就可以拿 aiAgent
作為一個物件來處理 AI 的內容了
routing {
route("/ai") {
post("/chat") {
val userInput = call.receive<String>()
val output = aiAgent(userInput, model = OpenAIModels.Chat.GPT4_1)
call.respondText(output)
}
}
}
Koog 的使用還有很多內容可以說
今天的部分就到這邊,我們明天見!