> 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/ui-and-presentation/transcript-ui/transcript-history-and-queries.md).

# 转录历史与查询

通过代码读取当前对话轮次时间线，实时响应轮次变化，并将会话历史导出为文本、Markdown 或 JSON。

`ConvaiManager.ActiveManager.Transcripts` 可让你的代码以结构化方式访问当前房间会话中的每一轮对话。通过 `CurrentTimeline` 和 `GetTurns`读取当前状态；通过 `Subscribe` 和 `SubscribeCommitted`响应实时变化；通过 `Export`导出已完成的对话轮次。此接口不会控制屏幕上显示的内容——相关说明请参阅 [Transcript UI](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/transcript-ui.md) 。完整 API 参考请参阅 [Transcript API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/transcript-api.md).

### 读取当前转录文本状态

`ConvaiManager.ActiveManager.Transcripts.CurrentTimeline` 返回一个不可变的 `TranscriptTimeline` ——它是在读取时对房间中所有对话轮次的一致视图。重复读取的开销很低：在运行时发布变更之前，它会返回同一个实例；只有时间线实际发生变化时，才会返回新实例。

{% hint style="info" %}
`ConvaiManager.ActiveManager.Transcripts` 会抛出 `InvalidOperationException` （如果 SDK 尚未完成初始化）。对于较早运行的代码（`OnEnable`, `Awake`），请改用 `ConvaiManager.ActiveManager.TryGetTranscripts(out ConvaiTranscripts transcripts)` ；它会返回 `false` ，而不是抛出异常。
{% endhint %}

| 成员               | 类型                                            | 说明                                         |
| ---------------- | --------------------------------------------- | ------------------------------------------ |
| `Cursor`         | `long`                                        | 单调递增计数器。每当运行时发布更新时都会变化                     |
| `ActiveTurns`    | `IReadOnlyList<TranscriptTurn>`               | 仍在进行中的对话轮次——尚未提交或中断                        |
| `CommittedTurns` | `IReadOnlyList<TranscriptTurn>`               | 已结束的对话轮次（处于`Committed` 或 `Interrupted` 状态） |
| `TurnsById`      | `IReadOnlyDictionary<string, TranscriptTurn>` | 通过 `TranscriptTurn.Id`快速查找，涵盖进行中和已提交的对话轮次  |
| `Turns`          | `IReadOnlyList<TranscriptTurn>`               | 所有对话轮次（进行中和已提交），按 `RoomSequence`           |

每个 `TranscriptTurn` 都提供 `DisplayText` （已提交的文本以及任何正在生成的临时文本）、 `Speaker` （一个 `TranscriptSpeaker` ，包含 `Type`, `Id`, `DisplayName`, `ParticipantId`), `StartedAtUtc`, `WasInterrupted`，以及 `Revision` ——一个整数，每当回合的存储数据发生变化时就会递增。请使用 `turn.IsCommitted` 检查回合是否已结束，而不要直接比较 `State` 。

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;
using System.Text;
using UnityEngine;

public class SessionReporter : MonoBehaviour
{
    public string BuildSessionReport()
    {
        TranscriptTimeline timeline = ConvaiManager.ActiveManager.Transcripts.CurrentTimeline;
        var sb = new StringBuilder();

        foreach (TranscriptTurn turn in timeline.CommittedTurns)
            sb.AppendLine($"[{turn.StartedAtUtc:HH:mm:ss}] {turn.Speaker.DisplayName}: {turn.DisplayText}");

        return sb.ToString();
    }
}
```

#### 查找单个回合

使用 `GetTurn(string turnId)` 可按 ID 以 O(1) 时间复杂度查找，或使用 `GetLatestTurn(TranscriptParticipantRef)` 查找特定玩家或角色最近的一条回合记录。

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;

// Look up a turn by its stable ID
TranscriptTurn turn = ConvaiManager.ActiveManager.Transcripts.GetTurn(turnId);

// Look up the most recent turn from a specific character
var characterRef = new TranscriptParticipantRef(
    TranscriptParticipantKind.Character,
    playerOrCharacterId: characterId,
    displayName: characterName);

TranscriptTurn latest = ConvaiManager.ActiveManager.Transcripts.GetLatestTurn(characterRef);
```

这两个方法在 `null` 不存在匹配的回合时都会返回该值。

### 使用 `TranscriptQuery`

传入一个 `TranscriptQuery` 至 `GetTurns(query)` 以检索时间线中的部分内容。省略查询或不设置某个字段，即表示停用对应的筛选条件。结果按 `RoomSequence`.

