1. 白皮書
第一天的白皮書介紹了 AI agents 基礎(chǔ)知識,還進一步介紹了 agents 的能力分類體系、agents 落地運維規(guī)范、多 agents 協(xié)作與安全性等內(nèi)容
1.1. AI Agents 簡介
AI Agent 定義:Model(模型) TOOLS(工具) Orchestration-Layer(編排) Runtime -Services (運行服務) 四個要素的結(jié)合。
- Model(大腦): 處理信息、評估選項、做出抉擇
- Tools(雙手): API拓展、調(diào)用代碼函數(shù)、與外部知識(數(shù)據(jù)庫)連接
- Orchestration Layer(神經(jīng)系統(tǒng)): 任務規(guī)劃(React)、管理記憶、決策調(diào)度(think-action-observe)
- Deployment(軀干): 托管部署、監(jiān)控、日志記錄等
Agent 開發(fā)者像一個導演,不需要編寫每一行代碼,而是搭建場景(instructions and prompts),配置演員(tools and APIs),提供私域信息(data)。主要目的是引導大模型呈現(xiàn)出預期的表現(xiàn)。
LLM 最大的特點就是靈活,導致她很難可靠且完美的完成某一特定任務。從 prompt engineering 到 context engineering,我們的目的是引導 LLM 生成期望的輸出。
每次調(diào)用她,我們會輸入:指令、事實依據(jù)、Tools、示例、會話歷史、私域數(shù)據(jù)等等,在上下文窗口中填入恰到好處的信息,然后獲得我們需要的輸出(模型唯一的作用:輸入->輸出)。而 Agent 則是通過管理我們的輸入來進行工作。
Agent 善后:追蹤(Traces)和日志(Logs)監(jiān)控Agent的思考過程和執(zhí)行鏈路,定位到與預期執(zhí)行鏈路不符的偏差點。開發(fā)者的職責是提供關(guān)鍵組件:專業(yè)領(lǐng)域知識、明確的角色設定、工具的無縫集成。在初始prompt設計完善的基礎(chǔ)上,還要多場景邊緣性測試然后持續(xù)全面評估并優(yōu)化。
本質(zhì)上:Agent 是一個專注于管理上下文窗口的系統(tǒng)。它始終處于持續(xù)不斷的循環(huán)過程中:整合上下文、給模型提供prompt、觀察模型結(jié)果,然后為下一步重新整合上下文。這里的上下文可能包括:指令、用戶輸入、會話歷史、長期記憶、來自權(quán)威來源的基礎(chǔ)信息、可使用的工具,以及已調(diào)用工具返回的結(jié)果等。這種對模型的精細化管理,能讓模型更有效的工作。
Agent 工作流程
Agent 通過一個持續(xù)的循環(huán)過程來實現(xiàn)其目標:
- 獲取任務:用戶提出一個需求
- 掃描場景:Agent 收集現(xiàn)有能解決用于需求的知識(memory history tools database等)
- 深入思考:根據(jù)1和2進行循環(huán)推理制定執(zhí)行計劃
- 采取行動:模型決策后開始調(diào)用Tools操作
- 觀察并迭代:觀察Tools返回結(jié)果,循環(huán)tool->observe->think->tool.......
這種" think、act、observe"的循環(huán)會持續(xù)進行——由編排層管理,由模型進行推理,由工具執(zhí)行,直到智能體的內(nèi)部計劃完成且初始任務達成。

1.2. Agentic 系統(tǒng)分類法
理解前面提到的 Agent 5步工作流程后,我們需要了解到這個循環(huán)的復雜性是可變的。對于架構(gòu)師來說,我們要根據(jù)我們需求的難易和復雜度決定構(gòu)建何種復雜程度的Agent。
Agentic system 從簡單到復雜可以分為以下五個級別:

