Skip to content

Use public Pipecat interfaces for voice tracing - #1155

Open
David Elner (delner) wants to merge 3 commits into
davidelner/sdk-856-python-pipecat-cascade-cleanupfrom
davidelner/sdk-856-pipecat-public-apis
Open

David Elner (delner) wants to merge 3 commits into
davidelner/sdk-856-python-pipecat-cascade-cleanupfrom
davidelner/sdk-856-pipecat-public-apis

Conversation

@delner

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

Copy link
Copy Markdown
Contributor

Reduce sensitivity to Pipecat updates through public service hooks and native turn events. Let custom services identify the client performing their model calls.

Stack: #1153 → #1154 → #1155

@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-19T19:02:57.062404Z 4a9ffe5 PR opened
ℹ️ 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: 4a9ffe5613

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

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

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
@delner
David Elner (delner) force-pushed the davidelner/sdk-856-pipecat-public-apis branch from 4a9ffe5 to e6a9d45 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
> 🤖 **This text was AI-generated.**

Private execution hooks and application bytecode inspection made cascade
tracing depend on implementation details that can change between Pipecat
releases. Scope model execution through public process_frame/run_stt/run_tts
methods and native assistant events, restoring context on every exit:

```text
process_frame -> run_tts -> OpenAI speech -> consumed audio
                 tts task -> Speech model span
```

Associate delayed turn callbacks with their originating response frames, and
identify the worker sink through public pipeline/processors identities. Remove
the redundant private segmented-STT hook. Replace bytecode traversal with
bounded native execution adapters and set_model_client() for custom services.
Capture ownership before execution so later bindings cannot change queued work.

Unknown unbound custom overrides retain task wrappers with a diagnostic;
explicit client bindings enable framework fallbacks without guessing SDK
ownership. Native client/settings access and transcript provenance still need
small legacy compatibility boundaries, documented in the integration README.

Refs: https://linear.app/braintrustdata/issue/SDK-856
@delner
David Elner (delner) force-pushed the davidelner/sdk-856-pipecat-public-apis branch from e6a9d45 to d450516 Compare November 19, 2026 19:30
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>
@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 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