Skip to content

Commit 3e63d33

Browse files
authored
feat: add Vertex AI support for the Responses API (#4139)
## Changes being requested Add `vertex(...)` so the standard `OpenAI` and `AsyncOpenAI` clients can send Responses API requests through Google Cloud Vertex AI. Configure a project and location or an explicit API root. Google Application Default Credentials and explicit Google credentials use the optional `openai[vertex]` extra; application-managed token callbacks work with the base package. Credentials are bound to the configured origin, redirects are disabled, and stored-response routes preserve escaped path segments. ## Additional context & links Validated with 36 focused provider tests, Ruff, targeted mypy, and the CI wheel check with and without the Vertex extra. The opt-in live Vertex acceptance test was not run.
1 parent ca54146 commit 3e63d33

9 files changed

Lines changed: 1170 additions & 3 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,9 @@ jobs:
124124
- name: Validate Bedrock wheel
125125
run: uv run --locked --all-extras python scripts/utils/validate-bedrock-wheel.py
126126

127+
- name: Validate Vertex wheel
128+
run: uv run --locked --all-extras python scripts/utils/validate-vertex-wheel.py
129+
127130
- name: Validate HTTPX2 wheel on Python 3.10
128131
run: uv run --locked --all-extras python scripts/utils/validate-httpx2-wheel.py
129132

‎pyproject.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ bedrock = [
5050
"botocore>=1.40.0,<2",
5151
"urllib3>=2.7.0,<3",
5252
]
53+
vertex = ["google-auth[requests]>=2.36,<3"]
5354

5455
[dependency-groups]
5556
dev = [
@@ -66,6 +67,7 @@ dev = [
6667
"trio >=0.22.2",
6768
"pytest-xdist>=3.6.1",
6869
"griffe>=1",
70+
"types-requests>=2.33.0.20261006",
6971
]
7072
pydantic-v1 = ["pydantic>=1.10.26,<2"]
7173
pydantic-v2 = ["pydantic>=2,<3"]
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
from __future__ import annotations
2+
3+
import os
4+
import sys
5+
import tempfile
6+
import subprocess
7+
from pathlib import Path
8+
from collections.abc import Callable
9+
10+
11+
def check_installed(with_vertex: bool) -> None:
12+
from typing import get_type_hints
13+
from importlib import metadata
14+
from unittest.mock import patch
15+
16+
import httpx2
17+
18+
import openai
19+
from openai.providers import vertex
20+
21+
assert Path(openai.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()), openai.__file__
22+
assert "credentials" in get_type_hints(vertex)
23+
24+
def handle(request: httpx2.Request) -> httpx2.Response:
25+
assert request.headers["authorization"] == "Bearer fixture-token"
26+
return httpx2.Response(200, json={"id": "resp_fixture", "object": "response", "output": []})
27+
28+
def send(token_provider: Callable[[], str] | None = None) -> None:
29+
with openai.OpenAI(
30+
provider=vertex(base_url="https://vertex.example/v1", token_provider=token_provider),
31+
http_client=httpx2.Client(transport=httpx2.MockTransport(handle), trust_env=False),
32+
) as client:
33+
client.responses.create(model="fixture", input="hello")
34+
35+
if with_vertex:
36+
from google.oauth2.credentials import Credentials
37+
38+
create_credentials: Callable[[str], object] = Credentials
39+
with patch("google.auth.default", return_value=(create_credentials("fixture-token"), "fixture-project")):
40+
send()
41+
else:
42+
try:
43+
metadata.version("google-auth")
44+
except metadata.PackageNotFoundError:
45+
pass
46+
else:
47+
raise AssertionError("The base wheel installed google-auth")
48+
49+
send(lambda: "fixture-token")
50+
try:
51+
send()
52+
except openai.OpenAIError as error:
53+
assert str(error) == "Install openai[vertex] to use Google credentials, or supply token_provider."
54+
else:
55+
raise AssertionError("Vertex ADC should require the vertex extra")
56+
57+
58+
def main() -> None:
59+
wheels = list(Path("dist").glob("*.whl"))
60+
if len(wheels) != 1:
61+
raise RuntimeError(f"Expected exactly one wheel in dist/, found: {wheels}")
62+
63+
wheel = wheels[0].resolve()
64+
install_env = os.environ.copy()
65+
# CI builds openai from source by default; this check must install the wheel it just built.
66+
install_env.pop("UV_NO_BINARY_PACKAGE", None)
67+
with tempfile.TemporaryDirectory() as directory:
68+
venv = Path(directory) / "venv"
69+
python = venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
70+
subprocess.run(["uv", "venv", "--python", sys.executable, str(venv)], check=True)
71+
for requirement, mode in ((str(wheel), "--plain"), (f"{wheel}[vertex]", "--vertex")):
72+
subprocess.run(["uv", "pip", "install", "--python", str(python), requirement], env=install_env, check=True)
73+
subprocess.run([str(python), "-I", str(Path(__file__).resolve()), mode], cwd=directory, check=True)
74+
75+
76+
if __name__ == "__main__":
77+
if sys.argv[1:] == ["--plain"]:
78+
check_installed(with_vertex=False)
79+
elif sys.argv[1:] == ["--vertex"]:
80+
check_installed(with_vertex=True)
81+
elif len(sys.argv) == 1:
82+
main()
83+
else:
84+
raise SystemExit("usage: validate-vertex-wheel.py [--plain | --vertex]")

‎src/openai/providers/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from .vertex import vertex as vertex
12
from .bedrock import bedrock as bedrock
23

3-
__all__ = ["bedrock"]
4+
__all__ = ["bedrock", "vertex"]

‎src/openai/providers/vertex.py‎

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
from __future__ import annotations
2+
3+
import os
4+
import re
5+
import inspect
6+
import threading
7+
from typing import TYPE_CHECKING, Any, Callable, Awaitable, cast
8+
from dataclasses import field, dataclass
9+
from typing_extensions import override
10+
11+
import anyio
12+
import httpx2
13+
import anyio.to_thread
14+
15+
from .._models import FinalRequestOptions
16+
from .._provider import _Provider, _create_provider, _ProviderRuntime
17+
from .._exceptions import OpenAIError, APITimeoutError
18+
19+
if TYPE_CHECKING:
20+
from google.auth.credentials import Credentials
21+
else:
22+
# Keep runtime type introspection available without importing the optional dependency.
23+
Credentials = Any
24+
25+
VertexTokenProvider = Callable[[], str | Awaitable[str]]
26+
_CLOUD_PLATFORM_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
27+
28+
29+
@dataclass(frozen=True)
30+
class _VertexDefinition:
31+
base_url: httpx2.URL
32+
token_provider: VertexTokenProvider | None = field(repr=False)
33+
credentials: Credentials | None = field(repr=False)
34+
name: str = field(default="vertex", init=False)
35+
36+
def configure(self) -> _ProviderRuntime:
37+
# ADC discovery/refresh belongs to this client. google-auth caches until expiry.
38+
lock = threading.Lock()
39+
credentials: Credentials | None = None
40+
41+
def adc_headers(request: httpx2.Request) -> dict[str, str]:
42+
nonlocal credentials
43+
limits = request.extensions.get("timeout", {})
44+
pool_timeout = limits.get("pool")
45+
acquired = lock.acquire() if pool_timeout is None else lock.acquire(timeout=max(0, pool_timeout))
46+
if not acquired:
47+
raise APITimeoutError(request=request)
48+
try:
49+
try:
50+
import requests
51+
import google.auth
52+
import google.auth.credentials
53+
from google.auth.exceptions import TransportError
54+
from google.auth.transport.requests import Request
55+
except ImportError as exc:
56+
raise OpenAIError(
57+
"Install openai[vertex] to use Google credentials, or supply token_provider."
58+
) from exc
59+
# No retained Session: client close/cancellation never leaves a Google transport open.
60+
with requests.Session() as session:
61+
62+
class BoundedRequest(Request):
63+
@override
64+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
65+
# Requests accepts separate connect/read limits, including None.
66+
kwargs["timeout"] = (limits.get("connect"), limits.get("read"))
67+
try:
68+
return super().__call__(*args, **kwargs) # type: ignore[no-untyped-call]
69+
except TransportError as exc:
70+
if isinstance(exc.__cause__, requests.exceptions.Timeout):
71+
raise APITimeoutError(request=request) from None
72+
raise
73+
74+
bounded_transport = BoundedRequest(session)
75+
if credentials is None:
76+
if self.credentials is None:
77+
# google-auth does not type its request or returned credentials.
78+
discover = cast(
79+
"Callable[..., tuple[Credentials, str | None]]", cast(Any, google.auth).default
80+
)
81+
credentials, _ = discover(scopes=_CLOUD_PLATFORM_SCOPES, request=bounded_transport)
82+
else:
83+
scope_credentials = cast(
84+
"Callable[..., Credentials]", cast(Any, google.auth.credentials).with_scopes_if_required
85+
)
86+
credentials = scope_credentials(self.credentials, scopes=_CLOUD_PLATFORM_SCOPES)
87+
headers: dict[str, str] = {}
88+
credentials.before_request(bounded_transport, request.method, str(request.url), headers) # type: ignore[no-untyped-call]
89+
return headers
90+
except (OpenAIError, APITimeoutError):
91+
raise
92+
except Exception:
93+
# Credential exceptions can include request bodies or private keys.
94+
raise OpenAIError(
95+
"Vertex Google authentication failed. Check ADC, project access and credential expiry."
96+
) from None
97+
finally:
98+
lock.release()
99+
100+
def transform(options: FinalRequestOptions) -> FinalRequestOptions:
101+
# Prevent even a user-configured http client from following redirects with credentials.
102+
options.follow_redirects = False
103+
return options
104+
105+
def prepare(request: httpx2.Request) -> None:
106+
origin = (request.url.scheme, request.url.host, request.url.port)
107+
configured = (self.base_url.scheme, self.base_url.host, self.base_url.port)
108+
if origin != configured:
109+
raise OpenAIError("Refusing to send Vertex credentials outside the configured origin.")
110+
if any(
111+
header in request.headers
112+
for header in ("authorization", "api-key", "openai-organization", "openai-project")
113+
):
114+
raise OpenAIError(
115+
"Vertex owns authentication; remove OpenAI project/organization and custom Authorization or api-key headers."
116+
)
117+
# Stored responses use the beta outer Google API version. Explicit proxy roots
118+
# without the Google resource shape are left intact. Match the raw path
119+
# to preserve escaped path segments.
120+
raw_path = request.url.raw_path
121+
if request.method in ("GET", "DELETE") and re.match(
122+
rb"^/v1/projects/[^/]+/locations/[^/]+/publishers/[^/]+/v1/responses/[^/]+(?:/|$)",
123+
raw_path.partition(b"?")[0],
124+
):
125+
request.url = request.url.copy_with(raw_path=raw_path.replace(b"/v1/", b"/v1beta1/", 1))
126+
127+
def set_token(request: httpx2.Request, token: object) -> None:
128+
if not isinstance(token, str) or not token.strip() or any(ord(c) < 33 or ord(c) > 126 for c in token):
129+
raise OpenAIError(
130+
"Vertex token provider must return a nonempty bearer token suitable for an HTTP header."
131+
)
132+
request.headers["Authorization"] = f"Bearer {token}"
133+
134+
def prepare_sync(request: httpx2.Request) -> None:
135+
prepare(request)
136+
if self.token_provider is None:
137+
request.headers.update(adc_headers(request))
138+
else:
139+
try:
140+
token = self.token_provider()
141+
except Exception:
142+
raise OpenAIError("Vertex token provider failed.") from None
143+
if inspect.isawaitable(token):
144+
if inspect.iscoroutine(token):
145+
token.close()
146+
raise OpenAIError("Use AsyncOpenAI with an async Vertex token provider.")
147+
set_token(request, token)
148+
149+
async def prepare_async(request: httpx2.Request) -> None:
150+
prepare(request)
151+
try:
152+
if self.token_provider is None:
153+
headers = await anyio.to_thread.run_sync(adc_headers, request, abandon_on_cancel=True)
154+
request.headers.update(headers)
155+
else:
156+
with anyio.fail_after(request.extensions.get("timeout", {}).get("read")) as scope:
157+
token = self.token_provider()
158+
if inspect.isawaitable(token):
159+
token = await token
160+
# Blocking callbacks cannot be interrupted by an async cancel scope.
161+
if anyio.current_time() >= scope.deadline:
162+
raise APITimeoutError(request=request)
163+
set_token(request, token)
164+
except TimeoutError:
165+
raise APITimeoutError(request=request) from None
166+
except OpenAIError:
167+
raise
168+
except Exception:
169+
raise OpenAIError("Vertex token provider failed.") from None
170+
171+
return _ProviderRuntime(
172+
name=self.name,
173+
base_url=self.base_url,
174+
transform_request=transform,
175+
prepare_request=prepare_sync,
176+
prepare_async_request=prepare_async,
177+
)
178+
179+
180+
def vertex(
181+
*,
182+
project: str | None = None,
183+
location: str | None = None,
184+
base_url: str | httpx2.URL | None = None,
185+
token_provider: VertexTokenProvider | None = None,
186+
credentials: Credentials | None = None,
187+
) -> _Provider:
188+
"""Configure normal OpenAI Responses calls for Vertex. ADC is lazy and requires openai[vertex].
189+
190+
Project and location fall back to GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION.
191+
An explicit base_url is the complete API root before /responses and takes precedence.
192+
On AsyncOpenAI, token_provider runs on the event loop and must not block it.
193+
"""
194+
if token_provider is not None and credentials is not None:
195+
raise OpenAIError("Set only one of credentials and token_provider.")
196+
if base_url is None:
197+
project = project or os.environ.get("GOOGLE_CLOUD_PROJECT")
198+
location = location or os.environ.get("GOOGLE_CLOUD_LOCATION")
199+
# Legacy domain-scoped projects include dots and a colon; exclude dot path segments.
200+
if not project or not re.fullmatch(r"[a-zA-Z0-9_-][a-zA-Z0-9_.:-]*", project):
201+
raise OpenAIError("Vertex requires a project ID (project or GOOGLE_CLOUD_PROJECT).")
202+
if not location or not re.fullmatch(r"[a-z0-9-]+", location):
203+
raise OpenAIError("Vertex requires a location (location or GOOGLE_CLOUD_LOCATION).")
204+
host = "aiplatform.googleapis.com" if location == "global" else f"{location}-aiplatform.googleapis.com"
205+
base_url = f"https://{host}/v1/projects/{project}/locations/{location}/publishers/openai/v1"
206+
url = httpx2.URL(base_url)
207+
if url.scheme not in ("http", "https") or not url.host or url.username or url.password or url.query or url.fragment:
208+
raise OpenAIError("Vertex base_url must be an HTTP(S) API root without credentials, query or fragment.")
209+
host = url.host.rstrip(".")
210+
if url.scheme != "https" and (host == "googleapis.com" or host.endswith(".googleapis.com")):
211+
raise OpenAIError("Google Vertex endpoints require HTTPS.")
212+
return _create_provider(_VertexDefinition(base_url=url, token_provider=token_provider, credentials=credentials))
213+
214+
215+
__all__ = ["vertex", "VertexTokenProvider"]

0 commit comments

Comments
 (0)