> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/chang-qi-ji-yi.md).

# 长期记忆

### 启用记忆

这是一个基于角色的功能。前往你的 Convai 仪表板 -> Character -> Memory 标签页 -> Memory Settings -> 启用长期记忆

<figure><img src="/files/4a76c1d6df948ba7e480e869e0cc94aba360a20a" alt=""><figcaption></figcaption></figure>

传入 `endUserId` 连接时：

```ts
const client = useConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  endUserId: 'a1b2c3d4-...',  // 任意字符串——优先使用（UUID 或电子邮件），例如 'user@example.com'
});
```

`client.memoryManager` 在成功连接后可用。

### 访问管理器

```ts
const memory = client.memoryManager;

if (!memory) {
  // 未提供 endUserId，或者客户端尚未连接
  return;
}
```

***

### 列出记忆

```ts
const result = await memory.listMemories({ page: 1, pageSize: 50 });

console.log(`总数：${result.total_count}`);
console.log(`是否还有更多：${result.has_more}`);

result.memories.forEach(m => {
  console.log(`[${m.id}] ${m.memory}`);
  // m.created_at、m.updated_at（ISO 时间戳）
});

// 如有需要，可进行分页
if (result.has_more) {
  const page2 = await memory.listMemories({ page: 2, pageSize: 50 });
}
```

#### 参数

| 字段     | 类型   | 默认值  | 范围     |
| ------ | ---- | ---- | ------ |
| `页码`   | `数字` | `1`  | 1–1000 |
| `每页数量` | `数字` | `50` | 1–100  |

***

### 添加记忆

传入一个或多个字符串作为记忆添加：

```ts
const result = await memory.addMemories([
  '用户偏好深色模式界面。',
  '用户正在学习西班牙语。',
  '用户把弹吉他作为爱好。',
]);

result.memories.forEach(m => {
  console.log(`已添加：${m.id} → ${m.memory}`);
});
```

角色将在未来的对话中自动使用这些内容。

***

### 获取单条记忆

```ts
const m = await memory.getMemory('f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c');

console.log(m.memory);      // “用户偏好深色模式界面。”
console.log(m.created_at);  // ISO 时间戳
console.log(m.updated_at);  // ISO 时间戳
```

***

### 删除一条记忆

```ts
const result = await memory.deleteMemory('f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c');

if (result.deleted) {
  console.log('已删除：', result.memory_id);
}
```

***

### 删除所有记忆

移除（角色，用户）对的所有记忆。删除在服务器端是异步的。

```ts
const result = await memory.deleteAllMemories();
console.log(result.message); // “记忆删除正在进行中...”

// 稍等片刻并验证
await new Promise(r => setTimeout(r, 2000));
const check = await memory.listMemories();
console.log('剩余：', check.total_count);
```

***

### 独立使用

`MemoryManager` 可以独立于客户端使用（例如在后端管理工具中）：

```ts
import { MemoryManager } from '@convai/web-sdk/core';

const manager = new MemoryManager(
  'YOUR_API_KEY',      // 或认证令牌
  'CHARACTER_ID',
  'END_USER_ID',
);

const memories = await manager.listMemories();
```

***

### Memory 对象结构

```ts
interface Memory {
  id: string;          // UUID
  memory: string;      // 文本内容
  created_at: string;  // ISO 8601 时间戳
  updated_at: string;  // ISO 8601 时间戳
}
```

***

### 自动记忆如何工作

当 `endUserId` 设置后，Convai 后端会从每段对话中提取有意义的事实并将它们存储为记忆。在以后与 **相同，** `endUserId`连接时，这些记忆会被注入到角色的上下文中，让它“记住”用户。这就是为什么该值必须对每个用户保持稳定且唯一——UUID 或电子邮件地址都很适合。

为此你无需调用任何 Memory API 方法。显式的 CRUD 方法用于从你的应用中读取、初始化或清理记忆。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/chang-qi-ji-yi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
