Appearance
DeepSeek Function Call 模型在文本中模仿调用而不实际触发
问题
调用 DeepSeek 的 function calling 接口时,模型没有返回正式的 tool_calls 字段,而是在 content 文本中用 JSON 格式"模仿"了一个函数调用:
json
// finish_reason 是 "stop" 而非 "tool_calls"
{
"content": "{\"name\":\"get_weather\",\"parameters\":{\"location\":\"Hangzhou\"}}<|eot_id|>",
"finish_reason": "stop"
}客户端代码期望 finish_reason: "tool_calls" 和 tool_calls 数组,但两者都没有。
根因
两种常见原因:
- tools 定义格式不正确:缺少必要字段或格式不符合 DeepSeek 要求
tool_choice设置问题:默认auto时模型可能决定不使用工具
解决方案
检查 tools 定义格式(参考官方示例):
python
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息", # description 必须有且清晰
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,如'北京'" # 每个参数都要有 description
}
},
"required": ["location"] # 明确 required 字段
}
}
}
]强制触发工具调用:
python
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": "get_weather"}} # 强制指定工具
)改进 user prompt:明确告知需要使用工具,而不是依赖模型自动判断:
python
# 不好:
{"role": "user", "content": "今天天气怎么样?"}
# 更好:
{"role": "user", "content": "请使用 get_weather 工具查询北京今天的天气"}