From f184dff933ab3eab07d03550d7df7ca899d5509e Mon Sep 17 00:00:00 2001 From: David Elner Date: Wed, 18 Nov 2026 18:30:42 -0500 Subject: [PATCH 1/3] fix(openai): trace streamed speech requests through consumption MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 **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 --- .../auto_test_scripts/test_auto_openai.py | 25 ++ .../braintrust/integrations/openai/_speech.py | 218 ++++++++++++++++++ .../integrations/openai/test_openai.py | 189 ++++++++++++++- .../braintrust/integrations/openai/tracing.py | 39 +++- 4 files changed, 460 insertions(+), 11 deletions(-) create mode 100644 py/src/braintrust/integrations/openai/_speech.py 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..f031e09f5 --- /dev/null +++ b/py/src/braintrust/integrations/openai/_speech.py @@ -0,0 +1,218 @@ +"""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, _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 {}), + } + + +def speech_filename(response: Any) -> str | None: + headers = getattr(response, "headers", None) + 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 "speech." + + { + "audio/wav": "wav", + "audio/mpeg": "mp3", + "audio/pcm": "pcm", + "audio/opus": "opus", + "audio/aac": "aac", + "audio/flac": "flac", + }.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 + # APIResponse exposes headers directly; the shared helper also supports + # the non-streaming HttpxBinaryResponseContent.response representation. + content_type = response.headers.get("content-type") + self.mime_type = ( + content_type.split(";", 1)[0].strip() + if isinstance(content_type, str) and content_type + else _infer_audio_mime_type(response, response_format) + ) + self.filename = speech_filename(response) + self.started = started + self.first_content = False + self.finished = False + self.audio = bytearray() + self.capture = span is not NOOP_SPAN and BraintrustEnv.CAPTURE_AGENT_AUDIO_ATTACHMENTS.get(False) + + def observe(self, chunk): + if self.finished or not chunk: + return + if not self.first_content: + self.first_content = True + self.span.log(metrics={"time_to_first_token": time.monotonic() - self.started}) + if self.capture and BraintrustEnv.CAPTURE_AGENT_AUDIO_ATTACHMENTS.get(False): + self.audio.extend(chunk) + + def finish(self, error=None, *, complete=False): + if self.finished: + return + self.finished = True + if error is not None and not isinstance(error, GeneratorExit): + self.span.log(error=error) + self.span.log(output=speech_output(bytes(self.audio) if complete else b"", self.mime_type, self.filename)) + self.audio.clear() + self.span.end() + + +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): + try: + for chunk in self.__wrapped__.iter_bytes(*args, **kwargs): + self._self_trace.observe(chunk) + yield chunk + except BaseException as exc: + self._self_trace.finish(exc) + raise + else: + self._self_trace.finish(complete=True) + + def read(self): + try: + data = self.__wrapped__.read() + except BaseException as exc: + self._self_trace.finish(exc) + raise + self._self_trace.observe(data) + self._self_trace.finish(complete=True) + return data + + def parse(self, *args, **kwargs): + # Execute SDK parsing with this proxy as self, so its read goes through + # the observation above. Preserve the provider's type/cache behavior. + return type(self.__wrapped__).parse(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) + + async def iter_bytes(self, *args, **kwargs): + try: + async for chunk in self.__wrapped__.iter_bytes(*args, **kwargs): + self._self_trace.observe(chunk) + yield chunk + except BaseException as exc: + self._self_trace.finish(exc) + raise + else: + self._self_trace.finish(complete=True) + + async def read(self): + try: + data = await self.__wrapped__.read() + except BaseException as exc: + self._self_trace.finish(exc) + raise + self._self_trace.observe(data) + self._self_trace.finish(complete=True) + return data + + async def parse(self, *args, **kwargs): + return await type(self.__wrapped__).parse(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, params): + """The SDK invokes this request only when its response context is entered.""" + span = start_span(**{"name": "Speech", "type": "llm", "set_current": False, **params}) + started = time.monotonic() + if is_async: + + async def call(): + try: + response = await wrapped(*args, **kwargs) + except BaseException as exc: + span.log(error=exc) + span.end() + raise + return AsyncSpeechResponse(response, _SpeechTrace(span, response, kwargs.get("response_format"), started)) + + return call() + try: + response = wrapped(*args, **kwargs) + except BaseException as exc: + span.log(error=exc) + span.end() + raise + return SpeechResponse(response, _SpeechTrace(span, response, kwargs.get("response_format"), started)) diff --git a/py/src/braintrust/integrations/openai/test_openai.py b/py/src/braintrust/integrations/openai/test_openai.py index b9d2e17ac..e0bc6b9c7 100644 --- a/py/src/braintrust/integrations/openai/test_openai.py +++ b/py/src/braintrust/integrations/openai/test_openai.py @@ -2197,6 +2197,17 @@ async def test_openai_audio_transcription(memory_logger, is_async, monkeypatch, assert response.text.lower() == TEST_TRANSCRIPT.lower() +def test_speech_input_preserves_generation_instructions(): + # Request-only normalization: no provider response or transport is involved. + from braintrust.integrations.openai._speech import speech_input + + assert speech_input({"input": "Hi.", "instructions": "Speak warmly."}) == { + "operation": "speech", + "prompt": "Hi.", + "parameters": {"instructions": "Speak warmly."}, + } + + @sync_async @pytest.mark.asyncio @pytest.mark.parametrize("capture", [False, True]) @@ -2206,22 +2217,192 @@ 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 +@sync_async +@pytest.mark.asyncio +@pytest.mark.parametrize("capture", [False, True]) +@pytest.mark.parametrize("consumption", ["full", "partial", "read", "empty"]) +@pytest.mark.vcr(cassette_name="test_openai_audio_speech_capture") +async def test_openai_streaming_speech_preserves_consumption_and_parent( + memory_logger, monkeypatch, is_async, capture, consumption +): + monkeypatch.setenv("BRAINTRUST_CAPTURE_AGENT_AUDIO_ATTACHMENTS", str(capture).lower()) + client = wrap_openai(_client(is_async)) + audio = bytearray() + with logger.start_span(name="tts", type="task") as parent: + 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"}}, + ) + if is_async: + async with manager as response: + if consumption == "read": + audio.extend(await response.read()) + elif consumption != "empty": + async for chunk in response.iter_bytes(128): + audio.extend(chunk) + if consumption == "partial": + break + else: + with manager as response: + if consumption == "read": + audio.extend(response.read()) + elif consumption != "empty": + for chunk in response.iter_bytes(128): + audio.extend(chunk) + if consumption == "partial": + break + 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"}: + part = model["output"]["content"][0]["file"] + assert part["file_data"]["type"] == "braintrust_attachment" + 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(cassette_name="test_openai_audio_speech_capture") +async def test_speech_stream_mime_uses_native_response_headers(memory_logger, is_async): + from braintrust.integrations.openai._speech import _SpeechTrace + + 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__() + try: + # Exercise inference without a request-format hint using a real SDK + # response and its recorded headers, rather than a fabricated response. + state = _SpeechTrace(logger.NOOP_SPAN, response, None, time.monotonic()) + assert state.mime_type == response.headers["content-type"] == "audio/wav" + finally: + if is_async: + await manager.__aexit__(None, None, None) + else: + manager.__exit__(None, None, 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..7d0391e73 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, @@ -2331,12 +2330,22 @@ def __init__(self, create_fn: Callable[..., Any] | None, acreate_fn: Callable[.. 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"} + from ._speech import speech_filename, speech_output + + data = getattr(response, "content", b"") + span.log(output=speech_output(data, _infer_audio_mime_type(response), speech_filename(response))) + + @classmethod + def _parse_params(cls, params: dict[str, Any]) -> dict[str, Any]: + from ._speech import speech_input + + 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 +2569,23 @@ def process_output(self, response: Any, span: Span): span.log(output=self._extract_text(response)) -_audio_speech_create_wrapper = _make_base_wrapper_callback(SpeechWrapper) +def _audio_speech_create_wrapper(wrapped, instance, args, kwargs): + # The streaming-response API sets this header before invoking create. + headers = kwargs.get("extra_headers") or {} + if any(str(key).lower() == RAW_RESPONSE_HEADER and value == "stream" for key, value in headers.items()): + from ._speech import trace_stream + + return trace_stream( + wrapped, + args, + kwargs, + is_async=_is_async_callable(wrapped), + start_span=start_span, + params=SpeechWrapper._parse_params(kwargs), + ) + return _make_base_wrapper_callback(SpeechWrapper)(wrapped, instance, args, kwargs) + + _audio_transcription_create_wrapper = _make_base_wrapper_callback(TranscriptionWrapper) _audio_translation_create_wrapper = _make_base_wrapper_callback(TranslationWrapper) From 98b4c8d5e755c9d1cc70b2e89c8f4a9a46d184c6 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Tue, 24 Nov 2026 12:53:30 -0500 Subject: [PATCH 2/3] fix(openai): start async speech spans on enter and observe all reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 **This text was AI-generated.** Follow-up to the streamed speech tracing in the previous commit. The async SDK builds its request coroutine as soon as `with_streaming_response.create()` is called, not when the context is entered. The Speech span was started outside that coroutine, so it began at create time, under whatever span was current then. If the manager was never entered, the span never ended. ```text with start_span("creator"): manager = client.audio.speech.with_streaming_response.create(...) with start_span("consumer"): async with manager as r: ... before: creator └─ Speech (timing includes the gap before enter) after: consumer └─ Speech ``` The span is now started inside the coroutine, so it opens when the request actually runs. Reading the body through some SDK helpers also skipped the proxy: `iter_text()` and `iter_lines()` iterate the httpx response directly, and `text()` / `json()` call the wrapped `read()`. Those reads logged no `time_to_first_token` or output, and the span only ended at `close()`. ```text iter_bytes / read / parse / stream_to_file -> observed (already) text / json -> run with self=proxy, audio captured iter_text / iter_lines -> observed for timing; no audio capture (decoded text is not the original bytes) ``` Also: - log response headers (cache metrics) on the streaming path, matching the non-streaming wrapper - read the filename from `response.response.headers` for non-streaming `HttpxBinaryResponseContent` - drop a redundant capture-flag check in `observe()` Tests are consolidated around real cassettes. The consumption test now covers every read method, creates the manager outside its parent span, and asserts the attachment content type. A new cassette-backed test covers a provider 400 before any audio streams. Low-value tests (a hand-built `_SpeechTrace` and a helper-only input check) are removed. Note: span `input`/`output` shape for non-streaming speech changed in the previous commit and should be called out in the changelog. Refs: https://linear.app/braintrustdata/issue/SDK-856 --- .../braintrust/integrations/openai/_speech.py | 115 +++++++++---- ...streaming_speech_request_error[async].yaml | 93 +++++++++++ ..._streaming_speech_request_error[sync].yaml | 93 +++++++++++ ...streaming_speech_request_error[async].yaml | 93 +++++++++++ ..._streaming_speech_request_error[sync].yaml | 93 +++++++++++ ...streaming_speech_request_error[async].yaml | 93 +++++++++++ ..._streaming_speech_request_error[sync].yaml | 93 +++++++++++ ...streaming_speech_request_error[async].yaml | 93 +++++++++++ ..._streaming_speech_request_error[sync].yaml | 93 +++++++++++ .../integrations/openai/test_openai.py | 157 ++++++++++++------ .../braintrust/integrations/openai/tracing.py | 1 + 11 files changed, 934 insertions(+), 83 deletions(-) create mode 100644 py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[async].yaml create mode 100644 py/src/braintrust/integrations/openai/cassettes/1.71.0/test_openai_streaming_speech_request_error[sync].yaml create mode 100644 py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[async].yaml create mode 100644 py/src/braintrust/integrations/openai/cassettes/1.77.0/test_openai_streaming_speech_request_error[sync].yaml create mode 100644 py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[async].yaml create mode 100644 py/src/braintrust/integrations/openai/cassettes/1.92.0/test_openai_streaming_speech_request_error[sync].yaml create mode 100644 py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[async].yaml create mode 100644 py/src/braintrust/integrations/openai/cassettes/latest/test_openai_streaming_speech_request_error[sync].yaml diff --git a/py/src/braintrust/integrations/openai/_speech.py b/py/src/braintrust/integrations/openai/_speech.py index f031e09f5..5fe8f1aff 100644 --- a/py/src/braintrust/integrations/openai/_speech.py +++ b/py/src/braintrust/integrations/openai/_speech.py @@ -31,7 +31,11 @@ def speech_input(params: dict[str, Any]) -> dict[str, Any]: def speech_filename(response: Any) -> str | None: + # Streaming APIResponse exposes headers directly; the non-streaming + # HttpxBinaryResponseContent keeps them on its httpx response. headers = getattr(response, "headers", None) + if headers is None: + headers = getattr(getattr(response, "response", None), "headers", None) disposition = headers.get("content-disposition") if headers is not None else None if not disposition: return None @@ -75,8 +79,6 @@ def speech_output(data: bytes, mime_type: str, filename: str | None = None) -> d class _SpeechTrace: def __init__(self, span, response, response_format, started): self.span = span - # APIResponse exposes headers directly; the shared helper also supports - # the non-streaming HttpxBinaryResponseContent.response representation. content_type = response.headers.get("content-type") self.mime_type = ( content_type.split(";", 1)[0].strip() @@ -90,13 +92,18 @@ def __init__(self, span, response, response_format, started): self.audio = bytearray() self.capture = span is not NOOP_SPAN and BraintrustEnv.CAPTURE_AGENT_AUDIO_ATTACHMENTS.get(False) - def observe(self, chunk): + 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 if not self.first_content: self.first_content = True self.span.log(metrics={"time_to_first_token": time.monotonic() - self.started}) - if self.capture and BraintrustEnv.CAPTURE_AGENT_AUDIO_ATTACHMENTS.get(False): + if not audio: + self.capture = False + self.audio.clear() + elif self.capture: self.audio.extend(chunk) def finish(self, error=None, *, complete=False): @@ -110,6 +117,30 @@ def finish(self, error=None, *, complete=False): 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) @@ -118,15 +149,13 @@ def __init__(self, response, trace): weakref.finalize(self, trace.finish) def iter_bytes(self, *args, **kwargs): - try: - for chunk in self.__wrapped__.iter_bytes(*args, **kwargs): - self._self_trace.observe(chunk) - yield chunk - except BaseException as exc: - self._self_trace.finish(exc) - raise - else: - self._self_trace.finish(complete=True) + 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: @@ -138,11 +167,18 @@ def read(self): self._self_trace.finish(complete=True) 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): - # Execute SDK parsing with this proxy as self, so its read goes through - # the observation above. Preserve the provider's type/cache behavior. 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) @@ -159,16 +195,14 @@ def __init__(self, response, trace): self._self_trace = trace weakref.finalize(self, trace.finish) - async def iter_bytes(self, *args, **kwargs): - try: - async for chunk in self.__wrapped__.iter_bytes(*args, **kwargs): - self._self_trace.observe(chunk) - yield chunk - except BaseException as exc: - self._self_trace.finish(exc) - raise - else: - self._self_trace.finish(complete=True) + 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: @@ -183,6 +217,12 @@ async def read(self): 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) @@ -193,26 +233,39 @@ async def close(self): self._self_trace.finish() -def trace_stream(wrapped, args, kwargs, *, is_async, start_span, params): - """The SDK invokes this request only when its response context is entered.""" - span = start_span(**{"name": "Speech", "type": "llm", "set_current": False, **params}) - started = time.monotonic() +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. + """ + + 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, kwargs.get("response_format"), started) + if is_async: async def call(): + span, started = start() try: response = await wrapped(*args, **kwargs) except BaseException as exc: span.log(error=exc) span.end() raise - return AsyncSpeechResponse(response, _SpeechTrace(span, response, kwargs.get("response_format"), started)) + return AsyncSpeechResponse(response, traced(span, response, started)) return call() + span, started = start() try: response = wrapped(*args, **kwargs) except BaseException as exc: span.log(error=exc) span.end() raise - return SpeechResponse(response, _SpeechTrace(span, response, kwargs.get("response_format"), started)) + 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 e0bc6b9c7..b1e1ceba2 100644 --- a/py/src/braintrust/integrations/openai/test_openai.py +++ b/py/src/braintrust/integrations/openai/test_openai.py @@ -2197,17 +2197,6 @@ async def test_openai_audio_transcription(memory_logger, is_async, monkeypatch, assert response.text.lower() == TEST_TRANSCRIPT.lower() -def test_speech_input_preserves_generation_instructions(): - # Request-only normalization: no provider response or transport is involved. - from braintrust.integrations.openai._speech import speech_input - - assert speech_input({"input": "Hi.", "instructions": "Speak warmly."}) == { - "operation": "speech", - "prompt": "Hi.", - "parameters": {"instructions": "Speak warmly."}, - } - - @sync_async @pytest.mark.asyncio @pytest.mark.parametrize("capture", [False, True]) @@ -2241,43 +2230,103 @@ async def test_openai_audio_speech_capture(memory_logger, monkeypatch, is_async, assert not memory_logger.upload_attempts +def _consume_speech_sync(response, consumption, tmp_path): + if consumption == "read": + return response.read() + if consumption == "parse": + return response.parse() + if consumption == "text": + response.text() + return response.http_response.content + if consumption == "stream_to_file": + path = tmp_path / "speech.wav" + 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() + text = "".join(chunks) + return b"RIFF" if text.startswith("RIFF") else b"" + audio = bytearray() + if consumption != "empty": + for chunk in response.iter_bytes(128): + audio.extend(chunk) + if consumption == "partial": + break + return bytes(audio) + + +async def _consume_speech_async(response, consumption, tmp_path): + if consumption == "read": + return await response.read() + if consumption == "parse": + return await response.parse() + if consumption == "text": + await response.text() + return response.http_response.content + if consumption == "stream_to_file": + path = tmp_path / "speech.wav" + await 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() + text = "".join([chunk async for chunk in chunks]) + return b"RIFF" if text.startswith("RIFF") else b"" + audio = bytearray() + if consumption != "empty": + async for chunk in response.iter_bytes(128): + audio.extend(chunk) + if consumption == "partial": + break + return bytes(audio) + + @sync_async @pytest.mark.asyncio -@pytest.mark.parametrize("capture", [False, True]) -@pytest.mark.parametrize("consumption", ["full", "partial", "read", "empty"]) +@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, is_async, capture, consumption + 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: - 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"}}, - ) if is_async: async with manager as response: - if consumption == "read": - audio.extend(await response.read()) - elif consumption != "empty": - async for chunk in response.iter_bytes(128): - audio.extend(chunk) - if consumption == "partial": - break + audio.extend(await _consume_speech_async(response, consumption, tmp_path)) else: with manager as response: - if consumption == "read": - audio.extend(response.read()) - elif consumption != "empty": - for chunk in response.iter_bytes(128): - audio.extend(chunk) - if consumption == "partial": - break + audio.extend(_consume_speech_sync(response, consumption, tmp_path)) assert logger.current_span() is parent memory_logger.flush() spans = memory_logger.pop() @@ -2300,9 +2349,10 @@ async def test_openai_streaming_speech_preserves_consumption_and_parent( else: assert audio.startswith(b"RIFF") assert model["metrics"]["time_to_first_token"] >= 0 - if capture and consumption in {"full", "read"}: + 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: @@ -2312,25 +2362,28 @@ async def test_openai_streaming_speech_preserves_consumption_and_parent( @sync_async @pytest.mark.asyncio -@pytest.mark.vcr(cassette_name="test_openai_audio_speech_capture") -async def test_speech_stream_mime_uses_native_response_headers(memory_logger, is_async): - from braintrust.integrations.openai._speech import _SpeechTrace - +@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="alloy", input="Hi.", response_format="wav" + model="tts-1", voice="not-a-voice", input="Hi.", response_format="wav" ) - response = await manager.__aenter__() if is_async else manager.__enter__() - try: - # Exercise inference without a request-format hint using a real SDK - # response and its recorded headers, rather than a fabricated response. - state = _SpeechTrace(logger.NOOP_SPAN, response, None, time.monotonic()) - assert state.mime_type == response.headers["content-type"] == "audio/wav" - finally: - if is_async: - await manager.__aexit__(None, None, None) - else: - manager.__exit__(None, None, None) + 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 diff --git a/py/src/braintrust/integrations/openai/tracing.py b/py/src/braintrust/integrations/openai/tracing.py index 7d0391e73..2ef2a67dd 100644 --- a/py/src/braintrust/integrations/openai/tracing.py +++ b/py/src/braintrust/integrations/openai/tracing.py @@ -2581,6 +2581,7 @@ def _audio_speech_create_wrapper(wrapped, instance, args, kwargs): kwargs, is_async=_is_async_callable(wrapped), start_span=start_span, + log_headers=log_headers, params=SpeechWrapper._parse_params(kwargs), ) return _make_base_wrapper_callback(SpeechWrapper)(wrapped, instance, args, kwargs) From 85e82e7aaba283ea0e4f4cdcbf00292469e2787d Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Tue, 24 Nov 2026 13:21:10 -0500 Subject: [PATCH 3/3] simplification --- .../braintrust/integrations/openai/_speech.py | 106 +++++++++++------- .../integrations/openai/test_openai.py | 60 +++------- .../braintrust/integrations/openai/tracing.py | 49 ++++---- 3 files changed, 107 insertions(+), 108 deletions(-) diff --git a/py/src/braintrust/integrations/openai/_speech.py b/py/src/braintrust/integrations/openai/_speech.py index 5fe8f1aff..88231503e 100644 --- a/py/src/braintrust/integrations/openai/_speech.py +++ b/py/src/braintrust/integrations/openai/_speech.py @@ -6,7 +6,12 @@ from typing import Any from braintrust.env import BraintrustEnv -from braintrust.integrations.utils import _infer_audio_mime_type, _is_not_given, _materialize_attachment +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 @@ -30,12 +35,35 @@ def speech_input(params: dict[str, Any]) -> dict[str, Any]: } -def speech_filename(response: Any) -> str | None: +# 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) - if headers is None: - headers = getattr(getattr(response, "response", None), "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 @@ -49,16 +77,7 @@ def speech_output(data: bytes, mime_type: str, filename: str | None = None) -> d resolved = _materialize_attachment( data, mime_type=mime_type, - filename=filename - or "speech." - + { - "audio/wav": "wav", - "audio/mpeg": "mp3", - "audio/pcm": "pcm", - "audio/opus": "opus", - "audio/aac": "aac", - "audio/flac": "flac", - }.get(mime_type, "bin"), + filename=filename or f"speech.{_SPEECH_EXTENSIONS.get(mime_type, 'bin')}", ) if resolved is not None: return { @@ -79,41 +98,52 @@ def speech_output(data: bytes, mime_type: str, filename: str | None = None) -> d class _SpeechTrace: def __init__(self, span, response, response_format, started): self.span = span - content_type = response.headers.get("content-type") - self.mime_type = ( - content_type.split(";", 1)[0].strip() - if isinstance(content_type, str) and content_type - else _infer_audio_mime_type(response, response_format) - ) + self.mime_type = speech_mime_type(response, response_format) self.filename = speech_filename(response) self.started = started self.first_content = False self.finished = False - self.audio = bytearray() + # 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 - if not self.first_content: - self.first_content = True - self.span.log(metrics={"time_to_first_token": time.monotonic() - self.started}) + self._mark_first_content() if not audio: self.capture = False - self.audio.clear() + self.chunks.clear() elif self.capture: - self.audio.extend(chunk) + self.chunks.append(chunk) - def finish(self, error=None, *, complete=False): + 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) - self.span.log(output=speech_output(bytes(self.audio) if complete else b"", self.mime_type, self.filename)) - self.audio.clear() + 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() @@ -163,8 +193,7 @@ def read(self): except BaseException as exc: self._self_trace.finish(exc) raise - self._self_trace.observe(data) - self._self_trace.finish(complete=True) + self._self_trace.complete(data) return data # Run these SDK methods with this proxy as self, so their internal @@ -210,8 +239,7 @@ async def read(self): except BaseException as exc: self._self_trace.finish(exc) raise - self._self_trace.observe(data) - self._self_trace.finish(complete=True) + self._self_trace.complete(data) return data async def parse(self, *args, **kwargs): @@ -239,14 +267,18 @@ def trace_stream(wrapped, args, kwargs, *, is_async, start_span, log_headers, pa 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, kwargs.get("response_format"), started) + return _SpeechTrace(span, response, response_format, started) if is_async: @@ -255,8 +287,7 @@ async def call(): try: response = await wrapped(*args, **kwargs) except BaseException as exc: - span.log(error=exc) - span.end() + _log_error_and_end_span(span, exc) raise return AsyncSpeechResponse(response, traced(span, response, started)) @@ -265,7 +296,6 @@ async def call(): try: response = wrapped(*args, **kwargs) except BaseException as exc: - span.log(error=exc) - span.end() + _log_error_and_end_span(span, exc) raise return SpeechResponse(response, traced(span, response, started)) diff --git a/py/src/braintrust/integrations/openai/test_openai.py b/py/src/braintrust/integrations/openai/test_openai.py index b1e1ceba2..19f71ee3e 100644 --- a/py/src/braintrust/integrations/openai/test_openai.py +++ b/py/src/braintrust/integrations/openai/test_openai.py @@ -2230,54 +2230,28 @@ async def test_openai_audio_speech_capture(memory_logger, monkeypatch, is_async, assert not memory_logger.upload_attempts -def _consume_speech_sync(response, consumption, tmp_path): - if consumption == "read": - return response.read() - if consumption == "parse": - return response.parse() +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": - response.text() + await _call(is_async, response.text) return response.http_response.content if consumption == "stream_to_file": path = tmp_path / "speech.wav" - response.stream_to_file(path, chunk_size=128) + 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() - text = "".join(chunks) - return b"RIFF" if text.startswith("RIFF") else b"" - audio = bytearray() - if consumption != "empty": - for chunk in response.iter_bytes(128): - audio.extend(chunk) - if consumption == "partial": - break - return bytes(audio) - - -async def _consume_speech_async(response, consumption, tmp_path): - if consumption == "read": - return await response.read() - if consumption == "parse": - return await response.parse() - if consumption == "text": - await response.text() - return response.http_response.content - if consumption == "stream_to_file": - path = tmp_path / "speech.wav" - await 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() - text = "".join([chunk async for chunk in chunks]) - return b"RIFF" if text.startswith("RIFF") else b"" - audio = bytearray() - if consumption != "empty": - async for chunk in response.iter_bytes(128): - audio.extend(chunk) - if consumption == "partial": - break - return bytes(audio) + 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 @@ -2323,10 +2297,10 @@ async def test_openai_streaming_speech_preserves_consumption_and_parent( with logger.start_span(name="tts", type="task") as parent: if is_async: async with manager as response: - audio.extend(await _consume_speech_async(response, consumption, tmp_path)) + audio.extend(await _consume_speech(is_async, response, consumption, tmp_path)) else: with manager as response: - audio.extend(_consume_speech_sync(response, consumption, tmp_path)) + audio.extend(await _consume_speech(is_async, response, consumption, tmp_path)) assert logger.current_span() is parent memory_logger.flush() spans = memory_logger.pop() diff --git a/py/src/braintrust/integrations/openai/tracing.py b/py/src/braintrust/integrations/openai/tracing.py index 2ef2a67dd..a0308bb50 100644 --- a/py/src/braintrust/integrations/openai/tracing.py +++ b/py/src/braintrust/integrations/openai/tracing.py @@ -28,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__) @@ -137,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", @@ -265,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: @@ -2324,21 +2324,15 @@ 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): - from ._speech import speech_filename, speech_output - data = getattr(response, "content", b"") - span.log(output=speech_output(data, _infer_audio_mime_type(response), speech_filename(response))) + 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]: - from ._speech import speech_input - return merge_dicts( params.pop("span_info", {}), { @@ -2569,12 +2563,13 @@ def process_output(self, response: Any, span: Span): span.log(output=self._extract_text(response)) -def _audio_speech_create_wrapper(wrapped, instance, args, kwargs): - # The streaming-response API sets this header before invoking create. - headers = kwargs.get("extra_headers") or {} - if any(str(key).lower() == RAW_RESPONSE_HEADER and value == "stream" for key, value in headers.items()): - from ._speech import trace_stream +_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, @@ -2584,7 +2579,7 @@ def _audio_speech_create_wrapper(wrapped, instance, args, kwargs): log_headers=log_headers, params=SpeechWrapper._parse_params(kwargs), ) - return _make_base_wrapper_callback(SpeechWrapper)(wrapped, instance, args, kwargs) + return _audio_speech_base_wrapper(wrapped, instance, args, kwargs) _audio_transcription_create_wrapper = _make_base_wrapper_callback(TranscriptionWrapper)