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

# 终端用户身份

了解 SDK 如何跨会话识别用户，以及如何用你自己的账户范围身份系统替换默认的基于设备提供程序。

## SDK 如何跨会话识别用户

只有当 Convai 后端能够可靠地将用户与其历史记录关联起来时，长期记忆才有用。用于建立这种关联的标识符是 `end_user_id` ——每次会话连接时发送到服务器的字符串。本页说明 SDK 默认如何生成此标识符、它在各个平台上提供哪些保证，以及如何用由应用管理的身份替换默认标识符。

## 稳定身份为何重要

如果 `end_user_id` 在不同会话之间发生变化，后端就会将该用户视为新人，之前的记忆也不会延续。反过来，如果两个不同用户共用同一个标识符，他们就会共享同一个记忆分区，角色也会混淆他们的身份。正确处理身份是确保长期记忆可靠运行的首要前提。

SDK 会将 `end_user_id` 作为会话连接请求的一部分发送。后端会将其解析为内部的 `speaker_id`，然后使用 `speaker_id:character_id` 作为该用户与该角色相关记忆的存储键。你的应用只会使用 `end_user_id` ——内部键属于后端实现细节。

{% hint style="warning" %}
如果 `end_user_id` 为空或只包含空白字符，SDK 会在发送前将其规范化为 `null` 。服务器会将 `null` 标识符视为匿名会话，不会存储或检索任何记忆。请务必确保你的身份提供程序返回非空字符串。
{% endhint %}

## 默认提供程序：DeviceEndUserIdProvider

SDK 开箱即用地注册 `DeviceEndUserIdProvider` 作为身份来源。它通过以下逻辑生成稳定且限定于设备的标识符：

### Player 构建版本

1. 读取 `SystemInfo.deviceUniqueIdentifier`.
2. 如果该值有效（非 null、非空、不是 `SystemInfo.unsupportedIdentifier`，且不全为零），则直接使用。
3. 否则，生成一个新的 `Guid` （格式为 `"N"`，不含连字符），将其存储在 `PlayerPrefs` 中，键为 `"convai.end_user_id"`，然后返回该值。后续每次运行都会返回同一个 GUID。

### Unity 编辑器

完全跳过设备标识符路径。编辑器始终从 `PlayerPrefs` 读取，使用相同的 `"convai.end_user_id"` 键；首次运行时生成新的 GUID，之后则重复使用。这样，同一项目中的每次 Play Mode 会话都具有一致的身份，无需登录即可测试记忆连续性。

### 平台行为摘要

| 环境                 | 身份来源                                | 持久性                              |
| ------------------ | ----------------------------------- | -------------------------------- |
| 玩家构建版本 — 设备 ID 可用  | `SystemInfo.deviceUniqueIdentifier` | 由操作系统管理；在某些平台上，重新安装后仍会保留         |
| 玩家构建版本 — 设备 ID 不可用 | 存储在 `PlayerPrefs`                   | 应用更新后仍会保留；重新安装或 `PlayerPrefs` 清除 |
| Unity 编辑器          | 存储在 `PlayerPrefs`                   | 编辑器重启后仍会保留；每个 Unity 项目对应一个 ID    |

{% hint style="warning" %}
**PlayerPrefs 并非安全存储。** 在无法获取设备 ID 的平台上，备用 GUID 存储在 `PlayerPrefs` 中，用户或项目中的其他代码都可以读取或清除它。对于身份标识要求严格的应用，请将默认提供程序替换为由身份验证系统支持的提供程序。
{% endhint %}

## PlayerId 字段并非 end\_user\_id

`ConvaiPlayer` 会公开一个 **Player ID** 字段，可在 Inspector 中查看。这是一个 **本地显示标识符** 仅用于转录文本 UI 中的归属标记——即对话动态中显示在玩家发言旁的名称。它绝不会发送到服务器，也不会影响长期记忆。

{% hint style="warning" %}
在 **Player ID** 中设置 `ConvaiPlayer` ——无论是在 Inspector 中设置，还是通过 `ConvaiPlayer.Configure(...)` ——都 **不会** 更改用于记忆的 `end_user_id` 。若要控制服务器用于记忆范围限定的标识符，请按下文所述实现自定义身份提供程序。
{% endhint %}

## 自定义身份提供程序

如果应用管理用户帐户，请替换默认提供程序——例如，用户登录后，您希望将记忆关联到其帐户，而非其物理设备。

### 两个身份接口

SDK 通过两个接口处理身份。对于大多数自定义实现，只需使用其中一个：

| 接口                         | 方法                    | 用途                                                                                        |
| -------------------------- | --------------------- | ----------------------------------------------------------------------------------------- |
| `IEndUserIdentityProvider` | `GetEndUserId()`      | **使用此接口。** 在连接时解析当前用户的标识符。通过以下方法注册： `ConvaiManager.SetEndUserIdentityProvider(provider)`. |
| `IEndUserIdProvider`       | `GenerateEndUserId()` | 较底层的标识符生成接口。由 `DeviceEndUserIdProvider`实现。大多数自定义提供程序不需要使用它。                               |

`DeviceEndUserIdProvider` 同时实现了这两个接口。自定义提供程序通常只实现 `IEndUserIdentityProvider`.

### 步骤 1：实现 IEndUserIdentityProvider

```csharp
using Convai.Domain.Identity;

public class AccountEndUserIdProvider : IEndUserIdentityProvider
{
    private readonly string _accountId;

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

    public string GetEndUserId() => _accountId;
}
```

对于同一位用户，跨会话返回的字符串必须保持稳定。服务器分配的账户 ID、经过哈希处理的电子邮件，或身份验证系统提供的任何不透明标识符都适用。请避免使用会因重新登录或更换设备而变化的值。

### 步骤 2：在连接前注册

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

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

    // Call this after your authentication flow resolves the account ID.
    public void OnUserSignedIn(string accountId)
    {
        var provider = new AccountEndUserIdProvider(accountId);
        _convaiManager.SetEndUserIdentityProvider(provider);
    }
}
```

`ConvaiManager.SetEndUserIdentityProvider` 接受任意 `IEndUserIdentityProvider`。连接会话时只读取一次此提供程序；会话已处于活动状态后再更改它不会生效，必须等到下次连接。

{% hint style="warning" %}
请注册提供程序 **在** 首次连接会话 `之前。如果你在` 之后 `ConvaiManager` 已打开会话后调用 SetEndUserIdentityProvider，则新身份要等到会话重启后才会生效。
{% endhint %}

### 步骤 3（可选）：附加用户元数据

你可以在连接时随 `end_user_id` 一并发送任意元数据。服务器会将其存储在终端用户记录中，你可以在终端用户管理编辑器工具中查看，也可以通过 `EndUsersService`检索。 `"name"` 键会受到特殊处理——它会用作编辑器终端用户列表中的显示名称。

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

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

    public AccountMetadataProvider(string displayName, string role)
    {
        _displayName = displayName;
        _role = role;
    }

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

请将它与身份提供程序一同注册：

```csharp
_convaiManager.SetEndUserIdentityProvider(new AccountEndUserIdProvider(accountId));
_convaiManager.SetEndUserMetadataProvider(new AccountMetadataProvider(displayName, role));
```

## 身份解析摘要

```mermaid
flowchart LR
    A[您的应用] -->|实现| B[IEndUserIdentityProvider]
    B -->|GetEndUserId| C[end_user_id 字符串]
    C -->|连接时发送| D[Convai 服务器]
    D -->|解析为| E[内部 speaker_id]
    E -->|存储键| F["speaker_id : character_id"]
    F --> G[(记忆分区)]
```

## 总结

The `end_user_id` 是长期记忆所有功能的基础——如果它不稳定，记忆就无法延续。默认的 `DeviceEndUserIdProvider` 会自动处理大多数基于设备的部署。对于带有用户账户的应用，请实现 `IEndUserIdentityProvider` 并在首次会话连接前注册。下一页 [为角色启用记忆功能](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin-beta-overview/features/long-term-memory/enabling-memory-on-characters.md)介绍如何为单个角色开启或关闭记忆功能。


---

# 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/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.
