hugs 文件
函式呼叫
加入 Hugging Face 社群
並獲得增強的文件體驗
開始使用
函式呼叫
函式呼叫是一項強大的功能,它使大型語言模型 (LLM) 能夠以結構化的方式與你的程式碼和外部系統進行互動。LLM 不僅僅是生成文字響應,還可以理解何時呼叫特定函式並提供必要的引數來執行現實世界的操作。
函式呼叫如何工作
該過程遵循以下步驟
這個週期可以根據需要繼續進行,從而允許應用程式和 LLM 之間進行復雜的多步互動。
示例用例
函式呼叫在許多實際應用中非常有用,例如
- 資料檢索:將自然語言查詢轉換為 API 呼叫以獲取資料 (例如,“顯示我最近的訂單”會觸發資料庫查詢)
- 執行操作:將使用者請求轉換為特定的函式呼叫 (例如,“安排會議”會變成日曆 API 呼叫)
- 計算任務:透過專用函式處理數學或邏輯運算 (例如,計算複利或進行統計分析)
- 資料處理管道:將多個函式呼叫連結在一起 (例如,獲取資料 → 解析 → 轉換 → 儲存)
- UI/UX 整合:根據使用者互動觸發介面更新 (例如,更新地圖示記或顯示圖表)
使用工具 (函式定義)
工具是為你的 LLM 定義可呼叫函式的主要方式。每個工具都需要
- 一個唯一的名稱
- 一個清晰的描述
- 一個定義預期引數的 JSON schema
下面是一個定義天氣相關函式的示例
from huggingface_hub import InferenceClient
client = InferenceClient("https://:8080") # Replace with your HUGS host
messages = [
{
"role": "system",
"content": "Don't make assumptions about values. Ask for clarification if needed.",
},
{
"role": "user",
"content": "What's the weather like the next 3 days in San Francisco, CA?",
},
]
tools = [
{
"type": "function",
"function": {
"name": "get_n_day_weather_forecast",
"description": "Get an N-day weather forecast",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The temperature unit to use",
},
"num_days": {
"type": "integer",
"description": "The number of days to forecast",
},
},
"required": ["location", "format", "num_days"],
},
},
}
]
response = client.chat_completion(
messages=messages,
tools=tools,
tool_choice="auto",
max_tokens=500,
)
print(response.choices[0].message.tool_calls[0].function)
# ChatCompletionOutputFunctionDefinition(arguments={'format': 'celsius', 'location': 'San Francisco, CA', 'num_days': 3}, name='get_n_day_weather_forecast', description=None)
模型將分析使用者的請求並生成對相應函式的結構化呼叫,同時提供正確的引數。
使用 Pydantic 模型實現結構化輸出
為了獲得更好的型別安全性和驗證,你可以使用 Pydantic 模型來定義你的函式 schema。這種方法提供了
- 執行時型別檢查
- 自動驗證
- 更好的 IDE 支援
- 透過 Python 型別提供清晰的文件
以下是如何使用 Pydantic 模型進行函式呼叫
from pydantic import BaseModel, Field
from typing import List
class ParkObservation(BaseModel):
location: str = Field(..., description="Where the observation took place")
activity: str = Field(..., description="What activity was being done")
animals_seen: int = Field(..., description="Number of animals spotted", ge=1, le=5)
animals: List[str] = Field(..., description="List of animals observed")
client = InferenceClient("https://:8080") # Replace with your HUGS host
response_format = {"type": "json", "value": ParkObservation.model_json_schema()}
messages = [
{
"role": "user",
"content": "I saw a puppy, a cat and a raccoon during my bike ride in the park.",
},
]
response = client.chat_completion(
messages=messages,
response_format=response_format,
max_tokens=500,
)
print(response.choices[0].message.content)
# { "activity": "bike ride",
# "animals": ["puppy", "cat", "raccoon"],
# "animals_seen": 3,
# "location": "the park"
# }
這將返回一個與你的 schema 相匹配的 JSON 物件,使其在你的應用程式中易於解析和使用。
高階用法模式
鏈式函式呼叫
LLM 可以協調多個函式呼叫以完成複雜任務
tools = [
{
"type": "function",
"function": {
"name": "search_products",
"description": "Search product catalog",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"category": {"type": "string", "enum": ["electronics", "clothing", "books"]}
}
}
}
},
{
"type": "function",
"function": {
"name": "create_order",
"description": "Create a new order",
"parameters": {
"type": "object",
"properties": {
"product_id": {"type": "string"},
"quantity": {"type": "integer", "minimum": 1}
}
}
}
}
]
錯誤處理和執行
在執行前務必驗證函式呼叫
import json
def get_n_day_weather_forecast(location, format, num_days):
return '{"temperature": 70, "condition": "sunny"}'
def handle_tool_call(tool_call):
try:
args = tool_call.function.arguments
# Validate required parameters
if tool_call.function.name == "get_n_day_weather_forecast":
if not all(k in args for k in ["location", "format", "num_days"]):
raise ValueError("Missing required parameters")
# Only pass arguments that match the function's parameters
valid_args = {k: v for k, v in args.items()
if k in get_n_day_weather_forecast.__code__.co_varnames}
return get_n_day_weather_forecast(**valid_args)
except json.JSONDecodeError:
return {"error": "Invalid function arguments"}
except Exception as e:
return {"error": str(e)}
res = handle_tool_call(response.choices[0].message.tool_calls[0])
print(res)
# {"temperature": 70, "condition": "sunny"}
最佳實踐
函式設計
- 保持函式名稱清晰具體
- 為函式和引數使用詳細的描述
- 包含引數約束 (最小值/最大值、列舉等)
錯誤處理
- 驗證所有函式輸入
- 為失敗的函式呼叫實現適當的錯誤處理
- 考慮為暫時性故障設定重試邏輯
安全
- 在執行前驗證並清理所有輸入
- 實施速率限制和訪問控制
- 根據使用者上下文考慮函式呼叫許可權
切勿直接透過函式呼叫暴露敏感操作。務必實施適當的驗證和授權檢查。
有關基本推理功能的更多資訊,請參閱我們的推理指南。
< > 在 GitHub 上更新