> 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/vision/scripting-api.md).

# Vision 脚本 API

Convai Unity SDK Vision 脚本 API 参考，包括发布控制、运行时状态查询、按需触发以及 respond-mode 事件。

视觉脚本主要围绕 `ConvaiVisionPublisher` 进行发布控制， `ConvaiRoomManager` 用于按需查询视觉状态和触发操作，帧源状态接口则用于获取捕获状态。领域事件可让你在生命周期发生变化或收到后端确认时作出响应，而无需轮询 `IsPublishing` 每一帧。

### `ConvaiVisionPublisher`

`ConvaiVisionPublisher` 是一个 `MonoBehaviour` ，用于管理 WebRTC 视频轨道。可通过 `GetComponent` 或序列化字段获取其引用。

#### 属性

| 属性               | 类型                    | 说明                                  |
| ---------------- | --------------------- | ----------------------------------- |
| `IsPublishing`   | `bool`                | `true` 表示 WebRTC 视频轨道正在主动发送数据。      |
| `FrameSource`    | `IVisionFrameSource`  | 当前正在使用的帧源。 `null` ，直到运行时注册完成。       |
| `PublishPolicy`  | `VisionPublishPolicy` | 当前的发布策略。                            |
| `VideoTrackName` | `string`              | WebRTC 轨道的名称（默认值： `"unity-scene"`). |

#### 方法

| 方法                                             | 说明                                                                                                      |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `SetPublishPolicy(VisionPublishPolicy policy)` | 更改客户端传输预算。将在下一帧发布时生效。                                                                                   |
| `EnablePublishing(bool enabled)`               | 在不更改所选策略的情况下启动或停止发布。该设置在所有策略下均有效，不仅限于 `Manual`。调用后，在本次会话剩余期间，该设置还会覆盖策略自身的启用或停用默认值；因此，之后更改策略将不再决定是否执行发布。 |

#### 用法

```csharp
using Convai.Modules.Vision;
using Convai.Runtime.Vision.Publishing;
using UnityEngine;

public class VisionController : MonoBehaviour
{
    [SerializeField] private ConvaiVisionPublisher _publisher;

    void Start()
    {
        // 将此场景切换为高响应模式
        _publisher.SetPublishPolicy(VisionPublishPolicy.HighResponsiveness);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
            bool isPublishing = _publisher.IsPublishing;
            Debug.Log($"Track '{_publisher.VideoTrackName}' publishing: {isPublishing}");
        }
    }
}
```

### `IVisionFrameSource`

所有内置帧源和任何自定义帧源都实现了此接口。

| 成员                     | 类型                           | 说明                                                |
| ---------------------- | ---------------------------- | ------------------------------------------------- |
| `IsCapturing`          | `bool` 属性                    | `true` 当源正在主动生成帧时。                                |
| `FrameCount`           | `long` 属性                    | 自开始捕获以来生成的总帧数。                                    |
| `FrameDimensions`      | `(int Width, int Height)` 属性 | 输出分辨率。返回 `(0, 0)` 初始化前。                           |
| `TargetFrameRate`      | `float` 属性                   | 配置的每秒帧数。                                          |
| `SourceId`             | `string` 属性                  | 用于多源场景的标识符字符串。                                    |
| `CurrentRenderTexture` | `RenderTexture` 属性           | 已沿 Y 轴翻转的 `RenderTexture` 其中包含最新帧。 `null` 未进行捕获时。 |
| `IsFrameReady`         | `bool` 属性                    | `true` 首个可用帧就绪后。                                  |
| `FrameReady`           | `event Action`               | 每当有新帧可用时，在 Unity 主线程上触发。                          |
| `StartCapture()`       | 方法                           | 开始捕获帧。                                            |
| `StopCapture()`        | 方法                           | 停止捕获帧并释放资源。                                       |

### `IVisionFrameSourceStatusProvider`

由内置源实现的可选伴随接口。提供更丰富的状态和错误信息。

