AWS Bedrock 및 Koog Framework를 사용하여 AI 에이전트 구축

·3분 읽기

원문: Koog Documentation — BedrockAgent 이 글은 Koog 공식 문서의 BedrockAgent 페이지를 한국어로 옮긴 번역본입니다. 문서 구조와 링크 의미를 유지하되, MkDocs 전용 UI 문법은 블로그에서 읽기 좋도록 정리했습니다.

AWS Bedrock 및 Koog Framework를 사용하여 AI 에이전트 구축

:material-github: Open on GitHub{ .md-button .md-button--기본 } :material-download: Download .ipynb{ .md-버튼 }

AWS Bedrock 통합과 Koog 프레임워크를 사용하여 지능형 AI 에이전트를 생성하는 방법에 대한 포괄적인 가이드에 오신 것을 환영합니다. 이 노트북에서는 자연어 명령을 통해 간단한 스위치 장치를 제어할 수 있는 기능적 에이전트를 구축하는 방법을 살펴보겠습니다.

당신이 배울 내용

  • Kotlin 주석을 사용하여 AI 에이전트용 맞춤 도구를 정의하는 방법
  • LLM 기반 에이전트를 위한 AWS Bedrock 통합 설정
  • 도구 레지스트리 생성 및 에이전트에 연결
  • 명령을 이해하고 실행할 수 있는 대화형 에이전트 구축

전제 조건

  • 적절한 권한이 있는 AWS Bedrock 액세스
  • 구성된 AWS 자격 증명(액세스 키 및 비밀 키)
  • Kotlin 코루틴에 대한 기본 이해

최초의 Bedrock 기반 AI 에이전트를 구축하는 방법을 살펴보겠습니다!

1%useLatestDescriptors2// %use koog
1import ai.koog.agents.core.tools.annotations.LLMDescription2import ai.koog.agents.core.tools.annotations.Tool3import ai.koog.agents.core.tools.reflect.ToolSet45// Simple state-holding device that our agent will control6class Switch {7    private var state: Boolean = false89    fun switch(on: Boolean) {10        state = on11    }1213    fun isOn(): Boolean {14        return state15    }16}1718/**19 * ToolSet implementation that exposes switch operations to the AI agent.20 *21 * Key concepts:22 * - @Tool annotation marks methods as callable by the agent23 * - @LLMDescription provides natural language descriptions for the LLM24 * - ToolSet interface allows grouping related tools together25 */26class SwitchTools(val switch: Switch) : ToolSet {2728    @Tool29    @LLMDescription("Switches the state of the switch to on or off")30    fun switchState(state: Boolean): String {31        switch.switch(state)32        return "Switch turned ${if (state) "on" else "off"} successfully"33    }3435    @Tool36    @LLMDescription("Returns the current state of the switch (on or off)")37    fun getCurrentState(): String {38        return "Switch is currently ${if (switch.isOn()) "on" else "off"}"39    }40}
1import ai.koog.agents.core.tools.ToolRegistry2import ai.koog.agents.core.tools.reflect.asTools34// Create our switch instance5val switch = Switch()67// Build the tool registry with our switch tools8val toolRegistry = ToolRegistry {9    // Convert our ToolSet to individual tools and register them10    tools(SwitchTools(switch).asTools())11}1213println("✅ Tool registry created with ${toolRegistry.tools.size} tools:")14toolRegistry.tools.forEach { tool ->15    println("  - ${tool.name}")16}

✅ 2가지 도구로 생성된 도구 레지스트리:

  • getCurrentState
  • 스위치 상태
1import ai.koog.prompt.executor.clients.bedrock.BedrockClientSettings2import ai.koog.prompt.executor.clients.bedrock.BedrockRegions34val region = BedrockRegions.US_WEST_2.regionCode5val maxRetries = 367// Configure Bedrock client settings8val bedrockSettings = BedrockClientSettings(9    region = region, // Choose your preferred AWS region10    maxRetries = maxRetries // Number of retry attempts for failed requests11)1213println("🌐 Bedrock configured for region: $region")14println("🔄 Max retries set to: $maxRetries")

🌐 지역: us-west-2에 대해 구성된 기반암 🔄 최대 재시도 설정: 3

1import ai.koog.prompt.executor.llms.all.simpleBedrockExecutor23// Create the Bedrock LLM executor with credentials from environment4val executor = simpleBedrockExecutor(5    awsAccessKeyId = System.getenv("AWS_BEDROCK_ACCESS_KEY")6        ?: throw IllegalStateException("AWS_BEDROCK_ACCESS_KEY environment variable not set"),7    awsSecretAccessKey = System.getenv("AWS_BEDROCK_SECRET_ACCESS_KEY")8        ?: throw IllegalStateException("AWS_BEDROCK_SECRET_ACCESS_KEY environment variable not set"),9    settings = bedrockSettings10)1112println("🔐 Bedrock executor initialized successfully")13println("💡 Pro tip: Set AWS_BEDROCK_ACCESS_KEY and AWS_BEDROCK_SECRET_ACCESS_KEY environment variables")

🔐 Bedrock 실행 프로그램이 성공적으로 초기화되었습니다. 💡 전문가 팁: AWS_BEDROCK_ACCESS_KEY 및 AWS_BEDROCK_SECRET_ACCESS_KEY 환경 변수 설정

1import ai.koog.agents.core.agent.AIAgent2import ai.koog.prompt.executor.clients.bedrock.BedrockModels34val agent = AIAgent(5    executor = executor,6    llmModel = BedrockModels.AnthropicClaude35SonnetV2, // State-of-the-art reasoning model7    systemPrompt = """8        You are a helpful assistant that controls a switch device.910        You can:11        - Turn the switch on or off when requested12        - Check the current state of the switch13        - Explain what you're doing1415        Always be clear about the switch's current state and confirm actions taken.16    """.trimIndent(),17    temperature = 0.1, // Low temperature for consistent, focused responses18    toolRegistry = toolRegistry19)2021println("🤖 AI Agent created successfully!")22println("📋 System prompt configured")23println("🛠️  Tools available: ${toolRegistry.tools.size}")24println("🎯 Model: ${BedrockModels.AnthropicClaude35SonnetV2}")25println("🌡️  Temperature: 0.1 (focused responses)")

🤖 AI 에이전트가 성공적으로 생성되었습니다! 📋 시스템 프롬프트 구성 🛠️ 사용 가능한 도구: 2 🎯 모델: LLModel(provider=Bedrock, id=us.anthropic.claude-3-5-sonnet-20241022-v2:0, Capability=[Temperature, Tools, ToolChoice, Image, Document, Completion], contextLength=200000, maxOutputTokens=8192) 🌡️ 온도: 0.1(집중 응답)

1import kotlinx.coroutines.runBlocking23println("🎉 Bedrock Agent with Switch Tools - Ready to Go!")4println("💬 You can ask me to:")5println("   • Turn the switch on/off")6println("   • Check the current switch state")7println("   • Ask questions about the switch")8println()9println("💡 Example: 'Please turn on the switch' or 'What's the current state?'")10println("📝 Type your request:")1112val input = readln()13println("\n🤖 Processing your request...")1415runBlocking {16    val response = agent.run(input)17    println("\n✨ Agent response:")18    println(response)19}

🎉 스위치 도구가 포함된 Bedrock 에이전트 - 준비 완료! 💬 나에게 다음을 요청할 수 있습니다. • 스위치를 켜거나 끕니다. • 현재 스위치 상태를 확인한다 • 스위치에 관해 질문하기

💡 예: '스위치를 켜주세요' 또는 '현재 상태는 어떻습니까?' 📝 요청을 입력하세요:

실행이 중단되었습니다.

방금 무슨 일이 일어났나요? 🎯

에이전트를 실행할 때 뒤에서 일어나는 마법은 다음과 같습니다.

  1. 자연어 처리: 귀하의 입력은 Bedrock을 통해 Claude 3.5 Sonnet으로 전송됩니다.
  2. 의도 인식: 모델은 사용자가 스위치로 수행하려는 작업을 이해합니다.
  3. 도구 선택: 귀하의 요청에 따라 상담원이 어떤 도구를 호출할지 결정합니다.
  4. 작업 실행: 스위치 개체에서 적절한 도구 메서드가 호출됩니다.
  5. 응답 생성: 에이전트는 발생한 일에 대한 자연어 응답을 공식화합니다.

이는 자연어 이해와 프로그래밍 작업 간의 원활한 통합이라는 Koog 프레임워크의 핵심 기능을 보여줍니다.

다음 단계 및 확장

더 나아갈 준비가 되셨나요? 탐구해 볼 몇 가지 아이디어는 다음과 같습니다.

🔧 향상된 도구

1@Tool2@LLMDescription("Sets a timer to automatically turn off the switch after specified seconds")3fun setAutoOffTimer(seconds: Int): String45@Tool6@LLMDescription("Gets the switch usage statistics and history")7fun getUsageStats(): String

🌐 여러 장치

1class HomeAutomationTools : ToolSet {2    @Tool fun controlLight(room: String, on: Boolean): String3    @Tool fun setThermostat(temperature: Double): String4    @Tool fun lockDoor(doorName: String): String5}

🧠 기억과 맥락

1val agent = AIAgent(2    executor = executor,3    // ... other config4    features = listOf(5        MemoryFeature(), // Remember past interactions6        LoggingFeature()  // Track all actions7    )8)

🔄 고급 작업 흐름

1// Multi-step workflows with conditional logic2@Tool3@LLMDescription("Executes evening routine: dims lights, locks doors, sets thermostat")4fun eveningRoutine(): String

주요 시사점

도구는 함수입니다: 모든 Kotlin 함수는 에이전트 기능이 될 수 있습니다 ✅ 주석은 동작을 유도합니다: @Tool 및 @LLMDescription은 기능을 검색 가능하게 만듭니다. ✅ ToolSets는 기능을 구성합니다: 관련 도구를 논리적으로 그룹화합니다. ✅ 레지스트리는 도구 상자입니다: ToolRegistry에는 사용 가능한 모든 에이전트 기능이 포함되어 있습니다. ✅ 에이전트가 모든 것을 조율합니다: AIAgent는 LLM 인텔리전스와 도구를 함께 제공합니다.

Koog 프레임워크를 사용하면 자연어를 이해하고 실제 작업을 수행할 수 있는 정교한 AI 에이전트를 구축하는 것이 놀라울 정도로 간단해졌습니다. 간단하게 시작한 다음 필요에 따라 더 많은 도구와 기능을 추가하여 에이전트의 기능을 확장하세요.

에이전트 구축을 즐기세요! 🚀

에이전트 테스트

에이전트가 실제로 작동하는 모습을 볼 시간입니다! 이제 에이전트는 자연어 요청을 이해하고 우리가 제공한 도구를 사용하여 스위치를 제어할 수 있습니다.

다음 명령을 시도해 보세요.

  • "스위치를 켜세요"
  • "현재 상태는 어떤가요?"
  • "전원 좀 꺼주세요"
  • "스위치가 켜져 있나요, 꺼져 있나요?"