함수 호출 (Function Calling)
함수 호출은 모델이 사용자 요구에 따라 사전 정의된 도구 함수를 자동으로 선택하여 호출할 수 있게 하며, 데이터 조회, API 호출, 작업 실행 등의 기능을 구현합니다.
기본 개념
함수 호출의 전체 흐름:
- 도구 정의 — 요청에서 사용 가능한 함수와 파라미터를 설명
- 모델 판단 — 모델이 도구 호출 필요 여부를 판단
- 호출 반환 — 모델이 함수 이름과 파라미터를 반환
- 함수 실행 — 함수를 실행하고 결과를 획득
- 대화 계속 — 결과를 모델에 다시 전송하여 최종 응답 생성
OpenAI 프로토콜
Python
function_calling.py
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.ofox.ai/v1",
api_key="<OFOXAI_API_KEY>"
)
# 1. 도구 정의
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "지정한 도시의 실시간 날씨 정보를 가져옵니다",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "도시 이름, 예: 서울, 부산"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "온도 단위"
}
},
"required": ["city"]
}
}
}]
# 2. 요청 전송
messages = [{"role": "user", "content": "서울 오늘 날씨 어때요?"}]
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
message = response.choices[0].message
# 3. 도구 호출 처리
if message.tool_calls:
for tool_call in message.tool_calls:
args = json.loads(tool_call.function.arguments)
# 4. 함수 실행
result = get_weather(args["city"]) # 직접 구현한 함수
# 5. 결과를 모델에 다시 전송
messages.append(message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
})
# 최종 응답 받기
final = client.chat.completions.create(
model="openai/gpt-4o",
messages=messages,
tools=tools
)
print(final.choices[0].message.content)Anthropic 프로토콜
Anthropic은 tools 파라미터를 사용하며, 형식이 약간 다릅니다:
anthropic_tools.py
import anthropic
client = anthropic.Anthropic(
base_url="https://api.ofox.ai/anthropic",
api_key="<OFOXAI_API_KEY>"
)
response = client.messages.create(
model="anthropic/claude-sonnet-4.5",
max_tokens=1024,
tools=[{
"name": "get_weather",
"description": "지정한 도시의 실시간 날씨 정보를 가져옵니다",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "도시 이름"}
},
"required": ["city"]
}
}],
messages=[{"role": "user", "content": "서울 오늘 날씨 어때요?"}]
)
# tool_use content block 처리
for block in response.content:
if block.type == "tool_use":
print(f"도구 호출: {block.name}, 파라미터: {block.input}")병렬 함수 호출
모델은 한 번의 응답에서 여러 도구 호출을 반환할 수 있으며, 이를 병렬로 실행해야 합니다:
# 모델이 동시에 여러 도구 호출을 요청할 수 있음
if message.tool_calls:
# 모든 도구 호출을 병렬로 실행
import asyncio
async def execute_tools(tool_calls):
tasks = []
for tc in tool_calls:
args = json.loads(tc.function.arguments)
tasks.append(execute_function(tc.function.name, args))
return await asyncio.gather(*tasks)tool_choice 파라미터
| 값 | 설명 |
|---|---|
"auto" | 모델이 도구 호출 여부를 자동 결정 (기본값) |
"none" | 도구 호출 비활성화 |
"required" | 도구 호출 강제 |
{"type": "function", "function": {"name": "xxx"}} | 지정 도구 강제 호출 |
지원 모델
다음 모델이 Function Calling을 지원합니다:
- OpenAI:
gpt-4o,gpt-4o-mini,o1,o3-mini - Anthropic:
claude-opus-4,claude-sonnet-4,claude-3-5-haiku - Google:
gemini-3.1-pro-preview,gemini-3-flash-preview,gemini-3-pro-preview - 기타:
deepseek-chat,qwen-max,glm-4
Last updated on