Skip to content

agents

AgentContext

Bases: BaseModel

State and app events for a single response run.

Set resume_from to a saved, authorized workflow from this thread or to None for a fresh run. Construct the context before starting the runner.

Source code in chatkit/agents.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
class AgentContext[TContext](BaseModel):
    """State and app events for a single response run.

    Set `resume_from` to a saved, authorized workflow from this thread or to
    `None` for a fresh run. Construct the context before starting the runner.
    """

    model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")

    thread: ThreadMetadata
    store: Annotated[ThreadStore[TContext], SkipValidation]
    request_context: TContext
    resume_from: WorkflowItem | None = Field(exclude=True, repr=False)
    _workflow_item: WorkflowItem | None = None
    _resumed_workflow_id: str | None = None
    _client_tool_request: _ClientToolRequest | None = None
    _client_tool_conflict: bool = False
    _events: asyncio.Queue[ThreadStreamEvent] = PrivateAttr(
        default_factory=asyncio.Queue
    )

    def model_post_init(self, _context: Any, /) -> None:
        if self.resume_from is None:
            return
        if self.resume_from.thread_id != self.thread.id:
            raise ValueError("The saved workflow must belong to the current thread.")
        self._workflow_item = self.resume_from.model_copy(deep=True)
        self._resumed_workflow_id = self._workflow_item.id

    @property
    def workflow_item(self) -> WorkflowItem | None:
        """The active workflow for this run."""
        return self._workflow_item

    @workflow_item.setter
    def workflow_item(self, item: WorkflowItem | None) -> None:
        self._workflow_item = item

    def generate_id(
        self, type: StoreItemType, thread: ThreadMetadata | None = None
    ) -> str:
        """Generate a new store-backed id for the given item type."""
        if type == "thread":
            return self.store.generate_thread_id(self.request_context)
        return self.store.generate_item_id(
            type, thread or self.thread, self.request_context
        )

    def request_client_tool(
        self,
        tool: ToolContext[AgentContext[TContext]],
        *,
        name: str,
        arguments: dict[str, Any],
        continuation: Literal["local", "responses"],
    ) -> None:
        """Request a browser callback for this invocation of an Agents SDK tool.

        Configure the agent to stop at the calling tool. The browser receives one
        pending call when the run finishes and supplies its result on the next turn.
        Choose local replay or a continuation linked to a stored Responses response.
        """
        if tool.context is not self or not tool.tool_call_id:
            raise ValueError("Pass the ToolContext for the current tool invocation.")
        if self._client_tool_request is not None:
            self._client_tool_conflict = True
            raise ValueError(_CLIENT_TOOL_CONFLICT)
        if continuation not in ("local", "responses"):
            raise ValueError("Choose 'local' or 'responses' for model continuation.")

        self._client_tool_request = _ClientToolRequest(
            item_id=tool.tool_call.id if tool.tool_call is not None else None,
            call_id=tool.tool_call_id,
            name=name,
            arguments=arguments,
            continuation=continuation,
        )

    async def stream_widget(
        self,
        widget: WidgetRootInput | AsyncGenerator[WidgetRootInput],
        copy_text: str | None = None,
    ) -> None:
        """Stream a widget into the thread by enqueueing widget events."""
        async with aclosing(
            stream_widget(self.thread, widget, copy_text, self.generate_id)
        ) as events:
            async for event in events:
                await self.stream(event)

    async def end_workflow(
        self, summary: WorkflowSummary | None = None, expanded: bool = False
    ) -> None:
        """Finalize the active workflow item, optionally attaching a summary."""
        if self.workflow_item is not None:
            await self.stream(
                self._finish_workflow(
                    self.workflow_item, summary=summary, expanded=expanded
                )
            )

    def _finish_workflow(
        self,
        item: WorkflowItem,
        *,
        summary: WorkflowSummary | None = None,
        expanded: bool = False,
    ) -> ThreadItemDoneEvent | ThreadItemReplacedEvent:
        if self.workflow_item is not None and self.workflow_item.id == item.id:
            self.workflow_item = None

        if summary is not None:
            item.workflow.summary = summary
        elif item.workflow.summary is None:
            delta = datetime.now(item.created_at.tzinfo) - item.created_at
            item.workflow.summary = DurationSummary(duration=int(delta.total_seconds()))
        item.workflow.expanded = expanded
        if item.id == self._resumed_workflow_id:
            return ThreadItemReplacedEvent(item=item)
        return ThreadItemDoneEvent(item=item)

    async def start_workflow(self, workflow: Workflow) -> None:
        """Begin streaming a new workflow item."""
        item = self._open_workflow(workflow)

        if workflow.type != "reasoning" and not workflow.tasks:
            # Defer sending added event until we have tasks
            return

        await self.stream(ThreadItemAddedEvent(item=item))

    def _open_workflow(self, workflow: Workflow) -> WorkflowItem:
        item = WorkflowItem(
            id=self.generate_id("workflow"),
            created_at=datetime.now(UTC),
            workflow=workflow,
            thread_id=self.thread.id,
        )
        self.workflow_item = item
        return item

    async def update_workflow_task(self, task: Task, task_index: int) -> None:
        """Update an existing workflow task and stream the delta."""
        if self.workflow_item is None:
            raise ValueError("Workflow is not set")
        # ensure reference is updated in case task is a copy
        self.workflow_item.workflow.tasks[task_index] = task
        await self.stream(
            ThreadItemUpdatedEvent(
                item_id=self.workflow_item.id,
                update=WorkflowTaskUpdated(
                    task=task,
                    task_index=task_index,
                ),
            )
        )

    async def add_workflow_task(self, task: Task) -> None:
        """Append a workflow task and stream the appropriate event."""
        item = self.workflow_item or self._open_workflow(
            Workflow(type="custom", tasks=[])
        )
        workflow = item.workflow
        workflow.tasks.append(task)

        if (
            item.id != self._resumed_workflow_id
            and workflow.type != "reasoning"
            and len(workflow.tasks) == 1
        ):
            await self.stream(ThreadItemAddedEvent(item=item))
        else:
            await self.stream(
                ThreadItemUpdatedEvent(
                    item_id=item.id,
                    update=WorkflowTaskAdded(
                        task=task,
                        task_index=len(workflow.tasks) - 1,
                    ),
                )
            )

    async def stream(self, event: ThreadStreamEvent) -> None:
        """Enqueue an event. Raises QueueShutDown after the response finishes."""
        await self._events.put(event)

