diff --git a/py/src/braintrust/integrations/auto_test_scripts/test_auto_openai.py b/py/src/braintrust/integrations/auto_test_scripts/test_auto_openai.py index 4db87dfed..8a26fa3ec 100644 --- a/py/src/braintrust/integrations/auto_test_scripts/test_auto_openai.py +++ b/py/src/braintrust/integrations/auto_test_scripts/test_auto_openai.py @@ -101,4 +101,29 @@ def _is_braintrust_wrapped(resource) -> bool: instrumentation="openai-auto", ) + +# Binary streaming uses the same natural provider span after auto + manual +# wrapping, without consuming audio ahead of the application. +with autoinstrument_test_context("test_openai_audio_speech_capture", integration="openai") as memory_logger: + client = wrap_openai(openai.OpenAI()) + with client.audio.speech.with_streaming_response.create( + model="tts-1", + voice="alloy", + input="Hi.", + response_format="wav", + span_info={"name": "custom speech", "metadata": {"request_tag": "auto-speech-test"}}, + ) as response: + assert b"".join(response.iter_bytes()).startswith(b"RIFF") + (span,) = memory_logger.pop() + assert span["span_attributes"]["name"] == "custom speech" + assert span["metadata"] == {"model": "tts-1", "provider": "openai", "request_tag": "auto-speech-test"} + assert span["span_attributes"]["type"] == "llm" + assert span["context"]["span_origin"]["instrumentation"]["name"] == "openai-auto" + assert span["input"] == { + "operation": "speech", + "prompt": "Hi.", + "parameters": {"voice": "alloy", "format": "wav"}, + } + assert "end" in span["metrics"] + print("SUCCESS") diff --git a/py/src/braintrust/integrations/openai/_speech.py b/py/src/braintrust/integrations/openai/_speech.py new file mode 100644 index 000000000..88231503e --- /dev/null +++ b/py/src/braintrust/integrations/openai/_speech.py @@ -0,0 +1,301 @@ +"""Observe binary speech responses without consuming application audio.""" + +import time +import weakref +from email.message import Message +from typing import Any + +from braintrust.env import BraintrustEnv +from braintrust.integrations.utils import ( + _infer_audio_mime_type, + _is_not_given, + _log_error_and_end_span, + _materialize_attachment, +) +from braintrust.logger import NOOP_SPAN +from wrapt import ObjectProxy + + +def speech_input(params: dict[str, Any]) -> dict[str, Any]: + parameters = { + target: params[source] + for source, target in ( + ("voice", "voice"), + ("response_format", "format"), + ("speed", "speed"), + ("language", "language"), + ("instructions", "instructions"), + ) + if source in params and params[source] is not None and not _is_not_given(params[source]) + } + return { + "operation": "speech", + "prompt": params.get("input"), + **({"parameters": parameters} if parameters else {}), + } + + +# Default attachment extensions for OpenAI speech response formats. Kept local +# because mimetypes lacks wav/pcm on some platforms. +_SPEECH_EXTENSIONS = { + "audio/wav": "wav", + "audio/mpeg": "mp3", + "audio/pcm": "pcm", + "audio/opus": "opus", + "audio/aac": "aac", + "audio/flac": "flac", +} + + +def _response_headers(response: Any) -> Any: + # Streaming APIResponse exposes headers directly; the non-streaming + # HttpxBinaryResponseContent keeps them on its httpx response. + headers = getattr(response, "headers", None) + return headers if headers is not None else getattr(getattr(response, "response", None), "headers", None) + + +def speech_mime_type(response: Any, response_format: Any = None) -> str: + headers = _response_headers(response) + content_type = headers.get("content-type") if headers is not None else None + if isinstance(content_type, str) and content_type: + return content_type.split(";", 1)[0].strip() + return _infer_audio_mime_type(None, response_format) + + +def speech_filename(response: Any) -> str | None: + headers = _response_headers(response) + disposition = headers.get("content-disposition") if headers is not None else None + if not disposition: + return None + message = Message() + message["Content-Disposition"] = disposition + return message.get_filename() + + +def speech_output(data: bytes, mime_type: str, filename: str | None = None) -> dict[str, Any]: + if data and BraintrustEnv.CAPTURE_AGENT_AUDIO_ATTACHMENTS.get(False): + resolved = _materialize_attachment( + data, + mime_type=mime_type, + filename=filename or f"speech.{_SPEECH_EXTENSIONS.get(mime_type, 'bin')}", + ) + if resolved is not None: + return { + "content": [ + { + "type": "file", + "file": { + "filename": resolved.filename, + "file_data": resolved.attachment, + "byte_size": len(data), + }, + } + ] + } + return {"content": []} + + +class _SpeechTrace: + def __init__(self, span, response, response_format, started): + self.span = span + self.mime_type = speech_mime_type(response, response_format) + self.filename = speech_filename(response) + self.started = started + self.first_content = False + self.finished = False + # Chunks are kept by reference and joined once at EOF. + self.chunks: list[bytes] = [] + self.capture = span is not NOOP_SPAN and BraintrustEnv.CAPTURE_AGENT_AUDIO_ATTACHMENTS.get(False) + + def _mark_first_content(self): + if not self.first_content: + self.first_content = True + self.span.log(metrics={"time_to_first_token": time.monotonic() - self.started}) + + def observe(self, chunk, *, audio=True): + """Record a consumed chunk; ``audio=False`` marks decoded text chunks, + which count toward timing but cannot be captured as audio bytes.""" + if self.finished or not chunk: + return + self._mark_first_content() + if not audio: + self.capture = False + self.chunks.clear() + elif self.capture: + self.chunks.append(chunk) + + def complete(self, data): + """Finish from a whole-body read, logging ``data`` without buffering it.""" + if self.finished: + return + if data: + self._mark_first_content() + self.finish(complete=True, data=data if self.capture else b"") + + def finish(self, error=None, *, complete=False, data=None): + if self.finished: + return + self.finished = True + if error is not None and not isinstance(error, GeneratorExit): + self.span.log(error=error) + if not complete: + data = b"" + elif data is None: + data = b"".join(self.chunks) + self.span.log(output=speech_output(data, self.mime_type, self.filename)) + self.chunks.clear() + self.span.end() + + +def _observe_iter(trace, iterator, *, audio=True): + try: + for chunk in iterator: + trace.observe(chunk, audio=audio) + yield chunk + except BaseException as exc: + trace.finish(exc) + raise + else: + trace.finish(complete=True) + + +async def _aobserve_iter(trace, iterator, *, audio=True): + try: + async for chunk in iterator: + trace.observe(chunk, audio=audio) + yield chunk + except BaseException as exc: + trace.finish(exc) + raise + else: + trace.finish(complete=True) + + +class SpeechResponse(ObjectProxy): + def __init__(self, response, trace): + super().__init__(response) + self._self_trace = trace + # The finalizer retains only trace state, never the response/proxy. + weakref.finalize(self, trace.finish) + + def iter_bytes(self, *args, **kwargs): + return _observe_iter(self._self_trace, self.__wrapped__.iter_bytes(*args, **kwargs)) + + def iter_text(self, *args, **kwargs): + return _observe_iter(self._self_trace, self.__wrapped__.iter_text(*args, **kwargs), audio=False) + + def iter_lines(self, *args, **kwargs): + return _observe_iter(self._self_trace, self.__wrapped__.iter_lines(*args, **kwargs), audio=False) + + def read(self): + try: + data = self.__wrapped__.read() + except BaseException as exc: + self._self_trace.finish(exc) + raise + self._self_trace.complete(data) + return data + + # Run these SDK methods with this proxy as self, so their internal + # read()/iter_bytes() calls go through the observation above while the + # provider's type and cache behavior is preserved. + def parse(self, *args, **kwargs): + return type(self.__wrapped__).parse(self, *args, **kwargs) + + def text(self, *args, **kwargs): + return type(self.__wrapped__).text(self, *args, **kwargs) + + def json(self, *args, **kwargs): + return type(self.__wrapped__).json(self, *args, **kwargs) + + def stream_to_file(self, *args, **kwargs): + return type(self.__wrapped__).stream_to_file(self, *args, **kwargs) + + def close(self): + try: + return self.__wrapped__.close() + finally: + self._self_trace.finish() + + +class AsyncSpeechResponse(ObjectProxy): + def __init__(self, response, trace): + super().__init__(response) + self._self_trace = trace + weakref.finalize(self, trace.finish) + + def iter_bytes(self, *args, **kwargs): + return _aobserve_iter(self._self_trace, self.__wrapped__.iter_bytes(*args, **kwargs)) + + def iter_text(self, *args, **kwargs): + return _aobserve_iter(self._self_trace, self.__wrapped__.iter_text(*args, **kwargs), audio=False) + + def iter_lines(self, *args, **kwargs): + return _aobserve_iter(self._self_trace, self.__wrapped__.iter_lines(*args, **kwargs), audio=False) + + async def read(self): + try: + data = await self.__wrapped__.read() + except BaseException as exc: + self._self_trace.finish(exc) + raise + self._self_trace.complete(data) + return data + + async def parse(self, *args, **kwargs): + return await type(self.__wrapped__).parse(self, *args, **kwargs) + + async def text(self, *args, **kwargs): + return await type(self.__wrapped__).text(self, *args, **kwargs) + + async def json(self, *args, **kwargs): + return await type(self.__wrapped__).json(self, *args, **kwargs) + + async def stream_to_file(self, *args, **kwargs): + return await type(self.__wrapped__).stream_to_file(self, *args, **kwargs) + + async def close(self): + try: + return await self.__wrapped__.close() + finally: + self._self_trace.finish() + + +def trace_stream(wrapped, args, kwargs, *, is_async, start_span, log_headers, params): + """Trace a ``with_streaming_response`` speech request until its body is consumed. + + The sync SDK calls this only when the response context is entered. The async + SDK calls it when ``create()`` is called, but the returned coroutine only runs + on ``__aenter__``, so the async span is started inside that coroutine. + + ``tracing`` passes its ``start_span`` (which tags the OpenAI instrumentation) + and ``log_headers``; importing them here would be circular. + """ + response_format = kwargs.get("response_format") + + def start(): + return start_span(**{"name": "Speech", "type": "llm", "set_current": False, **params}), time.monotonic() + + def traced(span, response, started): + log_headers(response, span) + return _SpeechTrace(span, response, response_format, started) + + if is_async: + + async def call(): + span, started = start() + try: + response = await wrapped(*args, **kwargs) + except BaseException as exc: + _log_error_and_end_span(span, exc) + raise + return AsyncSpeechResponse(response, traced(span, response, started)) + + return call() + span, started = start() + try: + response = wrapped(*args, **kwargs) + except BaseException as exc: + _log_error_and_end_span(span, exc) + raise + return SpeechResponse(response, traced(span, response, started)) diff --git a/py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[async].yaml b/py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[async].yaml new file mode 100644 index 000000000..2412bfe42 --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[async].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"input":"Hi.","model":"tts-1","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - AsyncOpenAI/Python 1.71.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - async:asyncio + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 1.71.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2bde2d49ab99-YYZ + connection: + - keep-alive + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:39 GMT + openai-processing-ms: + - '207' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + transfer-encoding: + - chunked + vary: + - Origin + via: + - envoy-router-7dfdf96b94-jgw6t + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_be6c97ec8fc545d19f2a8f6527dc1a1b + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[sync].yaml b/py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[sync].yaml new file mode 100644 index 000000000..22c2c4b03 --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[sync].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"input":"Hi.","model":"tts-1","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - OpenAI/Python 1.71.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - 'false' + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 1.71.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2bdafb97aaee-YYZ + connection: + - keep-alive + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:38 GMT + openai-processing-ms: + - '141' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + transfer-encoding: + - chunked + vary: + - Origin + via: + - envoy-router-99fc5859-49v2n + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_989c199b4e2445089a33871f9a406f95 + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[async].yaml b/py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[async].yaml new file mode 100644 index 000000000..cc841939a --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[async].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"input":"Hi.","model":"tts-1","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - AsyncOpenAI/Python 1.77.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - async:asyncio + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 1.77.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2bbada3cec72-YYZ + connection: + - keep-alive + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:33 GMT + openai-processing-ms: + - '64' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + transfer-encoding: + - chunked + vary: + - Origin + via: + - envoy-router-74fd9bf8c6-jmthb + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_07491d5a12044e58b20d5dd4c092bbe4 + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[sync].yaml b/py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[sync].yaml new file mode 100644 index 000000000..4b588904d --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[sync].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"input":"Hi.","model":"tts-1","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - OpenAI/Python 1.77.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - 'false' + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 1.77.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2bb86e65aa96-YYZ + connection: + - keep-alive + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:33 GMT + openai-processing-ms: + - '129' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + transfer-encoding: + - chunked + vary: + - Origin + via: + - envoy-router-766b86cd44-k64lx + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_1c0a35bad19942128bfe5460c56c8f28 + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[async].yaml b/py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[async].yaml new file mode 100644 index 000000000..b38e34431 --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[async].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"input":"Hi.","model":"tts-1","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - AsyncOpenAI/Python 1.92.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - async:asyncio + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 1.92.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2b93ce36a22f-YYZ + connection: + - keep-alive + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:28 GMT + openai-processing-ms: + - '166' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + transfer-encoding: + - chunked + vary: + - Origin + via: + - envoy-router-755f8bff66-4flbq + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_0faf8eb634aa48188a9d2a9fd68bea16 + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[sync].yaml b/py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[sync].yaml new file mode 100644 index 000000000..c7687e775 --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[sync].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"input":"Hi.","model":"tts-1","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - OpenAI/Python 1.92.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - 'false' + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 1.92.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2b911c28d92c-YYZ + connection: + - keep-alive + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:27 GMT + openai-processing-ms: + - '122' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + transfer-encoding: + - chunked + vary: + - Origin + via: + - envoy-router-6b6cf984cb-bsb2t + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_0cf3f7433e7847ffa594a860f0315f66 + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[async].yaml b/py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[async].yaml new file mode 100644 index 000000000..a7be5fe05 --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[async].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"model":"tts-1","input":"Hi.","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate, zstd + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - AsyncOpenAI/Python 3.51.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - async:asyncio + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 3.51.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2b6eff7f5577-YYZ + connection: + - keep-alive + content-length: + - '366' + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:21 GMT + openai-processing-ms: + - '49' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + vary: + - Origin + via: + - envoy-router-766b86cd44-k64lx + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_613cd4ce1b1e4a54b8c854545cad55ce + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[sync].yaml b/py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[sync].yaml new file mode 100644 index 000000000..63afc1db8 --- /dev/null +++ b/py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[sync].yaml @@ -0,0 +1,93 @@ +interactions: +- request: + body: '{"model":"tts-1","input":"Hi.","voice":"not-a-voice","response_format":"wav"}' + headers: + accept: + - application/octet-stream + accept-encoding: + - gzip, deflate, zstd + connection: + - keep-alive + content-length: + - '77' + content-type: + - application/json + host: + - api.openai.com + user-agent: + - OpenAI/Python 3.51.0 + x-stainless-arch: + - arm64 + x-stainless-async: + - 'false' + x-stainless-lang: + - python + x-stainless-os: + - MacOS + x-stainless-package-version: + - 3.51.0 + x-stainless-raw-response: + - stream + x-stainless-read-timeout: + - '600' + x-stainless-retry-count: + - '0' + x-stainless-runtime: + - CPython + x-stainless-runtime-version: + - 3.14.7 + method: POST + uri: https://api.openai.com/v1/audio/speech + response: + body: + string: "{\n \"error\": {\n \"message\": \"[{'type': 'enum', 'loc': ('body', + 'voice'), 'msg': \\\"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable', + 'alloy', 'ash', 'sage' or 'coral'\\\", 'ctx': {'expected': \\\"'nova', 'shimmer', + 'echo', 'onyx', 'fable', 'alloy', 'ash', 'sage' or 'coral'\\\"}}]\",\n \"type\": + \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}" + headers: + access-control-expose-headers: + - X-Request-ID + - CF-Ray + alt-svc: + - h3=":443"; ma=86400 + cf-cache-status: + - DYNAMIC + cf-ray: + - a5fa2b6a0dcfe720-YYZ + connection: + - keep-alive + content-type: + - application/json + date: + - Tue, 24 Nov 2026 17:35:21 GMT + openai-processing-ms: + - '58' + openai-version: + - '2020-10-01' + server: + - cloudflare + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + transfer-encoding: + - chunked + vary: + - Origin + via: + - envoy-router-99fc5859-rn8zj + x-content-type-options: + - nosniff + x-openai-proxy-wasm: + - v0.1 + x-ratelimit-limit-requests: + - '10000' + x-ratelimit-remaining-requests: + - '9999' + x-ratelimit-reset-requests: + - 6ms + x-request-id: + - req_a6dc07bd0b5f47389741f9f7c619c134 + status: + code: 400 + message: Bad Request +version: 1 diff --git a/py/src/braintrust/integrations/openai/test_openai.py b/py/src/braintrust/integrations/openai/test_openai.py index b9d2e17ac..19f71ee3e 100644 --- a/py/src/braintrust/integrations/openai/test_openai.py +++ b/py/src/braintrust/integrations/openai/test_openai.py @@ -2206,22 +2206,230 @@ async def test_openai_audio_speech_capture(memory_logger, monkeypatch, is_async, monkeypatch.setenv("BRAINTRUST_CAPTURE_USER_AUDIO_ATTACHMENTS", str(not capture).lower()) client = wrap_openai(_client(is_async)) response = await _call( - is_async, client.audio.speech.create, model="tts-1", voice="alloy", input="Hi.", response_format="wav" + is_async, + client.audio.speech.create, + model="tts-1", + voice="alloy", + input="Hi.", + response_format="wav", + span_info={"name": "custom speech", "metadata": {"request_tag": "speech-test"}}, ) assert response.content.startswith(b"RIFF") memory_logger.flush() (span,) = memory_logger.pop() - assert span["input"] == "Hi." + assert span["span_attributes"]["name"] == "custom speech" + assert span["metadata"] == {"model": "tts-1", "provider": "openai", "request_tag": "speech-test"} + assert span["input"] == {"operation": "speech", "prompt": "Hi.", "parameters": {"voice": "alloy", "format": "wav"}} if capture: - attachment = span["output"]["file"]["file_data"] + attachment = span["output"]["content"][0]["file"]["file_data"] assert attachment["type"] == "braintrust_attachment" assert attachment["content_type"].startswith("audio/") assert len(memory_logger.upload_attempts) == 1 else: - assert span["output"] == {"type": "audio"} + assert span["output"] == {"content": []} assert not memory_logger.upload_attempts +async def _consume_speech(is_async, response, consumption, tmp_path): + """Read a streamed speech response one way and return the audio bytes seen.""" + if consumption in {"read", "parse"}: + return await _call(is_async, getattr(response, consumption)) + if consumption == "text": + await _call(is_async, response.text) + return response.http_response.content + if consumption == "stream_to_file": + path = tmp_path / "speech.wav" + await _call(is_async, response.stream_to_file, path, chunk_size=128) + return path.read_bytes() + if consumption in {"iter_text", "iter_lines"}: + chunks = response.iter_text(128) if consumption == "iter_text" else response.iter_lines() + return b"RIFF" if "".join(await _drain(is_async, chunks)).startswith("RIFF") else b"" + if consumption == "partial": + stream = response.iter_bytes(128) + chunk = await anext(stream) if is_async else next(stream) + await stream.aclose() if is_async else stream.close() + return chunk + if consumption == "full": + return b"".join(await _drain(is_async, response.iter_bytes(128))) + return b"" + + +@sync_async +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("consumption", "capture"), + [ + *( + (consumption, True) + for consumption in ( + "full", + "partial", + "read", + "parse", + "text", + "stream_to_file", + "iter_text", + "iter_lines", + "empty", + ) + ), + # Capture gating does not depend on how the body is consumed. + ("full", False), + ], +) +@pytest.mark.vcr(cassette_name="test_openai_audio_speech_capture") +async def test_openai_streaming_speech_preserves_consumption_and_parent( + memory_logger, monkeypatch, tmp_path, is_async, capture, consumption +): + monkeypatch.setenv("BRAINTRUST_CAPTURE_AGENT_AUDIO_ATTACHMENTS", str(capture).lower()) + client = wrap_openai(_client(is_async)) + audio = bytearray() + # Create the manager outside the parent: the request (and its span) must + # start when the context is entered, even though the async SDK builds its + # request coroutine as soon as create() is called. + manager = client.audio.speech.with_streaming_response.create( + model="tts-1", + voice="alloy", + input="Hi.", + response_format="wav", + span_info={"name": "custom speech", "metadata": {"request_tag": "speech-test"}}, + ) + with logger.start_span(name="tts", type="task") as parent: + if is_async: + async with manager as response: + audio.extend(await _consume_speech(is_async, response, consumption, tmp_path)) + else: + with manager as response: + audio.extend(await _consume_speech(is_async, response, consumption, tmp_path)) + assert logger.current_span() is parent + memory_logger.flush() + spans = memory_logger.pop() + model = _find_span_by_name(spans, "custom speech") + assert len(spans) == 2 + assert model["span_parents"] == [parent.span_id] + assert model["span_attributes"]["type"] == "llm" + assert model["metadata"] == {"model": "tts-1", "provider": "openai", "request_tag": "speech-test"} + assert model["context"]["span_origin"]["instrumentation"]["name"] == "openai-auto" + assert model["input"] == { + "operation": "speech", + "prompt": "Hi.", + "parameters": {"voice": "alloy", "format": "wav"}, + } + assert model["metrics"]["end"] >= model["metrics"]["start"] + assert not {"tokens", "prompt_tokens", "completion_tokens"} & set(model["metrics"]) + if consumption == "empty": + assert not audio + assert "time_to_first_token" not in model["metrics"] + else: + assert audio.startswith(b"RIFF") + assert model["metrics"]["time_to_first_token"] >= 0 + if capture and consumption in {"full", "read", "parse", "text", "stream_to_file"}: + part = model["output"]["content"][0]["file"] + assert part["file_data"]["type"] == "braintrust_attachment" + assert part["file_data"]["content_type"] == "audio/wav" + assert part["byte_size"] == len(audio) + assert len(memory_logger.upload_attempts) == 1 + else: + assert model["output"] == {"content": []} + assert not memory_logger.upload_attempts + + +@sync_async +@pytest.mark.asyncio +@pytest.mark.vcr +async def test_openai_streaming_speech_request_error(memory_logger, is_async): + # A real provider rejection: the request fails before any audio streams. + client = wrap_openai(_client(is_async)) + manager = client.audio.speech.with_streaming_response.create( + model="tts-1", voice="not-a-voice", input="Hi.", response_format="wav" + ) + with logger.start_span(name="tts", type="task") as parent: + with pytest.raises(openai.BadRequestError): + if is_async: + async with manager: + pass + else: + with manager: + pass + memory_logger.flush() + model = _find_span_by_name(memory_logger.pop(), "Speech") + assert model["span_parents"] == [parent.span_id] + assert "400" in model["error"] and "voice" in model["error"] + assert model["metrics"]["end"] >= model["metrics"]["start"] + assert "time_to_first_token" not in model["metrics"] + assert "output" not in model or model["output"] is None + + +@sync_async +@pytest.mark.asyncio +@pytest.mark.vcr(cassette_name="test_openai_audio_speech_capture") +async def test_openai_streaming_speech_errors_omit_partial_attachments(memory_logger, monkeypatch, is_async): + monkeypatch.setenv("BRAINTRUST_CAPTURE_AGENT_AUDIO_ATTACHMENTS", "true") + client = wrap_openai(_client(is_async)) + manager = client.audio.speech.with_streaming_response.create( + model="tts-1", voice="alloy", input="Hi.", response_format="wav" + ) + if is_async: + async with manager as response: + stream = response.iter_bytes(128) + assert await anext(stream) + with pytest.raises(asyncio.CancelledError): + await stream.athrow(asyncio.CancelledError()) + else: + with manager as response: + stream = response.iter_bytes(128) + assert next(stream) + with pytest.raises(RuntimeError, match="stopped"): + stream.throw(RuntimeError("stopped")) + memory_logger.flush() + (span,) = memory_logger.pop() + assert "error" in span + assert span["metrics"]["end"] >= span["metrics"]["start"] + assert span["output"] == {"content": []} + assert not memory_logger.upload_attempts + + +@sync_async +@pytest.mark.asyncio +@pytest.mark.parametrize("consume_one", [False, True]) +@pytest.mark.vcr(cassette_name="test_openai_audio_speech_capture") +async def test_abandoned_speech_response_finalizes_without_partial_audio( + memory_logger, monkeypatch, is_async, consume_one +): + import gc + + monkeypatch.setenv("BRAINTRUST_CAPTURE_AGENT_AUDIO_ATTACHMENTS", "true") + client = wrap_openai(_client(is_async)) + manager = client.audio.speech.with_streaming_response.create( + model="tts-1", voice="alloy", input="Hi.", response_format="wav" + ) + response = await manager.__aenter__() if is_async else manager.__enter__() + if consume_one: + stream = response.iter_bytes(128) + assert await anext(stream) if is_async else next(stream) + del stream + # Release the real transport resource, then abandon the SDK response. + # Its trace must finalize without asking the transport for more bytes. + if is_async: + await response.http_response.aclose() + else: + response.http_response.close() + del response, manager + gc.collect() + if is_async: + # Python first schedules async-generator close, then releases its + # response reference. Trace finalization itself does no async work. + await asyncio.sleep(0) + await asyncio.sleep(0) + memory_logger.flush() + (span,) = memory_logger.pop() + assert "end" in span["metrics"] + assert span["output"] == {"content": []} + assert not memory_logger.upload_attempts + gc.collect() + assert memory_logger.pop() == [] + + @sync_async @pytest.mark.asyncio @pytest.mark.vcr diff --git a/py/src/braintrust/integrations/openai/tracing.py b/py/src/braintrust/integrations/openai/tracing.py index a025ff0c4..a0308bb50 100644 --- a/py/src/braintrust/integrations/openai/tracing.py +++ b/py/src/braintrust/integrations/openai/tracing.py @@ -13,7 +13,6 @@ from braintrust.env import BraintrustEnv from braintrust.integrations.question import _question_span_input, _question_span_output from braintrust.integrations.utils import ( - _extract_audio_output, _image_attachment_from_base64, _infer_audio_mime_type, _is_not_given, @@ -29,6 +28,8 @@ from braintrust.logger import Span from braintrust.logger import start_span as _bt_start_span +from ._speech import speech_filename, speech_input, speech_mime_type, speech_output, trace_stream + _INSTRUMENTATION = "openai-auto" _log = logging.getLogger(__name__) @@ -138,15 +139,6 @@ def start_span(*args, **kwargs): _MODERATION_METADATA_PARAMS = ("model",) -_SPEECH_METADATA_PARAMS = ( - "model", - "voice", - "response_format", - "speed", - "instructions", - "stream_format", -) - _AUDIO_FILE_METADATA_PARAMS = ( "model", "language", @@ -266,18 +258,25 @@ def _extract_moderation_metadata(response: Any) -> dict[str, Any]: return {"moderation": moderation} if moderation is not None else {} -def _raw_response_requested(kwargs: dict[str, Any]) -> bool: +def _raw_response_mode(kwargs: dict[str, Any]) -> str | None: + """Return ``"stream"`` (with_streaming_response), ``"raw"`` (with_raw_response), + or ``None`` when the raw-response header is absent or falsy.""" extra_headers = kwargs.get("extra_headers") if not isinstance(extra_headers, dict): - return False + return None for key, value in extra_headers.items(): if isinstance(key, str) and key.lower() == RAW_RESPONSE_HEADER: if isinstance(value, str): - return value.lower() in {"true", "stream"} - return bool(value) + value = value.lower() + return "stream" if value == "stream" else ("raw" if value == "true" else None) + return "raw" if value else None - return False + return None + + +def _raw_response_requested(kwargs: dict[str, Any]) -> bool: + return _raw_response_mode(kwargs) is not None def _materialize_logged_file_input(value: Any) -> Any: @@ -2325,18 +2324,22 @@ def process_output(self, response: Any, span: Span): class SpeechWrapper(BaseWrapper): - _metadata_params = _SPEECH_METADATA_PARAMS - def __init__(self, create_fn: Callable[..., Any] | None, acreate_fn: Callable[..., Any] | None): super().__init__(create_fn, acreate_fn, "Speech") def process_output(self, response: Any, span: Span): - output = ( - _extract_audio_output(response, prefix="generated_speech") - if BraintrustEnv.CAPTURE_AGENT_AUDIO_ATTACHMENTS.get(False) - else {"type": "audio"} + data = getattr(response, "content", b"") + span.log(output=speech_output(data, speech_mime_type(response), speech_filename(response))) + + @classmethod + def _parse_params(cls, params: dict[str, Any]) -> dict[str, Any]: + return merge_dicts( + params.pop("span_info", {}), + { + "input": speech_input(params), + "metadata": {"model": params.get("model"), "provider": "openai"}, + }, ) - span.log(output=output) class _AudioFileWrapper(BaseWrapper): @@ -2560,7 +2563,25 @@ def process_output(self, response: Any, span: Span): span.log(output=self._extract_text(response)) -_audio_speech_create_wrapper = _make_base_wrapper_callback(SpeechWrapper) +_audio_speech_base_wrapper = _make_base_wrapper_callback(SpeechWrapper) + + +def _audio_speech_create_wrapper(wrapped, instance, args, kwargs): + # with_streaming_response sets this header before invoking create; trace it + # here instead of letting the base callback skip raw-response calls. + if _raw_response_mode(kwargs) == "stream": + return trace_stream( + wrapped, + args, + kwargs, + is_async=_is_async_callable(wrapped), + start_span=start_span, + log_headers=log_headers, + params=SpeechWrapper._parse_params(kwargs), + ) + return _audio_speech_base_wrapper(wrapped, instance, args, kwargs) + + _audio_transcription_create_wrapper = _make_base_wrapper_callback(TranscriptionWrapper) _audio_translation_create_wrapper = _make_base_wrapper_callback(TranslationWrapper)