airflow.providers.anthropic.hooks.anthropic¶
Attributes¶
Classes¶
Top-level |
|
Status of a Managed Agents session. |
|
Verdict from one poll of a session; see |
|
Use the Anthropic SDK to interact with the Claude API. |
Functions¶
|
Normalize a session budget into the API's |
|
Judge a polled session from its object fields alone. |
|
Validate the event a deferred task resumes with, returning it if well-formed. |
|
Apply the success/skip/fail policy for a terminal batch's request counts. |
Module Contents¶
- class airflow.providers.anthropic.hooks.anthropic.BatchStatus[source]¶
-
Top-level
processing_statusof an Anthropic Message Batch.- classmethod is_in_progress(status)[source]¶
Return
Truewhile the batch has not reached the terminalendedstatus.This is broader than the
in_progressvalue: acancelingbatch is also non-terminal (cancellation is in flight but the batch has not ended yet), so it returnsTruetoo. Read the name as “not yet terminal”, not “equals thein_progressstatus”.
- class airflow.providers.anthropic.hooks.anthropic.SessionStatus[source]¶
-
Status of a Managed Agents session.
- airflow.providers.anthropic.hooks.anthropic.build_budget(budget)[source]¶
Normalize a session budget into the API’s
max_list_costpayload.A scalar is read as US dollars (
25,25.0and"25.00"all mean $25.00). The API wants minor units as an integer decimal string, so the conversion runs throughDecimal(never binary float) and rejects an amount finer than a cent rather than silently rounding money. A mapping is deep-copied and otherwise returned unchanged, so a raw payload the provider has not caught up with stays usable without a provider release.Warning
The ceiling is a stop trigger, not a cap: it is checked between model requests, so a request already in flight can carry the session well past it.
- class airflow.providers.anthropic.hooks.anthropic.SessionPollResult[source]¶
Bases:
NamedTupleVerdict from one poll of a session; see
AnthropicHook.poll_session_completion().Named rather than a bare tuple because
error_messageandstop_reasonare bothstr | None, so transposing them at a call site would still type-check.
- airflow.providers.anthropic.hooks.anthropic.evaluate_session_state(session, *, expect_outcome)[source]¶
Judge a polled session from its object fields alone.
Returns
(done, error_message, needs_event_check).done=Falsemeans keep polling.needs_event_check=Truemeans the session isidleon amessagerun and the object can’t say why — the caller must inspect the event log (seeAnthropicHook.poll_session_completion()).The
statusfield can’t distinguish a genuineend_turnfromrequires_actionorretries_exhausted, nor a just-createdidle. For an outcome run the true verdict is inoutcome_evaluations(judged here, which also defeats the start race).
- airflow.providers.anthropic.hooks.anthropic.validate_execute_complete_event(event=None)[source]¶
Validate the event a deferred task resumes with, returning it if well-formed.
The event crosses the triggerer/worker boundary through the metadata DB, so a resuming task can receive
Noneor a status its handlers do not recognize (version skew, a custom trigger). Both must fail loudly: theexecute_completehandlers raise ontimeout/errorand treat everything else as success, so an unrecognized status would otherwise silently succeed.
- airflow.providers.anthropic.hooks.anthropic.evaluate_batch_counts(*, batch_id, canceled, errored, expired, succeeded, fail_on_partial_error)[source]¶
Apply the success/skip/fail policy for a terminal batch’s request counts.
Lives in the hook module so both
AnthropicBatchOperatorandAnthropicBatchSensorshare it without an operator/sensor cross-import. RaisesAirflowSkipExceptionfor a fully-cancelled batch,AnthropicBatchJobErrorwhenfail_on_partial_errorand any request failed, otherwise returns (logging a warning for partial failures).
- class airflow.providers.anthropic.hooks.anthropic.AnthropicHook(conn_id=default_conn_name, *args, **kwargs)[source]¶
Bases:
airflow.providers.common.compat.sdk.BaseHookUse the Anthropic SDK to interact with the Claude API.
The connection’s
passwordis used as the API key andhostas an optional base URL (for gateways/proxies). Theextrafield selects the platform client and passes platform-specific configuration:platform: one ofanthropic(default),bedrock,vertex,aws,foundry.model: default model id used when an operator/hook call omitsmodel(lets you change the model without editing Dags); falls back toDEFAULT_MODEL.aws_region: region for thebedrockandawsplatforms.project_id/region: project and region for thevertexplatform.resource: Azure resource name for thefoundryplatform.anthropic_client_kwargs: extra keyword arguments forwarded to the client constructor (e.g.timeout,max_retries,default_headers).workload_identity: configure Workload Identity Federation (keyless OIDC auth) withidentity_token_file,federation_rule_id,organization_id,service_account_idand optionalworkspace_id/scope.
When the
anthropicplatform has no API Key and noworkload_identityblock, the client is built with no static credential so the SDK resolves them from the environment — supporting env-driven Workload Identity Federation andantprofiles.- Parameters:
conn_id (str) – Anthropic connection id.
- property default_model: str[source]¶
Default model id — connection
extra['model']if set, elseDEFAULT_MODEL.
- create_message(messages, model=None, max_tokens=1024, system=None, **kwargs)[source]¶
Create a single message response (one-shot
messages.create).- Parameters:
messages (list[dict[str, Any]]) – The conversation so far, as a list of message dicts.
model (str | None) – Model ID to use. Defaults to
default_model(the connection’sextra['model']orDEFAULT_MODEL).max_tokens (int) – Maximum number of tokens to generate.
system (str | None) – Optional system prompt.
- count_tokens(messages, model=None, system=None, **kwargs)[source]¶
Return the number of input tokens the given request would consume.
- create_batch(requests, model=None)[source]¶
Submit a Message Batch.
- Parameters:
requests (list[dict[str, Any]]) – A list of
{"custom_id": str, "params": {...}}dicts, whereparamsis amessages.createpayload (model,max_tokens,messages, …). A request that omitsmodelinheritsmodelbelow, or the connection’sdefault_model(extra['model']) when that is unset too.model (str | None) – Default model id for requests that do not set their own. Falls back to the connection’s
default_model.
- stream_batch_results(batch_id)[source]¶
Return a streaming iterator of per-request results, keyed by
custom_id.Results stream from the API and arrive in arbitrary order — key them by
result.custom_id, never by position. Results are available for 29 days after the batch is created. The result set can be very large: iterate and persist to object storage; do not materialize it into XCom.
- wait_for_batch(batch_id, wait_seconds=3, timeout=24 * 60 * 60)[source]¶
Poll a batch synchronously until it reaches the terminal
endedstatus.
- create_agent(name, model=None, **kwargs)[source]¶
Create a (reusable, versioned) Managed Agents agent. One-time setup.
modeldefaults todefault_model(the connection’sextra['model']orDEFAULT_MODEL). Pass a mapping instead of a bare id to set the model config, e.g.{"id": "claude-opus-5", "inference_geo": "us"}.
- create_environment(name, config=None, **kwargs)[source]¶
Create a (reusable) environment for agent sessions. One-time setup.
- create_session(agent, environment_id, **kwargs)[source]¶
Start a session against a pre-created agent + environment.
A
budgetkeyword accepts an amount in USD as well as the raw API payload; seebuild_budget().
- update_session(session_id, **kwargs)[source]¶
Update a live session – raise or clear its
budget, swapagenttools, retitle.Only the keywords you pass are sent, which matters because the API distinguishes omitted (preserve) from
None(clear). Soupdate_session(sid)changes nothing, whileupdate_session(sid, budget=None)removes the ceiling – the escape hatch for a session stopped by a model with no list price, which raising the budget cannot unblock.budgetaccepts an amount in USD or the raw payload (seebuild_budget()).agent={"tools": [...]}is a full replacement of the tool list, not a merge, and needs themid-conversation-tool-changes-2026-07-01beta.
- get_session_usage(session_id)[source]¶
Return a JSON-serializable token/cost summary for a session.
Plain scalars and a nested
list_costmapping rather than SDK models, so the result survives XCom serialization and can be queried across runs.amountis kept as the API’s minor-unit string ("44"is $0.44) rather than converted to a float, so no rounding is applied to a cost figure.Every field is optional server-side –
list_costis absent when usage includes a model with no list price – so missing values come back asNone. That absence is why every billable dimension is reported and not just the token totals: it is exactly when a caller has to reconstruct cost from usage that the breakdown must be complete. Cache writes (cache_creation) are billed above base input, and server tool calls are billed per request.
- static summarize_usage(session)[source]¶
Flatten an already-retrieved session’s usage; see
get_session_usage().Split out because
sessions.archivealso returns the session, so a caller that is tearing a session down can report its usage without a second request.Dumps the model rather than copying a fixed list of fields. The usage model sets
extra="allow", so a billable dimension added by the API is kept on the object – an allowlist here would drop it silently, which is worst precisely whenlist_costisNoneand a caller has to price the run from the breakdown.mode="json"keeps the result XCom-safe and leavesamounta minor-unit string.
- send_event(session_id, event)[source]¶
Send a single event (e.g. a
user.messageoruser.define_outcome).
- interrupt_session(session_id)[source]¶
Send
user.interruptto pause a running session.The API refuses to archive or delete a session while it is
running, so this is the only way to release one that is not going to stop on its own – seearchive_session().
- archive_session(session_id, *, attempts=6, wait_seconds=5)[source]¶
Archive a session (frees the server-side container). Best-effort teardown.
Returns the archived session, which carries its final
usage– so a caller tearing a session down does not need a separate retrieve to report what it spent.A
runningsession cannot be archived (nor deleted): the API rejects both with a 400. Only then does this interrupt the session and retry, because a session that will not stop on its own otherwise accrues billable runtime with no way to release it. Any other failure is re-raised untouched, so a transient 5xx does not senduser.interruptto a session that was working fine.Retrying costs up to
attemptsfurther calls withwait_secondsbetween them (about 25s at the defaults), which is longer than some callers have: a killed task’son_killis SIGKILLed a few seconds in, so it passes a much tighter budget.
- poll_session_completion(session_id, *, expect_outcome=False, kickoff_event_id=None)[source]¶
Return the
SessionPollResultfor one poll of a session.Combines the session object (status / outcome verdict) with the event log (
stop_reasonof the latest idle) so amessagerun distinguishes genuineend_turncompletion fromrequires_action/retries_exhausted/budget_reached.stop_reasonis the SDK’s own idle stop reason, orNonewhen the verdict did not come from an idle event (aterminatedsession, or an outcome verdict). It exists so callers can pick an error class without matching on the message text; pass it to_create_session_error().Note
A budget stop is classified on
messageruns only. Anoutcomerun is judged fromoutcome_evaluationsbefore the event log is consulted, so a budget stop there surfaces as whatever verdict the outcome recorded.
- wait_for_session(session_id, expect_outcome=False, kickoff_event_id=None, poll_interval=30, timeout=24 * 60 * 60)[source]¶
Poll a session synchronously until it completes.
- Parameters:
session_id (str) – The session to wait for.
expect_outcome (bool) – Whether the session is running a
user.define_outcomeloop (completion judged fromoutcome_evaluations).kickoff_event_id (str | None) – ID of the kickoff event, used to correlate the terminal idle event on a
messagerun (defeats the start race).poll_interval (float) – Seconds to sleep between polls.
timeout (float) – Maximum seconds to wait before raising
AnthropicAgentSessionTimeout.
- Raises:
AnthropicSessionBudgetExceeded – If the session stopped against its budget.