workflow_item property writable

workflow_item: WorkflowItem | None

The active workflow for this run.

generate_id

generate_id(type: StoreItemType, thread: ThreadMetadata | None = None) -> str

Generate a new store-backed id for the given item type.

Source code in chatkit/agents.py
219
220
221
222
223
224
225
226
227
def generate_id(
    self, type: StoreItemType, thread: ThreadMetadata | None = None
) -> str:
    """Generate a new store-backed id for the given item type."""
    if type == "thread":
        return self.store.generate_thread_id(self.request_context)
    return self.store.generate_item_id(
        type, thread or self.thread, self.request_context
    )

request_client_tool

request_client_tool(tool: ToolContext[AgentContext[TContext]], *, name: str, arguments: dict[str, Any], continuation: Literal['local', 'responses']) -> None

Request a browser callback for this invocation of an Agents SDK tool.

Configure the agent to stop at the calling tool. The browser receives one pending call when the run finishes and supplies its result on the next turn. Choose local replay or a continuation linked to a stored Responses response.

Source code in chatkit/agents.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def request_client_tool(
    self,
    tool: ToolContext[AgentContext[TContext]],
    *,
    name: str,
    arguments: dict[str, Any],
    continuation: Literal["local", "responses"],
) -> None:
    """Request a browser callback for this invocation of an Agents SDK tool.

    Configure the agent to stop at the calling tool. The browser receives one
    pending call when the run finishes and supplies its result on the next turn.
    Choose local replay or a continuation linked to a stored Responses response.
    """
    if tool.context is not self or not tool.tool_call_id:
        raise ValueError("Pass the ToolContext for the current tool invocation.")
    if self._client_tool_request is not None:
        self._client_tool_conflict = True
        raise ValueError(_CLIENT_TOOL_CONFLICT)
    if continuation not in ("local", "responses"):
        raise ValueError("Choose 'local' or 'responses' for model continuation.")

    self._client_tool_request = _ClientToolRequest(
        item_id=tool.tool_call.id if tool.tool_call is not None else None,
        call_id=tool.tool_call_id,
        name=name,
        arguments=arguments,
        continuation=continuation,
    )

