Debian Codegraph @

src/anthropic/_client.py

raw
1 from __future__ import annotations
2
3 import os
4 from typing import TYPE_CHECKING, Any, Mapping, TypeVar, Sequence
5 from typing_extensions import Self, override
6
7 import httpx2
8
9 from . import _exceptions
10 from ._qs import Querystring
11 from ._types import Omit, Timeout, NotGiven, RequestOptions, not_given
12 from ._utils import (
13 is_given,
14 is_mapping_t,
15 get_async_library,
16 )
17 from ._compat import model_copy, cached_property
18 from ._models import FinalRequestOptions
19 from ._version import __version__
20 from ._streaming import Stream as Stream, AsyncStream as AsyncStream
21 from ._exceptions import APIStatusError
22 from ._middleware import MiddlewareInput
23 from ._base_client import (
24 DEFAULT_MAX_RETRIES,
25 SyncAPIClient,
26 AsyncAPIClient,
27 merge_headers,
28 )
29
30 # --- credentials support (hand-written, upstream to Stainless) ---
31 from .lib.credentials import (
32 TokenCache,
33 InMemoryConfig,
34 AccessTokenAuth,
35 CredentialsFile,
36 AccessTokenProvider,
37 BaseURLBoundProvider,
38 AsyncAccessTokenProvider,
39 default_credentials,
40 )
41 from .lib.credentials._auth import (
42 warn_env_static_shadows_auto_discovery,
43 warn_explicit_static_shadows_credentials,
44 )
45 from .lib.credentials._close import has_async_close, close_credentials, async_close_credentials
46 from .lib.credentials._types import is_async_token_provider
47 from .lib.credentials._constants import _has_auto_discoverable_credentials
48
49
50 def _is_base_client(client: object) -> bool:
51 """True only for the base `Anthropic` / `AsyncAnthropic` classes, not subclasses.
52
53 Subclasses (`AnthropicAWS`, `AnthropicFoundry`) have their own auth paths
54 and must not run the credential chain or forward `credentials` through their
55 `__init__` (which doesn't accept the kwarg).
56 """
57 return type(client) in (Anthropic, AsyncAnthropic)
58
59
60 _ProviderT = TypeVar(
61 "_ProviderT", "AccessTokenProvider | None", "AccessTokenProvider | AsyncAccessTokenProvider | None"
62 )
63
64
65 def _bind_credentials_base_url(credentials: _ProviderT, base_url: str) -> _ProviderT:
66 """Return the provider this client should exchange tokens through.
67
68 See `BaseURLBoundProvider`; any other provider (plain callables,
69 custom impls) is returned untouched and resolves its own exchange URL.
70 """
71 if isinstance(credentials, BaseURLBoundProvider):
72 return credentials.for_base_url(base_url)
73 return credentials
74
75
76 def _keeps_base_url(current: httpx2.URL, requested: str | httpx2.URL | None) -> bool:
77 """Whether a `copy()` stays on the parent's deployment.
78
79 Tokens are only valid for the deployment that minted them, so the parent's
80 `TokenCache` is only shared in that case.
81 """
82 return requested is None or str(httpx2.URL(requested)).rstrip("/") == str(current).rstrip("/")
83
84
85 def _warn_explicit_shadow(*, api_key: str | None, auth_token: str | None, credentials: object) -> None:
86 """Warn when an explicit `api_key=` / `auth_token=` argument shadows
87 an explicit `credentials=` provider. Call *after* any copy-inheritance
88 merging so the params reflect the resolved values."""
89 if credentials is None:
90 return
91 if api_key is not None:
92 warn_explicit_static_shadows_credentials("api_key")
93 if auth_token is not None:
94 warn_explicit_static_shadows_credentials("auth_token")
95
96
97 def _warn_env_shadow(*, api_key: str | None, auth_token: str | None) -> None:
98 """Warn when an `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` from the
99 environment is set alongside signals that would normally drive profile /
100 federation auto-discovery (`ANTHROPIC_PROFILE`, a `configs/` directory,
101 or the workload-identity env trio). Per the credential-precedence spec,
102 the static credential wins and auto-discovery is silently skipped."""
103 if not _has_auto_discoverable_credentials():
104 return
105 if api_key is not None and os.environ.get("ANTHROPIC_API_KEY"):
106 warn_env_static_shadows_auto_discovery("ANTHROPIC_API_KEY")
107 if auth_token is not None and os.environ.get("ANTHROPIC_AUTH_TOKEN"):
108 warn_env_static_shadows_auto_discovery("ANTHROPIC_AUTH_TOKEN")
109
110
111 # --- end credentials support ---
112
113 if TYPE_CHECKING:
114 from .resources import beta, files, models, skills, messages
115 from .resources.files import Files, AsyncFiles
116 from .resources.models import Models, AsyncModels
117 from .resources.beta.beta import Beta, AsyncBeta
118 from .resources.skills.skills import Skills, AsyncSkills
119 from .resources.messages.messages import Messages, AsyncMessages
120
121 __all__ = ["Timeout", "RequestOptions", "Anthropic", "AsyncAnthropic", "Client", "AsyncClient"]
122
123
124 _CLIENT_LEVEL_HEADER_PARAMS = frozenset(("anthropic-workspace-id", "anthropic-user-profile-id"))
125
126
127 def _keep_client_header_params(options: FinalRequestOptions) -> FinalRequestOptions:
128 """Per-request header params arrive as `Omit` when unset, which would strip a value the
129 client itself sends (e.g. `AnthropicAWS(workspace_id=...)`, a credentials profile's
130 `workspace_id`, or `default_headers`). Drop those so the client-level header survives."""
131 headers = options.headers
132 if not is_given(headers) or not any(
133 name.lower() in _CLIENT_LEVEL_HEADER_PARAMS and isinstance(value, Omit) for name, value in headers.items()
134 ):
135 return options
136
137 options = model_copy(options)
138 options.headers = {
139 name: value
140 for name, value in headers.items()
141 if not (name.lower() in _CLIENT_LEVEL_HEADER_PARAMS and isinstance(value, Omit))
142 }
143 return options
144
145
146 class Anthropic(SyncAPIClient):
147 # client options
148 api_key: str | None
149 auth_token: str | None
150 webhook_key: str | None
151 credentials: AccessTokenProvider | None
152 _token_cache: TokenCache | None
153 _custom_auth: AccessTokenAuth | None
154
155 def __init__(
156 self,
157 *,
158 api_key: str | None = None,
159 auth_token: str | None = None,
160 credentials: AccessTokenProvider | None = None,
161 config: Mapping[str, Any] | None = None,
162 profile: str | None = None,
163 webhook_key: str | None = None,
164 base_url: str | httpx2.URL | None = None,
165 timeout: float | Timeout | None | NotGiven = not_given,
166 max_retries: int = DEFAULT_MAX_RETRIES,
167 default_headers: Mapping[str, str] | None = None,
168 default_query: Mapping[str, object] | None = None,
169 # Configure a custom httpx2 client.
170 # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
171 # See the [httpx2 documentation](https://httpx2.pydantic.dev/api/#client) for more details.
172 http_client: httpx2.Client | None = None,
173 middleware: Sequence[MiddlewareInput] | None = None,
174 # Enable or disable schema validation for data returned by the API.
175 # When enabled an error APIResponseValidationError is raised
176 # if the API responds with invalid data for the expected schema.
177 #
178 # This parameter may be removed or changed in the future.
179 # If you rely on this feature, please open a GitHub issue
180 # outlining your use-case to help us decide if it should be
181 # part of our public interface in the future.
182 _strict_response_validation: bool = False,
183 _token_cache: TokenCache | None | NotGiven = not_given,
184 ) -> None:
185 """Construct a new synchronous Anthropic client instance.
186
187 Credentials are resolved in the following order (first match wins):
188
189 1. Explicit constructor arguments — `api_key=`, `auth_token=`,
190 `credentials=`, `config=`, or `profile=`. When any of these
191 is passed, environment variables are not consulted for credentials.
192 2. `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` environment
193 variables.
194 3. `ANTHROPIC_PROFILE` environment variable — loads the named
195 profile from `<config_dir>/configs/<profile>.json`.
196 4. Workload identity federation environment variables —
197 `ANTHROPIC_IDENTITY_TOKEN[_FILE]` +
198 `ANTHROPIC_FEDERATION_RULE_ID` + `ANTHROPIC_ORGANIZATION_ID`.
199 5. The active profile on disk — the profile named by
200 `<config_dir>/active_config`, or `default`.
201
202 `credentials=`, `config=`, and `profile=` are mutually exclusive.
203
204 If a static credential is supplied alongside a credentials provider
205 (`credentials=` / `config=` / `profile=`), or if
206 `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` is set alongside a
207 profile or federation configuration, the static credential takes
208 precedence and a one-shot warning is logged on the `anthropic`
209 logger.
210 """
211 # --- credentials support (hand-written, upstream to Stainless) ---
212 # Explicit ctor args are total. If the caller passed any explicit
213 # credential argument, do NOT read credential env vars.
214 has_explicit_credential = (
215 api_key is not None
216 or auth_token is not None
217 or credentials is not None
218 or config is not None
219 or profile is not None
220 )
221 if not has_explicit_credential:
222 api_key = os.environ.get("ANTHROPIC_API_KEY") or None
223 auth_token = os.environ.get("ANTHROPIC_AUTH_TOKEN") or None
224 self.api_key = api_key
225 self.auth_token = auth_token
226 # --- end credentials support ---
227
228 if webhook_key is None:
229 webhook_key = os.environ.get("ANTHROPIC_WEBHOOK_SIGNING_KEY")
230 self.webhook_key = webhook_key
231
232 if base_url is None:
233 base_url = os.environ.get("ANTHROPIC_BASE_URL")
234 # base_url precedence: kwarg > ANTHROPIC_BASE_URL > profile config
235 # (filled in below from default_credentials) > hardcoded default.
236 # Track whether the user supplied one so the profile only fills the
237 # gap, never overrides.
238 base_url_is_explicit = base_url is not None
239 if base_url is None:
240 base_url = f"https://api.anthropic.com"
241
242 custom_headers_env = os.environ.get("ANTHROPIC_CUSTOM_HEADERS")
243 if custom_headers_env is not None:
244 parsed: dict[str, str] = {}
245 for line in custom_headers_env.split("\n"):
246 colon = line.find(":")
247 if colon >= 0:
248 parsed[line[:colon].strip()] = line[colon + 1 :].strip()
249 default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})}
250
251 # --- credentials support (hand-written, upstream to Stainless) ---
252 credential_headers: dict[str, str] = {}
253 if config is not None:
254 if credentials is not None or profile is not None:
255 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
256 in_memory = InMemoryConfig(dict(config))
257 credentials = in_memory
258 credential_headers = in_memory.extra_headers()
259 if not base_url_is_explicit and in_memory.resolved_base_url:
260 base_url = in_memory.resolved_base_url
261 elif profile is not None:
262 if credentials is not None:
263 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
264 creds_file = CredentialsFile(profile=profile)
265 credentials = creds_file
266 credential_headers = creds_file.extra_headers()
267 if not base_url_is_explicit and creds_file.resolved_base_url:
268 base_url = creds_file.resolved_base_url
269 if credentials is None and api_key is None and auth_token is None and _is_base_client(self):
270 result = default_credentials(base_url=str(base_url) if base_url else "https://api.anthropic.com")
271 if result is not None:
272 credentials = result.provider
273 credential_headers = result.extra_headers
274 if not base_url_is_explicit and result.base_url:
275 base_url = result.base_url
276
277 if is_async_token_provider(credentials):
278 raise TypeError("`Anthropic` cannot await an async `credentials` provider; use `AsyncAnthropic` instead.")
279 if has_async_close(credentials):
280 raise TypeError(
281 "`Anthropic` cannot await this `credentials` provider's `async def close()`; use `AsyncAnthropic` instead."
282 )
283
284 credentials = _bind_credentials_base_url(credentials, str(base_url))
285 self.credentials = credentials
286 _warn_explicit_shadow(api_key=api_key, auth_token=auth_token, credentials=credentials)
287 if _is_base_client(self):
288 # Subclasses never run the auto-discovery chain (gated on `_is_base_client`
289 # below), so nothing is shadowed and the warning would be spurious.
290 _warn_env_shadow(api_key=api_key, auth_token=auth_token)
291 if not isinstance(_token_cache, NotGiven):
292 self._token_cache = _token_cache
293 else:
294 self._token_cache = TokenCache(credentials) if credentials is not None else None
295 self._custom_auth = AccessTokenAuth(self._token_cache) if self._token_cache is not None else None
296 if credential_headers:
297 default_headers = {**credential_headers, **(default_headers or {})}
298 # --- end credentials support ---
299
300 super().__init__(
301 version=__version__,
302 base_url=base_url,
303 max_retries=max_retries,
304 timeout=timeout,
305 http_client=http_client,
306 custom_headers=default_headers,
307 custom_query=default_query,
308 middleware=middleware,
309 _strict_response_validation=_strict_response_validation,
310 )
311
312 self._default_stream_cls = Stream
313
314 @cached_property
315 def messages(self) -> Messages:
316 from .resources.messages import Messages
317
318 return Messages(self)
319
320 @cached_property
321 def models(self) -> Models:
322 from .resources.models import Models
323
324 return Models(self)
325
326 @cached_property
327 def files(self) -> Files:
328 from .resources.files import Files
329
330 return Files(self)
331
332 @cached_property
333 def skills(self) -> Skills:
334 from .resources.skills import Skills
335
336 return Skills(self)
337
338 @cached_property
339 def beta(self) -> Beta:
340 from .resources.beta import Beta
341
342 return Beta(self)
343
344 @cached_property
345 def with_raw_response(self) -> AnthropicWithRawResponse:
346 return AnthropicWithRawResponse(self)
347
348 @cached_property
349 def with_streaming_response(self) -> AnthropicWithStreamedResponse:
350 return AnthropicWithStreamedResponse(self)
351
352 @property
353 @override
354 def qs(self) -> Querystring:
355 return Querystring(array_format="brackets")
356
357 @property
358 @override
359 def auth_headers(self) -> dict[str, str]:
360 return {**self._api_key_auth, **self._bearer_auth}
361
362 @property
363 def _api_key_auth(self) -> dict[str, str]:
364 api_key = self.api_key
365 if api_key is None:
366 return {}
367 return {"X-Api-Key": api_key}
368
369 @property
370 def _bearer_auth(self) -> dict[str, str]:
371 # Symmetric with _api_key_auth: always emit if self.auth_token is set,
372 # regardless of whether a TokenCache is also installed. When both a
373 # static auth_token and a credentials provider are present, the static
374 # credential wins per the documented precedence — AccessTokenAuth
375 # short-circuits on a pre-set Authorization header and no token
376 # exchange runs.
377 auth_token = self.auth_token
378 if auth_token is None:
379 return {}
380 return {"Authorization": f"Bearer {auth_token}"}
381
382 @property
383 @override
384 def default_headers(self) -> dict[str, str | Omit]:
385 return {
386 **super().default_headers,
387 "X-Stainless-Async": "false",
388 "anthropic-version": "2023-06-01",
389 **self._custom_headers,
390 }
391
392 @override
393 def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
394 return _keep_client_header_params(super()._prepare_options(options))
395
396 @override
397 def _validate_headers(self, headers: httpx2.Headers, omitted: frozenset[str]) -> None:
398 # --- credentials support (hand-written, upstream to Stainless) ---
399 # The token cache *may* inject an Authorization header per-request via
400 # custom_auth, so validation that checks only default_headers would
401 # false-negative when credentials are the only auth source. Defer to
402 # the static-header check below — if a static api_key or auth_token
403 # is set it will already be on default_headers; otherwise custom_auth
404 # will fill in Authorization at request time.
405 if self._token_cache is not None and not headers.get("X-Api-Key") and not headers.get("Authorization"):
406 return
407 # --- end credentials support ---
408 if headers.get("Authorization") or headers.get("X-Api-Key"):
409 # valid
410 return
411
412 if headers.get("X-Api-Key") or "x-api-key" in omitted:
413 return
414
415 if headers.get("Authorization") or "authorization" in omitted:
416 return
417
418 raise TypeError(
419 '"Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"'
420 )
421
422 # --- credentials support (hand-written, upstream to Stainless) ---
423 @property
424 @override
425 def custom_auth(self) -> httpx2.Auth | None:
426 return self._custom_auth
427
428 @override
429 def _should_retry(self, response: httpx2.Response) -> bool:
430 # On 401 with a token cache, invalidate and retry once so the request
431 # is re-sent with a freshly minted Bearer token. The base-client retry
432 # loop rebuilds the request from FinalRequestOptions on each attempt,
433 # so body replay is handled for us. The single-shot guard relies on
434 # `x-stainless-retry-count` being `"0"` on the first attempt
435 # (see _base_client.py); if a caller Omit()s that header the guard
436 # silently no-ops, which fails safe (no retry, surface the 401).
437 if response.status_code == 401 and self._token_cache is not None:
438 self._token_cache.invalidate()
439 if response.request.headers.get("x-stainless-retry-count") == "0":
440 return True
441 return super()._should_retry(response)
442
443 @override
444 def close(self) -> None:
445 super().close()
446 close_credentials(self.credentials)
447
448 # --- end credentials support ---
449
450 def copy(
451 self,
452 *,
453 api_key: str | None = None,
454 auth_token: str | None = None,
455 credentials: AccessTokenProvider | None | NotGiven = not_given,
456 config: Mapping[str, Any] | None = None,
457 profile: str | None = None,
458 webhook_key: str | None = None,
459 base_url: str | httpx2.URL | None = None,
460 timeout: float | Timeout | None | NotGiven = not_given,
461 http_client: httpx2.Client | None = None,
462 max_retries: int | NotGiven = not_given,
463 default_headers: Mapping[str, str] | None = None,
464 set_default_headers: Mapping[str, str] | None = None,
465 default_query: Mapping[str, object] | None = None,
466 set_default_query: Mapping[str, object] | None = None,
467 middleware: Sequence[MiddlewareInput] | None | NotGiven = not_given,
468 _extra_kwargs: Mapping[str, Any] = {},
469 ) -> Self:
470 """
471 Create a new client instance re-using the same options given to the current client with optional overriding.
472 """
473 if default_headers is not None and set_default_headers is not None:
474 raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
475
476 if default_query is not None and set_default_query is not None:
477 raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
478
479 headers = self._custom_headers
480 if default_headers is not None:
481 headers = merge_headers(headers, default_headers)
482 elif set_default_headers is not None:
483 headers = set_default_headers
484
485 params = self._custom_query
486 if default_query is not None:
487 params = {**params, **default_query}
488 elif set_default_query is not None:
489 params = set_default_query
490
491 http_client = http_client or self._client
492 # --- credentials support (hand-written, upstream to Stainless) ---
493 if config is not None:
494 if not isinstance(credentials, NotGiven) or profile is not None:
495 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
496 _extra_kwargs = {"config": config, **_extra_kwargs}
497 elif profile is not None:
498 if not isinstance(credentials, NotGiven):
499 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
500 _extra_kwargs = {"profile": profile, **_extra_kwargs}
501 else:
502 resolved_credentials = self.credentials if isinstance(credentials, NotGiven) else credentials
503 if resolved_credentials is not None and _is_base_client(self):
504 _extra_kwargs = {"credentials": resolved_credentials, **_extra_kwargs}
505 # Share the parent's TokenCache only while the provider and
506 # deployment are unchanged; a new credentials= or base_url= gets
507 # its own cache.
508 if isinstance(credentials, NotGiven) and _keeps_base_url(self.base_url, base_url):
509 _extra_kwargs = {"_token_cache": self._token_cache, **_extra_kwargs}
510 # --- end credentials support ---
511 return self.__class__(
512 api_key=api_key or self.api_key,
513 auth_token=auth_token or self.auth_token,
514 webhook_key=webhook_key or self.webhook_key,
515 base_url=base_url or self.base_url,
516 timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
517 http_client=http_client,
518 max_retries=max_retries if is_given(max_retries) else self.max_retries,
519 default_headers=headers,
520 default_query=params,
521 middleware=self._middleware if isinstance(middleware, NotGiven) else middleware,
522 **_extra_kwargs,
523 )
524
525 # Alias for `copy` for nicer inline usage, e.g.
526 # client.with_options(timeout=10).foo.create(...)
527 with_options = copy
528
529 def with_middleware(self, *middleware: MiddlewareInput) -> Self:
530 """A new client with the given middleware appended after this client's middleware.
531
532 Convenience for applying extra middleware to a single request:
533
534 ```py
535 client.with_middleware(my_middleware).messages.create(...)
536 ```
537 """
538 return self.copy(middleware=[*self._middleware, *middleware])
539
540 @override
541 def _make_status_error(
542 self,
543 err_msg: str,
544 *,
545 body: object,
546 response: httpx2.Response,
547 ) -> APIStatusError:
548 if response.status_code == 400:
549 return _exceptions.BadRequestError(err_msg, response=response, body=body)
550
551 if response.status_code == 401:
552 return _exceptions.AuthenticationError(err_msg, response=response, body=body)
553
554 if response.status_code == 403:
555 return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
556
557 if response.status_code == 404:
558 return _exceptions.NotFoundError(err_msg, response=response, body=body)
559
560 if response.status_code == 409:
561 return _exceptions.ConflictError(err_msg, response=response, body=body)
562
563 if response.status_code == 413:
564 return _exceptions.RequestTooLargeError(err_msg, response=response, body=body)
565
566 if response.status_code == 422:
567 return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
568
569 if response.status_code == 429:
570 return _exceptions.RateLimitError(err_msg, response=response, body=body)
571
572 if response.status_code == 529:
573 return _exceptions.OverloadedError(err_msg, response=response, body=body)
574
575 if response.status_code >= 500:
576 return _exceptions.InternalServerError(err_msg, response=response, body=body)
577 return APIStatusError(err_msg, response=response, body=body)
578
579
580 class AsyncAnthropic(AsyncAPIClient):
581 # client options
582 api_key: str | None
583 auth_token: str | None
584 webhook_key: str | None
585 credentials: AccessTokenProvider | AsyncAccessTokenProvider | None
586 _token_cache: TokenCache | None
587 _custom_auth: AccessTokenAuth | None
588
589 def __init__(
590 self,
591 *,
592 api_key: str | None = None,
593 auth_token: str | None = None,
594 credentials: AccessTokenProvider | AsyncAccessTokenProvider | None = None,
595 config: Mapping[str, Any] | None = None,
596 profile: str | None = None,
597 webhook_key: str | None = None,
598 base_url: str | httpx2.URL | None = None,
599 timeout: float | Timeout | None | NotGiven = not_given,
600 max_retries: int = DEFAULT_MAX_RETRIES,
601 default_headers: Mapping[str, str] | None = None,
602 default_query: Mapping[str, object] | None = None,
603 # Configure a custom httpx2 client.
604 # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
605 # See the [httpx2 documentation](https://httpx2.pydantic.dev/api/#asyncclient) for more details.
606 http_client: httpx2.AsyncClient | None = None,
607 middleware: Sequence[MiddlewareInput] | None = None,
608 # Enable or disable schema validation for data returned by the API.
609 # When enabled an error APIResponseValidationError is raised
610 # if the API responds with invalid data for the expected schema.
611 #
612 # This parameter may be removed or changed in the future.
613 # If you rely on this feature, please open a GitHub issue
614 # outlining your use-case to help us decide if it should be
615 # part of our public interface in the future.
616 _strict_response_validation: bool = False,
617 _token_cache: TokenCache | None | NotGiven = not_given,
618 ) -> None:
619 """Construct a new async AsyncAnthropic client instance.
620
621 Credentials are resolved in the following order (first match wins):
622
623 1. Explicit constructor arguments — `api_key=`, `auth_token=`,
624 `credentials=`, `config=`, or `profile=`. When any of these
625 is passed, environment variables are not consulted for credentials.
626 2. `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` environment
627 variables.
628 3. `ANTHROPIC_PROFILE` environment variable — loads the named
629 profile from `<config_dir>/configs/<profile>.json`.
630 4. Workload identity federation environment variables —
631 `ANTHROPIC_IDENTITY_TOKEN[_FILE]` +
632 `ANTHROPIC_FEDERATION_RULE_ID` + `ANTHROPIC_ORGANIZATION_ID`.
633 5. The active profile on disk — the profile named by
634 `<config_dir>/active_config`, or `default`.
635
636 `credentials=`, `config=`, and `profile=` are mutually exclusive.
637
638 If a static credential is supplied alongside a credentials provider
639 (`credentials=` / `config=` / `profile=`), or if
640 `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` is set alongside a
641 profile or federation configuration, the static credential takes
642 precedence and a one-shot warning is logged on the `anthropic`
643 logger.
644 """
645 # --- credentials support (hand-written, upstream to Stainless) ---
646 # Explicit ctor args are total. If the caller passed any explicit
647 # credential argument, do NOT read credential env vars.
648 has_explicit_credential = (
649 api_key is not None
650 or auth_token is not None
651 or credentials is not None
652 or config is not None
653 or profile is not None
654 )
655 if not has_explicit_credential:
656 api_key = os.environ.get("ANTHROPIC_API_KEY") or None
657 auth_token = os.environ.get("ANTHROPIC_AUTH_TOKEN") or None
658 self.api_key = api_key
659 self.auth_token = auth_token
660 # --- end credentials support ---
661
662 if webhook_key is None:
663 webhook_key = os.environ.get("ANTHROPIC_WEBHOOK_SIGNING_KEY")
664 self.webhook_key = webhook_key
665
666 if base_url is None:
667 base_url = os.environ.get("ANTHROPIC_BASE_URL")
668 # base_url precedence: kwarg > ANTHROPIC_BASE_URL > profile config
669 # (filled in below from default_credentials) > hardcoded default.
670 # Track whether the user supplied one so the profile only fills the
671 # gap, never overrides.
672 base_url_is_explicit = base_url is not None
673 if base_url is None:
674 base_url = f"https://api.anthropic.com"
675
676 custom_headers_env = os.environ.get("ANTHROPIC_CUSTOM_HEADERS")
677 if custom_headers_env is not None:
678 parsed: dict[str, str] = {}
679 for line in custom_headers_env.split("\n"):
680 colon = line.find(":")
681 if colon >= 0:
682 parsed[line[:colon].strip()] = line[colon + 1 :].strip()
683 default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})}
684
685 # --- credentials support (hand-written, upstream to Stainless) ---
686 credential_headers: dict[str, str] = {}
687 if config is not None:
688 if credentials is not None or profile is not None:
689 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
690 in_memory = InMemoryConfig(dict(config))
691 credentials = in_memory
692 credential_headers = in_memory.extra_headers()
693 if not base_url_is_explicit and in_memory.resolved_base_url:
694 base_url = in_memory.resolved_base_url
695 elif profile is not None:
696 if credentials is not None:
697 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
698 creds_file = CredentialsFile(profile=profile)
699 credentials = creds_file
700 credential_headers = creds_file.extra_headers()
701 if not base_url_is_explicit and creds_file.resolved_base_url:
702 base_url = creds_file.resolved_base_url
703 if credentials is None and api_key is None and auth_token is None and _is_base_client(self):
704 result = default_credentials(base_url=str(base_url) if base_url else "https://api.anthropic.com")
705 if result is not None:
706 credentials = result.provider
707 credential_headers = result.extra_headers
708 if not base_url_is_explicit and result.base_url:
709 base_url = result.base_url
710 credentials = _bind_credentials_base_url(credentials, str(base_url))
711 self.credentials = credentials
712 _warn_explicit_shadow(api_key=api_key, auth_token=auth_token, credentials=credentials)
713 if _is_base_client(self):
714 # Subclasses never run the auto-discovery chain (gated on `_is_base_client`
715 # below), so nothing is shadowed and the warning would be spurious.
716 _warn_env_shadow(api_key=api_key, auth_token=auth_token)
717 if not isinstance(_token_cache, NotGiven):
718 self._token_cache = _token_cache
719 else:
720 self._token_cache = TokenCache(credentials) if credentials is not None else None
721 self._custom_auth = AccessTokenAuth(self._token_cache) if self._token_cache is not None else None
722 if credential_headers:
723 default_headers = {**credential_headers, **(default_headers or {})}
724 # --- end credentials support ---
725
726 super().__init__(
727 version=__version__,
728 base_url=base_url,
729 max_retries=max_retries,
730 timeout=timeout,
731 http_client=http_client,
732 custom_headers=default_headers,
733 custom_query=default_query,
734 middleware=middleware,
735 _strict_response_validation=_strict_response_validation,
736 )
737
738 self._default_stream_cls = AsyncStream
739
740 @cached_property
741 def messages(self) -> AsyncMessages:
742 from .resources.messages import AsyncMessages
743
744 return AsyncMessages(self)
745
746 @cached_property
747 def models(self) -> AsyncModels:
748 from .resources.models import AsyncModels
749
750 return AsyncModels(self)
751
752 @cached_property
753 def files(self) -> AsyncFiles:
754 from .resources.files import AsyncFiles
755
756 return AsyncFiles(self)
757
758 @cached_property
759 def skills(self) -> AsyncSkills:
760 from .resources.skills import AsyncSkills
761
762 return AsyncSkills(self)
763
764 @cached_property
765 def beta(self) -> AsyncBeta:
766 from .resources.beta import AsyncBeta
767
768 return AsyncBeta(self)
769
770 @cached_property
771 def with_raw_response(self) -> AsyncAnthropicWithRawResponse:
772 return AsyncAnthropicWithRawResponse(self)
773
774 @cached_property
775 def with_streaming_response(self) -> AsyncAnthropicWithStreamedResponse:
776 return AsyncAnthropicWithStreamedResponse(self)
777
778 @property
779 @override
780 def qs(self) -> Querystring:
781 return Querystring(array_format="brackets")
782
783 @property
784 @override
785 def auth_headers(self) -> dict[str, str]:
786 return {**self._api_key_auth, **self._bearer_auth}
787
788 @property
789 def _api_key_auth(self) -> dict[str, str]:
790 api_key = self.api_key
791 if api_key is None:
792 return {}
793 return {"X-Api-Key": api_key}
794
795 @property
796 def _bearer_auth(self) -> dict[str, str]:
797 # Symmetric with _api_key_auth: always emit if self.auth_token is set,
798 # regardless of whether a TokenCache is also installed. When both a
799 # static auth_token and a credentials provider are present, the static
800 # credential wins per the documented precedence — AccessTokenAuth
801 # short-circuits on a pre-set Authorization header and no token
802 # exchange runs.
803 auth_token = self.auth_token
804 if auth_token is None:
805 return {}
806 return {"Authorization": f"Bearer {auth_token}"}
807
808 @property
809 @override
810 def default_headers(self) -> dict[str, str | Omit]:
811 return {
812 **super().default_headers,
813 "X-Stainless-Async": f"async:{get_async_library()}",
814 "anthropic-version": "2023-06-01",
815 **self._custom_headers,
816 }
817
818 @override
819 async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
820 return _keep_client_header_params(await super()._prepare_options(options))
821
822 @override
823 def _validate_headers(self, headers: httpx2.Headers, omitted: frozenset[str]) -> None:
824 # --- credentials support (hand-written, upstream to Stainless) ---
825 if self._token_cache is not None and not headers.get("X-Api-Key") and not headers.get("Authorization"):
826 return
827 # --- end credentials support ---
828 if headers.get("Authorization") or headers.get("X-Api-Key"):
829 # valid
830 return
831
832 if headers.get("X-Api-Key") or "x-api-key" in omitted:
833 return
834
835 if headers.get("Authorization") or "authorization" in omitted:
836 return
837
838 raise TypeError(
839 '"Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"'
840 )
841
842 # --- credentials support (hand-written, upstream to Stainless) ---
843 @property
844 @override
845 def custom_auth(self) -> httpx2.Auth | None:
846 return self._custom_auth
847
848 @override
849 def _should_retry(self, response: httpx2.Response) -> bool:
850 # On 401 with a token cache, invalidate and retry once so the request
851 # is re-sent with a freshly minted Bearer token. The base-client retry
852 # loop rebuilds the request from FinalRequestOptions on each attempt,
853 # so body replay is handled for us. The single-shot guard relies on
854 # `x-stainless-retry-count` being `"0"` on the first attempt
855 # (see _base_client.py); if a caller Omit()s that header the guard
856 # silently no-ops, which fails safe (no retry, surface the 401).
857 if response.status_code == 401 and self._token_cache is not None:
858 self._token_cache.invalidate()
859 if response.request.headers.get("x-stainless-retry-count") == "0":
860 return True
861 return super()._should_retry(response)
862
863 @override
864 async def close(self) -> None:
865 await super().close()
866 await async_close_credentials(self.credentials)
867
868 # --- end credentials support ---
869
870 def copy(
871 self,
872 *,
873 api_key: str | None = None,
874 auth_token: str | None = None,
875 credentials: AccessTokenProvider | AsyncAccessTokenProvider | None | NotGiven = not_given,
876 config: Mapping[str, Any] | None = None,
877 profile: str | None = None,
878 webhook_key: str | None = None,
879 base_url: str | httpx2.URL | None = None,
880 timeout: float | Timeout | None | NotGiven = not_given,
881 http_client: httpx2.AsyncClient | None = None,
882 max_retries: int | NotGiven = not_given,
883 default_headers: Mapping[str, str] | None = None,
884 set_default_headers: Mapping[str, str] | None = None,
885 default_query: Mapping[str, object] | None = None,
886 set_default_query: Mapping[str, object] | None = None,
887 middleware: Sequence[MiddlewareInput] | None | NotGiven = not_given,
888 _extra_kwargs: Mapping[str, Any] = {},
889 ) -> Self:
890 """
891 Create a new client instance re-using the same options given to the current client with optional overriding.
892 """
893 if default_headers is not None and set_default_headers is not None:
894 raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
895
896 if default_query is not None and set_default_query is not None:
897 raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
898
899 headers = self._custom_headers
900 if default_headers is not None:
901 headers = merge_headers(headers, default_headers)
902 elif set_default_headers is not None:
903 headers = set_default_headers
904
905 params = self._custom_query
906 if default_query is not None:
907 params = {**params, **default_query}
908 elif set_default_query is not None:
909 params = set_default_query
910
911 http_client = http_client or self._client
912 # --- credentials support (hand-written, upstream to Stainless) ---
913 if config is not None:
914 if not isinstance(credentials, NotGiven) or profile is not None:
915 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
916 _extra_kwargs = {"config": config, **_extra_kwargs}
917 elif profile is not None:
918 if not isinstance(credentials, NotGiven):
919 raise TypeError("Pass at most one of `credentials=`, `config=`, or `profile=`.")
920 _extra_kwargs = {"profile": profile, **_extra_kwargs}
921 else:
922 resolved_credentials = self.credentials if isinstance(credentials, NotGiven) else credentials
923 if resolved_credentials is not None and _is_base_client(self):
924 _extra_kwargs = {"credentials": resolved_credentials, **_extra_kwargs}
925 # Share the parent's TokenCache only while the provider and
926 # deployment are unchanged; a new credentials= or base_url= gets
927 # its own cache.
928 if isinstance(credentials, NotGiven) and _keeps_base_url(self.base_url, base_url):
929 _extra_kwargs = {"_token_cache": self._token_cache, **_extra_kwargs}
930 # --- end credentials support ---
931 return self.__class__(
932 api_key=api_key or self.api_key,
933 auth_token=auth_token or self.auth_token,
934 webhook_key=webhook_key or self.webhook_key,
935 base_url=base_url or self.base_url,
936 timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
937 http_client=http_client,
938 max_retries=max_retries if is_given(max_retries) else self.max_retries,
939 default_headers=headers,
940 default_query=params,
941 middleware=self._middleware if isinstance(middleware, NotGiven) else middleware,
942 **_extra_kwargs,
943 )
944
945 # Alias for `copy` for nicer inline usage, e.g.
946 # client.with_options(timeout=10).foo.create(...)
947 with_options = copy
948
949 def with_middleware(self, *middleware: MiddlewareInput) -> Self:
950 """A new client with the given middleware appended after this client's middleware.
951
952 Convenience for applying extra middleware to a single request:
953
954 ```py
955 client.with_middleware(my_middleware).messages.create(...)
956 ```
957 """
958 return self.copy(middleware=[*self._middleware, *middleware])
959
960 @override
961 def _make_status_error(
962 self,
963 err_msg: str,
964 *,
965 body: object,
966 response: httpx2.Response,
967 ) -> APIStatusError:
968 if response.status_code == 400:
969 return _exceptions.BadRequestError(err_msg, response=response, body=body)
970
971 if response.status_code == 401:
972 return _exceptions.AuthenticationError(err_msg, response=response, body=body)
973
974 if response.status_code == 403:
975 return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
976
977 if response.status_code == 404:
978 return _exceptions.NotFoundError(err_msg, response=response, body=body)
979
980 if response.status_code == 409:
981 return _exceptions.ConflictError(err_msg, response=response, body=body)
982
983 if response.status_code == 413:
984 return _exceptions.RequestTooLargeError(err_msg, response=response, body=body)
985
986 if response.status_code == 422:
987 return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
988
989 if response.status_code == 429:
990 return _exceptions.RateLimitError(err_msg, response=response, body=body)
991
992 if response.status_code == 529:
993 return _exceptions.OverloadedError(err_msg, response=response, body=body)
994
995 if response.status_code >= 500:
996 return _exceptions.InternalServerError(err_msg, response=response, body=body)
997 return APIStatusError(err_msg, response=response, body=body)
998
999
1000 class AnthropicWithRawResponse:
1001 _client: Anthropic
1002
1003 def __init__(self, client: Anthropic) -> None:
1004 self._client = client
1005
1006 @cached_property
1007 def messages(self) -> messages.MessagesWithRawResponse:
1008 from .resources.messages import MessagesWithRawResponse
1009
1010 return MessagesWithRawResponse(self._client.messages)
1011
1012 @cached_property
1013 def models(self) -> models.ModelsWithRawResponse:
1014 from .resources.models import ModelsWithRawResponse
1015
1016 return ModelsWithRawResponse(self._client.models)
1017
1018 @cached_property
1019 def files(self) -> files.FilesWithRawResponse:
1020 from .resources.files import FilesWithRawResponse
1021
1022 return FilesWithRawResponse(self._client.files)
1023
1024 @cached_property
1025 def skills(self) -> skills.SkillsWithRawResponse:
1026 from .resources.skills import SkillsWithRawResponse
1027
1028 return SkillsWithRawResponse(self._client.skills)
1029
1030 @cached_property
1031 def beta(self) -> beta.BetaWithRawResponse:
1032 from .resources.beta import BetaWithRawResponse
1033
1034 return BetaWithRawResponse(self._client.beta)
1035
1036
1037 class AsyncAnthropicWithRawResponse:
1038 _client: AsyncAnthropic
1039
1040 def __init__(self, client: AsyncAnthropic) -> None:
1041 self._client = client
1042
1043 @cached_property
1044 def messages(self) -> messages.AsyncMessagesWithRawResponse:
1045 from .resources.messages import AsyncMessagesWithRawResponse
1046
1047 return AsyncMessagesWithRawResponse(self._client.messages)
1048
1049 @cached_property
1050 def models(self) -> models.AsyncModelsWithRawResponse:
1051 from .resources.models import AsyncModelsWithRawResponse
1052
1053 return AsyncModelsWithRawResponse(self._client.models)
1054
1055 @cached_property
1056 def files(self) -> files.AsyncFilesWithRawResponse:
1057 from .resources.files import AsyncFilesWithRawResponse
1058
1059 return AsyncFilesWithRawResponse(self._client.files)
1060
1061 @cached_property
1062 def skills(self) -> skills.AsyncSkillsWithRawResponse:
1063 from .resources.skills import AsyncSkillsWithRawResponse
1064
1065 return AsyncSkillsWithRawResponse(self._client.skills)
1066
1067 @cached_property
1068 def beta(self) -> beta.AsyncBetaWithRawResponse:
1069 from .resources.beta import AsyncBetaWithRawResponse
1070
1071 return AsyncBetaWithRawResponse(self._client.beta)
1072
1073
1074 class AnthropicWithStreamedResponse:
1075 _client: Anthropic
1076
1077 def __init__(self, client: Anthropic) -> None:
1078 self._client = client
1079
1080 @cached_property
1081 def messages(self) -> messages.MessagesWithStreamingResponse:
1082 from .resources.messages import MessagesWithStreamingResponse
1083
1084 return MessagesWithStreamingResponse(self._client.messages)
1085
1086 @cached_property
1087 def models(self) -> models.ModelsWithStreamingResponse:
1088 from .resources.models import ModelsWithStreamingResponse
1089
1090 return ModelsWithStreamingResponse(self._client.models)
1091
1092 @cached_property
1093 def files(self) -> files.FilesWithStreamingResponse:
1094 from .resources.files import FilesWithStreamingResponse
1095
1096 return FilesWithStreamingResponse(self._client.files)
1097
1098 @cached_property
1099 def skills(self) -> skills.SkillsWithStreamingResponse:
1100 from .resources.skills import SkillsWithStreamingResponse
1101
1102 return SkillsWithStreamingResponse(self._client.skills)
1103
1104 @cached_property
1105 def beta(self) -> beta.BetaWithStreamingResponse:
1106 from .resources.beta import BetaWithStreamingResponse
1107
1108 return BetaWithStreamingResponse(self._client.beta)
1109
1110
1111 class AsyncAnthropicWithStreamedResponse:
1112 _client: AsyncAnthropic
1113
1114 def __init__(self, client: AsyncAnthropic) -> None:
1115 self._client = client
1116
1117 @cached_property
1118 def messages(self) -> messages.AsyncMessagesWithStreamingResponse:
1119 from .resources.messages import AsyncMessagesWithStreamingResponse
1120
1121 return AsyncMessagesWithStreamingResponse(self._client.messages)
1122
1123 @cached_property
1124 def models(self) -> models.AsyncModelsWithStreamingResponse:
1125 from .resources.models import AsyncModelsWithStreamingResponse
1126
1127 return AsyncModelsWithStreamingResponse(self._client.models)
1128
1129 @cached_property
1130 def files(self) -> files.AsyncFilesWithStreamingResponse:
1131 from .resources.files import AsyncFilesWithStreamingResponse
1132
1133 return AsyncFilesWithStreamingResponse(self._client.files)
1134
1135 @cached_property
1136 def skills(self) -> skills.AsyncSkillsWithStreamingResponse:
1137 from .resources.skills import AsyncSkillsWithStreamingResponse
1138
1139 return AsyncSkillsWithStreamingResponse(self._client.skills)
1140
1141 @cached_property
1142 def beta(self) -> beta.AsyncBetaWithStreamingResponse:
1143 from .resources.beta import AsyncBetaWithStreamingResponse
1144
1145 return AsyncBetaWithStreamingResponse(self._client.beta)
1146
1147
1148 Client = Anthropic
1149
1150 AsyncClient = AsyncAnthropic