| 成员               | 类型                         | 说明                                                    |
| ---------------- | -------------------------- | ----------------------------------------------------- |
| `State`          | `VisionSourceState` 属性     | 当前生命周期状态。                                             |
| `ErrorKind`      | `VisionSourceErrorKind` 属性 | 当 `State == Failed`.                                  |
| `StatusMessage`  | `string` 属性                | 人类可读的状态详情。                                            |
| `HasUsableFrame` | `bool` 属性                  | `true` 当源至少生成一帧有效帧时。                                  |
| `StatusChanged`  | `event Action`             | 在以下内容发生变化时触发： `State`, `ErrorKind`或 `StatusMessage` 。 |

### 监视状态变化

```csharp
using Convai.Runtime.Vision.Sources;
using UnityEngine;

public class FrameSourceMonitor : MonoBehaviour
{
    [SerializeField] private MonoBehaviour _frameSourceComponent;

    private IVisionFrameSourceStatusProvider _statusProvider;

    void Start()
    {
        _statusProvider = _frameSourceComponent as IVisionFrameSourceStatusProvider;
        if (_statusProvider != null)
            _statusProvider.StatusChanged += OnStatusChanged;
    }

    void OnDestroy()
    {
        if (_statusProvider != null)
            _statusProvider.StatusChanged -= OnStatusChanged;
    }

    private void OnStatusChanged()
    {
        Debug.Log($"[Vision] State: {_statusProvider.State}  Error: {_statusProvider.ErrorKind}  {_statusProvider.StatusMessage}");

        if (_statusProvider.State == VisionSourceState.Failed)
            HandleCaptureFailure(_statusProvider.ErrorKind);
    }

    private void HandleCaptureFailure(VisionSourceErrorKind errorKind)
    {
        switch (errorKind)
        {
            case VisionSourceErrorKind.PermissionDenied:
                // Show UI prompting the user to grant camera permission
                break;
            case VisionSourceErrorKind.DeviceUnavailable:
                // Offer to switch to a different frame source
                break;
        }
    }
}
```

### `VisionSourceState` 参考

| 状态                   | 含义                                           |
| -------------------- | -------------------------------------------- |
| `Idle`               | 尚未启动采集。                                      |
| `AwaitingPermission` | 正在等待用户授予摄像头权限（Android / iOS）。                |
| `Starting`           | 正在初始化采集——设备正在打开， `RenderTexture`正在创建。        |
| `Ready`              | 采集正在运行，并持续生成帧。                               |
| `Degraded`           | 采集正在运行，但帧健康检查检测到了问题（例如，连续出现空白帧）。             |
| `Stopped`            | 采集已正常停止。                                     |
| `Failed`             | 采集失败，无法继续。请检查 `ErrorKind` 和 `StatusMessage`. |

### `ConvaiRoomManager` 视觉方法

`ConvaiRoomManager` 实现 `IConvaiRoomConnectionService` ，并提供三个运行时方法，用于在会话期间查询和驱动动态视觉上下文，而无需重新连接。可通过序列化 `ConvaiRoomManager` 字段、自定义 `IConvaiRoomConnectionService` 实现，或在没有可用场景引用时通过 `ConvaiManager.ActiveManager.TryGetRoomConnectionService(out IConvaiRoomConnectionService service)` 访问这些方法。

{% hint style="info" %}
自定义 `IConvaiRoomConnectionService` 实现必须实现以下全部三个方法。如果该实现不支持视觉功能，则任何一个方法都应返回 `false` 。
{% endhint %}

