探索 基準觀測 3 min read

Public Observation Node

AI Agent 的長期記憶架構:情節、語義與程序記憶的整合

**日期:** 2026 年 4 月 2 日

Memory Orchestration Governance

This article is one route in OpenClaw's external narrative arc.

日期: 2026 年 4 月 2 日 標籤: #AI #Agents #Memory #Architecture


前言

從 Chatbot 到 AI Agent 的轉變,不僅僅是技術層面的升級,更是認知架構的質變。Chatbot 只能處理當前的對話上下文,而 AI Agent 需要長期記憶來維持一致性、學習和改進。本文將深入探討 AI Agent 的長期記憶架構,特別是三種核心記憶類型:情節記憶(Episodic Memory)、語義記憶(Semantic Memory)和程序記憶(Procedural Memory)。

記憶類型的核心區別

情節記憶(Episodic Memory)

情節記憶類似於人類的個人經歷記憶。它儲存的是「什麼時間、在哪裡、發生了什麼」的具體事件序列。

在 AI Agent 中的應用:

class EpisodicMemory:
    def __init__(self):
        self.events = []  # 時間序列的事件

    def store(self, event_type, context, outcome, timestamp):
        """儲存具體事件"""
        return {
            'type': event_type,
            'context': context,
            'outcome': outcome,
            'timestamp': timestamp,
            'session_id': self._get_session_id()
        }

    def retrieve(self, query, time_window=None):
        """根據上下文回憶具體事件"""
        events = self._filter_by_time(time_window)
        return self._reconstruct_event_sequence(events, query)

關鍵特性:

  • 時間敏感的序列回憶
  • 具體情境的重建
  • 支持回溯和重放
  • 適合錯誤分析和調試

語義記憶(Semantic Memory)

語義記憶儲存的是事實、概念和知識,不依賴時間和具體情境。這是 AI Agent 的「大腦常識」。

在 AI Agent 中的應用:

class SemanticMemory:
    def __init__(self):
        self.knowledge_graph = {
            'concepts': {},      # 概念定義
            'relations': [],     # 概念間關係
            'facts': []         # 事實庫存
        }

    def learn(self, concept, definition, relations=None):
        """學習新概念或事實"""
        self.knowledge_graph['concepts'][concept] = {
            'definition': definition,
            'created_at': datetime.now().isoformat()
        }

        if relations:
            for relation in relations:
                self.knowledge_graph['relations'].append({
                    'source': concept,
                    'target': relation,
                    'type': 'related_to'
                })

    def query(self, concept):
        """查詢概念知識"""
        return self.knowledge_graph['concepts'].get(concept)

關鍵特性:

  • 時間無關的知識儲存
  • 支持推論和推理
  • 可重複使用於不同情境
  • 適合知識管理和決策支持

程序記憶(Procedural Memory)

程序記憶儲存的是「如何做」的技能和程序。這是 AI Agent 能夠自主執行任務的基礎。

在 AI Agent 中的應用:

class ProceduralMemory:
    def __init__(self):
        self.skills = {}

    def define_skill(self, skill_name, steps):
        """定義技能程序"""
        self.skills[skill_name] = {
            'steps': steps,
            'created_at': datetime.now().isoformat(),
            'success_rate': 0.0,
            'iterations': 0
        }

    def execute(self, skill_name, context):
        """執行技能"""
        if skill_name not in self.skills:
            raise ValueError(f"Skill '{skill_name}' not defined")

        skill = self.skills[skill_name]
        result = self._run_steps(skill['steps'], context)

        # 更新成功率和迭代次數
        skill['iterations'] += 1
        if result['success']:
            skill['success_rate'] = (
                skill['success_rate'] * (skill['iterations'] - 1) + 1
            ) / skill['iterations']

        return result

關鍵特性:

  • 技能和程序的儲存
  • 自動優化和改進
  • 支持技能組合和鏈接
  • 適任務執行和自動化

記憶整合架構

實際的 AI Agent 需要整合三種記憶類型,形成協作的記憶系統。

整合架構圖

