
Hindsight × AG2 集成指南為 AutoGen 社區分支 Agent 接入跨會話持久化記憶【免費下載鏈接】hindsightHindsight: Agent Memory That Learns項目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本文檔基于倉庫中 hindsight-docs/docs-integrations/ag2.md 編寫并結合 hindsight-integrations/ag2 下的源碼、測試與打包配置展開介紹如何為 AG2AutoGen 社區分支Agent 接入 Hindsight 持久化記憶系統。導讀AG2 是 AutoGen 的社區分支框架其多 Agent 協作模型非常靈活但默認不提供跨會話的長期記憶。本文講解如何通過hindsight-ag2集成包用一行代碼為 AG2 Agent 注冊retain記憶寫入、recall記憶檢索、reflect記憶反思三個工具讓 Agent 在多次對話之間持續記住用戶偏好、事實與決策。讀完本文你將掌握安裝步驟、全局配置與按工具集覆蓋參數的方法、GroupChat 共享記憶的搭建以及從源碼層面理解三個工具背后的 Hindsight API 調用鏈與配置優先級規則。功能特性一覽Drop-in 工具register_hindsight_tools()一行同時注冊 retain / recall / reflect 三個工具AG2 原生兼容工具是帶Annotated類型提示的普通 Python 函數與 AG2 的register_for_llm/register_for_execution注冊模式完全匹配GroupChat 支持多個 Agent 可以共享同一個 memory bank實現團隊級統一記憶按需選擇工具通過include_retain/include_recall/include_reflect只注冊需要的子集配置簡單靈活既可全局配置一次也可在每次創建工具集時按需覆蓋。安裝pip install hindsight-ag2從 hindsight-integrations/ag2/pyproject.toml 可以看到本包的版本與依賴約束requires-python 3.10依賴ag20.9.0、hindsight-client0.4.0也就是說除了 Python 3.10 與 AG2 之外你還需要一個正在運行的 Hindsight API 服務本地可通過docker compose部署或使用托管服務工具的每個調用都會通過hindsight-client走 HTTP 請求??焖匍_始把記憶工具掛到 Agent 上只需幾步from autogen import AssistantAgent, UserProxyAgent, LLMConfig from hindsight_ag2 import register_hindsight_tools llm_config LLMConfig(api_typeopenai, modelgpt-4o-mini) with llm_config: assistant AssistantAgent( nameassistant, system_messageYou are a helpful assistant with long-term memory., ) user_proxy UserProxyAgent( nameuser, human_input_modeNEVER, ) # Register Hindsight memory tools on both agents register_hindsight_tools( assistant, user_proxy, bank_idmy-bank, hindsight_api_urlhttp://localhost:8888, ) # The assistant can now use hindsight_retain, hindsight_recall, hindsight_reflect result user_proxy.initiate_chat( assistant, messageRemember that I prefer Python over JavaScript., )執行后assistant 就獲得了跨會話記憶能力hindsight_retain把「偏好 Python」寫入 bank下一次對話時hindsight_recall能把它搜出來hindsight_reflect還能基于歷史記憶給出綜合回答。工作原理三個工具背后的 Hindsight APIregister_hindsight_tools內部調用create_hindsight_tools()實現見 hindsight-integrations/ag2/hindsight_ag2/tools.py默認生成三個函數工具底層 Hindsight 操作行為說明hindsight_retain(content)retain(bank_id, content, ...)把原始文本交給 Hindsight由服務端自動抽取事實facts、實體entities與關系后存儲hindsight_recall(query)recall(bank_id, query, ...)Hindsight 執行語義搜索、BM25、圖譜遍歷與重排返回編號后的匹配記憶列表hindsight_reflect(query)reflect(bank_id, query, ...)Hindsight 基于 bank 的 disposition 特征把相關記憶綜合成有推理依據的回答源碼視角工具函數的真實形態在 tools.py 中hindsight_retain的關鍵實現如下def hindsight_retain( content: Annotated[ str, The information to store in long-term memory. Include important facts, user preferences, decisions, or anything that should be remembered across conversations., ], ) - str: retain_kwargs: dict[str, Any] {bank_id: bank_id, content: content} if effective_tags: retain_kwargs[tags] effective_tags if retain_metadata: retain_kwargs[metadata] retain_metadata if retain_document_id: retain_kwargs[document_id] retain_document_id resolved_client.retain(**retain_kwargs) return Memory stored successfully.可以看到幾個關鍵設計參數描述內嵌在類型提示里Annotated[str, ...]中的說明文字會由 AG2 讀取并生成 LLM 可見的 tool schema幫助模型理解「該存什么」。測試 tests/test_tools.py 的TestAnnotatedTypes正是用get_type_hints(..., include_extrasTrue)驗證了三個工具的參數都帶有__metadata__??蛇x參數按需注入只有顯式傳入tags/metadata/document_id時才加入請求體保證默認調用足夠輕量。統一異常封裝底層 client 拋出的任何異常都會被記錄日志并重新包裝為HindsightError見 hindsight-integrations/ag2/hindsight_ag2/errors.py返回給 AG2 的錯誤信息帶Retain failed: ...前綴便于 Agent 識別失敗原因。hindsight_recalltools.py內部會組裝bank_id/query/budget/max_tokens并按需附帶tagstags_match、types、include_entities最后把response.results渲染成「1. 記憶文本 / 2. 記憶文本 …」的編號列表返回若結果為空則返回No relevant memories found.。hindsight_reflecttools.py則把context、max_tokens缺省回退到effective_max_tokens、response_schema、tags/tags_match缺省回退到 recall 的對應值傳給reflect最終返回response.text??蛻舳巳绾伪唤馕龉ぞ卟⒉恢苯?new client而是經由 hindsight-integrations/ag2/hindsight_ag2/_client.py 的resolve_client()按優先級解析顯式傳入的client優先通常是調用方已配置好的Hindsight實例顯式傳入的hindsight_api_url/api_key全局配置configure()中設置的值環境變量HINDSIGHT_API_KEY僅對 api_key 生效??蛻舳四Jtimeout30.0并攜帶User-Agent: hindsight-ag2/version版本號取自包元數據見 _client.py。若以上路徑都解析不到 URL會直接拋出HindsightError: No Hindsight API URL configured...——這一點在test_raises_without_client_or_config中有對應測試。配置詳解全局配置configurefrom hindsight_ag2 import configure configure( hindsight_api_urlhttp://localhost:8888, api_keyyour-key, # or set HINDSIGHT_API_KEY env var budgetmid, # low / mid / high max_tokens4096, tags[source:ag2], # default tags for retain )configure()的實現位于 hindsight-integrations/ag2/hindsight_ag2/config.py它把參數組裝為HindsightAG2Config數據類存入模塊級全局變量。值得注意的默認值hindsight_api_url默認指向生產環境https://api.hindsight.vectorize.ioapi_key未傳時自動回退讀取環境變量HINDSIGHT_API_KEYbudget默認midmax_tokens默認4096recall_tags_match默認any。配套的get_config()返回當前全局配置reset_config()將其重置為None測試用例在每個用例前后調用它們以保證隔離。按工具集覆蓋create_hindsight_tools構造函數參數優先于全局配置。全局配置適合「一次設置、處處使用」而按工具集覆蓋適合「同一進程里多個 Agent 需要不同記憶策略」的場景from hindsight_ag2 import create_hindsight_tools tools create_hindsight_tools( bank_idmy-bank, hindsight_api_urlhttp://localhost:8888, budgethigh, max_tokens8192, tags[team:alpha], )從源碼tools.py可以看到完整的生效優先級顯式參數 全局配置(configure) 內置默認值(mid / 4096 / any)例如effective_budget budget if budget is not None else (config.budget if config else mid)。test_config_budget_used_when_no_explicit與test_explicit_budget_overrides_config兩個測試分別驗證了「配置兜底」與「顯式覆蓋」兩條路徑。API Referencecreate_hindsight_tools 全部參數下表來自原文檔參數名與源碼簽名一一對應tools.py參數默認值說明bank_id必填Hindsight 記憶庫memory bankIDclientNone預配置的Hindsight客戶端優先級最高hindsight_api_url來自全局配置Hindsight API 地址api_key來自全局配置API 密鑰budgetmidrecall / reflect 的檢索預算low/mid/highmax_tokens4096recall 結果的最大 token 數tagsNoneretain 寫入記憶時附加的標簽recall_tagsNonerecall 檢索時用于過濾的標簽recall_tags_matchany標簽匹配模式any/all/any_strict/all_strictretain_metadataNoneretain 操作的元數據字典retain_document_idNoneretain 的文檔 ID用于分組 / 更新已有記憶recall_typesNone過濾的事實類型world / experience / observationrecall_include_entitiesFalserecall 結果是否包含實體信息reflect_contextNonereflect 操作的額外上下文reflect_max_tokens取max_tokensreflect 結果的最大 token 數reflect_response_schemaNone約束 reflect 輸出格式的 JSON Schemareflect_tags取recall_tagsreflect 使用的記憶過濾標簽reflect_tags_match取recall_tags_matchreflect 的標簽匹配模式include_retainTrue是否包含 retain 工具include_recallTrue是否包含 recall 工具include_reflectTrue是否包含 reflect 工具典型用法示例只做記憶存儲include_recallFalse, include_reflectFalse限定檢索范圍recall_tags[scope:user], recall_tags_matchall讓 reflect 輸出結構化 JSONreflect_response_schema{type: object, properties: {summary: {type: string}}}。對應行為均有測試覆蓋test_include_retain_only、test_recall_passes_tags、test_reflect_passes_max_tokens_and_response_schema等可在 hindsight-integrations/ag2/tests/test_tools.py 中查閱。GroupChat多個 Agent 共享一份記憶多 Agent 協作時讓 researcher 與 writer 讀寫同一個 bank即可實現「誰存的事實大家都能用」from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager, LLMConfig from hindsight_ag2 import register_hindsight_tools llm_config LLMConfig(api_typeopenai, modelgpt-4o-mini) with llm_config: researcher AssistantAgent(nameresearcher, system_messageYou research topics.) writer AssistantAgent(namewriter, system_messageYou write content.) executor UserProxyAgent(nameexecutor, human_input_modeNEVER) # All agents share the same memory bank for agent in [researcher, writer]: register_hindsight_tools(agent, executor, bank_idteam-memory) group_chat GroupChat(agents[researcher, writer, executor], messages[]) manager GroupChatManager(groupchatgroup_chat)核心在于所有 Agent 使用同一個bank_id。記憶的隔離與共享完全由 bank 維度控制這與 Hindsight 的多租戶模型一致不同團隊用不同 bank 互不干擾同一團隊共享一個 bank 實現知識復用。executorUserProxyAgent負責實際執行工具調用因此也被傳入register_hindsight_tools。手動注冊完全控制注冊方式register_hindsight_tools實際上只是「創建工具 自動注冊」的便捷封裝。需要完全掌控注冊過程時可以拆開做from hindsight_ag2 import create_hindsight_tools tools create_hindsight_tools( bank_idmy-bank, hindsight_api_urlhttp://localhost:8888, ) for tool_fn in tools: assistant.register_for_llm(descriptiontool_fn.__doc__)(tool_fn) user_proxy.register_for_execution()(tool_fn)這段代碼的語義對應register_hindsight_tools的源碼實現tools.py對每個工具函數調用agent.register_for_llm(descriptiontool_fn.__doc__)讓 LLM 側感知工具及其用途描述再調用executor.register_for_execution()讓執行側可以運行該函數。手動方式下你可以只為特定 Agent 注冊工具子集自定義description默認使用函數 docstring把工具注冊到任意兩個 agent 組合不限于 assistant/user_proxy。測試test_registers_all_tools驗證了默認會注冊 3 個工具且兩邊的注冊次數均為 3test_registers_with_docstring_descriptions驗證每個register_for_llm調用都帶上了非空 description。模塊導出與錯誤處理包的公共 API 集中在 hindsight-integrations/ag2/hindsight_ag2/init.py導出了from .config import HindsightAG2Config, configure, get_config, reset_config from .errors import HindsightError from .tools import create_hindsight_tools, register_hindsight_tools即configure/get_config/reset_config配置管理、HindsightAG2Config配置數據類、HindsightError統一異常、create_hindsight_tools/register_hindsight_tools工具工廠與注冊。錯誤處理方面三個工具對底層調用的異常處理模式完全一致見 tools.pyexcept Exception as e: logger.error(Retain failed: %s, e) raise HindsightError(fRetain failed: {e}) from e底層網絡錯誤、認證失敗、服務端異常都會被包裝成HindsightError拋出避免原始異常類型泄漏到 AG2 的工具執行層。測試中test_retain_raises_hindsight_error、test_recall_raises_hindsight_error、test_reflect_raises_hindsight_error分別用RuntimeError模擬底層故障驗證了這一行為??焖衮炞C與測試倉庫在 hindsight-integrations/ag2/tests/test_tools.py 中提供了完整的單元測試覆蓋工具默認數量與命名、按開關裁剪工具、Annotated類型提示、參數透傳tags/metadata/document_id/budget/max_tokens/types/include_entities/context/response_schema、配置回退與覆蓋、錯誤封裝、自動注冊行為等??寺}庫后可在包目錄運行cd hindsight-integrations/ag2 uv run pytest環境要求小結Python 3.10ag2 0.9.0一個正在運行的 Hindsight API 服務hindsight_api_url指向其地址本地默認常為http://localhost:8888認證需要時通過api_key參數或HINDSIGHT_API_KEY環境變量提供。滿足以上條件后你的 AG2 Agent 即可獲得「會學習」的長期記憶跨會話記住用戶、跨 Agent 共享知識、按需對歷史記憶進行推理與綜合?!久赓M下載鏈接】hindsightHindsight: Agent Memory That Learns項目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight創作聲明:本文部分內容由AI輔助生成(AIGC),僅供參考