도구 사용(Tool use) & 에이전트 - 퀵스타트

도구 사용(Tool use) & 에이전트 - 퀵스타트

Cohere의 Command 모델(v2 API)로 도구 사용과 에이전트를 구축하는 퀵스타트 가이드예요.

출처: 문서

본문

도구 사용 & 에이전트란

도구 사용(tool use)을 통해 개발자는 외부 도구에 연결하고, 추론하며, 실제로 행동을 수행하는 에이전트형 애플리케이션을 만들 수 있어요.

Chat 엔드포인트에는 함수 호출(function calling), 다단계 추론, 인용 생성 같은 도구 사용 기능이 내장되어 있어요.

이 퀵스타트 가이드는 Chat 엔드포인트에서 도구 사용을 활용하는 방법을 보여드려요.

설정

먼저 다음 명령으로 Cohere Python SDK를 설치해요.

pip install -U cohere

다음으로 라이브러리를 import하고 클라이언트를 만들어요.

Cohere Platform

PYTHON

import cohere

co = cohere.ClientV2(
    "COHERE_API_KEY"
)  # Get your free API key here: https://dashboard.cohere.com/api-keys

Private Deployment

PYTHON

import cohere

co = cohere.ClientV2(
    api_key="",  # Leave this blank
    base_url="<YOUR_DEPLOYMENT_URL>",
)

Bedrock

PYTHON

import cohere

co = cohere.BedrockClientV2(
    aws_region="AWS_REGION",
    aws_access_key="AWS_ACCESS_KEY_ID",
    aws_secret_key="AWS_SECRET_ACCESS_KEY",
    aws_session_token="AWS_SESSION_TOKEN",
)

# Get the model name: https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html

SageMaker

PYTHON

import cohere

co = cohere.SagemakerClientV2(
    aws_region="AWS_REGION",
    aws_access_key="AWS_ACCESS_KEY_ID",
    aws_secret_key="AWS_SECRET_ACCESS_KEY",
    aws_session_token="AWS_SESSION_TOKEN",
)

Azure AI

PYTHON

import cohere

co = cohere.ClientV2(
    api_key="AZURE_API_KEY",
    base_url="AZURE_ENDPOINT",  # example: "https://cohere-command-r-plus-08-2024-xyz.eastus.models.ai.azure.com/"
)

도구 정의(Tool Definition)

먼저 도구를 설정해야 해요. 도구는 객체를 주고받을 수 있는 어떤 함수나 서비스든 될 수 있어요.

또한 도구 스키마를 Chat 엔드포인트에 전달할 수 있는 형식으로 정의해야 해요. 스키마에는 반드시 name, description, parameters 필드가 포함되어야 해요.

PYTHON

def get_weather(location):
    # Implement your tool calling logic here
    return [{"temperature": "20C"}]
    # Return a list of objects e.g. [{"url": "abc.com", "text": "..."}, {"url": "xyz.com", "text": "..."}]


functions_map = {"get_weather": get_weather}

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "gets the weather of a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "the location to get weather, example: San Fransisco, CA",
                    }
                },
                "required": ["location"],
            },
        },
    },
]

도구 호출(Tool Calling)

다음으로, 사용자 메시지와 함께 도구 스키마를 Chat 엔드포인트에 전달해요.

그러면 LLM이 (있다면) 도구 호출을 생성하고 tool_plan과 tool_calls 객체를 반환해요.

Cohere Platform

PYTHON

messages = [
    {"role": "user", "content": "What's the weather in Toronto?"}
]

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_calls)

Private Deployment

PYTHON

messages = [
    {"role": "user", "content": "What's the weather in Toronto?"}
]

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_calls)

Bedrock

PYTHON

messages = [
    {"role": "user", "content": "What's the weather in Toronto?"}
]

response = co.chat(
    model="YOUR_MODEL_NAME", messages=messages, tools=tools
)

if response.message.tool_calls:
    messages.append(response.message)
    print(response.message.tool_calls)

SageMaker

PYTHON

messages = [
    {"role": "user", "content": "What's the weather in Toronto?"}
]

response = co.chat(
    model="YOUR_ENDPOINT_NAME", messages=messages, tools=tools
)

if response.message.tool_calls:
    messages.append(response.message)
    print(response.message.tool_calls)

Azure AI

PYTHON

messages = [
    {"role": "user", "content": "What's the weather in Toronto?"}
]

response = co.chat(
    model="model",  # Pass a dummy string
    messages=messages,
    tools=tools,
)

if response.message.tool_calls:
    messages.append(response.message)
    print(response.message.tool_calls)
[ToolCallV2(id='get_weather_776n8ctsgycn', type='function', function=ToolCallV2Function(name='get_weather', arguments='{"location":"Toronto"}'))]

도구 실행(Tool Execution)

다음으로, 앞선 도구 호출 단계에서 생성된 인자에 기반해서 호출된 도구들이 실행돼요.

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:
            tool_content.append(
                {
                    "type": "document",
                    "document": {"data": json.dumps(data)},
                }
            )
            # Optional: add an "id" field in the "document" object, otherwise IDs are auto-generated
        messages.append(
            {
                "role": "tool",
                "tool_call_id": tc.id,
                "content": tool_content,
            }
        )

응답 생성(Response Generation)

결과가 LLM으로 다시 전달되고, LLM이 최종 응답을 생성해요.

Cohere Platform

PYTHON

response = co.chat(
    model="command-a-plus-05-2026", messages=messages, tools=tools
)
print(response.message.content[0].text)

Private Deployment

PYTHON

response = co.chat(
    model="command-a-plus-05-2026", messages=messages, tools=tools
)
print(response.message.content[0].text)

Bedrock

PYTHON

response = co.chat(
    model="YOUR_MODEL_NAME", messages=messages, tools=tools
)
print(response.message.content[0].text)

SageMaker

PYTHON

response = co.chat(
    model="YOUR_ENDPOINT_NAME", messages=messages, tools=tools
)
print(response.message.content[0].text)

Azure AI

PYTHON

response = co.chat(
    model="model",  # Pass a dummy string
    messages=messages,
    tools=tools,
)
print(response.message.content[0].text)
It is 20C in Toronto.

인용 생성(Citation Generation)

응답 객체에는 citations 필드가 있는데, 여기에는 응답이 기반하고 있는 문서의 특정 텍스트 조각들이 들어 있어요.

PYTHON

if response.message.citations:
    for citation in response.message.citations:
        print(citation, "\n")
start=6 end=9 text='20C' sources=[ToolSource(type='tool', id='get_weather_776n8ctsgycn:0', tool_output={'temperature': '20C'})] 

더 보기(Further Resources)

더 알아보기 (Learn more)