> ## Documentation Index
> Fetch the complete documentation index at: https://javaai.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 聊天记忆

Spring AI 中的聊天记忆提供了维护 AI 聊天应用程序的对话上下文和历史的机制。

## 概述

聊天记忆使 AI 应用程序能够：

* 维护对话历史
* 提供上下文感知的响应
* 实现不同的记忆策略
* 管理对话状态

## 记忆类型

<CardGroup cols={2}>
  <Card title="内存存储" icon="memory">
    用于开发和测试的简单内存存储
  </Card>

  <Card title="持久化存储" icon="database">
    用于生产环境的数据库支持存储
  </Card>

  <Card title="分布式存储" icon="network-wired">
    用于可扩展应用程序的分布式存储
  </Card>

  <Card title="自定义存储" icon="code">
    用于特定需求的自定义存储实现
  </Card>
</CardGroup>

## 实现

### 基本配置

```java theme={"system"}
@Configuration
public class ChatMemoryConfig {
    @Bean
    public ChatMemory chatMemory() {
        return new InMemoryChatMemory();
    }
}
```

### 使用聊天记忆

```java theme={"system"}
@Service
public class ChatService {
    private final ChatClient chatClient;
    private final ChatMemory chatMemory;

    public ChatService(ChatClient chatClient, ChatMemory chatMemory) {
        this.chatClient = chatClient;
        this.chatMemory = chatMemory;
    }

    public String chat(String message, String sessionId) {
        // 将消息添加到记忆中
        chatMemory.addMessage(sessionId, message);
        
        // 获取对话历史
        List<Message> history = chatMemory.getMessages(sessionId);
        
        // 使用上下文生成响应
        String response = chatClient.generate(history);
        
        // 将响应存储在记忆中
        chatMemory.addMessage(sessionId, response);
        
        return response;
    }
}
```

## 记忆策略

### 1. 固定窗口记忆

```java theme={"system"}
@Bean
public ChatMemory fixedWindowMemory() {
    return new FixedWindowChatMemory(10); // 保留最后10条消息
}
```

### 2. 基于令牌的记忆

```java theme={"system"}
@Bean
public ChatMemory tokenBasedMemory() {
    return new TokenBasedChatMemory(1000); // 在令牌限制内保留消息
}
```

### 3. 摘要记忆

```java theme={"system"}
@Bean
public ChatMemory summaryMemory() {
    return new SummaryChatMemory(summarizer);
}
```

## 配置属性

```properties theme={"system"}
spring.ai.chat.memory.type=in-memory
spring.ai.chat.memory.max-messages=100
spring.ai.chat.memory.max-tokens=1000
spring.ai.chat.memory.ttl=3600
```

## 最佳实践

<Note>
  在实现聊天记忆时，请考虑以下最佳实践：
</Note>

* **记忆大小**：根据您的用例选择适当的记忆大小
* **持久化**：在生产环境中使用持久化存储
* **清理**：为旧对话实现适当的清理机制
* **安全性**：确保适当的数据保护和隐私措施
* **可扩展性**：考虑为高规模应用程序使用分布式记忆

## 高级功能

### 自定义记忆实现

```java theme={"system"}
@Component
public class CustomChatMemory implements ChatMemory {
    @Override
    public void addMessage(String sessionId, String message) {
        // 自定义实现
    }

    @Override
    public List<Message> getMessages(String sessionId) {
        // 自定义实现
        return messages;
    }
}
```

### 记忆监控

监控记忆使用情况和性能：

```properties theme={"system"}
management.endpoints.web.exposure.include=chat-memory
management.endpoint.chat-memory.enabled=true
```

## 故障排除

常见问题和解决方案：

1. **内存泄漏**
   * 实现适当的清理
   * 设置适当的 TTL
   * 监控内存使用情况

2. **性能问题**
   * 使用适当的记忆类型
   * 实现缓存
   * 优化存储

3. **可扩展性**
   * 使用分布式记忆
   * 实现适当的分区
   * 考虑缓存策略

<Card title="文档有误？请协助编辑" icon="pencil" href="https://github.com/javaai-pig4cloud-com/javaai-docs/edit/main/spring-ai/api/chat-memory.mdx">
  发现文档问题？点击此处直接在 GitHub 上编辑并提交 PR，帮助我们改进文档！
</Card>
