CIRCLE
Reference

Core API

Reference of the auth_ai module: AuthClient, GrantManager, AiClient, the wallet and gateway clients, claims helpers and errors.

Everything below is exported from auth_ai. All I/O methods are coroutines (async def); the few synchronous ones are marked. The models are frozen pydantic models or frozen dataclasses.

AuthClient

The OIDC relying party for auth-service: authorization code with PKCE, refresh with RFC 8707 resource narrowing, logout, revocation and introspection. It keeps no session: you persist the handshake, the tokens and the claims where it suits you. Options are in Configuration.

MemberDescription
configThe resolved AuthClientConfig.
httpThe httpx2.AsyncClient used for every request. The default is built by build_http_client().
aclose()Closes the client when the SDK created it. async with AuthClient(...) does the same.
start_login(*, prompt=None, login_hint=None) -> LoginRequestGenerates state, nonce and the PKCE verifier and returns the authorization url and the handshake to persist until the callback. prompt is login, consent, select_account, create or none.
handle_callback(callback_url, handshake) -> LoginResultValidates the authorization response (a repeated parameter, error, iss, state and code), exchanges the code, and verifies the ID token. Failures are OIDC_002, OIDC_003 or TOK_001.
verify_id_token(id_token) -> IdTokenClaimsVerifies an ID token of the provider, with no nonce check.
refresh(refresh_token, *, resource=None) -> TokenSetExchanges a refresh token. The provider rotates it on every use; concurrent callers should go through a GrantManager. scope is never sent.
logout_url(*, id_token_hint=None, state=None) -> strURL ending the provider session (RP-initiated logout). Raises OIDC_004 when the provider has no end_session_endpoint.
revoke(token, hint=None)Revokes a token. OIDC_004 without a revocation_endpoint, OIDC_003 on a refusal.
introspect(token, hint=None) -> IntrospectionResultRFC 7662 introspection. OIDC_004 without an introspection_endpoint.
client_credentials(*, scope=None, resource=None) -> TokenSetThe client_credentials grant for the application itself. Raises CFG_001 without a client_secret.
verify_jwt(token, *, audience, typ=None) -> dict[str, Any]Low-level: verifies signature, issuer, audience and expiry of a JWT signed by the provider and returns its claims. Prefer BearerVerifier and the logout token verifier.

hint is "access_token" or "refresh_token". Discovery and the signing keys are cached for an hour, and a failed discovery is not cached.

Types

TypeFields
LoginRequesturl, handshake.
LoginHandshakestate, nonce, code_verifier. Persist them in a short-lived sealed cookie. They are hidden from repr.
LoginResulttokens (a TokenSet), claims (an IdTokenClaims), session_id (the provider sid, or None) and the property id_token.
TokenSetaccess_token, token_type, expires_at (Unix seconds), scope, refresh_token, id_token. The tokens are hidden from repr.
IntrospectionResultactive, plus scope, client_id, sub, username, iss, aud, exp, iat; other members are kept.

Prompt and TokenTypeHint are the Literal aliases of the values above.

GrantManager

GrantManager(*, auth, store, lock=None, expiry_skew_seconds=30). The only place that refreshes tokens. See Sessions and grants.

MethodDescription
save(grant_id, refresh_token)Stores the refresh token obtained at sign-in, replacing any older chain, and drops the cached access tokens of the grant.
has(grant_id) -> boolWhether a refresh token is stored.
get_access_token(grant_id, *, resource=None) -> AccessTokenAn access token narrowed to one resource, cached until expiry_skew_seconds before it expires. Raises TOK_002 when there is no grant or the provider answers invalid_grant.
refresh_tokens(grant_id) -> TokenSetRefreshes without narrowing and returns the whole token set, ID token included.
invalidate(grant_id, resource=None)Synchronous. Drops a cached access token the API refused.
revoke(grant_id)Revokes the refresh token at the provider, then forgets the grant even if the provider is unreachable.

AccessToken has access_token (hidden from repr) and expires_at.

Protocols and defaults:

NameDescription
GrantStoreget(grant_id) -> str | None, set(grant_id, refresh_token), delete(grant_id).
GrantLockhold(grant_id), an async context manager.
MemoryGrantStoreIn-process store, for tests and prototypes.
InProcessGrantLockOne asyncio.Lock per grant, dropped when idle. Covers one process only.

AiClient and UserAi

