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

# 长期记忆脚本参考

完整的记忆与终端用户 API 参考：方法签名、参数、返回类型、身份接口以及各自返回的数据模型。

Convai Unity SDK 中所有长期记忆脚本 API 的完整参考。涵盖 `ConvaiRestClient` 入口、 `MemoryService` 和 `EndUsersService`的所有方法、 `CharacterService`中的记忆相关方法、身份接口以及所有数据模型类型。

**Beta API。** `MemoryService` 和 `EndUsersService` 的方法使用 Convai Beta API 端点。 `CharacterService` 的方法（`GetMemoryEnabledAsync`, `SetMemoryEnabledAsync`）使用标准生产环境端点。签名稳定，但仍可能变更。请在生产环境中固定 SDK 版本。

***

### `ConvaiRestClient` 入口

```csharp
命名空间 Convai.RestAPI

public sealed class ConvaiRestClient : IDisposable
```

所有 LTM 操作的主要入口。线程安全且可重复使用——使用 `using` 语句在每次操作后释放，也可以在应用程序的整个生命周期内重复使用同一个实例。

**构造函数：**

```csharp
// 使用 API 密钥字符串初始化（使用默认选项）
public ConvaiRestClient(string apiKey)

// 使用完整选项初始化（自定义超时和传输方式）
public ConvaiRestClient(ConvaiRestClientOptions options)
```

**与 LTM 相关的属性：**

| 属性           | 类型                 | 说明             |
| ------------ | ------------------ | -------------- |
| `Memory`     | `MemoryService`    | 按角色范围执行的长期记忆操作 |
| `EndUsers`   | `EndUsersService`  | 最终用户身份和记录管理    |
| `Characters` | `CharacterService` | 角色配置，包括启用或禁用记忆 |

**使用模式：**

```csharp
// 始终使用 'using' — ConvaiRestClient 实现了 IDisposable
using var client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);
var response = await client.Memory.ListAsync(characterId, endUserId);
```

***

### `MemoryService`

```csharp
命名空间 Convai.RestAPI.Services

public sealed class MemoryService
```

通过 `ConvaiRestClient.Memory`访问。所有方法均为异步，并支持取消操作。

***

#### `AddAsync`

为用户与角色组合注入一条或多条自然语言事实。Convai 会对语义重叠的事实进行去重。

```csharp
public Task<AddMemoriesResponse> AddAsync(
    string characterId,
    string endUserId,
    IReadOnlyList<string> memories,
    IReadOnlyDictionary<string, object>? metadata = null,
    CancellationToken cancellationToken = default)
```

| 参数                  | 类型                                     | 说明                 |
| ------------------- | -------------------------------------- | ------------------ |
| `characterId`       | `string`                               | Convai 控制面板中的角色 ID |
| `endUserId`         | `string`                               | 稳定的用户标识符           |
| `memories`          | `IReadOnlyList<string>`                | 要存储的自然语言事实字符串      |
| `metadata`          | `IReadOnlyDictionary<string, object>?` | 附加到所有新增记录的可选键值数据   |
| `cancellationToken` | `CancellationToken`                    | 可选的取消支持            |

**返回：** `Task<AddMemoriesResponse>`

***

#### `ListAsync`

使用页码分页，检索用户与角色组合的已存储记忆记录。

```csharp
public Task<MemoryListResponse> ListAsync(
    string characterId,
    string endUserId,
    int page = 1,
    int pageSize = 50,
    CancellationToken cancellationToken = default)
```

| 参数                  | 类型                  | 默认值  | 说明         |
| ------------------- | ------------------- | ---- | ---------- |
| `characterId`       | `string`            | —    | 角色 ID      |
| `endUserId`         | `string`            | —    | 用户标识符      |
| `page`              | `int`               | `1`  | 页码（从 1 开始） |
| `pageSize`          | `int`               | `50` | 每页记录数      |
| `cancellationToken` | `CancellationToken` | —    | 可选的取消支持    |

**返回：** `Task<MemoryListResponse>`

***

#### `GetAsync`

