Skip to content
Draft
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
15 changes: 13 additions & 2 deletions py/noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,14 +539,17 @@ def test_livekit_agents(session, version):
group = "test-livekit-agents" if version == LATEST else f"test-livekit-agents-{version.replace('.', '-')}"
_install_group_locked(session, group)
_install_matrix_dep(session, "livekit-agents", version)
_session_install(session, "-e", ".[voice]")
livekit_server_dir = _ensure_livekit_server(session)
env = {
"LIVEKIT_URL": os.environ.get("LIVEKIT_URL", "ws://localhost:7880"),
"LIVEKIT_API_KEY": os.environ.get("LIVEKIT_API_KEY", "devkey"),
"LIVEKIT_API_SECRET": os.environ.get("LIVEKIT_API_SECRET", "secret"),
"PATH": f"{livekit_server_dir}{os.pathsep}{os.environ.get('PATH', '')}",
}
_run_tests(session, f"{INTEGRATION_DIR}/livekit_agents", version=version, env=env)
_run_tests(
session, [f"{INTEGRATION_DIR}/livekit_agents", f"{SRC_DIR}/voice/test_livekit.py"], version=version, env=env
)


PIPECAT_VERSIONS = _get_matrix_versions("pipecat-ai")
Expand All @@ -563,7 +566,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,
)
Expand Down Expand Up @@ -917,6 +920,14 @@ def test_audio_codecs(session):
session.run("pytest", "src/braintrust/_audio/test_codec.py", *session.posargs)


@nox.session()
def test_voice(session):
_install_test_deps(session)
_install_group_locked(session, "test-voice")
_session_install(session, "-e", ".[voice]")
_run_tests(session, [f"{SRC_DIR}/voice/test_session.py", f"{SRC_DIR}/voice/test_call.py"])


