從問 AI 到用 Agent · 架構補充

LLM Tool Use 完整拆解:一次帶工具的往返

Agent 之所以能「動手」,底層就是這個往返:你的程式、LLM、工具三方,把訊息傳來傳去,一共四步。這張時序圖把它攤開。

🔁 一次 tool use 的四步往返

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 度,晴時多雲」

每一步實際傳什麼(OpenAI 格式)

1你的程式 → LLM送出 messages + 工具定義
POST /chat/completions
{
  "messages": [{ "role": "user", "content": "台北天氣?" }],
  "tools": [{ "name": "get_weather", "parameters": {…} }]
}
2LLM → 你的程式回傳「要呼叫工具」的意圖
{
  "tool_calls": [{ "id": "call_123",
     "name": "get_weather",
     "arguments": {"location": "Taipei"} }],
  "finish_reason": "tool_calls"
}
3你的程式 執行工具 → 重送把真實結果加回對話
"messages": [
  原始訊息,
  { "role": "assistant", "tool_calls": [...] },   // LLM 的意圖
  { "role": "tool", "tool_call_id": "call_123",
    "content": "{temp:28, condition:晴}" }        // 真實執行結果
]
4LLM → 你的程式產生最終人話
{
  "message": { "content": "台北現在28度晴時多雲" },
  "finish_reason": "stop"
}

OpenAI vs Anthropic:同一件事,兩種格式

環節OpenAIAnthropic
工具定義tools[].function.parameterstools[].input_schema
模型要求呼叫平行的 tool_calls[] 陣列
finish_reason: tool_calls
content 裡含 tool_use 積木
stop_reason: tool_use
結果訊息角色role: "tool"role: "user"(內含 tool_result 積木)
參數格式arguments 為字串化 JSONinput 為物件直接傳

核心差異:OpenAI 用平行的 tool_calls 陣列;Anthropic 把文字、工具呼叫、結果都當成 content 積木,混排在同一訊息裡。

📺 對應單集:讓 Agent 動手:讀檔、查資料、操作系統  |  📚 回課綱總表 →