> 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/unity-plugin-beta-overview/features/long-term-memory/memory-management-api.md).

# 记忆管理 API

使用 MemoryService 脚本 API，以编程方式为任意用户–角色对添加、列出、检索和删除单个记忆记录。

## 以编程方式管理记忆记录

记忆管理 API 允许应用针对特定的用户–角色组合读取、添加和删除单条记忆记录。正常使用时，Convai 后端会在对话过程中自动累积记忆，无需编写代码。此 API 适用于需要主动控制的场景：在首次会话前预置事实、审核角色所知内容，或重置特定记忆而不清除用户的全部历史记录。

所有记忆操作都通过 `ConvaiRestClient.Memory`完成，它提供了 `MemoryService`.

{% hint style="info" %}
**Beta API 提示：** 所有长期记忆端点都会在 Convai 后端使用 Beta API 标志。截至本文撰写时，方法签名和响应结构保持稳定，但可能会在未来的 SDK 或后端更新中发生变化。发布到生产环境时，请固定 SDK 版本。
{% endhint %}

## 什么是记忆记录？

角色了解的关于用户的每条事实都存储为一个 `MemoryRecord`。 `Memory` 字段包含自然语言字符串，而非结构化数据。后端会根据对话自动写入这些内容，其形式类似笔记：

> `"The user's name is Alex and they work as a night-shift safety officer."` `"Alex struggled with fire extinguisher classification and prefers step-by-step explanations."`

会话开始时，角色会将这些字符串作为上下文，并能在回复中自然地引用它们。你也可以通过 `AddAsync` 写入自己的字符串——任何角色应该了解的事实性句子都可以。

| 字段          | 类型                           | 说明                       |
| ----------- | ---------------------------- | ------------------------ |
| `Id`        | `string`                     | 此记忆记录的唯一标识符。             |
| `Memory`    | `string`                     | 事实文本——角色将作为上下文使用的自然语言句子。 |
| `CreatedAt` | `string`                     | 首次存储该记录时的 ISO 8601 时间戳。  |
| `UpdatedAt` | `string`                     | 最近一次更新的 ISO 8601 时间戳。    |
| `Metadata`  | `Dictionary<string, object>` | 附加到记录的任意键值数据。可能为 `null`. |

## 设置 ConvaiRestClient

记忆操作需要使用你的 API 密钥进行身份验证的 `ConvaiRestClient` 。

```csharp
using System;
using Convai.RestAPI;
using UnityEngine;

public class MemoryManager : MonoBehaviour
{
    private ConvaiRestClient _client;

    private void Awake()
    {
        _client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);
    }

    private void OnDestroy()
    {
        _client?.Dispose();
    }
}
```

{% hint style="info" %}
`ConvaiSettings` 是用于存储 API 密钥的 ScriptableObject，可在以下位置进行配置： **Tools → Convai → Configuration**. `ConvaiRestClient` 实现了 `IDisposable` ——使用完毕后务必释放它，或将其作为长生命周期的单例进行管理。
{% endhint %}

{% hint style="info" %}
**查找 Character ID 和 end\_user\_id：** Character ID 位于 **角色 ID** 字段中，位置在 `ConvaiCharacter` 检查器里。 `end_user_id` 是身份提供方返回的值——如果你使用默认的 `DeviceEndUserIdProvider`，可以通过调用来读取 `new DeviceEndUserIdProvider().GetEndUserId()` 在主线程上。
{% endhint %}

{% hint style="info" %}
本页中的所有示例都使用 `async void` 以兼容 Unity。始终使用 `try/catch` 包装异步调用，如下所示—— `async void` 不会将未处理的异常传递给调用方。
{% endhint %}

## 列出记忆

检索角色针对指定用户的所有记忆。结果采用分页方式返回——持续迭代，直到 `HasMore` 为 `false`.