按 ID 检索单条记忆记录。

```csharp
public Task<MemoryRecord> GetAsync(
    string characterId,
    string endUserId,
    string memoryId,
    CancellationToken cancellationToken = default)
```

**返回：** `Task<MemoryRecord>`

***

#### `DeleteAsync`

按 ID 删除单条记忆记录。

```csharp
public Task<MemoryDeleteResponse> DeleteAsync(
    string characterId,
    string endUserId,
    string memoryId,
    CancellationToken cancellationToken = default)
```

**返回：** `Task<MemoryDeleteResponse>`

***

#### `DeleteAllAsync`

{% hint style="danger" %}
永久删除指定用户与角色组合的所有记忆记录。此操作无法撤销。
{% endhint %}

```csharp
public Task<MemoryDeleteAllResponse> DeleteAllAsync(
    string characterId,
    string endUserId,
    CancellationToken cancellationToken = default)
```

**返回：** `Task<MemoryDeleteAllResponse>`

***

### `EndUsersService`

```csharp
命名空间 Convai.RestAPI.Services

public sealed class EndUsersService
```

通过以下方式访问 `ConvaiRestClient.EndUsers`。所有方法均为异步方法，并支持取消操作。

***

#### `GetAsync`

按标识符检索单个终端用户记录。

```csharp
public Task<EndUserDetails> GetAsync(
    string endUserId,
    CancellationToken cancellationToken = default)
```

**返回：** `Task<EndUserDetails>`

***

#### `ListAsync`

使用基于游标的分页列出终端用户记录，并可选择日期筛选条件。

```csharp
public Task<EndUsersListResponse> ListAsync(
    int limit = 50,
    string? cursor = null,
    string? activeAfter = null,
    string? activeBefore = null,
    CancellationToken cancellationToken = default)
```

| 参数                  | 类型                  | 默认值       | 说明                        |
| ------------------- | ------------------- | --------- | ------------------------- |
| `limit`             | `int`               | `50`      | 每页记录数                     |
| `cursor`            | `string?`           | `时显示为灰色。` | 上一响应中的分页游标                |
| `activeAfter`       | `string?`           | `时显示为灰色。` | ISO 8601 — 仅返回在此日期之后活跃的用户 |
| `activeBefore`      | `string?`           | `时显示为灰色。` | ISO 8601 — 仅返回在此日期之前活跃的用户 |
| `cancellationToken` | `CancellationToken` | —         | 可选的取消支持                   |

**返回：** `Task<EndUsersListResponse>`

***

#### `UpdateMetadataAsync`

更新终端用户记录的元数据字典。未包含在补丁中的键将予以保留。

```csharp
public Task<EndUserUpdateResponse> UpdateMetadataAsync(
    string endUserId,
    IReadOnlyDictionary<string, object> metadataPatch,
    CancellationToken cancellationToken = default)
```

**返回：** `Task<EndUserUpdateResponse>`

***

#### `DeleteAsync`

{% hint style="danger" %}
删除终端用户记录，以及该用户在 **所有角色**中的全部记忆记录。此操作无法撤销。
{% endhint %}

```csharp
public Task<EndUserDeleteResponse> DeleteAsync(
    string endUserId,
    CancellationToken cancellationToken = default)
```

**返回：** `Task<EndUserDeleteResponse>`

***

### `CharacterService` — 记忆方法

```csharp
命名空间 Convai.RestAPI.Services

public sealed class CharacterService
```

通过以下方式访问 `ConvaiRestClient.Characters`。这两个方法用于控制角色的长期记忆（LTM）启用或禁用状态。

***

#### `GetMemoryEnabledAsync`

如果角色启用了长期记忆，则返回 `true` 。

```csharp
public Task<bool> GetMemoryEnabledAsync(
    string characterId,
    CancellationToken cancellationToken = default)
```

***

#### `SetMemoryEnabledAsync`

启用或禁用该角色的长期记忆。此设置会全局影响该角色的所有部署。

```csharp
public Task SetMemoryEnabledAsync(
    string characterId,
    bool enabled,
    CancellationToken cancellationToken = default)
```

