Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions py/src/braintrust/integrations/pipecat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Pipecat tracing compatibility

`setup_pipecat()` and `wrap_pipeline_worker()` trace cascade operations through
Pipecat's observer, public frame-processing methods, and public STT/TTS async
generators. Provider SDK spans join the framework task in the executing service
task. Uncovered transports emit `pipecat.*` model children instead. Model usage
and timing belong on those children, not their task wrappers.

## Custom service clients

Pipecat does not expose a universal public accessor for the client that executes
an operation. Braintrust recognizes known native execution routes in the tested
Pipecat versions. For custom services that override these routes, declare the
actual executing client before running the pipeline:

```python
from braintrust.integrations.pipecat import set_model_client

# The same client your custom service actually calls:
set_model_client(my_llm_service, operation="llm_response", client=openai_client)

# A custom service that sends its own HTTP or WebSocket request:
set_model_client(my_tts_service, operation="tts", client=None)
```

Supported operations are `llm_response`, `stt`, and `tts`. A client covered by a
Braintrust integration retains ownership when that integration is disabled;
only the framework task is then emitted. An uncovered client, including `None`,
gets a framework model child. Do not bind an unused SDK client or a client used
only to read configuration. Update the binding before each operation if the
service changes its execution path. Ownership is captured when each operation
starts, so later configuration changes do not affect queued earlier operations.

An unknown, unbound custom route emits its framework task and a diagnostic;
Braintrust does not guess ownership from provider names, application bytecode,
or whether a provider span appeared. Provider instrumentation can still emit
its natural child under that task. Explicit binding is required to opt an
unknown transport into framework model spans. This is a deliberate replacement
for the earlier static bytecode inference.

## Remaining compatibility boundaries

- Pipecat 1.3 lacks the public `settings` accessor. The integration uses the
legacy settings store only as a fallback.
- Known native request implementations have no public executing-client getter.
`_compat.py` matches their implementation identities before reading the
legacy client store. Application overrides require an explicit binding.
- Native transcript aggregators do not expose consumed transcription frame IDs
when writing context. Small, capability-gated aggregation hooks retain exact
frame/message lineage. Missing evidence omits optional links; matching text
does not establish provenance.
- Pipecat 1.3 has no public event-handler removal API. Its single shared callback
captures no observer or session, and uses only the originating event context.
Newer versions unregister the callback during cleanup.
- LLM provider context uses a bounded observer handshake. Delayed delivery
reserves the task identity for provider children while the queued observer
supplies its actual parent and operation data. Shutdown closes any remaining
pending task as incomplete, without extending the wait or buffering audio.

The GPT Live hooks are unchanged by the cascade compatibility refactor.
Non-OpenAI native adapters and WebSocket TTS require additional runtime coverage;
current provider-backed regressions use real OpenAI services and recorded HTTP
responses on Pipecat 1.3.0 and 1.16.0.
2 changes: 2 additions & 0 deletions py/src/braintrust/integrations/pipecat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
from braintrust.audio import AudioRecordingOptions
from braintrust.logger import NOOP_SPAN, current_span, init_logger

from ._model_clients import set_model_client
from .integration import PipecatIntegration
from .patchers import set_default_observer_options, wrap_pipeline_worker


__all__ = [
"PipecatIntegration",
"setup_pipecat",
"set_model_client",
"wrap_pipeline_worker",
]

Expand Down
124 changes: 124 additions & 0 deletions py/src/braintrust/integrations/pipecat/_compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Bounded compatibility with native Pipecat execution implementations.

