DeepSeek 如何用 tools 调用应用里的函数?
查看完整题解
参考回答
直接回答
请求中声明允许的工具名与参数结构。模型可能返回 tool_calls。应用先验证工具与参数,再调用自己控制的函数,把结果连同原有 tool_call_id 放回下一轮。
讲清原理
工具只能做应用已经允许的事。权限和副作用由应用判断。带思考模式的请求,要按当前文档保留所需的 reasoning_content,并把工具结果放在正确顺序。
例子与易错点
下面用模拟模型响应请求读一份预置库存,应用按可用商品 ID 验证参数,再回填同一个调用 ID。
import json
# Simulated model output. The application owns the read-only data and rules.
call = {"id": "call_1", "function": {"name": "check_stock",
"arguments": '{"sku":"A1"}'}}
inventory = {"A1": 7}
arguments = json.loads(call["function"]["arguments"])
assert call["function"]["name"] == "check_stock"
assert set(arguments) == {"sku"} and type(arguments["sku"]) is str
result = inventory.get(arguments["sku"])
message = {"role": "tool", "tool_call_id": call["id"],
"content": json.dumps({"stock": result})}
assert message["tool_call_id"] == "call_1" and json.loads(message["content"]) == {"stock": 7}
print("validated stock read and associated its result with call_1")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。