stream_widget async

stream_widget(widget: WidgetRootInput | AsyncGenerator[WidgetRootInput], copy_text: str | None = None) -> None

Stream a widget into the thread by enqueueing widget events.

Source code in chatkit/agents.py
259
260
261
262
263
264
265
266
267
268
269
async def stream_widget(
    self,
    widget: WidgetRootInput | AsyncGenerator[WidgetRootInput],
    copy_text: str | None = None,
) -> None:
    """Stream a widget into the thread by enqueueing widget events."""
    async with aclosing(
        stream_widget(self.thread, widget, copy_text, self.generate_id)
    ) as events:
        async for event in events:
            await self.stream(event)

end_workflow async

end_workflow(summary: WorkflowSummary | None = None, expanded: bool = False) -> None

Finalize the active workflow item, optionally attaching a summary.

Source code in chatkit/agents.py
271
272
273
274
275
276
277
278
279
280
async def end_workflow(
    self, summary: WorkflowSummary | None = None, expanded: bool = False
) -> None:
    """Finalize the active workflow item, optionally attaching a summary."""
    if self.workflow_item is not None:
        await self.stream(
            self._finish_workflow(
                self.workflow_item, summary=summary, expanded=expanded
            )
        )

start_workflow async

start_workflow(workflow: Workflow) -> None

Begin streaming a new workflow item.

Source code in chatkit/agents.py
302
303
304
305
306
307
308
309
310
async def start_workflow(self, workflow: Workflow) -> None:
    """Begin streaming a new workflow item."""
    item = self._open_workflow(workflow)

    if workflow.type != "reasoning" and not workflow.tasks:
        # Defer sending added event until we have tasks
        return

    await self.stream(ThreadItemAddedEvent(item=item))

update_workflow_task async

update_workflow_task(task: Task, task_index: int) -> None

Update an existing workflow task and stream the delta.

Source code in chatkit/agents.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
async def update_workflow_task(self, task: Task, task_index: int) -> None:
    """Update an existing workflow task and stream the delta."""
    if self.workflow_item is None:
        raise ValueError("Workflow is not set")
    # ensure reference is updated in case task is a copy
    self.workflow_item.workflow.tasks[task_index] = task
    await self.stream(
        ThreadItemUpdatedEvent(
            item_id=self.workflow_item.id,
            update=WorkflowTaskUpdated(
                task=task,
                task_index=task_index,
            ),
        )
    )

add_workflow_task async

add_workflow_task(task: Task) -> None

Append a workflow task and stream the appropriate event.

Source code in chatkit/agents.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
async def add_workflow_task(self, task: Task) -> None:
    """Append a workflow task and stream the appropriate event."""
    item = self.workflow_item or self._open_workflow(
        Workflow(type="custom", tasks=[])
    )
    workflow = item.workflow
    workflow.tasks.append(task)

    if (
        item.id != self._resumed_workflow_id
        and workflow.type != "reasoning"
        and len(workflow.tasks) == 1
    ):
        await self.stream(ThreadItemAddedEvent(item=item))
    else:
        await self.stream(
            ThreadItemUpdatedEvent(
                item_id=item.id,
                update=WorkflowTaskAdded(
                    task=task,
                    task_index=len(workflow.tasks) - 1,
                ),
            )
        )

stream async

stream(event: ThreadStreamEvent) -> None

Enqueue an event. Raises QueueShutDown after the response finishes.

Source code in chatkit/agents.py
363
364
365
async def stream(self, event: ThreadStreamEvent) -> None:
    """Enqueue an event. Raises QueueShutDown after the response finishes."""
    await self._events.put(event)

