Repository navigation
Description
Please read this first
- Have you read the docs? Yes.
- Have you searched for related issues? Yes. Add to docs, how to end
StreamedAudioInputgracefully #1686 / docs: #1686 update the document to mention the end of voice stream #1687 documentedNoneas the end-of-stream signal. fix(voice): finish transcription iterators when sessions close during setup #4995, fix(voice): start the dispatcher when a session ends with no turns #4259, fix(voice): wake stream when producer is cancelled #4825 and fix(voice): report transcription session close failures to the consumer #4343 cover close during setup, dispatcher start, cancellation and close errors, not end of input.
Describe the bug
StreamedAudioInput.add_audio(None) is documented as "indicates the end of the stream". With OpenAISTTModel, the pipeline doesn't actually end: result.stream() keeps waiting for about 16.7 minutes and the STT websocket stays open.
In src/agents/voice/models/openai_stt.py, _stream_audio just breaks when it reads None. It sends no input_audio_buffer.commit, doesn't close the websocket, and doesn't tell _handle_events. After that, nothing on the client side ends the session:
_handle_eventsfinishes only onWebsocketDoneSentinel(socket closed) or afterEVENT_INACTIVITY_TIMEOUT = 1000seconds without events.- So
transcribe_turns()doesn't finish,_run_multi_turnnever reachesoutput._done(), andsession_endedis never emitted.
Consequences:
async for event in result.stream()hangs for ~1000 s after the caller has said the input is over, and the websocket stays open for that time.- Because no commit is sent, a final utterance that server VAD hasn't closed yet (for example push-to-talk released mid-phrase) is never transcribed.
Debug information
- Agents SDK version:
mainat c467732 - Python version: 3.12
- OS: macOS 15
- Model:
gpt-4o-transcribeviaOpenAISTTModel; reproduced against a fake websocket, no network
Repro steps
A fake server acknowledges the session, transcribes one turn and keeps the socket open. TTS is a stub.
Repro script
import asyncio, json, time
from unittest.mock import patch
import numpy as np
from openai import AsyncOpenAI
from agents.voice import (
StreamedAudioInput, VoicePipeline, SingleAgentVoiceWorkflow, VoicePipelineConfig,
)
from agents.voice.models.openai_stt import OpenAISTTModel, EVENT_INACTIVITY_TIMEOUT
from agents.voice.model import TTSModel, TTSModelSettings
from agents import Agent
from agents.voice.workflow import VoiceWorkflowBase
class FakeServerWS:
def __init__(self):
self.incoming: asyncio.Queue[str] = asyncio.Queue()
self.sent: list[dict] = []
self.closed = asyncio.Event()
self.incoming.put_nowait(json.dumps({"type": "session.created"}))
async def __aenter__(self): return self
async def __aexit__(self, *a): self.closed.set()
async def send(self, payload: str):
msg = json.loads(payload)
self.sent.append(msg)
if msg["type"] == "session.update":
await self.incoming.put(json.dumps({"type": "session.updated"}))
if msg["type"] == "input_audio_buffer.append" and sum(
m["type"] == "input_audio_buffer.append" for m in self.sent) == 2:
# server VAD detects end of speech and transcribes the turn
await self.incoming.put(json.dumps({
"type": "conversation.item.input_audio_transcription.completed",
"item_id": "item_1", "transcript": "hello there"}))
async def close(self): self.closed.set()
def __aiter__(self): return self
async def __anext__(self):
get = asyncio.create_task(self.incoming.get())
closed = asyncio.create_task(self.closed.wait())
done, _ = await asyncio.wait({get, closed}, return_when=asyncio.FIRST_COMPLETED)
if closed in done:
get.cancel(); raise StopAsyncIteration
closed.cancel(); return get.result()
class EchoWorkflow(VoiceWorkflowBase):
async def run(self, transcription):
yield f"You said: {transcription}."
class SilentTTS(TTSModel):
@property
def model_name(self): return "fake-tts"
async def run(self, text, settings):
yield b"\x00\x00" * 10
async def main():
ws = FakeServerWS()
client = AsyncOpenAI(api_key="sk-test")
pipeline = VoicePipeline(
workflow=EchoWorkflow(),
stt_model=OpenAISTTModel("gpt-4o-transcribe", client),
tts_model=SilentTTS(),
config=VoicePipelineConfig(tracing_disabled=True),
)
audio = StreamedAudioInput()
with patch("websockets.connect", return_value=ws):
result = await pipeline.run(audio)
await audio.add_audio(np.zeros(2400, dtype=np.int16))
await audio.add_audio(np.zeros(2400, dtype=np.int16))
await audio.add_audio(None) # documented end-of-stream signal
t0 = time.monotonic()
events = []
async def consume():
async for ev in result.stream():
events.append(getattr(ev, "event", ev.type))
try:
await asyncio.wait_for(consume(), timeout=5)
print(f"stream finished after {time.monotonic()-t0:.2f}s: {events}")
except asyncio.TimeoutError:
print(f"EVENT_INACTIVITY_TIMEOUT = {EVENT_INACTIVITY_TIMEOUT}s")
print(f"stream still open 5s after add_audio(None); events so far: {events}")
print("sent to server after end of input:",
[m['type'] for m in ws.sent][-3:])
asyncio.run(main())Output on main:
EVENT_INACTIVITY_TIMEOUT = 1000s
stream still open 5s after add_audio(None); events so far: ['turn_started', 'voice_stream_event_audio', 'turn_ended']
sent to server after end of input: ['session.update', 'input_audio_buffer.append', 'input_audio_buffer.append']
Expected behavior
After add_audio(None), pending speech is committed and transcribed, then the STT session closes, session_ended is emitted and result.stream() finishes.
A possible fix: on None, commit the buffer if speech was detected but not yet committed (committing an empty buffer returns a server error, which the listener currently treats as fatal), then close the websocket once the committed items have their transcripts or after a short grace period, so _handle_events receives WebsocketDoneSentinel. I'm happy to share a patch if it helps.
Activity