Agent 之所以能「動手」,底層就是這個往返:你的程式、LLM、工具三方,把訊息傳來傳去,一共四步。這張時序圖把它攤開。
sequenceDiagram actor U as 使用者 participant App as 你的程式 (App) participant LLM as LLM participant Tool as 工具 get_weather U->>App: 「台北天氣?」 App->>LLM: ① messages + tools 定義 LLM-->>App: ② tool_calls:呼叫 get_weather
finish_reason = tool_calls App->>Tool: ③ 執行 get_weather(Taipei) Tool-->>App: {temp:28, 晴} App->>LLM: ④ 把 tool result 加回 messages 重送 LLM-->>App: ⑤ 最終人話回應
finish_reason = stop App-->>U: 「台北現在 28 度,晴時多雲」
POST /chat/completions
{
"messages": [{ "role": "user", "content": "台北天氣?" }],
"tools": [{ "name": "get_weather", "parameters": {…} }]
}{
"tool_calls": [{ "id": "call_123",
"name": "get_weather",
"arguments": {"location": "Taipei"} }],
"finish_reason": "tool_calls"
}"messages": [
原始訊息,
{ "role": "assistant", "tool_calls": [...] }, // LLM 的意圖
{ "role": "tool", "tool_call_id": "call_123",
"content": "{temp:28, condition:晴}" } // 真實執行結果
]{
"message": { "content": "台北現在28度晴時多雲" },
"finish_reason": "stop"
}| 環節 | OpenAI | Anthropic |
|---|---|---|
| 工具定義 | tools[].function.parameters | tools[].input_schema |
| 模型要求呼叫 | 平行的 tool_calls[] 陣列finish_reason: tool_calls | content 裡含 tool_use 積木stop_reason: tool_use |
| 結果訊息角色 | role: "tool" | role: "user"(內含 tool_result 積木) |
| 參數格式 | arguments 為字串化 JSON | input 為物件直接傳 |
核心差異:OpenAI 用平行的 tool_calls 陣列;Anthropic 把文字、工具呼叫、結果都當成 content 積木,混排在同一訊息裡。
📺 對應單集:讓 Agent 動手:讀檔、查資料、操作系統 | 📚 回課綱總表 →