| 方法                                                                                              | 返回     | 说明                                                                                                                |
| ----------------------------------------------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------- |
| `RequestVisionStatus(string updateId = null)`                                                   | `bool` | 请求后端提供当前会话的动态视觉缓冲区/状态诊断信息。后端会通过 [`VisionContextStatusReceived`](#visioncontextstatusreceived).                    |
| `TriggerVision(ConvaiVisionTriggerRequest request)`                                             | `bool` | 请求后端执行当前会话的动态视觉附加/响应行为——让角色查看缓冲帧，并根据请求作出回应。后端会通过 [`VisionContextTriggerReceived`](#visioncontexttriggerreceived). |
| `UpdateRespondMode(ConvaiRespondModeLane lane, ConvaiRespondMode mode, string updateId = null)` | `bool` | 更改一个输入通道在本次会话剩余时间内的响应模式，无需重新连接。后端会通过 [`RespondModeUpdateResultReceived`](#respondmodeupdateresultreceived).       |

每个方法在 `false` 不可用时返回该值（例如，房间尚未连接时）。

```csharp
using Convai.Runtime;
using Convai.Runtime.Adapters.Networking;
using Convai.Runtime.Vision.Context;
using UnityEngine;

public class VisionRuntimeQueries : MonoBehaviour
{
    [SerializeField] private ConvaiRoomManager _roomManager;

    public void QueryVisionStatus()
    {
        // 答案通过 VisionContextStatusReceived 返回。
        _roomManager.RequestVisionStatus();
    }

    public void TriggerVisionLook()
    {
        var request = new ConvaiVisionTriggerRequest
        {
            Text = "桌面上有什么变化？",
            RespondMode = ConvaiRespondMode.MustRespond
        };
        request.SetFrameWindow(-5, -1); // 最近缓冲的五帧

        // 答案通过 VisionContextTriggerReceived 返回。
        _roomManager.TriggerVision(request);
    }

    public void SwitchVisionToAuto()
    {
        // 由 RespondModeUpdateResultReceived 确认。
        _roomManager.UpdateRespondMode(ConvaiRespondModeLane.Vision, ConvaiRespondMode.Auto);
    }
}
```

### `ConvaiVisionTriggerRequest`

`Convai.Runtime.Vision.Context` — 密封类

用于显式动态视觉触发的参数，通过 `TriggerVision`。触发请求会让后端将缓冲的视觉帧附加到一个轮次中，并根据 `RespondMode`调用模型。如果未设置帧选择，后端会附加最新的未过期帧，数量不超过其配置的每轮帧数。

```csharp
new ConvaiVisionTriggerRequest(string updateId = null)
```

| 参数         | 类型       | 默认值    | 说明                                                                                        |
| ---------- | -------- | ------ | ----------------------------------------------------------------------------------------- |
| `updateId` | `string` | `null` | 幂等键，会在确认消息的 `update_id`中回显。省略时会生成唯一 ID。重复使用同一 ID 会使请求具备幂等性——后端会重放原始确认消息，而不会再次触发，因此重试始终安全。 |

#### 属性

| 属性                 | 类型                    | 说明                                                                                     |
| ------------------ | --------------------- | -------------------------------------------------------------------------------------- |
| `UpdateId`         | `string`              | 此请求的幂等键，由构造函数设置。                                                                       |
| `Text`             | `string`              | 随帧一并发送的可选提示，例如 `"What changed on the table?"`。留空时，后端会使用通用的帧检查提示。                       |
| `RespondMode`      | `ConvaiRespondMode?`  | 此触发请求对角色语音的影响方式。 `null` 表示使用连接时为触发通道设置的默认值（`ConvaiVisionRespondModeSettings.Trigger`). |
| `FrameWindowStart` | `int?`                | 相对帧窗口的起始位置，通过 `SetFrameWindow`.                                                        |
| `FrameWindowEnd`   | `int?`                | 相对帧窗口的结束位置，通过 `SetFrameWindow`.                                                        |
| `FramePtsIds`      | `IReadOnlyList<long>` | 可选的绝对帧选择，依据呈现时间戳（纳秒），与确认消息（`attached_frame_pts`）和视觉状态响应中报告的时间戳一致。如果同时设置了帧窗口，则优先采用此项。   |

#### 方法

| 方法                                             | 说明                                                                                                                                        |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `SetFrameWindow(int startIndex, int endIndex)` | 选择缓冲帧的相对窗口，例如 `SetFrameWindow(-5, -1)` 表示最近的五帧。负值从最新的缓冲帧开始倒数（`-1` = 最新帧）；非负值表示从最早保留帧开始计数的从零起始偏移量。对于超出范围的索引，后端会将其限制在最早保留帧，并在确认消息中报告实际附加的帧。 |
| `ClearFrameWindow()`                           | 清除先前设置的帧窗口，恢复为默认的最新帧选择。                                                                                                                   |

触发请求中的帧选择优先级如下：

1. `FramePtsIds` — 根据呈现时间戳进行绝对定位。不受过期时间窗口限制；如果时间戳对应的帧已从缓冲区中移除，触发请求会失败，结果为 `frame_id_evicted` 。
2. `SetFrameWindow(startIndex, endIndex)` — 相对窗口，如上所述。
3. 未设置任何选项 — 后端会附加最新的未过期帧，数量不超过其配置的每轮帧数。

### `ConvaiRespondModeLane`

`Convai.Runtime.Vision.Context` — 枚举

标识要使用其响应模式的输入通道 `UpdateRespondMode` 更改。用户文本和语音始终会触发响应，且无法更改。

| 值               | 线缆模态             | 说明                  |
| --------------- | ---------------- | ------------------- |
| `Vision`        | `vision`         | 新采样的视觉帧。            |
| `ContextUpdate` | `context_update` | 动态上下文文本更新。          |
| `Trigger`       | `trigger`        | 无需为每个请求指定模式的显式视觉触发。 |
| `SceneMetadata` | `scene_metadata` | 场景元数据更新。            |

### 领域事件

通过运行时订阅领域事件 `IEventHub` 以便在不轮询的情况下响应 Vision 生命周期变化和后端确认 `IsPublishing` 每一帧。使用以下方式获取事件中心： `ConvaiManager.ActiveManager.TryGetEventHub(out IEventHub hub)`。所有 Vision 事件都是值类型（`readonly struct`）——只需分配一次处理程序并持有引用。

```csharp
using Convai.Domain.DomainEvents.Vision;
using Convai.Domain.EventSystem;
using Convai.Runtime.Components;
using UnityEngine;

public class VisionAnalytics : MonoBehaviour
{
    private SubscriptionToken _captureStartedToken;
    private SubscriptionToken _captureStoppedToken;
    private SubscriptionToken _trackPublishedToken;
    private SubscriptionToken _trackUnpublishedToken;
    private SubscriptionToken _visionStatusToken;
    private SubscriptionToken _visionTriggerToken;
    private SubscriptionToken _respondModeToken;

    void Start()
    {
        if (ConvaiManager.ActiveManager == null) return;
        if (!ConvaiManager.ActiveManager.TryGetEventHub(out IEventHub hub)) return;

        _captureStartedToken = hub.Subscribe<VisionCaptureStarted>(OnCaptureStarted, EventDeliveryPolicy.MainThread);
        _captureStoppedToken = hub.Subscribe<VisionCaptureStopped>(OnCaptureStopped, EventDeliveryPolicy.MainThread);
        _trackPublishedToken = hub.Subscribe<VideoTrackPublished>(OnTrackPublished, EventDeliveryPolicy.MainThread);
        _trackUnpublishedToken = hub.Subscribe<VideoTrackUnpublished>(OnTrackUnpublished, EventDeliveryPolicy.MainThread);
        _visionStatusToken = hub.Subscribe<VisionContextStatusReceived>(OnVisionStatus, EventDeliveryPolicy.MainThread);
        _visionTriggerToken = hub.Subscribe<VisionContextTriggerReceived>(OnVisionTrigger, EventDeliveryPolicy.MainThread);
        _respondModeToken = hub.Subscribe<RespondModeUpdateResultReceived>(OnRespondModeUpdate, EventDeliveryPolicy.MainThread);
    }

    void OnDestroy()
    {
        if (ConvaiManager.ActiveManager == null) return;
        if (!ConvaiManager.ActiveManager.TryGetEventHub(out IEventHub hub)) return;

        hub.Unsubscribe(_captureStartedToken);
        hub.Unsubscribe(_captureStoppedToken);
        hub.Unsubscribe(_trackPublishedToken);
        hub.Unsubscribe(_trackUnpublishedToken);
        hub.Unsubscribe(_visionStatusToken);
        hub.Unsubscribe(_visionTriggerToken);
        hub.Unsubscribe(_respondModeToken);
    }

    private void OnCaptureStarted(VisionCaptureStarted e)
        => Debug.Log($"[Vision] Capture started: {e.Width}x{e.Height} @ {e.FramesPerSecond} fps (source: {e.SourceId})");

    private void OnCaptureStopped(VisionCaptureStopped e)
    {
        Debug.Log($"[Vision] Capture stopped after {e.TotalFramesCaptured} frames. Reason: {e.Reason}");
        if (e.IsError)
            Debug.LogError($"[Vision] Error: {e.ErrorMessage} (code: {e.ErrorCode})");
    }

    private void OnTrackPublished(VideoTrackPublished e)
        => Debug.Log($"[Vision] Track '{e.TrackName}' published. SID: {e.TrackSid}");

    private void OnTrackUnpublished(VideoTrackUnpublished e)
        => Debug.Log($"[Vision] Track '{e.TrackName}' unpublished. Reason: {e.Reason}");

    private void OnVisionStatus(VisionContextStatusReceived e)
        => Debug.Log($"[Vision] Status: {e.Outcome} (source: {e.ActiveSourceLabel}, last frame age: {e.LastFrameAgeMs} ms)");

    private void OnVisionTrigger(VisionContextTriggerReceived e)
        => Debug.Log($"[Vision] Trigger: {e.Outcome}, attached {e.FramesAttached} frame(s), respond mode {e.ActualRespondMode}");

    private void OnRespondModeUpdate(RespondModeUpdateResultReceived e)
        => Debug.Log($"[Vision] Respond mode for '{e.Modality}' is now '{e.Mode}' (status: {e.Status})");
}
```

### `VisionCaptureStarted`

当帧源开始生成帧时触发。

| 属性                | 类型         | 说明                                      |
| ----------------- | ---------- | --------------------------------------- |
| `Width`           | `int`      | 捕获宽度（像素）。                               |
| `Height`          | `int`      | 捕获高度（像素）。                               |
| `FramesPerSecond` | `float`    | 配置的帧率。                                  |
| `Timestamp`       | `DateTime` | 捕获开始的 UTC 时间。                           |
| `SourceId`        | `string`   | 源标识符（来自 `IVisionFrameSource.SourceId`). |
| `AspectRatio`     | `float`    | `Width / Height`.                       |
| `TotalPixels`     | `int`      | `Width * Height`.                       |

### `VisionFrameCaptured`

每次捕获帧时触发。此事件会在每一帧捕获时触发——在 60 秒会话中以 15 fps 运行时，会触发 900 次。请使用 `EventDeliveryPolicy.Immediate` 并保持处理程序轻量；进行分析时，应每隔 N 帧采样一次，而不是订阅每个事件。

| 属性           | 类型         | 说明           |
| ------------ | ---------- | ------------ |
| `Width`      | `int`      | 帧宽度（像素）。     |
| `Height`     | `int`      | 帧高度（像素）。     |
| `FrameIndex` | `long`     | 从零开始的捕获帧索引。  |
| `SizeBytes`  | `long`     | 帧数据大小（字节）。   |
| `Timestamp`  | `DateTime` | 帧捕获的 UTC 时间。 |
| `SourceId`   | `string`   | 源标识符。        |

### `VisionCaptureStopped`

当帧源停止生成帧时触发。

| 属性                    | 类型                        | 说明                                                                                    |
| --------------------- | ------------------------- | ------------------------------------------------------------------------------------- |
| `TotalFramesCaptured` | `long`                    | 会话期间捕获的帧总数。                                                                           |
| `Timestamp`           | `DateTime`                | 停止时间（UTC）。                                                                            |
| `Reason`              | `VisionCaptureStopReason` | 捕获停止的原因（`UserRequested`, `SessionEnded`, `CameraLost`, `Error`, `ComponentDisabled`). |
| `SourceId`            | `string`                  | 源标识符。                                                                                 |
| `ErrorMessage`        | `string`                  | 人类可读的错误详情。仅在 `Reason == Error`.                                                       |
| `ErrorCode`           | `string`                  | 来自 `SessionErrorCodes` 的结构化错误代码（Vision\* 常量）。仅在 `Reason == Error`.                    |
| `IsError`             | `bool`                    | `true` 当 `Reason == Error`.                                                           |
| `IsNormalStop`        | `bool`                    | `true` 当 `Reason` 为 `UserRequested` 或 `SessionEnded`.                                 |
| `HasErrorCode`        | `bool`                    | `true` 当 `ErrorCode` 不为空。                                                             |

