> 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/long-term-memory.md).

# 使用长期记忆

让 Convai 角色记住跨会话的每个最终用户，并从你的 Web 应用中列出、添加或删除这些记忆。

通过稳定的终端用户 ID 关联角色，使其能够跨会话记住终端用户；然后通过记忆管理器读取或更改该用户的记忆。当您识别用户并希望角色记住他们，或应用需要预置或清理角色记忆的内容时，请使用本页。

### 前提条件

* 已安装 Convai Web SDK，且连接正常。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).
* Convai API 密钥或身份验证令牌，以及来自以下位置的角色 ID： <code class="expression">space.vars.dashboard\_url</code>.
* 在 Convai 控制面板中为角色启用长期记忆：打开该角色，选择 **记忆** 选项卡，然后在 **记忆设置**.

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FzXOCfJacFgTrPdKUkmc2%2FMemory.png?alt=media&amp;token=f523e099-b5f8-4236-85ac-bdf32f05a1df" alt="The Memory tab of a character in the Convai dashboard, showing the Memory Settings panel with the long-term memory toggle"><figcaption></figcaption></figure>

### 使用终端用户 ID 连接

在配置中传入 `endUserId` 。接受任意非空字符串。请使用能在每个会话中标识同一用户的值，例如 UUID 或电子邮件地址。如果没有 `endUserId` ，该会话将是匿名会话，且没有记忆管理器。

{% tabs %}
{% tab title="React" %}

```tsx
import { useConvaiClient } from '@convai/web-sdk/react';

const client = useConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  endUserId: 'a1b2c3d4-5678-90ab-cdef-1234567890ab',
});
```

{% endtab %}

{% tab title="TypeScript" %}

```typescript
import { ConvaiClient } from '@convai/web-sdk/core';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  endUserId: 'a1b2c3d4-5678-90ab-cdef-1234567890ab',
});
```

{% endtab %}
{% endtabs %}

当 `connect()` 执行完成后， `client.state.endUserId` 会保存 Convai 返回的终端用户 ID，该 ID 可能与您传入的值不同。

### 获取记忆管理器

`client.memoryManager` 是一个 `MemoryManager` 实例或 `null`。SDK 仅在以下条件都满足时，才会在 `connect()` 期间创建它：Convai 为会话返回了终端用户 ID，且客户端持有 `apiKey` 或 `authToken`。它使用与连接相同的凭据。断开连接时，SDK 会将其重置为 `null` 。

```typescript
const memory = client.memoryManager;

if (!memory) {
  // 未连接，或会话没有终端用户 ID。
  throw new Error('Connect with an endUserId before using memories');
}
```

每个方法的作用范围均限定为当前会话的角色 ID 和终端用户 ID。

### 列出记忆

`listMemories()` 接受可选的 `{ page, pageSize }` 对象，并返回一页记忆。

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

console.log(`Total: ${result.total_count}, more pages: ${result.has_more}`);
for (const m of result.memories) {
  console.log(m.id, m.memory, m.created_at, m.updated_at);
}
```

| 选项         | 类型       | 默认值  | 范围             |
| ---------- | -------- | ---- | -------------- |
| `page`     | `number` | `1`  | 限制为 `1`–`1000` |
| `pageSize` | `number` | `50` | 上限为 `1`–`100`  |

响应是一个 `MemoryListResponse` ，包含 `memories`, `total_count`, `page`, `page_size`和 `has_more`。每个 `Memory` 都有 `id`, `memory`, `created_at`和 `updated_at`；时间戳为 ISO 字符串。

### 添加记忆

`addMemories()` 接收一个字符串数组。数组为空时会抛出 `Memories array is required and must not be empty` 。

```typescript
const added = await memory.addMemories([
  'Completed the forklift safety module.',
  'Prefers instructions in short steps.',
]);