ResponseStreamConverter

Used by stream_agent_response to convert streamed Agents SDK output into values used by ChatKit thread items and thread stream events.

Defines overridable methods for adapting streamed data (such as image generation results and partial updates) into the forms expected by ChatKit.

Source code in chatkit/agents.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
class ResponseStreamConverter:
    """Used by `stream_agent_response` to convert streamed Agents SDK output
    into values used by ChatKit thread items and thread stream events.

    Defines overridable methods for adapting streamed data (such as image
    generation results and partial updates) into the forms expected by ChatKit.
    """

    partial_images: int | None = None
    """
    The expected number of partial image updates for an image generation result.

    When set, this value is used to normalize partial image indices into a
    progress value in the range [0, 1]. If unset, all partial image updates are
    assigned a progress value of 0.
    """

    def __init__(self, *, partial_images: int | None = None):
        """
        Args:
            partial_images: The expected number of partial image updates for image
                generation results, or None if no progress normalization should
                be performed.
        """
        self.partial_images = partial_images

    async def base64_image_to_url(
        self,
        image_id: str,
        base64_image: str,
        partial_image_index: int | None = None,
    ) -> str:
        """
        Convert a base64-encoded image into a URL.

        This method is used to produce the URL stored on thread items for image
        generation results.

        Args:
            image_id: The ID of the image generation call. This stays stable across partial image updates.
            base64_image: The base64-encoded image.
            partial_image_index: The index of the partial image update, starting from 0.

        Returns:
            A URL string.
        """
        return f"data:image/png;base64,{base64_image}"

    def partial_image_index_to_progress(self, partial_image_index: int) -> float:
        """
        Convert a partial image index into a normalized progress value.

        Args:
            partial_image_index: The index of the partial image update, starting from 0.

        Returns:
            A float between 0 and 1 representing progress for the image
            generation result.
        """
        if self.partial_images is None or self.partial_images <= 0:
            return 0.0

        return min(1.0, partial_image_index / self.partial_images)

    async def file_citation_to_annotation(
        self, file_citation: AnnotationFileCitation
    ) -> Annotation | None:
        """Convert a Responses API file citation into an assistant message annotation."""
        filename = file_citation.filename
        if not filename:
            return None

        return Annotation(
            source=FileSource(filename=filename, title=filename),
            index=file_citation.index,
        )

    async def container_file_citation_to_annotation(
        self, container_file_citation: AnnotationContainerFileCitation
    ) -> Annotation | None:
        """Convert a Responses API container file citation into an assistant message annotation."""
        filename = container_file_citation.filename
        if not filename:
            return None

        return Annotation(
            source=FileSource(filename=filename, title=filename),
            index=container_file_citation.end_index,
        )

    async def url_citation_to_annotation(
        self, url_citation: AnnotationURLCitation
    ) -> Annotation | None:
        """Convert a Responses API URL citation into an assistant message annotation."""
        return Annotation(
            source=URLSource(url=url_citation.url, title=url_citation.title),
            index=url_citation.end_index,
        )

partial_images class-attribute instance-attribute

partial_images: int | None = partial_images

The expected number of partial image updates for an image generation result.

When set, this value is used to normalize partial image indices into a progress value in the range [0, 1]. If unset, all partial image updates are assigned a progress value of 0.

base64_image_to_url async

base64_image_to_url(image_id: str, base64_image: str, partial_image_index: int | None = None) -> str

Convert a base64-encoded image into a URL.

This method is used to produce the URL stored on thread items for image generation results.

Parameters:

Name Type Description Default
image_id str

The ID of the image generation call. This stays stable across partial image updates.

required
base64_image str

The base64-encoded image.

required
partial_image_index int | None

The index of the partial image update, starting from 0.

None

Returns:

Type Description
str

A URL string.

Source code in chatkit/agents.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
async def base64_image_to_url(
    self,
    image_id: str,
    base64_image: str,
    partial_image_index: int | None = None,
) -> str:
    """
    Convert a base64-encoded image into a URL.

    This method is used to produce the URL stored on thread items for image
    generation results.

    Args:
        image_id: The ID of the image generation call. This stays stable across partial image updates.
        base64_image: The base64-encoded image.
        partial_image_index: The index of the partial image update, starting from 0.

    Returns:
        A URL string.
    """
    return f"data:image/png;base64,{base64_image}"

