> 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/troubleshooting-and-diagnostics.md).

# 排查长期记忆问题

排查长期记忆无法持久保存的原因，验证终端用户身份在不同会话间是否稳定，并解决 Memory Management API 的 HTTP 错误。

大多数 LTM 问题可分为三类：记忆无法在不同会话间保留、记忆被分配给了错误的用户，以及 API 调用因 HTTP 错误而失败。查阅参考表格前，请先按以下诊断流程逐步排查。

***

### 初步排查

在检查其他内容之前，请按顺序完成以下三个步骤：

**1. 确认已为角色启用记忆功能**

登录 [convai.com](https://convai.com)，打开角色，并确认 **Memory** 选项卡显示 **Long-Term Memory: On**。默认情况下，记忆处于禁用状态——这是 LTM 看似无法正常工作的最常见原因。

**2. 确认终端用户 ID 在不同会话间保持稳定**

将以下诊断脚本添加到场景中。运行 Play Mode，停止后再运行一次。两次记录的 ID 必须完全相同。

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

public class EndUserIdDebug : MonoBehaviour
{
    private void Start()
    {
        var provider = new DeviceEndUserIdProvider();
        string id = provider.GetEndUserId();
        Debug.Log($"[LTM] end_user_id this session: {id}");
    }
}
```

如果 ID 在不同会话间发生变化，记忆就无法累积——服务器会将每个新 ID 视为新用户。

**3. 确认会话已成功连接**

检查 Console 中的 Convai 启动消息。连接失败（API 密钥无效、网络错误）会导致所有 LTM 操作无法进行，无论是否已有存储的数据。

***

### 判断流程

记忆无法保留时，请按以下流程排查：

```mermaid
graph TD
    A[LTM 是否已在角色控制面板中启用？] -->|否| B[前往 convai.com 启用并重试]
    A -->|是| C[不同会话中记录的 end_user_id 是否相同？]
    C -->|否| D[身份标识来源正在变化 — 请参阅“常见问题”]
    C -->|是| E[会话是否已成功连接？]
    E -->|否| F[先修复连接问题 — 检查 API 密钥或网络]
    E -->|是| G[对话中是否包含值得记住的信息？]
    G -->|否| H[进行更深入的对话后重试]
    G -->|是| I[联系 Convai 支持，并提供角色 ID 和会话时间戳]
```

***

### 常见问题

| 症状                      | 可能原因                                       | 解决方法                                                                                                                |
| ----------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| 角色从不提及之前会话中的内容          | 未为角色启用 LTM                                 | 在 [convai.com](https://convai.com)                                                                                  |
| 记忆在编辑器中有效，在构建版本中无效      | `DeviceEndUserIdProvider` 在编辑器和构建版本中返回不同的值 | 这是预期行为——编辑器使用 `PlayerPrefs` GUID；构建版本使用设备 ID。请确保构建版本的设备 ID 保持稳定。若要在不同上下文间保持一致，请实现自定义的 `IEndUserIdentityProvider`.   |
| 重新安装后记忆丢失               | `PlayerPrefs` 会在重新安装时被清除                   | 通过自定义提供程序使用服务器分配的账户 ID。基于设备和 GUID 的 ID 无法在重新安装后保留。                                                                  |
| 同一设备上的不同用户共享记忆          | 多位用户共用一台设备                                 | 必须为每位用户分配唯一的 `end_user_id`。如果 `DeviceEndUserIdProvider` 正在使用，则会共享设备级 GUID。请实现一个自定义提供程序，以返回每位用户各自的账户 ID。             |
| 自定义提供程序未生效              | 在 `ConnectAsync`                           | 之前注册。请在 `Awake()`中注册，并确保在 `ConvaiRoomManager.Start()` 完成之前完成注册。如果 `ConvaiCharacter` 已启用 **自动连接** ， `Start()` 可能会太晚。 |
| 记忆事实看起来不正确或已过时          | 测试遗留的过期记录                                  | 使用 `client.Memory.DeleteAllAsync` 在开始新的评估前清除测试数据。                                                                   |
| `GetEndUserId()` 返回空字符串 | 自定义提供程序返回 null 或空白字符                       | SDK 会在发送前将 null/空白字符规范化为 `null` ，因此会产生匿名会话。请确保提供程序始终返回非空值。                                                          |

***

### 运行时诊断

#### 列出用户的所有记忆

使用此脚本确认服务器存储的内容。可在 Inspector 中右键单击，然后选择 → **列出记忆**.

```csharp
using Convai.RestAPI;
using Convai.RestAPI.Internal;
using Convai.Runtime;
using Convai.Runtime.Identity;
using UnityEngine;

public class MemoryDiagnostic : MonoBehaviour
{
    [SerializeField] private string _characterId;

    [ContextMenu("List Memories")]
    private async void ListMemories()
    {
        var provider = new DeviceEndUserIdProvider();
        string endUserId = provider.GetEndUserId();

        Debug.Log($"[LTM] Querying memories for end_user_id: {endUserId}");

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

        int page = 1;
        bool hasMore = true;
        int totalRecords = 0;

        while (hasMore)
        {
            var response = await client.Memory.ListAsync(_characterId, endUserId, page);

            Debug.Log($"[LTM] Page {page} — {response.Memories.Count} records (total: {response.TotalCount})");

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

            totalRecords += response.Memories.Count;
            hasMore = response.HasMore;
            page++;
        }

        if (totalRecords == 0)
            Debug.Log("[LTM] No memory records found for this user–character pair.");
    }
}
```

#### 检查记忆启用状态

以编程方式确认当前是否已为某个角色启用 LTM。

```csharp
[ContextMenu("Check Memory Enabled")]
private async void CheckMemoryEnabled()
{
    using var client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);

    bool isEnabled = await client.Characters.GetMemoryEnabledAsync(_characterId);
    Debug.Log($"[LTM] Memory enabled for character '{_characterId}': {isEnabled}");
}
```

***

### API 错误代码

所有记忆管理 API 错误都会抛出 `ConvaiRestException`。其 `StatusCode` 属性对应以下原因。

| HTTP 状态                     | 原因                                                | 解决方法                                                                                                                                       |
| --------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `400 Bad Request`           | 缺少必需参数（`character_id`, `end_user_id`或 `memories`) | 调用前请确认所有必需参数均非 null 且不为空                                                                                                                   |
| `401 Unauthorized`          | API 密钥无效或缺失                                       | 重新配置 API 密钥，参见 [配置 API 密钥](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/getting-started/configure-api-key.md) |
| `403 Forbidden`             | 该角色不属于 API 密钥所有者的账户                               | 请确认角色 ID 属于与 API 密钥关联的账户                                                                                                                   |
| `404 Not Found`             | 角色 ID、最终用户 ID 或记忆 ID 无效                           | 请对照 Convai 控制面板仔细检查 ID。如果按 `memoryId`查询，请通过之前的 `ListAsync` 调用验证该 ID。                                                                       |
| `429 Too Many Requests`     | 超出速率限制                                            | 实现指数退避。例如，在 `2^attempt` 秒后重试，并使用 `CancellationToken` 在达到最大重试次数后中止。                                                                         |
| `500 Internal Server Error` | 暂时性服务器错误                                          | 短暂延迟后重试请求。如果错误持续出现，请查看 Convai 状态页面，并向支持团队提供角色 ID 和时间戳。                                                                                     |

#### 指数退避模式

```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Convai.RestAPI;

public static class MemoryRetryHelper
{
    public static async Task<T> WithRetry<T>(
        Func<Task<T>> operation,
        int maxAttempts = 3,
        CancellationToken cancellationToken = default)
    {
        for (int attempt = 0; attempt < maxAttempts; attempt++)
        {
            try
            {
                return await operation();
            }
            catch (ConvaiRestException ex) when (ex.StatusCodeInt == 429 || ex.StatusCodeInt == 500)
            {
                if (attempt == maxAttempts - 1) throw;

                int delayMs = (int)Math.Pow(2, attempt) * 1000;
                await Task.Delay(delayMs, cancellationToken);
            }
        }

        throw new InvalidOperationException("Unreachable.");
    }
}
```

***

### 后续步骤

{% 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 %}

{% content-ref url="/pages/b54beab8714c42a31356b3abe240c02692f3d79b" %}
[为角色配置记忆](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/long-term-memory/configure-memory-for-a-character.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/troubleshooting-and-diagnostics.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.