### `VideoTrackPublished`

WebRTC 视频轨道成功打开时触发。

{% hint style="warning" %}
`IsVisionTrack` 检查轨道名称是否为 `"vision"`，而不是 `"unity-scene"`。使用默认轨道名称时， `IsVisionTrack` 返回 `false`。直接使用 `TrackName` 来识别轨道；如果集成依赖于 `"vision"` ，则在 Inspector 中将轨道重命名为 `IsVisionTrack`.
{% endhint %}

| 属性              | 类型         | 说明                                                |
| --------------- | ---------- | ------------------------------------------------- |
| `TrackSid`      | `string`   | LiveKit 轨道会话 ID。                                  |
| `TrackName`     | `string`   | 由 `VideoTrackName` 设置的轨道名称（默认值： `"unity-scene"`). |
| `Timestamp`     | `DateTime` | UTC 发布时间。                                         |
| `RoomSessionId` | `string`   | 房间会话 ID。                                          |
| `IsVisionTrack` | `bool`     | `true` 当 `TrackName == "vision"` （不区分大小写）时。       |

### `VideoTrackUnpublished`

WebRTC 视频轨道被移除时触发。

| 属性              | 类型                          | 说明                                                                                      |
| --------------- | --------------------------- | --------------------------------------------------------------------------------------- |
| `TrackSid`      | `string`                    | LiveKit 轨道会话 ID。                                                                        |
| `TrackName`     | `string`                    | 轨道名称。                                                                                   |
| `Timestamp`     | `DateTime`                  | 取消发布的 UTC 时间。                                                                           |
| `Reason`        | `VideoTrackUnpublishReason` | 轨道取消发布的原因（`UserRequested`, `SessionEnded`, `SourceLost`, `Error`, `ComponentDisabled`). |
| `RoomSessionId` | `string`                    | 房间会话 ID。                                                                                |
| `IsVisionTrack` | `bool`                      | `true` 当 `TrackName == "vision"` （注意事项与 `VideoTrackPublished.IsVisionTrack`).           |
| `相同）`           | `bool`                      | `true` 当 `Reason` 为 `UserRequested` 或 `SessionEnded`.                                   |

