> 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/troubleshooting/connection-and-api-issues.md).

# 连接与 API 问题

解读 Convai 会话错误代码、查看房间管理器诊断信息，并解决身份验证、传输和限流失败。

所有会话错误都会通过 `ConvaiSessionEventRelay.OnSessionError`。事件载荷包含一个 `ErrorCode` 字符串以及一个人类可读的 `Message`。错误代码采用分层点号格式： `{category}.{detail}`。类别前缀告诉你系统的哪一层失败了。

| 类别前缀           | 失败了什么                                             |
| -------------- | ------------------------------------------------- |
| `config.*`     | SDK 配置——缺少 API key、Character ID 或 Auth Token 模式设置 |
| `connection.*` | Convai API 或网络——身份验证、路由、限制                        |
| `transport.*`  | WebRTC / LiveKit 层——ICE、对等连接、信令                   |
| `server.*`     | Convai 自身管线——配额、致命错误                              |
| `session.*`    | 会话生命周期——令牌过期、状态冲突                                 |

### 订阅会话错误

添加 `ConvaiSessionEventRelay` 到与……相同的 GameObject 上 `ConvaiManager` 并在 Inspector 中连接，或在代码中订阅：

```csharp
using Convai.Runtime.Presentation.Events;
using UnityEngine;

public class ErrorListener : MonoBehaviour
{
    [SerializeField] private ConvaiSessionEventRelay _sessionRelay;

    private void OnEnable()
    {
        _sessionRelay.OnSessionError.AddListener(OnError);
    }

    private void OnDisable()
    {
        _sessionRelay.OnSessionError.RemoveListener(OnError);
    }

    private void OnError(SessionErrorRelayData data)
    {
        Debug.LogError($"[MyApp] 会话错误：{data.ErrorCode} — {data.Message}");
    }
}
```

#### 直接读取错误状态

`ConvaiRoomManager` 将最近的错误代码和消息存储为普通属性——无需订阅事件。这对于按需记录诊断状态很有用：

```csharp
var room = FindFirstObjectByType<ConvaiRoomManager>();
Debug.Log($"状态:           {room.CurrentState}");
Debug.Log($"已连接:       {room.IsConnected}");
Debug.Log($"最后错误代码: {room.LastSessionErrorCode}");
Debug.Log($"最后错误信息:  {room.LastSessionErrorMessage}");
Debug.Log($"连接尝试次数:{room.ConnectAttemptCount}  重新连接次数: {room.ReconnectCount}");
```

### 配置错误

配置错误会在连接时立即触发——在任何网络流量之前。先修复这些问题。

| 错误代码                                 | 说明                                                                                    | 修复方法                                                                                                                                                                                        |
| ------------------------------------ | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config.api_key_missing`             | API key 字段为空，位于 `ConvaiSettings`                                                      | 打开 Edit → Project Settings → Convai SDK 并粘贴你的 API key                                                                                                                                       |
| `config.character_id_missing`        | `CharacterId` 上的字段 `ConvaiCharacter` 为空                                               | 在……中设置 Character ID `ConvaiCharacter` Inspector 字段                                                                                                                                          |
| `config.auth_token_provider_missing` | Auth Mode 是 Auth Token，但没有 `IConvaiAuthTokenProvider` 已注册提供程序，也未配置 Token Endpoint URL | 注册一个提供程序或配置 Token Endpoint URL——参见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md)                                                         |
| `config.auth_token_endpoint_invalid` | 已配置的 Token Endpoint URL 不是 HTTPS，也不是回环开发地址                                            | 使用 `https://`，或 `http://localhost` / `http://127.0.0.1` 用于本地开发——参见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md)                         |
| `config.auth_token_mode_required`    | `ConnectWithAuthTokenAsync` 在 Auth Mode 仍为 API Key 时调用了                               | 在调用前先在 Convai Project Settings 中将 Auth Mode 设置为 Auth Token `ConnectWithAuthTokenAsync` ——见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md) |

{% hint style="warning" %}
如果 API key 为空，SDK 会在任何连接尝试之前发出警告： `Convai Bootstrapper：未配置 API key。请在 Edit > Project Settings > Convai SDK 中设置你的 API key。` 这会在播放时触发——请在测试连接前修复。
{% endhint %}

### 连接错误

当 Convai 拒绝或无法满足连接请求时会出现这些代码。大多数都有明确原因和直接修复方法。

| 错误代码                                            | 说明                                         | 自动重试  | 修复方法                                                                                                              |
| ----------------------------------------------- | ------------------------------------------ | ----- | ----------------------------------------------------------------------------------------------------------------- |
| `connection.connect_invalid_api_key`            | 该 API key 被 Convai 拒绝                      | 没有    | 从 Convai 仪表板复制一个新 key；检查是否有尾随空格                                                                                   |
| `connection.auth_token_fetch_failed`            | Auth Token 模式在连接前未能解析出令牌（提供程序异常、令牌为空或端点失败） | 是     | 参见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md) 查看确切的控制台消息和原因 |
| `connection.auth_failed`                        | 身份验证失败（令牌已撤销或凭据错误）                         | 没有    | 重新输入你的 API key；检查该 key 是否已在仪表板中撤销                                                                                 |
| `connection.invalid_token`                      | 提供的连接令牌无效                                  | 没有    | 令牌由内部生成——如果出现此项，请重新连接以生成新令牌                                                                                       |
| `connection.connect_invalid_session_id`         | 连接请求使用了无效的会话标识符                            | 没有    | Session ID 由内部生成——重新连接以重置会话                                                                                       |
| `connection.connect_character_not_found`        | 该 Character ID 在你的账户中不存在                   | 没有    | 确认 Convai 仪表板中的 Character ID 完全一致                                                                                 |
| `connection.connect_realtime_not_allowed`       | 该账户未启用实时访问                                 | 没有    | 升级你的 Convai 方案或联系支持                                                                                               |
| `connection.connect_concurrency_limit_reached`  | 你的方案的同时会话上限已达到                             | 是     | 断开空闲角色；升级方案以获得更高上限                                                                                                |
| `connection.connect_speaker_limit_reached`      | 该账户已达到后端 speaker 上限                        | 没有    | 减少同时处于活动状态的角色数量，或提高你的账户上限。SDK 不会对此重试——与并发限制不同，它被视为硬性限制，而不是临时状况。                                                   |
| `connection.connect_bot_start_failed`           | Convai 管线启动失败（临时性后端问题）                     | 是     | SDK 会自动重试；如果持续存在，请联系支持                                                                                            |
| `connection.connect_unhandled_server_exception` | 连接期间 Convai 发生未处理异常                        | 是     | SDK 会自动重试；如果持续存在，请查看 Convai 状态页面                                                                                  |
| `connection.timeout`                            | 连接未在超时时间内完成                                | 是     | 检查互联网连接；增加 **连接超时** 在设置中（默认 30 秒，最大 120 秒）                                                                        |
| `connection.network_error`                      | DNS 失败、套接字错误或网络不可达                         | 是     | 验证互联网连接；检查 Convai 域名未被防火墙阻止                                                                                       |
| `connection.rate_limited`                       | 短时间内连接请求过多                                 | 是     | 降低重新连接尝试频率；在代码中为重试之间增加延迟                                                                                          |
| `connection.service_unavailable`                | Convai 暂时不可用（HTTP 503）                     | 是     | 等待后重试；SDK 会自动退避                                                                                                   |
| `connection.server_error`                       | Convai 返回了 5xx 错误                          | 是     | 临时性——SDK 会重试；如果持续存在，请查看 Convai 状态页面                                                                               |
| `connection.not_found`                          | 未找到资源（角色或房间）（HTTP 404）                     | 没有    | 确认你的账户中存在该 Character ID                                                                                           |
| `connection.bad_request`                        | 连接请求中的参数无效                                 | 没有    | 检查 CharacterId 和其他连接参数不包含无效字符                                                                                     |
| `connection.connect_validation_error`           | 连接请求未通过 API 验证（HTTP 422）                   | 没有    | 查看错误消息以了解哪个字段验证失败                                                                                                 |
| `connection.failed`                             | 未被特定代码覆盖的通用连接失败                            | 视情况而定 | 检查 `LastSessionErrorMessage` 了解详情                                                                                 |

### 传输错误

传输错误发生在 WebRTC / LiveKit 层，即 Convai 接受连接请求之后。它们几乎总是临时性的，SDK 会自动重试。

| 错误代码                               | 说明                       | 需要检查什么                                 |
| ---------------------------------- | ------------------------ | -------------------------------------- |
| `transport.ice_failed`             | WebRTC ICE 协商失败——无法到达对等端 | 确认网络允许 UDP 流量；企业防火墙常常阻止 WebRTC         |
| `transport.peer_connection_failed` | 无法建立 WebRTC 对等连接         | 与 ICE 失败相同——检查 UDP 端口以及 STUN/TURN 可访问性 |
| `transport.livekit_error`          | LiveKit SDK 报告了错误        | 通常是临时性的；检查网络稳定性                        |
| `transport.signal_disconnected`    | LiveKit 信令服务器连接已断开       | 通常会自动重连；持续失败表明网络不稳定                    |

{% hint style="info" %}
WebRTC 需要可访问 UDP 端口。在企业部署中，请与你的网络团队合作，将 Convai LiveKit 端点列入白名单。完整的域名和端口列表请参见 Network & API Requirements 页面。
{% endhint %}

### 服务器与使用错误

| 错误代码                         | 说明                     | 修复方法                          |
| ---------------------------- | ---------------------- | ----------------------------- |
| `server.usage_limit_reached` | 已超过每日或每月使用配额           | 在 Convai 仪表板中查看使用情况；升级你的方案    |
| `server.fatal_error`         | 致命管线错误——会话已被 Convai 终止 | 会话无法恢复；发起新的连接                 |
| `server.error`               | Convai 报告了非致命管线错误      | SDK 会重试；如果持续存在，请向 Convai 支持报告 |

### 会话与协议错误

| 错误代码                       | 说明                    | 修复方法                               |
| -------------------------- | --------------------- | ---------------------------------- |
| `session.token_expired`    | 会话令牌已过期               | 重新连接以获取新令牌                         |
| `session.invalid_state`    | 在无效状态下尝试了某个操作         | 检查你的 connect/disconnect 调用顺序       |
| `session.cancelled`        | 会话已被你的代码取消            | 如果你调用……这是预期的 `DisconnectAsync` 手动地 |
| `protocol.message_invalid` | 从 Convai 收到了无效的协议消息   | 通常表明 SDK/后端版本不匹配；更新 SDK            |
| `protocol.parse_failed`    | SDK 无法解析来自 Convai 的消息 | 通常表明 SDK/后端版本不匹配；更新 SDK            |

### 重试行为

SDK 对临时性错误使用指数退避策略。每次失败尝试后，它会先等待再重试：

| 尝试    | 此次尝试前的延迟 |
| ----- | -------- |
| 1（初始） | 无——立即    |
| 2     | 1 秒      |
| 3     | 2 秒      |
| 4（最终） | 4 秒      |

尝试四次后，SDK 放弃并触发 `OnSessionError` 并带上最终错误代码。 **非临时性错误——例如无效 API key、找不到角色或不允许实时——完全不会重试。** SDK 会触发 `OnSessionError` 立即。

以下错误代码会触发自动重试：

* `connection.timeout`
* `connection.network_error`
* `connection.server_error`
* `connection.service_unavailable`
* `connection.rate_limited`
* `connection.connect_concurrency_limit_reached`
* `connection.connect_bot_start_failed`
* `connection.connect_unhandled_server_exception`
* `connection.auth_token_fetch_failed`
* `transport.ice_failed`
* `transport.signal_disconnected`
* `server.error`

### 运行时诊断

读取 `ConvaiRoomManager` 使用状态属性来缩小连接失败范围。属性会实时更新——无需订阅事件。完整属性参考、诊断快照 API 和代码示例请参见 Debug Tools Reference。

{% content-ref url="/pages/41fb22d336940f24c4bfbf2655c6122580016b9b" %}
[调试工具参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/troubleshooting/debug-tools-reference.md)
{% endcontent-ref %}

### 快速参考：常见故障模式

| 症状                                        | 可能原因                    | 修复方法                                                                  | 验证                             |
| ----------------------------------------- | ----------------------- | --------------------------------------------------------------------- | ------------------------------ |
| `config.api_key_missing` 每次连接时            | 从未输入 API key            | Edit → Project Settings → Convai SDK → 粘贴 key                         | 重新进入 Play 模式——错误不再触发           |
| `connection.connect_invalid_api_key`      | 错误或已撤销的 API key         | 从 Convai 仪表板复制一个新 key                                                 | 会话到达 `已连接` state               |
| `connection.connect_character_not_found`  | Character ID 拼写错误或账户错误  | 在 Convai 仪表板中验证；检查复制粘贴产生的空白字符                                         | 会话到达 `已连接` state               |
| `connection.connect_realtime_not_allowed` | 账户未启用实时功能               | 升级方案                                                                  | 会话到达 `已连接` state               |
| `connection.timeout` 每次                   | 防火墙阻止连接                 | 将 Convai 域名列入白名单；尝试使用其他网络                                             | 会话在超时窗口内连接成功                   |
| `transport.ice_failed` 反复地                | 严格防火墙阻止 UDP             | 允许 UDP；向网络管理员请求 TURN 中继                                               | 会话连接成功；WebRTC 协商完成             |
| `server.usage_limit_reached`              | 配额超出                    | 查看 Convai 仪表板的使用情况页面                                                  | 在使用额度重置或方案升级后会话连接成功            |
| 角色连接一次后便再也不重连                             | `ReconnectPolicy` 已达到上限 | SDK 在 3 次重新连接尝试后停止（默认 `MaxReconnectAttempts`）；再次调用 `ConnectAsync` 以重试 | `ConnectAsync` 调用成功；角色连接成功     |
| `connection.rate_limited`                 | 短时间内连接过多                | 在你的应用逻辑中为连接调用添加最小延迟                                                   | `connection.rate_limited` 不再触发 |
| `CurrentState` 卡在 `Error`                 | 无法恢复的会话失败               | 调用 `DisconnectAsync()` 然后 `ConnectAsync()` 以重置                        | 会话转变为 `已连接`                    |

### 下一步

关于 SDK 日志系统、内置诊断工具和会话指标的完整参考，请参见 Debug Tools Reference。

{% content-ref url="/pages/41fb22d336940f24c4bfbf2655c6122580016b9b" %}
[调试工具参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/troubleshooting/debug-tools-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/troubleshooting/connection-and-api-issues.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.