***

### 身份接口

#### `IEndUserIdentityProvider`

```csharp
namespace Convai.Domain.Identity

public interface IEndUserIdentityProvider
{
    string GetEndUserId();
}
```

实现此接口以提供自定义用户标识符。请在首次调用 `ConvaiManager.SetEndUserIdentityProvider(provider)` 之前注册 `ConnectAsync` 。

***

#### `IEndUserMetadataProvider`

```csharp
namespace Convai.Domain.Identity

public interface IEndUserMetadataProvider
{
    IReadOnlyDictionary<string, object> GetEndUserMetadata();
}
```

可选地与 `IEndUserIdentityProvider` 一起实现此接口，以发送显示元数据。键 `"name"` 会填充编辑器面板中的 `EndUserDetails.DisplayName` 。请通过以下方法注册： `ConvaiManager.SetEndUserMetadataProvider(provider)`.

***

#### `IEndUserIdProvider`

```csharp
namespace Convai.Domain.Identity

public interface IEndUserIdProvider
{
    string GenerateEndUserId();
}
```

用于生成稳定 ID 的较低层级接口。 `DeviceEndUserIdProvider` 同时实现了 `IEndUserIdProvider` 和 `IEndUserIdentityProvider`。对于自定义提供程序，请直接实现 `IEndUserIdentityProvider` ——这是 `ConvaiManager.SetEndUserIdentityProvider` 接受的接口。

***

#### `DeviceEndUserIdProvider`

```csharp
namespace Convai.Runtime.Identity

public sealed class DeviceEndUserIdProvider : IEndUserIdProvider, IEndUserIdentityProvider
```

默认身份提供程序，会自动注册，无需配置。

| 上下文               | 行为                                                  |
| ----------------- | --------------------------------------------------- |
| Unity 编辑器         | 读取或创建 GUID，并存储在 `PlayerPrefs["convai.end_user_id"]` |
| 播放器构建版 — 设备 ID 有效 | 返回 `SystemInfo.deviceUniqueIdentifier`              |
| 播放器构建版 — 设备 ID 无效 | 回退到 `PlayerPrefs["convai.end_user_id"]` GUID        |

GUID 格式：32 个字符的十六进制字符串，不带连字符（例如： `a1b2c3d4e5f6789012345678abcdef01`).

***

### 数据模型

#### `MemoryRecord`

```csharp
namespace Convai.RestAPI.Internal

public class MemoryRecord
```

| 属性          | JSON 键         | 类型                           | 说明               |
| ----------- | -------------- | ---------------------------- | ---------------- |
| `Id`        | `"id"`         | `string`                     | 唯一记录标识符          |
| `Memory`    | `"memory"`     | `string`                     | 以自然语言句子表示的已存储事实  |
| `CreatedAt` | `"created_at"` | `string`                     | ISO 8601 创建时间戳   |
| `UpdatedAt` | `"updated_at"` | `string`                     | ISO 8601 上次更新时间戳 |
| `Metadata`  | `"metadata"`   | `Dictionary<string, object>` | 可选的附加键值数据        |

***

#### `AddMemoriesResponse`

| 属性         | JSON 键       | 类型                      | 说明            |
| ---------- | ------------ | ----------------------- | ------------- |
| `Memories` | `"memories"` | `List<MemoryAddResult>` | 每个提交的事实对应一个结果 |

#### `MemoryAddResult`

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

***

#### `MemoryListResponse`

| 属性           | JSON 键          | 类型                   | 说明         |
| ------------ | --------------- | -------------------- | ---------- |
| `Memories`   | `"memories"`    | `List<MemoryRecord>` | 此页上的记录     |
| `TotalCount` | `"total_count"` | `int`                | 所有页面中的记录总数 |
| `Page`       | `"page"`        | `int`                | 当前页码       |
| `PageSize`   | `"page_size"`   | `int`                | 每页记录数      |
| `HasMore`    | `"has_more"`    | `bool`               | 是否存在更多页面   |