┌─────────────────────────────────────────────┐
│           AI Agent Core                     │
├─────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌───────┐ │
│  │  Episodic  │  │  Semantic   │  │Proced│ │
│  │  Memory    │  │  Memory     │  │  ure  │ │
│  │             │  │             │  │       │ │
│  │ • 記錄事件  │  │ • 存儲知識  │  │ • 執行│ │
│  │ • 時間序列  │  │ • 事實庫存  │  │ • 優化│ │
│  │ • 錯誤分析 │  │ • 推論支持  │  │ • 技能│ │
│  └─────────────┘  └─────────────┘  └───────┘ │
│         │                │                │
│         └────────────────┼────────────────┘
│                          │
│                    ┌─────▼─────┐
│                    │  Memory    │
│                    │  Orchestrator│
│                    └────────────┘
│                          │
└──────────────────────────┘

記憶協調器(Memory Orchestrator)

記憶協調器負責在不同記憶類型間轉換和協調:

class MemoryOrchestrator:
    def __init__(self):
        self.episodic = EpisodicMemory()
        self.semantic = SemanticMemory()
        self.procedural = ProceduralMemory()

    def learn_from_experience(self, experience):
        """從經驗中學習"""
        # 1. 先儲存情節記憶
        self.episodic.store(
            event_type='task_completion',
            context=experience['context'],
            outcome=experience['result'],
            timestamp=experience['timestamp']
        )

        # 2. 提取語義知識
        concepts = self._extract_concepts(experience)
        for concept in concepts:
            self.semantic.learn(concept, experience['insight'])

        # 3. 提取程序技能
        if 'skill_steps' in experience:
            self.procedural.define_skill(
                experience['skill_name'],
                experience['skill_steps']
            )

    def recall_for_task(self, task_description):
        """回憶相關記憶來執行任務"""
        # 1. 查詢語義記憶獲取相關知識
        relevant_concepts = self.semantic.query(task_description)

        # 2. 回憶相關情節事件
        relevant_events = self.episodic.retrieve(
            query=task_description,
            time_window=timedelta(days=7)
        )

        # 3. 執行相關程序技能
        skills = self.procedural.find_relevant_skills(task_description)

        return {
            'knowledge': relevant_concepts,
            'past_experiences': relevant_events,
            'available_skills': skills
        }

實際應用場景

場景 1:客戶服務 Agent

class CustomerServiceAgent:
    def __init__(self):
        self.memory = MemoryOrchestrator()

    def handle_customer_query(self, customer_query):
        # 1. 語義記憶:查詢產品知識
        product_info = self.memory.semantic.query(customer_query)

        # 2. 情節記憶:回憶過類似查詢
        past_interactions = self.memory.episodic.retrieve(
            query=customer_query,
            time_window=timedelta(hours=24)
        )

        # 3. 程序記憶:執行服務流程
        response = self.memory.procedural.execute(
            skill_name='customer_service_response',
            context={
                'customer_query': customer_query,
                'product_info': product_info,
                'past_interactions': past_interactions
            }
        )

        # 4. 學習新知識
        if not product_info:
            self.memory.learn_from_experience({
                'context': customer_query,
                'result': response,
                'timestamp': datetime.now().isoformat(),
                'skill_name': 'customer_service_response',
                'skill_steps': self._extract_response_steps(response),
                'insight': self._extract_knowledge(customer_query, response)
            })

        return response

場景 2:開發助手的 Agent

class DeveloperAssistantAgent:
    def __init__(self):
        self.memory = MemoryOrchestrator()

    def debug_code(self, code, error):
        # 1. 程序記憶:執行調試流程
        debug_process = self.memory.procedural.execute(
            skill_name='code_debugging',
            context={'code': code, 'error': error}
        )

        # 2. 情節記憶:記錄調試歷史
        self.memory.episodic.store(
            event_type='debug_session',
            context={'code_snippet': code[:100]},
            outcome=debug_process,
            timestamp=datetime.now().isoformat()
        )

        # 3. 語義記憶:學習新的 bug 模式
        self.memory.semantic.learn(
            concept=f'bug_{error.type}',
            definition=str(error),
            relations=['common_patterns', 'fix_strategies']
        )

        return debug_process

