> 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/end-user-identity.md).

# 终端用户身份

了解 SDK 如何识别长期记忆范围内的用户，以及如何实现基于身份验证的自定义身份提供程序。

每个长期记忆会话都需要一个稳定的 `end_user_id` ——SDK 在每次连接时都会将此字符串发送给 Convai。Convai 使用它来限定存储记忆的范围：从对话中提取的事实会按以下组合进行存储： `end_user_id` 和 `character_id`。如果此标识符在不同会话间发生变化，服务器就会将该用户视为新人，记忆也不会延续。

SDK 提供了 `DeviceEndUserIdProvider` 作为无需配置的默认实现。对于启用了用户身份验证的应用程序，你可以将其替换为自定义提供程序，让它返回你的账户 ID。

***

### 默认身份： `DeviceEndUserIdProvider`

`DeviceEndUserIdProvider` 同时实现了 `IEndUserIdProvider` 和 `IEndUserIdentityProvider`。它会自动注册，无需配置。

**在 Unity 编辑器中：** 始终读取或创建一个 GUID，并将其存储在 `PlayerPrefs` 中，使用的键为 `"convai.end_user_id"`。同一台机器上的每次 Play Mode 会话都会共用此 GUID，因此在开发和测试期间，记忆会按预期累积。

**在播放器构建中：** 首先尝试使用 `SystemInfo.deviceUniqueIdentifier`。如果该值不可用、为空、等于 `SystemInfo.unsupportedIdentifier`或全为零，则回退到一个 `PlayerPrefs` GUID——生成一次后，在该设备后续的所有会话中重复使用。

GUID 的格式为不带连字符的 32 位十六进制字符串（例如， `a1b2c3d4e5f6789012345678abcdef01`）。你会在控制台日志中以及检查 `EndUserDetails.EndUserId`.

`时看到这种格式。` 重新安装后， `时看到这种格式。` PlayerPrefs [不会保留。清除](#implement-a-custom-identity-provider) 或重新安装应用程序会生成新的 GUID。Convai 会将新 GUID 视为新用户——使用新 ID 将无法访问此前存储的所有记忆（不过这些记忆仍保留在服务器上，并关联旧 ID）。如果应用程序需要在重新安装后保持数据连续性，请通过自定义提供程序使用服务器分配的账户 ID。请参阅下文的

***

### 实现自定义身份提供程序。

**玩家 ID 不等于最终用户 ID `在` ConvaiPlayer `组件上设置玩家 ID，不会改变用于限定记忆范围的` end\_user\_id** 。 `玩家 ID 只决定本地玩家的名称在转录文本和调试日志中的显示方式。记忆范围始终由`IEndUserIdentityProvider `在`.

***

### 决定，而非玩家 ID。实现自定义身份提供程序

如果您的应用会对用户进行身份验证，请实现 `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;
    }
}
```

请使用由后端分配的帐户 ID 作为标识符。不要使用电子邮件地址或显示名称——它们可能会更改，导致服务器将该用户视为新用户。

#### （可选）附加元数据

实现 `IEndUserMetadataProvider` ，以便随身份信息一同发送显示信息。Convai 会将这些元数据存储在 `EndUserDetails.Metadata` 中，并使用 `"name"` 键在编辑器的“长期记忆”面板中填充显示名称。

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

public class AccountMetadataProvider : IEndUserMetadataProvider
{
    private readonly string _displayName;
    private readonly string _department;

    public AccountMetadataProvider(string displayName, string department)
    {
        _displayName = displayName;
        _department = department;
    }

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

#### 在首次连接前注册

在首次会话连接前，调用 `SetEndUserIdentityProvider` 和 `SetEndUserMetadataProvider` ，在 `ConvaiManager` **上进行设置**。如果 `ConvaiCharacter` 已启用 **自动连接** ，则连接会在 `ConvaiRoomManager.Start()` 完成后立即启动——请在 `Awake()`中注册提供程序，而不是在 `Start()`中注册，以确保执行顺序正确。

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

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

    private void Awake()
    {
        // 在 ConvaiRoomManager.Start() 之前调用 — 适用于自动连接角色
        string accountId = AuthService.CurrentUser.AccountId;
        string displayName = AuthService.CurrentUser.DisplayName;
        string department = AuthService.CurrentUser.Department;

        _convaiManager.SetEndUserIdentityProvider(new AccountIdentityProvider(accountId));
        _convaiManager.SetEndUserMetadataProvider(new AccountMetadataProvider(displayName, department));
    }
}
```

{% hint style="danger" %}
如果你在当前会话中调用 `SetEndUserIdentityProvider` 之后， `ConnectAsync` 已经被调用，那么提供程序变更不会影响活动连接。新的提供程序将从下一次 `ConnectAsync` 调用开始生效。请务必在连接前注册。
{% endhint %}

***

### 终端用户 ID 为空或仅包含空白字符

{% hint style="danger" %}
如果 `GetEndUserId()` 返回空字符串、仅包含空白字符的字符串或 `null`，SDK 会在发送前将其规范化为 `null` 。Convai 会将 `null` 视为匿名会话 — **不会存储或检索任何记忆**。请务必确保你的身份来源返回非空且不全为空白字符的值。
{% endhint %}

***

### 身份来源比较

| 场景        | 推荐来源                           | 重新安装后仍保留 | 切换设备后仍保留 |
| --------- | ------------------------------ | -------- | -------- |
| 开发/测试     | `DeviceEndUserIdProvider` （默认） | 否        | 否        |
| 消费类应用，无账户 | `DeviceEndUserIdProvider` （默认） | 否        | 否        |
| 消费类应用，有账户 | 自定义提供程序 → 服务器账户 ID             | 是        | 是        |
| 企业/培训平台   | 自定义提供程序 → 服务器账户 ID             | 是        | 是        |

***

### 后续步骤

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

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


---

# 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/end-user-identity.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.
