Agent 設計準則
三大準則:
- 透明:讓用户感知 Agent 的存在,以及其行為
- 可控:用户可以設置 agent的偏好,並對 Agent 進行指令,以及監控其行為
- 一致性:Agent 行為保持一致,避免用户對 Agent 行為產生困惑
透明性設計
透明性要求 Agent 在交互過程中清晰表達其意圖、能力和限制:
- 身份標識:Agent 應該明確告知用户其 AI 身份,避免誤導
- 能力邊界:清楚説明 Agent 能做什麼,不能做什麼
- 決策解釋:在做出重要決策時,提供簡要的推理過程
- 狀態反饋:及時告知用户當前正在執行的操作和進度
可控性實現
可控性確保用户能夠有效指導和干預 Agent 的行為:
- 偏好設置:允許用户設置個人偏好,如語言風格、詳細程度等
- 指令覆蓋:用户指令應優先於 Agent 的默認行為
- 中斷機制:提供暫停、撤銷、重置等控制選項
- 監控面板:展示 Agent 的執行歷史和決策依據
一致性保障
一致性避免用户產生困惑,建立可預期的交互體驗:
- 行為模式:保持相似場景下的一致響應模式
- 語言風格:維持統一的溝通語氣和專業程度
- 決策邏輯:避免自相矛盾的決策和建議
- 錯誤處理:統一優雅的錯誤提示和恢復機制
工具使用設計模式
工具使用分類:
- 動態信息檢索
- 代碼執行
- workflow 自動流
- 內容生成和編輯
agent 工具使用中需要實現的內容包括:
- function/tool schema 定義
- tool 執行邏輯實現
- 消息處理
- 工具集成框架
- 錯誤處理
- 狀態管理
工具設計原則
Schema 設計最佳實踐
schema 定義:告訴大模型工具的用途和用法:
# Function description for the model to read
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
工具命名規範
- 語義化命名:函數名應準確反映其功能,如
calculate_mortgage_payment - 動詞開頭:使用動詞+名詞的結構,如
get_weather_data - 避免歧義:避免使用可能產生多種理解的名稱
- 保持一致:相似功能保持命名風格一致
參數設計原則
- 最小必要:只包含完成任務必需的參數
- 類型明確:明確定義每個參數的數據類型
- 默認值:為非必需參數提供合理的默認值
- 驗證規則:在描述中説明參數的取值範圍和格式要求
工具執行架構
tool 執行邏輯
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
錯誤處理機制
- 輸入驗證:檢查參數類型、範圍和格式
- 異常捕獲:使用 try-except 捕獲可能的異常
- 友好提示:返回用户可理解的錯誤信息
- 降級處理:在主功能失敗時提供備選方案
性能優化
- 緩存機制:對頻繁請求的數據實施緩存
- 異步執行:耗時操作採用異步方式
- 批量處理:支持批量請求以提高效率
- 超時控制:設置合理的超時時間
調用流程管理
- 意圖識別:Agent 判斷是否需要調用工具
- 參數提取:從用户輸入中提取工具參數
- 工具選擇:選擇最合適的工具執行
- 執行監控:跟蹤工具執行狀態
- 結果處理:解析和格式化工具返回結果
- 上下文更新:將結果整合到對話上下文中
Agent Framework 示例
好在通常我們不需要從零到一完成所有以上繁瑣的工作,可以使用 agent framework 幫助我們完成通用工作,示例如下:
import asyncio
from random import randint
from agent_framework import ChatAgent, ai_function
from agent_framework.openai import OpenAIChatClient
from util import get_model_endpoint
AGENT_NAME = "TravelAgent"
AGENT_INSTRUCTIONS = """You are a helpful AI Agent that can help plan vacations for customers.
Important: When users specify a destination, always plan for that location. Only suggest random destinations when the user hasn't specified a preference.
When the conversation begins, introduce yourself with this message:
"Hello! I'm your TravelAgent assistant. I can help plan vacations and suggest interesting destinations for you. Here are some things you can ask me:
1. Plan a day trip to a specific location
2. Suggest a random vacation destination
3. Find destinations with specific features (beaches, mountains, historical sites, etc.)
4. Plan an alternative trip if you don't like my first suggestion
What kind of trip would you like me to help you plan today?"
Always prioritize user preferences. If they mention a specific destination like "Bali" or "Paris," focus your planning on that location rather than suggesting alternatives.
"""
@ai_function(
name="get_random_destination",
description="Get a random travel destination suggestion.",
)
def get_random_destination() -> str:
destinations = [
"Barcelona, Spain", # Mediterranean cultural hub
"Paris, France", # European artistic center
"Berlin, Germany", # Historical European capital
"Tokyo, Japan", # Asian technology metropolis
"Sydney, Australia", # Oceanic coastal city
"New York, USA", # American urban center
"Cairo, Egypt", # African historical capital
"Cape Town, South Africa", # African scenic destination
"Rio de Janeiro, Brazil", # South American beach city
"Bali, Indonesia", # Southeast Asian island paradise
]
# Factory Method Pattern: Create destination selection on demand
return destinations[randint(0, len(destinations) - 1)]
async def main():
model_url, api_key, model_name = get_model_endpoint()
openai_chat_client = OpenAIChatClient(base_url=model_url, api_key=api_key, model_id=model_name)
tools = [get_random_destination]
agent = ChatAgent(
name=AGENT_NAME,
chat_client=openai_chat_client,
instructions=AGENT_INSTRUCTIONS,
tools=tools,
tool_call_parser="llama3_json",
tool_choice="auto",
)
thread = agent.get_new_thread()
response = await agent.run("plan me a day trip", thread=thread)
last_message = response.messages[-1]
text_content = last_message.contents[0].text
print("Travel plan: ", text_content)
if __name__ == "__main__":
asyncio.run(main())
主流 Agent Framework 對比
LangChain
- 特點:功能最全面,生態系統豐富
- 優勢:文檔完善,社區活躍,集成度高
- 適用:企業級應用,複雜工作流
- 學習曲線:中等偏陡
Microsoft Agent Framework
- 特點:提供統一的Agent開發平台,融合了Semantic Kernel和AutoGen的理念
- 優勢:模塊化設計,支持多Agent協作,易於集成和部署
- 適用:構建複雜AI Agent應用,多LLM提供商集成
- 學習曲線:中等
Framework 選擇指南
- 項目規模:小型項目選輕量級框架,大型項目選功能全面的框架
- 團隊經驗:考慮團隊技術棧和學習能力
- 性能要求:高併發場景需要性能優化好的框架
- 定製化需求:需要深度定製時選擇擴展性強的框架
RAG (Retrieval-Augmented Generation)
動態獲取外部資源,作為生成的增強。
RAG 核心原理
RAG通過結合檢索系統和生成模型,實現知識的動態獲取:
- 檢索階段:從知識庫中檢索相關信息
- 增強階段:將檢索結果整合到提示詞中
- 生成階段:基於增強後的提示詞生成回答
"Maker-Checker" 模式
不是單次 檢索 + 讀取的模式,而是模型全權負責推理、錯誤處理(改寫)、工具選擇和調用、信息檢索,並按需多次循環的過程。
Maker-Checker 工作流程
- 需求理解:分析用户查詢的核心需求
- 查詢生成:構建合適的檢索查詢
- 信息檢索:執行檢索操作
- 質量檢查:評估檢索結果的相關性
- 迭代優化:必要時調整查詢重新檢索
- 答案生成:綜合所有信息生成最終回答
因為 Agent 高度自動化,因此需要在 agent 執行過程中保證:
- 透明、可解釋:記錄檢索過程和決策依據
- 無變差、平衡的 retrieve:避免信息偏見和遺漏
通常記錄整體執行過程中的推理內容、query生成、query結果等,用作自動、人為監控。
RAG 優化策略
檢索優化
- 多路召回:同時使用多種檢索策略
- 重排序:對初步結果進行精細排序
- 查詢擴展:自動擴展和改寫查詢
- 語義理解:使用嵌入向量提升語義匹配
知識庫優化
- 文檔切分:合理的文檔粒度劃分
- 元數據標註:添加時間、來源等元信息
- 版本管理:支持知識的更新和版本控制
- 質量控制:建立知識審核和更新機制
Planning (規劃)
規劃是 Agent 的核心能力之一,涉及任務分解、資源分配和執行策略制定。
規劃層次結構
戰略層規劃
- 目標設定:明確長期目標和成功標準
- 資源評估:評估可用資源和時間限制
- 風險評估:識別潛在風險和應對策略
- 里程碑定義:設置關鍵檢查點
戰術層規劃
- 任務分解:將大目標分解為可執行任務
- 依賴分析:識別任務間的依賴關係
- 優先級排序:確定任務執行順序
- 時間估算:評估各任務所需時間
執行層規劃
- 具體步驟:制定詳細的執行步驟
- 異常處理:準備備選方案和應急措施
- 監控機制:設置執行監控和反饋機制
- 調整策略:制定動態調整計劃的方法
規劃算法
經典規劃算法
- HTN (Hierarchical Task Networks):分層任務網絡規劃
- STRIPS:經典AI規劃算法
- PDDL:規劃領域定義語言
- A*:啓發式搜索算法
現代規劃方法
- 強化學習:通過試錯學習最優策略
- 蒙特卡洛樹搜索:用於複雜決策場景
- 進化算法:遺傳算法等羣體智能方法
- 神經網絡規劃:使用深度學習進行規劃
規劃挑戰與解決
不確定性處理
- 概率規劃:考慮不確定性的規劃
- 魯棒優化:制定抗干擾的計劃
- 自適應規劃:根據環境變化調整計劃
- 多場景規劃:為不同情況制定預案
動態環境適應
- 在線規劃:實時調整執行策略
- 增量規劃:逐步完善和更新計劃
- 重規劃機制:當環境變化時重新規劃
- 學習機制:從歷史經驗中學習改進
多智能體設計
多智能體系統涉及多個 Agent 的協作、通信和協調。
多智能體架構
- agent communication:定義 Agent 間的通信協議和語言
- agent 協作:制定協作策略和衝突解決機制
- agent 架構:設計 Agent 的內部結構和交互接口
- 多 agent 交互可感知:確保 Agent 能感知和理解其他 Agent 的行為
- 多 agent 組織方式: 中心化、去中心化、分層
- 人工參與:什麼時候需要人工參與,什麼形式參與
多智能體組織方式
中心化架構
- 中央協調器:所有決策由中央 Agent 做出
- 優點:統一控制,決策一致性高
- 缺點:單點故障,擴展性有限
- 適用:小規模,強一致性要求的場景
去中心化架構
- 自治決策:每個 Agent 獨立做出決策
- 優點:容錯強勁,可擴展性好
- 缺點:協調複雜,可能產生衝突
- 適用:大規模,動態環境
分層架構
- 多級管理:不同層級負責不同粒度的決策
- 優點:平衡了集中和分散的優勢
- 缺點:架構複雜,層級間通信開銷
- 適用:中等規模,需要分級管理的場景
多智能體常見設計模式
- group chat: 多智能體間可以直接相互溝通。
- hand-off: 如 workflow automation, customer support場景。
- collaborative filtering: 協作過濾,多個 Agent 共同過濾和篩選信息
通信機制
通信類型
- 直接通信:Agent 間點對點通信
- 廣播通信:一個 Agent 向所有其他 Agent 發送消息
- 組播通信:向特定組的 Agent 發送消息
- 間接通信:通過環境或其他媒介傳遞信息
通信內容
- 任務信息:任務分配、進度彙報
- 狀態信息:Agent 當前狀態和能力
- 協調信息:衝突解決、資源協商
- 知識共享:經驗、教訓、最佳實踐
協作策略
任務分配
- 能力匹配:根據 Agent 能力分配任務
- 負載均衡:考慮 Agent 當前負載
- 優先級排序:根據任務緊急程度分配
- 動態調整:根據執行情況動態重新分配
衝突解決
- 協商機制:通過談判解決資源衝突
- 仲裁機制:第三方仲裁解決爭議
- 投票機制:多數表決決定
- 優先級機制:根據預設優先級解決衝突
元認知 (Metacognition)
元認知是 Agent 對自身認知過程的認知和調控能力。
元認知層次
監控層
- 性能監控:實時監控自身表現
- 錯誤檢測:識別和診斷錯誤
- 進度跟蹤:跟蹤任務執行進度
- 資源監控:監控計算資源使用情況
調控層
- 策略調整:根據監控結果調整策略
- 學習優化:從經驗中學習改進
- 資源重分配:動態調整資源分配
- 目標修正:必要時修正目標和計劃
元認知能力實現
自我評估
- 置信度評估:對決策結果的可信度評估
- 能力評估:對自身能力的準確認知
- 侷限性識別:識別自身知識和能力的侷限
- 不確定性量化:量化決策中的不確定性
學習機制
- 經驗總結:從成功和失敗中總結經驗
- 模式識別:識別問題解決的通用模式
- 知識更新:不斷更新和完善知識庫
- 策略優化:優化決策和執行策略
元認知應用場景
- 複雜問題解決:在複雜環境中進行深度推理
- 學習新任務:快速適應和學習新任務
- 異常處理:在異常情況下的自適應處理
- 性能優化:持續優化自身性能表現
Agent 可觀測與評估
為什麼需要觀測 Agent 的執行過程和執行結果?:
- 定位錯誤: 當 Agent 執行出錯時,通過觀測其執行過程可以快速定位錯誤發生的位置。
- 評估 Agent 性能: 觀測 Agent 的執行結果可以評估其性能,如準確率、召回率、F1 等指標。
- 監控 Agent 行為: 觀測 Agent 的執行過程可以監控其行為,如是否遵守指令、是否重複執行相同操作等。
- 控制成本、時延:
觀測體系架構
數據收集層
- 日誌記錄:詳細記錄 Agent 的所有操作和決策
- 指標採集:收集關鍵性能指標
- 事件追蹤:追蹤重要事件的發生和處理
- 狀態快照:定期保存 Agent 狀態
數據處理層
- 數據清洗:去除噪聲和無效數據
- 數據聚合:按時間、類型等維度聚合數據
- 特徵提取:提取有價值的特徵信息
- 異常檢測:識別異常行為和模式
可視化層
- 實時監控:實時展示關鍵指標
- 歷史趨勢:展示指標的歷史變化趨勢
- 對比分析:支持不同 Agent 或不同時期的對比
- 報告生成:自動生成觀測報告
評估指標體系
常用檢測指標:
- 時延:響應時間、任務完成時間
- 成本:計算資源消耗、API 調用成本
- 正確率:任務完成準確率、決策正確性
- 用户反饋:用户滿意度、投訴率
- 請求失敗率:任務失敗比例、錯誤類型分佈
技術指標
- 任務成功率:成功完成的任務比例
- 平均響應時間:從請求到響應的平均時間
- 資源利用率:CPU、內存、網絡等資源使用情況
- 併發處理能力:同時處理多個任務的能力
- 穩定性指標:系統可用時間、故障恢復時間
業務指標
- 用户滿意度:用户對 Agent 服務的滿意程度
- 任務完成質量:完成任務的完整性和準確性
- 成本效益比:投入成本與產出的比值
- 學習改進速度:Agent 學習和改進的效率
觀測打點注入
觀測打點注入:使用 Trace 和 Span 的方式記錄,比如 OpenTelemetry。
Trace 設計
- 調用鏈追蹤:記錄完整的調用鏈路
- 時間戳記錄:精確記錄每個操作的時間
- 上下文傳遞:在調用鏈中傳遞上下文信息
- 異常標記:標記異常發生的位置和類型
Span 設計
- 操作範圍定義:定義每個 Span 的開始和結束
- 標籤添加:為 Span 添加有意義的標籤
- 事件記錄:在 Span 中記錄重要事件
- 關係建立:建立 Span 之間的父子關係
Agent 評估方法
Agent 評估:
- 離線評估:在測試環境中使用預設數據集進行評估
- 在線評估:在生產環境中實時監控和評估
離線評估
- 基準測試:使用標準測試集進行評估
- 對比實驗:與其他 Agent 或基線方法對比
- A/B 測試:對比不同版本或配置的效果
- 壓力測試:測試在高負載下的性能表現
在線評估
- 實時監控:持續監控生產環境表現
- 用户反饋收集:收集和分析用户反饋
- 漸進式 rollout:逐步發佈新版本並監控效果
- 快速回滾:在發現問題時快速回滾到穩定版本
Agent 成本管理&優化
Agent 成本管理&優化:
- 使用更小的模型:通過 Agent 評估,對應特定任務選擇性價比更高的大小合適的模型。
- 智能路由:根據任務複雜度,路由到不同成本的模型上。
- 緩存:常用請求、workflow 結果的緩存;可以引入專門的 Agent 進行請求相似度評估。
成本優化策略
模型選擇優化
- 任務分級:根據任務複雜度選擇合適規模的模型
- 動態切換:根據實時負載和性能要求切換模型
- 混合部署:同時使用多個模型,根據需求分配任務
- 模型蒸餾:使用大模型訓練小模型,保持性能降低成本
智能路由策略
- 複雜度評估:自動評估任務複雜度
- 負載均衡:考慮系統整體負載情況
- 成本預測:預測不同處理方案的成本
- 質量保障:確保在成本控制下維持服務質量
緩存機制設計
- 結果緩存:緩存常見問題的答案
- 中間結果緩存:緩存計算過程中的中間結果
- 模板緩存:緩存常用的響應模板
- 智能預取:預測用户需求並提前準備
Agent 協議
Agent 協議定義了 Agent 之間以及 Agent 與外部系統之間的通信標準和交互規範。
協議分類
- MCP (Model Context Protocol)
- A2A (Agent to Agent protocol)
- NLWeb (Natural Language Web interaction)
MCP (Model Context Protocol)
MCP (model context protocol) 是一種開發協議,用來為大模型提供額外的上下文和工具能力,包括:
- 指令(模板): 大模型需要執行的任務指令(模板),用作解決複雜工作流。
- 工具: 大模型可以調用的外部工具,如計算器,代碼執行器。
- 數據:API 調用,數據查詢等
MCP 架構模式
MCP 採用傳統的 client-server 模式,其中:
- client: 大模型Agent,負責執行指令、調用工具、處理數據等。
- server: 負責提供額外的上下文和工具能力,如指令模板、工具實現、數據查詢等。
- host:對應的應用,比如 trae,vscode 等
MCP 優勢分析
使用 MCP 的優勢,和解決的問題包括:
- 解耦: 大模型Agent 和 應用 之間解耦,應用可以根據需要定製指令、工具、數據等。
- 可擴展性: 應用可以根據需要添加新的指令、工具、數據等,而不需要修改大模型Agent的代碼。
- 可維護性: 應用的代碼和配置都在應用端,而不是大模型Agent端,方便維護和升級。
- 性能: 大模型Agent 只需要關注指令執行和工具調用,而不需要處理數據查詢等。
MCP 應用場景
- IDE 集成:如 VS Code、Trae 等開發環境
- 數據處理:結構化數據的查詢和處理
- 工具集成:各種外部工具和 API 的集成
- 知識管理:企業知識庫的訪問和管理
A2A (Agent to Agent Protocol)
Agent to Agent protocol (A2A) 是 agent 間相互交互的協議,用來幫助 agent 間相互協作。
A2A 核心組件
A2A 中主要包括:
- Agent card:用於 Agent 對外展示自己自己的名字、描述、能力等。
- Agent executor:用於將上下文傳遞給remote agent,或調用 LLM 解析收到的 context
- Artifact:Agent 執行結果的標識
- event queue:Agent 執行狀態管理
A2A 解決問題
A2A 結局的問題:
- 增強協作:支持不同平台、不同供應商直接的 Agent 的協作能力
- 模型自由選擇:不同 Agent 可以使用自己合適的不同地層 LLM。
A2A 通信模式
- 點對點通信:兩個 Agent 直接通信
- 發佈訂閲:Agent 發佈消息,其他 Agent 訂閲
- 請求響應:一個 Agent 請求,另一個 Agent 響應
- 事件驅動:基於事件的消息傳遞
NLWeb (Natural Language Web)
通過自然語言與 web 頁面交互。
NLWeb 核心能力
- 自然語言理解:理解用户的自然語言指令
- 頁面元素識別:識別網頁上的可操作元素
- 動作執行:執行點擊、輸入、滾動等操作
- 結果反饋:將執行結果反饋給用户
NLWeb 應用場景
- 自動化測試:使用自然語言描述測試用例
- 網頁自動化:自動化網頁操作流程
- 輔助工具:幫助用户完成複雜的網頁操作
- 數據採集:從網頁中提取結構化數據
上下文工程
上下文工程是指管理 Agent 用來做計劃、決策、執行所需要的全部信息。受限於 LLM上下文大小、成本等因素,上下文窗口大小是優先的。上下文工程需要再上下文窗口中增加、刪除、壓縮信息。
和提示詞工程的區別聯繫
- 提示詞工程:靜態的指令和規則
- 上下文工程:動態信息管理(包括最初的提示詞),用來保證隨着時間推移 Agent 總能獲取到為完成任務所需要的有效信息。
上下文工程的內容
- 指令:提示詞、系統信息、few-shot 示例、工具描述
- 知識:客觀事實、RAG信息查詢、長短期記憶
- 工具:外部函數、API、MCP servers的定義,用户使用反饋等
- 對話歷史:LLM 對話歷史
- 用户偏好:外部存儲的或者交互過程中收集到的用户偏好
有效上下文管理的準則
- Agent 備忘錄:在單 session 中記錄用户交互、當前任務相關信息等。
- 記憶管理:外部存儲用户單 session 內容,存儲可以先壓縮、總結;用作跨session 加載用户的偏好、feedback等
- 上下文壓縮:隨着上下文增長,需要壓縮、總結上下文,保持上下文窗口大小在可控範圍內。常用總結或截斷的方式,分別保留最相關和最近的上下文信息。
- Multi-Agent: multi-agent 是另一種上下文管理方式,因為每個 agent 有自己獨立的上下文窗口,並且各自可以有着獨立的上下文管理方式。
上下文壓縮技術
摘要壓縮
- 關鍵信息提取:提取對話中的關鍵信息
- 漸進式摘要:隨着對話進行逐步更新摘要
- 層次化摘要:按重要性層次組織摘要
- 主題聚類:按主題對信息進行聚類壓縮
選擇性保留
- 時間權重:最近的信息權重更高
- 重要性評分:根據信息重要性決定保留
- 相關性過濾:過濾掉與當前任務無關的信息
- 用户關注:保留用户特別關注的信息
常見上下文管理失敗原因
上下文中毒
- what:上下文中記錄了 LLM 產生的錯誤信息。
- 解決:對關鍵結論加入上下文前進行驗證和校驗。
上下文濫用
- what:上下文過多、過雜,導致模型無法使用模型中的知識,被上下文中的內容完全拖累。
- 解決:定期上下文總結,僅保留關鍵內容,讓 LLM focus
上下文困惑
- what:通常提供過多的工具,讓 llm 無法抓住重點。
- 解決:管理工具的加載,比如利用 RAG 對工具進行粗過濾,防止提供過多工具讓大模型困惑,抓不住重點。
上下文衝突
- what:上下文中存在相互衝突內容,導致最終推理和結論混亂
- 解決:上下文剪枝,用最新的上下文替換掉衝突的舊上下文。
Agent memory
為 Agent 提供存儲和之後獲取信息的能力。
Agent memory能夠讓應用更加自動化、智能化。
內存類型
- 短期記憶: 用於存儲當前任務相關信息,通常在 session 結束後清除。用於存儲當前任務相關信息。主要保存任務的需求、步驟、決策、實體等上下文
- 長期記憶: 用於存儲用户偏好、反饋、歷史交互等,通常在多個session間長期保存。
- 人設記憶:幫助 Agent 保持系統"人設",更好的以該"人設"完成任務
- (structured) RAG:
Agent memory 的實現
- 使用專用工具 比如 mem0, 能夠記錄用户的偏好、交互上下文、成功失敗歷史等,是無狀態的 agent 任務變成有狀態的。主要過程分為兩階段:
- 提取:利用 LLM從用户交互中提取關鍵信息,比如用户需求、上下文、偏好等。
- 更新:根據用户反饋和交互歷史,更新長期記憶,包括新增、更新、刪除記憶等。
- 使用 RAG 工具存儲記憶
利用記憶的 Agent 自我進化設計範式
引入專職的 “knowledge agent”。在 agent 與用户交互中自動:
- 識別有用信息
- 提取並壓縮有用信息
- 存儲以上信息
- 在後續 Agent 交互中利用存儲的信息,增強 promt,來輔助完成任務。(類似 RAG)
記憶優化
- 延遲優化:使用更小的模型進行信息是否有價值的快速判斷,作為粗過濾。
- 知識存儲優化:過時信息可以優化到“冷存儲”中
Deep agent - 當前 Agent 設計的最佳實踐賞析
Langchain 團隊提出的概念,旨在解決傳統 ReAct 模型中:單 agent 上下文容量不足,無法解決長上下文或複雜任務的問題;無法持久化存儲任務相關信息,不支持回滾,time-travel 等問題。
Deep agent 應該包含以下能力:
- 精細化系統prompt: 系統 prompt 中包含詳細的描述,few-shot 示例等。可參考 claud code 中的系統 prompt 設計。
- planing tool: 能夠根據任務自主進行計劃,通常是一個 write todo tools. 可以拆解子任務、記錄執行進度、動態調整計劃等。
- sub agents: 根據領域,區分出專門的特有 agent,上下文高效獨立管理
- 持久化層:持久化上下文,執行過程、結果等。支持跨會話使用,回滾,錯誤恢復、單點重試、time-travel,human in the loop等能力。最簡單的實現是使用文件系統進行持久化。
當設計一個 deep agent 時,核心需要考慮因素包括:
- core config:
- system prompt
- tools
- model
- features:
- backend
- subagents
- interrupts
from typing import Literal
from tavily import TavilyClient
import os
from deepagents import create_deep_agent
from util import get_model_endpoint
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
一個最簡單的 deep agent - deep research agent 示例:
# create a search tool
def internet_search(
query: str,
topic: Literal["general", "finance", "news"] = "finance",
max_ret: int = 5,
include_raw_content: bool = False,
):
"""Perform an internet search using Tavily.
Args:
query (str): The search query.
topic (Literal["general", "finance", "news"], optional): The topic of the search. Defaults to "finance".
max_ret (int, optional): The maximum number of results to return. Defaults to 5.
include_raw_content (bool, optional): Whether to include raw content in the results. Defaults to False.
"""
return tavily_client.search(
query=query,
max_results=max_ret,
topic=topic,
include_raw_content=include_raw_content,
)
# system promt
research_instructions = """You are an expert researcher. Your job is to conduct thorough research and then write a polished report.
You have access to an internet search tool as your primary means of gathering information.
## `internet_search`
Use this to run an internet search for a given query. You can specify the max number of results to return, the topic, and whether raw content should be included.
"""
model_url, api_key, model_name = get_model_endpoint()
chat_model = ChatOpenAI(
base_url=model_url, api_key=SecretStr(api_key), model=model_name
)
# create agent
agent = create_deep_agent(model=chat_model, tools=[internet_search], system_prompt=research_instructions)
# run agent
result = agent.invoke({"messages": [{"role": "user", "content": "What is deep agent?"}]})
print(result["messages"][-1].content)
示例輸出如下:
uv run deep_agents.py
### What Are Deep Agents?
Deep Agents are an advanced architecture for AI agents designed to handle **complex, multi-step tasks** requiring sustained reasoning, tool use, context management, and collaborative workflows. Unlike traditional agents that rely on simple tool-calling loops, Deep Agents excel at planning, delegating subtasks to specialized sub-agents, and maintaining persistent memory across interactions. They are powered by frameworks like LangChain and enable applications like Claude Code, Deep Research, and Manus to tackle real-world challenges with precision and scalability.
### **Core Characteristics of Deep Agents**
Deep Agents distinguish themselves through four key attributes:
1. **Planning Capability**: Break large tasks into subtasks and adjust plans dynamically.
2. **Context Management**: Retain and reference critical information across long interactions.
3. **Sub-Agent Delegation**: Launch specialized agents for focused tasks (e.g., research, writing).
4. **File System Integration**: Persist and share information across steps via a virtual file system, enabling true "memory" beyond conversation history.
### **Core Components of Deep Agents**
Deep Agents rely on four foundational components to achieve their capabilities:
#### 1. **Detailed System Prompts**
A comprehensive system prompt guides the agent through structured workflows. For example, the `DEEP_AGENT_SYSTEM_PROMPT` in the tutorial outlines:
- **Planning**: Break tasks into subtasks with `todo_write`.
- **Research**: Use web search tools (e.g., Tavily) to gather information.
- **Delegation**: Spawn sub-agents for specialized work (e.g., job search, cover letter writing).
- **Documentation**: Maintain notes in a virtual file system.
*Example*: The job application assistant prompt specifies generating valid JSON job listings and concise cover letters.
#### 2. **Planning Tools**
This forces the agent to explicitly plan steps, ensuring transparency and adjustability.
#### 3. **Sub-Agent Delegation**
Deep Agents can spawn specialized sub-agents with unique prompts, tools, and descriptions. In the job application demo:
- **Job-Search Agent**: Focuses on finding relevant job postings.
- **Cover-Letter Agent**: Generates tailored cover letters for each job.
*Example*:
...
#### 4. **File System Integration**
Agents use tools like `read_file`, `write_file`, and `edit_file` to manage state across steps and sub-agents. For example:
- **File Storage**: Save job listings or cover letters in a virtual file system (e.g., `cover_letters.md`).
- **Shared Workspace**: Sub-agents can read/write to the same files, enabling collaboration.
### **Demo: Job Application Assistant with Deep Agents**
The tutorial demonstrates building a Deep Agent to automate job searches and cover letter drafting. Key steps include:
#### **1. Setup & Dependencies**
Install required libraries:
#### **2. UI & Input Handling**
Users upload resumes (PDF/DOCX/TXT), specify job title/location, and skills. The app extracts resume text using `extract_text()`:
#### **3. Tool Integration**
- **Web Search**: Use Tavily API to fetch job listings via `internet_search()`.
- **LLM**: OpenAI’s GPT-4o-mini for reasoning and content generation.
#### **4. Agent Configuration**
The main agent is created with sub-agents for job search and cover letters:
...
#### **5. Execution & Results**
The agent processes the task prompt (resume, skills, job criteria), generates JSON-formatted job listings, and writes cover letters to `cover_letters.md`. Users download the output as a Word document.
### **Key Takeaways**
Deep Agents represent a paradigm shift in AI, enabling **multi-step, context-aware, and collaborative workflows** that traditional agents cannot handle. By combining detailed system prompts, planning tools, sub-agent delegation, and file system integration, they excel at complex tasks like job applications, research, and code development. Frameworks like LangChain’s `deepagents` package make this architecture accessible, allowing developers to build production-ready agents with minimal effort.
For practical implementation, explore the tutorial’s demo project to see how Deep Agents transform manual job applications into automated, AI-driven workflows!
**Source**: Adapted from LangChain’s Deep Agents tutorial by Aashi Dutt (DataCamp).
deep agents 必要 tools
一個 deep agent 應該支持至少一下 tool:
- todo_write: 用於創建任務列表,支持子任務拆解。
- read_file: 用於讀取agent的文件系統中的文件內容。
- ls: 列出文件列表
- glob/grep: 文件內容檢索
- write_file: 用於寫入agent的文件系統中的文件內容。
- edit_file: 用於編輯agent的文件系統中的文件內容。
- task: 創建 subagent 用户處理任務。
- [optional] internet_search: 用於互聯網搜索.
subagents
sub-agents 的對比單 agent 主要優勢:
- 上下文獨立 -> 更大的上下文窗口
- 並行執行
- 特化能力: 獨立工具等 -> 上下文獨立 -> 更大的上下文窗口
- token 節省
subagents 工作原理:main agent 擁有一個 task tool,這個 tool 可以創建 sub agent,並注入專用上下文。 sub agent 執行完成後返回結果給 main agent,sub agent是無狀態的。
除默認“通用“sub-agent 外,用户應該根據場景按需定義更多專用 sub-agent 和專用 tool。
human in the loop
一些關鍵、敏感 tool 需要用户 approve 才能執行,可以利用 langraph 的持久化能力實現。
from langchain.tools import tool
from deepagents import create_deep_agent
from langgraph.checkpoint.memory import MemorySaver
@tool
def delete_file(path: str) -> str:
"""Delete a file from the filesystem."""
return f"Deleted {path}"
@tool
def read_file(path: str) -> str:
"""Read a file from the filesystem."""
return f"Contents of {path}"
@tool
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email."""
return f"Sent email to {to}"
# Checkpointer is REQUIRED for human-in-the-loop
checkpointer = MemorySaver()
agent = create_deep_agent(
model="claude-sonnet-4-5-20250929",
tools=[delete_file, read_file, send_email],
interrupt_on={
"delete_file": True, # Default: approve, edit, reject
"read_file": False, # No interrupts needed
"send_email": {"allowed_decisions": ["approve", "reject"]}, # No editing
},
checkpointer=checkpointer # Required!
)