1. 使用场景
Function Calling(函数调用)允许模型根据用户需求调用外部工具或 API,核心价值包括:- 扩展数值计算能力:解决模型原生计算不精准的问题。
- 获取实时外部信息:通过调用搜索、天气、数据库等接口获取即时数据。
- 环境交互与控制:自动化操控智能设备、发送邮件或执行代码。
2. 使用方式
2.1 通过 REST API 添加 tools 参数
在发送请求时,通过tools 字段定义可用的函数列表:
Copy
{
"model": "DeepSeek-V3.2",
"messages": [
{ "role": "user", "content": "帮我计算 123.45 乘以 67.89" }
],
"tools": [
{
"type": "function",
"function": {
"name": "calculate_mul",
"description": "计算两个数字的乘积",
"parameters": {
"type": "object",
"properties": {
"a": { "type": "number", "description": "乘数 a" },
"b": { "type": "number", "description": "乘数 b" }
},
"required": ["a", "b"]
}
}
}
]
}
2.2 通过 OpenAI 库请求
推荐使用 OpenAI SDK 进行集成,调用方式如下:Copy
response = client.chat.completions.create(
model="DeepSeek-V3.2",
messages=messages,
tools=[
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "获取指定股票代码的实时价格",
"parameters": {
"type": "object",
"properties": {
"symbol": { "type": "string" }
},
"required": ["symbol"]
}
}
}
]
)
3. 支持模型列表
您可以访问 模型广场,查看模型是否支持工具调用。4. 使用示例 (Python)
以下展示一个完整的闭环调用示例:Copy
from openai import OpenAI
import json
client = OpenAI(
api_key="Your-api_key",
base_url="https://api.nonelinear.com/v1"
)
# 1. 定义工具函数
def calculate_add(a, b):
return a + b
tools = [
{
"type": "function",
"function": {
"name": "calculate_add",
"description": "计算两个数字之和",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["a", "b"]
}
}
}
]
# 2. 发起首次请求
messages = [{"role": "user", "content": "123.45 加上 67.89 等于多少?"}]
response = client.chat.completions.create(
model="DeepSeek-V3.2-Think",
messages=messages,
tools=tools
)
# 3. 处理工具调用
tool_call = response.choices[0].message.tool_calls[0]
if tool_call:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
# 执行本地函数
function_response = calculate_add(**function_args)
# 将结果反馈给模型
messages.append(response.choices[0].message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": str(function_response)
})
# 再次请求获取自然语言回答
final_response = client.chat.completions.create(
model="DeepSeek-V3.2-Think",
messages=messages
)
print(final_response.choices[0].message.content)
相关链接