***

#### `MemoryDeleteResponse`

| 属性         | JSON 键        | 类型       | 说明                 |
| ---------- | ------------- | -------- | ------------------ |
| `Message`  | `"message"`   | `string` | 人类可读的结果消息          |
| `MemoryId` | `"memory_id"` | `string` | 已删除记录的 ID          |
| `Deleted`  | `"deleted"`   | `bool`   | `true` 如果找到并删除了该记录 |

***

#### `MemoryDeleteAllResponse`

| 属性            | JSON 键           | 类型       | 说明        |
| ------------- | ---------------- | -------- | --------- |
| `Message`     | `"message"`      | `string` | 人类可读的结果消息 |
| `CharacterId` | `"character_id"` | `string` | 已清除记忆的角色  |
| `EndUserId`   | `"end_user_id"`  | `string` | 已清除记忆的用户  |

***

#### `EndUserDetails`

| 属性               | JSON 键                | 类型                           | 备注                                                                                                                  |
| ---------------- | --------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `EndUserId`      | `"end_user_id"`       | `string`                     | 稳定标识符                                                                                                               |
| `LastActiveTs`   | `"last_active_ts"`    | `string`                     | 上次会话时间戳（ISO 8601）                                                                                                   |
| `LastLtmUsageTs` | `"last_ltm_usage_ts"` | `string`                     | 上次 LTM 交互时间（ISO 8601）                                                                                               |
| `Metadata`       | `"end_user_metadata"` | `Dictionary<string, object>` | 提供方 `IEndUserMetadataProvider`                                                                                      |
| `DisplayName`    | —                     | `string`                     | **计算得出** — `Metadata["name"]` 如果存在且非空；否则使用 `"User {EndUserId[..8]}"`，可选择追加相对的最后活跃时间（例如： `"User a1b2c3d4 (3d ago)"`) |
| `ShortId`        | —                     | `string`                     | **计算得出** — `EndUserId` 的截断形式，用于显示                                                                                   |

***

#### `EndUsersListResponse`

| 属性           | JSON 键          | 类型                     | 说明                        |
| ------------ | --------------- | ---------------------- | ------------------------- |
| `EndUsers`   | `"end_users"`   | `List<EndUserDetails>` | 此页上的记录                    |
| `TotalCount` | `"total_count"` | `int`                  | 终端用户记录总数                  |
| `NextCursor` | `"next_cursor"` | `string`               | 下一页的游标令牌； `null` 表示没有后续页面 |
| `HasMore`    | `"has_more"`    | `bool`                 | 是否存在更多页面                  |

***

#### `EndUserUpdateResponse`

扩展 `EndUserDetails` 并添加一个字段：

| 属性        | JSON 键      | 类型       | 说明        |
| --------- | ----------- | -------- | --------- |
| `Message` | `"message"` | `string` | 人类可读的结果消息 |

***

#### `EndUserDeleteResponse`

| 属性          | JSON 键          | 类型       | 说明                 |
| ----------- | --------------- | -------- | ------------------ |
| `Message`   | `"message"`     | `string` | 人类可读的结果消息          |
| `EndUserId` | `"end_user_id"` | `string` | 已删除用户的 ID          |
| `Deleted`   | `"deleted"`     | `bool`   | `true` 如果找到并删除了该记录 |

***

#### `MemorySettings`

| 属性          | JSON 键      | 类型     | 默认值     | 说明               |
| ----------- | ----------- | ------ | ------- | ---------------- |
| `IsEnabled` | `"enabled"` | `bool` | `false` | 角色的 LTM 是否处于启用状态 |

***

### 错误处理

操作失败时会抛出 `ConvaiRestException`:

```csharp
try
{
    var response = await client.Memory.ListAsync(characterId, endUserId);
}
catch (ConvaiRestException ex)
{
    Debug.LogError($"LTM 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/7a63a06da6d31beb01ce563b8e8b3398f3436122" %}
[排查长期记忆问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/troubleshooting-and-diagnostics.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/long-term-memory-scripting-reference.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.
