airflow.providers.anthropic.operators.agent¶
Classes¶
Run a Managed Agents session against a pre-created agent and environment. |
Module Contents¶
- class airflow.providers.anthropic.operators.agent.AnthropicAgentSessionOperator(*, agent_id, environment_id, message=None, outcome=None, conn_id=AnthropicHook.default_conn_name, deferrable=conf.getboolean('operators', 'default_deferrable', fallback=False), poll_interval=30, timeout=24 * 60 * 60, budget=None, vault_ids=None, session_resources=None, session_kwargs=None, **kwargs)[source]¶
Bases:
airflow.providers.common.compat.sdk.BaseOperatorRun a Managed Agents session against a pre-created agent and environment.
Anthropic runs the agent loop server-side; the worker creates a session, sends the initial instruction, and waits for the session to reach a terminal status. In deferrable mode it releases the worker slot while a trigger polls the session status.
Provide exactly one of
message(a single user turn) oroutcome(auser.define_outcomerubric that the agent iterates against until satisfied).Important
This operator is for autonomous agents — configure the agent without client-side custom tools or an
always_askpermission policy.Completion is detected accurately for both modes. A
messagerun reads the terminalsession.status_idleevent’sstop_reason(correlated against the kickoff event to avoid a start-race false positive):end_turnsucceeds, whilerequires_action(the agent is blocked on input),retries_exhaustedandbudget_reachedraise an error rather than silently passing. Anoutcomerun is judged from the session’soutcome_evaluationsverdict (satisfiedvs.failed/max_iterations_reached/interrupted).Agents and environments are created once (see
create_agent()), not per task run.Outputs the agent writes to
/mnt/session/outputs/are retrieved afterwards via the Files API (scope_id=<session_id>); the operator returns the session ID only.The session’s token counts and list cost are pushed to XCom under
usageon both success and failure, so cost per Dag run can be queried. This matters because a budget is a stop trigger rather than a cap: the ceiling is checked between model requests, so it does not tell you what the session actually spent.See also
For more information, take a look at the guide: AnthropicAgentSessionOperator
- Parameters:
agent_id (str) – ID of a pre-created agent.
environment_id (str) – ID of a pre-created environment.
message (str | None) – A single user message to start the session. Mutually exclusive with
outcome.outcome (dict[str, Any] | None) – A
user.define_outcomepayload (description,rubric, optionalmax_iterations). Mutually exclusive withmessage.conn_id (str) – The Anthropic connection ID to use.
deferrable (bool) – Run the operator in deferrable mode.
poll_interval (float) – Seconds between session status checks (both paths).
timeout (float) – Seconds to wait for a terminal status. Defaults to 24 hours. In deferrable mode the trigger enforces this and tears the session down on timeout; set
execution_timeoutonly for a shorter hard cap (which preempts that graceful teardown).vault_ids (list[str] | None) – Vault IDs providing MCP/credential access to the session.
session_resources (list[dict[str, Any]] | None) – Session resources (files, GitHub repos, memory stores). Named
session_resourcesto avoid colliding with the reservedBaseOperator.resources; forwarded tosessions.createasresources.budget (airflow.providers.anthropic.hooks.anthropic.BudgetSpec | None) –
Spend ceiling for the session. A number or numeric string is read as US dollars (
budget=25is $25.00); a mapping is passed through as the raw API payload. On amessagerun, a session that stops against it raisesAnthropicSessionBudgetExceeded. On anoutcomerun completion is judged fromoutcome_evaluationsbefore the idle event is consulted, so a budget stop surfaces as the outcome verdict and the genericAnthropicAgentSessionErrorinstead.Warning
The ceiling is a stop trigger, not a cap. It is checked between model requests, so a request already in flight runs to completion and the session can finish well above the limit. Airflow
retriesalso each start a new session with a fresh budget, so preferretries=0when a budget is set.session_kwargs (dict[str, Any] | None) – Extra keyword arguments forwarded to
sessions.create. Settingbudgethere as well as via thebudgetargument is rejected.
- template_fields: collections.abc.Sequence[str] = ('agent_id', 'environment_id', 'message', 'outcome', 'budget')[source]¶
- property hook: airflow.providers.anthropic.hooks.anthropic.AnthropicHook[source]¶
Return an instance of the AnthropicHook.
- execute(context)[source]¶
Derive when creating an operator.
The main method to execute the task. Context is the same dictionary used as when rendering jinja templates.
Refer to get_template_context for more context.
- on_kill()[source]¶
Archive the session if the (non-deferred) task is killed.
Only fires while the worker process is alive, i.e. the synchronous path (
deferrable=False). On Airflow 3.3+ a killed deferred task is archived by the trigger’son_kill. On older Airflow the session of a killed deferred task is not archived automatically; archive it manually via the hook.The supervisor escalates to SIGKILL a few seconds after asking the task to stop, so the hook’s default retry budget would never finish here – the process dies inside the first sleep and the session is never released. This budget gives the interrupt a beat to land (the status change is not instant) while still fitting inside that window: two attempts, one second apart.