codecamp

Deepseek Function Calling

Function Calling 让模型能够调用外部工具,来增强自身能力。

提示

当前版本 deepseek-chat 模型 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}")

这个例子的执行流程如下:

  1. 用户:询问现在的天气
  2. 模型:返回 function get_weather({location: 'Hangzhou'})
  3. 用户:调用 function get_weather({location: 'Hangzhou'}),并传给模型。
  4. 模型:返回自然语言,"The current temperature in Hangzhou is 24°C."

注:上述代码中 get_weather 函数功能需由用户提供,模型本身不执行具体函数。


Deepseek JSON Output
Deepseek 上下文硬盘缓存
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }