Debian Codegraph @

src/anthropic/lib/google_cloud/_client.py

raw
1 from __future__ import annotations
2
3 import os
4 import inspect
5 import threading
6 from typing import TYPE_CHECKING, Any, Union, Mapping, TypeVar, Callable, Sequence, Awaitable, cast
7 from functools import partial
8 from typing_extensions import Self, override
9
10 import httpx2
11
12 from ..._types import Timeout, NotGiven, not_given
13 from ..._utils import asyncify, is_given
14 from ..._client import Anthropic, AsyncAnthropic
15 from ..._models import FinalRequestOptions
16 from ..._streaming import Stream, AsyncStream
17 from ..._exceptions import AnthropicError
18 from ..._middleware import MiddlewareInput
19 from ..._base_client import DEFAULT_MAX_RETRIES, BaseClient, merge_headers
20 from .._extras._google_auth import refresh_credentials, load_default_credentials
21
22 # Bind the install-hint extra so a missing google-auth dep points users at
23 # `pip install anthropic[google_cloud]` rather than the vertex extra.
24 _load_adc_credentials = partial(load_default_credentials, extra="google_cloud")
25 _refresh_credentials = partial(refresh_credentials, extra="google_cloud")
26
27 if TYPE_CHECKING:
28 from google.auth.credentials import Credentials as GoogleCredentials # type: ignore
29
30
31 # The gateway base URL; stays overridable via the `base_url` argument and env var.
32 DEFAULT_URL_TEMPLATE = (
33 "https://claude.googleapis.com/v1alpha/projects/{project}/locations/{location}/workspaces/{workspace_id}/invoke"
34 )
35
36 # Used when no location is configured; the gateway should always be addressed
37 # via the global region.
38 DEFAULT_LOCATION = "global"
39
40 TokenProvider = Callable[[], str]
41 AsyncTokenProvider = Callable[[], "str | Awaitable[str]"]
42
43 _HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx2.Client, httpx2.AsyncClient])
44 _DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]])
45
46
47 class _GoogleCredentialsState:
48 """Holder for the Google credentials object, its refresh lock, and the project
49 ADC resolved.
50
51 Shared between a client and its `copy()`/`with_options()` clones (when the
52 credential configuration is inherited) so a lazily-loaded ADC credential is
53 minted once — not once per clone — and concurrent loads/refreshes are
54 serialized: google-auth credential objects are not safe to `refresh()`
55 concurrently.
56 """
57
58 def __init__(self, credentials: GoogleCredentials | None) -> None:
59 self._lock = threading.Lock()
60 self.credentials: GoogleCredentials | None = credentials
61 self.adc_project: str | None = None
62
63 def token(self) -> str:
64 """Return a valid access token, loading ADC / refreshing as needed. Blocking."""
65 with self._lock:
66 if self.credentials is None:
67 self.credentials, self.adc_project = _load_adc_credentials()
68 elif self.credentials.expired or not self.credentials.token:
69 _refresh_credentials(self.credentials)
70
71 token = self.credentials.token
72 if not token:
73 raise AnthropicError("Could not resolve a GCP access token from the configured Google credentials")
74 assert isinstance(token, str)
75 return token
76
77
78 class BaseGoogleCloudClient(BaseClient[_HttpxClientT, _DefaultStreamT]):
79 """Marker base so `_is_base_client()` keeps these clients off the first-party
80 credential-discovery chain (it matches only the exact `Anthropic` /
81 `AsyncAnthropic` classes). Auth is handled entirely by this helper."""
82
83 workspace_id: str | None
84 _project: str | None
85 _location: str
86 _creds_state: _GoogleCredentialsState
87 _base_url_deferred: bool
88 _base_url_overridden: bool
89
90 @property
91 @override
92 def base_url(self) -> httpx2.URL:
93 return self._base_url
94
95 @base_url.setter
96 def base_url(self, url: httpx2.URL | str) -> None:
97 # An explicit post-construction assignment wins over (and cancels) the
98 # pending project back-fill.
99 self._base_url_deferred = False
100 self._base_url = self._enforce_trailing_slash(url if isinstance(url, httpx2.URL) else httpx2.URL(url))
101
102 @property
103 def google_credentials(self) -> GoogleCredentials | None:
104 """The `google.auth` credentials in use (explicit or lazily-loaded ADC), if any.
105
106 Distinct from `.credentials`, which is the base client's first-party
107 credentials provider and is always `None` on this client.
108 """
109 return self._creds_state.credentials
110
111 def _resolve_deferred_base_url(self) -> None:
112 """Derive and set the real base URL once the project is known.
113
114 Called on every request (after the project back-fill from ADC, if any);
115 a no-op once the base URL has been derived.
116 """
117 if not self._base_url_deferred:
118 return
119 if self._project is None:
120 raise AnthropicError(
121 "No `project` was provided and one could not be resolved from Google credentials. "
122 "Pass the `project` argument, set the `ANTHROPIC_GOOGLE_CLOUD_PROJECT` "
123 "environment variable, or provide `base_url` directly."
124 )
125 # Deferred derivation implies auth, and constructing with auth requires a workspace ID.
126 assert self.workspace_id is not None
127 self.base_url = DEFAULT_URL_TEMPLATE.format(
128 project=self._project, location=self._location, workspace_id=self.workspace_id
129 )
130 self._base_url_deferred = False
131
132
133 def _resolve_base_url(
134 *,
135 base_url: str | httpx2.URL | None,
136 project: str | None,
137 location: str,
138 workspace_id: str | None,
139 allow_deferred_project: bool,
140 ) -> str | httpx2.URL | None:
141 """base_url (arg or `ANTHROPIC_GOOGLE_CLOUD_BASE_URL`, resolved by the caller)
142 > derived template.
143
144 Returns `None` when derivation must wait for the project to be back-filled
145 from Google credentials on the first request (`allow_deferred_project`).
146 """
147 if base_url is not None:
148 return base_url
149
150 # Derivation needs the workspace ID in the path; the constructors reject a
151 # missing workspace before calling this without an explicit base_url.
152 assert workspace_id is not None
153 if project is None:
154 if allow_deferred_project:
155 return None
156 raise ValueError(
157 "No `project` was provided. Pass `project`, set the `ANTHROPIC_GOOGLE_CLOUD_PROJECT` "
158 "environment variable, or provide `base_url` directly."
159 )
160 return DEFAULT_URL_TEMPLATE.format(project=project, location=location, workspace_id=workspace_id)
161
162
163 def _reject_skip_auth_conflict(
164 *,
165 skip_auth: bool,
166 token_provider: object | None,
167 credentials: object | None,
168 ) -> None:
169 if skip_auth and (token_provider is not None or credentials is not None):
170 raise ValueError(
171 "`skip_auth` is mutually exclusive with `token_provider` and `credentials`; "
172 "`skip_auth` disables authentication entirely."
173 )
174
175
176 def _project_from_credentials(credentials: GoogleCredentials) -> str | None:
177 """Best-effort project from an explicit credentials object — service-account /
178 impersonated credentials usually know theirs."""
179 for attr in ("project_id", "quota_project_id"):
180 value = getattr(credentials, attr, None)
181 if isinstance(value, str) and value:
182 return value
183 return None
184
185
186 class AnthropicGoogleCloud(BaseGoogleCloudClient[httpx2.Client, Stream[Any]], Anthropic):
187 """Synchronous client for the first-party Anthropic API served through Google's
188 gateway (Claude Platform on Google Cloud).
189
190 The whole first-party surface is proxied verbatim (no URL or body rewriting), so
191 this subclasses the full `Anthropic` client. Authentication is a GCP bearer
192 token.
193 """
194
195 workspace_id: str | None
196 _skip_auth: bool
197
198 def __init__(
199 self,
200 *,
201 project: str | None = None,
202 location: str | None = None,
203 workspace_id: str | None = None,
204 token_provider: TokenProvider | None = None,
205 credentials: GoogleCredentials | None = None,
206 skip_auth: bool = False,
207 base_url: str | httpx2.URL | None = None,
208 timeout: float | Timeout | None | NotGiven = not_given,
209 max_retries: int = DEFAULT_MAX_RETRIES,
210 default_headers: Mapping[str, str] | None = None,
211 default_query: Mapping[str, object] | None = None,
212 http_client: httpx2.Client | None = None,
213 middleware: Sequence[MiddlewareInput] | None = None,
214 _strict_response_validation: bool = False,
215 ) -> None:
216 """Construct a new synchronous Claude Platform on Google Cloud client.
217
218 Auth precedence (first match wins, unless `skip_auth=True`):
219 1. `token_provider` — a callable returning a GCP access token, invoked per request.
220 2. `credentials` — a `google.auth` Credentials object, refreshed as needed.
221 3. Application Default Credentials (`google.auth.default`).
222
223 Args:
224 project: GCP consumer project id (or `ANTHROPIC_GOOGLE_CLOUD_PROJECT`,
225 else `GOOGLE_CLOUD_PROJECT`). Only needed when the base URL must be
226 derived; if omitted there, it is taken from an explicit `credentials`
227 object when it exposes one, or back-filled from ADC on the first request.
228 location: GCP location (or `ANTHROPIC_GOOGLE_CLOUD_LOCATION`). Optional —
229 defaults to `global`, the region the gateway should normally be
230 addressed through.
231 workspace_id: The Anthropic workspace ID (or `ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID`).
232 Required unless `skip_auth` is set with an explicit `base_url`.
233 skip_auth: For pre-authenticated proxies — skips token attachment. A
234 workspace ID is still needed to derive the base URL; pass `base_url`
235 to construct without one. Mutually exclusive with the credential
236 arguments.
237 """
238 _reject_skip_auth_conflict(skip_auth=skip_auth, token_provider=token_provider, credentials=credentials)
239
240 self._skip_auth = skip_auth
241 self._token_provider = token_provider
242 self._creds_state = _GoogleCredentialsState(credentials)
243 if location is None:
244 location = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_LOCATION")
245 if location is None:
246 location = DEFAULT_LOCATION
247 self._location = location
248 if project is None:
249 project = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_PROJECT")
250 if project is None:
251 project = os.environ.get("GOOGLE_CLOUD_PROJECT")
252 if project is None and credentials is not None:
253 project = _project_from_credentials(credentials)
254 self._project = project
255
256 if base_url is None:
257 base_url = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_BASE_URL")
258 # Distinguishes a user-supplied gateway URL from a template-derived one, so
259 # `copy(project=..., location=...)` knows whether to re-derive.
260 self._base_url_overridden = base_url is not None
261
262 if workspace_id is None:
263 workspace_id = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID")
264 # The workspace ID is required unless `skip_auth` is set together with an
265 # explicit base URL — no URL to derive.
266 if workspace_id is None and not (skip_auth and base_url is not None):
267 raise ValueError(
268 "No workspace ID found. Set the `workspace_id` argument or the "
269 "`ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID` environment variable."
270 )
271 self.workspace_id = workspace_id
272
273 resolved_base_url = _resolve_base_url(
274 base_url=base_url,
275 project=self._project,
276 location=self._location,
277 workspace_id=self.workspace_id,
278 # Without auth there are no Google credentials to back-fill the project from.
279 allow_deferred_project=not skip_auth,
280 )
281 self._base_url_deferred = resolved_base_url is None
282
283 super().__init__(
284 # Deferred case: pass an empty (valid) URL so the parent doesn't fall through to
285 # `ANTHROPIC_BASE_URL` / api.anthropic.com; `_prepare_options` derives the real
286 # URL (or raises) before the first request is built.
287 base_url=resolved_base_url if resolved_base_url is not None else "",
288 timeout=timeout,
289 max_retries=max_retries,
290 default_headers=default_headers,
291 default_query=default_query,
292 http_client=http_client,
293 middleware=middleware,
294 _strict_response_validation=_strict_response_validation,
295 )
296 # Never inherit first-party static credentials from the environment — the
297 # base reads ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN when no explicit
298 # credential is passed, which would otherwise leak as `X-Api-Key` to the
299 # gateway host. `auth_headers` is also overridden below as a hard guarantee.
300 self.api_key = None
301 self.auth_token = None
302
303 @property
304 @override
305 def auth_headers(self) -> dict[str, str]:
306 # Auth is a GCP bearer token attached in `_prepare_request`; never emit
307 # first-party `X-Api-Key` / `Authorization` headers from static credentials.
308 return {}
309
310 @override
311 def _validate_headers(self, headers: httpx2.Headers, omitted: frozenset[str]) -> None:
312 # The bearer token is attached per-request in `_prepare_request`, not via
313 # default headers, so the base auth-presence check would false-negative.
314 return
315
316 def _get_token(self) -> str:
317 provider = self._token_provider
318 if provider is not None:
319 token = provider()
320 if inspect.isawaitable(token):
321 cast(Any, token).close()
322 raise AnthropicError(
323 "`token_provider` returned an awaitable. Async token providers are only "
324 "supported on `AsyncAnthropicGoogleCloud`."
325 )
326 return token
327
328 return self._creds_state.token()
329
330 @override
331 def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
332 if not self._skip_auth and self._base_url_deferred:
333 if self._project is None and self._token_provider is None:
334 # An ADC load also resolves the credentials' project; do it here —
335 # independent of token attachment — so the back-fill happens even
336 # when the request carries its own `Authorization` header.
337 self._creds_state.token()
338 self._project = self._creds_state.adc_project
339 self._resolve_deferred_base_url()
340
341 return options
342
343 @override
344 def _prepare_request(self, request: httpx2.Request) -> None:
345 if self._skip_auth:
346 return
347
348 if request.headers.get("Authorization") is not None:
349 # A caller-supplied Authorization header (per-request, default_headers,
350 # or ANTHROPIC_CUSTOM_HEADERS) wins; the check is case-insensitive so
351 # we never emit two conflicting Authorization headers.
352 return
353
354 request.headers["Authorization"] = f"Bearer {self._get_token()}"
355
356 def copy( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] — subclass uses GCP auth
357 self,
358 *,
359 project: str | None = None,
360 location: str | None = None,
361 workspace_id: str | None | NotGiven = not_given,
362 token_provider: TokenProvider | None | NotGiven = not_given,
363 credentials: GoogleCredentials | None | NotGiven = not_given,
364 skip_auth: bool | None = None,
365 base_url: str | httpx2.URL | None = None,
366 timeout: float | Timeout | None | NotGiven = not_given,
367 http_client: httpx2.Client | None = None,
368 middleware: Sequence[MiddlewareInput] | None | NotGiven = not_given,
369 max_retries: int | NotGiven = not_given,
370 default_headers: Mapping[str, str] | None = None,
371 set_default_headers: Mapping[str, str] | None = None,
372 default_query: Mapping[str, object] | None = None,
373 set_default_query: Mapping[str, object] | None = None,
374 _extra_kwargs: Mapping[str, Any] = {},
375 ) -> Self:
376 """Create a new client re-using the current options, with optional overrides.
377
378 Passing either of `token_provider` / `credentials` replaces the
379 inherited credential configuration wholesale — the source not passed is
380 cleared, so an explicit lower-precedence credential takes effect.
381 `workspace_id=None` clears the workspace ID; `project` /
382 `location` overrides re-derive a template-derived base URL.
383 """
384 if default_headers is not None and set_default_headers is not None:
385 raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
386
387 if default_query is not None and set_default_query is not None:
388 raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
389
390 headers = self._custom_headers
391 if default_headers is not None:
392 headers = merge_headers(headers, default_headers)
393 elif set_default_headers is not None:
394 headers = set_default_headers
395
396 params = self._custom_query
397 if default_query is not None:
398 params = {**params, **default_query}
399 elif set_default_query is not None:
400 params = set_default_query
401
402 resolved_skip_auth = skip_auth if skip_auth is not None else self._skip_auth
403 credential_overridden = is_given(token_provider) or is_given(credentials)
404 new_token_provider: TokenProvider | None = None
405 new_credentials: GoogleCredentials | None = None
406 if credential_overridden:
407 new_token_provider = token_provider if is_given(token_provider) else None
408 new_credentials = credentials if is_given(credentials) else None
409 elif not resolved_skip_auth: # don't round-trip credentials into a skip_auth clone
410 new_token_provider = self._token_provider
411 new_credentials = self._creds_state.credentials
412
413 if base_url is None and not self._base_url_overridden:
414 # The current URL is template-derived (or still pending); leave it unset
415 # so __init__ re-derives from the new project/location.
416 new_base_url: str | httpx2.URL | None = None
417 else:
418 new_base_url = base_url if base_url is not None else self.base_url
419
420 client = self.__class__(
421 project=project if project is not None else self._project,
422 location=location if location is not None else self._location,
423 workspace_id=workspace_id if is_given(workspace_id) else self.workspace_id,
424 token_provider=new_token_provider,
425 credentials=new_credentials,
426 skip_auth=resolved_skip_auth,
427 base_url=new_base_url,
428 timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
429 http_client=http_client or self._client,
430 max_retries=max_retries if is_given(max_retries) else self.max_retries,
431 default_headers=headers,
432 default_query=params,
433 middleware=self._middleware if isinstance(middleware, NotGiven) else middleware,
434 _strict_response_validation=self._strict_response_validation,
435 **_extra_kwargs,
436 )
437 if not credential_overridden and not resolved_skip_auth:
438 # Clones share lazily-loaded ADC credentials (and the refresh lock) so a
439 # per-call `with_options()` clone doesn't mint its own token.
440 client._creds_state = self._creds_state
441 return client
442
443 with_options = copy # type: ignore[assignment]
444
445
446 class AsyncAnthropicGoogleCloud(BaseGoogleCloudClient[httpx2.AsyncClient, AsyncStream[Any]], AsyncAnthropic):
447 """Asynchronous client for the first-party Anthropic API served through Google's
448 gateway (Claude Platform on Google Cloud). See `AnthropicGoogleCloud`.
449 """
450
451 workspace_id: str | None
452 _skip_auth: bool
453
454 def __init__(
455 self,
456 *,
457 project: str | None = None,
458 location: str | None = None,
459 workspace_id: str | None = None,
460 token_provider: AsyncTokenProvider | None = None,
461 credentials: GoogleCredentials | None = None,
462 skip_auth: bool = False,
463 base_url: str | httpx2.URL | None = None,
464 timeout: float | Timeout | None | NotGiven = not_given,
465 max_retries: int = DEFAULT_MAX_RETRIES,
466 default_headers: Mapping[str, str] | None = None,
467 default_query: Mapping[str, object] | None = None,
468 http_client: httpx2.AsyncClient | None = None,
469 middleware: Sequence[MiddlewareInput] | None = None,
470 _strict_response_validation: bool = False,
471 ) -> None:
472 """Construct a new asynchronous Claude Platform on Google Cloud client.
473
474 `token_provider` may be sync or async; sync providers are run off the
475 event loop. See `AnthropicGoogleCloud` for the full argument and
476 auth-precedence docs.
477 """
478 _reject_skip_auth_conflict(skip_auth=skip_auth, token_provider=token_provider, credentials=credentials)
479
480 self._skip_auth = skip_auth
481 self._token_provider = token_provider
482 self._creds_state = _GoogleCredentialsState(credentials)
483 if location is None:
484 location = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_LOCATION")
485 if location is None:
486 location = DEFAULT_LOCATION
487 self._location = location
488 if project is None:
489 project = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_PROJECT")
490 if project is None:
491 project = os.environ.get("GOOGLE_CLOUD_PROJECT")
492 if project is None and credentials is not None:
493 project = _project_from_credentials(credentials)
494 self._project = project
495
496 if base_url is None:
497 base_url = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_BASE_URL")
498 self._base_url_overridden = base_url is not None
499
500 if workspace_id is None:
501 workspace_id = os.environ.get("ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID")
502 # The workspace ID is required unless `skip_auth` is set together with an
503 # explicit base URL — no URL to derive.
504 if workspace_id is None and not (skip_auth and base_url is not None):
505 raise ValueError(
506 "No workspace ID found. Set the `workspace_id` argument or the "
507 "`ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID` environment variable."
508 )
509 self.workspace_id = workspace_id
510
511 resolved_base_url = _resolve_base_url(
512 base_url=base_url,
513 project=self._project,
514 location=self._location,
515 workspace_id=self.workspace_id,
516 # Without auth there are no Google credentials to back-fill the project from.
517 allow_deferred_project=not skip_auth,
518 )
519 self._base_url_deferred = resolved_base_url is None
520
521 super().__init__(
522 # Deferred case: pass an empty (valid) URL so the parent doesn't fall through to
523 # `ANTHROPIC_BASE_URL` / api.anthropic.com; `_prepare_options` derives the real
524 # URL (or raises) before the first request is built.
525 base_url=resolved_base_url if resolved_base_url is not None else "",
526 timeout=timeout,
527 max_retries=max_retries,
528 default_headers=default_headers,
529 default_query=default_query,
530 http_client=http_client,
531 middleware=middleware,
532 _strict_response_validation=_strict_response_validation,
533 )
534 self.api_key = None
535 self.auth_token = None
536
537 @property
538 @override
539 def auth_headers(self) -> dict[str, str]:
540 return {}
541
542 @override
543 def _validate_headers(self, headers: httpx2.Headers, omitted: frozenset[str]) -> None:
544 return
545
546 async def _get_token(self) -> str:
547 provider = self._token_provider
548 if provider is not None:
549 if inspect.iscoroutinefunction(provider):
550 token = await provider()
551 assert isinstance(token, str)
552 return token
553 # A plain sync provider may block on a token mint; run it off
554 # the event loop so concurrent requests aren't stalled.
555 token = await asyncify(provider)()
556 if inspect.isawaitable(token):
557 token = await token
558 assert isinstance(token, str)
559 return token
560
561 return await asyncify(self._creds_state.token)()
562
563 @override
564 async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
565 if not self._skip_auth and self._base_url_deferred:
566 if self._project is None and self._token_provider is None:
567 # An ADC load also resolves the credentials' project; do it here —
568 # independent of token attachment — so the back-fill happens even
569 # when the request carries its own `Authorization` header.
570 await asyncify(self._creds_state.token)()
571 self._project = self._creds_state.adc_project
572 self._resolve_deferred_base_url()
573
574 return options
575
576 @override
577 async def _prepare_request(self, request: httpx2.Request) -> None:
578 if self._skip_auth:
579 return
580
581 if request.headers.get("Authorization") is not None:
582 # A caller-supplied Authorization header (per-request, default_headers,
583 # or ANTHROPIC_CUSTOM_HEADERS) wins; the check is case-insensitive so
584 # we never emit two conflicting Authorization headers.
585 return
586
587 request.headers["Authorization"] = f"Bearer {await self._get_token()}"
588
589 def copy( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] — subclass uses GCP auth
590 self,
591 *,
592 project: str | None = None,
593 location: str | None = None,
594 workspace_id: str | None | NotGiven = not_given,
595 token_provider: AsyncTokenProvider | None | NotGiven = not_given,
596 credentials: GoogleCredentials | None | NotGiven = not_given,
597 skip_auth: bool | None = None,
598 base_url: str | httpx2.URL | None = None,
599 timeout: float | Timeout | None | NotGiven = not_given,
600 http_client: httpx2.AsyncClient | None = None,
601 middleware: Sequence[MiddlewareInput] | None | NotGiven = not_given,
602 max_retries: int | NotGiven = not_given,
603 default_headers: Mapping[str, str] | None = None,
604 set_default_headers: Mapping[str, str] | None = None,
605 default_query: Mapping[str, object] | None = None,
606 set_default_query: Mapping[str, object] | None = None,
607 _extra_kwargs: Mapping[str, Any] = {},
608 ) -> Self:
609 """Create a new client re-using the current options, with optional overrides.
610
611 See `AnthropicGoogleCloud.copy` for the override semantics.
612 """
613 if default_headers is not None and set_default_headers is not None:
614 raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
615
616 if default_query is not None and set_default_query is not None:
617 raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
618
619 headers = self._custom_headers
620 if default_headers is not None:
621 headers = merge_headers(headers, default_headers)
622 elif set_default_headers is not None:
623 headers = set_default_headers
624
625 params = self._custom_query
626 if default_query is not None:
627 params = {**params, **default_query}
628 elif set_default_query is not None:
629 params = set_default_query
630
631 resolved_skip_auth = skip_auth if skip_auth is not None else self._skip_auth
632 credential_overridden = is_given(token_provider) or is_given(credentials)
633 new_token_provider: AsyncTokenProvider | None = None
634 new_credentials: GoogleCredentials | None = None
635 if credential_overridden:
636 new_token_provider = token_provider if is_given(token_provider) else None
637 new_credentials = credentials if is_given(credentials) else None
638 elif not resolved_skip_auth: # don't round-trip credentials into a skip_auth clone
639 new_token_provider = self._token_provider
640 new_credentials = self._creds_state.credentials
641
642 if base_url is None and not self._base_url_overridden:
643 # The current URL is template-derived (or still pending); leave it unset
644 # so __init__ re-derives from the new project/location.
645 new_base_url: str | httpx2.URL | None = None
646 else:
647 new_base_url = base_url if base_url is not None else self.base_url
648
649 client = self.__class__(
650 project=project if project is not None else self._project,
651 location=location if location is not None else self._location,
652 workspace_id=workspace_id if is_given(workspace_id) else self.workspace_id,
653 token_provider=new_token_provider,
654 credentials=new_credentials,
655 skip_auth=resolved_skip_auth,
656 base_url=new_base_url,
657 timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
658 http_client=http_client or self._client,
659 max_retries=max_retries if is_given(max_retries) else self.max_retries,
660 default_headers=headers,
661 default_query=params,
662 middleware=self._middleware if isinstance(middleware, NotGiven) else middleware,
663 _strict_response_validation=self._strict_response_validation,
664 **_extra_kwargs,
665 )
666 if not credential_overridden and not resolved_skip_auth:
667 # Clones share lazily-loaded ADC credentials (and the refresh lock) so a
668 # per-call `with_options()` clone doesn't mint its own token.
669 client._creds_state = self._creds_state
670 return client
671
672 with_options = copy # type: ignore[assignment]