for (const m of added.memories) {
  console.log(`Added ${m.id}: ${m.memory}`);
}
```

每个返回条目都包含 `id`, `event` （始终为 `"ADD"`）和 `memory`.

### 读取或删除单条记忆

`getMemory()` 返回单个 `Memory`. `deleteMemory()` 返回 `{ message, memory_id, deleted }`。两者都会在 `Memory ID is required` ID 为空时抛出此错误。

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

const result = await memory.deleteMemory(m.id);
if (result.deleted) {
  console.log('Deleted', result.memory_id);
}
```

### 删除最终用户的所有记忆

`deleteAllMemories()` 会删除当前角色与最终用户组合的所有记忆。在 Convai 上，删除操作是异步的，因此响应确认的是请求，而非删除结果。

```typescript
const result = await memory.deleteAllMemories();
console.log(result.message, result.character_id, result.end_user_id);
```

{% hint style="warning" %}
删除操作无法撤销。稍后再次列出记忆，确认它们已被删除后，再告知最终用户。
{% endhint %}

### 不连接会话即可使用记忆管理器

导入 `MemoryManager` ，来自 `@convai/web-sdk/core` ，即可在不建立连接的情况下管理记忆，例如在管理工具中使用。

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

const manager = new MemoryManager(
  'YOUR_API_KEY',
  'YOUR_CHARACTER_ID',
  'a1b2c3d4-5678-90ab-cdef-1234567890ab',
);

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

构造函数签名为 `new MemoryManager(apiKeyOrAuthToken, characterId, endUserId, baseUrl?, useAuthToken?)`:

| 参数                  | 类型        | 默认值                        | 说明                                                |
| ------------------- | --------- | -------------------------- | ------------------------------------------------- |
| `apiKeyOrAuthToken` | `string`  | 无                          | API 密钥；当 `useAuthToken` 为 `true`.                 |
| `characterId`       | `string`  | 无                          | 记忆所属的角色。                                          |
| `endUserId`         | `string`  | 无                          | 记忆所属的最终用户。                                        |
| `baseUrl`           | `string`  | `'https://api.convai.com'` | 记忆 API 的源地址。末尾的斜杠会被移除。                            |
| `useAuthToken`      | `boolean` | `false`                    | 将凭据作为 `API-AUTH-TOKEN` 发送，而不是作为 `CONVAI-API-KEY`. |

当参数为空时，构造函数会抛出 `API key or auth token is required`, `Character ID is required`或 `End user ID is required` 。若要更改现有实例的作用范围，请调用 `setEndUserId()` 或 `setCharacterId()`；使用以下方法读取当前值 `getEndUserId()` 和 `getCharacterId()`.

### 故障排查

#### 内存管理器为 null

**症状：** `client.memoryManager` 为 `null` （连接后）。

**原因：** 配置中没有 `endUserId`, `connect()` 尚未完成，或者客户端已断开连接。

**修复方法：** 传入 `endUserId`，并在 `client.memoryManager` 在 `connect()` 完成后读取。

**验证：** `client.state.endUserId` 是一个字符串，并且 `client.memoryManager` 不为 `null`.

#### 内存调用被拒绝

**症状：** 某个 `MemoryManager` 方法返回一个 `Error`.

**原因：** Convai 拒绝了该请求。错误消息是响应中的 `ERROR` 字段；如果响应中没有该字段，则为 `HTTP error! status: <code>` 。

**修复方法：** 检查凭据、角色 ID，以及消息中的内存 ID。

**验证：** `listMemories()` 成功返回预期的 `total_count`.

### 后续步骤

{% content-ref url="/pages/534e8cdc1d57114dcd7601d4455823f77a9ad2ef" %}
[使用认证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md)
{% endcontent-ref %}

{% content-ref url="/pages/f1fc7386520b3ebeeafa719a8d9efb554e1d7024" %}
[ConvaiClient 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/dff296725774f9173a7391e28344f5f94cf35b60" %}
[配置和类型参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md)
{% endcontent-ref %}


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/long-term-memory.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