partial_image_index_to_progress

partial_image_index_to_progress(partial_image_index: int) -> float

Convert a partial image index into a normalized progress value.

Parameters:

Name Type Description Default
partial_image_index int

The index of the partial image update, starting from 0.

required

Returns:

Type Description
float

A float between 0 and 1 representing progress for the image

float

generation result.

Source code in chatkit/agents.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def partial_image_index_to_progress(self, partial_image_index: int) -> float:
    """
    Convert a partial image index into a normalized progress value.

    Args:
        partial_image_index: The index of the partial image update, starting from 0.

    Returns:
        A float between 0 and 1 representing progress for the image
        generation result.
    """
    if self.partial_images is None or self.partial_images <= 0:
        return 0.0

    return min(1.0, partial_image_index / self.partial_images)

file_citation_to_annotation async

file_citation_to_annotation(file_citation: AnnotationFileCitation) -> Annotation | None

Convert a Responses API file citation into an assistant message annotation.

Source code in chatkit/agents.py
507
508
509
510
511
512
513
514
515
516
517
518
async def file_citation_to_annotation(
    self, file_citation: AnnotationFileCitation
) -> Annotation | None:
    """Convert a Responses API file citation into an assistant message annotation."""
    filename = file_citation.filename
    if not filename:
        return None

    return Annotation(
        source=FileSource(filename=filename, title=filename),
        index=file_citation.index,
    )

container_file_citation_to_annotation async

container_file_citation_to_annotation(container_file_citation: AnnotationContainerFileCitation) -> Annotation | None

Convert a Responses API container file citation into an assistant message annotation.

Source code in chatkit/agents.py
520
521
522
523
524
525
526
527
528
529
530
531
async def container_file_citation_to_annotation(
    self, container_file_citation: AnnotationContainerFileCitation
) -> Annotation | None:
    """Convert a Responses API container file citation into an assistant message annotation."""
    filename = container_file_citation.filename
    if not filename:
        return None

    return Annotation(
        source=FileSource(filename=filename, title=filename),
        index=container_file_citation.end_index,
    )

url_citation_to_annotation async

url_citation_to_annotation(url_citation: AnnotationURLCitation) -> Annotation | None

Convert a Responses API URL citation into an assistant message annotation.

Source code in chatkit/agents.py
533
534
535
536
537
538
539
540
async def url_citation_to_annotation(
    self, url_citation: AnnotationURLCitation
) -> Annotation | None:
    """Convert a Responses API URL citation into an assistant message annotation."""
    return Annotation(
        source=URLSource(url=url_citation.url, title=url_citation.title),
        index=url_citation.end_index,
    )

stream_agent_response async

stream_agent_response(context: AgentContext, result: RunResultStreaming, *, converter: ResponseStreamConverter = _DEFAULT_RESPONSE_STREAM_CONVERTER, delivery: Literal['streaming', 'reviewed_text'] = 'streaming') -> AsyncGenerator[ResponderEvent]

Convert a streamed Agents SDK run into ChatKit thread stream events.

This function consumes a streaming run result and yields ThreadStreamEvent objects and server-only persistence events as the run progresses. Closing the stream early cancels an active run.

Parameters:

Name Type Description Default
context AgentContext

The AgentContext to use for the stream.

required
result RunResultStreaming

The RunResultStreaming to convert.

required
converter ResponseStreamConverter

Defines overridable methods for adapting streamed data (such as image generation results and partial updates) into the forms expected by ChatKit.

_DEFAULT_RESPONSE_STREAM_CONVERTER
delivery Literal['streaming', 'reviewed_text']

Stream events immediately, or publish only the final string after its Agents SDK output guardrails pass. Reviewed text excludes intermediate events, annotations, app UI events and browser tool handoffs.

'streaming'

Returns:

Type Description
AsyncGenerator[ResponderEvent]