```csharp
using System;
using System.Threading;
using Convai.RestAPI.Internal;
using UnityEngine;

public async void ListAllMemories(
    string characterId,
    string endUserId,
    CancellationToken cancellationToken = default)
{
    try
    {
        int page = 1;
        const int pageSize = 50;

        do
        {
            MemoryListResponse response = await _client.Memory.ListAsync(
                characterId,
                endUserId,
                page,
                pageSize,
                cancellationToken);

            foreach (MemoryRecord record in response.Memories)
            {
                Debug.Log($"[{record.Id}] {record.Memory}");
            }

            if (!response.HasMore) break;
            page++;

        } while (true);
    }
    catch (Exception e)
    {
        Debug.LogError($"[LTM] Failed to list memories: {e.Message}");
    }
}
```

### ListAsync 参数

| 参数                  | 类型                  | 默认值       | 说明             |
| ------------------- | ------------------- | --------- | -------------- |
| `characterId`       | `string`            | 必填        | 要列出记忆的角色。      |
| `endUserId`         | `string`            | 必填        | 要读取其记忆分区的最终用户。 |
| `page`              | `int`               | `1`       | 从 1 开始的页码。     |
| `pageSize`          | `int`               | `50`      | 每页的记录数。        |
| `cancellationToken` | `CancellationToken` | `default` | 可选的取消支持。       |

### MemoryListResponse 字段

| 字段           | 类型                   | 说明          |
| ------------ | -------------------- | ----------- |
| `Memories`   | `List<MemoryRecord>` | 当前页上的记录。    |
| `TotalCount` | `int`                | 所有页面中的记录总数。 |
| `Page`       | `int`                | 当前页码。       |
| `PageSize`   | `int`                | 此响应使用的页面大小。 |
| `HasMore`    | `bool`               | 是否存在更多页面。   |

## 获取单条记忆

通过 ID 检索指定记录。如果你已从先前的 `ListAsync` 调用。

```csharp
public async void GetMemory(
    string characterId,
    string endUserId,
    string memoryId,
    CancellationToken cancellationToken = default)
{
    try
    {
        MemoryRecord record = await _client.Memory.GetAsync(
            characterId,
            endUserId,
            memoryId,
            cancellationToken);

        Debug.Log($"Memory: {record.Memory} (created {record.CreatedAt})");
    }
    catch (Exception e)
    {
        Debug.LogError($"[LTM] Failed to get memory: {e.Message}");
    }
}
```

## 添加记忆

以编程方式注入一条或多条事实。传入自然语言字符串列表，服务器会将每条字符串分别存储为一条 `MemoryRecord`.

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

