Chuyển đến nội dung chính

第 4 課:函數呼叫 — 為 Agent 提供“手腳”

OpenAI、Anthropic、Gemini 的函數呼叫/工具使用機制。定義工具架構 (JSON)、處理 tool_calls、平行函數呼叫。建構計算器代理程式和天氣代理。

🧠 人工智慧與機器學習 — 第 3 課 第 4 課:函數呼叫 — 讓代理“手把手” 腳”

建構 AI 代理:從零到生產

第二部分:函數呼叫和工具使用

亞洲開發網

簡介

函數呼叫是將 LLM 從文字產生器轉變為代理的超級能力。 LLM 不僅僅以文字回應,還可以輸出結構化 JSON 來呼叫您定義的函數/工具。本文深入探討了所有 3 個主要提供者的函數呼叫機制。


1. 函數呼叫是如何運作的?

┌──────────┐     ┌──────────┐     ┌──────────┐     ┌──────────┐
│  User    │────►│   LLM    │────►│  Your    │────►│   LLM    │────► Final
│  Prompt  │     │ (Choose  │     │  Code    │     │ (Process │     Response
│          │     │  tools)  │     │ (Execute)│     │  result) │
└──────────┘     └──────────┘     └──────────┘     └──────────┘
                  Output:          Output:
                  tool_calls[]     tool results

關鍵見解

LLM 實際上並沒有呼叫該函數。它只是輸出 JSON 說“我想用參數 Y 呼叫函數 X”。 您的程式碼實際上會呼叫該函數並將結果傳回給 LLM。


2.OpenAI函數調用

2.1 工具的定義

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_products",
            "description": "Tìm kiếm sản phẩm trong database",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Từ khóa tìm kiếm"},
                    "category": {"type": "string", "enum": ["electronics", "clothing", "books"]},
                    "max_price": {"type": "number", "description": "Giá tối đa (VND)"},
                    "sort_by": {"type": "string", "enum": ["price_asc", "price_desc", "rating"]}
                },
                "required": ["query"]
            }
        }
    }
]

2.2 平行函數調用

當同時需要大量資訊時,LLM可以並行呼叫多個工具:

# User: "So sánh thời tiết Hà Nội, Đà Nẵng và Sài Gòn"
# LLM sẽ output 3 tool_calls cùng lúc!
for tool_call in message.tool_calls:
    # tool_call 1: get_weather("Hanoi")
    # tool_call 2: get_weather("Da Nang")
    # tool_call 3: get_weather("Ho Chi Minh City")
    ...

3. 人擇工具的使用

克勞德使用不同的語法但概念相同:

response = anthropic_client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[{
        "name": "search_products",
        "description": "Tìm kiếm sản phẩm",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string"},
                "category": {"type": "string"}
            },
            "required": ["query"]
        }
    }],
    messages=[{"role": "user", "content": "Tìm laptop dưới 20 triệu"}]
)

4.建立工具登錄模式

class ToolRegistry:
    def __init__(self):
        self.tools = {}
        self.schemas = []
    
    def register(self, name, description, parameters):
        def decorator(func):
            self.tools[name] = func
            self.schemas.append({
                "type": "function",
                "function": {
                    "name": name,
                    "description": description,
                    "parameters": parameters
                }
            })
            return func
        return decorator
    
    def execute(self, name, args):
        return self.tools[name](**args)

registry = ToolRegistry()

@registry.register("get_weather", "Lấy thời tiết", {
    "type": "object",
    "properties": {"city": {"type": "string"}},
    "required": ["city"]
})
def get_weather(city):
    return f"Thời tiết {city}: 32°C, nắng"

總結

  • 函數呼叫=LLM輸出JSON→你的程式碼執行→結果回傳LLM
  • 開放人工智慧: tools 參數+ tool_calls 回應。反應
  • 人擇: tools 參數+ tool_use 內容區塊
  • 並行通話有助於座席更快地處理
  • 工具登錄模式有助於乾淨地管理工具

練習

1.實作5個工具:計算機、天氣、web_search、file_read、send_email 2. 建構具有平行函數呼叫的代理 3. 寫出好的工具描述-比較清晰和模糊的描述 4. 實作 tool_choice="required" 與 "auto" 並觀察差異