openai-python icon indicating copy to clipboard operation
openai-python copied to clipboard

feat(client): opt-in httpx2 backend via an openai[httpx2] extra

Open peterlundberg opened this issue 4 months ago • 2 comments

  • [x] I understand that this repository is auto-generated and my pull request may not be merged

Changes being requested

Draft, for reference and discussion — a concrete example of what supporting httpx2 would actually take, prompted by #3375 (consider migrating from httpx to httpx2). Opt-in only; zero behaviour change unless the extra is installed and the client is explicitly constructed with an httpx2 client. I'm not attached to this shape: happy to rework it toward a different approach, or for this to simply be closed if the team lands elsewhere — it will have served its purpose either way.

An opt-in openai[httpx2] extra, mirroring the ergonomics of the accepted openai[aiohttp] extra:

pip install openai[httpx2]
from openai import OpenAI, DefaultHttpx2Client

client = OpenAI(http_client=DefaultHttpx2Client())

DefaultAsyncHttpx2Client mirrors it for AsyncOpenAI.

Design

_httpx2_compat.py (new leaf module, guarded try: import httpx2) centralises everything: client-type tuples, exception tuples (TIMEOUT_EXCEPTIONS, HTTP_STATUS_ERRORS, STREAM_CONSUMED_ERRORS, REQUEST_NOT_READ_ERRORS), a URL-coercion helper, HTTPX2_DEFAULT_TIMEOUT, human-readable accepted-type names for error messages, and Default{,Async}Httpx2Client (with RuntimeError stubs and TYPE_CHECKING aliases to httpx.* when the extra is absent — the same pattern as DefaultAioHttpClient).

Other files then need only substitutions:

  • two isinstance(http_client, httpx.{,Async}Client) gates → *_HTTP_CLIENT_TYPES tuples (and the TypeError message names both accepted types when the extra is installed)
  • except httpx.TimeoutException / except httpx.HTTPStatusError (×2 each) → both-hierarchy tuples; likewise StreamConsumed in _response.py, the timeout tuple in the assistants streaming helper, and RequestNotRead in the Bedrock SigV4 body-signing path
  • _build_request: url=coerce_httpx2_request_url(self._client, prepared_url) — httpx2's build_request rejects a classic httpx.URL (accepts str or httpx2.URL), so httpx2 clients get str(url); classic clients are untouched
  • the default-timeout structural compare also excludes HTTPX2_DEFAULT_TIMEOUT, so a bare httpx2.Client() gets the SDK's 600s default rather than httpx2's 5s (parity with how a bare httpx.Client() is treated today)
  • logging.getLogger("httpx2") joins the log-level setup; __init__.py gains only the two export lines (same place the DefaultAioHttpClient export lives)

Verification

  • Full existing suite unchanged and green (incl. pydantic-v1 session); pyright-strict + mypy green on the 3.9 floor.
  • httpx2 suite: 34 tests via a dedicated nox -s test-httpx2 session on 3.10–3.14 — isinstance gates, both timeout footguns, URL coercion, status→SDK-error mapping, retries (incl. x-stainless-retry-count), Bedrock body-signing seam, graceful degradation without the extra (subprocess-forced absence).
  • Commits are split per concern (deps → feat → tests → docs → CI → review fixes) for cherry-pickability.

Additional context & links

Why

