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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions py/noxfile.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -210,6 +210,16 @@ def test_openai(session, version):
_run_core_tests(session)


@nox.session()
def test_openai_http2_streaming(session):
_install_test_deps(session)
_install(session, "openai")
# h2 is isolated to this session because it's only needed to force the
# HTTP/2 LegacyAPIResponse streaming path used by the regression test.
session.install("h2")
_run_tests(session, f"{WRAPPER_DIR}/test_openai_http2.py")


@nox.session()
def test_openrouter(session):
"""Test wrap_openai with OpenRouter. Requires OPENROUTER_API_KEY env var."""
Expand Down
38 changes: 32 additions & 6 deletions py/src/braintrust/oai.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,8 +19,14 @@

class NamedWrapper:
def __init__(self, wrapped: Any):
# Keep the legacy mangled attribute for existing wrapped-client checks
# that introspect `_NamedWrapper__wrapped` directly.
self.__wrapped = wrapped

@property
def _wrapped(self) -> Any:
return self.__wrapped

def __getattr__(self, name: str) -> Any:
return getattr(self.__wrapped, name)

Expand All@@ -33,8 +39,8 @@ def __init__(self, response: Any):

async def __aenter__(self):
if hasattr(self._response, "__aenter__"):
return await self._response.__aenter__()
return self._response
await self._response.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self._response, "__aexit__"):
Expand DownExpand Up@@ -188,7 +194,7 @@ def gen():
span.end()

should_end = False
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage", {}))
Expand DownExpand Up@@ -244,7 +250,7 @@ async def gen():

should_end = False
streamer = gen()
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
metrics = _parse_metrics_from_usage(log_response.get("usage"))
Expand DownExpand Up@@ -365,6 +371,16 @@ def __iter__(self) -> Any:
def __next__(self) -> Any:
return next(self._traced_generator)

def __enter__(self) -> Any:
if hasattr(self._wrapped, "__enter__"):
self._wrapped.__enter__()
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__exit__"):
return self._wrapped.__exit__(exc_type, exc_val, exc_tb)
return None


class _AsyncTracedStream(NamedWrapper):
"""Traced async stream. Iterates via the traced generator while delegating
Expand All@@ -380,6 +396,16 @@ def __aiter__(self) -> Any:
async def __anext__(self) -> Any:
return await self._traced_generator.__anext__()

async def __aenter__(self) -> Any:
if hasattr(self._wrapped, "__aenter__"):
await self._wrapped.__aenter__()
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> Any:
if hasattr(self._wrapped, "__aexit__"):
return await self._wrapped.__aexit__(exc_type, exc_val, exc_tb)
return None


class _RawResponseWithTracedStream(NamedWrapper):
"""Proxy for LegacyAPIResponse that replaces parse() with a traced stream,
Expand DownExpand Up@@ -445,7 +471,7 @@ def gen():
should_end = False
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _TracedStream(raw_response, gen()))
return gen()
return _TracedStream(raw_response, gen())
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand DownExpand Up@@ -498,7 +524,7 @@ async def gen():
streamer = gen()
if self.return_raw and hasattr(create_response, "parse"):
return _RawResponseWithTracedStream(create_response, _AsyncTracedStream(raw_response, streamer))
return AsyncResponseWrapper(streamer)
return _AsyncTracedStream(raw_response, streamer)
else:
log_response = _try_to_dict(raw_response)
event_data = self._parse_event_from_result(log_response)
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
interactions:
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw6be6DuhpHqDlc8nKm7x3iMAL6","object":"chat.completion.chunk","created":1748488174,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb30e8d5e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:34 GMT
Server:
- cloudflare
Set-Cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
path=/; expires=Thu, 29-May-25 03:39:34 GMT; domain=.api.openai.com; HttpOnly;
Secure; SameSite=None
- _cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000;
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "313"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "317"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_7718454117290f001d635e2ea50bf0b5
status:
code: 200
message: OK
- request:
body: '{"messages":[{"role":"user","content":"What''s 12 + 12?"}],"model":"gpt-4o-mini","stream":true,"stream_options":{"include_usage":true}}'
headers:
accept:
- application/json
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- "134"
content-type:
- application/json
cookie:
- __cf_bm=AIq4yjX3ru.J9gwNR6zSYLQNorConUZa5qtJ6wXxuvE-1748488174-1.0.1.1-KquMaoYitsL5z76ow2IPzasSn98mtC1_QEt9VOT1pvvQt_obPUDugNtsEGJCc_wP50_X4wP.kC7nYuf98KX8dCPpiq2ZqY5vwVCdgocqRxU;
_cfuvid=o0LrLIiV.VvLFX1H1bbtbV01AjzSfXrfrVn0fU7pANY-1748488174648-0.0.1.1-604800000
host:
- api.openai.com
user-agent:
- AsyncOpenAI/Python 1.82.0
x-stainless-arch:
- arm64
x-stainless-async:
- async:asyncio
x-stainless-lang:
- python
x-stainless-os:
- MacOS
x-stainless-package-version:
- 1.82.0
x-stainless-raw-response:
- "true"
x-stainless-read-timeout:
- "600"
x-stainless-retry-count:
- "0"
x-stainless-runtime:
- CPython
x-stainless-runtime-version:
- 3.13.3
method: POST
uri: https://api.openai.com/v1/chat/completions
response:
body:
string:
'data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
+"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"12"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
equals"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"
"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"24"},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}


data: {"id":"chatcmpl-BcNw7TPkf33tHhtv5BBYd6zunIaPW","object":"chat.completion.chunk","created":1748488175,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_54eb4bd693","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}


data: [DONE]


'
headers:
CF-RAY:
- 9472cb34d8b0e56c-EWR
Connection:
- keep-alive
Content-Type:
- text/event-stream; charset=utf-8
Date:
- Thu, 29 May 2025 03:09:35 GMT
Server:
- cloudflare
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
access-control-expose-headers:
- X-Request-ID
alt-svc:
- h3=":443"; ma=86400
cf-cache-status:
- DYNAMIC
openai-organization:
- braintrust-data
openai-processing-ms:
- "324"
openai-version:
- "2020-10-01"
strict-transport-security:
- max-age=31536000; includeSubDomains; preload
x-envoy-upstream-service-time:
- "328"
x-ratelimit-limit-requests:
- "30000"
x-ratelimit-limit-tokens:
- "150000000"
x-ratelimit-remaining-requests:
- "29999"
x-ratelimit-remaining-tokens:
- "149999993"
x-ratelimit-reset-requests:
- 2ms
x-ratelimit-reset-tokens:
- 0s
x-request-id:
- req_8e14ac90b3fc7df08ab71458200c0b80
status:
code: 200
message: OK
version: 1
Loading
Loading