{"product_id":"memory-management-quản-ly-bộ-nhớ-dai-hạn-cho-claude-agents","title":"Memory Management — Quản lý bộ nhớ dài hạn cho Claude agents","description":"\n\u003cp\u003eKhi xây dựng AI agents hoạt động liên tục, bạn sẽ nhanh chóng gặp hai thách thức không thể tránh khỏi: \u003cstrong\u003emất kiến thức giữa các sessions\u003c\/strong\u003e và \u003cstrong\u003econtext window bị đầy\u003c\/strong\u003e trong conversations dài. Bài viết này giới thiệu các giải pháp chính thức từ Anthropic cho cả hai vấn đề.\u003c\/p\u003e\n\n\u003ch2\u003eHai thách thức cốt lõi của long-running agents\u003c\/h2\u003e\n\n\u003ch3\u003eThách thức 1: Mất patterns giữa sessions\u003c\/h3\u003e\n\u003cp\u003eHãy tưởng tượng bạn có một Code Review Agent. Mỗi ngày nó review hàng chục pull requests cho team của bạn. Nhưng mỗi lần khởi động mới, nó \"quên\" hết mọi thứ:\u003c\/p\u003e\n\u003cul\u003e\n  \u003cli\u003eTeam này ưu tiên readable code hơn clever code\u003c\/li\u003e\n  \u003cli\u003eProject dùng snake_case cho Python variables\u003c\/li\u003e\n  \u003cli\u003eSecurity reviews cần đặc biệt nghiêm ngặt với authentication code\u003c\/li\u003e\n  \u003cli\u003eJunior developer X đang học và cần feedback chi tiết hơn\u003c\/li\u003e\n\u003c\/ul\u003e\n\n\u003cp\u003eAgent phải \"học lại\" từ đầu mỗi session — hoặc bạn phải nhét toàn bộ context đó vào system prompt, làm nó ngày càng phình to.\u003c\/p\u003e\n\n\u003ch3\u003eThách thức 2: Context window bị đầy\u003c\/h3\u003e\n\u003cp\u003eVới conversations dài — debugging session kéo dài nhiều giờ, project planning qua nhiều vòng — context window sẽ đầy. Lúc đó bạn phải chọn: truncate (mất thông tin cũ) hay crash.\u003c\/p\u003e\n\n\u003ch2\u003eGiải pháp 1: Memory Tool cho cross-session learning\u003c\/h2\u003e\n\n\u003cp\u003eAnthropic cung cấp \u003cstrong\u003ememory tool\u003c\/strong\u003e (tên chính thức: \u003ccode\u003ememory_20250818\u003c\/code\u003e) — một file-based memory system cho phép Claude ghi nhớ thông tin quan trọng giữa các conversations.\u003c\/p\u003e\n\n\u003ch3\u003eCách hoạt động\u003c\/h3\u003e\n\u003cp\u003eMemory tool sử dụng một file văn bản đặt tại thư mục \u003ccode\u003e\/memories\u003c\/code\u003e. Claude có thể đọc và ghi file này giữa các conversations. Đây là \u003cstrong\u003eclient-side implementation\u003c\/strong\u003e — bạn quản lý file này trên server của mình, không phải Anthropic.\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eimport anthropic\n\nclient = anthropic.Anthropic()\n\n# Khởi tạo memory tool\ndef create_agent_with_memory(memory_file_path):\n    # Đọc memories hiện tại\n    try:\n        with open(memory_file_path, 'r', encoding='utf-8') as f:\n            current_memories = f.read()\n    except FileNotFoundError:\n        current_memories = \"No memories yet.\"\n\n    system_prompt = f\"\"\"You are a Code Review Agent for a Vietnamese software team.\n\nCURRENT MEMORIES:\n{current_memories}\n\nUse your memory to provide consistent, personalized reviews.\nWhen you learn something important about the team's preferences,\ncoding standards, or individual developers, save it to memory.\"\"\"\n\n    return system_prompt\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch3\u003eDefine memory tool\u003c\/h3\u003e\n\u003cpre\u003e\u003ccode\u003eMEMORY_TOOL = {\n    \"name\": \"memory_20250818\",\n    \"description\": \"\"\"Save important information to long-term memory.\n    Use this when you learn:\n    - Team coding preferences and standards\n    - Project-specific conventions\n    - Individual developer patterns\n    - Recurring issues to watch for\"\"\",\n    \"input_schema\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"action\": {\n                \"type\": \"string\",\n                \"enum\": [\"save\", \"clear\"],\n                \"description\": \"save: append to memory. clear: reset memory.\"\n            },\n            \"content\": {\n                \"type\": \"string\",\n                \"description\": \"The information to save to memory.\"\n            }\n        },\n        \"required\": [\"action\", \"content\"]\n    }\n}\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch3\u003eXử lý memory tool calls\u003c\/h3\u003e\n\u003cpre\u003e\u003ccode\u003edef handle_memory_tool(tool_input, memory_file_path):\n    action = tool_input[\"action\"]\n    content = tool_input[\"content\"]\n\n    if action == \"save\":\n        # Append to memory file\n        with open(memory_file_path, 'a', encoding='utf-8') as f:\n            from datetime import datetime\n            timestamp = datetime.now().strftime(\"%Y-%m-%d\")\n            f.write(f\"\n[{timestamp}] {content}\")\n        return {\"success\": True, \"message\": \"Memory saved.\"}\n\n    elif action == \"clear\":\n        with open(memory_file_path, 'w', encoding='utf-8') as f:\n            f.write(\"\")\n        return {\"success\": True, \"message\": \"Memory cleared.\"}\n\n    return {\"success\": False, \"message\": \"Unknown action.\"}\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eDemo: Code Review Agent với long-term memory\u003c\/h2\u003e\n\n\u003cp\u003eDưới đây là agent hoàn chỉnh có khả năng nhớ preferences của team qua nhiều sessions:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eimport anthropic\nimport json\nimport os\n\nclient = anthropic.Anthropic()\nMEMORY_FILE = \"\/memories\/code_review_agent.txt\"\nos.makedirs(\"\/memories\", exist_ok=True)\n\ndef run_code_review_session(code_to_review, feedback=\"\"):\n    \"\"\"Chạy một session review với memory persistence.\"\"\"\n\n    # Load memories\n    try:\n        with open(MEMORY_FILE, 'r') as f:\n            memories = f.read() or \"No prior memories.\"\n    except FileNotFoundError:\n        memories = \"No prior memories.\"\n\n    system = f\"\"\"You are a Code Review Agent for a Vietnamese dev team.\n\nLONG-TERM MEMORIES:\n{memories}\n\nReview code thoroughly. When you notice consistent patterns\nabout team preferences, save them to memory for future sessions.\nAlways respond in Vietnamese.\"\"\"\n\n    messages = [{\"role\": \"user\", \"content\": code_to_review}]\n    if feedback:\n        messages.append({\"role\": \"user\", \"content\": f\"Team feedback: {feedback}\"})\n\n    # Agentic loop\n    while True:\n        response = client.messages.create(\n            model=\"claude-opus-4-5\",\n            max_tokens=2048,\n            system=system,\n            tools=[MEMORY_TOOL],\n            messages=messages\n        )\n\n        if response.stop_reason == \"end_turn\":\n            # Extract text response\n            for block in response.content:\n                if hasattr(block, 'text'):\n                    return block.text\n            break\n\n        elif response.stop_reason == \"tool_use\":\n            messages.append({\"role\": \"assistant\", \"content\": response.content})\n            tool_results = []\n\n            for block in response.content:\n                if block.type == \"tool_use\":\n                    result = handle_memory_tool(block.input, MEMORY_FILE)\n                    tool_results.append({\n                        \"type\": \"tool_result\",\n                        \"tool_use_id\": block.id,\n                        \"content\": json.dumps(result)\n                    })\n\n            messages.append({\"role\": \"user\", \"content\": tool_results})\n        else:\n            break\n\n    return \"Review completed.\"\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch3\u003eTest qua nhiều sessions\u003c\/h3\u003e\n\u003cpre\u003e\u003ccode\u003e# Session 1: Review code lần đầu\ncode_sample = \"\"\"\ndef getUserData(userId):\n    result = db.query(f\"SELECT * FROM users WHERE id = {userId}\")\n    return result\n\"\"\"\n\nreview = run_code_review_session(\n    code_sample,\n    feedback=\"Team note: chúng tôi dùng snake_case và rất coi trọng SQL injection prevention\"\n)\nprint(\"Session 1:\", review)\n\n# Session 2: Agent đã nhớ preferences từ session trước\ncode_sample_2 = \"\"\"\ndef calculateTotalPrice(items, discount):\n    total = sum([item.price for item in items])\n    return total * (1 - discount)\n\"\"\"\n\nreview2 = run_code_review_session(code_sample_2)\nprint(\"Session 2:\", review2)\n# Agent sẽ tự động check SQL injection và naming conventions\n# vì đã lưu preferences từ session trước\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eGiải pháp 2: Context Editing — Auto-compaction strategies\u003c\/h2\u003e\n\n\u003cp\u003eKhi conversation dài, bạn cần chiến lược xử lý context thông minh. Có ba pattern phổ biến:\u003c\/p\u003e\n\n\u003ch3\u003ePattern 1: Sliding Window\u003c\/h3\u003e\n\u003cp\u003eGiữ N messages gần nhất, bỏ messages cũ:\u003c\/p\u003e\n\u003cpre\u003e\u003ccode\u003edef sliding_window_messages(messages, max_messages=20):\n    \"\"\"Giữ system + N messages gần nhất.\"\"\"\n    if len(messages) \u0026lt;= max_messages:\n        return messages\n    # Luôn giữ system message đầu tiên nếu có\n    return messages[-max_messages:]\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch3\u003ePattern 2: Summary-based compaction\u003c\/h3\u003e\n\u003cp\u003eTóm tắt messages cũ thay vì xóa hoàn toàn:\u003c\/p\u003e\n\u003cpre\u003e\u003ccode\u003edef compact_with_summary(messages, threshold=15000):\n    \"\"\"Khi tokens gần đầy, tóm tắt conversation cũ.\"\"\"\n    # Ước tính token count (4 chars ~ 1 token)\n    total_chars = sum(\n        len(str(m.get('content', '')))\n        for m in messages\n    )\n\n    if total_chars \u0026lt; threshold * 4:\n        return messages  # Chưa cần compact\n\n    # Tóm tắt nửa đầu conversation\n    old_messages = messages[:-5]  # Giữ 5 messages gần nhất\n    recent_messages = messages[-5:]\n\n    summary_prompt = \"Summarize the key decisions, findings, and context from this conversation in 3-5 bullet points:\"\n    summary_content = \"\n\".join([\n        str(m.get('content', '')) for m in old_messages\n    ])\n\n    summary_response = client.messages.create(\n        model=\"claude-haiku-4-5\",\n        max_tokens=500,\n        messages=[{\n            \"role\": \"user\",\n            \"content\": f\"{summary_prompt}\n\n{summary_content}\"\n        }]\n    )\n\n    summary_text = summary_response.content[0].text\n    summary_message = {\n        \"role\": \"user\",\n        \"content\": f\"[CONVERSATION SUMMARY]\n{summary_text}\"\n    }\n\n    return [summary_message] + recent_messages\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch3\u003ePattern 3: Selective retention\u003c\/h3\u003e\n\u003cp\u003eGiữ lại những messages có giá trị cao (tool results, decisions) và bỏ messages chit-chat:\u003c\/p\u003e\n\u003cpre\u003e\u003ccode\u003edef selective_retention(messages, max_tokens=50000):\n    \"\"\"Giữ messages quan trọng, bỏ filler messages.\"\"\"\n    important_keywords = [\n        'decision', 'important', 'remember', 'conclusion',\n        'error', 'fix', 'solution', 'warning', 'critical'\n    ]\n\n    scored_messages = []\n    for i, msg in enumerate(messages):\n        content = str(msg.get('content', '')).lower()\n        score = sum(1 for kw in important_keywords if kw in content)\n        # Messages gần đây được ưu tiên hơn\n        recency_bonus = i \/ len(messages) * 3\n        scored_messages.append((score + recency_bonus, i, msg))\n\n    # Sort by score, giữ top messages\n    scored_messages.sort(reverse=True)\n\n    # Estimate tokens và chọn messages fit trong budget\n    retained = []\n    token_count = 0\n    for score, idx, msg in scored_messages:\n        msg_tokens = len(str(msg.get('content', ''))) \/\/ 4\n        if token_count + msg_tokens \u0026lt; max_tokens:\n            retained.append((idx, msg))\n            token_count += msg_tokens\n\n    # Sắp xếp lại theo thứ tự ban đầu\n    retained.sort(key=lambda x: x[0])\n    return [msg for _, msg in retained]\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eBest practices: Khi nào nên save vs forget?\u003c\/h2\u003e\n\n\u003ctable\u003e\n  \u003cthead\u003e\n    \u003ctr\u003e\n      \u003cth\u003eLoại thông tin\u003c\/th\u003e\n      \u003cth\u003eHành động\u003c\/th\u003e\n      \u003cth\u003eLý do\u003c\/th\u003e\n    \u003c\/tr\u003e\n  \u003c\/thead\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eTeam coding standards\u003c\/td\u003e\n      \u003ctd\u003eSave vào memory\u003c\/td\u003e\n      \u003ctd\u003eÁp dụng cho mọi session tương lai\u003c\/td\u003e\n    \u003c\/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eUser preferences đã confirm\u003c\/td\u003e\n      \u003ctd\u003eSave vào memory\u003c\/td\u003e\n      \u003ctd\u003ePersonalization tốt hơn\u003c\/td\u003e\n    \u003c\/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eKết quả tính toán tạm thời\u003c\/td\u003e\n      \u003ctd\u003eForget sau session\u003c\/td\u003e\n      \u003ctd\u003eKhông có giá trị dài hạn\u003c\/td\u003e\n    \u003c\/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eLỗi đã fix\u003c\/td\u003e\n      \u003ctd\u003eSave pattern, forget details\u003c\/td\u003e\n      \u003ctd\u003ePattern quan trọng, không phải line numbers\u003c\/td\u003e\n    \u003c\/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eChit-chat, greetings\u003c\/td\u003e\n      \u003ctd\u003eForget\u003c\/td\u003e\n      \u003ctd\u003eTốn context, không có giá trị\u003c\/td\u003e\n    \u003c\/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eSecurity vulnerabilities đã phát hiện\u003c\/td\u003e\n      \u003ctd\u003eSave ngay lập tức\u003c\/td\u003e\n      \u003ctd\u003eCritical — cần nhớ để tránh lặp lại\u003c\/td\u003e\n    \u003c\/tr\u003e\n  \u003c\/tbody\u003e\n\u003c\/table\u003e\n\n\u003ch2\u003eKết hợp memory + compaction: Complete agent pattern\u003c\/h2\u003e\n\n\u003cpre\u003e\u003ccode\u003eclass PersistentAgent:\n    \"\"\"Agent với cả long-term memory và context compaction.\"\"\"\n\n    def __init__(self, agent_id, memory_dir=\"\/memories\"):\n        self.agent_id = agent_id\n        self.memory_file = f\"{memory_dir}\/{agent_id}.txt\"\n        self.conversation_history = []\n        self.max_context_chars = 60000\n        os.makedirs(memory_dir, exist_ok=True)\n\n    def load_memories(self):\n        try:\n            with open(self.memory_file, 'r') as f:\n                return f.read()\n        except FileNotFoundError:\n            return \"No memories yet.\"\n\n    def chat(self, user_message):\n        # Auto-compact nếu context quá lớn\n        total_chars = sum(\n            len(str(m.get('content', '')))\n            for m in self.conversation_history\n        )\n\n        if total_chars \u0026gt; self.max_context_chars:\n            self.conversation_history = compact_with_summary(\n                self.conversation_history\n            )\n\n        self.conversation_history.append({\n            \"role\": \"user\",\n            \"content\": user_message\n        })\n\n        response = client.messages.create(\n            model=\"claude-opus-4-5\",\n            max_tokens=2048,\n            system=f\"Your memories:\n{self.load_memories()}\",\n            tools=[MEMORY_TOOL],\n            messages=self.conversation_history\n        )\n\n        # Handle tool calls và responses...\n        # (full agentic loop như trên)\n\n        return response\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eTổng kết\u003c\/h2\u003e\n\n\u003cp\u003eMemory management là nền tảng để xây dựng AI agents thực sự hữu ích trong production:\u003c\/p\u003e\n\n\u003cul\u003e\n  \u003cli\u003e\n\u003cstrong\u003eMemory tool\u003c\/strong\u003e (\u003ccode\u003ememory_20250818\u003c\/code\u003e) giải quyết vấn đề mất kiến thức giữa sessions\u003c\/li\u003e\n  \u003cli\u003e\n\u003cstrong\u003eContext compaction\u003c\/strong\u003e giải quyết vấn đề context window bị đầy trong conversations dài\u003c\/li\u003e\n  \u003cli\u003eKết hợp cả hai tạo ra agents có thể hoạt động liên tục, học hỏi và cải thiện theo thời gian\u003c\/li\u003e\n\u003c\/ul\u003e\n\n\u003cp\u003eBước tiếp theo: Tìm hiểu \u003ca href=\"\/collections\/nang-cao\"\u003eContext Compaction tự động\u003c\/a\u003e với \u003ccode\u003ecompaction_control\u003c\/code\u003e parameter để server tự quản lý việc nén context thay vì bạn phải tự code.\u003c\/p\u003e\n","brand":"Minh Tuấn","offers":[{"title":"Default Title","offer_id":66959027175469,"sku":null,"price":0.0,"currency_code":"VND","in_stock":true}],"thumbnail_url":"\/\/cdn.shopify.com\/s\/files\/1\/0763\/9531\/5245\/files\/memory-management-qu_n-ly-b_-nh_-dai-h_n-cho-claude-agents.jpg?v=1782891815","url":"https:\/\/claudeae.com\/products\/memory-management-qu%e1%ba%a3n-ly-b%e1%bb%99-nh%e1%bb%9b-dai-h%e1%ba%a1n-cho-claude-agents","provider":"Claude.vn","version":"1.0","type":"link"}