### `VisionContextStatusReceived`

后端对 `vision-status` 查询的确认响应，该查询通过 `RequestVisionStatus`发送，用于描述会话动态视觉帧缓冲区的状态。

| 属性                  | 类型         | 说明                                                                                  |
| ------------------- | ---------- | ----------------------------------------------------------------------------------- |
| `Status`            | `string`   | 响应状态： `success`, `error`, `processing`或 `pending`.                                  |
| `Message`           | `string`   | 随响应附带的可选人类可读消息。                                                                     |
| `UpdateId`          | `string`   | 请求幂等键的回显。                                                                           |
| `Outcome`           | `string`   | 缓冲区结果： `frames_available`, `buffer_empty`, `no_active_video`或 `vision_not_enabled`. |
| `ActiveSource`      | `string`   | 后端为此会话选定的视频源参与者 ID（如果有）。                                                            |
| `ActiveSourceLabel` | `string`   | 所选视频发布者的源标签（例如 webcam、canvas、screen）。                                               |
| `LastFrameAgeMs`    | `int`      | 缓冲区中最新帧的时长，单位为毫秒； `0` 未知或缓冲区中没有帧时。                                                  |
| `RawExtras`         | `JObject`  | 完整的 extras 负载，包括 `vision_buffer` 诊断对象（保留的帧、PTS 时间窗口、丢弃计数器），用于没有类型化访问器的字段。           |
| `Timestamp`         | `DateTime` | 此事件在客户端创建时的 UTC 时间。                                                                 |

