

# 使用双向 API 处理输出事件
<a name="sonic-output-events"></a>

Amazon Nova Sonic 模型回复问题时会遵循结构化事件序列。该流程以包含 `sessionId`、`promptName` 和 `completionId` 等唯一标识符的 `completionStart` 事件开始。这些标识符在整个回复周期中保持一致，并统一了后续的所有回复事件。

## 概述
<a name="sonic-output-overview"></a>

每种回复类型都遵循一致的三部分模式：`contentStart` 定义内容类型和格式，接着是实际的内容事件，然后以 `contentEnd` 结束该部分。回复通常按顺序包括多个内容块：自动语音识别（ASR）转录（即用户所说的话）、可选的“工具使用”（即需要外部信息时）、文本回复（即模型计划要说的话）和音频回复（即语音输出）。

## 响应内容类型
<a name="sonic-response-content-types"></a>

### ASR 转录文本
<a name="sonic-asr-transcription"></a>

ASR 转录会首先显示，在 `contentStart` 中通过 `role: "USER"` 和 `"additionalModelFields": "{\"generationStage\":\"FINAL\"}"` 提供模型对用户语音的理解。

### 工具使用
<a name="sonic-tool-use-response"></a>

模型需要外部数据时，它会发送包含特定工具名称和参数的工具相关事件。

### 文本回复
<a name="sonic-text-response"></a>

文本回复通过 `role: "ASSISTANT"` 和 `"additionalModelFields": "{\"generationStage\":\"SPECULATIVE\"}"` 提供计划语音的预览。

### 语音回复
<a name="sonic-audio-response"></a>

然后，音频回复会传送 base64 编码的语音片段，并在整个流中共享相同的 `contentId`。

## 插话支持
<a name="sonic-barge-in-support"></a>

在音频生成过程中，Amazon Nova Sonic 借助插话能力实现自然流畅的对话交互。如果用户中断正在说话的 Amazon Nova Sonic，Nova Sonic 会立即停止生成语音，切换到聆听模式，并发送内容通知，表明已发生中断。由于 Nova Sonic 的运行速度比实时速度更快，有些音频可能已经传送但尚未播放。中断通知让客户端应用程序能够清除其音频队列并立即停止播放，从而打造回复式对话体验。

## 最终转录
<a name="sonic-final-transcription"></a>

音频生成完成（或通过插话功能被中断）后，Amazon Nova Sonic 会额外返回一条文本回复，其中包含实际播报内容的语句级转录文本。此文本回复包括带有 `role: "ASSISTANT"` 和 `"additionalModelFields": "{\"generationStage\":\"FINAL\"}"` 的 `contentStart` 事件。

## 使用情况跟踪
<a name="sonic-usage-tracking"></a>

在响应处理全过程中，系统会发送 `usageEvent` 事件来跟踪词元消耗情况。此类事件包含输入词元与输出词元（语音及文本）的详细指标及其累计总量。每个 `usageEvent` 都与对话流中的其他事件保持相同的 `sessionId`、`promptName`、和 `completionId`。详情部分会提供词元使用量的增量变动（差值）与实时累计总量，便于精准监控会话期间的使用情况。

## 完成
<a name="sonic-completion"></a>

模型会发送一个 `completionEnd` 事件，其中包含原始标识符以及表明对话如何结束的 `stopReason`。此事件层次结构确保应用程序可以跟踪回复的哪些部分属于同一部分并相应地加以处理，从而在多个回合中维护对话上下文。

输出事件流程从进入回复生成阶段开始。该流程从自动语音识别开始，选择要使用的工具，转录语音，生成音频，完成转录，然后完成会话。

