|
| 1 | +"""Run speech transcriptions through a caller-owned native Session.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +from collections.abc import AsyncGenerator |
| 7 | +from dataclasses import dataclass |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from .._public import preserve_module_identity as _preserve_module_identity |
| 11 | +from ..observation import EventGap, OutputTextDelta, TurnStarted |
| 12 | +from ..session import Session |
| 13 | +from ..turn import Turn |
| 14 | + |
| 15 | + |
| 16 | +class VoiceEventGapError(RuntimeError): |
| 17 | + """Native output observations were lost before they could be spoken.""" |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class _Invocation: |
| 22 | + submission: asyncio.Task[Turn[str]] |
| 23 | + cancellation: asyncio.Task[None] | None = None |
| 24 | + finished: bool = False |
| 25 | + |
| 26 | + |
| 27 | +async def _join(task: asyncio.Task[Any]) -> None: |
| 28 | + """Join owned cleanup even if the caller receives another cancellation.""" |
| 29 | + while not task.done(): |
| 30 | + try: |
| 31 | + await asyncio.shield(task) |
| 32 | + except asyncio.CancelledError: |
| 33 | + continue |
| 34 | + task.result() |
| 35 | + |
| 36 | + |
| 37 | +class NativeSessionVoiceWorkflow: |
| 38 | + """Speak native output while retaining the Session's history and policies. |
| 39 | +
|
| 40 | + The application opens and closes the Session and handles its interactions. |
| 41 | + Each transcription submits a new root turn. Concurrent runs are rejected; |
| 42 | + an already busy Session follows its normal rejection policy. Close a run |
| 43 | + iterator explicitly when stopping early, for example with contextlib.aclosing. |
| 44 | + Closing or cancelling a run stops and joins only its own native turn. |
| 45 | + """ |
| 46 | + |
| 47 | + def __init__(self, session: Session[Any, Any]) -> None: |
| 48 | + self._session = session |
| 49 | + self._invocation: _Invocation | None = None |
| 50 | + |
| 51 | + async def on_start(self) -> AsyncGenerator[str, None]: |
| 52 | + """Start without adding a greeting to the caller's conversation.""" |
| 53 | + return |
| 54 | + yield |
| 55 | + |
| 56 | + async def run(self, transcription: str) -> AsyncGenerator[str, None]: |
| 57 | + """Yield this transcription's native text; propagate terminal failures.""" |
| 58 | + if not isinstance(transcription, str) or not transcription.strip(): |
| 59 | + raise ValueError("transcription must be a nonempty string") |
| 60 | + if self._invocation is not None: |
| 61 | + raise RuntimeError("NativeSessionVoiceWorkflow already has an active run") |
| 62 | + |
| 63 | + # Reserve before awaiting admission. Shielding retains the exact Turn if |
| 64 | + # cancellation races with submit returning its locally issued handle. |
| 65 | + invocation = _Invocation( |
| 66 | + asyncio.create_task(self._session.submit(transcription, output_type=str)) |
| 67 | + ) |
| 68 | + self._invocation = invocation |
| 69 | + completed = False |
| 70 | + primary_error: BaseException | None = None |
| 71 | + try: |
| 72 | + turn = await asyncio.shield(invocation.submission) |
| 73 | + started = False |
| 74 | + preceding_gap = False |
| 75 | + async for event in turn.events(): |
| 76 | + if invocation.cancellation is not None: |
| 77 | + raise asyncio.CancelledError |
| 78 | + if isinstance(event, TurnStarted) and event.submission_id == turn.submission_id: |
| 79 | + started = True |
| 80 | + preceding_gap = False |
| 81 | + elif isinstance(event, EventGap): |
| 82 | + if started: |
| 83 | + raise VoiceEventGapError("Native voice output observations were lost") |
| 84 | + preceding_gap = True |
| 85 | + elif isinstance(event, OutputTextDelta): |
| 86 | + if preceding_gap: |
| 87 | + raise VoiceEventGapError("Native voice turn start or output was lost") |
| 88 | + yield event.delta |
| 89 | + if preceding_gap: |
| 90 | + raise VoiceEventGapError("Native voice turn observations were lost") |
| 91 | + await turn.get_result() |
| 92 | + if invocation.cancellation is not None: |
| 93 | + raise asyncio.CancelledError |
| 94 | + completed = True |
| 95 | + except BaseException as error: |
| 96 | + primary_error = error |
| 97 | + raise |
| 98 | + finally: |
| 99 | + invocation.finished = True |
| 100 | + try: |
| 101 | + if not completed: |
| 102 | + await self._cancel(invocation) |
| 103 | + except BaseException: |
| 104 | + # Keep the reservation after failed cleanup. A later cancel can |
| 105 | + # retry the same exact turn before any new work is admitted. |
| 106 | + if primary_error is None: |
| 107 | + raise |
| 108 | + else: |
| 109 | + if self._invocation is invocation: |
| 110 | + self._invocation = None |
| 111 | + |
| 112 | + async def _cancel(self, invocation: _Invocation) -> None: |
| 113 | + cancellation = invocation.cancellation |
| 114 | + if cancellation is None or ( |
| 115 | + cancellation.done() |
| 116 | + and not cancellation.cancelled() |
| 117 | + and cancellation.exception() is not None |
| 118 | + ): |
| 119 | + |
| 120 | + async def stop() -> None: |
| 121 | + try: |
| 122 | + turn = await invocation.submission |
| 123 | + except Exception: |
| 124 | + # Failed admission issued no handle and owns no native work. |
| 125 | + return |
| 126 | + await turn.cancel() |
| 127 | + |
| 128 | + invocation.cancellation = asyncio.create_task(stop()) |
| 129 | + assert invocation.cancellation is not None |
| 130 | + await _join(invocation.cancellation) |
| 131 | + |
| 132 | + async def cancel(self) -> None: |
| 133 | + """Stop and join the current owned turn without closing the Session. |
| 134 | +
|
| 135 | + A suspended run iterator must still be closed by its consumer before a |
| 136 | + new run can begin. Calling cancel again is safe and joins the same stop. |
| 137 | + """ |
| 138 | + invocation = self._invocation |
| 139 | + if invocation is not None: |
| 140 | + await self._cancel(invocation) |
| 141 | + if invocation.finished and self._invocation is invocation: |
| 142 | + self._invocation = None |
| 143 | + |
| 144 | + |
| 145 | +_preserve_module_identity(globals(), "agents.voice.workflow") |
0 commit comments