# Not a default session: it needs a wheel from `make build`, so a bare `nox`
# (`make test`) must not pick it up.
@nox.session(default=False)
Expand Down
7 changes: 7 additions & 0 deletions py/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ braintrust = "braintrust.integrations.harbor:HarborPlugin"
# Install the qualified PyAV on Python 3.12+. Encoding detects PyAV/libopus
# capability at runtime, including PyAV installed by a voice framework.
audio = ["av==19.0.2; python_version>='3.12'"]
voice = ["websockets>=15,<16", "av==19.0.2; python_version>='3.12'"]
cli = ["boto3", "python-dotenv", "uv>=0.13.4", "starlette", "uvicorn"]
# TODO: remove the doc extra in the next major version.
doc = []
Expand All @@ -73,6 +74,7 @@ temporal = [
"temporalio>=1.19.0; python_version>='3.10'",
]
all = [
"websockets>=15,<16",
"av==19.0.2; python_version>='3.12'",
"boto3",
"openai-agents",
Expand Down Expand Up @@ -241,6 +243,11 @@ test-pipecat = [
"websockets==15.0.1",
]

test-voice = [
{include-group = "test"},
"aiohttp==3.14.5",
]

test-crewai = [
{include-group = "test"},
# CrewAI's no-network smoke test forces the LiteLLM fallback path via
Expand Down
103 changes: 103 additions & 0 deletions py/src/braintrust/voice/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Voice evals

`voice_task` runs a fresh voice call for each eval row. The SDK manages the simulator connection, audio pacing, interruptions, tracing, recordings, and cleanup. It supports a Pipecat agent in the eval process or another service, and a built-in LiveKit connector.

Install `braintrust[voice]` and your agent framework. Audio conversion uses PyAV, included in the extra on Python 3.12 and later. Configure the normal Braintrust credentials and deployment URL. The helpers require data plane feature version 149 and an enabled voice session service.

## Pipecat

Adapt your existing agent entrypoint to accept a native Pipecat transport. Construct and run the pipeline inside `voice.connect`, so the existing Braintrust instrumentation inherits the eval's parent.

```python
from braintrust import voice


async def run_eval_call(call):
async with voice.connect(call) as session:
agent_output = await run_agent(
transport=session.pipecat_transport(),
)
return session.result(agent_output=agent_output)
```

`run_agent` is your application's existing pipeline runner. Place `transport.input()` and `transport.output()` at the pipeline's input and output, enable your normal Braintrust Pipecat instrumentation, and return your application's observed result. Neither audio frames nor playback acknowledgements belong in the eval script.

Use that handler directly for a local agent:

```python
from braintrust import Eval
from braintrust.voice import SimulatedUser, voice_task


def transferred_correctly(output, expected):
return float(output["agent_output"]["transferred_to"] == expected)


Eval(
"Voice evals",
data=[
{
"input": {"request": "Ask to speak with billing"},
"expected": "billing",
}
],
task=voice_task(
agent=run_eval_call,
simulated_user=SimulatedUser(
name="Billing caller",
instructions="You are calling support. {{request}}. Finish after the transfer.",
),
),
scores=[transferred_correctly],
max_concurrency=1,
)
```

For a remote agent, the connector forwards the call context to your authenticated service and awaits the handler's result:

```python
async def connect_agent(call):
return await agent_service.run_eval_call(call)
```

The context is a plain JSON object containing single-use connection credentials and an exported tracing parent. Forward it securely and do not log it. The receiving service runs the same `run_eval_call` handler with its own Braintrust credentials. The connector must await completion and propagate errors, rather than returning a job ID or an initial acknowledgement.

## LiveKit

On the eval side, replace the callback with a built-in connector:

```python
import os

from braintrust.voice import LiveKitAgent

agent = LiveKitAgent(
server_url=os.environ["LIVEKIT_URL"],
agent_name="support-agent",
)
```

Pass `agent` to `voice_task`. The connector reads `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET`, joins a fresh room, and dispatches the named agent.

In the existing LiveKit entrypoint, enable the normal Braintrust instrumentation and wrap the call session after joining the room:

```python
async def handle_call(ctx):
await ctx.connect()
session = create_agent_session()
async with voice.livekit_agent(session, ctx.room) as call:
await run_existing_call(session, ctx.room)
call.agent_output = get_call_result()
```

`create_agent_session`, `run_existing_call`, and `get_call_result` represent your existing application logic. The helper reads the caller's parent, keeps it active during the call, closes the session, flushes the trace, and reports the actual result or failure back to the eval. Calls without a voice-eval participant retain their existing tracing behavior. Closing the LiveKit room belongs outside this context so the completion message can be delivered.

## Results and custom tasks

`session.result()` returns `agent_output`, `caller_transcript`, `recording`, `reason`, `session_id`, and `span_id`. `agent_output` is `None` unless the application supplies a result. The transcript contains only simulated caller speech. The recording contains both participants, with attachment references and timeline metadata in the existing segmented audio schema.

Use `SimulatedUserRef(id=...)` or `SimulatedUserRef(name=...)` to reuse a saved caller. A name must resolve to exactly one caller. Inline definitions do not create saved callers.

Use `await run_voice_call(agent=..., simulated_user=..., scenario=input)` inside a custom task. Both helpers infer the project and tracing parent from the active SDK context. Outside an eval or project logger, supply `project_id`. Only the scenario is sent to the caller; expected output stays with the eval's scorers.

Timeouts, missing terminal events, agent failures, recording failures, and unexpected disconnects fail the call. Established calls are never reconnected or replayed automatically.
16 changes: 16 additions & 0 deletions py/src/braintrust/voice/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Voice evals with managed audio transports and distributed tracing.

Install braintrust[voice], plus your agent framework. Use voice_task in an Eval,
forward its call context to the agent, and use connect(call) in that process.
"""

from ._call import run_voice_call as run_voice_call
from ._call import voice_task as voice_task
from ._livekit import livekit_agent as livekit_agent
from ._session import VoiceSession as VoiceSession
from ._session import connect as connect
from ._types import LiveKitAgent as LiveKitAgent
from ._types import SimulatedUser as SimulatedUser
from ._types import SimulatedUserRef as SimulatedUserRef
from ._types import VoiceCall as VoiceCall
from ._types import VoiceCallResult as VoiceCallResult
182 changes: 182 additions & 0 deletions py/src/braintrust/voice/_call.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import asyncio
import dataclasses
import importlib
from collections.abc import Awaitable, Callable
from urllib.parse import quote

import jsonschema

from .. import logger
from ..span_identifier_v3 import SpanObjectTypeV3
from ..span_identifier_v4 import SpanComponentsV4
from ..span_types import SpanTypeAttribute
from ..util import response_raise_for_status
from ._types import (
AgentConnector,
Caller,
Initiator,
JSONValue,
LiveKitAgent,
SimulatedUser,
VoiceCall,
VoiceCallResult,
parse_result,
)


MIN_FF_VERSION = 149


def _project_id(parent: str, project_id: str | None, state: logger.BraintrustState) -> str:
if project_id:
return project_id
components = SpanComponentsV4.from_str(parent)
if components.object_type == SpanObjectTypeV3.PROJECT_LOGS and components.object_id:
return components.object_id
if components.object_type == SpanObjectTypeV3.EXPERIMENT and components.object_id:
experiment = state.current_experiment
if experiment is not None and experiment.id == components.object_id:
return experiment.project.id
response = state.api_conn().get_json(f"v1/experiment/{quote(components.object_id, safe='')}")
value = response.get("project_id")
if isinstance(value, str):
return value
raise ValueError("Pass project_id or run the voice call inside an Eval or project logger")


def _create_call(
caller: Caller,
scenario: dict[str, JSONValue],
initiator: Initiator,
timeout: int,
project_id: str | None,
parent: str,
state: logger.BraintrustState,
) -> VoiceCall:
state.login()
version = state.api_conn().get_json("version").get("ff_version")
if not isinstance(version, int) or version < MIN_FF_VERSION:
raise RuntimeError(f"Voice eval helpers require data plane feature version {MIN_FF_VERSION} or later")
components = SpanComponentsV4.from_str(parent)
if components.compute_object_metadata_args and components.object_type == SpanObjectTypeV3.PROJECT_LOGS:
metadata = logger._compute_logger_metadata(state=state, **components.compute_object_metadata_args)
parent = dataclasses.replace(
components, object_id=metadata.project.id, compute_object_metadata_args=None
).to_str()
project_id = _project_id(parent, project_id, state)
if isinstance(caller, SimulatedUser):
definition = {k: v for k, v in dataclasses.asdict(caller).items() if v is not None}
else:
caller_id = caller.id
if caller_id is None:
response = state.api_conn().get_json(
f"v1/project/{quote(project_id, safe='')}/simulated_user",
{"simulated_user_name": caller.name, "limit": 2},
)
matches = response.get("objects")
if not isinstance(matches, list) or len(matches) != 1:
raise ValueError(
f"Expected exactly one simulated user named {caller.name!r}; use an ID to disambiguate"
)
caller_id = matches[0]["id"]
definition = {"id": caller_id}
response = state.api_conn().post(
f"v1/project/{quote(project_id, safe='')}/voice_session",
json={
"simulated_user": definition,
"scenario": scenario,
"initiator": initiator,
"parent": parent,
"timeout_seconds": timeout,
},
timeout=60,
)
response_raise_for_status(response)
handle = response.json()
return VoiceCall(
connection_url=handle["connection_url"],
session_token=handle["session_token"],
expires_at=handle["expires_at"],
session_id=handle["session_id"],
span_id=handle["span_id"],
parent=parent,
timeout_seconds=timeout,
)


async def run_voice_call(
*,
agent: AgentConnector | LiveKitAgent,
simulated_user: Caller,
scenario: dict[str, JSONValue],
initiator: Initiator = "agent",
timeout: int = 600,
project_id: str | None = None,
parent: str | None = None,
state: logger.BraintrustState | None = None,
) -> VoiceCallResult:
"""Run one fresh call. The connector must await completion and return session.result()."""
if type(timeout) is not int or not 15 <= timeout <= 600:
raise ValueError("timeout must be an integer between 15 and 600 seconds")
if initiator not in ("agent", "simulated_user"):
raise ValueError("initiator must be agent or simulated_user")
if isinstance(agent, LiveKitAgent):
from ._livekit import credentials

importlib.import_module("livekit.api")
importlib.import_module("livekit.rtc")
credentials(agent)
elif not callable(agent):
raise TypeError("agent must be an async call connector or LiveKitAgent")
if state is None:
state = logger._internal_get_global_state()
if parent is None and project_id and not logger.get_span_parent_object(state=state).export():
parent = logger.init_logger(project_id=project_id, state=state, set_current=False).export()
with logger.start_span(name="Voice call", type=SpanTypeAttribute.TASK, parent=parent, state=state) as span:
call = await asyncio.to_thread(
_create_call, simulated_user, scenario, initiator, timeout, project_id, span.export(), state
)
span.log(
input=scenario, metadata={"voice_session_id": call["session_id"], "simulator_span_id": call["span_id"]}
)
if isinstance(agent, LiveKitAgent):
from ._livekit import run_livekit

result = await asyncio.wait_for(run_livekit(call, agent), timeout + 150)
else:
result = await asyncio.wait_for(agent(call), timeout + 150)
try:
result = parse_result(result)
except (jsonschema.ValidationError, TypeError, ValueError):
raise ValueError(
"connect_agent must return the completed session.result(), not a job or call-start response"
) from None
if result["session_id"] != call["session_id"]:
raise ValueError(
"connect_agent must return the completed session.result(), not a job or call-start response"
)
span.log(output=result)
return result


def voice_task(
*,
agent: AgentConnector | LiveKitAgent,
simulated_user: Caller,
initiator: Initiator = "agent",
timeout: int = 600,
project_id: str | None = None,
) -> Callable[[dict[str, JSONValue]], Awaitable[VoiceCallResult]]:
"""Create an async task for Eval or EvalAsync. Only input becomes the caller's scenario."""

async def task(input: dict[str, JSONValue]) -> VoiceCallResult:
return await run_voice_call(
agent=agent,
simulated_user=simulated_user,
scenario=input,
initiator=initiator,
timeout=timeout,
project_id=project_id,
)

return task
Loading
Loading