Pipecat 1.3/1.16 have no public executing-client accessor. Only inspect the
legacy client store after matching the complete known execution route. An
inherited unused client or an overridden request method proves nothing.
"""

import inspect
import sys
from typing import Any


# operation, implementation module/class, method route[, client store].
# Identity checks allow inherited implementations, never application overrides.
_EXECUTIONS = (
(
"llm_response",
"openai.base_llm",
"BaseOpenAILLMService",
("process_frame", "_process_context", "get_chat_completions"),
),
(
"llm_response",
"anthropic.llm",
"AnthropicLLMService",
("process_frame", "_process_context", "_create_message_stream"),
),
("llm_response", "google.llm", "GoogleLLMService", ("process_frame", "_process_context", "_stream_content")),
# Bedrock creates its runtime client per request from this session.
("llm_response", "aws.llm", "AWSBedrockLLMService", ("process_frame", "_process_context"), "_aws_session"),
("tts", "openai.tts", "OpenAITTSService", ("run_tts",)),
("tts", "google.tts", "GeminiTTSService", ("run_tts",)),
Comment thread
delner marked this conversation as resolved.
Resolved
)

# These native operations execute transports without a covered model SDK.
# Deliberately list concrete execution methods, not provider labels.
_TRANSPORTS = (
("tts", "cartesia.tts", "CartesiaTTSService"),
("tts", "cartesia.tts", "CartesiaHttpTTSService"),
("tts", "elevenlabs.tts", "ElevenLabsTTSService"),
("tts", "elevenlabs.tts", "ElevenLabsHttpTTSService"),
("tts", "google.tts", "GoogleTTSService"),
("tts", "google.tts", "GoogleHttpTTSService"),
("stt", "deepgram.stt", "DeepgramSTTService"),
("stt", "elevenlabs.stt", "ElevenLabsSTTService"),
("stt", "elevenlabs.stt", "ElevenLabsRealtimeSTTService"),
("stt", "google.stt", "GoogleSTTService"),
("stt", "openai.stt", "OpenAIRealtimeSTTService"),
# The Realtime LLM service talks to its websocket directly, not the SDK.
(
"llm_response",
"openai.realtime.llm",
"OpenAIRealtimeLLMService",
("process_frame", "_handle_evt_response_done"),
),
)


def _implementation(module: str, name: str) -> Any:
# The service's actual class has already loaded its defining module. Do not
# import optional providers just to classify another service.
return getattr(sys.modules.get("pipecat.services." + module), name, None)


def _function(method: Any) -> Any:
method = inspect.unwrap(method)
return getattr(method, "__func__", method)


def _matches(service: Any, cls: Any, methods: tuple[str, ...]) -> bool:
return cls is not None and all(
callable(expected := getattr(cls, name, None))
and _function(getattr(service, name, None)) is _function(expected)
for name in methods
)


def _tts_dispatch_matches(service: Any, cls: Any) -> bool:
# The public dispatchers and their known version-specific execution path
# must agree too: an inherited but unused run_tts proves no ownership.
methods = tuple(
name
for name in (
"process_frame",
"tts_process_generator",
"_handle_tts_speak",
"_handle_text",
"_handle_aggregated_text",
"_speak_text",
"_synthesize_text",
"_push_tts_frames",
)
if callable(getattr(cls, name, None))
)
return cls is not None and _matches(service, cls, methods)


def executing_client(service: Any, operation: str) -> tuple[bool, Any]:
for kind, module, name, methods, *store in _EXECUTIONS:
cls = _implementation(module, name)
if (
operation == kind
and _matches(service, cls, methods)
and (kind != "tts" or _tts_dispatch_matches(service, cls))
):
return True, vars(service).get(store[0] if store else "_client")
if operation == "stt" and all(
_matches(service, _implementation(module, name), methods)
for module, name, methods in (
("stt_service", "SegmentedSTTService", ("process_frame",)),
("whisper.base_stt", "BaseWhisperSTTService", ("run_stt",)),
("openai.stt", "OpenAISTTService", ("_transcribe",)),
)
):
return True, vars(service).get("_client")
for kind, module, name, *methods in _TRANSPORTS:
cls = _implementation(module, name)
if (
operation == kind
and _matches(service, cls, methods[0] if methods else ("process_frame", "run_" + kind))
and (kind != "tts" or _tts_dispatch_matches(service, cls))
):
return True, None
return False, None
74 changes: 74 additions & 0 deletions py/src/braintrust/integrations/pipecat/_model_clients.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Explicit execution ownership for application-defined Pipecat services."""

from typing import Any, Literal


ModelOperationKind = Literal["llm_response", "stt", "tts"]
_BINDINGS = "_braintrust_model_clients"

# These namespaces identify actual clients covered by Braintrust integrations,
# independently of whether those integrations are currently enabled.
_SDK_OPERATIONS = {
"openai": {"llm_response", "stt", "tts"},
"anthropic": {"llm_response"},
"google.genai": {"llm_response", "tts"},
"mistralai": {"llm_response", "stt", "tts"},
"cohere": {"llm_response", "stt"},
"huggingface_hub": {"llm_response"},
# Bedrock sessions: the Bedrock integration traces the clients they create.
"aiobotocore": {"llm_response"},
"aioboto3": {"llm_response"},
"botocore": {"llm_response"},
"boto3": {"llm_response"},
}


def set_model_client(service: Any, *, operation: ModelOperationKind, client: Any) -> None:
"""Declare the client that actually executes a custom service's operation.

Call before running the service. Pass the actual provider SDK client, or
``None`` when the service executes its own HTTP/WebSocket request. An unused
client or a client used only for configuration must not be bound here.

Built-in compatible services are detected automatically. A custom service
that overrides their execution path should bind its client explicitly;
Braintrust does not inspect application bytecode or guess dynamic dispatch.
A covered SDK retains ownership even when its integration is disabled.
Update the binding before an operation if the service switches clients.
"""
if operation not in {"llm_response", "stt", "tts"}:
raise ValueError(f"Unsupported Pipecat operation: {operation}")
bindings = dict(getattr(service, _BINDINGS, {}))
bindings[operation] = client
setattr(service, _BINDINGS, bindings)


def sdk_client_covers(client: Any, operation: str) -> bool:
return any(
operation in operations and (base.__module__ == namespace or base.__module__.startswith(namespace + "."))
for base in type(client).__mro__
for namespace, operations in _SDK_OPERATIONS.items()
)


def provider_client_expected(service: Any, operation: str) -> bool:
bindings = getattr(service, _BINDINGS, {})
if operation in bindings:
return sdk_client_covers(bindings[operation], operation)
from ._compat import executing_client

known, client = executing_client(service, operation)
if known:
return sdk_client_covers(client, operation)
# Guessing could duplicate billable usage from a disabled provider
# integration. Require an explicit binding for unknown execution paths.
if not getattr(service, "_braintrust_ownership_warning", False):
from .tracing._common import LOG

LOG.warning(
"Unknown Pipecat model execution path on %s; use "
"braintrust.integrations.pipecat.set_model_client() to enable ownership tracing",
type(service).__name__,
)
service._braintrust_ownership_warning = True
return True
Loading