httpx has effectively stalled: no stable release since v0.28.1 (Dec 2024), and issues/ discussions were closed off repo-wide in Feb 2026 (encode/httpx#3784). The ecosystem is moving to Pydantic's maintained fork, httpx2. For example, Starlette's test client now prefers httpx2 and warns on plain httpx(Kludex/starlette#3291) with the author calling it "the least annoying path forward for every consumer." Keeping an unmaintained library on the live request path of every SDK consumer is the underlying concern; this PR exists to make the "what would supporting an alternative actually take" side of that discussion concrete, not to insist on this particular answer.

Honest caveat: this is heavier than the aiohttp extra, and why

openai[aiohttp] is transport-shaped: DefaultAioHttpClient is still an httpx.AsyncClient, it only swaps the network transport, so it sails through every existing isinstance/except httpx.* check untouched.

httpx2 is a separate library — its own Client/AsyncClient, its own exception hierarchy (httpx2.TimeoutException is not httpx.TimeoutException), its own Response. So an httpx2 client is not an httpx.AsyncClient and does not raise httpx.*. Supporting it requires widening the SDK's type/exception checks to both backends. That cost is inherent — not a design choice that can be avoided by mimicking the aiohttp shape.

Where this may really belong: a note on Stainless routing

From the outside, the httpx coupling doesn't appear to live in this SDK's spec-generated code: _base_client.py and the other runtime modules carry no "generated from our OpenAPI spec" header and look near-identical across Stainless-generated SDKs (e.g. anthropic-sdk-python, which also ships the same aiohttp = ["aiohttp", "httpx_aiohttp>=0.1.9"] extra). How that runtime is actually factored and maintained is only visible to the Stainless/OpenAI folks — apologies if this is mis-aimed — but two things seem worth stating:

  1. This may not be openai-python's decision alone. If that runtime is shared, the durable fix would sit at the Stainless level, where it could flow to every generated Python SDK at once. If this PR ends up being useful mainly as a spec for that conversation, that's a fine outcome.
  2. The diff is shaped with that in mind. Stainless's public docs describe custom code as persisting via a semantic three-way merge on regeneration, which suggests every hand-modified line in a runtime file is a recurring merge surface. This PR tries to minimise that surface: all httpx2 knowledge lives in one new leaf module, and runtime files get only one-line substitutions that should be mechanical to express at the template level — if that's the right place for them.

Things I'd want a maintainer's call on

  • Python support: httpx2 requires 3.10+ (it dropped 3.9). The extra carries a python_version >= '3.10' marker, so it installs nothing on 3.9.
  • Testing: respx doesn't support httpx2 (lundberg/respx#316), so the tests use httpx2's own MockTransport in standalone files (generated tests/test_client.py/ conftest.py untouched). httpx2 is absent from the 3.9-floored dev lock, so the dedicated nox -s test-httpx2 session installs the extra on 3.10+ and runs the suite as required, not skippable. A 3.10+ CI job would want to call it.
  • cast_to=httpx.Response: with an httpx2 backend this returns a duck-compatible httpx2.Response (not an isinstance of httpx.Response); cast_to=httpx2.Response isn't a recognised sentinel. Kept as a documented limitation — happy to add a backend-neutral sentinel if preferred.
  • Timeout parity footgun: a client whose timeout equals httpx2's own default (5s) is structurally indistinguishable from "not customised" and gets the SDK default — same as classic httpx today. Documented in the README caveats with the workaround.
  • Typing: httpx2 ships py.typed; the TYPE_CHECKING aliases keep pyright-strict + mypy green on 3.9 (where httpx2 isn't installable), mirroring the aiohttp approach.
  • Adjacent asks: the TCP-keepalive requests (#3269, #3368) and the HTTP/2-default asks (#3476, #3477) circle the same underlying question as this PR — how much of the HTTP stack should be swappable or configurable. An opt-in backend extra is one possible shape for that; a more general pluggable-transport story (in the SDK or on the Stainless side) would be another. Happy to rework toward whichever direction is preferred.

Disclosure: this implementation and write-up were produced with AI assistance; I have reviewed, adjusted, and verified all of it myself to the best of my ability.

peterlundberg avatar Jul 09 '26 20:07 peterlundberg

This doesn't actually implement HTTP/2. httpx2 here is a distinct forked HTTP library, not HTTP/2 protocol support. It doesn't touch http2= anywhere in _base_client.py. This looks like it's solving a different problem than #3476 asked for, and the scope is much larger than the issue calls for?

amirhosseinghanipour avatar Jul 25 '26 22:07 amirhosseinghanipour

@amirhosseinghanipour I don't think this PR is about HTTP/2 but more so about replacing the abandoned httpx python package. See this issue: https://github.com/openai/openai-python/issues/3375

mve avatar Jul 29 '26 13:07 mve

Justin, I could work on that and also fix the conflicts. But before that, I wonder what your and or openai's stance on https://github.com/openai/openai-python/issues/3375#issuecomment-4961766028 is - ie will something come from stainless and/or should something more flexible with @runtime_checkable Protocol be considered?

peterlundberg avatar Aug 04 '26 20:08 peterlundberg

Hold on. #3524 seams to have applied most of this already, was created after this PR, and is merged. Do you want anything from this PR or should I close it? Anything else you would want help on?

peterlundberg avatar Aug 04 '26 21:08 peterlundberg

Hi @peterlundberg — thank you for taking the time to put this together and for calling attention to HTTPX2 support. I double-checked the current main branch, and the underlying change is already available in https://github.com/openai/openai-python/commit/ae8c3d5d: the SDK now uses HTTPX2 as its supported default backend throughout the sync and async clients, rather than requiring an opt-in extra.

Since the behavior you were aiming for is already covered, I’m going to close this PR to keep the queue tidy. We really appreciate the contribution and the care you put into improving the SDK!

jbeckwith-oai avatar Aug 12 '26 21:08 jbeckwith-oai