### `VisionContextTriggerReceived`

对通过以下方式发送的 `vision-trigger` 请求的后端确认，通过 `TriggerVision`发送；报告触发器的处理结果（响应模式、降级情况），以及附加到模型轮次的帧。

| 属性                     | 类型                    | 说明                                                                                                                                                     |
| ---------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Status`               | `string`              | 响应状态： `success`, `error`, `processing`或 `pending`.                                                                                                     |
| `Message`              | `string`              | 随响应附带的可选人类可读消息。                                                                                                                                        |
| `UpdateId`             | `string`              | 请求幂等键的回显。                                                                                                                                              |
| `Outcome`              | `string`              | 触发结果，例如 `frames_available`, `buffer_empty`, `vision_not_enabled`, `invalid_respond_mode`, `invalid_frame_indices`, `frame_id_evicted`或 `rate_limited`. |
| `RequestedRespondMode` | `string`              | 请求指定的响应模式（`silent`/`auto`/`must_respond`).                                                                                                             |
| `ActualRespondMode`    | `string`              | 状态触发降级后，后端实际采用的响应模式。                                                                                                                                   |
| `RequestedRunLlm`      | `string`              | 线路上请求的 LLM 策略（`true`/`auto`/`false`).                                                                                                                  |
| `ActualRunLlm`         | `string`              | 降级后实际采用的 LLM 策略。                                                                                                                                       |
| `LlmTriggered`         | `bool`                | `true` 表示该触发器导致调用了 LLM。                                                                                                                                |
| `Downgraded`           | `bool`                | `true` 表示后端降低了请求的响应模式（例如，机器人正忙或用户正在说话）。                                                                                                                |
| `DowngradeReason`      | `string`              | 请求被降级的原因，例如 `bot_busy` 或 `user_speaking`；否则为空。                                                                                                         |
| `FramesAttached`       | `int`                 | 附加到该轮次的图像帧数量。                                                                                                                                          |
| `AttachOutcome`        | `string`              | 附加结果： `attached`, `deduped_stub`, `stale_skipped`，或 `none`.                                                                                            |
| `ImageTokensEstimate`  | `int`                 | 后端对已附加帧所耗图像令牌数的估算（仅用于归因，不用于计费）。                                                                                                                        |
| `AttachedFramePts`     | `IReadOnlyList<long>` | 模型实际看到的帧的呈现时间戳（纳秒）。                                                                                                                                    |
| `RawExtras`            | `JObject`             | 完整的附加数据负载（包括 `vision_buffer` 诊断信息），用于无法通过类型化访问器访问的字段。                                                                                                  |
| `Timestamp`            | `DateTime`            | 此事件在客户端创建时的 UTC 时间。                                                                                                                                    |

### `RespondModeUpdateResultReceived`

后端对通过 `respond-mode-update` 发送的请求的确认， `UpdateRespondMode`会回显已应用的通道和模式；如果无法更改通道，则回显拒绝信息。

| 属性          | 类型         | 说明                                                  |
| ----------- | ---------- | --------------------------------------------------- |
| `Status`    | `string`   | 响应状态： `应用成功时为 success` ； `拒绝时为 error` 。             |
| `Message`   | `string`   | 可选的人类可读消息（例如，用户输入通道被拒绝的原因）。                         |
| `UpdateId`  | `string`   | 后端返回幂等键时，回显请求中的幂等键。                                 |
| `Modality`  | `string`   | 更新所针对的通道，以后端模态字符串表示（例如 `vision`, `context_update`). |
| `Mode`      | `string`   | 该通道当前生效的响应模式（`silent`/`auto`/`must_respond`).       |
| `RawExtras` | `JObject`  | 完整的附加数据负载，包括后端完整的 `respond_modes` 通道快照。             |
| `Timestamp` | `DateTime` | 此事件在客户端创建时的 UTC 时间。                                 |

### 后续步骤

{% content-ref url="/pages/cb7758289bc48a93210bce51933fd819fd05e245" %}
[自定义帧来源](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/vision/custom-frame-sources.md)
{% endcontent-ref %}

{% content-ref url="/pages/86612bc613c5a299a468b71b3fb8a40e625ee1fe" %}
[排查视觉问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/vision/troubleshooting-and-diagnostics.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/vision/scripting-api.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.
