Koog 문서 번역 07: Basic Agents
원문: Koog Documentation — Basic Agents 이 글은 Koog 공식 문서의 Basic Agents 페이지를 한국어로 옮긴 번역본입니다. 문서 구조와 링크 의미를 유지하되, MkDocs 전용 UI 문법은 블로그에서 읽기 좋도록 정리했습니다.
기본 에이전트
기본 에이전트는 가장 일반적인 사용 사례에 적합한 간단한 실행 흐름과 함께 사전 정의된 전략을 사용합니다. 문자열 입력(질문, 요청 또는 작업 설명)을 수락하고 이 입력을 구성된 LLM으로 보냅니다. LLM은 제공된 도구를 호출하기로 결정할 수 있습니다. 에이전트는 도구를 실행하고 결과를 LLM으로 다시 보냅니다. 이는 LLM이 더 이상 도구 호출을 요청하지 않고 문자열 응답을 반환할 때까지 반복됩니다. 그런 다음 에이전트는 이 응답을 출력합니다.
그래프 기반 에이전트에서는 기본 에이전트에서 사용하는 사전 정의된 전략 그래프를 다시 생성하는 방법을 확인할 수 있습니다.
참고: Prerequisites
환경과 프로젝트가 다음 요구 사항을 충족하는지 확인하세요.
JDK 17+
Kotlin 2.2.0+
Gradle 8.0+ 또는 Maven 3.8+
Koog 패키지을 종속성으로 추가합니다.
Gradle(Kotlin)
12dependencies {34 implementation("ai.koog:koog-agents:0.7.1")56}7Gradle(그루비)
12dependencies {34 implementation 'ai.koog:koog-agents:0.7.1'56}7Maven
12<dependency>34 <groupId>ai.koog</groupId>56 <artifactId>koog-agents-jvm</artifactId>78 <version>0.7.1</version>910</dependency>11LLM 공급자로부터 API 키를 얻거나 Ollama를 통해 로컬 LLM을 실행하세요.
자세한 내용은 Quickstart을 참조하세요.
이 페이지의 예에서는 OPENAI_API_KEY 환경 변수를 설정했다고 가정합니다.
최소 에이전트 만들기
가장 기본적인 에이전트를 생성하려면 AIAgent을 인스턴스화하세요.
prompt executor에 language model를 제공합니다.
Kotlin
1val agent = AIAgent(2 promptExecutor = simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")),3 llmModel = OpenAIModels.Chat.GPT4o4)이 에이전트는 문자열을 입력으로 예상하고 문자열을 출력으로 반환합니다.
에이전트를 실행하려면 일부 사용자 입력과 함께 run() 함수를 사용하세요.
1fun main() = runBlocking {2 val result = agent.run("Hello! How can you help me?")3 println(result)4}Java
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")))3 .llmModel(OpenAIModels.Chat.GPT4o)4 .build();이 에이전트는 문자열을 입력으로 예상하고 문자열을 출력으로 반환합니다.
에이전트를 실행하려면 일부 사용자 입력과 함께 run() 메서드를 사용하세요.
1String result = agent.run("Hello! How can you help me?");2System.out.println(result);에이전트은 다음과 같은 일반적인 답변을 반환합니다.
1I can assist with a wide range of topics and tasks. Here are some examples:231. **Answering questions**: I can provide information on various subjects, from science and history to entertainment and culture.42. **Generating text**: I can help with writing tasks, such as suggesting alternative phrases, providing definitions, or even creating entire articles or stories.53. **Translation**: I can translate text from one language to another, including popular languages such as Spanish, French, German, Chinese, and many more.64. **Conversation**: I can engage in natural-sounding conversations, using context and understanding to respond to questions and statements.75. **Brainstorming**: I can help generate ideas for creative projects, such as writing stories, composing music, or coming up with business ideas.86. **Learning**: I can help with language learning, explaining grammar rules, vocabulary, and pronunciation.97. **Calculations**: I can perform mathematical calculations, including basic arithmetic, algebra, and more advanced math concepts.1011What's on your mind? Do you have a specific question, topic, or task you'd like to tackle?시스템 프롬프트 추가
에이전트의 역할을 정의하려면 system message을 제공하세요. 작업과 관련된 목적, 상황 및 지침도 포함됩니다.
Kotlin
1val agent = AIAgent(2 promptExecutor = simpleOpenAIExecutor(System.getenv("YOUR_API_KEY")),3 systemPrompt = "You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.",4 llmModel = OpenAIModels.Chat.GPT4o5)Java
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")))3 .systemPrompt("You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.")4 .llmModel(OpenAIModels.Chat.GPT4o)5 .build();시스템 프롬프트의 지침은 에이전트의 응답을 안내합니다.
1I'm here to help you navigate the wild world of internet memes!23What's on your mind? Are you trying to understand a specific meme, need help finding a popular joke, or perhaps want some recommendations for trending memes? Let me know, and I'll do my best to provide you with some LOLs!LLM 출력 구성
일부 LLM parameters을 에이전트 생성자에 직접 제공할 수 있습니다.
(Kotlin) 또는 빌더 메소드(Java)를 통해 LLM의 동작을 사용자 정의합니다.
예를 들어, temperature 매개변수를 사용하여 생성된 응답의 무작위성을 조정합니다.
Kotlin
1val agent = AIAgent(2 promptExecutor = simpleOpenAIExecutor(System.getenv("YOUR_API_KEY")),3 systemPrompt = "You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.",4 llmModel = OpenAIModels.Chat.GPT4o,5 temperature = 0.76)Java
1AIAgent<String, String> agent = AIAgent.builder()2 .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")))3 .systemPrompt("You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.")4 .llmModel(OpenAIModels.Chat.GPT4o)5 .temperature(0.7)6 .build();다음은 다양한 온도 값을 사용한 몇 가지 응답 예입니다.
0.4
1I'm here to help you navigate the wild world of internet memes! Whether you're looking for explanations, examples, or just want to share a meme with someone, I'm your go-to expert. What's on your mind? Got a specific meme in mind that's got you curious? Or maybe you need some meme-related advice? Fire away!0.7
1I'm here to help you navigate the wild world of internet memes!23What's on your mind? Need help understanding a specific meme, finding a popular joke or trend, or maybe even creating your own meme? Let's get this meme party started!1.0
1I'd be happy to help you navigate the wild world of internet memes!23Whether you're looking for explanations of classic memes, suggestions for new ones to try out, or just want to discuss your favorite meme culture trends, I'm here to assist. What's on your mind?45Do you have a specific question about memes (e.g., "What does this meme mean?"), or are you looking for some meme-related recommendations (e.g., "Can you recommend a funny meme to share with friends?"). Let me know how I can help!도구 추가
에이전트는 tools을 사용하여 특정 작업을 수행할 수 있습니다.
먼저 @Tool 주석으로 함수(Kotlin) 또는 메서드(Java)에 주석을 달아 도구를 만듭니다.
Kotlin
1@Tool2@LLMDescription("Ask the user a question by sending it to stdout and return the answer from stdin")3fun askUser(4 @LLMDescription("Question from the agent")5 question: String6): String {7 println(question)8 return readln()9}그런 다음 ToolRegistry을 사용하여 에이전트가 이 도구를 사용할 수 있도록 합니다.
1val agent = AIAgent(2 promptExecutor = simpleOpenAIExecutor(System.getenv("YOUR_API_KEY")),3 systemPrompt = "You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.",4 llmModel = OpenAIModels.Chat.GPT4o,5 temperature = 0.7,6 toolRegistry = ToolRegistry {7 tool(::askUser)8 }9)이 예에서 askUser은 에이전트가 콘솔에서 인쇄하고 읽기를 통해 사용자와의 대화를 유지하는 데 도움이 되는 도구입니다.
에이전트이 사용자에게 질문하기로 결정한 경우
println()을 통해 stdout에 쓰고 readln()을 통해 stdin에서 읽는 이 도구를 호출할 수 있습니다.
Java
1// Create a ToolSet class2class UserConversationTools implements ToolSet {3 @Tool4 @LLMDescription("Ask the user a question by sending it to stdout and return the answer from stdin")5 public String askUser(6 @LLMDescription("Question from the agent")7 String question8 ) {9 System.out.println(question);10 Scanner scanner = new Scanner(System.in);11 return scanner.nextLine();12 }13}그런 다음 ToolRegistry을 사용하여 에이전트가 이 도구를 사용할 수 있도록 합니다.
1UserConversationTools askUser = new UserConversationTools();23ToolRegistry toolRegistry = ToolRegistry.builder()4 .tools(askUser)5 .build();67AIAgent<String, String> agent = AIAgent.builder()8 .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")))9 .systemPrompt("You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.")10 .llmModel(OpenAIModels.Chat.GPT4o)11 .temperature(0.7)12 .toolRegistry(toolRegistry)13 .build();이 예에서 askUser은 에이전트가 콘솔에서 인쇄하고 읽기를 통해 사용자와의 대화를 유지하는 데 도움이 되는 도구입니다.
다음은 에이전트와의 상호작용 예시입니다.
1Agent: Which meme would you like me to explain? Please choose from: Grumpy Cat, Success Kid, or Doge.23User: Explain Doge45Agent:67**Doge**89Doge is a popular internet meme that originated on the imageboard website 4chan in 2013. The meme features a picture of a Shiba Inu dog with a caption written in a playful, exaggerated style.1011The typical format of a Doge meme includes:1213* A photo of a Shiba Inu dog14* A caption written in all capital letters, using a intentionally simplistic and childlike tone15* Exaggerated or made-up words or phrases, often used to convey a humorous or nonsensical idea1617Examples of Doge memes might include:1819* "Such wow. Such happy."20* "I had fun today!"21* "Wow, I am good at napping."2223The meme is known for its lighthearted and playful tone, and is often used to express excitement, happiness, or silliness. The meme has since become a cultural phenomenon, with countless variations and parodies emerging online.에이전트 반복 조정
무한 루프를 피하기 위해 Koog는 모든 에이전트가 제한된 수의 단계(기본적으로 50단계)를 수행하도록 허용합니다.
에이전트에 추가 단계가 필요할 것으로 예상되는 경우 maxIterations 매개변수를 사용하여 이 제한을 늘리십시오.
(예: 도구 호출 및 LLM 요청) 또는 몇 단계만 필요한 에이전트의 경우 이를 줄입니다.
예를 들어, 여기에 설명된 간단한 에이전트에는 10개 이상의 단계가 필요하지 않습니다.
Kotlin
1val agent = AIAgent(2 promptExecutor = simpleOpenAIExecutor(System.getenv("YOUR_API_KEY")),3 systemPrompt = "You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.",4 llmModel = OpenAIModels.Chat.GPT4o,5 temperature = 0.7,6 toolRegistry = ToolRegistry {7 tool(::askUser)8 },9 maxIterations = 1010)Java
1// Create a ToolSet class2class UserConversationTools implements ToolSet {3 @Tool4 @LLMDescription("Ask the user a question by sending it to stdout and return the answer from stdin")5 public String askUser(6 @LLMDescription("Question from the agent")7 String question8 ) {9 System.out.println(question);10 Scanner scanner = new Scanner(System.in);11 return scanner.nextLine();12 }13}1415// In main method:16UserConversationTools askUser = new UserConversationTools();1718ToolRegistry toolRegistry = ToolRegistry.builder()19 .tools(askUser)20 .build();2122AIAgent<String, String> agent = AIAgent.builder()23 .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")))24 .systemPrompt("You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.")25 .llmModel(OpenAIModels.Chat.GPT4o)26 .temperature(0.7)27 .toolRegistry(toolRegistry)28 .maxIterations(10)29 .build();참고
모델, 온도, 최대 반복 횟수 및 기타 매개변수를 Kotlin 생성자에 직접 전달하는 대신 또는 Java 빌더를 사용하는 경우 이를 별도의 구성 객체로 정의하고 전달할 수도 있습니다. 자세한 내용은 Agent configuration을 참조하세요.
에이전트 런타임 중 이벤트 처리
테스트 및 디버깅을 지원하고 연결된 에이전트 상호 작용을 위한 후크를 만들기 위해, Koog는 EventHandler 기능을 제공합니다.
Kotlin
기능을 설치하고 이벤트 핸들러를 등록하려면 에이전트 생성자 람다 내에서 handleEvents() 함수를 호출하세요.
1val agent = AIAgent(2 promptExecutor = simpleOpenAIExecutor(System.getenv("YOUR_API_KEY")),3 systemPrompt = "You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.",4 llmModel = OpenAIModels.Chat.GPT4o,5 temperature = 0.7,6 toolRegistry = ToolRegistry {7 tool(::askUser)8 },9 maxIterations = 1010){11 handleEvents {12 // Handle tool calls13 onToolCallStarting { eventContext ->14 println("Tool called: ${eventContext.toolName} with args ${eventContext.toolArgs}")15 }16 }17}Java
EventHandler.Feature에 이벤트 핸들러를 등록하려면 에이전트 빌더에서 .install() 메소드를 사용하십시오.
1// Create a ToolSet class2class UserConversationTools implements ToolSet {3 @Tool4 @LLMDescription("Ask the user a question by sending it to stdout and return the answer from stdin")5 public String askUser(6 @LLMDescription("Question from the agent")7 String question8 ) {9 System.out.println(question);10 Scanner scanner = new Scanner(System.in);11 return scanner.nextLine();12 }13}1415// In main method:16UserConversationTools askUser = new UserConversationTools();1718ToolRegistry toolRegistry = ToolRegistry.builder()19 .tools(askUser)20 .build();2122AIAgent<String, String> agent = AIAgent.builder()23 .promptExecutor(simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")))24 .systemPrompt("You are an expert in internet memes. Be helpful, friendly, and answer user questions concisely, showing your knowledge of memes.")25 .llmModel(OpenAIModels.Chat.GPT4o)26 .temperature(0.7)27 .toolRegistry(toolRegistry)28 .maxIterations(10)29 .install(EventHandler.Feature, config -> {30 config.onToolCallStarting(eventContext -> {31 System.out.println("Tool called: " + eventContext.getToolName() +32 " with args " + eventContext.getToolArgs());33 });34 })35 .build();이제 에이전트는 askUser 도구를 호출할 때 다음과 유사한 내용을 출력합니다.
1Tool called: askUser with args {"question":"Which meme would you like me to explain?"}Koog 에이전트 기능에 대한 자세한 내용은 Features을 참조하세요.
다음 단계
- graph-based agents 및 functional agents 구축에 대해 자세히 알아보세요.