AiClient(*, auth, grants) builds the per-user clients. for_user(grant_id) returns a UserAi, where grant_id is the key the refresh token was saved under (the user's sub).

MemberDescription
walletA WalletClient.
gatewayA GatewayClient. A property that raises CFG_001 when gateway_url is not configured.

WalletClient

The signed-in user's own wallet, read with a token minted for the auth-service audience with the wallet:self:read scope. A 401 drops the cached token and retries once.

MethodReturnsDescription
get_account()WalletAccountbalance, is_unlimited, can_spend, currency ("eur"). Decide with can_spend.
get_stats(*, days=None)WalletStatsSpend over days (1 to 90, 30 by default): total, not_billed, calls, series, by_application, by_kind, by_model and daily.
get_session_usage(session_id, *, days=None)WalletSessionUsageWhat one chat session spent, for the calling application only: session_id, application_slug, days, total, not_billed, calls, by_model.
list_transactions(*, limit=None, cursor=None, type=None)WalletTransactionPageNewest first, keyset-paginated: pass next_cursor back until it is None. type is a WalletTransactionType.
get_topup_options()TopupOptionsenabled, currency, min_cents, max_cents.
topup_url()strSynchronous. The Credit tab of the user's profile.

WalletTransactionType is "topup", "grant", "refund", "usage", "adjust" or "reversal". A WalletTransaction has id, type, amount, delta, balance_after, application_id, metadata and created_at.

All amounts are int micro-euros. The models use snake_case attributes, read the camelCase wire names, and to_json() returns the camelCase dictionary with amounts as strings, which is what the BFF routes send. MICRO_PER_EUR is 1_000_000, and format_euros(amount, fraction_digits=2) truncates toward zero (0 to 6 digits, ValueError otherwise). The per-model, per-application and daily entry classes (ModelUsage and the others) are defined in auth_ai.wallet.

GatewayClient

The LiteLLM gateway on behalf of a signed-in user. The user's access token is the API key: it is minted per call, cached by the grant manager and never stored.

MemberDescription
openai_base_url<gateway_url>/v1, the base_url of an OpenAI-compatible SDK.
create_http_client(*, timeout=None, transport=None)An httpx2.AsyncClient that signs every request with a fresh token. Pass it to an OpenAI-compatible SDK as http_client. You own it and close it.
authThe GatewayAuth (an httpx2.Auth) the client uses. It refuses any origin other than the gateway's with CFG_001, and a 401 drops the cached token.
get_access_token()A fresh access token as a str, for clients that cannot take an httpx2 client.
list_models()list[GatewayModel] from /v1/models.
list_agents()list[GatewayAgent] from /v1/agents.
list_mcp_servers()list[GatewayMcpServer] from /v1/mcp/server.
mcp_url(server_name=None)Synchronous. <gateway_url>/mcp, or <gateway_url>/<server_name>/mcp. Names outside [A-Za-z0-9][A-Za-z0-9_.-]{0,127} raise CFG_001.
post_json(path, body)POSTs JSON to a gateway route and returns the parsed answer as object, which you validate.

The listings validate the answer and raise GW_005 when its shape is unexpected. GatewayModel has id (and optionally object, created, owned_by), GatewayAgent has agent_id and agent_name, and GatewayMcpServer has server_id and optionally server_name, alias, description and transport. Members the gateway adds are kept.

Failures map by HTTP status, with to_gateway_error(status, body, headers=None): 402 is GW_001, 429 is GW_002, 401 and 403 are GW_003, 503 is GW_004, anything else is GW_005; a network failure is GW_004. is_insufficient_credit(err) is true for a GW_001 AuthAiError; is_insufficient_credit_status(err) tests an error of an OpenAI-compatible SDK for a status_code or status of 402.

Claims, helpers and SessionUser

ExportDescription
IdTokenClaimsFrozen model: iss, sub, aud, exp, iat, then roles, permissions, features, plan, org_id, sid, azp and the profile claims name, picture, given_name, family_name, company, updated_at, email, email_verified, phone_number. Unknown claims are kept (model_extra).
AccessTokenClaimsThe same base, with a required azp and a scope string.
FeatureValuestr | int | float | bool.
has_role, has_permission, has_feature, get_featureSee Entitlements.
SessionUser, to_session_user(claims)The browser-safe user: sub, name, email, email_verified, picture, roles, permissions, features, plan, org_id. to_json() returns the camelCase dictionary without the None members.

build_http_client

build_http_client(*, timeout_seconds, transport=None, auth=None) -> httpx2.AsyncClient builds the client every SDK call uses: HTTP/2 negotiated over TLS with HTTP/1.1 as the fallback, gzip and brotli responses (plus zstd where the runtime provides it, Python 3.14), and no redirects. Pass its result as http_client to keep these defaults behind your own proxy or transport. You own it and close it.

Errors

ExportDescription
AuthAiErrorThe exception of every failure: code, message, details and the original exception as __cause__. to_public_json() returns {"code", "message"} with the registry's generic message; to_json() adds the detailed message and the details.
ERRThe registry: ERR.TOK_002() builds the error of one code. Each factory takes an optional message and the keyword arguments details and cause. Raise the result.
AuthAiErrorCode, AuthAiErrorDetailsThe Literal of the codes, and the type of details (a mapping of str to str, int, float, bool or None).
is_auth_ai_error_code(value)Whether value is a known code string.

The codes are listed in Error codes.

Copyright © 2026