Skip to content

The agent engineering platform.

fix(openai): build Codex async headers off the event loop in `_agenerate` (#38129)

Mason Daugherty37b339f8c468
diff --git a/libs/partners/openai/langchain_openai/chat_models/codex.py b/libs/partners/openai/langchain_openai/chat_models/codex.py
index 564149c34d..842d48fd31 100644
--- a/libs/partners/openai/langchain_openai/chat_models/codex.py
+++ b/libs/partners/openai/langchain_openai/chat_models/codex.py
@@ -55,6 +55,15 @@ env var.
"""
ORIGINATOR_ENV_VAR = "LANGCHAIN_CODEX_ORIGINATOR"
ACCOUNT_ID_HEADER = "ChatGPT-Account-Id"
+_CODEX_HEADERS_KWARG = "_codex_headers"
+"""Private kwarg used to hand pre-built Codex headers to `_get_request_payload`.
+
+The async `_agenerate`/`_astream` paths build the headers from a token fetched
+off the event loop (via `aget_token`) and pass them through this kwarg so the
+sync payload builder doesn't fall back to `_codex_headers_sync` — which would
+acquire a thread + cross-process file lock on the loop. Leading underscore keeps
+it out of the public surface; it is popped before the payload reaches the SDK.
+"""
EXPERIMENTAL_UNOFFICIAL_WARNING = (
"`_ChatOpenAICodex` is experimental and unofficial. It uses ChatGPT "
"subscription OAuth against Codex endpoints and must only be used where "
@@ -438,7 +447,7 @@ class _ChatOpenAICodex(ChatOpenAI):
way `_convert_input` only runs once (inside super) instead of once
here and again there.
"""
- codex_headers = kwargs.pop("_codex_headers", None)
+ codex_headers = kwargs.pop(_CODEX_HEADERS_KWARG, None)
payload_input: LanguageModelInput = input_
if _maybe_has_system_messages(input_):
messages = self._convert_input(input_).to_messages()
@@ -466,6 +475,12 @@ class _ChatOpenAICodex(ChatOpenAI):
# silently overwriting it would hide a programming error).
if payload.get("instructions") is None:
payload["instructions"] = self.instructions
+ # An async caller may have already built the headers off the event loop
+ # and passed them through `_codex_headers`. Honor them verbatim — the
+ # `is not None` check (not truthiness) is deliberate: an explicit empty
+ # dict means "no headers, already decided async" and must NOT trigger a
+ # sync `get_token()` (which blocks the loop on a file lock). Only the
+ # purely-sync path, where the kwarg is absent, reads the token here.
headers = (
codex_headers if codex_headers is not None else self._codex_headers_sync()
)
@@ -478,9 +493,13 @@ class _ChatOpenAICodex(ChatOpenAI):
run_manager: AsyncCallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ChatResult:
- # Prime the cache via async refresh so the sync header build that
- # happens inside `super()._agenerate` does not block the event loop.
- await self.token_provider.aget_token()
+ # Fetch the token off the event loop and build the headers here, then
+ # hand them to the sync payload builder via `_codex_headers`. This keeps
+ # `_get_request_payload` (run on the loop inside `super()._agenerate`)
+ # from falling back to the sync `get_token()`, which would acquire a
+ # thread + cross-process file lock on the loop.
+ token = await self.token_provider.aget_token()
+ kwargs[_CODEX_HEADERS_KWARG] = self._build_headers(token.account_id)
return await super()._agenerate(
messages, stop=stop, run_manager=run_manager, **kwargs
)
@@ -492,8 +511,10 @@ class _ChatOpenAICodex(ChatOpenAI):
run_manager: AsyncCallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> AsyncIterator[ChatGenerationChunk]:
+ # Build the headers from a token fetched off the event loop (see
+ # `_agenerate` for why) and pass them to the sync payload builder.
token = await self.token_provider.aget_token()
- kwargs["_codex_headers"] = self._build_headers(token.account_id)
+ kwargs[_CODEX_HEADERS_KWARG] = self._build_headers(token.account_id)
async for chunk in super()._astream(
messages, stop=stop, run_manager=run_manager, **kwargs
):
diff --git a/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py b/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py
index f2161a64b0..c32532f090 100644
--- a/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py
+++ b/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py
@@ -59,6 +59,24 @@ class FakeTokenProvider:
return token.access_token
+class AsyncOnlyTokenProvider(FakeTokenProvider):
+ """Provider whose async path never delegates to sync `get_token`.
+
+ Lets a test prove an async code path stayed off the event loop: any stray
+ sync `get_token()` would bump `calls`, which the async path must leave
+ untouched.
+ """
+
+ async def aget_token(self) -> _ChatGPTToken:
+ self.async_calls += 1
+ return _ChatGPTToken(
+ access_token=self.access_token,
+ refresh_token="rt",
+ expires_at=datetime.now(timezone.utc) + timedelta(hours=1),
+ account_id=self.account_id,
+ )
+
+
def _build_model(**overrides: Any) -> _ChatOpenAICodex:
provider = overrides.pop("token_provider", None) or FakeTokenProvider()
return _ChatOpenAICodex(
@@ -469,38 +487,36 @@ def test_caller_headers_win_over_codex_defaults() -> None:
assert headers[ACCOUNT_ID_HEADER] == "acct-1"
-async def test_agenerate_primes_async_token_cache(
+async def test_agenerate_builds_codex_headers_without_sync_token_read(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """`_agenerate` must call `aget_token` so refresh doesn't block the loop."""
- provider = FakeTokenProvider()
+ """`_agenerate` must not call sync `get_token` on the event loop."""
+ provider = AsyncOnlyTokenProvider(account_id="acct-async")
model = _build_model(token_provider=provider)
+ kwargs_seen: dict[str, Any] = {}
- async def _fake_super_agenerate(*_a: Any, **_k: Any) -> Any:
+ async def _fake_super_agenerate(*_a: Any, **kwargs: Any) -> Any:
+ kwargs_seen.update(kwargs)
return "sentinel"
monkeypatch.setattr(ChatOpenAI, "_agenerate", _fake_super_agenerate)
- before = provider.async_calls
+ before_sync = provider.calls
+ before_async = provider.async_calls
result = await model._agenerate([HumanMessage("hi")])
+
assert result == "sentinel"
- assert provider.async_calls == before + 1
+ assert provider.async_calls == before_async + 1
+ assert provider.calls == before_sync
+ assert kwargs_seen["_codex_headers"] == {
+ ACCOUNT_ID_HEADER: "acct-async",
+ ORIGINATOR_HEADER: ORIGINATOR_VALUE,
+ }
async def test_astream_builds_codex_headers_without_sync_token_read(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""`_astream` must not call sync `get_token` on the event loop."""
-
- class AsyncOnlyTokenProvider(FakeTokenProvider):
- async def aget_token(self) -> _ChatGPTToken:
- self.async_calls += 1
- return _ChatGPTToken(
- access_token=self.access_token,
- refresh_token="rt",
- expires_at=datetime.now(timezone.utc) + timedelta(hours=1),
- account_id=self.account_id,
- )
-
provider = AsyncOnlyTokenProvider(account_id="acct-async")
model = _build_model(token_provider=provider)
kwargs_seen: dict[str, Any] = {}
@@ -523,6 +539,32 @@ async def test_astream_builds_codex_headers_without_sync_token_read(
}
+async def test_astream_empty_headers_skip_sync_token_read(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An accountless token yields `{}` headers — still no sync read on the loop.
+
+ Guards the deliberate `is not None` check in `_get_request_payload`: an
+ explicitly-built empty dict must be honored as-is, not treated as falsy and
+ routed back through the blocking sync `get_token()`.
+ """
+ provider = AsyncOnlyTokenProvider(account_id=None)
+ model = _build_model(token_provider=provider, originator=None)
+ kwargs_seen: dict[str, Any] = {}
+
+ async def _fake_super_astream(*_a: Any, **kwargs: Any) -> Any:
+ kwargs_seen.update(kwargs)
+ yield "chunk"
+
+ monkeypatch.setattr(ChatOpenAI, "_astream", _fake_super_astream)
+ before_sync = provider.calls
+ received = [chunk async for chunk in model._astream([HumanMessage("hi")])]
+
+ assert received == ["chunk"]
+ assert provider.calls == before_sync
+ assert kwargs_seen["_codex_headers"] == {}
+
+
def test_callable_api_key_returns_provider_token() -> None:
"""The `api_key` callable wired into the SDK must yield the access token."""
provider = FakeTokenProvider(access_token="abc-123")