An async iterator that yields thread stream events representing the run result.

Source code in chatkit/agents.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
async def stream_agent_response(
    context: AgentContext,
    result: RunResultStreaming,
    *,
    converter: ResponseStreamConverter = _DEFAULT_RESPONSE_STREAM_CONVERTER,
    delivery: Literal["streaming", "reviewed_text"] = "streaming",
) -> AsyncGenerator[ResponderEvent]:
    """
    Convert a streamed Agents SDK run into ChatKit thread stream events.

    This function consumes a streaming run result and yields `ThreadStreamEvent`
    objects and server-only persistence events as the run progresses.
    Closing the stream early cancels an active run.

    Args:
        context: The AgentContext to use for the stream.
        result: The RunResultStreaming to convert.
        converter: Defines overridable methods for adapting streamed data (such as image
            generation results and partial updates) into the forms expected by ChatKit.
        delivery: Stream events immediately, or publish only the final string after its
            Agents SDK output guardrails pass. Reviewed text excludes intermediate events,
            annotations, app UI events and browser tool handoffs.

    Returns:
        An async iterator that yields thread stream events representing the run result.
    """
    queue_iterator = _AsyncQueueIterator(context._events)
    model_events = aiter(result.stream_events())
    cancel_requested = False

    def cancel_run() -> None:
        nonlocal cancel_requested
        if cancel_requested or result.is_complete:
            return
        cancel_requested = True
        try:
            result.cancel()
        except Exception, asyncio.CancelledError:
            logger.exception("Failed to cancel the Agents SDK run")

    merged_events = _merge_generators(model_events, queue_iterator, on_abort=cancel_run)
    reviewed_phases: dict[str, AssistantMessagePhase] = {}
    try:
        if delivery == "reviewed_text":
            # SDK guardrails check the final output, not every event emitted on the way.
            # Consume both sources without exposing or retaining their candidate events.
            async with aclosing(merged_events):
                async for event in merged_events:
                    _record_reviewed_phase(reviewed_phases, event)
            context._events.shutdown(immediate=True)
        elif delivery == "streaming":
            async with aclosing(
                _stream_agent_response(
                    context, merged_events, queue_iterator, converter
                )
            ) as events:
                async for event in events:
                    yield event
        else:
            raise ValueError("Unknown Agents response delivery mode.")
        await _close_stream(model_events)
        if result.interruptions:
            if context._client_tool_request is not None:
                raise ValueError("A paused run cannot also hand off a browser tool.")
            # AgentContext holds a live store and request-scoped resources.
            # The app restores these from the authorized thread when resuming.
            checkpoint = result.to_state().to_string(context_serializer=lambda _: {})
            yield ApprovalRequired(checkpoint)
            return
        if delivery == "reviewed_text":
            if context._client_tool_request is not None:
                raise ValueError(
                    "Reviewed text delivery cannot issue a browser tool request."
                )
            message = _reviewed_text_message(context, result, reviewed_phases)
            if message is not None:
                yield ThreadItemDoneEvent(item=message)
            return
        if (request := context._client_tool_request) is not None:
            item_id = request.item_id
            if not item_id or item_id == _CHAT_COMPLETIONS_PLACEHOLDER_ID:
                item_id = context.generate_id("tool_call")
            yield ClientToolRequest(
                item=ClientToolCallItem(
                    id=item_id,
                    thread_id=context.thread.id,
                    name=request.name,
                    arguments=request.arguments,
                    created_at=datetime.now(UTC),
                ),
                call_id=request.call_id,
                model_continuation=_capture_model_continuation(request, result),
            )
    except BaseException as error:
        cancel_run()
        context._events.shutdown(immediate=True)
        for stream in (merged_events, model_events):
            try:
                await _close_stream(stream)
            except Exception, asyncio.CancelledError:
                logger.exception("Failed to close an agent event stream")
        if delivery == "reviewed_text" and isinstance(error, BaseStreamError):
            # Error messages from checks and provider callbacks can contain the candidate.
            raise StreamError(
                ErrorCode.STREAM_ERROR, allow_retry=error.allow_retry
            ) from None
        raise