한 실제 문제에서 시작된 호출 체인
가정해보자, 당신이 날씨 조회 에이전트를 구축하고 있다고 하자. 사용자가 물었다: “베이징 지금 몇 도야?” 에이전트가 답하기 위해서는 반드시 다음 과정을 거쳐야 한다: 의도 이해 → 도구 정의 매칭 → 파라미터 채우기 → 함수 실행 → 결과 반환 → 답변 구성. 이 과정이 바로 tool calling이다.
# 工具定义:一个简单的天气函数
def get_weather(city: str, date: str = "today") -> str:
# 实际调用天气 API
return f"{city} 在 {date} 的天气是晴,25°C"
# 工具描述(供模型选用)
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名"},
"date": {"type": "string", "description": "日期,格式 YYYY-MM-DD"}
},
"required": ["city"]
}
}
}
]
# Agent 调用 LLM 时传入 tools
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "北京现在多少度?"}],
tools=TOOLS,
tool_choice="auto"
)
# 模型返回 tool_call
tool_call = response.choices[0].message.tool_calls[0]
# tool_call.function.name = "get_weather"
# tool_call.function.arguments = '{"city":"北京"}'
# 你执行函数并返回结果
result = get_weather("北京")
# 将结果作为 tool 消息回传给模型
为什么 tool calling 是 Agent 的“手指”
没有 tool calling,AI 只能生成文字建议,无法真正操作任何系统。有了它,Agent 可以:
- 查询数据库:
search_customer(customer_id) - 触发工作流:
create_jira_ticket(summary, priority) - 控制设备:
turn_off_light(room="living_room")
每个工具都是 Agent 的一只手。tool calling 就是大脑(LLM)指挥手的过程。

最容易失败的地方
1. 参数解析错误
模型可能生成错误的 JSON arguments——比如字段名拼写、类型不对、缺少 required 参数。
例子:
- 工具需要
city,模型给了location date格式不是YYYY-MM-DD而是"내일"
应对:在工具描述里写清约束,解析时增加容错逻辑。
import json
def safe_parse_tool_call(tool_call):
try:
args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError:
# 모델이 제공한 arguments가 유효하지 않을 때
return None, "파라미터 파싱 실패"
return args, None
2. 幻觉调用
模型在不确定时,可能虚构参数调用工具。比如用户没提到城市,模型却调用 get_weather("베이징")。
应对:在 tool_choice 设为 "auto",让模型自由决定;如果工具是 destructive 的(如删除、修改),必须加入人为确认步骤。
3. 并发与冲突
Agent 可能同时调用多个工具(例如 parallel_tool_calls)。如果两个工具修改同一个资源,可能产生冲突。
应对:为每个工具设计幂等性或加锁机制。

真实场景:电商客服 Agent
场景:用户要求“帮我查一下订单 12345 的状态,如果已发货就提醒我签收,否则帮我取消订单”。
Agent 需要:
- 调用
get_order_status("12345") - 根据结果调用
send_reminder(user_id)或cancel_order("12345")
如果 get_order_status 返回 "delivered",Agent 调用 send_reminder。如果返回 "processing",则调用 cancel_order(但取消订单需要权限——此处容易失败:模型可能直接执行,你需要加上“取消前必须用户二次确认”的 guardrail)。
失败点:模型可能跳过确认直接取消订单。解决方案:将确认步骤建模为另一个工具 confirm_cancellation(order_id),要求 Agent 先调用确认工具,再执行取消。
替换方案:没有 tool calling 时怎么办
如果你的 API 或框架不支持 tool calling,或模型不支持 function calling,你可以:
- 用结构化输出模拟:要求模型输出 JSON 格式并且指定字段表示动作。例如:
{"action":"get_weather", "args":{"city":"베이징"}} - 用文本解析:手动解析模型输出中的特定指令,例如“调用天气函数:城市=北京”。这种方式容易出错,但适合简单场景。
不过,标准 tool calling 让开发者只需定义工具描述,模型自动匹配,远比手动解析可靠。
落地第一步
- 选择一个支持 tool calling 的框架:OpenAI API、Claude API、LangChain、Vercel AI SDK 都支持。
- 定义你的第一个工具:从只读、非破坏性的开始,比如
search_knowledge_base. - 루프 작성:
- 사용자 메시지 전송 도구 정의
- 모델이 반환한 tool_call 처리
- 도구 실행, 결과 반환
- 결과를 새로운 메시지로 모델에 전달, 모델이 최종 답변 생성
- 오류 처리 추가: 파싱 실패, 시간 초과, 도구 반환 오류가 발생하면 모델이 오류 정보를 기반으로 파라미터를 수정하거나 사용자가 이해할 수 있는 메시지를 생성하게 함.
# 一个简化版 loop
def agent_loop(user_message):
messages = [{"role": "user", "content": user_message}]
while True:
response = client.chat.completions.create(
model="gpt-4o", messages=messages, tools=TOOLS, tool_choice="auto"
)
msg = response.choices[0].message
if not msg.tool_calls:
return msg.content
messages.append(msg)
for tool_call in msg.tool_calls:
name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
# 动态调用
result = tools_map[name](**args)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": str(result)
})
요약
Tool calling은 에이전트가 “말할 수 있는” 단계에서 “행동할 수 있는” 단계로 넘어가는 핵심적인 도약이다. 그 메커니즘을 이해하고, 실패 상황을 예측하며, 합리적으로 가드레일을 설계해야만 에이전트가 실제로 안정적으로 작동할 수 있다. 이미 실습을 시작했다면, 더 많은 공학적 세부 사항—파라미터 심층 검증, 여러 도구의 조합, 컨텍스트 관리—에 직면하게 될 것이다. 이는 체계적인 학습 내용이다.
다음 단계에서는 더 복잡한 multi-step tool calling과 다중 에이전트 조정을 탐색하여, 당신이 구축하는 에이전트가 실제 환경에서 신뢰할 수 있도록 할 수 있다.

아직 댓글이 없습니다