DeepInfra Tool Calling — 모델이 외부 함수를 부르게 하기
DeepInfra Tool Calling — 모델이 외부 함수를 부르게 하기
AI 에이전트를 만들 때 가장 중요한 능력이 뭐냐고 묻는다면, 바로 도구 호출(Tool Calling)이에요. 웹 검색, 코드 실행, DB 쿼리, API 호출 같은 외부 도구를 모델이 스스로 호출할지 판단하고, 그 결과를 최종 응답에 자연스럽게 녹여내게 하는 게 이 기능의 핵심이에요. 도구 호출이 안정적이지 않으면 에이전트 시스템이 제대로 굴러가기 어려워요.
DeepInfra는 도구 호출 정확도를 최우선 과제로 삼아요. 함수 호출 파싱, 인자 추출, 왕복 신뢰성을 모든 지원 모델에서 올바르게 유지하는 데 많은 엔지니어링을 투자해요. Moonshot의 K2-Vendor-Verifier 평가에서 DeepInfra는 테스트된 프로바이더 중 가장 높은 정확도를 기록했어요. 현재 카탈로그의 Kimi 모델은 moonshotai/Kimi-K3이에요.
DeepInfra는 OpenAI 호환 함수 호출 API를 제공해요. 배경 설명은 DeepInfra 블로그를 참고하면 좋아요.
설정
클라이언트만 만들면 준비 끝이에요.
import openai
import json
client = openai.OpenAI(
base_url="https://api.deepinfra.com/v1/openai",
api_key="$DEEPINFRA_TOKEN",
)
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.deepinfra.com/v1/openai",
apiKey: "$DEEPINFRA_TOKEN",
});
함수 정의
먼저 모델이 호출할 실제 함수를 정의해요. 예시로 위치를 받아 날씨를 돌려주는 함수를 만들어 볼게요.
def get_current_weather(location):
"""Get the current weather in a given location"""
if "tokyo" in location.lower():
return json.dumps({"location": "Tokyo", "temperature": "75"})
elif "san francisco" in location.lower():
return json.dumps({"location": "San Francisco", "temperature": "60"})
elif "paris" in location.lower():
return json.dumps({"location": "Paris", "temperature": "70"})
else:
return json.dumps({"location": location, "temperature": "unknown"})
async function get_current_weather(location) {
if (location.toLowerCase().includes("tokyo")) {
return JSON.stringify({"location": "Tokyo", "temperature": "75"});
} else if (location.toLowerCase().includes("san francisco")) {
return JSON.stringify({"location": "San Francisco", "temperature": "60"});
} else if (location.toLowerCase().includes("paris")) {
return JSON.stringify({"location": "Paris", "temperature": "70"});
} else {
return JSON.stringify({"location": location, "temperature": "unknown"});
}
}
1단계: 모델에 도구 전달
tools 파라미터로 함수의 이름과 인자 스키마를 모델에 알려줘요. tool_choice를 "auto"로 하면 모델이 필요할 때만 도구를 호출해요.
tools = [{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
}
},
"required": ["location"]
},
}
}]
messages = [{"role": "user", "content": "What is the weather in San Francisco?"}]
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=messages,
tools=tools,
tool_choice="auto",
)
tool_calls = response.choices[0].message.tool_calls
for tool_call in tool_calls:
print(tool_call.model_dump())
응답은 이렇게 생겨요. 모델이 어떤 함수를 어떤 인자로 호출할지 알려줘요.
{'id': 'call_X0xYqdnoUonPJpQ6HEadxLHE', 'function': {'arguments': '{"location": "San Francisco"}', 'name': 'get_current_weather'}, 'type': 'function'}
2단계: 함수 실행 후 결과를 다시 보내기
모델의 도구 호출 지시대로 함수를 실제로 실행하고, 그 결과를 role: "tool" 메시지로 대화에 이어 붙여요. 그 다음 같은 대화로 재요청하면 모델이 도구 결과를 반영한 최종 답변을 내놓아요.
# Extend conversation with assistant's reply
messages.append(response.choices[0].message)
for tool_call in tool_calls:
function_name = tool_call.function.name
if function_name == "get_current_weather":
function_args = json.loads(tool_call.function.arguments)
function_response = get_current_weather(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"content": function_response,
})
# Get a new response from the model with function results
second_response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=messages,
tools=tools,
tool_choice="auto",
)
print(second_response.choices[0].message.content)
이렇게 하면 모델이 결과를 바탕으로 "샌프란시스코의 현재 기온은 60도예요." 같은 답을 내놓아요.
팁
- 명확하고 상세한 함수 설명을 써요 — 모델 품질이 여기에 크게 의존해요
- 낮은 temperature(< 1.0)를 써서 파라미터 값이 튀는 걸 막아요
- 도구 호출을 쓸 땐 시스템 메시지를 피해요
- 함수가 많을수록 모델 품질이 떨어져요 — 목록을 집중해서 유지해요
top_p와top_k는 기본값으로 둬요
지원 기능
| 기능 | 지원 여부 |
|---|---|
| 단일 도구 호출 | ✅ |
| 병렬 도구 호출 | ✅ (품질은 모델마다 다를 수 있음) |
tool_choice: "auto" |
✅ |
tool_choice: "none" |
✅ |
| 스트리밍 모드 | ✅ |
| 중첩 호출 | ❌ |
알아둘 점
- 함수 정의는 입력 토큰 사용량에 포함돼요
- 도구 호출을 써도 추론 사용량은 평소대로 계산돼요
더 알아보기
- Chat Completions — 도구 호출이 동작하는 채팅 완성 API
- Structured Outputs — 도구와 함께 쓰기 좋은 JSON 응답
- DeepInfra 문서 전체 인덱스