源码: conversation.rs:353-390 返回: (assistant_message, optional_usage)
(
events: list[AssistantEvent],
)
| 162 | |
| 163 | |
| 164 | def build_assistant_message( |
| 165 | events: list[AssistantEvent], |
| 166 | ) -> tuple[Message, Optional[TokenUsage]]: |
| 167 | """源码: conversation.rs:353-390 |
| 168 | |
| 169 | 返回: (assistant_message, optional_usage) |
| 170 | """ |
| 171 | text_buffer: str = "" |
| 172 | blocks: list = [] |
| 173 | finished: bool = False |
| 174 | usage: Optional[TokenUsage] = None |
| 175 | |
| 176 | for event in events: |
| 177 | if isinstance(event, TextDeltaEvent): |
| 178 | text_buffer += event.text |
| 179 | |
| 180 | elif isinstance(event, ToolUseEvent): |
| 181 | # flush 文本缓冲 — 源码: conversation.rs:392-398 |
| 182 | if text_buffer: |
| 183 | blocks.append(TextContentBlock(text=text_buffer)) |
| 184 | text_buffer = "" |
| 185 | blocks.append(ToolContentBlock( |
| 186 | id=event.id, |
| 187 | name=event.name, |
| 188 | input=event.input, |
| 189 | )) |
| 190 | |
| 191 | elif isinstance(event, MessageStopEvent): |
| 192 | finished = True |
| 193 | |
| 194 | # 最后 flush 残留文本 |
| 195 | if text_buffer: |
| 196 | blocks.append(TextContentBlock(text=text_buffer)) |
| 197 | |
| 198 | if not finished: |
| 199 | raise RuntimeError( |
| 200 | "assistant stream ended without a message stop event" |
| 201 | ) |
| 202 | if not blocks: |
| 203 | raise RuntimeError("assistant stream produced no content") |
| 204 | |
| 205 | message = Message(role="assistant", content=blocks) |
| 206 | return message, usage |
| 207 | |
| 208 | |
| 209 | # ============================================================ |
no test coverage detected