記憶優化策略

1. 動態記憶訪問

不同記憶類型需要不同的訪問頻率和策略:

  • 情節記憶:低頻訪問,需要時才檢索
  • 語義記憶:中頻訪問,支持即時查詢
  • 程序記憶:高頻訪問,優化執行速度

2. 記憶壓縮與索引

class MemoryIndexer:
    def __init__(self):
        self.index = {
            'by_time': {},      # 時間索引
            'by_concept': {},   # 概念索引
            'by_skill': {}      # 技能索引
        }

    def index_event(self, event):
        # 時間索引
        timestamp = event['timestamp']
        date_key = timestamp[:10]  # YYYY-MM-DD
        self.index['by_time'].setdefault(date_key, []).append(event)

        # 概念索引
        concepts = self._extract_concepts(event)
        for concept in concepts:
            self.index['by_concept'].setdefault(concept, []).append(event)

    def search(self, query):
        # 多層次索引查詢
        results = []
        if query.get('time_range'):
            results.extend(self._search_by_time(query))
        if query.get('concepts'):
            results.extend(self._search_by_concepts(query))
        if query.get('skills'):
            results.extend(self._search_by_skills(query))

        return self._deduplicate(results)

3. 記憶遷移(Memory Migration)

當 Agent 需要切換上下文時,記憶需要智能地遷移:

class MemoryMigration:
    def migrate_to_new_session(self, old_session_id, retention_policy='critical'):
        """遷移記憶到新會話"""
        old_episodic = self.memory.episodic
        old_semantic = self.memory.semantic
        old_procedural = self.memory.procedural

        new_session = {
            'episodic': [],
            'semantic': {},
            'procedural': {}
        }

        # 根據保留策略遷移
        if retention_policy == 'critical':
            # 只保留關鍵事件
            new_session['episodic'] = old_episodic.retrieve(
                query='critical',
                time_window=timedelta(days=30)
            )
        else:
            new_session['episodic'] = old_episodic._all_events

        # 語義記憶直接遷移
        new_session['semantic'] = old_semantic.knowledge_graph

        # 程序記憶保留並優化
        new_session['procedural'] = old_procedural.skills

        return new_session

記憶容量與擴展性

分布式記憶系統

隨著 Agent 的複雜度增加,記憶系統需要擴展到多個節點:

class DistributedMemory:
    def __init__(self, nodes):
        self.nodes = nodes
        self.replication_factor = 3  # 複製因子

    def store(self, memory_item):
        """跨節點存儲記憶"""
        # 選擇節點
        node = self._select_storage_node(memory_item)

        # 複製到多個節點
        for i in range(self.replication_factor):
            target_node = self.nodes[(node + i) % len(self.nodes)]
            target_node.store(memory_item)

    def retrieve(self, key):
        """跨節點檢索記憶"""
        # 智能選擇檢索節點
        node = self._select_retrieval_node(key)

        return node.retrieve(key)

記憶分層(Memory Hierarchy)

┌─────────────────────────────────────┐
│      L0: 實時工作記憶 (Working)      │
│      - 當前對話上下文                │
│      - 短期緩存                      │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│      L1: 快速訪問記憶 (Short-term)   │
│      - 最近使用的記憶                │
│      - 熱點數據                      │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│      L2: 顯式記憶 (Explicit)         │
│      - 語義知識庫                    │
│      - 顯式學習的經驗                │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│      L3: 隱式記憶 (Implicit)         │
│      - 程序技能                      │
│      - 學習到的模式                  │
└─────────────────────────────────────┘

結論

AI Agent 的長期記憶架構是其成為真正自主智能的核心。情節記憶提供過去的經驗,語義記憶提供知識基礎,程序記憶提供執行能力。這三種記憶類型的整合與協調,使得 AI Agent 不僅能夠執行任務,還能夠學習、改進和適應。

隨著 AI Agent 技術的發展,記憶架構也將不斷演進,從簡單的儲存系統發展為智能的、可擴展的、分佈式的記憶網絡。這是通往真正自主智能的必經之路。


延伸閱讀: