Skip to content

Align Pipecat voice traces with the audio schema - #1154

Open
David Elner (delner) wants to merge 6 commits into
mainfrom
davidelner/sdk-856-python-pipecat-cascade-cleanup
Open

David Elner (delner) wants to merge 6 commits into
mainfrom
davidelner/sdk-856-python-pipecat-cascade-cleanup

Conversation

@delner

@delner David Elner (delner) commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🤖 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.
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.

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 Use public Pipecat interfaces for voice tracing #1155.

Refs: SDK-856

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T03:11:53.703901Z 01218b9 New commits
ℹ️ About Codex in GitHub

Your 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 69c17c4a22

ℹ️ 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".

@delner
David Elner (delner) force-pushed the davidelner/sdk-856-openai-speech branch from c0bb1fb to 7d6b1dd Compare November 19, 2026 19:29
@delner
David Elner (delner) force-pushed the davidelner/sdk-856-python-pipecat-cascade-cleanup branch from 69c17c4 to 22db4c0 Compare November 19, 2026 19:29
@delner David Elner (delner) self-assigned this Nov 20, 2026
Abhijeet Prasad (AbhiPrasad) added a commit that referenced this pull request Nov 24, 2026
> 🤖 **This text was AI-generated.**

Stack: **#1153** → #1154 → #1155

## Problem

Streamed text-to-speech requests were missing from traces:

```python
with client.audio.speech.with_streaming_response.create(model="tts-1", voice="alloy", input="Hi.") as response:
    response.stream_to_file("speech.wav")
```

The OpenAI SDK marks `with_streaming_response` calls with the
`x-stainless-raw-response: stream` header. The shared wrapper callback
skips tracing whenever that header is present, so that it doesn't
double-trace its own internal `with_raw_response` call. 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.

```text
before                          after
tts : task                      tts : task
  (no child)                    └─ Speech : llm
```

## Solution

`_audio_speech_create_wrapper` now checks the raw-response mode. When
the mode is `"stream"`, it routes to a new `_speech.trace_stream`. That
function opens a `Speech` span and returns a `wrapt.ObjectProxy` around
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.

```text
patched Speech.create
        │
  _raw_response_mode(kwargs)
   ├─ "stream" → trace_stream()  → SpeechResponse / AsyncSpeechResponse proxy
   ├─ "raw"    → untraced passthrough (our own internal with_raw_response call)
   └─ None     → SpeechWrapper (non-streaming, unchanged flow)

proxy method                       effect on span
iter_bytes / read                  observe → time_to_first_token, buffer audio, end at EOF
parse / text / json / stream_to_file   run the SDK method with self=proxy, so its reads are observed
iter_text / iter_lines             timing only (decoded text is not the original audio)
close() / weakref.finalize         end the span with empty output if not finished
```

Details:

- **Span timing (async).** The async SDK builds its request coroutine as
soon as `create()` is called. The span is started *inside* that
coroutine, so it opens when `async with` is entered and is parented to
whatever span is current at that point.
- **Audio capture.** Audio is captured as an attachment only when
`BRAINTRUST_CAPTURE_AGENT_AUDIO_ATTACHMENTS` is 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.
- **Request errors.** A provider rejection (for example a 400) is logged
on the span, and the span ends before the error is re-raised.
- **Caller `span_info`** is 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.create`
spans look like:

```text
             before                    after
input        "Hi."                     {"operation": "speech", "prompt": "Hi.",
                                        "parameters": {"voice": "alloy", "format": "wav"}}
metadata     {"provider": "openai"}    {"model": "tts-1", "provider": "openai"}
output       {"type": "audio"}         {"content": []}  or  {"content": [{"type": "file", ...}]}
```

## End-to-end trace

These are real `gpt-4o-mini-tts` requests from this branch, sent with
audio capture on: **[view trace in
Braintrust](https://www.braintrust.dev/app/Braintrust%20SDKs/object?object_type=project_logs&object_id=4f042522-8bae-488d-9f73-e1095570d9af&id=42f74e9e-8fb4-471c-8062-a59f3bbc39db)**

Spans were read back with BTQL. "Bytes read" is what the client
received; "attachment" is what was logged.

| Scenario | `Speech` parent | time_to_first_token | Attachment | Bytes
read |
|---|---|---|---|---|
| sync `iter_bytes` to EOF | that scenario | ✅ | `speech.wav`,
audio/wav, 151244 B | 151244 |
| sync `stream_to_file` | that scenario | ✅ | `speech.wav`, audio/wav,
146444 B | 146444 |
| sync partial (break after first chunk) | that scenario | ✅ | none (as
intended) | 1024 |
| async `read()` | that scenario | ✅ | `speech.wav`, audio/wav, 151244 B
| 151244 |
| async: created under *creator*, entered under *consumer* |
**consumer** (creator has no child) | ✅ | `speech.wav`, audio/wav,
134444 B | 134444 |
| sync non-streaming `create` | that scenario | n/a | `speech.wav`,
audio/wav, 170444 B | 170444 |
| sync request error (`voice="not-a-voice"`) | that scenario | ❌ (no
audio) | none; `error` = 400 Invalid value | — |

Every `Speech` span ended, carried `metadata = {"model":
"gpt-4o-mini-tts", "provider": "openai"}`, and was tagged with
instrumentation `openai-auto`.

## Limitations / follow-ups

- `iter_text()` / `iter_lines()` record timing but never capture audio.
- `stream_format` is 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.
- Mid-stream transport failures can't be recorded in a cassette, so
tests inject them with `generator.throw()` on the real response stream.
Request-level errors are covered by recorded 400 cassettes.

Refs: [SDK-856](https://linear.app/braintrustdata/issue/SDK-856)

---------

Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com>
Base automatically changed from davidelner/sdk-856-openai-speech to main November 24, 2026 19:18
David Elner (delner) and others added 3 commits November 24, 2026 14:30
> 🤖 **This text was AI-generated.**

Cascade operations lost model telemetry for uncovered clients, synthesized
conversational associations from timing/text, and could detach provider speech
from its task. Track actual client ownership and scope model execution so
traces preserve the provider or framework model child:

```text
llm_response : task              tts : task
└─ pipecat.llm_response : llm     └─ Speech : llm
```

Keep usage and model timing on model children, including final request tools.
Retain observed request/usage evidence when queued starts arrive late.
Ignore transcript notifications that the native aggregator did not append.
Use observed context/frame IDs for links and native aggregation for turn membership.
Enclose within-turn speech pauses and omit unknown playback interruption
outcomes. Prefer public service settings with a legacy-version fallback.

Private Pipecat compatibility hooks and static ownership inspection remain
isolated follow-up work in the next layer of this stack.

Refs: https://linear.app/braintrustdata/issue/SDK-856
> 🤖 **This text was AI-generated.**

When a model request is built before the observer has started its span,
the tracer keeps a snapshot to log later. That snapshot deep-copied the
whole request (raw messages, tool schemas, every setting), but binding
only logs the normalized messages and four tool settings:

```text
before: bt_safe_deep_copy((normalized, params))
after:  bt_safe_deep_copy((normalized, request_metadata(params)))
                                       └─ tools, tool_choice,
                                          parallel_tool_calls, max_tool_calls
```

`request_metadata()` is now shared by `ModelOperation.request`. Other
cleanups in the model child:

- Build WAV attachments straight from the audio `bytearray` instead of
  copying it to `bytes` first. Input audio that is already WAV is copied
  once.
- Remove `ModelOperation.texts`, which was filled but never read.

Multiple `span.log` calls on one span are left as they are: rows are
merged locally before upload, and each call copies only its own fields.

Tests cover the same behavior with fewer full voice sessions:

- Run the uncovered HTTP client test as two cases instead of four;
  audio capture and SDK configuration are independent.
- Fold the "provider integration disabled" check into the main voice
  session test, and the explicit synthesis parent checks into the
  speech stream test.
- Fold the nested pipeline test into the delayed observation test as a
  `nested_native_turn` layout, and share the delayed observer helper.
- Trim the TTS hook compatibility matrix and a redundant transcript
  provenance variant.

Refs: https://linear.app/braintrustdata/issue/SDK-856
> 🤖 **This text was AI-generated.**

OpenAI Realtime responses had their own model child, separate from the
general Pipecat model child every other service uses. A class-name check
kept the two from both firing:

```text
before                                after
llm_response : task                   llm_response : task
└─ pipecat.realtime.response : llm    └─ pipecat.llm_response : llm
   (own span, raw Realtime output)       (usage from response.done)