1.2.1. LLM
大模型僅基于訓練數(shù)據(jù)回答問題,無任何Tools、實時數(shù)據(jù)知識和記憶等等
1.2.2. LLM + Tools
大模型可以決策調(diào)用Tools去進行檢索實時數(shù)據(jù)、調(diào)用API等等豐富自己的知識和執(zhí)行能力(與外部世界交互)
1.2.3. LLM + Tools + Context-Engineering
通過高質(zhì)量的上下文管控LLM有限的注意力,戰(zhàn)略性規(guī)劃復雜、多模塊任務
1.2.4. (LLM + Tools + Context-Engineering) x n
在上一步的基礎(chǔ)上,構(gòu)造多個agents進行協(xié)作分工,主agent管理多個subagents
1.2.5. Self Evolving
Agent 能夠識別自身能力的不足,并動態(tài)創(chuàng)建 Tools 甚至 Subagent 來彌補這些不足, 賦予 Agent 主動拓張自己能力的能力,自我進化。
1.3. Agent 核心架構(gòu):模型、工具與編排
落地三個組件從概念到代碼的實現(xiàn),具體架構(gòu)如何設計
1.3.1. Model:Agent的大腦
LLM 是推理核心,選擇要素:
- 卓越的推理能力
- 應對復雜多步驟任務
- 可靠的工具調(diào)用能力
- 成本...
具體落地方案:
- 針對你的業(yè)務用各個模型進行測試,做出在質(zhì)量、速度和價格上的最佳選擇。
- 可以在 Agent 內(nèi)根據(jù)不同需求的難易程度選擇不同的模型,組件多模型團隊。
- 模型會不段進化,Agent系統(tǒng)要具備持續(xù)集成新模型的能力。
1.3.2. Tools
Tools 使 Agent 能夠超越其靜態(tài)的訓練數(shù)據(jù),獲取實時信息并在現(xiàn)實世界中采取行動。一個強大的 Tool 接口包含三個環(huán)節(jié):定義功能、調(diào)用以及觀察結(jié)果。幾種主要的工具類型如下:
1.3.2.1. 檢索信息
google-search、RAG、查詢向量數(shù)據(jù)庫、查詢私域數(shù)據(jù)文檔、自然語言轉(zhuǎn)SQL查詢結(jié)構(gòu)化數(shù)據(jù)庫等等
1.3.2.2. 執(zhí)行操作
行動類工具:發(fā)郵件、執(zhí)行Python腳本、Human-in-the-Loop、操作瀏覽器等
1.3.2.3. 函數(shù)調(diào)用
可靠的進行函數(shù)調(diào)用,依賴MCP等規(guī)范
1.3.3. The Orchestration Layer
編排層是連接 LLM 和 Tools 的神經(jīng)網(wǎng)絡,運行Think, Act,Observe"循環(huán)的引擎,控制 Agent 行為的狀態(tài)機(可以參考 LangGraph 框架)
1.3.3.1. 核心設計
- Agent 自主程度:(自由)React -> Workflow(限制)
- 實現(xiàn)方式:(快速簡單)無代碼 -> 代碼優(yōu)先(復雜控制)
- 框架選擇:多模型支持、具備可觀測性
1.3.3.2. 借助領(lǐng)域知識和角色定位
開發(fā)者最有力的干預模型手段是向 Agent 傳授領(lǐng)域知識并賦予其獨特的角色設定,通過 System Prompt 或一組核心指令來實現(xiàn),作為 Agent 的行為準則。
例:你是xxx、你有哪些限制、期望輸出的格式、語氣、何時為何使用tools等等,并提供幾個場景示例。
1.3.3.3. 用上下文增強
- 短期記憶:當前會話的循環(huán)歷史記錄,Human、AI、Tools 的 Message
- 長期記憶:夸會話持久性存儲,會話記錄落盤和恢復
1.3.3.4. 多智能體協(xié)作
任務復雜性提高,單一超級 Agent 效率低下,需要組建 Agents 專家團隊各司其職。

迭代優(yōu)化模式會創(chuàng)建一個反饋循環(huán),使用“生成循環(huán)”智能體創(chuàng)建內(nèi)容,并使用“質(zhì)量評估”智能體根據(jù)……進行評估,然后使用“Prompt 增強”執(zhí)行體增強。
對于更線性的 Workflow,序列模式更合適,它就像一條數(shù)字裝配線,一個 Agent 的輸出直接成為下一個 Agent 的輸入。
對于高風險任務,Human-in-the-Loop (HITL) 模式至關(guān)重要,它會在Workflow中設置一個刻意的停頓,以便在 Agent 采取重大行動前獲得 Human 的批準。
1.3.4. 部署與服務化
Agent 只是一種新的軟件形式,很多軟件部署原則仍然適用(docker CI/CD等),額外需要注意的是會話歷史記錄、長期記憶記錄和客觀性性等內(nèi)容。
Google 的 Agent 專用部署運行平臺 Vertex AI Agent Engine:

