ReMe是一個新興的AI Agent的記憶管理架構,它創新性地將 Agent 的記憶系統劃分為Personal Memory (個人記憶)、Task Memory(任務記憶)+Tool Memory(工具記憶)三大模組,旨在協助 Agent 在與使用者和任務的互動中,智能地抽取、複用和共用記憶。本教程將引導您完成基於 ReMe + AnalyticDB for MySQL 的 AI Agent 記憶管理實踐,內容涵蓋環境準備、服務啟動,以及三大核心記憶模組的詳細操作示範。
前提條件
在開始之前,請確保您已滿足以下條件:
已建立AnalyticDB for MySQL 版叢集,並確保其版本支援向量檢索功能(如餘弦相似性)。具體操作請參見:企業版、基礎版及湖倉版快速入門。
已擷取支援 AnalyticDB for MySQL 的 ReMe 架構版本。
說明請通過DingTalk聯絡阿里雲服務支援(DingTalk帳號:
x5v_rm8wqzuqf),擷取對應安裝包。已擷取模型服務 API Key,本教程使用阿里雲百鍊大模型服務平台,請開通服務並擷取 API Key,詳情請參考文檔:擷取API Key。
操作指南
環境準備
準備 AnalyticDB for MySQL。
在您的 AnalyticDB for MySQL 叢集中建立一個用於本教程的資料庫。
CREATE DATABASE reme;如果您計劃通過公網串連,請在 AnalyticDB for MySQL 控制台為叢集開啟公網訪問地址,並將您運行 Demo 環境的公網 IP 位址添加到白名單中。
安裝 ReMe 及依賴。
檢查 Python 環境:確保您的運行環境中已安裝 Python。本教程在 Python 3.12.2 版本下驗證通過。
# 使用Mac, 檢查Python版本, 如無請至官網安裝 https://www.python.org/ python3 --version # 使用Linux, 檢查Python版本, 如無使用 yum 進行安裝, sudo yum install python python --version安裝 ReMe 架構:解壓您擷取的 Mem0 架構檔案,並安裝必要的依賴庫。
# 解壓並安裝 flowllm unzip flowllm.zip cd flowllm pip install . # 解壓並安裝 ReMe unzip ReMe.zip cd Reme pip install .
配置並啟動
配置環境變數:
為了安全起見,建議將大模型的 API Key 配置為環境變數。
echo "export DASHSCOPE_API_KEY='<YOUR_DASHSCOPE_API_KEY>'" >> ~/.bashrc # 可選,預設為新加坡 echo "export DASHSCOPE_BASE_URL='https://dashscope-intl.aliyuncs.com/compatible-mode/v1'" >> ~/.bashrc source ~/.bashrc #檢查是否生效 echo $DASHSCOPE_API_KEY echo $DASHSCOPE_BASE_URL將AnalyticDB for MySQL的串連資訊配置至環境變數:
cd ReMe mv example.env .env編輯
.env檔案,將以下內容替換為您的實際配置資訊:FLOW_EMBEDDING_API_KEY=<YOUR_DASHSCOPE_API_KEY> FLOW_EMBEDDING_BASE_URL=<YOUR_DASHSCOPE_BASE_URL> FLOW_LLM_API_KEY=<YOUR_DASHSCOPE_API_KEY> FLOW_LLM_BASE_URL=<YOUR_DASHSCOPE_BASE_URL> ADB_HOST=<YOUR_ADB_HOST> ADB_PORT=3306 ADB_USER=<YOUR_ADB_USER> ADB_PASSWORD=<YOUR_ADB_PASSWORD> ADB_DATABASE=reme啟動 ReMe 服務:
執行以下命令啟動 ReMe 服務。
cd ReMe reme \ backend=http \ http.port=8002 \ llm.default.model_name=qwen3-max \ embedding_model.default.model_name=text-embedding-v4 \ vector_store.default.backend=aliyun_adb_mysql服務啟動成功後,控制台將顯示服務運行狀態。

