透過將大型語言模型 (LLM) 與外部工具及 API 結合,我們能大幅擴展其能力,使其不僅限於文本生成,更能執行實際操作,例如查詢資料庫、發送電郵、或控制智能家居裝置。DeepSeek 提供的 Function Calling 功能,正是實現此目標的關鍵技術。本文將深入探討 DeepSeek Function Calling 的核心概念、工具調用的實踐方法,以及如何利用 JSON 模式確保輸出結構化,助您建構更具互動性和自動化的應用。
DeepSeek Function Calling 是一種強大的機制,允許開發者定義一系列外部工具(或稱函數),並將其描述提供給 DeepSeek 模型。當模型收到用戶查詢,判斷需要利用外部工具才能給出最佳回應時,它會自動生成調用這些工具所需的參數。開發者隨後接收到模型生成的工具調用請求,執行相應的工具函數,最後將工具的執行結果回傳給模型,讓模型生成最終的自然語言回應。
這項功能的核心優勢包括:
要使用 DeepSeek 的 API 服務,您需要準備 DeepSeek API Key 並設定您的開發環境。
取得 API Key:
安裝 DeepSeek Python SDK:
pip 命令安裝 DeepSeek 官方的 Python SDK:pip install deepseek
初始化 DeepSeek 客戶端:
Deepseek 客戶端。建議將 API Key 儲存在環境變數中,以提高安全性。import os
from deepseek import Deepseek
# 建議從環境變數中讀取 API Key
# export DEEPSEEK_API_KEY='YOUR_API_KEY_HERE'
client = Deepseek(api_key=os.environ.get("DEEPSEEK_API_KEY"))
if not client.api_key:
print("錯誤:請設定 DEEPSEEK_API_KEY 環境變數。")
exit()
工具調用是 Function Calling 的核心。它涉及定義工具、讓模型決定是否調用,以及執行工具並將結果回傳給模型。
在向 DeepSeek 模型發送請求時,您需要透過 tools 參數提供您希望模型能夠調用的工具清單。每個工具都應該包含其名稱、描述及參數模式 (schema)。
範例:定義一個天氣查詢工具
假設我們要建立一個能夠查詢城市天氣的工具。我們需要告訴模型這個工具叫做 get_current_weather,它接受 location(城市名稱)和 unit(溫度單位,可選)作為參數。
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "獲取指定地點的當前天氣資訊。使用此工具查詢實時天氣數據。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名稱,例如:香港、倫敦、紐約。",
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "溫度單位,攝氏度或華氏度,預設為攝氏度。",
},
},
"required": ["location"],
},
},
}
]
上圖展示了 DeepSeek 與外部 API 服務整合的典型流程,從用戶請求到工具調用、結果回傳的數據流向。
以下是實現完整工具調用流程的步驟:
步驟 1:向模型發送帶有工具定義的請求
當用戶提出「香港現在天氣如何?」這類問題時,我們會將用戶訊息連同定義好的工具一併發送給 DeepSeek 模型。
messages = [
{"role": "user", "content": "香港現在天氣如何?"},
]
response = client.chat.completions.create(
model="deepseek-chat", # 或 deepseek-coder 等支持 function calling 的模型
messages=messages,
tools=tools,
tool_choice="auto", # 允許模型自動決定是否調用工具
)
步驟 2:處理模型的工具調用請求
模型收到請求後,會分析用戶意圖。如果它判斷需要 get_current_weather 工具,其回應會包含 tool_calls 字段。
response_message = response.choices[0].message
if response_message.tool_calls:
tool_call = response_message.tool_calls[0]
function_name = tool_call.function.name
function_args = tool_call.function.arguments
print(f"模型建議調用工具:{function_name},參數:{function_args}")
# 將模型的訊息加入對話歷史
messages.append(response_message)
步驟 3:在應用程式中執行工具函數
您的應用程式需要根據模型建議的 function_name 和 function_args 來執行實際的工具函數。
# 模擬實際的天氣查詢函數
def get_current_weather(location: str, unit: str = "celsius") -> dict:
# 這裡會是真實的 API 調用,例如:
# import requests
# api_key = "YOUR_WEATHER_API_KEY"
# url = f"https://api.weatherapi.com/v1/current.json?key={api_key}&q={location}"
# response = requests.get(url).json()
# temperature = response['current']['temp_c'] if unit == 'celsius' else response['current']['temp_f']
# return {"location": location, "temperature": temperature, "unit": unit, "description": "晴朗"}
# 為了演示,我們返回硬編碼數據
if location == "香港":
return {"location": "香港", "temperature": 28, "unit": unit, "description": "部分多雲"}
elif location == "倫敦":
return {"location": "倫敦", "temperature": 15, "unit": unit, "description": "多雲"}
else:
return {"location": location, "temperature": "未知", "unit": unit, "description": "資料不足"}
# 解析參數並調用函數
available_functions = {
"get_current_weather": get_current_weather,
}
if function_name in available_functions:
# 注意:function_args 是 JSON 字符串,需要解析
import json
parsed_args = json.loads(function_args)
function_response = available_functions[function_name](**parsed_args)
print(f"工具函數執行結果:{function_response}")
步驟 4:將工具執行結果回傳給模型
將工具函數的執行結果,作為一個新的 tool 角色訊息,連同之前的對話歷史,再次發送給模型。
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": json.dumps(function_response),
}
)
final_response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
)
print(f"最終回應:{final_response.choices[0].message.content}")
else:
print(f"錯誤:未知的工具名稱 {function_name}")
除了工具調用,DeepSeek 還提供了 JSON 模式,確保模型回應的格式為有效的 JSON 對象。這對於需要從模型獲取結構化數據(例如資料庫查詢參數、數據分析結果或特定格式的內容)的應用程式非常有用。
透過在 API 請求中設定 response_format={"type": "json_object"},您可以強制 DeepSeek 模型生成符合 JSON 規範的回應。模型將盡力將其生成的所有內容(包括訊息文本)格式化為一個 JSON 物件。
範例:從一段文本中提取產品資訊
假設您需要從用戶的評論中提取產品名稱和評價星級。
messages_json = [
{"role": "user", "content": "提取這段評論中的產品名稱和星級:這款 DeepSeek AI 模型真的太棒了,性能卓越,我給它打五顆星!"}
]
response_json = client.chat.completions.create(
model="deepseek-chat",
messages=messages_json,
response_format={"type": "json_object"}
)
# 獲取模型的回應內容
json_output_content = response_json.choices[0].message.content
print(f"原始 JSON 輸出字符串:\n{json_output_content}")
# 解析 JSON 字符串
import json
try:
parsed_data = json.loads(json_output_content)
print("\n解析後的 JSON 數據:")
print(json.dumps(parsed_data, indent=2, ensure_ascii=False))
except json.JSONDecodeError as e:
print(f"\nJSON 解析錯誤:{e}")
模型可能會生成類似以下的 JSON 輸出:
{
"product_name": "DeepSeek AI 模型",
"rating": 5,
"comment": "性能卓越,太棒了"
}
上圖展示了 DeepSeek 模型在 JSON 模式下輸出的數據結構,清晰地將信息格式化為可編程處理的 JSON 對象。
即使在 JSON 模式下,清晰的提示詞 (prompt) 依然重要。您可以透過在 user 訊息中明確指示所需的 JSON 結構,進一步引導模型生成更精確的輸出。
messages_guided_json = [
{"role": "user", "content": """
請根據以下文章,提取產品的「名稱」、「價格」及「主要特點」。
文章:
隆重推出 DeepSeek Pro 智能助理,原價港幣 1,299 元,現特價僅售港幣 999 元!它具備超長續航力、語音識別及智能排程功能,是您日常工作的好幫手。
請將結果以 JSON 格式輸出,鍵名分別為 `product_name`, `price_hkd`, `features` (列表)。
"""}
]
response_guided_json = client.chat.completions.create(
model="deepseek-chat",
messages=messages_guided_json,
response_format={"type": "json_object"}
)
print(json.dumps(json.loads(response_guided_json.choices[0].message.content), indent=2, ensure_ascii=False))
預期輸出:
{
"product_name": "DeepSeek Pro 智能助理",
"price_hkd": 999,
"features": [
"超長續航力",
"語音識別",
"智能排程功能"
]
}
DeepSeek 的 Function Calling 和 JSON 模式為開發者開啟了建構更智能、更具互動性的 AI 應用的大門。透過掌握工具調用,您可以將 DeepSeek 模型與無限的外部服務連接起來,使其能夠執行複雜的任務和工作流程。而 JSON 模式則確保了數據輸出的結構化和可預測性,極大地簡化了後續的數據處理和整合。
希望這篇入門教程能幫助您理解並開始在您的項目中應用 DeepSeek 的這些強大功能。隨著您對這些功能的深入探索,您將能夠創造出更多富有創意和實用價值的應用程式。