```

The Realtime `response.done` hook now only reports usage, including
cached audio tokens, into the response's existing `ModelOperation`
through a shared `report_usage()`. The child gets the same output,
timing, request settings and error handling as other services, and the
Realtime class-name check, `finish_realtime_response` and the separate
span are removed. `pipecat.realtime.response` has not been released.

Streaming STT services run `run_stt` on every input frame, including
silence. After a turn ended, the next silent frame opened a new `stt`
span and buffered audio (about 32 KB/s) until the next transcript.
`model_operation` now applies the same gate as `consume_audio`: during
observed VAD silence with no recognition in progress it returns a
detached operation that opens nothing and buffers nothing.

Cleanups in the same files:

- Cache model ownership per service and operation instead of walking
  service bytecode on every response, sentence and recognition.
- Remove dead code: `completes_turn`, `has_output_transport`, the no-op
  metrics handler, `message_text` and `_context_turn`.
- Move `_ACTIVE_MODEL` to `_model.py`, drop repeated local imports, and
  share `_accepts`, `_current_operation`, `_has_base` and `_wav_part`.
- Drop pre-checks that `FunctionWrapperPatcher.patch()` already runs.
- Tests: add a cassette constant and context helper, and drop checks
  already covered by `_assert_cascade_released`.

Refs: https://linear.app/braintrustdata/issue/SDK-856
@AbhiPrasad
Abhijeet Prasad (AbhiPrasad) force-pushed the davidelner/sdk-856-python-pipecat-cascade-cleanup branch from 22db4c0 to 1f952a4 Compare November 24, 2026 20:43
> 🤖 **This text was AI-generated.**

Many Pipecat tests replayed another test's cassette, and the "uncovered
client" cases ran on hand-written stand-ins: OpenAI services that sent
their requests over raw httpx, a fake streaming STT, and a fake deferred
TTS. Those stand-ins hid real bugs.

Tests now use real Pipecat services and their own recordings:

```text
before                              after
_http_services() STT/TTS            ElevenLabsSTTService, ElevenLabsHttpTTSService (VCR)
fake StreamingSTT                   ElevenLabsRealtimeSTTService  (websocket cassette)
fake DeferredSpeech                 ElevenLabsTTSService          (websocket cassette)
replayed other tests' cassettes     one cassette per test (or per differing variant)
```

`_WebsocketCassette` records a provider websocket once and replays it
from a local server. Client messages are counted, never stored, except
for client-chosen `context_id`s, which replay maps to the live ones. The
LLM stand-in stays as the one documented exception, since every Pipecat
LLM in the test environment calls an SDK the integrations cover; its
injected duplicate-usage behavior is removed.

Real providers exposed real bugs, fixed here:

- Bedrock: Pipecat's Bedrock service calls an aiobotocore session, which
  the ownership table did not list, so a Bedrock response got both the
  Bedrock integration's span and a duplicate `pipecat.llm_response`.
  Session client factories (aiobotocore, aioboto3, botocore, boto3) now
  count as covered.
- Websocket TTS: a reply's sentences stream into one provider context
  whose audio arrives after `run_tts` returns. Each call opened its own
  model child, so no audio was captured. Later text in a deferred context
  now joins the open operation, which records all text sent.
- ElevenLabs model spans had no `provider`; `elevenlabs` is now mapped.

Test infrastructure:

- Filter the `xi-api-key` header from cassettes, and add an ElevenLabs
  dummy key for playback.
- Normalize aiohttp header names and drop multipart writer bodies before
  recording, since YAML cannot store them.
- Install aiobotocore in the Pipecat nox session.
- `_assert_no_errors` keeps a recorded provider error (quota, plan, auth)
  from passing as a valid recording.

The websocket TTS test skips on Pipecat 1.3.0: without tracing or the
recorder, its ElevenLabs websocket TTS never lets an EndFrame finish in a
pipeline without a transport. The Bedrock test skips on 1.3.0, whose
service uses aioboto3, which the session does not install.

Refs: https://linear.app/braintrustdata/issue/SDK-856

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e45e9e53a7

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "Codex (@codex) address that feedback".

Comment on lines +153 to 154
if turn is None and id(processor) in self.native_turn_processors:
turn = self._turn = _AgentTurn(self._spans.turn("agent_turn"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve interruption suppression without an assistant aggregator

For pipelines without a native assistant aggregator, responses now leave _turn unset, but interrupt() still sets _interrupted_reply only when _turn exists. Consequently, after a barge-in, the transport's already-dequeued audio can restart playback: start_playback() sees a false interruption flag and creates another agent_speech span for the interrupted reply. Update interruption tracking independently of conversational turn creation so these pipelines retain the existing suppression of leftover playback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 This text was AI-generated.

Valid, thanks. This branch gates agent_turn on a downstream assistant aggregator, so in pipelines without one interrupt() never set _interrupted_reply, and the chunk the transport writes after a barge-in opened a third agent_speech.

Fixed in b57bd9b: interrupt() now sets the flag whenever it ends a reply's work (playback, a response, or a synthesis), with or without a turn. The guard in start_playback() already covers the turnless case.

Added test_barge_in_without_assistant_aggregator_opens_no_leftover_speech (recorded, both Pipecat versions). It uses _VoiceSession(assistant_aggregator=False) plus the existing hold_inflight_audio hook to force the ordering. It failed before the fix with three agent_speech spans, and passes after with exactly the interrupted reply and the answer.

> 🤖 **This text was AI-generated.**

After a barge-in, Pipecat's output transport still writes the audio chunk
it had already dequeued, which restarts bot speech. #1165 ignores that
restart, but `interrupt()` only set its flag when an agent turn existed.
This branch opens agent turns only on routes with an assistant
aggregator, so in pipelines without one the leftover chunk opened a new
`agent_speech` span for the interrupted reply:

```text
before                                after
agent_speech (interrupted)            agent_speech (interrupted)
agent_speech (leftover chunk, ~3s)    agent_speech (answer)
agent_speech (answer)
```

`interrupt()` now sets the flag whenever it ends a reply's work
(playback, a response, or a synthesis), with or without a turn.

`_VoiceSession` gains an `assistant_aggregator=False` option. Without the
aggregator, a reply is done when its response reaches the sink or when it
is interrupted, since the barge-in drops the interrupted reply's end
frame.

Refs: https://linear.app/braintrustdata/issue/SDK-856
> 🤖 **This text was AI-generated.**

Pipecat cassettes stored every speech-to-text upload's audio, about 1.8 MB
of the 6.6 MB total. VCR matches on method and URL only, so those request
bodies are never read back.

```text
before                       after
latest/  3.5 MB              latest/  2.1 MB
1.3.0/   3.1 MB              1.3.0/   2.0 MB
```

- Recording now blanks the bodies of OpenAI transcription/translation and
  ElevenLabs speech-to-text uploads.
- The Pipecat `vcr_config` replaced the shared `before_record_request` and
  silently dropped `sanitize_input_audio`; it is now chained in.
- Existing cassettes were rewritten with VCR's serializer to blank those
  bodies; nothing else changed.

The rest is mostly TTS audio in responses, which replay feeds back
through the pipeline, so it stays.

Refs: https://linear.app/braintrustdata/issue/SDK-856

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants