> 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 密钥、Character ID，或未设置 Auth Token 模式 |
| `connection.*` | Convai API 或网络 — 身份验证、路由、限制                        |
| `transport.*`  | WebRTC / LiveKit 层 — ICE、对等连接、信令                   |
| `server.*`     | Convai 自身的处理流程 — 配额、致命错误                           |
| `session.*`    | 会话生命周期 — 令牌过期、状态冲突                                 |

### 订阅会话错误

将 `ConvaiSessionEventRelay` 添加到与 `ConvaiManager` 相同的 GameObject 上，并在 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] Session error: {data.ErrorCode} — {data.Message}");
    }
}
```

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

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

```csharp
var room = FindFirstObjectByType<ConvaiRoomManager>();
Debug.Log($"State:           {room.CurrentState}");
Debug.Log($"Connected:       {room.IsConnected}");
Debug.Log($"Last error code: {room.LastSessionErrorCode}");
Debug.Log($"Last error msg:  {room.LastSessionErrorMessage}");
Debug.Log($"Connect attempts:{room.ConnectAttemptCount}  Reconnects: {room.ReconnectCount}");
```

### 配置错误

配置错误会在连接时立即触发 — 此时尚未产生任何网络流量。请先修复这些错误。

| 错误代码                                 | 说明                                                                          | 解决方法                                                                                                                                                                                                            |
| ------------------------------------ | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config.api_key_missing`             | 中的 API 密钥字段为空： `ConvaiSettings`                                             | 打开 Edit → Project Settings → Convai SDK，然后粘贴 API 密钥                                                                                                                                                             |
| `config.character_id_missing`        | `CharacterId` 字段位于 `ConvaiCharacter` 为空                                     | 在 `ConvaiCharacter` 检查器字段中设置 Character ID                                                                                                                                                                       |
| `config.auth_token_provider_missing` | 身份验证模式为 Auth Token，但未注册 `IConvaiAuthTokenProvider` ，且未配置 Token Endpoint URL | 注册一个提供程序或配置 Token Endpoint URL——请参阅 [身份验证故障排除](https://docs.convai.com/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` ——请参阅 [身份验证故障排除](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md)                  |
| `config.auth_token_mode_required`    | `ConnectWithAuthTokenAsync` 调用时，身份验证模式仍为 API Key                            | 调用 `ConnectWithAuthTokenAsync` 之前，请在 Convai Project Settings 中将身份验证模式设为 Auth Token——请参阅 [身份验证故障排除](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md) |

{% hint style="warning" %}
如果 API 密钥为空，SDK 会在尝试连接前发出警告： `Convai Bootstrapper: API key not configured. Please set your API key in Edit > Project Settings > Convai SDK.` 此警告会在进入 Play 模式时触发——请在测试连接前修复。
{% endhint %}

### 连接错误

Convai 拒绝或无法完成连接请求时，会出现这些代码。大多数错误都有明确原因和直接的解决方法。

| 错误代码                                            | 说明                                   | 自动重试  | 解决方法                                                                                                                                      |
| ----------------------------------------------- | ------------------------------------ | ----- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `connection.connect_invalid_api_key`            | Convai 拒绝了此 API 密钥                   | 否     | 从 Convai 控制面板复制一个新密钥；检查末尾是否有空格                                                                                                            |
| `connection.auth_token_fetch_failed`            | 身份验证令牌模式在连接前未能获取令牌（提供程序异常、令牌为空或端点故障） | 是     | 请参阅 [身份验证故障排除](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md) 了解具体的控制台消息和原因 |
| `connection.auth_failed`                        | 身份验证失败（令牌已撤销或凭据无效）                   | 否     | 重新输入 API 密钥；检查该密钥是否已在控制面板中撤销                                                                                                              |
| `connection.invalid_token`                      | 提供的连接令牌无效                            | 否     | 令牌由内部生成——如果出现此错误，请重新连接以生成新令牌                                                                                                              |
| `connection.connect_invalid_session_id`         | 连接请求使用了无效的会话标识符                      | 否     | 会话 ID 由内部生成——重新连接即可重置会话                                                                                                                   |
| `connection.connect_character_not_found`        | 此账号中不存在该角色 ID                        | 否     | 请确认 Convai 控制台中的角色 ID 完全一致                                                                                                                |
| `connection.connect_realtime_not_allowed`       | 此账号未启用实时访问权限                         | 否     | 请升级 Convai 套餐或联系支持团队                                                                                                                      |
| `connection.connect_concurrency_limit_reached`  | 已达到套餐允许的同时会话数上限                      | 是     | 断开空闲角色；升级套餐以提高上限                                                                                                                          |
| `connection.connect_speaker_limit_reached`      | 此账号已达到后端说话者数量上限                      | 否     | 减少同时处于活动状态的角色数量，或提高账号的上限。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）               | 否     | 请确认此账号中存在该角色 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 端点加入允许列表。完整的域名和端口列表请参阅“网络与 API 要求”页面。
{% 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 密钥无效、未找到角色或未启用实时功能），不会进行任何重试。** 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 和代码示例，请参阅调试工具参考。

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

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

| 症状                                        | 可能原因                    | 解决方法                                                                    | 验证                             |
| ----------------------------------------- | ----------------------- | ----------------------------------------------------------------------- | ------------------------------ |
| `config.api_key_missing` 每次连接时            | 从未输入 API 密钥             | 编辑 → 项目设置 → Convai SDK → 粘贴密钥                                           | 重新进入播放模式 — 不再触发错误              |
| `connection.connect_invalid_api_key`      | API 密钥错误或已撤销            | 从 Convai 控制面板复制新的密钥                                                     | 会话进入 `Connected` 状态            |
| `connection.connect_character_not_found`  | 角色 ID 拼写错误或账号不正确        | 在 Convai 控制面板中验证；检查复制粘贴时是否带入空格                                          | 会话进入 `Connected` 状态            |
| `connection.connect_realtime_not_allowed` | 账号未启用实时功能               | 升级套餐                                                                    | 会话进入 `Connected` 状态            |
| `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()` 以重置                          | 会话转换为 `Connected`              |

### 后续步骤

如需了解 SDK 日志系统、内置诊断工具和会话指标的完整参考，请参阅《调试工具参考》。

{% content-ref url="/pages/41fb22d336940f24c4bfbf2655c6122580016b9b" %}
[调试工具参考](https://docs.convai.com/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.
