diff --git a/py/noxfile.py b/py/noxfile.py index 192d6430..7156b7ef 100644 --- a/py/noxfile.py +++ b/py/noxfile.py @@ -563,7 +563,7 @@ def test_pipecat(session, version): # loaded from Nox's virtualenv when it is beneath the current directory. _run_tests( session, - f"{INTEGRATION_DIR}/pipecat/test_pipecat.py", + [f"{INTEGRATION_DIR}/pipecat/test_pipecat.py", f"{SRC_DIR}/voice/test_pipecat.py"], version=version, run_from_temp_dir=True, ) diff --git a/py/src/braintrust/voice/README.md b/py/src/braintrust/voice/README.md index 43b0372f..e18dadf9 100644 --- a/py/src/braintrust/voice/README.md +++ b/py/src/braintrust/voice/README.md @@ -64,3 +64,20 @@ The SDK owns the WebSocket handshake, pacing, playback acknowledgements, interru Use `await run_voice_call(agent=..., simulated_user_id=..., input=input)` in a custom eval task. Both helpers require an active eval task; the project is inferred from its experiment, or supplied explicitly as `project_id`. Expected output and scorer configuration stay in the eval. Calls retain the backend's ten-minute limit. Missing terminal events, agent or recording errors, cancellation, and unexpected disconnects fail the call. Established calls are never reconnected or replayed automatically. + +## Pipecat + +Install your supported `pipecat-ai` version alongside `braintrust[voice]`, then pass the native transport to your existing pipeline runner: + +```python +from braintrust import voice +from braintrust.voice.pipecat import PipecatTransport + + +async def run_eval_call(call): + async with voice.connect(call) as session: + output = await run_agent(transport=PipecatTransport(session)) + return session.result(agent_output=output) +``` + +Place `transport.input()` and `transport.output()` at the pipeline's input and output. Construct the pipeline inside `voice.connect` and enable your normal Braintrust Pipecat instrumentation. The transport connects audio, handles interrupted playback, signals `EndFrame` on call completion, and propagates `ErrorFrame` failures through the awaited runner. Application code supplies its existing agent runner and observed output. diff --git a/py/src/braintrust/voice/pipecat.py b/py/src/braintrust/voice/pipecat.py new file mode 100644 index 00000000..6104e19d --- /dev/null +++ b/py/src/braintrust/voice/pipecat.py @@ -0,0 +1,110 @@ +import asyncio +from dataclasses import dataclass, field + +from pipecat.frames.frames import ( + CancelFrame, + EndFrame, + ErrorFrame, + Frame, + InputAudioRawFrame, + InterruptionFrame, + OutputAudioRawFrame, + StartFrame, +) +from pipecat.processors.frame_processor import FrameDirection +from pipecat.transports.base_input import BaseInputTransport +from pipecat.transports.base_output import BaseOutputTransport +from pipecat.transports.base_transport import BaseTransport, TransportParams + +from ._session import VoiceSession + + +@dataclass +class _CallerAudio(InputAudioRawFrame): + consumed: asyncio.Future[None] | None = field(default=None, repr=False) + epoch: int = 0 + + +class _Input(BaseInputTransport): + def __init__(self, session: VoiceSession, params: TransportParams): + super().__init__(params) + self._voice = session + self._epoch = 0 + + async def start(self, frame: StartFrame): + await super().start(frame) + await self.set_transport_ready(frame) + + async def consume(audio: bytes): + consumed = asyncio.get_running_loop().create_future() + await self.push_audio_frame( + _CallerAudio(audio=audio, sample_rate=24000, num_channels=1, consumed=consumed, epoch=self._epoch) + ) + await consumed + + async def clear(): + self._epoch += 1 + + async def ended(): + await self.push_frame(EndFrame()) + + self._voice.set_audio_sink(consume, clear=clear, ended=ended) + + async def push_frame(self, frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM): + if not isinstance(frame, _CallerAudio) or frame.epoch == self._epoch: + await super().push_frame(frame, direction) + if isinstance(frame, _CallerAudio) and frame.consumed is not None and not frame.consumed.done(): + frame.consumed.set_result(None) + + async def process_frame(self, frame: Frame, direction: FrameDirection): + if isinstance(frame, ErrorFrame): + await self._voice.fail(RuntimeError(frame.error)) + await super().process_frame(frame, direction) + + +class _Output(BaseOutputTransport): + def __init__(self, session: VoiceSession, params: TransportParams): + super().__init__(params) + self._voice = session + + async def start(self, frame: StartFrame): + await super().start(frame) + await self.set_transport_ready(frame) + + async def write_audio_frame(self, frame: OutputAudioRawFrame): + try: + await self._voice.send_audio(frame.audio, frame.sample_rate, frame.num_channels) + return True + except Exception as error: + await self._voice.fail(error) + raise + + async def process_frame(self, frame: Frame, direction: FrameDirection): + if isinstance(frame, (InterruptionFrame, CancelFrame)): + self._voice.clear_output() + if isinstance(frame, ErrorFrame): + await self._voice.fail(RuntimeError(frame.error)) + await super().process_frame(frame, direction) + + +class PipecatTransport(BaseTransport): + """Native input/output processors for a managed voice eval session.""" + + def __init__(self, session: VoiceSession): + super().__init__() + params = TransportParams( + audio_in_enabled=True, + audio_out_enabled=True, + audio_in_sample_rate=24000, + audio_out_sample_rate=24000, + audio_out_channels=1, + audio_out_end_silence_secs=0, + ) + self._input = _Input(session, params) + self._output = _Output(session, params) + + def input(self) -> BaseInputTransport: + return self._input + + def output(self) -> BaseOutputTransport: + return self._output diff --git a/py/src/braintrust/voice/test_pipecat.py b/py/src/braintrust/voice/test_pipecat.py new file mode 100644 index 00000000..d22ea079 --- /dev/null +++ b/py/src/braintrust/voice/test_pipecat.py @@ -0,0 +1,96 @@ +import asyncio +import inspect +import json +import struct + +import pytest +from braintrust import logger +from braintrust.voice import connect +from braintrust.voice.test_session import simulator, terminal +from braintrust.voice.test_session import tracing as tracing + + +pytest.importorskip("pipecat") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("agent_error", [False, True]) +async def test_real_pipecat_pipeline_consumes_audio_and_reports_failures(tracing, agent_error): + # A native pipeline must exchange audio and surface ErrorFrames through the managed session. + from braintrust.voice.pipecat import PipecatTransport + from pipecat.frames.frames import ErrorFrame, InputAudioRawFrame, OutputAudioRawFrame + from pipecat.pipeline.pipeline import Pipeline + from pipecat.pipeline.worker import PipelineWorker + from pipecat.processors.frame_processor import FrameDirection, FrameProcessor + from pipecat.workers.runner import WorkerRunner + + wire_audio = [] + acknowledgements = [] + + class Echo(FrameProcessor): + async def process_frame(self, frame, direction): + await super().process_frame(frame, direction) + if isinstance(frame, InputAudioRawFrame): + if agent_error: + await self.push_frame(ErrorFrame(error="Agent failed", fatal=True), FrameDirection.UPSTREAM) + else: + await self.push_frame( + OutputAudioRawFrame(audio=frame.audio, sample_rate=frame.sample_rate, num_channels=1) + ) + else: + await self.push_frame(frame, direction) + + async def handler(socket): + await socket.send(struct.pack("<480h", *([100] * 480))) + if not agent_error: + await socket.send(json.dumps({"type": "audio.clear", "epoch": 1})) + await socket.send(struct.pack("<480h", *([200] * 480))) + finished = False + async for message in socket: + if isinstance(message, bytes): + wire_audio.append(message) + if any(message) and not finished: + finished = True + await socket.send(json.dumps(terminal())) + else: + event = json.loads(message) + if event["type"] == "playback.ack": + acknowledgements.append(event) + if event["type"] == "stop": + await socket.send(json.dumps(terminal())) + return + + async def run(call): + async with connect(call) as session: + transport = PipecatTransport(session) + pipeline = Pipeline([transport.input(), Echo(), transport.output()]) + options = {"enable_turn_tracking": False, "enable_rtvi": False, "check_dangling_tasks": False} + worker = PipelineWorker( + pipeline, + idle_timeout_secs=None, + **{ + key: value for key, value in options.items() if key in inspect.signature(PipelineWorker).parameters + }, + ) + runner = WorkerRunner( + handle_sigint=False, + **{ + key: value + for key, value in options.items() + if key == "check_dangling_tasks" and key in inspect.signature(WorkerRunner).parameters + }, + ) + await runner.add_workers(worker) + await asyncio.wait_for(runner.run(), 5) + return session.result() + + with logger.start_span(name="Task") as parent: + async with simulator(handler, parent.export()) as call: + if agent_error: + with pytest.raises(RuntimeError, match="Agent failed"): + await run(call) + else: + result = await run(call) + assert result["reason"] == "Client stopped session" + assert any(any(audio) for audio in wire_audio) + assert all(event["epoch"] == 1 for event in acknowledgements)