> 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/usage-examples.md).

# 长期记忆使用示例

Unity 长期记忆的四种完整模式——零配置持久化、身份验证、记忆预置和记忆重置。

这些示例涵盖了最常见的四种长期记忆集成模式。每个示例都可以独立运行，并展示了完整的设置步骤、相关代码和预期的运行结果。

### 模式 1 — 零配置持久化

如果 `DeviceEndUserIdProvider` （SDK 默认值）满足需求，且不需要按账户区分记忆，则无需编写代码。在仪表板中启用 LTM 后，SDK 会自动处理身份识别和存储。

**适用场景：** 没有用户账户的消费级应用、快速原型，或基于编辑器的测试。

**限制：** 记忆与设备绑定。清除 `PlayerPrefs` 或重新安装应用会生成新的身份标识，之前的记忆不会保留。

**设置：**

1. 登录 [convai.com](https://convai.com)，打开角色，并将 **长期记忆** 切换为 **开启** （位于 **记忆** 选项卡中）。
2. 将 `ConvaiManager` 和 `ConvaiCharacter` 添加到场景中，并配置角色 ID。
3. 进入播放模式并开始对话。退出播放模式以触发记忆提取。
4. 再次进入播放模式，确认角色能够回忆起之前分享的内容。

无需注册 `IEndUserIdentityProvider` 。SDK 默认使用 `DeviceEndUserIdProvider` 。

**预期结果：** 角色会自动提及之前会话中的事实。同一台机器上的每个会话都会使用 `PlayerPrefs["convai.end_user_id"]` 中存储的同一个 GUID。

***

### 模式 2 — 身份验证

当用户通过账户登录时，使用自定义的 `IEndUserIdentityProvider` 。这样可以确保用户在更换设备或重新安装应用后仍能保留记忆。

**适用场景：** 带有用户身份验证的应用，例如企业培训平台、入职引导系统，以及支持账户的消费级应用。

```csharp
using Convai.Domain.Identity;

public class AccountIdentityProvider : IEndUserIdentityProvider
{
    private readonly string _accountId;

    public AccountIdentityProvider(string accountId)
    {
        _accountId = accountId;
    }

    public string GetEndUserId()
    {
        return _accountId;
    }
}
```

在 `Awake()` 中注册提供程序，确保注册发生在 `ConvaiRoomManager.Start()` 执行完成之前：

```csharp
using Convai.Runtime.Components;
using UnityEngine;

public class IdentityRegistrar : MonoBehaviour
{
    [SerializeField] private ConvaiManager _convaiManager;

    private void Awake()
    {
        string accountId = AuthService.CurrentUser.AccountId;
        _convaiManager.SetEndUserIdentityProvider(new AccountIdentityProvider(accountId));
    }
}
```

还可以附加显示名称，这样编辑器的“长期记忆”面板会显示易读的标签，而不是原始 ID：

```csharp
using System.Collections.Generic;
using Convai.Domain.Identity;

public class AccountMetadataProvider : IEndUserMetadataProvider
{
    private readonly string _displayName;

    public AccountMetadataProvider(string displayName)
    {
        _displayName = displayName;
    }

    public IReadOnlyDictionary<string, object> GetEndUserMetadata()
    {
        return new Dictionary<string, object> { { "name", _displayName } };
    }
}
```

```csharp
_convaiManager.SetEndUserMetadataProvider(
    new AccountMetadataProvider(AuthService.CurrentUser.DisplayName));
```

**预期结果：** 每位用户的记忆都存储在其账户 ID 下。记忆会在不同设备和重新安装后保留。编辑器面板会显示用户的显示名称。

***

### 模式 3 — 首次会话前预置记忆

在用户首次对话前预先加载相关事实，让角色从一开始就能引用已完成的模块、认证或入职状态。

{% hint style="danger" %}
**请勿在面向玩家的构建版本中使用此模式。** `ConvaiRestClient` 需要使用你的 API 密钥。将 API 密钥嵌入分发的应用程序会使其暴露，容易被提取。仅可通过服务器端服务或编辑器工具预置记忆。
{% endhint %}

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

public class OnboardingMemorySeeder : MonoBehaviour
{
    // 仅供编辑器或服务器端使用 — 切勿随附嵌入的 API 密钥
    [ContextMenu("为新员工预置记忆")]
    private async void SeedEmployeeMemory()
    {
        string characterId = "onboarding-assistant-id";
        string employeeAccountId = "emp-00421";

        var certifications = new List<string>
        {
            "The employee completed Fire Safety Level 1 on 2025-04-10.",
            "The employee completed Hazardous Materials Handling on 2025-04-15.",
            "The employee has not yet completed Confined Space Entry certification."
        };

        using var client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);
        var response = await client.Memory.AddAsync(characterId, employeeAccountId, certifications);

        Debug.Log($"Seeded {response.Memories.Count} memory records.");
    }
}
```

**预期结果：** 员工首次与入职助手对话时，角色已了解其认证状态，并会引导他们学习下一个必修模块。

***

### 模式 4 — 重置用户记忆

清除某个用户与角色组合的所有已存储事实，然后可选择停用 LTM。当用户记录已过时，或需要在测试会话之间重置时，可使用此操作。

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

public class MemoryReset : MonoBehaviour
{
    [ContextMenu("清除记忆后停用 LTM")]
    private async void PurgeAndDisable()
    {
        string characterId = "your-character-id";
        string endUserId = "target-end-user-id";

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

        // 第 1 步：删除此用户与角色组合的所有记忆
        await client.Memory.DeleteAllAsync(characterId, endUserId);
        Debug.Log("Memories purged.");

        // 第 2 步：停用角色的 LTM
        await client.Characters.SetMemoryEnabledAsync(characterId, false);
        Debug.Log("Long-term memory disabled.");
    }
}
```

如果只想删除记忆并保持 LTM 启用，请调用 `DeleteAllAsync` 并跳过 `SetMemoryEnabledAsync` 步骤。如果要删除用户在所有角色下的记录，而非仅针对一个角色，请改用 `client.EndUsers.DeleteAsync(endUserId)` 。请参阅 [管理终端用户记录](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/end-user-management.md).

**预期结果：** 此用户与角色组合的下一次会话将不包含任何已存储的上下文。角色会将该用户视为新联系人。

***

### 后续步骤

{% content-ref url="/pages/0b7e1084a14c3bcf13fec179ad83b458f07ecff4" %}
[记忆管理 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/memory-management-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/9c55a31cd790424665e521972bff5affc2dbe7f9" %}
[长期记忆脚本参考](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)
{% 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/usage-examples.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.