1.3.5. Agents 運維:應對不可預測性
從傳統(tǒng)確定性軟件到隨機的 Agentic 系統(tǒng)轉(zhuǎn)變,需要一種新的理念。由于語言的復雜性,通常我們需要用 LLM 來評估 Agent 的工作質(zhì)量:完成了所有應該做的、沒做不該做的、回復語氣得當?shù)鹊取?br>
生成式人工智能(GenAI)的發(fā)展主要有兩個領(lǐng)域:模型開發(fā)和應用開發(fā),運維方式繼承關(guān)系如下:

1.3.5.1. A/B 測試來衡量指標
明確當前業(yè)務背景下,模型工作產(chǎn)出的具體指標(KPI),構(gòu)建KPI的可觀測策略,量化測試模型的工作效果。
1.3.5.2. 讓 LLM 評判
某些業(yè)務無法設定標準答案,通過讓領(lǐng)域?qū)<?精通此業(yè)務人員)提供預定義的標準,來叫 LLM 評判 Agent 的工作產(chǎn)出
1.3.5.3. 新版本能不能上?
- 一旦你自動化了數(shù)十個評估場景并建立了可信賴的質(zhì)量評分體系,你就可以放心的開始迭代升級的 Agent 了。新版本在整個評估數(shù)據(jù)集上運行測試,將分數(shù)與現(xiàn)版本進行對比(自動化評估)。
- 還要額外考慮的因素:延遲、成本和任務的成功率等。
- 采用A/B部署方式,收集生產(chǎn)指標結(jié)合模型評分體系一起決定新版本能不能上?
1.3.5.4. 追蹤調(diào)試你的 Agent
可以使用類似 OpenTelemetry 這種客觀性追蹤調(diào)用鏈路和日志的工具去查看你 Agent 的異常問題。觀察發(fā)送給模型的Prompt、模型內(nèi)部推理過程、選擇的Tool和參數(shù)以及Tool返回結(jié)果等。
1.3.5.5. 用戶反饋的重要性
獲取用戶反饋并形成一個新的評估數(shù)據(jù)集用于測試你的 Agent,可以讓系統(tǒng)對用戶反饋的問題具有免疫性。
1.3.6. Agent 交互
高質(zhì)量的 Agent 需要與其他 Agents 和用戶連接起來,你需要思考如何將你的 Agent 融入到更廣泛的生態(tài)系統(tǒng)之中。
1.3.6.1. Agents & 人
- 通過用戶界面提供給用戶,比如聊天機器人:用戶輸入,Agent 接收處理并返回一段文本給到用戶。
- 控制你的電腦,比如操作瀏覽器:打開小紅書,輸入XXX,進行搜索。
- 渲染你的UI,根據(jù)你的問題需求熱生成UI界面進行展示交互
- 訪問你的攝像頭麥克風直接獲取的你感官世界獲取的信息進行回應。
1.3.6.2. Agents & Agents
不同團隊的不同專業(yè) Agents 連接起來需要通用標準:
- 發(fā)現(xiàn): 我的 Agent 如何找到其他的 Agents 并了解他們的功能?
- 通信: 如何確保他們使用相同的語言交互?
Agent2Agent(A2A)協(xié)議 :為解決該問題而設計的開放式標準,它相當于智能體生態(tài)中的 “通用握手協(xié)議”:
- 通過 A2A 協(xié)議,任何智能體都能發(fā)布一份名為 “智能體名片(Agent Card)” 的數(shù)字化文件。這份簡潔的 JSON 格式文件會公示智能體的核心能力、網(wǎng)絡端點(用于通信連接的地址),以及與該智能體交互所需的安全憑證。這種設計讓 “智能體發(fā)現(xiàn)” 過程變得簡單且標準化。
- A2A 協(xié)議與 MCP 的定位不同:MCP 側(cè)重處理事務性請求(如訂單查詢、數(shù)據(jù)調(diào)取等單一明確的任務指令),而 A2A 通信則通常用于輔助完成更復雜的問題解決流程(如多智能體協(xié)作拆解項目、聯(lián)合分析跨領(lǐng)域數(shù)據(jù)等)。
- Agent 被發(fā)現(xiàn)后,會采用面向任務的架構(gòu)進行通信。與簡單的 “請求 - 響應” 模式不同,Agents 間的交互以異步 “任務” 形式構(gòu)建:client agent 向 server agent 發(fā)送任務請求,隨后 server agent 可通過長連接實時流式返回更新信息。
- 這種穩(wěn)健、標準化的通信協(xié)議是實現(xiàn) Level 3 multi-agent systems 的關(guān)鍵一環(huán),借助 A2A 協(xié)議,原本零散孤立的 Agents 集合,被轉(zhuǎn)化為一個真正具備互操作性的生態(tài)系統(tǒng)。
1.3.6.3. Agent & 金錢
是否允許 Agent 代表用戶安全可靠地進行交易?出了問題責任在誰?
Agent支付協(xié)議:Agent Payments Protocol (AP2)
1.3.7. Agent Security
Agent 的實用性和安全性具備沖突:
- 實用性:賦予它更多的權(quán)利(發(fā)郵件、增刪改查數(shù)據(jù)庫)
- 安全性:限制他有害的行為(刪庫跑路、敏感數(shù)據(jù)泄露)
- 硬編碼規(guī)則,為 Agent 提供可預測、可審計的硬性限制 Prompt(禁止刪除表)
- 訓練模型或者小模型對操作進行安全檢查
1.3.7.1 Agent ID:一類新型主體
Agent 不僅僅是一段代碼,它是一個自主的參與者,是一種需要自身可驗證身份的新型主體。就像員工會領(lǐng)到工牌一樣,平臺上的每個智能體都必須獲得一個安全、可驗證的“數(shù)字護照”。
對每個身份進行驗證并為所有身份設置訪問控制,是 Agents 安全的基礎(chǔ)。一旦 Agents 擁有可通過加密方式驗證的身份,就可以為其賦予特定的、最小權(quán)限的許可(不同系統(tǒng)間權(quán)限隔離)。它能確保單個 Agent 被入侵或行為異常,潛在的影響范圍也能得到控制。
1.3.7.2 訪問約束策略
策略的本質(zhì)是授權(quán)(你能干啥)而非認證(你是誰),需通過 “最小權(quán)限原則” 約束訪問范圍。Agentic 系統(tǒng)的權(quán)限關(guān)系更復雜,策略需延伸到 Agent 交互的所有關(guān)鍵環(huán)節(jié):
- Agents: 限制自身能力
- Tools: 控制工具使用范圍
- SubAgents: 限制子 Agents 能力
- Context: 管控上下文敏感信息
- Remote Agent: 跨系統(tǒng)遠程 Agent 的訪問
1.3.7.3 ADK 智能體的保護
ADK 采用:
- 身份驗證(Agent Identity)
- 建立訪問策略(授權(quán)你能干啥)
- 工具和 SubAgents 內(nèi)置防護
- AI 動態(tài)防護(before_tool_callback工具調(diào)用前回調(diào)、AI插件實時監(jiān)控輸入輸出)
- 托管安全服務(Model Armor)
的混合方案,既讓 Agent 具備強大功能,又能保證其可信任性和安全性。
1.3.8. 擴展單個 Agent 到 Agents 集群
單個到數(shù)百個的擴張管理起來會很復雜,需要更好的架構(gòu)性設計。
1.3.8.1 安全和隱私
縱深防御策略:從數(shù)據(jù)層開始,到控制輸入輸出、Prompt防火墻等(企業(yè)級別的數(shù)據(jù)保護)
1.3.8.2 Agents 治理
agent sprawl(智能體蔓延):隨著多執(zhí)行體復雜交互網(wǎng)絡的出現(xiàn),需要一個作為所有智能體活動控制平面的中央網(wǎng)關(guān):可以檢查、路由、監(jiān)控和管理每一次 Agents 之間的交互。
- 運行時策略:驗證身份和授權(quán)操作,跟蹤記錄 Agent 行為日志和指標
- 集中式管理:Agents Tools 注冊表系統(tǒng)(管理界面)
1.3.8.3 成本和可靠性
企業(yè)級智能體必須既可靠又具成本效益。
1.3.9. 進化和學習
現(xiàn)實環(huán)境中政策、技術(shù)和數(shù)據(jù)不斷變化,Agents 需要具備成為老古董的能力。
1.3.9.1 智能體如何學習和自我進化
和人類相似,Agent 從經(jīng)驗和外部信息中學習。
- 運行過程中通過日志和跟蹤記錄積累失敗和成功的經(jīng)驗
- 外部數(shù)據(jù)源更新,私域知識的更新
- 增強型上下文工程:持續(xù)優(yōu)化Prompt、示例和內(nèi)存中用于檢索的信息
- Tool的新增和優(yōu)化:獲取、創(chuàng)建、修改 Tool
示例:
-
學習新的合規(guī)指南
金融企業(yè)必須在符合隱私和監(jiān)管規(guī)則的前提下給用戶提供報告
Querying Agent: 響應用戶請求檢索原始數(shù)據(jù)
Reporting Agent: 總結(jié)數(shù)據(jù)生成報告
Critiquing Agent: 根據(jù)已知合規(guī)指南對報告進行審查,模糊場景提交給人工干預
Learning Agent: 學習整個流程尤其是人工專家干預部分,將人工反饋歸納為新的合規(guī)指南中的一條。
學習新合規(guī)鏈路
1.3.9.2 模擬與 Agent 訓練平臺
離線過程中而非運行時獲取的信息來優(yōu)化 Agents 能力。
模擬環(huán)境、使用高級模擬數(shù)據(jù)生成器、與領(lǐng)域?qū)<易稍儷@取指導。
1.4. 高級 Agents 示例
自己隨便看看就好
1.4.1. Google Co-Scientist
1.4.2. AlphaEvolve Agent
1.5. 總結(jié)
生成式人工智能智能體標志著一次關(guān)鍵的進化,將人工智能從單純的內(nèi)容創(chuàng)作,轉(zhuǎn)變?yōu)榻鉀Q問題過程中積極且自主的搭檔。
Agent 三個基本組件:Model Tools Orchestration-Layer 組合在一起實現(xiàn)了連續(xù)的 "Think, Act, Observe" 循環(huán)鏈路。
Agent 開發(fā)者的工作變成了引導、約束和調(diào)試 Agent 行為。
2. 代碼實驗室
2.1. first AI agent
基礎(chǔ)模型對話中加入谷歌查詢 Tool 來達到根據(jù)用戶需求實時進行谷歌搜索的能力
root_agent = Agent(
name="helpful_assistant",
model=Gemini(
model="gemini-2.5-flash-lite",
retry_options=retry_config
),
description="A simple agent that can answer general questions.",
instruction="You are a helpful assistant. Use Google Search for current info or if unsure.",
tools=[google_search],
)
print("? Root Agent defined.")
2.2. first multi-agent system
2.2.1. Research & Summarization System
主 agent 調(diào)用檢索 agent 和總結(jié) agent 實現(xiàn)檢索總結(jié)系統(tǒng)
-
ResearchAgent 負責使用谷歌搜索Tool進行數(shù)據(jù)檢索
# Research Agent: Its job is to use the google_search tool and present findings. research_agent = Agent( name="ResearchAgent", model=Gemini( model="gemini-2.5-flash-lite", retry_options=retry_config ), instruction="""You are a specialized research agent. Your only job is to use the google_search tool to find 2-3 pieces of relevant information on the given topic and present the findings with citations.""", tools=[google_search], output_key="research_findings", # The result of this agent will be stored in the session state with this key. ) print("? research_agent created.") -
SummarizerAgent 負責總結(jié)ResearchAgent 的檢索結(jié)果
# Summarizer Agent: Its job is to summarize the text it receives. summarizer_agent = Agent( name="SummarizerAgent", model=Gemini( model="gemini-2.5-flash-lite", retry_options=retry_config ), # The instruction is modified to request a bulleted list for a clear output format. instruction="""Read the provided research findings: {research_findings} Create a concise summary as a bulleted list with 3-5 key points.""", output_key="final_summary", ) print("? summarizer_agent created.") -
ResearchCoordinator 作為 Root 負責啟動任務調(diào)用兩個 AgentTool
# Root Coordinator: Orchestrates the workflow by calling the sub-agents as tools. root_agent = Agent( name="ResearchCoordinator", model=Gemini( model="gemini-2.5-flash-lite", retry_options=retry_config ), # This instruction tells the root agent HOW to use its tools (which are the other agents). instruction="""You are a research coordinator. Your goal is to answer the user's query by orchestrating a workflow. 1. First, you MUST call the `ResearchAgent` tool to find relevant information on the topic provided by the user. 2. Next, after receiving the research findings, you MUST call the `SummarizerAgent` tool to create a concise summary. 3. Finally, present the final summary clearly to the user as your response.""", # We wrap the sub-agents in `AgentTool` to make them callable tools for the root agent. tools=[AgentTool(research_agent), AgentTool(summarizer_agent)], ) print("? root_agent created.") - 通過 ResearchCoordinator 啟動主流程
runner = InMemoryRunner(agent=root_agent) response = await runner.run_debug( "What are the latest advancements in quantum computing and what do they mean for AI?" )
2.2.2. Blog Post Creation with Sequential Agents
確定鏈路workflow demo,使用順序鏈路調(diào)用 Agents 創(chuàng)建博客文章
- Outline Agent : 為給定主題創(chuàng)建博客大綱
- Writer Agent : 撰寫博客文章
-
Editor Agent : 編輯博客文章草稿,使其清晰且結(jié)構(gòu)合理
順序鏈路
與上一個demo類似,三個子 Agent 由主 Agent 整合為 SequentialAgent(順序性Agent)即可:
root_agent = SequentialAgent(
name="BlogPipeline",
sub_agents=[outline_agent, writer_agent, editor_agent],
)
print("? Sequential Agent created.")
2.2.3. Parallel Multi-Topic Research
當你有多個獨立任務時,你可以使用 ParallelAgent 同時運行所有這些任務。該 Agent 會并發(fā)執(zhí)行其所有子 Agent,顯著加快工作流程。所有并行任務完成后,你就可以將它們的合并結(jié)果傳遞到最后的 “聚合” 步驟。
一個包含四個 Agents 的系統(tǒng):
- Tech Researcher :研究人工智能 / 機器學習新聞和趨勢
- Health Researcher :研究近期醫(yī)療新聞和趨勢
- Finance Researcher :研究金融和金融科技新聞和趨勢
-
Aggregator Agent :將所有研究成果整合為一份摘要
并行鏈路
前三個 Researcher 均為帶有谷歌搜索 Tool 的** Agent **,不再贅述。
Aggregator Agent 代碼如下,將三個 Researcher 結(jié)果和總結(jié)需求提交給 LLM :
# The AggregatorAgent runs *after* the parallel step to synthesize the results.
aggregator_agent = Agent(
name="AggregatorAgent",
model=Gemini(
model="gemini-2.5-flash-lite",
retry_options=retry_config
),
# It uses placeholders to inject the outputs from the parallel agents, which are now in the session state.
instruction="""Combine these three research findings into a single executive summary:
**Technology Trends:**
{tech_research}
**Health Breakthroughs:**
{health_research}
**Finance Innovations:**
{finance_research}
Your summary should highlight common themes, surprising connections, and the most important key takeaways from all three reports. The final summary should be around 200 words.""",
output_key="executive_summary", # This will be the final output of the entire system.
)
print("? aggregator_agent created.")
并發(fā)執(zhí)行方式如下:
主 Agent 為順序鏈路 Agent,先執(zhí)行 parallel_research_team 然后執(zhí)行aggregator_agent。
parallel_research_team 為并行 Agent,同時執(zhí)行三個researcher。
# The ParallelAgent runs all its sub-agents simultaneously.
parallel_research_team = ParallelAgent(
name="ParallelResearchTeam",
sub_agents=[tech_researcher, health_researcher, finance_researcher],
)
# This SequentialAgent defines the high-level workflow: run the parallel team first, then run the aggregator.
root_agent = SequentialAgent(
name="ResearchSystem",
sub_agents=[parallel_research_team, aggregator_agent],
)
runner = InMemoryRunner(agent=root_agent)
response = await runner.run_debug(
"Run the daily executive briefing on Tech, Health, and Finance"
)
2.2.4. Iterative Story Refinement
當一項任務需要通過反饋和修訂循環(huán)來改進時,你可以使用循環(huán)代理(LoopAgent)。循環(huán)代理會重復運行一組子代理,直到滿足特定條件或達到最大迭代次數(shù)。這就形成了一個優(yōu)化周期,使代理系統(tǒng)能夠不斷改進自己的工作。
一個包含兩個 Agents 的系統(tǒng):
- Writer Agent :撰寫短篇小說草稿
-
Critic Agent :審閱并評論短篇小說,提出改進建議
循環(huán)鏈路
- 初始化撰寫小說 Agent :
# This agent runs ONCE at the beginning to create the first draft. initial_writer_agent = Agent( name="InitialWriterAgent", model=Gemini( model="gemini-2.5-flash-lite", retry_options=retry_config ), instruction="""Based on the user's prompt, write the first draft of a short story (around 100-150 words). Output only the story text, with no introduction or explanation.""", output_key="current_story", # Stores the first draft in the state. ) print("? initial_writer_agent created.") - 評價小說 Agent,如果通過返回
APPROVED,否則給出修改建議:# This agent's only job is to provide feedback or the approval signal. It has no tools. critic_agent = Agent( name="CriticAgent", model=Gemini( model="gemini-2.5-flash-lite", retry_options=retry_config ), instruction="""You are a constructive story critic. Review the story provided below. Story: {current_story} Evaluate the story's plot, characters, and pacing. - If the story is well-written and complete, you MUST respond with the exact phrase: "APPROVED" - Otherwise, provide 2-3 specific, actionable suggestions for improvement.""", output_key="critique", # Stores the feedback in the state. ) print("? critic_agent created.") - 當評論通過返回
APPROVED退出循環(huán)用的函數(shù):# This is the function that the RefinerAgent will call to exit the loop. def exit_loop(): """Call this function ONLY when the critique is 'APPROVED', indicating the story is finished and no more changes are needed.""" return {"status": "approved", "message": "Story approved. Exiting refinement loop."} print("? exit_loop function created.") - 指揮上面三個部分協(xié)作的 Agent:
# This agent refines the story based on critique OR calls the exit_loop function. refiner_agent = Agent( name="RefinerAgent", model=Gemini( model="gemini-2.5-flash-lite", retry_options=retry_config ), instruction="""You are a story refiner. You have a story draft and critique. Story Draft: {current_story} Critique: {critique} Your task is to analyze the critique. - IF the critique is EXACTLY "APPROVED", you MUST call the `exit_loop` function and nothing else. - OTHERWISE, rewrite the story draft to fully incorporate the feedback from the critique.""", output_key="current_story", # It overwrites the story with the new, refined version. tools=[ FunctionTool(exit_loop) ], # The tool is now correctly initialized with the function reference. ) print("? refiner_agent created.") - 程序的主 Agent構(gòu)造
主 Agent 先順序鏈路執(zhí)行 initial_writer_agent 初始化故事,然后執(zhí)行 story_refinement_loop 進入 LoopAgent,循環(huán)調(diào)用 critic_agent 對故事評價和 refiner_agent 指揮1、2、3部分協(xié)作。# The LoopAgent contains the agents that will run repeatedly: Critic -> Refiner. story_refinement_loop = LoopAgent( name="StoryRefinementLoop", sub_agents=[critic_agent, refiner_agent], max_iterations=2, # Prevents infinite loops ) # The root agent is a SequentialAgent that defines the overall workflow: Initial Write -> Refinement Loop. root_agent = SequentialAgent( name="StoryPipeline", sub_agents=[initial_writer_agent, story_refinement_loop], ) print("? Loop and Sequential Agents created.") runner = InMemoryRunner(agent=root_agent) response = await runner.run_debug( "Write a short story about a lighthouse keeper who discovers a mysterious, glowing map" )
2.3. 選擇合適的 Agent 模式

| Agent 類型 | 適用場景 | 示例 | 核心特點 |
|---|---|---|---|
| LLM 編排 | 需要動態(tài)協(xié)調(diào)調(diào)度的場景 | 研究 + 總結(jié) | 由LLM決定調(diào)用組件 |
| Sequential | 任務順序有要求、需線性執(zhí)行的場景 | 列大綱 → 撰寫 → 編輯 | 執(zhí)行順序固定可確定 |
| Parallel | 任務相互獨立、需提升效率的場景 | 多主題研究 | 多個任務并發(fā)執(zhí)行 |
| Loop | 需要迭代優(yōu)化、持續(xù)改進的場景 | 撰寫者 + 評論者協(xié)同優(yōu)化 | 通過重復循環(huán)提升質(zhì)量 |
參考文獻:
5-Day AI Agents Intensive Course with Google
Introduction to Agents
Day 1a - From Prompt to Action
Day 1b - Agent Architectures



