Debian Codegraph @

src/anthropic/lib/_scoped_client.py

raw
1 """Shared util for building a Bearer-only sub-client for a helper.
2
3 Several helpers (the environment poller, the environment worker, the session
4 tool runner) need to issue requests authenticated by a per-helper credential
5 (a self-hosted environment key, today) rather than the parent client's own
6 `X-Api-Key`. They each want to inherit the parent's full configuration —
7 `timeout`, `max_retries`, `http_client`, custom `default_headers`,
8 `default_query` — and override only the auth bits, plus tag every request
9 with their own `x-stainless-helper` value.
10
11 `_copy_client_with_bearer_auth` is the one shared construction.
12 """
13
14 from __future__ import annotations
15
16 from typing import TYPE_CHECKING, Dict, TypeVar, cast
17
18 from ._stainless_helpers import STAINLESS_HELPER_HEADER, StainlessHelperHeaderValue
19
20 if TYPE_CHECKING:
21 from .._client import Anthropic, AsyncAnthropic
22
23
24 __all__ = ["_copy_client_with_bearer_auth"]
25
26
27 ClientT = TypeVar("ClientT", "Anthropic", "AsyncAnthropic")
28
29
30 def _copy_client_with_bearer_auth(client: ClientT, *, auth_token: str, helper: StainlessHelperHeaderValue) -> ClientT:
31 """Return a copy of `client` authenticated with `auth_token` as Bearer.
32
33 The returned sub-client inherits the parent's full configuration via
34 `client.copy()` (`base_url`, `timeout`, `max_retries`,
35 `http_client`, `default_query`, and any custom `default_headers`).
36 Overrides applied:
37
38 - `auth_token=auth_token` — the new credential.
39 - `credentials=None` — any inherited credentials provider is cleared so
40 the bearer is the unambiguous auth.
41 - `default_headers` merges in `x-stainless-helper: <helper>` so every
42 request the sub-client issues is tagged for SDK telemetry without
43 per-call plumbing.
44 - `api_key=None` — the parent's `X-Api-Key` is cleared via a post-hoc
45 mutation; today's `copy()` treats `api_key=None` as "inherit" via
46 truthy-or, so the assignment is the only way to drop the parent's API
47 key from the sub-client.
48 - Any inherited `Authorization` / `X-Api-Key` entries in the parent's
49 custom default-headers are stripped from the sub-client. They would
50 otherwise win over the bearer we just set, because
51 `AsyncAnthropic.default_headers` merges `_custom_headers` after
52 `auth_headers` (and so beats the `Authorization` value produced by
53 `auth_token`).
54 """
55 if not auth_token:
56 raise ValueError(f"Expected a non-empty value for `auth_token` but received {auth_token!r}")
57 scoped = client.copy(
58 auth_token=auth_token,
59 credentials=None,
60 default_headers={STAINLESS_HELPER_HEADER: helper},
61 )
62 scoped.api_key = None
63 # `_custom_headers` is typed as `Mapping[str, str]` (immutable
64 # interface) but is constructed as a plain `dict` at runtime — cast
65 # so we can `pop()` keys without re-typing the base client.
66 custom: Dict[str, str] = cast("Dict[str, str]", scoped._custom_headers)
67 for key in list(custom):
68 if key.lower() in ("authorization", "x-api-key"):
69 custom.pop(key)
70 return scoped