> 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 问题

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

| 类别前缀           | 发生故障的部分                         |
| -------------- | ------------------------------- |
| `config.*`     | SDK 配置——缺少 API 密钥或 Character ID |
| `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 密钥字段为空 `ConvaiSettings`          | 打开 Edit → Project Settings → Convai SDK 并粘贴你的 API 密钥 |
| `config.character_id_missing` | `CharacterId` 上的字段 `ConvaiCharacter` 为空 | 在以下位置设置 Character ID： `ConvaiCharacter` Inspector 字段 |

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

### 连接错误

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

| 错误代码                                            | 说明                       | 自动重试 | 修复                                         |
| ----------------------------------------------- | ------------------------ | ---- | ------------------------------------------ |
| `connection.connect_invalid_api_key`            | API 密钥被 Convai 拒绝        | 没有   | 从 Convai 仪表板复制一个新的密钥；检查末尾是否有空格             |
| `connection.auth_failed`                        | 身份验证失败（令牌已撤销或凭据错误）       | 没有   | 重新输入你的 API 密钥；检查该密钥是否已在仪表板中被撤销             |
| `connection.invalid_token`                      | 提供的连接令牌无效                | 没有   | 令牌由内部生成——如果出现此错误，请重新连接以生成新令牌               |
| `connection.connect_invalid_session_id`         | 连接请求使用了无效的会话标识符          | 没有   | 会话 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`      | 此账户已达到后端发言者上限            | 是    | 减少并发活动角色数量                                 |
| `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`    | 在无效状态下尝试了某个操作         | 检查你的连接/断开连接调用顺序            |
| `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`
* `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 密钥             | Edit → Project Settings → Convai SDK → 粘贴密钥                         | 重新进入播放模式——错误不再触发               |
| `connection.connect_invalid_api_key`      | 错误或已撤销的 API 密钥          | 从 Convai 仪表板复制一个新的密钥                                                | 会话到达 `已连接` 状态                  |
| `connection.connect_character_not_found`  | Character ID 拼写错误或账户错误  | 在 Convai 仪表板中验证；检查复制粘贴产生的空白字符                                       | 会话到达 `已连接` 状态                  |
| `connection.connect_realtime_not_allowed` | 账户未启用实时功能               | 升级套餐                                                                | 会话到达 `已连接` 状态                  |
| `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` 卡在 `错误`                    | 无法恢复的会话故障               | 调用 `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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/troubleshooting/connection-and-api-issues.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
