feat(client): support callable auth tokens
Summary:
Fixes #1496 by allowing auth_token to be a string or a callable returning the current bearer token. Callable tokens are resolved when auth headers are built, so long-running clients can use refreshed tokens.
Changes:
- [ ] Add an
AuthTokenalias for static and callable bearer tokens. - [ ] Resolve callable auth tokens per request for sync and async clients.
- [ ] Preserve callable token behavior through copied clients.
- [ ] Document short-lived bearer token usage in the README.
- [ ] Add tests for callable tokens and credential precedence.
Testing instructions:
- [ ] Run
uv run python -m pytest tests\test_client.py -k "auth_token_callable or validate_headers" -n0. - [ ] Run
uv run python -m pytest tests\lib\test_credentials.py -k "auth_token_callable or explicit_auth_token_shadows or copy_with_explicit_api_key_shadows" -n0. - [ ] Run
uv run ruff check src\anthropic\_client.py src\anthropic\__init__.py tests\test_client.py tests\lib\test_credentials.py README.md. - [ ] Run
uv run pyright src\anthropic\_client.py src\anthropic\__init__.py.
This is the right fix and it still fills a real gap after the conflicting PR that included credentials= shipped in v0.109. credentials= covers the advanced case but requires the full AccessTokenProvider protocol (__call__(self, *, force_refresh: bool = False) -> AccessToken), so anyone who just has a Callable[[], str] that returns a bearer token has to hand-roll an adapter and a no-op force_refresh. Making auth_token accept str | Callable[[], str], the way this PR does, is the missing simple path and is symmetric with how api_key should behave.
The branch is currently CONFLICTING, almost certainly because credentials= touched _client.py after this was opened. @wilyan09007 are you able to rebase onto main? Happy to help reconcile the auth-header resolution with the new credential precedence so the two paths coexist cleanly.
Flagging for maintainer triage as well, this has been open since early May with no review and it closes out #1496. (cc @RobertCraigie / @bradabrams
Also worth considering, either in scope or as an immediate follow-up: the async client accepting Callable[[], Awaitable[str]], awaited in async_auth_flow rather than bridged through asyncify, so async-native credential sources don't have to fall back to their sync variant. The sync callable in this PR is unaffected; this is an additive widen on the AsyncAnthropic path.