![\[alt text not found\]](http://docs.aws.amazon.com/zh_cn/nova/latest/nova2-userguide/images/Output-Event -Flow_3.png)


## 输出事件流
<a name="sonic-output-event-flow"></a>

本节介绍了输出事件流程的结构。

### 1. UsageEvent
<a name="sonic-usage-event"></a>

```
"event": {
    "usageEvent": {
        "completionId": "string", // unique identifier for completion
        "details": {
            "delta": { // incremental changes since last event
                "input": {
                    "speechTokens": number, // input speech tokens
                    "textTokens": number // input text tokens
                },
                "output": {
                    "speechTokens": number, // speech tokens generated
                    "textTokens": number // text tokens generated
                }
            },
            "total": { // cumulative counts
                "input": {
                    "speechTokens": number, // total speech tokens processed
                    "textTokens": number // total text tokens processed
                },
                "output": {
                    "speechTokens": number, // total speech tokens generated
                    "textTokens": number // total text tokens generated
                }
            }
        },
        "promptName": "string", // same unique identifier from promptStart event
        "sessionId": "string", // unique identifier
        "totalInputTokens": number, // cumulative input tokens
        "totalOutputTokens": number, // cumulative output tokens
        "totalTokens": number // total tokens in the session
    }
}
```

### 2. CompleteStartEvent
<a name="sonic-completion-start-event"></a>

```
"event": {
    "completionStart": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
    }
}
```

### 3. TextOutputContent
<a name="sonic-text-output-content"></a>

#### ContentStart
<a name="sonic-text-output-content-start"></a>

```
"event": {
    "contentStart": {
        "additionalModelFields": "{\"generationStage\":\"FINAL\"}" | "{\"generationStage\":\"SPECULATIVE\"}",
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // unique identifier for the content block
        "type": "TEXT",
        "role": "USER" | "ASSISTANT",
        "textOutputConfiguration": {
            "mediaType": "text/plain"
        }
    }
}
```

#### TextOutput
<a name="sonic-text-output"></a>

```
"event": {
    "textOutput": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // same unique identifier from its contentStart
        "content": "string" // User transcribe or Text Response
    }
}
```

#### ContentEnd
<a name="sonic-text-output-content-end"></a>

```
"event": {
    "contentEnd": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // same unique identifier from its contentStart
        "stopReason": "PARTIAL_TURN" | "END_TURN" | "INTERRUPTED",
        "type": "TEXT"
    }
}
```

### 4. ToolUse
<a name="sonic-tool-use-output"></a>

#### ContentStart
<a name="sonic-tool-use-content-start"></a>

```
"event": {
    "contentStart": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // unique identifier for the content block
        "type": "TOOL",
        "role": "TOOL",
        "toolUseOutputConfiguration": {
            "mediaType": "application/json"
        }
    }
}
```

#### ToolUse
<a name="sonic-tool-use-event"></a>

```
"event": {
    "toolUse": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // same unique identifier from its contentStart
        "content": "json",
        "toolName": "string",
        "toolUseId": "string"
    }
}
```

#### ContentEnd
<a name="sonic-tool-use-content-end"></a>

```
"event": {
    "contentEnd": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // same unique identifier from its contentStart
        "stopReason": "TOOL_USE",
        "type": "TOOL"
    }
}
```

### 5. AudioOutputContent
<a name="sonic-audio-output-content"></a>

#### ContentStart
<a name="sonic-audio-output-content-start"></a>

```
"event": {
    "contentStart": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // unique identifier for the content block
        "type": "AUDIO",
        "role": "ASSISTANT",
        "audioOutputConfiguration": {
            "mediaType": "audio/lpcm",
            "sampleRateHertz": 8000 | 16000 | 24000,
            "sampleSizeBits": 16,
            "encoding": "base64",
            "channelCount": 1
        }
    }
}
```

#### AudioOutput
<a name="sonic-audio-output-event"></a>

```
"event": {
    "audioOutput": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // same unique identifier from its contentStart
        "content": "base64EncodedAudioData", // Audio
    }
}
```

#### ContentEnd
<a name="sonic-audio-output-content-end"></a>

```
"event": {
    "contentEnd": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "contentId": "string", // same unique identifier from its contentStart
        "stopReason": "PARTIAL_TURN" | "END_TURN",
        "type": "AUDIO"
    }
}
```

### 6. CompletionEndEvent
<a name="sonic-completion-end-event"></a>

```
"event": {
    "completionEnd": {
        "sessionId": "string", // unique identifier
        "promptName": "string", // same unique identifier from promptStart event
        "completionId": "string", // unique identifier
        "stopReason": "END_TURN" 
    }
}
```