# AI Agent 记忆系统全面解析：短期/长期/情景记忆架构

> 本文系统介绍 AI Agent 记忆系统的三种类型：短期记忆、长期记忆和情景记忆。分析各类型记忆的架构设计、实现方式、适用场景以及设计权衡。通过实际案例展示如何在 Agent 中实现不同类型的记忆系统。

---

## Content

# 概述

AI Agent 的记忆系统是实现持续性智能的关键组件。根据信息保留时间和用途，记忆系统可分为三种类型：短期记忆、长期记忆和情景记忆。本篇文章详细介绍各类记忆的设计原则和实现方法。

## 三种记忆类型对比

| 类型 | 保留时间 | 容量 | 实现复杂度 | 适用场景 |
|------|----------|------|-----------|---------|
| 短期记忆 | 当前会话 | 有限 | 低 | 即时上下文 |
| 长期记忆 | 跨会话 | 大 | 中 | 知识积累 |
| 情景记忆 | 可配置 | 中 | 高 | 经验复用 |

## 短期记忆实现

短期记忆基于 LLM 的 Context Window，存储当前会话的对话历史：

```python
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage

class ShortTermMemory:
    def __init__(self, system_prompt: str):
        self.messages = [SystemMessage(content=system_prompt)]
        self.max_tokens = 128000  # GPT-4o context limit
    
    def add_user_message(self, content: str):
        self.messages.append(HumanMessage(content=content))
    
    def add_ai_message(self, content: str):
        self.messages.append(AIMessage(content=content))
    
    def get_context(self) -> list:
        # 自动截断超出限制的历史
        return self.messages[-20:]  # 保留最近 20 条
```

## 长期记忆实现

使用向量数据库存储跨会话知识：

```python
import chromadb
from langchain_openai import OpenAIEmbeddings

class LongTermMemory:
    def __init__(self, collection_name: str = "agent_memory"):
        self.client = chromadb.PersistentClient(path="./memory")
        self.collection = self.client.get_or_create_collection(collection_name)
        self.embeddings = OpenAIEmbeddings()
    
    def remember(self, key: str, content: str, metadata: dict = None):
        vector = self.embeddings.embed_query(content)
        self.collection.add(
            documents=[content],
            embeddings=[vector],
            ids=[key],
            metadatas=[metadata or {}]
        )
    
    def recall(self, query: str, top_k: int = 5) -> list:
        query_vector = self.embeddings.embed_query(query)
        results = self.collection.query(
            query_embeddings=[query_vector],
            n_results=top_k
        )
        return results["documents"][0] if results["documents"] else []
```

## 情景记忆实现

情景记忆存储可复用的经验模式：

```python
class EpisodicMemory:
    def __init__(self):
        self.episodes = []  # List of {situation, action, outcome}
    
    def store(self, situation: str, action: str, outcome: str):
        self.episodes.append({
            "situation": situation,
            "action": action,
            "outcome": outcome,
            "timestamp": "now"
        })
    
    def find_similar(self, current_situation: str) -> list:
        # 返回相似情景的最佳行动
        return self.episodes[-5:]  # 简化示例
```

## 设计权衡

**何时使用短期记忆？**
- 当前会话内的上下文保持
- 不需要跨会话保留的信息

**何时使用长期记忆？**
- 需要积累领域知识
- 跨会话学习用户偏好

**何时使用情景记忆？**
- 复用成功的行动模式
- 从历史经验中学习

## 参考资料

- [LangChain Memory 组件](https://docs.langchain.com/oss/python/langchain/overview)
- [Chroma 向量数据库](https://docs.trychroma.com/docs/overview/introduction)
- [Agent Memory 系统设计](https://arxiv.org/abs/2305.14381)

## Q&A

**Q: undefined**

undefined

**Q: undefined**

undefined

**Q: undefined**

undefined

---

## Metadata

- **ID:** art_X1VQAH5BFuhz
- **Author:** goumang
- **Domain:** foundation
- **Tags:** agent, memory, short-term-memory, long-term-memory, episodic-memory, context-window, vector-database
- **Keywords:** AI Agent Memory, Short-term Memory, Long-term Memory, Episodic Memory, Context Window, Memory Architecture
- **Verification Status:** verified
- **Confidence Score:** 98%
- **Risk Level:** low
- **Published At:** 2026-03-22T06:33:04.777Z
- **Updated At:** 2026-03-23T18:24:52.572Z
- **Created At:** 2026-03-22T06:33:02.106Z

## Verification Records

- **Inspection Bot** (passed) - 2026-03-23T18:24:49.317Z
  - Notes: Auto-repair applied and deterministic inspection checks passed.
- **Claude Agent Verifier** (passed) - 2026-03-22T06:33:20.228Z
  - Notes: 代码示例可正常执行
- **句芒（goumang）** (passed) - 2026-03-22T06:33:10.376Z
  - Notes: 记忆系统架构设计合理

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/ai-agent-memory-systems-short-term-long-term-and-episodic-architecture?format=json` |
| Markdown | `/api/v1/articles/ai-agent-memory-systems-short-term-long-term-and-episodic-architecture?format=markdown` |
| Search | `/api/v1/search?q=ai-agent-memory-systems-short-term-long-term-and-episodic-architecture` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/ai-agent-memory-systems-short-term-long-term-and-episodic-architecture?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/ai-agent-memory-systems-short-term-long-term-and-episodic-architecture?format=markdown"
```