public async void AddMemories(
    string characterId,
    string endUserId,
    CancellationToken cancellationToken = default)
{
    try
    {
        var facts = new List<string>
        {
            "The trainee completed Module 1 with a score of 88%.",
            "The trainee struggled with fire extinguisher classification in Module 1.",
            "The trainee prefers step-by-step explanations over summaries."
        };

        AddMemoriesResponse response = await _client.Memory.AddAsync(
            characterId,
            endUserId,
            facts,
            metadata: null,
            cancellationToken);

        foreach (MemoryAddResult result in response.Memories)
        {
            Debug.Log($"[{result.Event}] {result.Memory}");
        }
    }
    catch (Exception e)
    {
        Debug.LogError($"[LTM] Failed to add memories: {e.Message}");
    }
}
```

### AddAsync 参数

| 参数                  | 类型                                     | 默认值       | 说明               |
| ------------------- | -------------------------------------- | --------- | ---------------- |
| `characterId`       | `string`                               | 必填        | 要添加记忆的角色。        |
| `endUserId`         | `string`                               | 必填        | 要写入其分区的最终用户。     |
| `memories`          | `IReadOnlyList<string>`                | 必填        | 一条或多条自然语言事实字符串。  |
| `metadata`          | `IReadOnlyDictionary<string, object>?` | `null`    | 应用于所有新增记录的可选元数据。 |
| `cancellationToken` | `CancellationToken`                    | `default` | 可选的取消支持。         |

### MemoryAddResult 字段

| 字段       | 说明                                       |
| -------- | ---------------------------------------- |
| `Id`     | 新建或更新记录的 ID。                             |
| `Event`  | 服务器执行的操作： `"ADD"`, `"UPDATE"`或 `"NONE"`. |
| `Memory` | 最终存储的文本。服务器可能会改写输入内容，以保持一致性。             |

{% hint style="info" %}
服务器会对与现有记录重叠的事实进行去重和合并。发生这种情况时， `Event` 会是 `"UPDATE"` 或 `"NONE"` 而不是 `"ADD"`，并且 `Id` 指向现有记录。最终存储的文本可能与传入的内容略有不同。
{% endhint %}

## 删除单条记忆

通过 ID 删除一条特定记录。可用此操作更正错误事实，而无需清除所有内容。

```csharp
public async void DeleteMemory(
    string characterId,
    string endUserId,
    string memoryId,
    CancellationToken cancellationToken = default)
{
    try
    {
        MemoryDeleteResponse response = await _client.Memory.DeleteAsync(
            characterId,
            endUserId,
            memoryId,
            cancellationToken);

        Debug.Log($"Deleted: {response.Deleted} — Memory ID: {response.MemoryId}");
    }
    catch (Exception e)
    {
        Debug.LogError($"[LTM] Failed to delete memory: {e.Message}");
    }
}
```

## 删除用户的所有记忆

一次性删除用户与角色分区中的所有记忆记录。最终用户记录本身会保留。

```csharp
public async void DeleteAllMemories(
    string characterId,
    string endUserId,
    CancellationToken cancellationToken = default)
{
    try
    {
        MemoryDeleteAllResponse response = await _client.Memory.DeleteAllAsync(
            characterId,
            endUserId,
            cancellationToken);

        Debug.Log($"All memories cleared for user {response.EndUserId} on character {response.CharacterId}.");
    }
    catch (Exception e)
    {
        Debug.LogError($"[LTM] Failed to delete all memories: {e.Message}");
    }
}
```

{% hint style="danger" %}
`DeleteAllAsync` 是 **不可逆的**。指定用户与角色组合的所有记忆记录都将被永久删除。角色在未来的会话中将不再记得该用户。API 不会显示确认对话框——请在调用此方法前，在应用中实现确认机制。
{% endhint %}

## 完整 API 参考

所有方法都位于 `ConvaiRestClient.Memory` (`MemoryService`）。所有 `CancellationToken` 参数都是可选的，默认值为 `default`.

| 方法               | 签名                                                                                                                                            | 返回                              |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `AddAsync`       | `(string characterId, string endUserId, IReadOnlyList<string> memories, IReadOnlyDictionary<string, object>? metadata, CancellationToken ct)` | `Task<AddMemoriesResponse>`     |
| `ListAsync`      | `(string characterId, string endUserId, int page, int pageSize, CancellationToken ct)`                                                        | `Task<MemoryListResponse>`      |
| `GetAsync`       | `(string characterId, string endUserId, string memoryId, CancellationToken ct)`                                                               | `Task<MemoryRecord>`            |
| `DeleteAsync`    | `(string characterId, string endUserId, string memoryId, CancellationToken ct)`                                                               | `Task<MemoryDeleteResponse>`    |
| `DeleteAllAsync` | `(string characterId, string endUserId, CancellationToken ct)`                                                                                | `Task<MemoryDeleteAllResponse>` |

## 总结

记忆管理 API 让您可以通过程序全面控制角色对每位用户的认知——无需访问 Convai 控制面板，即可检查、预置、修正和清除记忆记录。若要管理用户本身（查看哪些用户拥有记忆、更新元数据或彻底删除用户记录），请参阅下一页：最终用户管理。


---

# 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/unity-plugin-beta-overview/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.