啟動參數說明:
參數
說明
LLM
使用阿里雲百鍊平台的 qwen3-max 模型(可替換為其他支援的模型)
Embedder
使用阿里雲百鍊平台的 text-embedding-v4 模型,向量維度為 1536
vector_store
使用 AnalyticDB for MySQL 作為向量儲存後端
核心記憶操作示範
個人記憶
個人記憶用於儲存和檢索與特定使用者相關的靜態資訊,如姓名、職業、興趣愛好等。
運行 Demo:
cd ReMe python3 ./cookbook/simple_demo/use_personal_memory_demo.py運行效果分析:
建立對話並提取資訊:Demo 首先通過多輪對話輸入使用者的個人資訊(姓名、職業、興趣等)。ReMe 會自動從對話中抽取這些資訊並存入個人記憶。
記憶摘要與儲存:系統將提取的資訊歸納為結構化的記憶條目,包含關鍵詞、來源訊息和觀察類型等中繼資料,並持久化到AnalyticDB for MySQL中。
語義檢索驗證:最後,Demo 通過一系列自然語言提問來驗證記憶的檢索效果。
Demo 執行的檢索樣本及預期結果:
lhj@B-F21WMGFD-2205 ReMe % python3 ./cookbook/simple_demo/use_personal_memory_demo.py Clearing existing memories... {"answer": "", "messages": [], "success": true, "metadata": {"action_result": ""}} Creating conversation with personal information... Summarizing personal memories... { "answer": "", "messages": [], "success": true, "metadata": { "memory_list": [ { "workspace_id": "personal_memory_demo", "memory_id": "7f253fb5ab75402eaa84e23cee76ef52", "memory_type": "personal", "when_to_use": "John Smith, 28 years old, tech company, San Francisco", "content": "user's name is John Smith, age 28, works at a tech company in San Francisco", "score": 0.0, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "John Smith, 28 years old, tech company, San Francisco", "source_message": "My name is John Smith, I'm 28 years old, and I work at a tech company in San Francisco", "observation_type": "personal_info" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "d423370cfa5e47e2b53f5c77f4e2353e", "memory_type": "personal", "when_to_use": "software engineer, backend development, Python, Go", "content": "user is a software engineer specializing in backend development with Python and Go", "score": 0.0, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "software engineer, backend development, Python, Go", "source_message": "I'm a software engineer, mainly doing backend development using Python and Go", "observation_type": "personal_info" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "88474b71f7f24ac3961a349914407250", "memory_type": "personal", "when_to_use": "basketball, sci-fi movies, Dune Part 2", "content": "user enjoys playing basketball and watching sci-fi movies, recently watched Dune Part 2", "score": 0.0, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "basketball, sci-fi movies, Dune Part 2", "source_message": "I enjoy playing basketball and watching sci-fi movies. I recently watched Dune Part 2", "observation_type": "personal_info" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "9a8b4f81c66b4068b2e53146374ebc7a", "memory_type": "personal", "when_to_use": "cat, Shadow, pet", "content": "user has a 3-year-old cat named Shadow", "score": 0.0, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "cat, Shadow, pet", "source_message": "I have a cat named Shadow who is 3 years old", "observation_type": "personal_info" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "b72a6d0927e04ea7a2de9e28b4c008ec", "memory_type": "personal", "when_to_use": "Japanese cuisine, sushi, ramen", "content": "user is interested in Japanese cuisine, especially sushi and ramen", "score": 0.0, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "Japanese cuisine, sushi, ramen", "source_message": "I'm really interested in Japanese cuisine, especially sushi and ramen", "observation_type": "personal_info" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "f900b79060804a1587d59032c63f1e3c", "memory_type": "personal", "when_to_use": "Japan, Tokyo, Kyoto, trip", "content": "user is planning a trip to Tokyo and Kyoto in December 2025", "score": 0.0, "time_created": "2025-11-04 17:22:46", "time_modified": "2025-11-04 17:22:46", "author": "qwen3-max", "metadata": { "keywords": "Japan, Tokyo, Kyoto, trip", "time_info": "December 2025", "source_message": "I'm planning a trip to Japan next month, mainly to Tokyo and Kyoto", "observation_type": "personal_info_with_time" }, "target": "user", "reflection_subject": "" } ], "deleted_memory_ids": [], "update_result": { "deleted_count": 0, "inserted_count": 6 } } } Waiting for memories to be processed... Retrieving personal memories... Query: What's my name and age? { "answer": "user's name is John Smith, age 28, works at a tech company in San Francisco\nuser has a 3-year-old cat named Shadow\nuser is planning a trip to Tokyo and Kyoto in December 2025", "messages": [], "success": true, "metadata": { "memory_list": [ { "workspace_id": "personal_memory_demo", "memory_id": "7f253fb5ab75402eaa84e23cee76ef52", "memory_type": "personal", "when_to_use": "John Smith, 28 years old, tech company, San Francisco", "content": "user's name is John Smith, age 28, works at a tech company in San Francisco", "score": 0.038895229, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "John Smith, 28 years old, tech company, San Francisco", "source_message": "My name is John Smith, I'm 28 years old, and I work at a tech company in San Francisco", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "9a8b4f81c66b4068b2e53146374ebc7a", "memory_type": "personal", "when_to_use": "cat, Shadow, pet", "content": "user has a 3-year-old cat named Shadow", "score": 0.027221944999999997, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "cat, Shadow, pet", "source_message": "I have a cat named Shadow who is 3 years old", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "f900b79060804a1587d59032c63f1e3c", "memory_type": "personal", "when_to_use": "Japan, Tokyo, Kyoto, trip", "content": "user is planning a trip to Tokyo and Kyoto in December 2025", "score": 0.024106982, "time_created": "2025-11-04 17:22:46", "time_modified": "2025-11-04 17:22:46", "author": "qwen3-max", "metadata": { "keywords": "Japan, Tokyo, Kyoto, trip", "time_info": "December 2025", "source_message": "I'm planning a trip to Japan next month, mainly to Tokyo and Kyoto", "observation_type": "personal_info_with_time", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" } ] } } Query: What do I do for work? { "answer": "user's name is John Smith, age 28, works at a tech company in San Francisco\nuser is a software engineer specializing in backend development with Python and Go\nuser is planning a trip to Tokyo and Kyoto in December 2025", "messages": [], "success": true, "metadata": { "memory_list": [ { "workspace_id": "personal_memory_demo", "memory_id": "7f253fb5ab75402eaa84e23cee76ef52", "memory_type": "personal", "when_to_use": "John Smith, 28 years old, tech company, San Francisco", "content": "user's name is John Smith, age 28, works at a tech company in San Francisco", "score": 0.029179364000000003, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "John Smith, 28 years old, tech company, San Francisco", "source_message": "My name is John Smith, I'm 28 years old, and I work at a tech company in San Francisco", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "d423370cfa5e47e2b53f5c77f4e2353e", "memory_type": "personal", "when_to_use": "software engineer, backend development, Python, Go", "content": "user is a software engineer specializing in backend development with Python and Go", "score": 0.024785686, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "software engineer, backend development, Python, Go", "source_message": "I'm a software engineer, mainly doing backend development using Python and Go", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "f900b79060804a1587d59032c63f1e3c", "memory_type": "personal", "when_to_use": "Japan, Tokyo, Kyoto, trip", "content": "user is planning a trip to Tokyo and Kyoto in December 2025", "score": 0.017342727, "time_created": "2025-11-04 17:22:46", "time_modified": "2025-11-04 17:22:46", "author": "qwen3-max", "metadata": { "keywords": "Japan, Tokyo, Kyoto, trip", "time_info": "December 2025", "source_message": "I'm planning a trip to Japan next month, mainly to Tokyo and Kyoto", "observation_type": "personal_info_with_time", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" } ] } } Query: What are my hobbies? { "answer": "user is planning a trip to Tokyo and Kyoto in December 2025\nuser is a software engineer specializing in backend development with Python and Go\nuser is interested in Japanese cuisine, especially sushi and ramen", "messages": [], "success": true, "metadata": { "memory_list": [ { "workspace_id": "personal_memory_demo", "memory_id": "f900b79060804a1587d59032c63f1e3c", "memory_type": "personal", "when_to_use": "Japan, Tokyo, Kyoto, trip", "content": "user is planning a trip to Tokyo and Kyoto in December 2025", "score": 0.025223058, "time_created": "2025-11-04 17:22:46", "time_modified": "2025-11-04 17:22:46", "author": "qwen3-max", "metadata": { "keywords": "Japan, Tokyo, Kyoto, trip", "time_info": "December 2025", "source_message": "I'm planning a trip to Japan next month, mainly to Tokyo and Kyoto", "observation_type": "personal_info_with_time", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "d423370cfa5e47e2b53f5c77f4e2353e", "memory_type": "personal", "when_to_use": "software engineer, backend development, Python, Go", "content": "user is a software engineer specializing in backend development with Python and Go", "score": 0.024959816000000003, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "software engineer, backend development, Python, Go", "source_message": "I'm a software engineer, mainly doing backend development using Python and Go", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "b72a6d0927e04ea7a2de9e28b4c008ec", "memory_type": "personal", "when_to_use": "Japanese cuisine, sushi, ramen", "content": "user is interested in Japanese cuisine, especially sushi and ramen", "score": 0.020527664, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "Japanese cuisine, sushi, ramen", "source_message": "I'm really interested in Japanese cuisine, especially sushi and ramen", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" } ] } } Query: Do I have any pets? { "answer": "user has a 3-year-old cat named Shadow\nuser's name is John Smith, age 28, works at a tech company in San Francisco\nuser is planning a trip to Tokyo and Kyoto in December 2025", "messages": [], "success": true, "metadata": { "memory_list": [ { "workspace_id": "personal_memory_demo", "memory_id": "9a8b4f81c66b4068b2e53146374ebc7a", "memory_type": "personal", "when_to_use": "cat, Shadow, pet", "content": "user has a 3-year-old cat named Shadow", "score": 0.044214043, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "cat, Shadow, pet", "source_message": "I have a cat named Shadow who is 3 years old", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "7f253fb5ab75402eaa84e23cee76ef52", "memory_type": "personal", "when_to_use": "John Smith, 28 years old, tech company, San Francisco", "content": "user's name is John Smith, age 28, works at a tech company in San Francisco", "score": 0.026690182000000003, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "John Smith, 28 years old, tech company, San Francisco", "source_message": "My name is John Smith, I'm 28 years old, and I work at a tech company in San Francisco", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "f900b79060804a1587d59032c63f1e3c", "memory_type": "personal", "when_to_use": "Japan, Tokyo, Kyoto, trip", "content": "user is planning a trip to Tokyo and Kyoto in December 2025", "score": 0.023277275, "time_created": "2025-11-04 17:22:46", "time_modified": "2025-11-04 17:22:46", "author": "qwen3-max", "metadata": { "keywords": "Japan, Tokyo, Kyoto, trip", "time_info": "December 2025", "source_message": "I'm planning a trip to Japan next month, mainly to Tokyo and Kyoto", "observation_type": "personal_info_with_time", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" } ] } } Query: What are my travel plans? { "answer": "user is planning a trip to Tokyo and Kyoto in December 2025\nuser's name is John Smith, age 28, works at a tech company in San Francisco\nuser is a software engineer specializing in backend development with Python and Go", "messages": [], "success": true, "metadata": { "memory_list": [ { "workspace_id": "personal_memory_demo", "memory_id": "f900b79060804a1587d59032c63f1e3c", "memory_type": "personal", "when_to_use": "Japan, Tokyo, Kyoto, trip", "content": "user is planning a trip to Tokyo and Kyoto in December 2025", "score": 0.04186047600000001, "time_created": "2025-11-04 17:22:46", "time_modified": "2025-11-04 17:22:46", "author": "qwen3-max", "metadata": { "keywords": "Japan, Tokyo, Kyoto, trip", "time_info": "December 2025", "source_message": "I'm planning a trip to Japan next month, mainly to Tokyo and Kyoto", "observation_type": "personal_info_with_time", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "7f253fb5ab75402eaa84e23cee76ef52", "memory_type": "personal", "when_to_use": "John Smith, 28 years old, tech company, San Francisco", "content": "user's name is John Smith, age 28, works at a tech company in San Francisco", "score": 0.025156727000000004, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "John Smith, 28 years old, tech company, San Francisco", "source_message": "My name is John Smith, I'm 28 years old, and I work at a tech company in San Francisco", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "d423370cfa5e47e2b53f5c77f4e2353e", "memory_type": "personal", "when_to_use": "software engineer, backend development, Python, Go", "content": "user is a software engineer specializing in backend development with Python and Go", "score": 0.019123243, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "software engineer, backend development, Python, Go", "source_message": "I'm a software engineer, mainly doing backend development using Python and Go", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" } ] } } Query: What foods do I like? { "answer": "user is interested in Japanese cuisine, especially sushi and ramen\nuser is planning a trip to Tokyo and Kyoto in December 2025\nuser is a software engineer specializing in backend development with Python and Go", "messages": [], "success": true, "metadata": { "memory_list": [ { "workspace_id": "personal_memory_demo", "memory_id": "b72a6d0927e04ea7a2de9e28b4c008ec", "memory_type": "personal", "when_to_use": "Japanese cuisine, sushi, ramen", "content": "user is interested in Japanese cuisine, especially sushi and ramen", "score": 0.0316972, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "Japanese cuisine, sushi, ramen", "source_message": "I'm really interested in Japanese cuisine, especially sushi and ramen", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "f900b79060804a1587d59032c63f1e3c", "memory_type": "personal", "when_to_use": "Japan, Tokyo, Kyoto, trip", "content": "user is planning a trip to Tokyo and Kyoto in December 2025", "score": 0.022572586000000002, "time_created": "2025-11-04 17:22:46", "time_modified": "2025-11-04 17:22:46", "author": "qwen3-max", "metadata": { "keywords": "Japan, Tokyo, Kyoto, trip", "time_info": "December 2025", "source_message": "I'm planning a trip to Japan next month, mainly to Tokyo and Kyoto", "observation_type": "personal_info_with_time", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" }, { "workspace_id": "personal_memory_demo", "memory_id": "d423370cfa5e47e2b53f5c77f4e2353e", "memory_type": "personal", "when_to_use": "software engineer, backend development, Python, Go", "content": "user is a software engineer specializing in backend development with Python and Go", "score": 0.021622963000000002, "time_created": "2025-11-04 17:22:50", "time_modified": "2025-11-04 17:22:50", "author": "qwen3-max", "metadata": { "keywords": "software engineer, backend development, Python, Go", "source_message": "I'm a software engineer, mainly doing backend development using Python and Go", "observation_type": "personal_info", "match_event_flag": "0", "match_msg_flag": "0" }, "target": "user", "reflection_subject": "" } ] } }查詢問題
預期檢索結果
"What do I do for work?"
返回與工作相關的記憶(軟體工程師、Python/Go後端開發)。
"What are my hobbies?"
返回興趣愛好相關的記憶(日本料理、旅行計劃)。
"Do I have any pets?"
返回寵物相關的記憶(3歲的貓 Shadow)。
任務記憶
任務記憶用於記錄 Agent 在完成特定任務過程中積累的經驗和方法論,使其在處理未來相似任務時能夠複用歷史經驗,提升效率和品質。
運行 Demo:
cd ReMe python3 ./cookbook/simple_demo/use_task_memory_demo.py運行效果分析:
首次任務執行:Agent 接收“分析特斯拉公司”的任務,並將其拆解為公司概況、財務表現、技術創新等六個維度,然後通過搜尋工具收集資訊。
方法論提煉:任務完成後,系統從執行過程中提煉出可複用的方法論層面的經驗。例如:
如何將一個複雜的分析任務拆解為多個子任務。
如何通過兩階段檢索策略來填補資訊空白。
如何組織輸出結構以提升報告的可讀性。
記憶複用:當 Agent 接收到類似的新任務(如“分析小米公司”)時,系統會自動檢索並應用此前積累的任務經驗,產生一個增強後的、更優的查詢策略,從而產出更全面、結構更合理的分析結果。
Demo 執行的檢索樣本及預期結果:
=== Task Memory Demo === 1. Deleting workspace... Workspace 'test_workspace' deleted successfully 2. Running agent with first query... Agent response: I have gathered comprehensive information about Xiaomi Corporation through multiple targeted searches. Here's a summary of the analysis: 1. **Company Overview**: Xiaomi Corporation is a Chinese multinational technology company founded in 2010, known for its smartphones, smart home devices, and IoT ecosystem. It operates globally with a strong presence in Asia, Europe, and Latin America. 2. **Financial Performance (2024)**: Xiaomi reported robust financial results in 2024, with significant revenue growth driven by smartphone sales and expansion in its Internet of Things (IoT) product lines. The company maintained profitability despite global economic challenges. 3. **Product Portfolio & Innovations**: Xiaomi continues to innovate in areas such as high-performance smartphones (e.g., Mi series), foldable phones, electric vehicles (Xiaomi SU7), and an expanding range of smart home products integrated into its MIUI ecosystem. 4. **Market Position**: Xiaomi remains one of the top five global smartphone manufacturers, particularly strong in emerging markets. Its competitive pricing strategy and focus on value-for-money products have helped it gain market share. 5. **Challenges & Risks (2025)**: Key challenges include increasing competition from brands like Samsung, Apple, and Oppo, supply chain volatility, geopolitical tensions affecting international operations, and the need to sustain innovation in the EV sector. 6. **Recent Developments (2025)**: In early 2025, Xiaomi launched its new electric vehicle model, the SU7 Pro, which received positive reviews. The company also expanded its AI-powered smart home platform and strengthened partnerships in Southeast Asia and Europe. This analysis provides a holistic view of Xiaomi Corporation’s current status, strategic direction, and future outlook. Messages saved to messages.jsonl 3. Running memory-augmented agent workflow... --- Building memories with query: 'Analyze the company Tesla.' --- Agent response: I have gathered comprehensive information about Tesla through multiple search queries. Here is a summary of the key aspects: 1. **Company Overview**: Tesla, Inc. is an American electric vehicle and clean energy company founded in 2003 by Martin Eberhard and Marc Tarpenning, with Elon Musk playing a pivotal role since 2004. The company designs, manufactures, and sells electric vehicles (EVs), solar panels, and energy storage systems. 2. **Financial Performance (2024)**: Tesla reported strong financial results in 2024, with increased revenue driven by higher vehicle deliveries and growth in its energy products segment. However, the company faced challenges related to production scaling and global economic conditions affecting demand. 3. **Recent Innovations and Technology Developments**: Tesla continues to lead in EV technology, including advancements in battery efficiency, autonomous driving (Full Self-Driving or FSD), and the development of next-generation platforms like the "Tesla Model 2" (rumored). The company also expanded its AI capabilities through projects like Optimus (humanoid robot). 4. **CEO Elon Musk's Recent Activities**: Elon Musk has been actively involved in public discussions about AI ethics, infrastructure projects (e.g., Hyperloop), and the future of transportation. He has also engaged in high-profile social media interactions and strategic decisions impacting Tesla’s direction. 5. **Market Position and Competition**: Tesla remains a dominant player in the global EV market, though it faces increasing competition from traditional automakers (e.g., Ford, Volkswagen) and new entrants (e.g., BYD, Rivian). Despite this, Tesla maintains a strong brand presence and technological edge. 6. **Environmental Impact and Sustainability Initiatives**: Tesla is committed to reducing carbon emissions through its products and operations. The company emphasizes sustainable manufacturing practices, renewable energy integration, and recycling programs for batteries. This analysis provides a well-rounded view of Tesla’s current status, challenges, and future outlook. --- Summarizing conversation to create memories --- Memory list: [{'workspace_id': 'test_workspace', 'memory_id': '4a0f9408ee2b4cdda721d6bfed8a0a24', 'memory_type': 'task', 'when_to_use': 'When analyzing a complex, multi-faceted entity like a major corporation that requires coverage across business, financial, technological, leadership, competitive, and sustainability dimensions.', 'content': "The agent decomposed the broad request 'Analyze the company Tesla' into six distinct thematic subtasks (overview, financials, innovation, leadership, competition, sustainability) and executed parallel and sequential tool calls to gather targeted information. This structured decomposition ensured comprehensive coverage without redundancy, while iterative querying allowed refinement based on emerging context.", 'score': 0.85, 'time_created': '2025-11-04 19:35:23', 'time_modified': '2025-11-04 19:35:23', 'author': 'qwen3-max', 'metadata': {'when_to_use': 'When analyzing a complex, multi-faceted entity like a major corporation that requires coverage across business, financial, technological, leadership, competitive, and sustainability dimensions.', 'experience': "The agent decomposed the broad request 'Analyze the company Tesla' into six distinct thematic subtasks (overview, financials, innovation, leadership, competition, sustainability) and executed parallel and sequential tool calls to gather targeted information. This structured decomposition ensured comprehensive coverage without redundancy, while iterative querying allowed refinement based on emerging context.", 'tags': ['problem decomposition', 'multi-perspective analysis', 'corporate analysis', 'iterative search'], 'confidence': 0.95, 'step_type': 'reasoning', 'tools_used': ['dashscope_search']}}, {'workspace_id': 'test_workspace', 'memory_id': '51ddcd1b679e45fc86aacd5982a1cc54', 'memory_type': 'task', 'when_to_use': 'When initial information gathering is insufficient to form a holistic answer, and additional contextual layers (e.g., leadership impact or market dynamics) are needed to enrich understanding.', 'content': 'After an initial round of three searches, the agent proactively identified gaps—specifically around leadership influence and competitive landscape—and issued a second wave of targeted queries. This adaptive two-phase retrieval strategy demonstrates effective metacognition: assessing coverage completeness and filling critical knowledge gaps before synthesis.', 'score': 0.85, 'time_created': '2025-11-04 19:35:23', 'time_modified': '2025-11-04 19:35:23', 'author': 'qwen3-max', 'metadata': {'when_to_use': 'When initial information gathering is insufficient to form a holistic answer, and additional contextual layers (e.g., leadership impact or market dynamics) are needed to enrich understanding.', 'experience': 'After an initial round of three searches, the agent proactively identified gaps—specifically around leadership influence and competitive landscape—and issued a second wave of targeted queries. This adaptive two-phase retrieval strategy demonstrates effective metacognition: assessing coverage completeness and filling critical knowledge gaps before synthesis.', 'tags': ['adaptive querying', 'gap analysis', 'context enrichment', 'sequential tool use'], 'confidence': 0.9, 'step_type': 'decision', 'tools_used': ['dashscope_search']}}, {'workspace_id': 'test_workspace', 'memory_id': '79e7bb2e055640f3975c12c719e10092', 'memory_type': 'task', 'when_to_use': 'When synthesizing information from multiple heterogeneous sources into a coherent, structured summary for user consumption.', 'content': 'The final response organized findings into six clearly labeled thematic sections that directly mirrored the query decomposition strategy. This alignment between information-gathering structure and output format enhanced clarity, reduced cognitive load, and ensured all subtasks were visibly addressed—demonstrating strong traceability from intent to delivery.', 'score': 0.85, 'time_created': '2025-11-04 19:35:23', 'time_modified': '2025-11-04 19:35:23', 'author': 'qwen3-max', 'metadata': {'when_to_use': 'When synthesizing information from multiple heterogeneous sources into a coherent, structured summary for user consumption.', 'experience': 'The final response organized findings into six clearly labeled thematic sections that directly mirrored the query decomposition strategy. This alignment between information-gathering structure and output format enhanced clarity, reduced cognitive load, and ensured all subtasks were visibly addressed—demonstrating strong traceability from intent to delivery.', 'tags': ['structured synthesis', 'thematic organization', 'answer coherence', 'user-centric summarization'], 'confidence': 0.85, 'step_type': 'action', 'tools_used': []}}] Memory saved to memory.jsonl --- Retrieving memories for query: 'Analyze Xiaomi Corporation' --- Retrieved memory: To effectively analyze Xiaomi Corporation, adopt a structured, multi-dimensional approach that systematically examines its core business segments, financial performance, technological innovation, leadership strategy, competitive positioning, and sustainability initiatives. Begin by decomposing the analysis into these six thematic pillars to ensure comprehensive coverage without redundancy. Use parallel and sequential information-gathering methods to collect targeted data on each dimension—starting with Xiaomi’s product ecosystem (smartphones, IoT, EVs), revenue streams, and geographic footprint. If initial findings lack depth in critical areas such as leadership vision or competitive dynamics in key markets like China, India, or Europe, proactively issue follow-up queries to fill those gaps. This adaptive two-phase retrieval ensures a holistic understanding before synthesis. Finally, organize the output into clearly labeled sections that mirror the original analytical framework, creating a coherent, traceable narrative that directly addresses the user’s request while minimizing cognitive load. This method—proven effective for complex corporate analyses like Tesla—ensures actionable, well-rounded insights tailored to Xiaomi’s unique position at the intersection of consumer electronics, smart hardware, and emerging mobility. --- Running agent with memory-augmented query --- Augmented query: To effectively analyze Xiaomi Corporation, adopt a structured, multi-dimensional approach that systematically examines its core business segments, financial performance, technological innovation, leadership strategy, competitive positioning, and sustainability initiatives. Begin by decomposing the analysis into these six thematic pillars to ensure comprehensive coverage without redundancy. Use parallel and sequential information-gathering methods to collect targeted data on each dimension—starting with Xiaomi’s product ecosystem (smartphones, IoT, EVs), revenue streams, and geographic footprint. If initial findings lack depth in critical areas such as leadership vision or competitive dynamics in key markets like China, India, or Europe, proactively issue follow-up queries to fill those gaps. This adaptive two-phase retrieval ensures a holistic understanding before synthesis. Finally, organize the output into clearly labeled sections that mirror the original analytical framework, creating a coherent, traceable narrative that directly addresses the user’s request while minimizing cognitive load. This method—proven effective for complex corporate analyses like Tesla—ensures actionable, well-rounded insights tailored to Xiaomi’s unique position at the intersection of consumer electronics, smart hardware, and emerging mobility. User Question: Analyze Xiaomi Corporation Agent response: Based on the comprehensive analysis of Xiaomi Corporation, here is a structured overview across key dimensions: ### 1. **Business Segments & Product Ecosystem** Xiaomi operates through three core segments: - **Smartphones**: A cornerstone of its business, with a strong global presence. - **IoT and Smart Home Devices**: A rapidly growing segment including wearables, home appliances, and smart lighting. Xiaomi’s ecosystem approach integrates hardware, software, and services. - **Electric Vehicles (EVs)**: A strategic new venture launched in 2021, with the Mi EV model entering production. This marks a significant pivot into mobility. ### 2. **Financial Performance & Revenue Streams** In 2024, Xiaomi reported robust financial performance: - Revenue growth driven by smartphone sales and IoT expansion. - Diversified revenue streams: smartphones (~50%), IoT (~30%), and EVs (~20% projected). - Strong profitability in key markets like China and India, with increasing margins from high-margin IoT products. ### 3. **Technological Innovation** Xiaomi is investing heavily in R&D: - Development of proprietary AI chips (e.g., Surge series) to enhance performance in smartphones and IoT devices. - Focus on AI integration across its ecosystem, including voice assistants and smart home automation. - Advancements in battery technology and energy efficiency for both mobile and EV platforms. ### 4. **Leadership Strategy & Vision** Under CEO Lei Jun, Xiaomi’s strategy emphasizes: - "Internet + Hardware + Software" integration to create seamless user experiences. - Long-term vision of building a global smart lifestyle ecosystem. - Strategic focus on innovation, cost-efficiency, and rapid market entry. ### 5. **Competitive Positioning** Xiaomi holds strong positions in key markets: - **China**: One of the top 3 smartphone vendors, leveraging brand loyalty and affordable premium offerings. - **India**: Market leader in smartphones, with aggressive pricing and extensive retail networks. - **Europe**: Rapidly gaining share, particularly in mid-to-high-end segments, due to design quality and value-for-money propositions. ### 6. **Sustainability & Future Initiatives** Xiaomi is advancing sustainability efforts: - Commitment to carbon neutrality goals by 2030. - Eco-friendly materials in packaging and product design. - EV development aligns with global green mobility trends, with zero-emission vehicles under development. ### Additional Insights - **Global Expansion**: Aggressive international rollout via online platforms and local partnerships, especially in Southeast Asia, Latin America, and Europe. - **Supply Chain**: Collaborates with leading manufacturers (e.g., Foxconn, BYD) while maintaining control over core R&D and design. - **Consumer Loyalty**: High customer retention due to ecosystem lock-in and consistent product quality. Xiaomi’s future success hinges on its ability to scale EV production, deepen AI integration, and maintain its competitive edge in emerging markets. 4. Dumping memory to disk... Memory dumped to ./ 5. Loading memory from disk... Memory loaded from ./ === Demo Complete ===
工具記憶
工具記憶用於記錄 Agent 使用各類工具(API、函數等)的經驗,包括工具的核心功能、成功模式、常見問題和最佳實務。
運行 Demo:
cd ReMe python3 ./cookbook/simple_demo/use_tool_memory_demo.py運行效果分析:
類比工具調用:Demo 首先類比了 70 條工具調用記錄,涵蓋
database_query、file_processor、web_search三種工具。產生經驗摘要:系統自動分析這些調用記錄,為每種工具產生一份詳細的使用經驗摘要。包含以下關鍵維度:
維度
說明
核心功能
工具的主要用途和適用情境。
成功模式
工具調用成功的典型條件和參數組合。
常見問題
工具調用失敗的常見原因分析。
最佳實務
使用建議和注意事項。
統計資訊
成功率、平均耗時、平均 Token 消耗等量化指標。
Demo 執行的檢索樣本及預期結果:
2025-11-04 19:39:10.101 | INFO | flowllm.utils.common_utils:load_env:64 - load env_path=.env set FLOW_APP_NAME=ReMe [1] Cleaning workspace... ✓ Workspace 'test_tool_memory_workspace' deleted [2] Adding mock tool call results... [ADD] 70 results for 3 tools: database_query, file_processor, web_search ✓ Added successfully, created/updated 3 tool memories [3] Summarizing tool memories... [SUMMARIZE] web_search,database_query,file_processor ✓ Summarized 3 tool memories ============================================================ Tool: web_search ============================================================ 1. **Core Function**: The web_search tool retrieves authoritative technical documentation, tutorials, and best practices for specific developer-focused queries (e.g., "GraphQL advantages", "OAuth2 flow"). Use it when seeking reliable, in-depth technical information. 2. **Success Patterns**: High-quality results occur with precise, domain-specific queries (e.g., "JWT authentication", "MongoDB schema design") combined with valid parameters like language="en" and filter="technical_docs". These consistently yield 14–19 relevant, authoritative sources. 3. **Common Issues**: Queries fail or return minimal results when: (a) the query is overly generic (e.g., "test query 1"), (b) an unsupported language (e.g., "unknown") is specified, or (c) the request times out (10s cap). Nonsensical queries correctly return zero results but are handled gracefully. 4. **Best Practices**: - Always use specific, technical keywords that reflect real developer tasks or concepts. - Validate language parameters (use "en" or other supported codes) and avoid placeholder or invalid values. ## Statistics - **Success Rate**: 75.00% - **Average Score**: 0.350 - **Average Time Cost**: 4.300s - **Average Token Cost**: 96.0 ============================================================ Tool: database_query ============================================================ 1. **Core Function**: Executes SQL-like queries on specified tables, returning matching rows up to a user-defined limit. Use when retrieving filtered, ordered, or pattern-matched data from known tables. 2. **Success Patterns**: Queries succeed when using valid table/column names, clear WHERE conditions (e.g., id > N), and reasonable limits. Results are reliable when row counts respect the limit or truthfully reflect available data (even if fewer rows exist). 3. **Common Issues**: Frequent failures occur when: (a) returned rows exceed the specified limit—indicating improper limit enforcement; (b) invalid table/column names cause errors; or (c) results omit actual data rows, returning only metadata. 4. **Best Practices**: - Always verify table and column names match the schema to avoid execution errors. - Treat returned row counts skeptically if they exceed your limit—reformulate or validate the query. - For large datasets with LIKE or sorting, expect performance notes; consider indexing suggestions provided in successful responses. ## Statistics - **Success Rate**: 80.00% - **Average Score**: 0.650 - **Average Time Cost**: 2.157s - **Average Token Cost**: 55.8 ============================================================ Tool: file_processor ============================================================ 1. **Core Function**: The file_processor reads structured and unstructured files (CSV, JSON, XML, TXT, PDF) and returns metadata—file size and record count—without exposing raw content. Use it to quickly assess file contents before deeper processing. 2. **Success Patterns**: Works reliably on files under ~500KB across all supported formats when valid paths and encodings (e.g., UTF-8) are provided. Consistently returns useful metadata for small-to-medium files in under 3 seconds. 3. **Common Issues**: Fails silently on large files (>500KB–1MB), returning only a size warning without metadata or content—despite marking the call as "successful." Also fails if the file path is invalid, though it correctly reports this error. 4. **Best Practices**: - Pre-check file size; avoid using file_processor on files likely exceeding 500KB. - Always validate file paths before calling to prevent "file not found" errors. - Use UTF-8 encoding for text-based formats unless otherwise required. ## Statistics - **Success Rate**: 83.33% - **Average Score**: 0.722 - **Average Time Cost**: 7.058s - **Average Token Cost**: 173.6 [4] Retrieving tool memories... [RETRIEVE] web_search ✓ Retrieved 1 memories Tool: web_search Calls: 30 ------------------------------------------------------------ 1. **Core Function**: The web_search tool retrieves authoritative technical documentation, tutorials, and best practices for specific developer-focused queries (e.g., "GraphQL advantages", "OAuth2 flow"). Use it when seeking reliable, in-depth technical information. 2. **Success Patterns**: High-quality results occur with precise, domain-specific queries (e.g., "JWT authentication", "MongoDB schema design") combined with valid parameters like language="en" and filter="technical_docs". These consistently yield 14–19 relevant, authoritative sources. 3. **Common Issues**: Queries fail or return minimal results when: (a) the query is overly generic (e.g., "test query 1"), (b) an unsupported language (e.g., "unknown") is specified, or (c) the request times out (10s cap). Nonsensical queries correctly return zero results but are handled gracefully. 4. **Best Practices**: - Always use specific, technical keywords that reflect real developer tasks or concepts. - Validate language parameters (use "en" or other supported codes) and avoid placeholder or invalid values. ## Statistics - **Success Rate**: 75.00% - **Average Score**: 0.350 - **Average Time Cost**: 4.300s - **Average Token Cost**: 96.0 ✓ Saved to tool_memory.json [RETRIEVE] database_query ✓ Retrieved 1 memories Tool: database_query Calls: 22 ------------------------------------------------------------ 1. **Core Function**: Executes SQL-like queries on specified tables, returning matching rows up to a user-defined limit. Use when retrieving filtered, ordered, or pattern-matched data from known tables. 2. **Success Patterns**: Queries succeed when using valid table/column names, clear WHERE conditions (e.g., id > N), and reasonable limits. Results are reliable when row counts respect the limit or truthfully reflect available data (even if fewer rows exist). 3. **Common Issues**: Frequent failures occur when: (a) returned rows exceed the specified limit—indicating improper limit enforcement; (b) invalid table/column names cause errors; or (c) results omit actual data rows, returning only metadata. 4. **Best Practices**: - Always verify table and column names match the schema to avoid execution errors. - Treat returned row counts skeptically if they exceed your limit—reformulate or validate the query. - For large datasets with LIKE or sorting, expect performance notes; consider indexing suggestions provided in successful responses. ## Statistics - **Success Rate**: 80.00% - **Average Score**: 0.650 - **Average Time Cost**: 2.157s - **Average Token Cost**: 55.8 ✓ Saved to tool_memory.json [RETRIEVE] file_processor ✓ Retrieved 1 memories Tool: file_processor Calls: 18 ------------------------------------------------------------ 1. **Core Function**: The file_processor reads structured and unstructured files (CSV, JSON, XML, TXT, PDF) and returns metadata—file size and record count—without exposing raw content. Use it to quickly assess file contents before deeper processing. 2. **Success Patterns**: Works reliably on files under ~500KB across all supported formats when valid paths and encodings (e.g., UTF-8) are provided. Consistently returns useful metadata for small-to-medium files in under 3 seconds. 3. **Common Issues**: Fails silently on large files (>500KB–1MB), returning only a size warning without metadata or content—despite marking the call as "successful." Also fails if the file path is invalid, though it correctly reports this error. 4. **Best Practices**: - Pre-check file size; avoid using file_processor on files likely exceeding 500KB. - Always validate file paths before calling to prevent "file not found" errors. - Use UTF-8 encoding for text-based formats unless otherwise required. ## Statistics - **Success Rate**: 83.33% - **Average Score**: 0.722 - **Average Time Cost**: 7.058s - **Average Token Cost**: 173.6 ✓ Saved to tool_memory.json [5] Testing memory persistence... ✓ Memory dumped to ./ ✓ Memory loaded from ./ ============================================================ DEMO COMPLETE ✓ ============================================================
進階實踐:AppWorld 對比實驗(可選)
ReMe 的 cookbook 目錄下提供了基於 AppWorld 等基準測試集的對比實驗,用於量化驗證記憶增強對 Agent 效能的提升效果。
該實驗預計已耗用時間較長,且會消耗較多的大模型服務 Token,請根據實際情況決定是否運行。
步驟一:準備實驗環境。
# 建立 conda 環境 conda create -p ./appworld-env python==3.12 conda activate ./appworld-env # 安裝依賴 pip install -r requirements.txt # 安裝 AppWorld 並下載資料集 pip install appworld appworld install appworld download data步驟二:載入記憶庫。
curl -X POST "http://0.0.0.0:8002/vector_store" \ -H "Content-Type: application/json" \ -d '{ "workspace_id": "appworld", "action": "load", "path": "./docs/library" }'步驟三:運行實驗指令碼。
python run_appworld.py該指令碼將在開發資料集上運行 AppWorld 任務,對比使用 ReMe 記憶(
use_memory=True)和不使用記憶兩種模式下 Agent 的表現。主要配置參數:
參數
說明
預設值
max_workers並行背景工作執行緒數
6
num_runs每個任務的重複運行次數
4
use_memory是否啟用 ReMe 記憶庫
-
步驟四:統計實驗結果。
python run_exp_statistic.py實驗指標說明:
指標
說明
best@1單次啟動並執行平均效能
best@k取 k 次運行中的最佳效能並求平均,k 值越高越能反映潛力上限
實驗結果檔案儲存在
./exp_result/目錄下,統計摘要匯出至experiment_summary.csv。