> 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/convai-unity-sdk/features/long-term-memory/memory-management-api.md).

# 记忆管理 API

列出、添加、检索和删除某位玩家的角色记忆记录，涵盖设置、所有方法、响应类型和错误处理。

Memory Management API 允许你直接读取和写入记忆记录，无需等待对话生成这些记录。你可以用它审核角色对用户的了解、在首次会话前预置事实，或删除不再准确的特定记忆。

{% hint style="warning" %}
**Beta API。** 方法签名稳定，但可能会在未来的 SDK 更新中发生变化。在生产环境中固定 SDK 版本，并在升级前查看更新日志。
{% endhint %}

所有记忆操作均可通过 `ConvaiRestClient.Memory`完成。 `ConvaiRestClient` 是一个独立于实时会话的 REST 客户端，你可以随时调用它，包括在编辑器脚本中、Play Mode 之外调用。

***

### 初始化客户端

使用你的 API 密钥初始化 `ConvaiRestClient` 。该客户端实现了 `IDisposable` ，因此完成后务必使用 `using` 语句，或调用 `Dispose()` 。

```csharp
using var client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);
```

每项记忆操作都需要两个标识符：

* **`characterId`** — 来自 `ConvaiCharacter` 检查器的角色 ID
* **`endUserId`** — 由你的 `IEndUserIdentityProvider` 返回的标识符（或使用默认的 `PlayerPrefs` 时使用的 GUID，默认提供程序为 `DeviceEndUserIdProvider`)

***

### `MemoryRecord` 数据模型

每条存储的事实都是一个 `MemoryRecord`:

| 属性          | 类型                           | 说明                     |
| ----------- | ---------------------------- | ---------------------- |
| `Id`        | `string`                     | 此记忆记录的唯一标识符            |
| `Memory`    | `string`                     | 以自然语言句子表示的存储事实         |
| `CreatedAt` | `string`                     | 首次存储该事实时的 ISO 8601 时间戳 |
| `UpdatedAt` | `string`                     | 上次更新的 ISO 8601 时间戳     |
| `Metadata`  | `Dictionary<string, object>` | 附加到此记录的可选键值数据          |

示例 `Memory` 取值： `"The user's name is Alex."`, `"Alex completed the confined-space safety module on 2025-03-12."`, `"Alex prefers step-by-step explanations over summaries."`

完整的类型参考（包括响应模型），请参阅 [长期记忆脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/long-term-memory-scripting-reference.md).

***

### 记忆 CRUD 操作

#### 列出记忆

检索某个用户与角色组合的所有已存储记忆记录。结果采用分页方式返回——使用 `page` 和 `pageSize` 遍历大量记录。

```csharp
using Convai.RestAPI;
using Convai.RestAPI.Internal;
using System.Collections.Generic;
using UnityEngine;

public class MemoryInspector : MonoBehaviour
{
    [ContextMenu("列出所有记忆")]
    private async void ListAllMemories()
    {
        string characterId = "your-character-id";
        string endUserId = "target-end-user-id";

        using var client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);

        int page = 1;
        bool hasMore = true;
        var allMemories = new List<MemoryRecord>();

        while (hasMore)
        {
            var response = await client.Memory.ListAsync(characterId, endUserId, page, pageSize: 50);
            allMemories.AddRange(response.Memories);
            hasMore = response.HasMore;
            page++;
        }

        foreach (var record in allMemories)
        {
            Debug.Log($"[{record.Id}] {record.Memory}");
        }
    }
}
```

**`MemoryListResponse` 字段：**

| 属性           | 类型                   | 说明       |
| ------------ | -------------------- | -------- |
| `Memories`   | `List<MemoryRecord>` | 此页记录数    |
| `TotalCount` | `int`                | 已存储记录总数  |
| `Page`       | `int`                | 当前页码     |
| `PageSize`   | `int`                | 每页记录数    |
| `HasMore`    | `bool`               | 是否存在更多页面 |

***

#### 获取单条记忆

通过记录 ID 检索一条特定记录。

```csharp
var record = await client.Memory.GetAsync(characterId, endUserId, memoryId);
Debug.Log($"记忆：{record.Memory}");
```

***

#### 添加记忆

以自然语言字符串的形式注入一条或多条事实。Convai 会对重叠事实进行去重——如果添加的事实在语义上与现有事实等效，系统会更新现有记录，而不是创建重复记录。

```csharp
var facts = new List<string>
{
    "Jordan 是 Northfield 设施的夜班安全员。",
    "Jordan 已完成受限空间进入认证。",
    "Jordan 更喜欢实用示例，而不是偏重理论的解释。"
};

var response = await client.Memory.AddAsync(characterId, endUserId, facts);

foreach (var result in response.Memories)
{
    Debug.Log($"[{result.Event}] {result.Memory} (id: {result.Id})");
}
```

**`AddMemoriesResponse` 和 `MemoryAddResult` 字段：**

`AddAsync` 返回 `AddMemoriesResponse`，其中包含一个 `List<MemoryAddResult>`。每个结果对应一条已提交的事实：

| 属性       | 类型       | 说明                                 |
| -------- | -------- | ---------------------------------- |
| `Id`     | `string` | 已创建或更新记录的 ID                       |
| `Event`  | `string` | `"add"` 用于新记录， `"update"` 用于去重后的更新 |
| `Memory` | `string` | Convai 存储的规范化事实文本                  |

***

#### 删除单条记忆

根据记录 ID 删除一条特定记录。

```csharp
var result = await client.Memory.DeleteAsync(characterId, endUserId, memoryId);
Debug.Log($"Deleted: {result.Deleted}");
```

***

#### 删除所有记忆

{% hint style="danger" %}
`DeleteAllAsync` 将永久删除 **所有** 指定用户与角色组合对应的记忆记录。此操作无法撤销。在面向用户的流程中调用此方法前，务必设置确认步骤。
{% endhint %}

```csharp
var result = await client.Memory.DeleteAllAsync(characterId, endUserId);
Debug.Log($"All memories deleted for user {result.EndUserId} on character {result.CharacterId}.");
```

***

### 处理 API 错误

将所有异步记忆调用放在 `try/catch`中。操作失败时会抛出 `ConvaiRestException` ，其中包含 HTTP 状态码。

```csharp
try
{
    var response = await client.Memory.ListAsync(characterId, endUserId);
    // process response
}
catch (ConvaiRestException ex)
{
    Debug.LogError($"Memory API error {ex.StatusCode}: {ex.Message}");
}
```

请参阅 [长期记忆故障排查](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/troubleshooting-and-diagnostics.md) 了解完整的 HTTP 状态码参考。

***

### 后续步骤

{% content-ref url="/pages/d41fbdd4f21a090aa6d7e39be7a7eb215d0435c2" %}
[长期记忆使用示例](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/usage-examples.md)
{% endcontent-ref %}

{% content-ref url="/pages/49cef55d22f33c0ffdf4893701cd5a6686bd7590" %}
[管理终端用户记录](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/end-user-management.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/convai-unity-sdk/features/long-term-memory/memory-management-api.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.
