Cohere로 에이전트 만들기
Cohere로 에이전트 만들기
이 페이지는 단일 도구를 사용하는 에이전트를 만드는 방법을 설명해요. 도구를 정의하는 것부터 그에 대응하는 출력을 질의하는 것까지, 작업을 수행하기 위한 간단하고 수동적인 단계를 만들어 볼게요.
출처: 문서
본문
이 튜토리얼에서는 하나의 도구를 가진 단일 모델 Cohere 에이전트를 만드는 과정을 차근차근 살펴볼게요. 도구 정의부터 해당 출력 질의까지, 작업을 수행하기 위한 간단하고 수동적인 단계를 만드는 방법을 배우게 돼요.
이 튜토리얼은 코드 불필요한 Cohere 소개인 "Build Things with Cohere"에서 각색했어요. 환경을 설정하려면 다음 중 하나를 완료하세요:
-
튜토리얼 시리즈의 Part 1: 설치 및 설정을 완료해요.
-
그리고/또는 SDK 설치와 키 발급에 대한 빠른 안내가 있는 Quickstart를 확인해요.
에이전트란 무엇인가요? (What is an Agent?)
에이전트는 LLM을 활용해 자연어 요청, 도구 호출, 단계들을 연결해 작업을 수행하는 AI 애플리케이션이에요. 에이전트는 어떤 단계를 밟을지, 어떤 도구를 호출할지 결정한 다음 직접 호출해요. Cohere는 멀티스텝 도구 사용을 통해 여러분이 직접 에이전트를 만들 수 있게 해줘요.
에이전트는 어떻게 작동하나요? (How the Agent Works)
에이전트는 다음 구성 요소로 이루어져 있어요:
-
LLM: 에이전트를 구동하는 언어 모델이에요. Cohere 모델 간에 전환할 때는 Command A+가 더 지능적이지만 더 느리고, Command R+는 덜 지능적이지만 더 빠르다는 점을 염두에 두세요.
-
Tools (도구): 도구는 모델의 능력을 확장해요. 예를 들어 웹을 탐색하거나, 코드를 실행하거나, 내부 데이터에 접근할 수 있게 해줘요. LLM은 스스로 내부 데이터를 가져올 수 없기 때문에 도구가 필요해요. 이 튜토리얼에서는 에이전트가 도구 하나만 갖게 될 거예요.
-
Agent Orchestrator (에이전트 오케스트레이터): 이 구성 요소는 에이전트의 "두뇌" 역할을 하며, 다음에 무엇을 할지 결정해요. 일련의 단계를 사용해 주어진 사용자 텍스트 프롬프트를 어떻게 처리할지 결정해요. 예를 들어, 먼저 웹 검색에서 정보를 찾은 다음 도구 호출을 결정하는 식이에요.
-
Chat History (대화 기록): 에이전트는 대화 기록을 유지하며, 대화에서 일어난 모든 상호 작용을 추적해요.
1단계: 도구 정의하기 (Define the Tool)
이 단계에서는 IBM Knowledge Panel에서 이름이 지정된 Entity를 검색하는 함수를 만들 거예요. 특수 문자를 처리하기 위해 URL 인코딩에 RFC3986 인코딩을 사용할게요. 모델이 검색할 수 있도록 토론 페이지 링크를 제공할 거예요.
이 예시에서는 회사/창업자 쌍을 검색하는 함수를 사용하고 있어요. 이 함수는 입력으로 회사 이름을 받아요.
PYTHON
import requests
PANEL_EXAMPLE = "https://duckduckgo.com/?q=entity+panel&ia=knowledge
URL_BASE = "https://en.wikipedia.org/w/index.php?search="
def search_knowledge_panel(entity: str, rfc3986_encoded: bool = True) -> str:
if rfc3986_encoded:
url = URL_BASE + quote(entity)
else:
url = URL_BASE + entity
# Fetch page source
response = requests.get(url)
# Return the user-friendly content
return response.text
def reload_func():
"reload module"
def main():
entity = "Co1t"
# Need to import this to use quote()
from urllib.parse import quote
print(...)
2단계: 에이전트 설정하기 (Set up the Agent)
Cohere 클라이언트와 에이전트를 설정해요.
PYTHON
# Import necessary libraries
import cohere
# Initialize API client
co = cohere.ClientV2(api_key="YOUR_COHERE_API_KEY")
# Set up agent parameters
tools = [
{
"type": "function",
"function": {
"name": "search_knowledge_panel",
"description": "Search the IBM Knowledge Panel for a given entity (e.g., company or founder).",
"parameters": {
"type": "object",
"properties": {
"entity": {
"type": "string",
"description": "The entity (company or founder) to search for.",
}
},
"required": ["entity"]
}
}
}
]
# Mention the tools to the model
print(
"Defining the tool passed to the model: ", tools[0]["function"]["name"]
)
3단계: 도구 연결하고 상호 작용하기 (Connect the Tool and Interact)
이제 정의한 도구를 함께 전달하면서 모델에 호출을 만들 수 있어요.
PYTHON
# Defining the message to ask and tool call to make
message = "Find the founders of Co1t"
# Pass the message and tools to the model
response = co.chat(
model="command-a-03-2025",
messages=[
{"role": "user", "content": message}
],
tools=tools,
)
# See the response
print(response.message.tool_calls)
# print(response.message.content[0].text)
4단계: 모델에 도구 출력 제공하기 (Provide the Tool Output Back to the Model)
이제 도구의 출력을 모델에 다시 제공해 최종 답변을 생성할 수 있게 해야 해요.
PYTHON
# Now, using the output from the model we need to make the tool call
# execution of the tool
query = response.message.tool_calls[0].function.arguments
search_results = search_knowledge_panel(query)
search_results_shortened = search_results[:5000]
# Encapsulate the output
tool_output = [{
"type": "function_result",
"id": response.message.tool_calls[0].id,
"function_results": [
{
"call_id": response.message.tool_calls[0].id,
"output": search_results_shortened,
}
],
}]
# Prepare the message for response generation
generate_response = co.chat(
model="command-a-03-2025",
messages=[
{"role": "user", "content": message},
{"role": "assistant", "tool_calls": response.message.tool_calls},
{"role": "tool", "tool_call_id": response.message.tool_calls[0].id, "content": [{"type": "text", "text": search_results_shortened}]},
],
tools=tools,
)
print(generate_response.message.content[0].text)
다음 단계 (Next Steps)
더 배우고 싶다면 다음 섹션으로 계속 진행하세요: agentic RAG.