DeepSeek API
快速开始
首次调用 API
模型 & 价格
Temperature 设置
Token 用量计算
限速
错误码
API文档
基本信息
对话补全
POST
FIM 补全(Beta)
POST
列出模型
GET
查询余额
GET
API指南
推理模型 (deepseek-reasoner)
多轮对话
对话前缀续写(Beta)
FIM 补全(Beta)
JSON Output
Function Calling
上下文硬盘缓存
提示库
代码改写
代码解释
代码生成
内容分类
结构化输出
角色扮演(自定义人设)
角色扮演(情景续写)
散文写作
诗歌创作
文案大纲生成
宣传标语生成
模型提示词生成
中英翻译专家
常见问题
Function Calling
创建时间: 2025-05-29 17:11
Function Calling 让模型能够调用外部工具,来增强自身能力。
样例代码
这里以获取用户当前位置的天气信息为例,展示了使用 Function Calling 的完整 Python 代码。
Function Calling 的具体 API 格式请参考对话补全文档。
from openai import OpenAI
def send_messages(messages):
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools
)
return response.choices[0].message
client = OpenAI(
api_key="<your api key>",
base_url="https://api.deepseek.com",
)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather of an location, the user shoud supply a location first",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"]
},
}
},
]
messages = [{"role": "user", "content": "How's the weather in Hangzhou?"}]
message = send_messages(messages)
print(f"User>\t {messages[0]['content']}")
tool = message.tool_calls[0]
messages.append(message)
messages.append({"role": "tool", "tool_call_id": tool.id, "content": "24℃"})
message = send_messages(messages)
print(f"Model>\t {message.content}")
这个例子的执行流程如下:
- 用户:询问现在的天气
- 模型:返回 function
get_weather({location: 'Hangzhou'})
- 用户:调用 function
get_weather({location: 'Hangzhou'})
,并传给模型。 - 模型:返回自然语言,"The current temperature in Hangzhou is 24°C."
注:上述代码中 get_weather
函数功能需由用户提供,模型本身不执行具体函数。
最后更新: -