도구 사용(함수 호출)의 기본 사용법
도구 사용(함수 호출)의 기본 사용법
Cohere의 도구 사용 능력을 활용하는 방법에 대한 개요로, 개발자가 에이전트형 워크플로를 구축할 수 있게 해줍니다 (API v2).
출처: 문서
본문
개요(Overview)
도구 사용은 개발자가 Cohere의 Command 모델 패밀리를 검색 엔진, API, 함수, 데이터베이스 등 외부 도구에 연결할 수 있게 해주는 기법이에요.
이는 도구를 활용해 외부 데이터 소스에 접근하고, API를 통해 작업을 수행하며, 벡터 데이터베이스와 상호작용하고, 검색 엔진을 질의하는 등 풍부한 동작 집합을 열어줍니다. 특히 많은 엔터프라이즈 데이터가 외부 소스에 존재하기 때문에 엔터프라이즈 개발자에게 특히 가치 있어요.
Chat 엔드포인트는 함수 호출, 다단계 추론, 인용 생성 같은 도구 사용 능력이 기본 내장되어 있습니다.

도구 사용으로 문서를 검색하는 엔드투엔드 예시
이것은 도구 사용의 전체 "왕복(round trip)"을 보여주는 완전하고 최소한의 예시예요: 모델이 사용자로부터 메시지를 받고, 도구 호출을 생성하고, 도구 결과를 얻고, 인용과 함께 응답합니다.
PYTHON
# ! pip install -U cohere # Do this if you don't already have the Cohere client installed.
import json
import cohere
def search_docs(query: str, top_k: int = 3):
# Implement your retrieval logic here (vector DB, keyword search, etc.)
# For simplicity, we'll return a few hardcoded "documents".
return [
{
"title": "Cohere API v2 - Chat",
"url": "https://docs.cohere.com/reference/chat",
"text": "Use the Chat endpoint to generate responses and optionally call tools.",
},
{
"title": "Tool use (function calling) overview",
"url": "https://docs.cohere.com/v2/docs/tool-use-overview",
"text": "Tool use connects models to external tools like search engines and APIs.",
},
{
"title": "Structured outputs",
"url": "https://docs.cohere.com/docs/structured-outputs",
"text": "Use JSON schema to define structured inputs/outputs for tools and responses.",
},
][:top_k]
functions_map = {"search_docs": search_docs}
tools = [
{
"type": "function",
"function": {
"name": "search_docs",
"description": "Search documentation and return relevant snippets as documents.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query to look up in the docs.",
},
"top_k": {
"type": "integer",
"description": "How many documents to return.",
},
},
"required": ["query"],
},
},
}
]
co = cohere.ClientV2("COHERE_API_KEY")
# Step 1: user message
messages = [
{
"role": "user",
"content": "How does tool use work in Cohere? Please cite your sources.",
}
]
# Step 2: model generates tool calls
response = co.chat(
model="command-a-plus-05-2026", messages=messages, tools=tools
)
if response.message.tool_calls:
messages.append(response.message)
# Step 3: application executes tools and sends tool results back
for tc in response.message.tool_calls:
tool_result = functions_map[tc.function.name](
**json.loads(tc.function.arguments)
)
tool_content = []
for data in tool_result:
tool_content.append(
{
"type": "document",
"document": {"data": json.dumps(data)},
}
)
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"content": tool_content,
}
)
# Step 4: model generates a response grounded in tool results (with citations)
response = co.chat(
model="command-a-plus-05-2026", messages=messages, tools=tools
)
print(response.message.content[0].text)
print(response.message.citations)
아래 섹션들에서는 설정부터 시작해 도구 사용 루프의 단계를 살펴볼게요.
설정(Setup)
먼저 Cohere 라이브러리를 임포트하고 클라이언트를 만듭니다.
Cohere 플랫폼
PYTHON
# ! pip install -U cohere
import cohere
co = cohere.ClientV2(
"COHERE_API_KEY"
) # Get your free API key here: https://dashboard.cohere.com/api-keys
프라이빗 배포(Private deployment)
PYTHON
# ! pip install -U cohere
import cohere
co = cohere.ClientV2(
api_key="", # Leave this blank
base_url="<YOUR_DEPLOYMENT_URL>",
)
도구 정의(Tool definition)
도구 사용 워크플로를 실행하기 전에 도구를 정의해야 해요. 이 과정을 두 단계로 나눌 수 있습니다:
- 도구 만들기
- 도구 스키마 정의
도구 만들기(Creating the tool)
도구는 여러분이 만드는 어떤 함수든, 또는 주어진 입력에 대해 객체를 반환하는 외부 서비스일 수 있어요. 몇 가지 예시:
- 웹 검색 엔진
- 이메일 서비스
- SQL 데이터베이스
- 벡터 데이터베이스
- 문서 검색 서비스
- 스포츠 데이터 서비스
- 다른 LLM.
이 가이드에서는 주어진 쿼리에 대한 관련 문서 스니펫을 반환하는 search_docs 함수를 정의해요. 여기서 어떤 검색 로직이든 구현할 수 있지만, 단순화를 위해 몇몇 하드코딩된 문서를 반환하겠습니다.
PYTHON
def search_docs(query, top_k=3):
# Implement any retrieval logic here (vector DB, keyword search, etc.)
return [
{
"title": "Tool use (function calling) overview",
"url": "https://docs.cohere.com/v2/docs/tool-use-overview",
"text": "Tool use connects models to external tools like search engines and APIs.",
},
{
"title": "Chat API reference (v2)",
"url": "https://docs.cohere.com/reference/chat",
"text": "Use the Chat endpoint to generate responses and optionally call tools.",
},
{
"title": "Structured outputs",
"url": "https://docs.cohere.com/docs/structured-outputs",
"text": "Use JSON schema to define structured inputs/outputs for tools and responses.",
},
][:top_k]
# Return a string or a list of objects. In Step 3 below, we'll wrap each object into a `document`
# content block so the model can cite specific tool results.
functions_map = {"search_docs": search_docs}
Chat 엔드포인트는 도구 결과로 문자열 또는 객체 목록을 받아들여요. 따라서 반환 값을 이런 방식으로 포맷해야 합니다. 다음은 몇 가지 예시입니다.
PYTHON
# Example: String
docs_search_results = "Tool use connects models to external tools like search engines and APIs."
# Example: List of objects
docs_search_results = [
{
"title": "Tool use (function calling) overview",
"url": "https://docs.cohere.com/v2/docs/tool-use-overview",
"text": "Tool use connects models to external tools like search engines and APIs.",
},
{
"title": "Structured outputs",
"url": "https://docs.cohere.com/docs/structured-outputs",
"text": "Use JSON schema to define structured inputs/outputs for tools and responses.",
},
]
도구 스키마 정의(Defining the tool schema)
또한 Chat 엔드포인트에 전달할 수 있는 형식으로 도구 스키마를 정의해야 해요. 스키마는 JSON Schema 사양을 따르며 다음 필드를 포함해야 합니다:
name: 도구의 이름.description: 도구가 무엇이고 무엇에 사용되는지에 대한 설명.parameters: 도구가 받아들이는 파라미터 목록. 각 파라미터에 대해 다음 필드를 정의해야 합니다:type: 파라미터의 유형.properties: 파라미터의 이름과 다음 필드:type: 파라미터의 유형.description: 파라미터가 무엇이고 무엇에 사용되는지에 대한 설명.
required: 이름으로 된 필수 속성 목록으로,properties객체의 키로 나타납니다.
이 스키마는 LLM에게 도구가 무엇을 하는지 알려주며, LLM은 그 안에 포함된 정보를 바탕으로 특정 도구를 사용할지 결정해요.
따라서 스키마가 더 설명적이고 명확할수록 LLM이 올바른 도구 호출 결정을 내릴 가능성이 높아집니다.
일반적인 개발 주기에서는 name, description, properties 같은 필드가 최상의 결과를 얻기 위해 몇 차례 반복이 필요할 가능성이 높아요(프롬프트 엔지니어링과 유사한 접근 방식).
다음은 예시입니다:
PYTHON
tools = [
{
"type": "function",
"function": {
"name": "search_docs",
"description": "Search documentation and return relevant snippets as documents.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query to look up in the docs.",
},
"top_k": {
"type": "integer",
"description": "How many documents to return.",
},
},
"required": ["query"],
},
},
},
]
참고(Note)
엔드포인트는 JSON Schema 사양의 하위 집합을 지원합니다. 지원 및 미지원 파라미터 목록은 Structured Outputs 문서를 참조하세요.
도구 사용 워크플로(Tool use workflow)
높은 수준에서 핵심 도구 사용 루프에는 네 단계가 있어요:
- 1단계: 사용자 메시지 얻기: 사용자가 "Cohere에서 도구 사용은 어떻게 작동하나요? 출처를 인용해 주세요."라고 묻습니다.
- 2단계: 도구 호출 생성:
search_docs("tool use Cohere")같은 것으로 문서 검색 도구에 도구 호출이 이루어집니다. - 3단계: 도구 결과 얻기: 도구가 관련 문서 스니펫(문서들)을 반환합니다.
- 4단계: 응답 및 인용 생성: 모델이 그 스니펫에 근거한 답변을 인용과 함께 제공합니다.
다음 섹션에서는 이 단계들의 구현을 자세히 살펴볼게요.
1단계: 사용자 메시지 얻기
첫 단계에서는 사용자 메시지를 받아 role을 user로 설정해 messages 목록에 추가합니다.
PYTHON
messages = [
{
"role": "user",
"content": "How does tool use work in Cohere? Please cite your sources.",
}
]
시스템 메시지(System message)
선택사항: 시스템 메시지를 정의하려면 role을 system으로 설정해 messages 목록에 추가할 수 있어요.
PYTHON
system_message = """## Task & Context
You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
## Style Guide
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.
"""
messages = [
{"role": "system", "content": system_message},
{
"role": "user",
"content": "How does tool use work in Cohere? Please cite your sources.",
},
]
2단계: 도구 호출 생성
다음으로, 도구 호출 목록을 생성하기 위해 Chat 엔드포인트를 호출해요. 이는 Chat 엔드포인트에 model, messages, tools 파라미터를 전달해 수행합니다.
모델이 도구가 필요하다고 판단하면 엔드포인트는 수행할 도구 호출 목록을 다시 보내요. 그럴 경우 두 가지 유형의 정보를 반환합니다:
tool_plan: 사용자 쿼리를 고려해 취해야 할 다음 단계에 대한 모델의 반성(reflection).tool_calls: 수행할 도구 호출 목록(있는 경우), 자동 생성된 도구 호출 ID와 함께. 각 생성된 도구 호출은 다음을 포함합니다:id: 도구 호출 IDtype: 도구 호출의 유형(function)function: 호출할 함수, 함수의name과 함수에 전달할arguments를 포함.
그런 다음 role을 assistant로 설정해 이들을 messages 목록에 추가합니다.
PYTHON
response = co.chat(
model="command-a-plus-05-2026", messages=messages, tools=tools
)
if response.message.tool_calls:
messages.append(response.message)
print(response.message.tool_plan, "\n")
print(response.message.tool_calls)
cURL
curl --request POST \
--url https://api.cohere.ai/v2/chat \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Authorization: bearer ***" \
--data '{
"model": "command-a-plus-05-2026",
"messages": [
{
"role": "user",
"content": "How does tool use work in Cohere? Please cite your sources."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "search_docs",
"description": "Search documentation and return relevant snippets as documents.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query to look up in the docs."
},
"top_k": {
"type": "integer",
"description": "How many documents to return."
}
},
"required": ["query"]
}
}
}
]
}'
예제 응답:
I will search the docs for how tool use works in Cohere.
[
ToolCallV2(
id="search_docs_1byjy32y4hvq",
type="function",
function=ToolCallV2Function(
name="search_docs", arguments='{"query":"tool use Cohere","top_k":3}'
),
)
]
기본적으로 Python SDK를 사용할 때 엔드포인트는 도구 호출을 ToolCallV2 및 ToolCallV2Function 유형의 객체로 전달해요. 이를 통해 개발 중 흔한 오류를 방지하는 데 도움이 되는 내장 유형 안전성과 검증을 얻을 수 있습니다.
또는 일반 사전(plain dictionary)을 사용해 도구 호출 메시지를 구성할 수도 있어요.
이 두 옵션은 아래에 나와 있습니다.
Python 객체(Python objects)
PYTHON
messages = [
{
"role": "user",
"content": "Find docs about tool use and structured outputs.",
},
{
"role": "assistant",
"tool_plan": "I will search the docs for tool use and structured outputs.",
"tool_calls": [
ToolCallV2(
id="search_docs_dkf0akqdazjb",
type="function",
function=ToolCallV2Function(
name="search_docs",
arguments='{"query":"tool use","top_k":3}',
),
),
ToolCallV2(
id="search_docs_gh65bt2tcdy1",
type="function",
function=ToolCallV2Function(
name="search_docs",
arguments='{"query":"structured outputs","top_k":3}',
),
),
],
},
]
일반 사전(Plain dictionaries)
PYTHON
messages = [
{
"role": "user",
"content": "Find docs about tool use and structured outputs.",
},
{
"role": "assistant",
"tool_plan": "I will search the docs for tool use and structured outputs.",
"tool_calls": [
{
"id": "search_docs_dkf0akqdazjb",
"type": "function",
"function": {
"name": "search_docs",
"arguments": '{"query":"tool use","top_k":3}',
},
},
{
"id": "search_docs_gh65bt2tcdy1",
"type": "function",
"function": {
"name": "search_docs",
"arguments": '{"query":"structured outputs","top_k":3}',
},
},
],
},
]
직접 응답(Directly responding)
모델은 도구 호출을 하지 않기로 결정하고, 대신 사용자 메시지에 직접 응답할 수 있어요. 이는 여기에 설명되어 있습니다.
병렬 도구 호출(Parallel tool calling)
모델은 두 개 이상의 도구 호출이 필요하다고 판단할 수 있어요. 이는 같은 도구를 여러 번 호출하거나, 얼마든지 많은 호출에 걸쳐 다른 도구들을 호출하는 것일 수 있어요. 이는 여기에 설명되어 있습니다.
3단계: 도구 결과 얻기
이 단계에서는 실제 함수 호출이 일어나요. 엔드포인트가 준 도구 호출 페이로드를 바탕으로 필요한 도구를 호출합니다.
각 도구 호출에 대해 messages 목록에 다음을 추가합니다:
- 이전 단계에서 생성된
tool_call_id. - 다음 필드를 가진 각 도구 결과의
content:document인typedocument는 다음을 포함:data: 도구 결과의 내용을 저장.id(선택사항): 각 문서에 인용용 고유 ID를 제공할 수 있고, 그렇지 않으면 자동 생성.
PYTHON
import json
if response.message.tool_calls:
for tc in response.message.tool_calls:
tool_result = functions_map[tc.function.name](
**json.loads(tc.function.arguments)
)
tool_content = []
for data in tool_result:
# Optional: the "document" object can take an "id" field for use in citations, otherwise auto-generated
tool_content.append(
{
"type": "document",
"document": {"data": json.dumps(data)},
}
)
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"content": tool_content,
}
)
4단계: 응답 및 인용 생성
이쯤 되면 도구 호출은 이미 실행됐고, 결과가 LLM에 반환됐어요.
이 단계에서는 다시 model, messages(지금은 도구 호출 및 도구 실행 단계의 정보로 갱신됨), tools 파라미터를 전달해 Chat 엔드포인트를 호출해 사용자에게 응답을 생성합니다.
모델은 도구가 제공한 정보에 근거하여 사용자에게 응답을 생성해요.
그런 다음 role을 assistant로 설정해 응답을 messages 목록에 추가합니다.
PYTHON
response = co.chat(
model="command-a-plus-05-2026", messages=messages, tools=tools
)
messages.append(
{"role": "assistant", "content": response.message.content[0].text}
)
print(response.message.content[0].text)
cURL
curl --request POST \
--url https://api.cohere.ai/v2/chat \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Authorization: bearer ***" \
--data '{
"model": "command-a-plus-05-2026",
"messages": [
{
"role": "user",
"content": "How does tool use work in Cohere? Please cite your sources."
},
{
"role": "assistant",
"tool_plan": "I will search the docs for how tool use works in Cohere.",
"tool_calls": [
{
"id": "search_docs_1byjy32y4hvq",
"type": "function",
"function": {
"name": "search_docs",
"arguments": "{\"query\":\"tool use Cohere\",\"top_k\":3}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "search_docs_1byjy32y4hvq",
"content": [
{
"type": "document",
"document": {
"data": "{\"title\": \"Tool use (function calling) overview\", \"url\": \"https://docs.cohere.com/v2/docs/tool-use-overview\", \"text\": \"Tool use connects models to external tools like search engines and APIs.\"}"
}
}
]
}
],
"tools": [
{
"type": "function",
"function": {
"name": "search_docs",
"description": "Search documentation and return relevant snippets as documents.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query to look up in the docs."
},
"top_k": {
"type": "integer",
"description": "How many documents to return."
}
},
"required": ["query"]
}
}
}
]
}'
예제 응답:
Tool use lets models call external tools (like doc search) and then answer using the tool results, with citations.
또한 세밀한 인용을 생성하는데, 이는 Command 모델 패밀리에서 기본 제공됩니다. 여기서 모델이 두 개의 인용을 생성하는 것을 볼 수 있는데, 응답의 각 특정 구간에 대해 하나씩이며, 도구 결과를 사용해 질문에 답합니다.
PYTHON
print(response.message.citations)
예제 응답:
[Citation(start=0, end=8, text='Tool use', sources=[ToolSource(type='tool', id='search_docs_1byjy32y4hvq:0', tool_output={'title': 'Tool use (function calling) overview', 'url': 'https://docs.cohere.com/v2/docs/tool-use-overview', 'text': 'Tool use connects models to external tools like search engines and APIs.'})], type='TEXT_CONTENT')]
다단계 도구 사용(에이전트)
위에서는 모델이 도구 호출을 한 번만(단일 호출 또는 병렬 호출) 수행한 다음 응답을 생성한다고 가정해요. 항상 그런 것은 아닙니다: 모델은 사용자 요청에 답하기 위해 일련의 도구 호출을 수행하기로 결정할 수 있어요. 이는 2단계와 3단계가 루프에서 여러 번 실행된다는 뜻입니다. 이를 다단계 도구 사용(multi-step tool use)이라고 하며 여기에 설명되어 있습니다.
상태 관리(State management)
이 섹션에서는 위의 도구 사용 워크플로에 설명된 대로 messages 목록을 통해 상태가 관리되는 방식을 더 자세히 살펴봅니다.
워크플로의 각 단계에서 엔드포인트는 특정 유형의 정보를 messages 목록에 추가할 것을 요구해요. 이는 특정 시점에 모델이 응답을 생성하는 데 필요한 컨텍스트를 갖도록 보장하기 위함입니다.
요약하면, 도구 호출이 포함된 대화의 각 단일 턴은 다음으로 구성됩니다:
- 사용자 메시지를 담은
user메시지content
- 도구 호출 정보를 담은
assistant메시지tool_plantool_callsidtypefunction(name과arguments로 구성)
- 도구 결과를 담은
tool메시지tool_call_id- 다음 필드를 가진 문서 목록을 담는
content— 각 문서는 다음을 포함:typedocument(data와 선택적id로 구성)
- 모델의 응답을 담은 최종
assistant메시지content
이들은 위에서 설명한 네 단계에 해당합니다. messages 목록은 아래와 같아요.
PYTHON
for message in messages:
print(message, "\n")
{
"role": "user",
"content": "How does tool use work in Cohere? Please cite your sources."
}
{
"role": "assistant",
"tool_plan": "I will search the docs for how tool use works in Cohere.",
"tool_calls": [
ToolCallV2(
id="search_docs_1byjy32y4hvq",
type="function",
function=ToolCallV2Function(
name="search_docs", arguments='{"query":"tool use Cohere","top_k":3}'
),
)
],
}
{
"role": "tool",
"tool_call_id": "search_docs_1byjy32y4hvq",
"content": [{"type": "document", "document": {"data": "{\"title\":\"Tool use (function calling) overview\",\"url\":\"https://docs.cohere.com/v2/docs/tool-use-overview\",\"text\":\"Tool use connects models to external tools like search engines and APIs.\"}"}}],
}
{
"role": "assistant",
"content": "Tool use lets models call external tools (like doc search) and then answer using the tool results, with citations."
}
messages의 순서는 아래 다이어그램에 표현되어 있습니다.
%%{init: {'htmlLabels': true}}%%
flowchart TD
classDef defaultStyle fill:#fff,stroke:#000,color:#000;
A["<div><b>USER</b><br />Query</div>"]
B["<div><b>ASSISTANT</b><br />Tool call</div>"]
C["<div><b>TOOL</b><br />Tool result</div>"]
D["<div><b>ASSISTANT</b><br />Response</div>"]
A -.-> B
B -.-> C
C -.-> D
class A,B,C,D defaultStyle;
이 순서는 도구 사용의 기본 사용 패턴을 나타냄을 참고하세요. 다음 페이지는 이를 다른 시나리오에 어떻게 적용하는지 설명합니다.