Koog 문서 한국어 번역 07: 기본 에이전트
원문: Koog 공식 문서
기본 에이전트
기본 에이전트는 대부분의 일반적인 사용 사례에 적합한 단순한 실행 흐름을 갖는 미리 정의된 전략을 사용합니다. 문자열 입력(질문, 요청, 또는 작업 설명)을 받아 설정된 LLM에 전달합니다. LLM은 제공된 도구를 호출하기로 결정할 수 있습니다. 에이전트는 도구를 실행하고 결과를 다시 LLM에 전달합니다. LLM이 더 이상 도구 호출을 요청하지 않고 문자열 응답을 반환할 때까지 이 과정이 반복됩니다. 그런 다음 에이전트는 해당 응답을 출력합니다.
그래프 기반 에이전트에서는 기본 에이전트가 사용하는 미리 정의된 전략 그래프를 직접 재현하는 방법을 확인할 수 있습니다.
참고 — 사전 준비 사항
이 페이지의 예제는
OPENAI_API_KEY환경 변수가 설정되어 있다고 가정합니다. 사전 준비 사항, 의존성 추가, API 키 설정 방법은 Koog 빠른 시작 가이드를 참고하세요.
최소한의 에이전트 만들기
가장 기본적인 에이전트를 만들려면 AIAgent를 인스턴스화하고,
프롬프트 실행기와 언어 모델을 제공합니다.
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?시스템 프롬프트 추가
에이전트의 역할과 작업과 관련된 목적, 컨텍스트, 지침을 정의하려면 시스템 메시지를 제공합니다.
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 파라미터를 에이전트 생성자(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();다음은 temperature 값에 따른 응답 예시입니다.
temperature = 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!temperature = 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!temperature = 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!도구 추가
에이전트는 도구를 사용하여 특정 작업을 수행할 수 있습니다.
먼저, 함수(Kotlin) 또는 메서드(Java)에 @Tool 어노테이션을 붙여 도구를 만듭니다.
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).
에이전트에 더 많은 스텝(도구 호출 및 LLM 요청 포함)이 필요할 것으로 예상되면 maxIterations 파라미터로 이 제한을 늘리거나,
몇 단계만 필요한 에이전트의 경우 줄일 수 있습니다.
예를 들어, 여기서 설명하는 단순한 에이전트는 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();팁: 모델, temperature, 최대 반복 횟수 등의 파라미터를 Kotlin 생성자나 Java 빌더에 직접 전달하는 대신, 별도의 설정 객체로 정의하여 전달할 수도 있습니다. 자세한 내용은 에이전트 설정을 참고하세요.
에이전트 런타임 중 이벤트 처리
테스트 및 디버깅을 지원하고 연결된 에이전트 상호작용을 위한 훅을 만들기 위해, 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
에이전트 빌더에서 .install() 메서드를 사용하여 EventHandler.Feature로 이벤트 핸들러를 등록합니다.
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를 참고하세요.
다음 단계
- 그래프 기반 에이전트와 함수형 에이전트 구축에 대해 자세히 알아보세요.