Deepseek Function Calling

2025-02-05 11:09 更新

Function Calling 讓模型能夠調(diào)用外部工具,來增強自身能力。

提示?

當前版本 deepseek-chat 模型 Function Calling 功能效果不穩(wěn)定,會出現(xiàn)循環(huán)調(diào)用、空回復的情況。我們正在積極修復中,預計將在下一個版本中得到修復。

樣例代碼?

這里以獲取用戶當前位置的天氣信息為例,展示了使用 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}")

這個例子的執(zhí)行流程如下:

  1. 用戶:詢問現(xiàn)在的天氣
  2. 模型:返回 function get_weather({location: 'Hangzhou'})
  3. 用戶:調(diào)用 function get_weather({location: 'Hangzhou'}),并傳給模型。
  4. 模型:返回自然語言,"The current temperature in Hangzhou is 24°C."

注:上述代碼中 get_weather 函數(shù)功能需由用戶提供,模型本身不執(zhí)行具體函數(shù)。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號