간단한 진공청소기 에이전트 구축
·3분 읽기
원문: Koog Documentation — VaccumAgent 이 글은 Koog 공식 문서의 VaccumAgent 페이지를 한국어로 옮긴 번역본입니다. 문서 구조와 링크 의미를 유지하되, MkDocs 전용 UI 문법은 블로그에서 읽기 좋도록 정리했습니다.
간단한 진공청소기 에이전트 구축
:material-github: Open on GitHub{ .md-button .md-button--기본 } :material-download: Download .ipynb{ .md-버튼 }
이 노트북에서는 새로운 Kotlin 에이전트 프레임워크를 사용하여 기본 반사 에이전트를 구현하는 방법을 살펴보겠습니다. 우리의 예는 고전적인 "진공 세계" 문제입니다. 깨끗하거나 더러운 두 위치와 이를 청소해야 하는 에이전트가 있는 간단한 환경입니다.
먼저 환경 모델을 이해해 보겠습니다.
1import kotlin.random.Random23/**4 * Represents a simple vacuum world with two locations (A and B).5 *6 * The environment tracks:7 * - The current location of the vacuum agent ('A' or 'B')8 * - The cleanliness status of each location (true = dirty, false = clean)9 */10class VacuumEnv {11 var location: Char = 'A'12 private set1314 private val status = mutableMapOf(15 'A' to Random.nextBoolean(),16 'B' to Random.nextBoolean()17 )1819 fun percept(): Pair<Char, Boolean> = location to status.getValue(location)2021 fun clean(): String {22 status[location] = false23 return "cleaned"24 }2526 fun moveLeft(): String {27 location = 'A'28 return "move to A"29 }3031 fun moveRight(): String {32 location = 'B'33 return "move to B"34 }3536 fun isClean(): Boolean = status.values.all { it }3738 fun worldLayout(): String = "${status.keys}"3940 override fun toString(): String = "location=$location, dirtyA=${status['A']}, dirtyB=${status['B']}"41}VacuumEnv 클래스는 간단한 세계를 모델링합니다.
- 두 위치는 문자 'A'와 'B'로 표시됩니다.
- 각 위치는 깨끗하거나 더러울 수 있습니다(무작위로 초기화됨).
- 상담원은 언제든지 어느 위치에나 있을 수 있습니다.
- 에이전트는 현재 위치와 더러운지 여부를 인식할 수 있습니다.
- 에이전트는 특정 위치로 이동하거나 현재 위치를 청소하는 등의 조치를 취할 수 있습니다.
진공 에이전트용 도구 만들기
이제 AI 에이전트가 환경과 상호 작용하는 데 사용할 도구를 정의해 보겠습니다.
1import ai.koog.agents.core.tools.annotations.LLMDescription2import ai.koog.agents.core.tools.annotations.Tool3import ai.koog.agents.core.tools.reflect.ToolSet456/**7 * Provides tools for the LLM agent to control the vacuum robot.8 * All methods either mutate or read from the VacuumEnv passed to the constructor.9 */10@LLMDescription("Tools for controlling a two-cell vacuum world")11class VacuumTools(private val env: VacuumEnv) : ToolSet {1213 @Tool14 @LLMDescription("Returns current location and whether it is dirty")15 fun sense(): String {16 val (loc, dirty) = env.percept()17 return "location=$loc, dirty=$dirty, locations=${env.worldLayout()}"18 }1920 @Tool21 @LLMDescription("Cleans the current cell")22 fun clean(): String = env.clean()2324 @Tool25 @LLMDescription("Moves the agent to cell A")26 fun moveLeft(): String = env.moveLeft()2728 @Tool29 @LLMDescription("Moves the agent to cell B")30 fun moveRight(): String = env.moveRight()31}VacuumTools 클래스는 LLM 에이전트와 환경 간의 인터페이스를 생성합니다.
- Kotlin AI 에이전트 프레임워크에서
ToolSet를 구현합니다. - 각 도구에는
@Tool주석이 달려 있으며 LLM에 대한 설명이 있습니다. - 도구를 사용하면 에이전트가 환경을 감지하고 조치를 취할 수 있습니다.
- 각 메서드는 작업 결과를 설명하는 문자열을 반환합니다.
에이전트 설정
다음으로 AI 에이전트를 구성하고 생성합니다.
1import ai.koog.agents.core.agent.AIAgent2import ai.koog.agents.core.agent.config.AIAgentConfig3import ai.koog.agents.core.tools.ToolRegistry4import ai.koog.agents.core.tools.reflect.asTools5import ai.koog.agents.ext.agent.chatAgentStrategy6import ai.koog.agents.ext.tool.AskUser7import ai.koog.agents.ext.tool.SayToUser8import ai.koog.prompt.dsl.prompt9import ai.koog.prompt.executor.clients.openai.OpenAIModels10import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor11import ai.koog.prompt.params.LLMParams121314val env = VacuumEnv()15val apiToken = System.getenv("OPENAI_API_KEY") ?: error("OPENAI_API_KEY environment variable not set")16val executor = simpleOpenAIExecutor(apiToken = apiToken)1718val toolRegistry = ToolRegistry {19 tool(SayToUser)20 tool(AskUser)21 tools(VacuumTools(env).asTools())22}2324val systemVacuumPrompt = """25 You are a reflex vacuum-cleaner agent living in a two-cell world labelled A and B.26 Your goal: make both cells clean, using the provided tools.27 First, call sense() to inspect where you are. Then decide: if dirty → clean(); else moveLeft()/moveRight().28 Continue until both cells are clean, then tell the user "done".29 Use sayToUser to inform the user about each step.30""".trimIndent()3132val agentConfig = AIAgentConfig(33 prompt = prompt("chat", params = LLMParams(temperature = 1.0)) {34 system(systemVacuumPrompt)35 },36 model = OpenAIModels.Chat.GPT4o,37 maxAgentIterations = 50,38)3940val agent = AIAgent(41 promptExecutor = executor,42 strategy = chatAgentStrategy(),43 agentConfig = agentConfig,44 toolRegistry = toolRegistry45)이 설정에서는:
- 환경의 인스턴스를 만듭니다.
- OpenAI의 GPT-4o 모델에 대한 연결을 설정했습니다.
- 에이전트가 사용할 수 있는 도구를 등록합니다.
- 에이전트에게 목표와 행동 규칙을 제공하는 시스템 프롬프트를 정의합니다.
- 채팅 전략과 함께
AIAgent생성자를 사용하여 에이전트를 생성합니다.
에이전트 실행
마지막으로 에이전트를 실행해 보겠습니다.
1import kotlinx.coroutines.runBlocking23runBlocking {4 agent.run("Start cleaning, please")5}상담원의 말: 현재 셀 A에 있습니다. 이미 깨끗합니다. 요원의 말: B실로 옮겨졌습니다. 이미 깨끗해요.
이 코드를 실행하면:
- 상담원은 청소를 시작하라는 초기 메시지를 받습니다.
- 도구를 사용하여 환경을 감지하고 결정을 내립니다.
- 두 셀이 모두 깨끗해질 때까지 계속 청소됩니다.
- 프로세스 전반에 걸쳐 사용자에게 현재 수행 중인 작업에 대한 정보를 제공합니다.
1// Finally we can validate that the work is finished by printing the env state23env위치=B, 더티A=거짓, 더티B=거짓