Repository navigation
Trace OpenAI streaming speech generation - #1153
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c0bb1fbb36
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
c0bb1fb to
7d6b1dd
Compare
> 🤖 **This text was AI-generated.** Streaming speech requests previously bypassed model tracing, leaving audio framework operations without their provider child. Trace the actual OpenAI request and consumed response as a naturally named Speech span: ```text tts : task └─ Speech : llm ``` Capture canonical speech inputs and opt-in audio only after successful EOF. Preserve streaming, cancellation, errors, and caller span_info for synchronous and asynchronous clients without consuming additional response bytes. Refs: https://linear.app/braintrustdata/issue/SDK-856
> 🤖 **This text was AI-generated.**
Follow-up to the streamed speech tracing in the previous commit.
The async SDK builds its request coroutine as soon as
`with_streaming_response.create()` is called, not when the context is
entered. The Speech span was started outside that coroutine, so it began
at create time, under whatever span was current then. If the manager was
never entered, the span never ended.
```text
with start_span("creator"):
manager = client.audio.speech.with_streaming_response.create(...)
with start_span("consumer"):
async with manager as r: ...
before: creator └─ Speech (timing includes the gap before enter)
after: consumer └─ Speech
```
The span is now started inside the coroutine, so it opens when the
request actually runs.
Reading the body through some SDK helpers also skipped the proxy:
`iter_text()` and `iter_lines()` iterate the httpx response directly, and
`text()` / `json()` call the wrapped `read()`. Those reads logged no
`time_to_first_token` or output, and the span only ended at `close()`.
```text
iter_bytes / read / parse / stream_to_file -> observed (already)
text / json -> run with self=proxy, audio captured
iter_text / iter_lines -> observed for timing; no audio
capture (decoded text is not
the original bytes)
```
Also:
- log response headers (cache metrics) on the streaming path, matching
the non-streaming wrapper
- read the filename from `response.response.headers` for non-streaming
`HttpxBinaryResponseContent`
- drop a redundant capture-flag check in `observe()`
Tests are consolidated around real cassettes. The consumption test now
covers every read method, creates the manager outside its parent span,
and asserts the attachment content type. A new cassette-backed test
covers a provider 400 before any audio streams. Low-value tests (a
hand-built `_SpeechTrace` and a helper-only input check) are removed.
Note: span `input`/`output` shape for non-streaming speech changed in the
previous commit and should be called out in the changelog.
Refs: https://linear.app/braintrustdata/issue/SDK-856
d69a6b6 to
98b4c8d
Compare
> 🤖 **This text was AI-generated.** Stack: #1153 (merged) → **#1154** → #1155 ## Problem Pipecat voice traces did not match the audio trace schema: - **Missing model work.** A service that calls its model through a client no provider integration covers (a custom HTTP client, a websocket provider such as ElevenLabs) produced a Pipecat task span with no model child. Its tokens, time to first token, request tools and audio were lost. - **Duplicate model work.** Pipecat's Bedrock service was treated as uncovered even though the Bedrock integration traces it, so one response got two model spans and double-counted tokens. - **Detached provider spans.** Provider speech spans could end up outside the `tts` task they belong to. - **Guessed links.** Conversation links were inferred from timing and matching text, so unrelated transcripts and responses could be connected. - **Invented turns.** A bare model response opened an `agent_turn` even when no assistant aggregator grouped the conversation. ```text before after llm_response : task llm_response : task (no child, usage lost) └─ pipecat.llm_response : llm (uncovered client) └─ Chat Completion / Bedrock : llm (covered client) tts : task tts : task (Speech span elsewhere) └─ Speech : llm / pipecat.tts : llm ``` ## Solution **Model children follow actual client ownership.** Before an operation runs, the tracer checks which client the service's execution methods call. If a provider integration covers that client, the provider's span is the model child. Otherwise the tracer opens a `pipecat.<op>` child (`llm_response`, `stt`, `tts`) carrying usage, time to first token, the final request's tools and opt-in audio. The result is cached per service. AWS session client factories (aiobotocore, aioboto3, botocore, boto3) count as covered, since the Bedrock integration traces the clients they create. ```text service.run_tts / _process_context / run_stt │ provider_client_expected(service, op) (cached per service) ├─ covered → provider span (Chat Completion, Speech, Bedrock, ...) under the task └─ uncovered → pipecat.<op> child carrying usage and audio ``` **Streaming providers.** - A websocket TTS reply streams all its sentences into one provider context, and the audio arrives after `run_tts` returns. Later text in that context joins the open model operation, so the child records everything sent and captures the audio. - Streaming STT runs on every input frame. Silence after a turn no longer opens a recognition or buffers audio. **OpenAI Realtime uses the same child.** The Realtime `response.done` hook from #1168 reports usage, including cached audio tokens, into the response's `pipecat.llm_response` child. It previously created a separate, unreleased `pipecat.realtime.response` span. **Links come from observed IDs, not text.** Context links use the frame IDs and message identity that Pipecat's native aggregator records. Transcripts the aggregator didn't add are ignored, and an edited message keeps its links only while unchanged. **Turns come from the native aggregator.** `agent_turn` opens only on routes with an `LLMAssistantAggregator` downstream; other responses stay directly under `session`. **Late or out-of-order observations.** Pipecat observers run on a queue, so a request or its usage can execute before the observer sees the response start. That evidence is kept and attached once the span exists. **Smaller fixes:** - Speech pauses within a turn are enclosed by the turn. - Playback with an unknown interruption outcome no longer reports `interrupted: false`. - ElevenLabs spans record `provider: elevenlabs`. - Public service settings are preferred, with a fallback for older Pipecat versions. **Real providers in tests.** The uncovered-client tests now use real ElevenLabs STT/TTS services instead of hand-written stand-ins, and each test has its own recording. That switch exposed the Bedrock, websocket TTS and provider bugs above. VCR doesn't record websockets, so `_WebsocketCassette` records a provider websocket once and replays it from a local server. Client messages are counted, not stored, so audio and keys stay out of the file. The `xi-api-key` header is filtered from cassettes. ## Limitations / follow-ups - Every Pipecat LLM in the test environment calls an SDK the integrations cover, so the uncovered LLM path still uses one documented stand-in: the real OpenAI service sending its request over httpx, with recorded traffic. - On Pipecat 1.3.0 the websocket TTS test is skipped, because that version's ElevenLabs websocket TTS never finishes shutdown in a pipeline without a transport, even without tracing. The Bedrock test is also skipped there, because 1.3.0's Bedrock service uses aioboto3. - Ownership is decided by inspecting service bytecode against a hand-maintained table of provider entry points. A follow-up could have provider integrations publish the entry points they patch. - Private Pipecat compatibility hooks remain isolated work for #1155. Refs: [SDK-856](https://linear.app/braintrustdata/issue/SDK-856/python-pipecat-cascade-cleanup) --------- Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com>
Stack: #1153 → #1154 → #1155
Problem
Streamed text-to-speech requests were missing from traces:
The OpenAI SDK marks
with_streaming_responsecalls with thex-stainless-raw-response: streamheader. The shared wrapper callback skips tracing whenever that header is present, so that it doesn't double-trace its own internalwith_raw_responsecall. As a result, streamed speech never produced a span, and audio frameworks built on top of it (LiveKit, Pipecat) showed their TTS step with no provider child.Solution
_audio_speech_create_wrappernow checks the raw-response mode. When the mode is"stream", it routes to a new_speech.trace_stream. That function opens aSpeechspan and returns awrapt.ObjectProxyaround the SDK response. The span stays open while the caller consumes the audio, and it ends when the stream finishes, errors, is closed, or the response is garbage-collected.Details:
create()is called. The span is started inside that coroutine, so it opens whenasync withis entered and is parented to whatever span is current at that point.BRAINTRUST_CAPTURE_AGENT_AUDIO_ATTACHMENTSis on and the body was read cleanly to the end. Partial, cancelled, errored or abandoned streams log{"content": []}. Chunks are kept by reference and joined once at the end, and whole-body reads are logged without being copied.span_infois honored on both the streaming and non-streaming paths.Span shape change (non-streaming too)
The streaming and non-streaming paths share the same input and output shape. This changes what existing non-streaming
audio.speech.createspans look like:End-to-end trace
These are real
gpt-4o-mini-ttsrequests from this branch, sent with audio capture on: view trace in BraintrustSpans were read back with BTQL. "Bytes read" is what the client received; "attachment" is what was logged.
Speechparentiter_bytesto EOFspeech.wav, audio/wav, 151244 Bstream_to_filespeech.wav, audio/wav, 146444 Bread()speech.wav, audio/wav, 151244 Bspeech.wav, audio/wav, 134444 Bcreatespeech.wav, audio/wav, 170444 Bvoice="not-a-voice")error= 400 Invalid valueEvery
Speechspan ended, carriedmetadata = {"model": "gpt-4o-mini-tts", "provider": "openai"}, and was tagged with instrumentationopenai-auto.Limitations / follow-ups
iter_text()/iter_lines()record timing but never capture audio.stream_formatis not recorded in the span input.client.audio.speech.with_raw_response.create(...)called directly by users is still untraced. That passthrough is shared with other endpoints and is unchanged here.generator.throw()on the real response stream. Request-level errors are covered by recorded 400 cassettes.Refs: SDK-856