聊天機械人之後,工作重心移到那層看不見的「代理層」:模型負責推理,工具負責動手,記憶與評估負責讓它不出事。Micheal Lanham 用五層功能架構把這件事拆開,再用三層代理循環把它們串起來。本站按原書十一章整理成可查、可玩、可自我檢查的中文導讀。
本書沒有另找名家推薦序。以下引句全部出自作者前言與〈About this book〉,英文照錄原文,中文為本站歸納;出處以章節/篇名標示。
“Although the hype is still around new model releases, in reality, the bulk of the work and influence is in the hidden agentic layer that now drives how we interact with AI.”
Micheal Lanham · Preface
模型發布仍然佔據新聞頭條,但真正決定系統好不好用的,是包在模型外面那層代理邏輯:它怎樣選工具、怎樣記住上下文、怎樣在出錯前自我檢查。這正是全書的主題。
“I want to introduce AI agents as tools accessible to everyone, tools we shouldn’t fear but instead respect, manage responsibly, and learn to work with in harmony.”
Micheal Lanham · Preface
作者的立場不是「代理會取代人」,而是「代理是需要被治理的工具」。這個立場貫穿第八至十章:部署、評估、監控與 metacognition 都不是附加功能,而是代理能不能上生產線的前提。
“But this time around, explaining the deep internals of how agents work wasn’t necessary, because all frameworks now abstract those details.”
Micheal Lanham · About this book
第二版的寫法假設你不需要自己實作 transformer 或訓練流程:框架已把細節抽象掉。所以書中大量使用 OpenAI Agents SDK、MCP 伺服器與現成工具,重點放在「怎樣組裝」而不是「怎樣造模型」。
“This edition is almost a complete update, so it includes all the new basics that an agentic developer needs to be successful.”
Micheal Lanham · About this book
與第一版相比,第二版把五層功能架構正式化並放在開頭當組織原則,新增 MCP 專章(第三章)與 Docker 分散式編排(第八章),並補上 A2A、評估工具鏈與認知型代理(第十章)。
AI Agents in Action, Second Edition: Intelligent workflows with LLMs, MCP, A2A, and more
本站為中文導讀與原創歸納,不是原書譯本;英文引句逐字照錄,版權屬原作者與出版社。
原書把代理能力拆成五層,並用這五層當全書的組織原則(ch1)。要留意:分層只是紙上的組織方式,不是執行順序——推理會回頭查人格設定,規劃會叫工具,工具結果再餵回推理。
代理之所以是代理,在於它會跑一個自主循環:感知輸入與上下文、規劃、行動(叫工具)、從結果學習並修正。第九章再把這個內環往上疊成三層:內環、任務環、元環。
“An agent’s agency gives it the ability to process information through an autonomous loop called the sense, plan, act, learn process.”
第 1 章 · The rise of AI agents
系統提示就是代理的身份證:角色、專長、語氣、邊界。原書提醒 persona 不只是開場白,它會約束推理選項與輸出方式。三種來源:手寫、由另一個模型代寫、用演化式演算法按表現自動選汰。
“The persona, often referred to as the system prompt, guides an agent in completing tasks, learning how to respond, and understanding other nuances.”
第 1 章 · 1.3.1 The agent persona
工具讓代理走出自己的程式:呼叫 API、查資料庫、讀檔案、開票。原書把工具分成任務完成、情境檢索、知識記憶、評估回饋幾類;其中情境檢索工具只讀不改狀態,跟真正會改變世界的行動要分開設計。
“Context retrieval tools fetch information the agent needs to ground its next decision, such as running a search, querying a vector store, reading a file, or calling a read-only API, without changing any external state.”
第 1 章 · 1.3.2 Agent tools and actions
短流程、少工具、錯誤可逆,用模型原生推理就夠;長流程、工具多、錯誤不可逆(發信、轉帳、改生產資料),才值得加 CoT、ReAct、Reflexion、ToT 這類結構。單路徑快而脆,多路徑穩但貴。
“For more demanding agents, though, we want more control over how the agent reasons, including what it considers, in what order, and with what guardrails.”
第 1 章 · 1.3.3 Agent reasoning and planning
知識是靜態、外部的資料(文件、手冊、schema),記憶是動態、互動得來的經驗(對話、偏好、過去決策)。兩者都用 RAG 在決策時取最相關片段,但儲存與更新節奏不同;真正硬的約束是 context window。
“The model is no longer the only source of knowledge in the system; it is the reasoning layer on top of knowledge retrieved from documents, databases, APIs, or anywhere else the agent can access.”
第 6 章 · Working with memory and knowledge RAG
這是硬化層:LLM-as-judge、grounding 檢查、critic agent、輸入輸出 guardrail。它在代理循環的 learn 階段發揮作用,也是「能不能上生產」的分界線。原書的規矩很直白:沒有評估與回饋迴圈,就不要上線。
“As a golden rule, you should never promote agents into production systems unless you employ evaluation and feedback patterns.”
第 7 章 · Building robust agents with evaluation and feedback
左邊是代理循環(感 → 規 → 行 → 學),右邊是五層功能的剖面。點任何一層,下面會顯示該層的定調、書中要點、對應章節與最常見的失手方式。分層是組織方式,不是執行順序。
點擊任何一層 · 或用下方按鈕切換
第三章的重點之一:工具的 name 與 description 本身就是提示,模型靠它決定何時呼叫、帶什麼參數。下面把你寫的需求即時轉成一份 MCP 風格的工具規格,並列出三個最常被忽略的檢查點。
12 題按書中的設計判斷出題,涵蓋五層架構、MCP、多代理、記憶、評估與部署。每題選最接近你現況的答案,總分會把你分成四型,並給對應章節。
下表由各章導讀自動整理:每章一句定位、一個最關鍵概念、一個最常見錯誤。想深入就按章節導覽。
| 章 | 一句話 | 最關鍵概念 | 最易踩坑 |
|---|---|---|---|
| 1 | 從提示詞調參進到 agent 架構:自主性、五層能力、MCP 工具層與三種多代理型態。 | 自主性光譜:assistant 逐步批准,agent 以目標授權跑 SPAL 迴圈。 | 把接了工具的聊天機器人當成 agent,卻沒有目標授權、迴圈與評估。 |
| 2 | 從 token 機率、prompt 到工具與 trace,把 agent 拆成可調零件。 | LLM 是機率 token 預測器,prompt 與參數是在壓縮它的不確定性。 | 以為 temperature 設 0 就完全穩定,或把幾十個工具塞給同一個 agent。 |
| 3 | MCP 用 JSON-RPC 統一工具整合,讓代理從重造零件變成組裝 | tools 由模型決定,resources 與 prompts 由使用者決定 | 把內部小函式也包成伺服器,換來延遲與多一種失敗模式 |
| 4 | 從單代理到多代理的架構選擇、拆分與防護,重點在結構而非代理數量。 | 決策、控制、通訊三軸決定 pattern;確定性檢查取代代理判斷。 | 一開始就上 orchestrator,或把通過與否交給 LLM 自行判斷。 |
| 5 | 推理要外掛結構,規劃要外顯成可重讀的狀態。 | decomposition 與 planning 是可獨立失敗的兩種操作。 | 把 CoT 當成萬靈丹,或讓計畫只存在模型腦中。 |
| 6 | RAG 用檢索補足凍結的知識,靠混合檢索與 grounding 才站得住。 | retrieval 加 augmentation,把外部知識與記憶拉進 prompt。 | 只上 vector search,也沒有機制驗證 grounding 是否生效。 |
| 7 | 把評估與回饋做進開發迴圈,讓強健性可量測、可重跑。 | TDAD:先寫 benchmark 與錯誤範例,再以最小改動讓 agent 過關。 | 用 strict equality 比對自然語言,把答對的輸出判成失敗。 |
| 8 | 三種消費形態、容器化與 Compose 編排、延遲選路、可觀測性與安全基線,把代理從 demo 推到可維運系統。 | 先定延遲預算,再選 edge、同步 API 或 event-driven worker,線路配 WebRTC、HTTP 加 SSE 或 message bus。 | 把 API key 放前端、用 tunnel 當部署、把政策規則寫死在 prompt 裡,三重疊加等於無防禦。 |
| 9 | 三層迴圈:SPAL 內層、外部化任務層、agent 主導的元層。 | 強型別輸出加分層終止條件,才是會收斂的迴圈。 | 只信 agent 自己說夠了,卻沒設硬上限與成本上限。 |
| 10 | 把推理原語升級為有共享工作空間、動態路由與自我監控的認知架構 | 後設認知:agent 用內部訊號判斷自己是否卡住、是否已超出知識邊界 | 以為把 Reflexion 疊上 ToT 就會變聰明,卻沒有模組決定何時該用哪一個 |
| 11 | 五層架構下的生產級 agent 實戰清單,從 persona 寫到量測。 | 把 agent 拆成五層,各層獨立優化之後再整合。 | 工具與文件全塞進 prompt,既無上限也無量測。 |
← 左右滑動看完整表格 →
每章列出該章主張、4–6 個重點、書中出現的專案或案例、英文原文引句與出處,最後給一個可以馬上做的行動。引句保留英文原文,中文段落為本站歸納。
本章主張 LLM 應用要從被動回應升級為主動執行,分界線是自主性而非有沒有接工具。作者用 sense-plan-act-learn 迴圈拆解代理行為,用 MCP(JSON-RPC 2.0 開放標準)把工具整合從每個 agent 各自重寫變成可共用的伺服器層,再以 persona 到 evaluation 五層架構與三種多代理型態,把 agent 當系統設計。
書中把 LLM 使用拆成 direct chat、tool-augmented、assistant、agent 四型。assistant 每次用工具都要逐次批准,只做單一任務;agent 拿到目標層級授權,自行推理、規劃、選工具並串接多步。這條線是光譜,所以生產系統要階梯式 human-in-the-loop:低風險自動、中風險確認、寄信付款刪資料一律批准。
sense 對輸入與 context,plan 對 LLM 推理,act 對工具執行,learn 對評估與記憶更新,這就是 SPAL 迴圈,血統可追到 OODA 與 BDI。目標要拆到工具層,工具輸出常成下個輸入,即 tool chaining。短流程、錯誤可逆時內建 reasoning 夠用;長流程或不可逆則要外掛 ReAct、Reflexion 或改用外部 planner。
MCP 由 Anthropic 於 2024 年 11 月釋出,建在 JSON-RPC 2.0 上,讓 agent 以語言無關格式連外部服務。做法是跑起 server 並註冊,agent 呼叫 list_tools 取得清單與描述,再自行決定用哪個並依結果修正。它解掉工具存取不一致、格式不可靠、整合碎裂與實作複雜度。代價是安全:server 等於特權執行面,要審來源、釘版本、給最小權限。
agent 能力切成 persona、tools and actions、reasoning and planning、knowledge and memory、evaluation and feedback 五層。核心三層幾乎必備,後兩層按需取捨。重點是這不是固定執行順序:推理回頭查 persona 約束選項,規劃呼叫工具,工具結果回饋推理。把它當能力地圖而非呼叫堆疊,才不會誤讀成 runtime 流程。
knowledge 是靜態外部資料,如文件、手冊、schema,隨來源更新且全體共用;memory 是互動長出的動態經驗,持續更新並綁定使用者。儲存也不同:知識放 vector store 或圖資料庫求召回,記憶放 session store 求時近性。兩者都靠 RAG 在決策時注入 context,而 context window 是硬約束,決定不放什麼和決定檢索什麼一樣重要。
多代理有四理由:分工、平行、分攤 context、本質多角色。三型態由簡到繁:agent flow 像組裝線,靠 threaded 共用對話、blackboard 具名欄位或 chained 逐棒傳遞協調;orchestration 是 hub-and-spoke,中央 agent 把 worker 當工具用;collaboration 讓 agent 同儕互評,能解難題但冗長昂貴。選型原則是夠用最便宜那個,不是最強那個。
“Assistants use tools to perform single tasks with user approval, whereas agents can reason, plan, and execute multiple tasks independently to achieve higher-level goals.”
第 1 章 · The rise of AI agents
“An agent’s agency gives it the ability to process information through an autonomous loop called the sense, plan, act, learn process.”
第 1 章 · The rise of AI agents
“You will learn to build and connect these agents using modern frameworks like the OpenAI Agents SDK and the Model Context Protocol, linking them to databases, APIs, knowledge stores, and complete applications.”
第 1 章 · The rise of AI agents
“The five primary functional layers of an agent are persona, tools and actions, reasoning and planning, knowledge and memory, and evaluation and feedback.”
第 1 章 · The rise of AI agents
“More context is not always better, and the assembly line form is often the right default until you see evidence that agents need to look further upstream.”
第 1 章 · The rise of AI agents
本章主張 agent 不是魔法,而是三層可工程化的堆疊:以機率預測 token 的 LLM、壓縮不確定性的 prompt 結構,以及負責編排與工具呼叫的 OpenAI Agents SDK。作者要求把 token 成本、temperature 與 top-p、Pydantic 型別輸出、trace 觀測、工具上限,全當成設計變數來權衡,而非上線後補救。
模型先把文字切成 token 並轉成詞彙表索引,再對整個詞彙表輸出下一顆 token 的機率分布,最後由 greedy、top-k 或 nucleus 等解碼策略抽樣。關鍵是同一輸入永遠得到同一分布,變化只來自取樣。知識不存在查詢表裡,而是分散在 attention 與 MLP 層的權重中,每次 forward pass 重新計算。RLHF 只讓模型學會聽指令與對話,並不會提升推理能力。
同一份資料寫成 JSON 會比純文字多出許多 token,因為大括號、引號與欄位名都要計價,書中例子是 13 對 6。這是 agent 系統的隱形成本:輸出 token 通常是輸入的兩到五倍單價,一次 run 可能搬動上百萬 token。實務上要用 tiktoken 量測,OpenAI Agents SDK 也會自動回報每次互動的輸入輸出 token 數。輸入越長,輸出的不確定性通常也越高。
temperature 把每顆 token 的機率壓平或拉尖,top-p 只保留累積機率達門檻的候選集,penalty 項抑制重複,max_tokens 則是硬上限。書中建議多數情況只調 temperature 與 max_tokens,並依角色設定:寫程式的 agent 用 0 加低頻率懲罰,創意寫作用高溫加高 presence penalty。temperature 為 0 只降低變異,seed 適合除錯與評測。
書中整理出跨模型通用的手法:指定清楚的 role、把指令放前面並用唯一分隔符包住使用者資料、給出具體字數與受眾、用 few-shot 範例當小型單元測試、要求逐步思考以留下可審核的推理軌跡、多用正向指令、把模糊詞換成數值界線。Listing 2.1 與 2.2 示範如何把含判斷分支的工作流程寫成一段 prompt。反向做法是把靜態內容放前面,吃 prompt caching 折扣。
LLM 本質是隨機的,字串輸出會在下游 agent 之間製造變異,因此要用 output_type 綁定 Pydantic 模型。書中先示範 list[str],再改成 dict[int, str] 而觸發 strict JSON schema 的 UserError,正解是改用 TypedDict 加 extra=forbid,而非關掉 strict_json_schema。型別化還有個好處:prompt 不必再長篇規定輸出格式。
只給 prompt 不給工具,做出來的是 prompt chaining,不是 agent;真正的 agency 來自 agent 自己決定何時呼叫哪個工具。工具可以是本地函式(用 function_tool 裝飾)、經 MCP 暴露的服務,或 handoff 給另一個 agent。但每註冊一個工具,它的 JSON 描述就出現在每一次 LLM 呼叫裡,付費、拉長指令、多一個失敗點。給 agent 刪檔工具,就要預期它真的會刪。
“The key takeaway here is to understand that an LLM works in terms of probabilities of predicting tokens, so we must consider tokens and token prediction when constructing prompts and instructing agents.”
第 2 章 · Core components: LLMs, prompting, and agents
“Prompt engineering is how you make agents predictable and productive, keep costs down, and avoid unexpected behavior.”
第 2 章 · Core components: LLMs, prompting, and agents
“Generation knobs such as temperature, top-p, max_tokens, and penalty terms let you trade off creativity, consistency, and expense for each agent role.”
第 2 章 · Core components: LLMs, prompting, and agents
“It is important to remember that, after you register a tool with an agent, it is included in all calls to the LLM, whether the tool is used or not.”
第 2 章 · Core components: LLMs, prompting, and agents
“Open-source tools like LangSmith, Langfuse, Arize Phoenix, and Weights and Biases Weave provide framework-agnostic tracing that works across OpenAI, Anthropic, local models, and custom agent stacks.”
第 2 章 · Core components: LLMs, prompting, and agents
MCP 是 Anthropic 以 JSON-RPC 2.0 訂的開放標準,把代理接外部服務改為統一介面。本章主張:工具整合碎片化與資料存取客製化,都源於缺少共同協定,MCP 讓開發從造工具變成組裝元件。作者用 STDIO 與 SSE 傳輸與 tools、resources、prompts 三原語,說明代理可包成可重用零件,也提醒自主性會放大錯用工具的代價。
書中把 MCP 要解的問題列成四項:工具整合碎片化,每家供應商的 schema 與呼叫格式都不同;資料存取不一致,檔案、資料庫、Web API 各要一套客製接法;多代理協作沒有標準,每個串接都要手寫;安全、權限與監控難以橫向統一。MCP 的做法是把這些差異收斂到 JSON-RPC 2.0 的伺服器後面,代理端只註冊一個 server。為何重要:跨供應商的橫向變更不必在每份實作重做一次,維護成本從乘法回到加法。
tools 是模型自行決定何時呼叫的動作,resources 是可讀取的資料與物件,prompts 是伺服器提供的樣板。真正的分野是誰決定何時使用:工具由代理主動伸手,資源與樣板由使用者或應用程式挑選後遞給代理,Claude Desktop 與 Cursor 都用此模式。OpenAI Agents SDK 目前只支援 tools,作者接受此限制,但提醒若框架支援三者,應按原意使用,不要把 resource 硬包成 tool。
STDIO 由客戶端把伺服器當子程序啟動,走 stdin 與 stdout,沒有網路堆疊,延遲低、製程管理簡單,但嚴格一對一,只有父程序能通話。SSE 讓伺服器成為 HTTP 服務,客戶端把請求 POST 到 messages 端點,伺服器以事件流回推,可多客戶端、可穿防火牆與負載平衡。切換通常只是換建構子與連線參數。單一伺服器只有一種傳輸,所謂混合部署其實是同一個代理同時接多個本地與遠端伺服器。
Claude Desktop 這類助理收一個請求、做一次、停下來,且預設要人按下允許;代理則跑迴圈,呼叫工具、觀察結果、決定下一步,中途不回問使用者。作者強調權限提示屬於安全模式,不是架構分界,Claude Code 與 Cursor 也會問權限卻仍是代理。自主性同時提高工具設計與選擇的門檻:助理選錯一次只得一個錯答案,代理可能把同一個錯遞延成十步之後才被發現。
因為自主,書中要求工具允許清單、沙箱、輸出驗證、速率與預算上限,以及高風險動作的人工檢查點。特別點名工具輸出造成的 prompt injection 是槓桿最大的攻擊面:代理讀進來的網頁、文件、郵件都進入上下文,可能被當成指令執行,該視為預設狀況而非邊緣案例。同時提醒 MCP 只消除 schema 與呼叫格式的工作,認證、錯誤處理、版本管理與伺服器可用性仍要自己負責。
時間旅行日誌代理原本把 record_event 與 load_journal 放在同一模組,工具與代理共享記憶體狀態。改寫後工具搬進 FastMCP 伺服器,代理只看得到名稱、描述、參數 schema 與回傳型別,看不到也碰不到實作,日誌可換成 Postgres 或遠端 API 而代理程式不動。代價是每次呼叫多一層延遲與一種新的失敗模式,所以書中建議只在工具真的外部、跨團隊或要跨代理共享時才用 MCP,內部邏輯優先走程序內函式。
“Every MCP server provides functionality through three types of components, each serving a specific purpose in agent workflows: tools, resources, and prompts.”
第 3 章 · Actions with Model Context Protocol
“Without MCP, your agent faces a similar challenge: each tool or service you want to connect to requires its own custom integration.”
第 3 章 · Actions with Model Context Protocol
“An agent runs a loop in which it can call tools, observe results, decide what to do next, and continue working toward a goal across many steps without returning to the user between steps.”
第 3 章 · Actions with Model Context Protocol
“MCP provides an inspector tool that lets you explore any server, whether remote, local, developed, or downloaded.”
第 3 章 · Actions with Model Context Protocol
“That separation is what makes tools composable across agents, replaceable across deployments, and shareable across teams.”
第 3 章 · Actions with Model Context Protocol
多代理並非越多越好。章節主張盤點決策權、控制權與通訊三軸,再選架構形狀:把過載的單一代理拆成角色明確的 agent flow,用結構化輸出與程式碼決策點換取可重現性;只有需要集中規劃與動態分工時才升級到 orchestrator。handoff 省下協調程式碼,卻讓接收端暴露於格式錯誤、上下文外洩與注入,邊界須補 guardrail 與 trace。
架構設計先問三件事。決策是承諾下一步行動的權限,關鍵在於哪個代理持有它、當下能看到多少上下文;控制是實際執行工具與產生輸出的權限,可與決策分離,規劃者不必然動手。通訊則是哪些上下文在代理之間流動。三軸的組合決定架構手感:開放通訊換來協作彈性卻造成 context bloat,封閉通訊讓代理專注卻可能重複勞動。先想清楚三軸怎麼走,選 pattern 才算刻意而非預設。
書中把 pattern 收斂成三種。flow 像組裝線,決策、控制、通訊逐站傳遞,最好除錯也最易評估,但不會部分執行,任一節點失敗整條就斷。orchestrator 是 hub-and-spoke,決策集中、控制按需下放,適合複雜判斷與直接面對使用者,代價是難建置與評估。collaboration 讓所有代理共用中央通道、決策與控制互相流轉,適合目標模糊且結果多元的題目,但 token 與延遲最高。原則是由簡入繁,先 flow。
拆分的觸發點是可觀察的失效。overload 指工具過多或 prompt 過長導致選錯工具,常見症狀是工具描述重疊,例如 search_documents 與 search_files,解法是讓描述足以區辨。其次是 specialization 與成本延遲:每個工具的 JSON schema 都隨每次呼叫送出,三十個工具可能加上六千到一萬二千 token。作法先想清楚專業化,再綁定角色與工具,每個代理只掛自己的 MCP server。
LLM 本質上不確定,把通過與否交給代理,等於讓硬規則被繞過。書中把分支外移到程式碼:研究代理以 pydantic 的 ResearchSourcesModel 作 output_type,SDK 層強制回應形狀,程式可直接檢查清單長度是否大於零,零就中止,否則才啟動規劃代理。多個輸入包成帶標籤的 dict,轉字串後成為結構化 JSON,比整段對話歷史更省 token。
handoff 把轉交寫進代理關係,不必手寫協調碼,只需在 instructions 指明對象、設定 handoffs 並提高 max_turns;代價是依賴藏在 prompt,難檢視。conversation thread 共用上下文,代價是每個代理都背噪音;pass-off 由呼叫端掌握輸入輸出,控制最細而程式碼最複雜;增強式 handoff 在主線程過濾通訊並保留上下文。搭配 draw_graph 與 Traces 先看圖再查。
guardrail 不是事後過濾,而是語意斷路器,在具風險的動作落地前就中止。成本要誠實面對:用 LLM 把關,每一步都多一次模型呼叫。因此先跑便宜的確定性檢查,如 schema、assert、長度門檻,再用小型分類器模型攔 PII、毒性與 prompt injection,最後才用 LLM guardrail 處理真正需要語意理解的判斷。handoff 常見三種失效:形狀不符、上下文外洩、指令注入,後者風險最高。
“Agent-to-agent flows work like prompt chaining with superpowers: each node can invoke tools and reason independently, yet pass concise, typed outputs downstream to keep the context lean.”
第 4 章 · Architecting and building multi-agent systems
“Overload—The agent has too many tools, too long a prompt, or both, and starts failing to execute tasks correctly.”
第 4 章 · Architecting and building multi-agent systems
“Handoffs are tricky because the receiving agent has no native protection against malformed input, leaked context, or hostile instructions arriving from upstream.”
第 4 章 · Architecting and building multi-agent systems
“A production-ready agentic flow blends typed I/O, deterministic checkpoints, visual traces, scoped tool sets, and guardrails, yielding pipelines that can scale, recover, and evolve without surprise.”
第 4 章 · Architecting and building multi-agent systems
“Your experience will often dictate which pattern to use for a particular use case, and a reasonable starting point is to build flows before moving to orchestration, collaboration, or other coordination strategies.”
第 4 章 · Architecting and building multi-agent systems
本章主張:LLM 預設不會思考,只是單次前向傳遞的 token 預測器,agent 必須外掛推理與規劃結構。作者把 reasoning 拆成 decomposition 與 planning 兩種可獨立失敗的操作,再依瓶頸選用 CoT、ReAct、ToT、Reflexion,並用 sequential thinking MCP server 當外部記事本。
decomposition 把任務切成子問題,planning 決定子問題的順序、依賴、工具與接法。兩者常被混為一談,但失敗樣態不同:拆得對卻排錯順序,或順序對卻拆錯邊界,症狀與修法都不一樣。作者主張先診斷是哪一種操作壞掉,再決定要改提示、改工具集,還是改外部的計畫表示。
非推理模型只有單次前向傳遞,容易短路成聽起來合理的淺答;CoT 提示要求模型輸出中間步驟,能改善多步表現,卻沒有賦予新能力,對強模型的幫助大於對弱模型的救援。推理模型(OpenAI o 系列、Claude extended thinking、Gemini reasoning mode)把思考階段變成可計算的預算,換來更穩的多步推理,代價是 token 與延遲。
ReAct 交錯 thought、action、observation,每次工具結果都回饋到下一輪推理。關鍵不是有沒有 tool call,而是有沒有一個閉環:單次 CoT 中間插一次工具呼叫,仍然只是單次。這個迴圈由 agent framework 執行,不在模型內部,因此能從錯誤動作復原、中途改計畫,也是多數生產級 agent 與 multi-agent 系統的結構基礎。
LLM 跨呼叫沒有持續狀態,也沒有內在世界模型,所以計畫不能只存在模型裡。planning 模式把計畫寫到 memory、scratchpad 或對話 context,讓 agent 每一步重讀,內容涵蓋子任務、依賴、中間結果與進度。這些欄位必須顯式定義,否則長流程會漂移。書中用舊金山三日行程示範:出現美術館休館、新創不開放等新資訊,就整份計畫重寫。
ToT 對候選推理路徑做搜尋:展開分支、評估、剪枝,必要時回溯,適合需要前瞻的規劃、解謎與遊戲;它無法只用單一提示完成,剪枝與回溯要靠 LangGraph 之類的外部編排程式。Reflexion 則是 solver 與 critic 的自我批評迴圈,一次只走一條路,用批評加深 context,成本較低;但所謂的學習只是輸入更豐富,權重並沒有更新。
Anthropic 的 sequential thinking MCP server 只暴露一個工具,參數含 thought、thought_number、total_thoughts、branch_from_thought,讓 agent 把思考步驟寫出去、標記修訂與分支。它本身不推理,價值在跨步驟的連續性與可檢視性,配合提示就能在上面跑 ReAct 或 ToT。書中提醒工具清單要精簡,多餘工具會放大迴圈成本。
“Planning patterns produce an explicit plan—stored outside the model in memory, a scratchpad, or the conversation context—that the agent reads on each step to coordinate work toward the overall objective.”
第 5 章 · Agent reasoning and planning
“The LLM itself has no persistent state across calls and no inner world model, so the global view is a property of the architecture, not the model.”
第 5 章 · Agent reasoning and planning
“The agent interleaves reasoning steps, tool actions, and observations of the results, allowing it to incorporate new information into subsequent reasoning.”
第 5 章 · Agent reasoning and planning
“The improvement across attempts comes from the model conditioning on a richer context, not from any actual learning, since no model weights are updated.”
第 5 章 · Agent reasoning and planning
“Chain-of-thought (CoT) prompting turns a model’s hidden intuition into explicit, step-by-step thoughts that are easy to debug, at the cost of extra tokens and latency.”
第 5 章 · Agent reasoning and planning
LLM 知識凍結在訓練時點,新文件與跨 session 偏好都答不了。RAG 以 ingestion 與 retrieval 把知識、記憶拉進 context window;但純 vector search 漏掉精確詞與即時資料,須以 keyword、SQL、graph 與 RRF 補強,再用 grounding 釘回原文。
Retrieval 從 LLM 之外的長期儲存取回知識或記憶,augmentation 把片段塞進 prompt,兩者合起來就是 RAG。儲存可無限成長,真正受限的是單次能放進 context window 的量,現代模型約二十萬到百萬 token。所以 agent 不必記住全部,只需每次帶進最相關片段。Knowledge 偏文件與結構化資料,memory 偏對話與經驗,但共用同一套 embed、index、search 原語。
TF-IDF 產生稀疏向量,權重來自詞頻與逆文件頻率,只看字面,所以 vehicles 查不到 cars;但查人名、錯誤碼這類精確詞反而比 embedding 準。稠密向量由神經網路訓練,維度約 384 到 3072,語意相近者在空間中靠近。Cosine similarity 忽略長度只看方向,是兩種向量的共同度量;書中用 PCA 把 1536 維降到 3 維,讓人看見語意分群。
語意相似不等於語意正確,檢索只看得見相似度,看不見真偽;固定回傳 top-K 通常五到十筆,排名第十一的正解直接被丟掉;近似最近鄰演算法為速度犧牲精度。書中補上實務症狀:查錯誤碼 P0420 只回泛泛的排氣頁、Freon 對不上 refrigerant、十二份重複產品表擠掉其他文件、昨天更新的價格不在 embedding 裡,以及索引沒套 ACL 會洩漏機密 HR 備註。
實務幾乎一定並用多種檢索:vector 與 keyword 同時跑,各回一份排名,但 BM25 與 cosine 分數尺度不同,不能直接相加。Reciprocal Rank Fusion 只看名次,把兩份清單的 1/(k+rank) 相加,k 通常取 60,兩邊都排前面的文件因此勝出,且跨後端穩健。用 agent 時也可把兩種檢索各包成工具,讓它自己決定何時用哪一個。
沒有明確指示,模型會用自身參數補答案,這是 RAG 最常見的失敗。有效做法是寫死規則:只能依 context 回答,沒有就直說;要求每個論點引用來源;或先列出相關段落再作答。Grounding 有強弱之分,客服、法律、醫療需要可追溯的強 grounding,內部研究可接受弱的。它還牽涉 chunk 切法與評估框架,必須搭配抽查與幻覺率量測,否則等於沒做。
Memory 借用認知詞彙只是為了分類,實作仍是 context window、外部儲存、狀態管理與檢索四件事。Graph 記憶以節點表示實體、邊表示關係,多跳問題因此變快;代價是模糊比對弱、實體抽取不穩,Doc 與 Doc Brown 可能被當成兩人,故要與 semantic memory 組成 hybrid。記憶多了要壓縮:k-means 分群後摘要成單一記憶,或直接遺忘過時項目;受監管行業遺忘同時是法遵問題。
“The combined retrieval and augmentation mechanism, called retrieval-augmented generation (RAG), has become a standard for providing relevant context for a prompt.”
第 6 章 · Working with memory and knowledge RAG
“The agent can, in principle, access arbitrarily large memory stores because the storage lives outside the LLM, in a database, vector store, or filesystem that grows independently of any model’s context window.”
第 6 章 · Working with memory and knowledge RAG
“Vector similarity search is the semantic workhorse, but by itself, it misses exact matches, jargon, numbers, and fresh updates.”
第 6 章 · Working with memory and knowledge RAG
“Reciprocal-rank fusion or agent-directed tool chaining merges the two result sets into a single, ranked context.”
第 6 章 · Working with memory and knowledge RAG
“When developing RAG systems and agents, you almost always insist that the model ground its answers in the retrieved content.”
第 6 章 · Working with memory and knowledge RAG
強健性必須可量測才能改善:本章把 evaluation 與 feedback 接進 Learn 步驟,以 benchmark、紅隊、人類回饋與 critic 分層覆蓋。方法是 TDAD:先寫 benchmark 與錯誤範例,預期失敗,再以最小改動過關。作者警告 agent collusion 與 strict equality 會製造假信心,並用 Phoenix trace 沉澱評估資料。
deterministic 測試適合可精確比對的結構化輸出,例如 schema 是否正確、有沒有呼叫對的工具;LLM 或 agent evaluator 處理 rubric 評分、分類、兩份輸出互相比較這類程度問題;人類評估補上邊界案例、政策與語氣。三者不是替代關係,而是按輸出類型分工,選錯方法就量測不到重點。
test-driven agent development 把需求寫成 benchmark 再寫 agent:每條 benchmark 附預期答案與已知錯誤答案,讓評估器有對照。測試要跑三次以上,因為 LLM 有隨機性,單次通過可能只是抽樣運氣。書中第一版 RAG agent 五題全錯,這是預期結果,先確立基準線才判斷得出後續改動是否有效。
最小修改的順序是:改一個詞、加一個子句、加一句話、加一節、改或加工具、換模型或參數。從小往大試,能在不膨脹 prompt 的前提下解決問題;每次加一段、從不刪減的團隊最後會得到多頁互相矛盾的 system prompt。工具用得不對時優先修名稱與 docstring,只有 MCP 托管、改不動描述時才回 prompt 補指示。
strict equality 對自然語言輸出幾乎一定過嚴:大小寫、標點、多餘修飾詞都會讓正確答案被判錯。書中第二輪有兩題其實答對,卻因 Photons 與 photons 的差異被記為失敗,把比對改成小寫之後才回到滿分。要修的是評估器不是 agent。這類 bug 最危險,它會讓團隊誤判 agent 能力,或反過來給出假信心。
grounding agent 拿同一份 retrieved context 檢查答案是否有依據,是 RAG 的必要護欄;grounding 本身是通用技術,也可用於 tool call 驗證與 memory 核對。在 OpenAI Agents SDK 裡用 output_guardrail 包住 grounding agent,未 grounded 就觸發 tripwire,再由 try except 決定重試或回固定答案。重試上限要明確設計,否則迴圈會變成隱性的壞輸出來源。
Arize Phoenix 以 OpenTelemetry 接收 trace,可自架或用 Docker 執行,看到每個 agent 與 LLM 呼叫的 latency、token 成本與原始輸出。加上 using_session 與 using_metadata 後能依 run_id 或 env 篩選;把 span 存成 dataset 就能跑 experiment 與 evaluator,annotation 則把人工判斷變成可查詢標籤,日後當回歸測試集。
“As a golden rule, you should never promote agents into production systems unless you employ evaluation and feedback patterns.”
第 7 章 · Building robust agents with evaluation
“From the failure, identify the minimum updates to the agent’s prompt and tools that will let the benchmark pass.”
第 7 章 · Building robust agents with evaluation
“As mentioned earlier, our preference should always be to correct the tool-use description if an agent is struggling to use a tool.”
第 7 章 · Building robust agents with evaluation
“Grounding itself is a general technique for verifying that model output ties back to a verifiable source, and it applies beyond RAG to tool-call validation, memory verification, and citation auditing.”
第 7 章 · Building robust agents with evaluation
“If you are a serious agent engineer, it is highly recommended that you include Phoenix in your set of tracing, evaluation, and development tools.”
第 7 章 · Building robust agents with evaluation
代理系統要落地,部署形態同 prompt、工具一樣決定成敗。本章把消費方式收斂成三種:嵌進瀏覽器的 edge 模式、用 FastAPI 包成同步 API 的微服務、掛在佇列後的非同步 worker。落地路徑是先寫 Dockerfile 把單一代理容器化,再用 Docker Compose 把語音前端與圖像代理編排成 stack,再談 front-door 模式與 WebRTC、HTTP+SSE、message bus 三條線路的分工。治理上把代理當軟件:版本化 prompt 與模型、用 Phoenix 做 OpenTelemetry 追蹤、設 timeout 與斷路器、以 idempotency key 快取工具呼叫,最後靠威脅模型、最小權限、工具沙箱與 schema-first 合約擋 prompt injection。
書中把消費方式分三種:代理與應用同一個 codebase、代理跑在後端服務只經自家 API 對外、或把代理封成容器微服務再以 API、MCP、A2A 供其他代理當工具用。嵌入瀏覽器最簡單、延遲最低,但有三個易被忽略的坑:前端程式碼裡的 API key 用開發者工具就抄得走;CORS 預設擋住瀏覽器直連多數 LLM 與工具端點;同一個 key 被多個瀏覽器共用時,一個用戶就可以燒光所有人的配額。作者的結論很直接:原型與內部工具可以嵌,任何面向客戶、涉及成本或安全的場景,代理都應該退到後端,由瀏覽器經自家認證 API 呼叫。
微服務的重點是把關注點切開,令每個代理可以獨立升級、替換、加減。做法是先請 LLM 依 02_app.py 產生 Dockerfile,用 python:3.11-slim 做基底、複製 requirements.txt 安裝依賴、EXPOSE 8000 並以 uvicorn 起服務,再 docker build 成 image-generator,docker run 時才用 -e 注入 OPENAI_API_KEY。單一容器跑通之後改用 Docker Compose,一個 YAML 就聲明 web、image_agent、web_agent 三個容器與 ports、environment、depends_on,docker compose up --build 一次起齊整組 stack。作者提醒 Compose 檔難以直接搬去雲端,而且容器只該放一個代理,多代理流程要用 flow 或 orchestration 組合。
部署位置由延遲目標反推,因為用戶體驗通常先寫死了延遲預算。直接對話的客服代理要即時,適合 edge;自主研究代理跑幾分鐘到幾小時,適合 worker 加佇列。三種主要形態是 edge、同步 API 微服務、event-driven worker。作者給的預設路線是:拿不定主意就先做 API,把熱路徑搬去 edge,把重工具丟去非同步 worker。線路同樣按延遲揀:WebRTC 或 WebSocket 做全雙工語音與 barge-in,HTTP 加 SSE 做可代理、可日誌、可快取的串流工具呼叫,message bus 則用 Redis、NATS、Kafka 解耦慢工具。前端用 front-door 代理模式,把複雜度推去有型別的 worker。
大型多輪系統最常在狀態這一層出事。對話記憶放 Redis 或 PostgreSQL 這類快儲存,長期事實與知識放向量索引,並做成多個代理共用的獨立服務。工具設計要冪等:同一組輸入呼叫一次或多次結果相同,天氣查詢是,寄信不是。書中示範用工具名加參數做 canonical JSON 再雜湊成 key,命中就回快取,令重試、重播與除錯都安全。發佈方面把代理當軟件:版本化 prompt、工具 schema、模型選擇,用離線測試、影子流量、小規模 canary 逐級放量並可自動回滾,同時釘住每輪實際用過的模型與工具端點,否則事故無法重現。
看不到就修不了。OpenAI Agents SDK 支援 OpenTelemetry,書中再疊 Phoenix,把 UI、Gateway、Agent、Tools、Model 全鏈路都 trace。要追三類東西:trace span 帶 session_id、turn_id、tool_call_id 以便在 Phoenix 過濾;metrics 分營運面的 p50 與 p95 延遲、工具成功率、每意圖 token 用量、每 session 成本,品質面的 grounding rate、幻覺率、評估器通過率,產品面的任務完成率與轉人手率;日誌用結構化 JSON 並遮蔽 PII。可靠性靠時間預算與 fallback:快回 1.5 秒、工具 15 至 60 秒,超時就降級,工具連續失敗就跳斷路器,任何情況都不要把錯誤丟給用戶。
代理能自主行動,所以安全要當一等公民。先列資產,再逐個暴露面做對映:client、gateway、agent runtime、tool server、model provider、storage,每個面各自危及哪些 key、資料、日誌。最高槓桿的攻擊是 prompt injection,分直接與間接兩種,間接更難防,因為惡意內容可以藏在搜尋結果、文件、郵件甚至圖片裡。防禦是分層而非完備:指令階層把系統提示放最高位、把工具輸出當不可信資料而非指令、用 schema-first 的嚴格 JSON 參數並拒絕多餘欄位、高風險動作加人手檢查點。政策則要放在代理外面,寫進 prompt 既脆弱又無法審計。
“By the end of the chapter, you should be able to choose an appropriate deployment strategy for your agent, containerize it, orchestrate multiple agents, and understand the basics of securing and operating them in production.”
第 8 章 · Deploying agents and agentic systems
“Microservices and containers cleanly separate concerns; agents make ideal microservices because they’re self-contained and easy to scale, swap, and version.”
第 8 章 · Deploying agents and agentic systems
“If in doubt, start with API, move hot paths to edge (browser), and offload heavy tools to event-driven worker agents.”
第 8 章 · Deploying agents and agentic systems
“Observability is non-negotiable: trace from UI > Gateway > Agent > Tools > Model; track latency, cost, and success metrics; prefer structured logs with PII redaction.”
第 8 章 · Deploying agents and agentic systems
“Threat-model surfaces, enforce least privilege, manage secrets correctly, sandbox tools, and defend against prompt injection with schema-first tool contracts and instruction hierarchies.”
第 8 章 · Deploying agents and agentic systems
本章把 agentic loop 分三層:內層 SPAL 由 agent 決定工具與停手時機;第二層把 goal、plan、state 外部化到程式碼;第三層改由 agent 掌權,長成 orchestration 或 collaboration。能否收斂,取決於狀態如何跨輪傳遞、終止條件是否分層、工具是否經 MCP server 接入,並要求強型別輸出。
第一層 SPAL 是內層,agent 依 goal 感測狀態、規劃、用工具執行、評估結果,直到達標或觸發終止;工具選擇與停手時機都由 agent 決定,開發者只給目標與邊界。第二層把 goal、plan、state 搬到 agent 之外,用程式碼包住迴圈,換取更長視野與跨迭代狀態;第三層再把這些交回 agent。目標越長,越需把短期記憶外置,否則 context window 與 LLM 長跑能力都跟不上。
deep research 是第二層典型實作。書中用 Pydantic 建 state 與 plan 物件,存 findings、待查問題、迭代次數與上限,以屬性判斷是否續跑,並用子題清單追蹤進度。關鍵是 to_context:把累積狀態序列化成字串餵給 LLM,開發者因此能控制每輪看到什麼。書中只傳最近五筆 findings,用 pop(0) 取題形成廣度優先,改從尾端取就變深度優先,等於 tree-of-thought 搜尋。
每輪產出必須可解析,不能是自由文字。書中定義迭代輸出模型,欄位包含發現摘要、來源、待查問題、達標旗標、信心值與計劃更新。控制器靠這些欄位決定流程:問題清單空了或標記達標就觸發終止。少了強型別,就得用正則猜自由文字,脆弱又易錯。用 OpenAI Agents SDK 只需給 output_type,SDK 會把格式寫進 instructions,改類別不必回頭改提示詞。
終止閘門是每輪結尾的決策點,書中要求疊五層:最大迭代次數當安全網、token 或成本上限當煞車、達標宣告當理想出口、品質門檻由評估者把關、最後是停滯偵測。停滯比失敗難抓:失敗會拋錯或回空,停滯卻產出與兩輪前幾乎相同的合理內容;做法是把相鄰兩輪摘要轉成向量算 cosine similarity,連續兩輪超過約 85% 就收手。沒有硬上限的迴圈,是等著發生的線上事故。
第三層由 agent 而非程式碼控制,因此分兩型。orchestration 由單一 orchestrator 以 handoff 把 worker 當工具,保留全域計劃與狀態,動作只有 delegate、re_plan、finalize,能在中途重新拆解目標。collaboration 是對等協作,研究者、評論者、彙整者共用一份狀態,輪替貢獻,靠同意達標比例過門檻才停。代價是每次決策多一次 LLM 呼叫,拆解已知時硬寫的第二層更便宜。
迴圈跑完只有一堆發現快照,可能重疊、矛盾或留白。書中另開 synthesis agent,吃全部發現與計劃,輸出結構化報告,含摘要、關鍵發現、來源、信心評估與缺口限制;它只跑一次,所以能塞進完整發現,並依最終狀態對提早終止加註保留。作者提醒別讓研究 agent 最後一輪順手寫報告:一旦為報告結構優化,探索品質就下滑。單次分類或格式轉換加迴圈,只多付延遲。
“But two more agentic loop layers can extend the work of the agent: layer 2, the task loop, and layer 3, the meta loop.”
第 9 章 · Understanding the agentic loop
“What makes this loop agentic, rather than just a while loop in code, is that the agent itself makes decisions at each step.”
第 9 章 · Understanding the agentic loop
“Control what the agent sees at each cycle to manage context window usage by truncating, summarizing, or compressing earlier findings as the loop progresses.”
第 9 章 · Understanding the agentic loop
“Without it, you are left parsing free-text responses to determine loop control flow, which is fragile and error prone.”
第 9 章 · Understanding the agentic loop
“Recall from section 9.1 that the meta loop places an agent, rather than code, in control of the decide, state, and plan elements.”
第 9 章 · Understanding the agentic loop
章節主張:CoT、ReAct、ToT、Reflexion 只是認知原語,疊起來只會更複雜,不會更聰明。缺的是決定何時用哪個、監控是否有效、失效時改道的架構。作者借 Minsky 心智社會、Baars 全域工作空間與 Kahneman 雙系統,做出 CognitiveWorkspace 加五個專職模組與 MCP 知識圖譜記憶,讓後設認知成為防自信答錯的結構。
書中列出五種能推理卻不會思考的預設行為:自信答錯、跳針重試、僵化計劃、過度承諾的猜測、淺層組合。每一個都對應明確缺口:證據評估、停滯感知、模型更新、知識邊界偵測、組合推理。關鍵論點是修法屬於結構元件,不是再寫一段 prompt 或多掛一個 skill。先拿十條多樣查詢跑自己的 agent,對照日誌找出症狀,就能判斷缺哪個模組。
認知是 agent 對任務內部模型的品質,書中拆成四項可量測能力:任務分解、依賴推理、組合式工具使用、模型更新。後設認知則是想自己的思考:信心校準、停滯偵測、知識邊界感知。作者強調 LLM 口頭說不確定幾乎沒有資訊量,真正有用的是 token 機率、檢索分數與證據一致性這些隱性訊號,因此監控必須寫進架構,不能靠模型自述。
Minsky 的心智社會主張智慧來自多個專門模組的互動,對應拆成五個專職 agent 而非單一全能 agent。Baars 的全域工作空間提供共享狀態,讓任何模組寫入的訊號被所有模組看見。Kahneman 的系統一與系統二給出深度路由:簡單查詢走快速路徑,複雜、矛盾、模糊的查詢才進完整認知循環。三個理論各自落地成一個可寫程式的元件,而不只是比喻。
CognitiveWorkspace 用 Pydantic 模型承載六類狀態:任務表徵、候選假設、中間結果、信心狀態、執行歷史、注意力訊號。它不同於對話歷史或 scratchpad,因為它同時記錄自己有多確定、證據是否互相矛盾、當前策略有沒有進展。其中 active_signal 最關鍵:evaluation 寫入 CONTRADICTION,attention 就改道去 replan,這就是廣播機制。
attention 是唯一純程式碼控制的模組,用 route_attention 讀工作空間訊號決定下一個模組,讓它成為架構而非固定管線。STAGNATION 會把失敗策略寫入 failed_approaches 再轉 META_PLAN,CONTRADICTION 會把策略改成 HYPOTHESIS_TEST,信心低於 0.2 直接 ESCALATE。書中提醒這些門檻值是靜態的認知設定,先固定住,等架構跑順再談動態調整。
memory 模組包住 MCP memory server,用 entities、relations、observations 三種原語存經驗:問題類型是 entity,有效策略是 observation,結構關聯是 relation。它有三個行為:規劃前主動檢索、評估後記錄成敗、發現共同策略時建關聯。作者明說知識圖譜換不掉向量庫,因為結構關係比表面相似更有用;要語意搜尋可換 mcp-mem0,架構不動。
“Every practitioner who has shipped an agent into production has seen at least three of these five failure modes: a confident wrong answer, a broken record, a rigid plan, an overcommitted guess, and a shallow composition.”
第 10 章 · The cognitive agent that thinks and adapts
“Each one maps to a specific cognitive or metacognitive deficit that we will address with architecture rather than prompting, skills, or reasoning.”
第 10 章 · The cognitive agent that thinks and adapts
“We draw on Minsky’s society of mind, Baars’ global workspace theory, and Kahneman’s system 1/system 2 framework to build a cognitive agent architecture.”
第 10 章 · The cognitive agent that thinks and adapts
“In this architecture, specialized modules share a common workspace, an attention mechanism routes control dynamically, and emergent behaviors such as curiosity, adaptive persistence, and self-aware uncertainty arise from the interaction of simple parts.”
第 10 章 · The cognitive agent that thinks and adapts
“Metacognitive monitoring, specifically confidence-gated execution, stagnation detection, and knowledge boundary awareness, is the most valuable production capability because it prevents confidently wrong answers.”
第 10 章 · The cognitive agent that thinks and adapts
本章主張按 persona、工具、reasoning、知識、評估五層分別優化再整合。手法是把 persona 當 API 合約、工具單一職責以免 tool bloat、用 ReAct 配計劃與迭代上限、把 RAG 當第一級能力並以 metadata 分區,靠 tracing 與 evals 量測。
把 persona 當成對下游選擇的契約而非散文。角色與邊界要寫清楚,關鍵規則在指令開頭與結尾各放一次,抵抗 recency 與漂移,並留明確的不知道出口。範圍要窄,單一職責的 agent 比萬能 bot 好測也好省成本。跨 agent 時用 Pydantic 約束的 JSON 輸出,減少解析錯誤與 token 膨脹。動態指令只注入必要事實,過量會讓 agent 混亂。
模型靠名稱、docstring 與型別 schema 學會用工具,描述要精準,並用 function tool 生成 schema。以 tool_choice 與 parallel tool calls 控制何時跑,一次呼叫夠用就提早停。能用 hosted tool 或檢驗過的 MCP server 就別重造。要為失敗設計 timeout、retry 與友善 fallback。每個工具都在每次呼叫加上描述成本,即 tool bloat。
多步任務需要計劃、迴圈與停止條件。非簡單任務採 ReAct,在思考與行動間交替,觀察後再決定下一步;大目標用 plan-then-execute,先列三到五項清單,必要時借助 sequential thinking 這類 MCP server 把想法外顯。迭代要設上限,達到就回報 needs_followup 並給盡力而為的結果。輸出前加一道自我複核。單次任務反而該把 reasoning 關掉。
知識與記憶都從檢索開始。別把文件塞進 prompt,而是給 agent 一個檢索工具,背後是向量庫加 metadata 過濾。短期上下文用 session thread,長期事實寫進向量庫並選擇性檢索。規模化要用 ANN 索引如 HNSW 或 IVF、依領域分 shard、用 metadata 過濾,並混用語意、關鍵字與圖層次檢索。切塊要語意連貫,回答只引用檢索內容,資料依 role 與 tenant 分區。
沒有量測就沒有改進。把 prompt、工具呼叫、token 數、延遲與結果全 trace 起來並接上 observability 堆疊;SDK 內建 tracing 不足,生產環境建議改用 Phoenix。每次改 prompt 或換模型都跑策展測試集與 LLM-as-judge。人類回饋要留通道,HITL 是最真實的訊號。輸入輸出與高風險工具前後都要有 guardrail 與 schema 驗證,並照 AIOps 迭代。
“Treat agent design as five stacked layers: persona, tools and actions, reasoning and planning, knowledge and memory, and evaluation and feedback.”
第 11 章 · Tips for building agentic systems
“Production-ready agentic systems emerge from tight personas, well-scoped tools, guided reasoning, disciplined retrieval, and relentless measurement.”
第 11 章 · Tips for building agentic systems
“As a rule, always keep tool sets small, and when using MCP servers, be conscious of how many tools the server exposes.”
第 11 章 · Tips for building agentic systems
“Although most foundational consumer models use reasoning today, it is often best to understand and control how that reasoning is used.”
第 11 章 · Tips for building agentic systems
“As you can see, what we describe as one agent is actually multiple agents, six in this case, performing various roles and working together.”
第 11 章 · Tips for building agentic systems