| 字段                      | 类型                           | 默认值         | 说明                               |
| ----------------------- | ---------------------------- | ----------- | -------------------------------- |
| `ParticipantKind`       | `TranscriptParticipantKind?` | `null` （任意） | 限定为 `Player` 或 `Character` 类型的轮次 |
| `PlayerOrCharacterId`   | `string`                     | `null` （任意） | 按 ID 限定为特定玩家或角色                  |
| `ParticipantId`         | `string`                     | `null` （任意） | 按房间范围内的参与者 ID 限定（多用户房间）          |
| `IncludeActiveTurns`    | `bool`                       | `true`      | 在结果中包含进行中的轮次                     |
| `IncludeCommittedTurns` | `bool`                       | `true`      | 在结果中包含已完成的轮次                     |

`TranscriptQuery.ParticipantKind` 使用 `TranscriptParticipantKind` (`Player` 或 `Character`）。这是一个独立于 `TranscriptSpeakerType` (`Player`, `Character`（或 `System`）的枚举，后者会出现在 `TranscriptSpeaker` 和 `TranscriptSubscriptionOptions` 中，详见本页下文。

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;
using System.Collections.Generic;

var query = new TranscriptQuery
{
    ParticipantKind = TranscriptParticipantKind.Character,
    IncludeActiveTurns = false,
    IncludeCommittedTurns = true
};

IReadOnlyList<TranscriptTurn> characterTurns =
    ConvaiManager.ActiveManager.Transcripts.GetTurns(query);
```

### 响应实时转录内容变更

调用 `Subscribe(callback, options)` 即可在每次匹配的轮次发生变更时接收一个 `TranscriptChange` 。 `Subscribe` 会返回一个 `IDisposable` ——调用 Dispose 取消订阅，通常在 `OnDisable`.

`TranscriptChange.Kind` 用于说明发生了什么； `TranscriptChange.Turn` 是更新后的轮次，或者在 `null` 如果 `Kind` 为 `Removed` （此时读取 `TurnId` ）。

| `TranscriptChangeKind` | 含义                             |
| ---------------------- | ------------------------------ |
| `Added`                | 该轮次首次出现在时间线中                   |
| `Updated`              | 该轮次仍处于活动状态（流式输出或稳定状态）时，文本发生了变化 |
| `Committed`            | 该轮次正常结束                        |
| `Interrupted`          | 该轮次因被另一位说话者打断而结束               |
| `Corrected`            | 该轮次先前已发送的文本被追溯修正               |
| `Removed`              | 该轮次已从时间线中移除； `Turn` 为 `null`   |

`TranscriptSubscriptionOptions` 用于控制哪些轮次和变更类型会传递给回调：

| 字段                | 类型                       | 默认值         | 说明                                       |
| ----------------- | ------------------------ | ----------- | ---------------------------------------- |
| `ReplayExisting`  | `bool`                   | `false`     | 在开始实时更新之前，立即为当前匹配的每个轮次调用回调               |
| `IncludeActive`   | `bool`                   | `true`      | 包含尚未结束的轮次变更                              |
| `IncludeTerminal` | `bool`                   | `true`      | 包含已提交、中断或修正的轮次变更                         |
| `SpeakerType`     | `TranscriptSpeakerType?` | `null` （任意） | 仅限 `Player`, `Character`或 `System` 类型的轮次 |
| `SpeakerId`       | `string`                 | `null` （任意） | 按 ID 限定为特定玩家或角色                          |
| `ParticipantId`   | `string`                 | `null` （任意） | 按房间范围内的参与者 ID 限定（多用户房间）                  |

`SubscribeCommitted(callback, options)` 是一个便捷封装，基于 `Subscribe` 并强制 `IncludeActive = false` 和 `IncludeTerminal = true`，因此回调只会在一轮结束后触发——如果只关心已定稿的历史记录（例如聊天记录或评分系统），请使用此选项。

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;
using Convai.Runtime.Facades;
using System;
using TMPro;
using UnityEngine;

public class WordCountTracker : MonoBehaviour
{
    [SerializeField] private TMP_Text _wordCountLabel;

    private ConvaiTranscripts _transcripts;
    private IDisposable _subscription;
    private int _wordCount;

    private void OnEnable()
    {
        ConvaiManager manager = ConvaiManager.ActiveManager;
        if (manager == null || !manager.TryGetTranscripts(out _transcripts)) return;

        _subscription = _transcripts.SubscribeCommitted(
            OnPlayerTurnCommitted,
            new TranscriptSubscriptionOptions { SpeakerType = TranscriptSpeakerType.Player });
    }

    private void OnDisable()
    {
        _subscription?.Dispose();
        _subscription = null;
    }

    private void OnPlayerTurnCommitted(TranscriptChange change)
    {
        if (change.Turn == null) return;
        if (change.Kind != TranscriptChangeKind.Committed && change.Kind != TranscriptChangeKind.Interrupted) return;

        _wordCount += change.Turn.DisplayText.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
        _wordCountLabel.text = $"Words spoken: {_wordCount}";
    }
}
```

对于需要立即查看此前轮次的后加入查看者，请设置 `ReplayExisting = true` ，并将其作为选项传递给 `Subscribe` ——匹配的轮次会在实时更新开始前先传递给回调一次。

### 导出并清除转录历史记录

`Export(TranscriptExportFormat format)` 会将每个已提交的轮次按 `RoomSequence`排序，并序列化为一个字符串。它从 `CurrentTimeline.CommittedTurns` 读取数据——绝不会包含活动中的轮次。

| `TranscriptExportFormat` | 输出                                                    |
| ------------------------ | ----------------------------------------------------- |
| `PlainText`              | 每轮一行： `"{speaker}: {turn.DisplayText}"`               |
| `Markdown`               | 每轮一行： `"**{speaker}:** {turn.DisplayText}"`，轮次之间以空行分隔 |
| `Json`                   | 缩进格式的 JSON 数组，其中包含 `TranscriptTurn` 对象                |

该 `{speaker}` 值为 `turn.Speaker.DisplayName`，或 `turn.Speaker.Type` 当 `DisplayName` 为空时。

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;
using System.IO;
using UnityEngine;

public class SessionExporter : MonoBehaviour
{
    public void ExportSessionToDisk(string filePath)
    {
        string json = ConvaiManager.ActiveManager.Transcripts.Export(TranscriptExportFormat.Json);
        File.WriteAllText(filePath, json);
    }
}
```

调用 `Clear()` 以移除规范房间历史记录中的所有回合：

```csharp
ConvaiManager.ActiveManager.Transcripts.Clear();
```

{% hint style="warning" %}
`Clear()` 会清除 `CurrentTimeline`, `GetTurns`和 `Export` 读取的规范房间历史记录——这与清除聊天面板的可视显示不同，而且无法撤销。
{% endhint %}

### 故障排查

| 症状                                                                        | 可能原因                                                                                                                  | 解决方法                                                                                                                  | 验证                                                    |
| ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| `ConvaiManager.ActiveManager.Transcripts` 会抛出 `InvalidOperationException` | 在 `ConvaiManager` 完成初始化之前访问                                                                                           | 请使用 `ConvaiManager.ActiveManager.TryGetTranscripts(out var transcripts)`，或先检查 `ConvaiManager.IsBootstrapped` 是否为 true | `TryGetTranscripts` 返回 `true` 且 `transcripts` 不为 null |
| `Subscribe` 回调从未触发                                                        | 在房间会话已经结束后才订阅，或者 `TranscriptSubscriptionOptions` 筛选条件排除了所有回合                                                          | 请在房间连接前或连接后立即订阅；确认 `SpeakerType`, `SpeakerId`和 `ParticipantId` 与实际参与者匹配                                               | 订阅后发生下一次回合变更时，回调会触发                                   |
| `GetTurns()` 查询条件已设置时返回空列表                                                | `PlayerOrCharacterId` 或 `ParticipantId` 与任何参与者都不匹配，或者两者都不匹配 `IncludeActiveTurns` 和 `IncludeCommittedTurns` 均为 `false` | 在未筛选的 `turn.Speaker.Id` 和 `turn.Speaker.ParticipantId` Subscribe `回调中` 记录日志，以找到正确的值                                   | `GetTurns()` 使用修正后的查询会返回非空列表                          |
| `change.Turn` 为 `null` 在 `Subscribe` 回调中                                  | `change.Kind` 为 `TranscriptChangeKind.Removed`                                                                        | 当 `change.TurnId` 而不是 `change.Turn` 在 `Kind` 为 `Removed`                                                              | 移除时，回调不再抛出空引用异常                                       |
| `Export(TranscriptExportFormat.PlainText)` 会返回空字符串                        | 尚无已提交的轮次                                                                                                              | `Export` 只读取 `CurrentTimeline.CommittedTurns`；等待轮次完成，或先检查 `CommittedTurns.Count` 是否                                   | `CurrentTimeline.CommittedTurns.Count` 大于零，然后再导出      |

### 后续步骤

现在，您可以完整读取房间的转录时间线、接收实时变更通知，并导出转录内容。有关本页所涉及的完整 API，请参阅 Transcript API 参考。要在场景中显示这些数据，请参阅 Transcript UI。要配置运行时启用的视觉模式，请参阅 Settings Panel。

{% content-ref url="/pages/1a33f148fac3ddf7352a86abb1f67ce91973142c" %}
[转录 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/transcript-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/49fed70bb2b468bcc6348096af1fc53fdb0656ce" %}
[转录 UI](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/transcript-ui.md)
{% endcontent-ref %}

{% content-ref url="/pages/dddf624ca0ae7ec32afa0c9e601f2cb7c7ab2b6a" %}
[设置面板](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/settings-panel.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/ui-and-presentation/transcript-ui/transcript-history-and-queries.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.
