모델 기능
도구 호출
도구 호출(함수 호출)을 사용하면 모델이 직접 정의한 함수에 대한 구조화된 호출을 반환합니다. 코드가 이를 실행하고 결과를 다시 전달하면 모델이 그 결과를 바탕으로 답변합니다. 도구 호출 기능을 갖춘 모델에서 사용할 수 있습니다.
전체 흐름
- 1함수를
tools에 JSON Schema로 정의합니다. - 2모델이
tool_calls를 반환합니다(finish_reason은tool_calls). - 3코드가 각 함수를 실행하고 결과를 일치하는
tool_call_id와 함께role: "tool"메시지로 추가합니다. - 4API를 다시 호출하면 모델이 도구 결과를 활용해 답변합니다.
import json
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string", "description": "City name, e.g. Tokyo"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]
resp = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools)
msg = resp.choices[0].message
if msg.tool_calls:
messages.append(msg) # 1. keep the assistant's tool_calls
for call in msg.tool_calls:
args = json.loads(call.function.arguments) # 2. run the tool in your code
result = {"city": args["city"], "temp_c": 22, "sky": "clear"}
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
final = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools)
print(final.choices[0].message.content) # 3. the model answers using the result도구 사용 제어
| tool_choice | 동작 |
|---|---|
"auto" (기본값) | 모델이 판단합니다 |
"none" | 도구를 절대 호출하지 않습니다 |
"required" | 최소 하나의 도구를 호출합니다 |
{"type": "function", "function": {"name": "..."}} | 특정 함수를 강제합니다 |
일부 최신 모델은 강제 도구 사용(
required 또는 특정 함수 지정)을 지원하지 않고 400을 반환합니다. auto를 사용하고 프롬프트에 각 도구의 사용 시점을 명시하세요.병렬 호출
모델은 여러 개의 tool_calls를 한 번에 반환할 수 있습니다. 모두 실행한 뒤 같은 요청에 각 결과를 tool_call_id로 매칭하여 tool 메시지로 전송하세요.
Anthropic 형식
네이티브 형식에서는 도구를 input_schema로 정의하고, 호출은 tool_use / tool_result 콘텐츠 블록으로 주고받습니다.
resp = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=[{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}],
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
)
# When stop_reason == "tool_use", content holds tool_use blocks; run them and reply with:
# {"role": "user", "content": [{"type": "tool_result", "tool_use_id": block.id, "content": "..."}]}팁
- 이름과 설명은 명확하게 작성하세요. 도구가 무엇을 하는지, 언제 사용하는지가 모델의 선택 기준이 됩니다.
- 스키마는 엄격하게 작성하세요.
enum과required를 사용하고 모호한 자유 텍스트 필드는 피하세요. - 도구를 실행하기 전에 인자를 검증하세요. 문자열 매칭이 아니라 항상 JSON으로 파싱하세요.
- 도구 결과에는 모델에 필요한 필드만 담아 간결하게 반환하세요. 입력 토큰을 절약할 수 있습니다.