|
| 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