kaxil commented on code in PR #69003: URL: https://github.com/apache/airflow/pull/69003#discussion_r3481873710
########## providers/anthropic/src/airflow/providers/anthropic/hooks/anthropic.py: ########## @@ -0,0 +1,531 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import time +from enum import Enum +from functools import cached_property +from typing import TYPE_CHECKING, Any, cast + +from anthropic import ( + Anthropic, + AnthropicAWS, + AnthropicBedrock, + AnthropicFoundry, + AnthropicVertex, + IdentityTokenFile, + WorkloadIdentityCredentials, +) + +from airflow.providers.anthropic.exceptions import ( + AnthropicAgentSessionError, + AnthropicAgentSessionTimeout, + AnthropicBatchTimeout, + AnthropicError, +) +from airflow.providers.common.compat.sdk import BaseHook + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + + from anthropic.types import Message + from anthropic.types.beta import ( + BetaEnvironment, + BetaManagedAgentsAgent, + BetaManagedAgentsSession, + environment_create_params, + ) + from anthropic.types.beta.sessions import BetaManagedAgentsEventParams + from anthropic.types.messages import MessageBatch, MessageBatchIndividualResponse + from anthropic.types.messages.batch_create_params import Request + +#: Default model used when an operator or hook caller does not specify one. +DEFAULT_MODEL = "claude-opus-4-8" + +#: Platforms that serve the first-party-only endpoints (Message Batches, token +#: counting, the Models API). Amazon Bedrock, Google Vertex AI and Microsoft +#: Foundry do not serve these, so the hook fails fast rather than surfacing a +#: raw ``404`` from the SDK. +FIRST_PARTY_PLATFORMS = frozenset({"anthropic", "aws"}) + +AnthropicClient = Anthropic | AnthropicBedrock | AnthropicVertex | AnthropicAWS | AnthropicFoundry + + +class BatchStatus(str, Enum): + """Top-level ``processing_status`` of an Anthropic Message Batch.""" + + IN_PROGRESS = "in_progress" + CANCELING = "canceling" + ENDED = "ended" + + @classmethod + def is_in_progress(cls, status: str) -> bool: + """Return ``True`` while the batch has not reached the terminal ``ended`` status.""" + return status != cls.ENDED + + +class SessionStatus(str, Enum): + """Status of a Managed Agents session.""" + + RESCHEDULING = "rescheduling" + RUNNING = "running" + IDLE = "idle" + TERMINATED = "terminated" + + @classmethod + def is_terminal(cls, status: str) -> bool: + """ + Return ``True`` once the session has stopped working. + + ``idle`` means the agent finished its turn (done, for an autonomous run); + ``terminated`` is an unrecoverable failure. Both stop the wait. + """ + return status in (cls.IDLE, cls.TERMINATED) + + +#: ``outcome_evaluations[].result`` values that mean the outcome did NOT succeed. +OUTCOME_FAILURE_RESULTS = frozenset({"failed", "max_iterations_reached", "interrupted"}) + + +def evaluate_session_state( + session: BetaManagedAgentsSession, *, expect_outcome: bool +) -> tuple[bool, str | None, bool]: + """ + Judge a polled session from its object fields alone. + + Returns ``(done, error_message, needs_event_check)``. ``done=False`` means keep + polling. ``needs_event_check=True`` means the session is ``idle`` on a ``message`` + run and the object can't say *why* — the caller must inspect the event log (see + :meth:`AnthropicHook.poll_session_completion`). + + The ``status`` field can't distinguish a genuine ``end_turn`` from ``requires_action`` + or ``retries_exhausted``, nor a just-created ``idle``. For an outcome run the true + verdict is in ``outcome_evaluations`` (judged here, which also defeats the start race). + """ + if session.status == SessionStatus.TERMINATED: + return True, f"Session {session.id} terminated.", False + if session.status != SessionStatus.IDLE: + return False, None, False + if not expect_outcome: + return False, None, True + for evaluation in session.outcome_evaluations: + if evaluation.result == "satisfied": + return True, None, False + if evaluation.result in OUTCOME_FAILURE_RESULTS: + return True, f"Outcome not satisfied for session {session.id}: {evaluation.result}.", False + # idle but no terminal outcome verdict yet (e.g. the run has not started) + return False, None, False + + +class AnthropicHook(BaseHook): + """ + Use the Anthropic SDK to interact with the Claude API. + + The connection's ``password`` is used as the API key and ``host`` as an optional + base URL (for gateways/proxies). The ``extra`` field selects the platform client + and passes platform-specific configuration: + + - ``platform``: one of ``anthropic`` (default), ``bedrock``, ``vertex``, ``aws``, ``foundry``. + - ``model``: default model id used when an operator/hook call omits ``model`` (lets you + change the model without editing DAGs); falls back to :data:`DEFAULT_MODEL`. Review Comment: Applied in `260a157`. ########## providers/anthropic/tests/system/anthropic/example_anthropic_agent.py: ########## @@ -0,0 +1,65 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from airflow.sdk import dag, task + +ANTHROPIC_CONN_ID = "anthropic_default" + + +@dag(schedule=None, catchup=False) +def anthropic_managed_agent(): + @task + def setup_agent_and_environment() -> dict[str, str]: + # One-time setup helper — in production run this once and store the IDs, do not + # create a fresh agent every DAG run. Here we create them and pass the IDs via XCom. Review Comment: Applied in `260a157`. ########## providers/anthropic/tests/system/anthropic/example_anthropic_batch.py: ########## @@ -0,0 +1,81 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from typing import Any + +from airflow.sdk import dag, task + +ANTHROPIC_CONN_ID = "anthropic_default" +MODEL = "claude-opus-4-8" + +POKEMON = ["pikachu", "charmander", "bulbasaur"] + + +@dag(schedule=None, catchup=False) +def anthropic_batch_messages(): + @task + def build_requests(names: list[str]) -> list[dict[str, Any]]: + return [ + { + "custom_id": name, + "params": { + "model": MODEL, + "max_tokens": 256, + "messages": [{"role": "user", "content": f"Describe {name} in one sentence."}], + }, + } + for name in names + ] + + @task + def collect_results(batch_id: str) -> dict[str, str]: + # Results stream from the API unordered; key them by custom_id. For large + # batches, persist to object storage instead of returning via XCom. + from airflow.providers.anthropic.hooks.anthropic import AnthropicHook + + hook = AnthropicHook(conn_id=ANTHROPIC_CONN_ID) + summaries: dict[str, str] = {} + for entry in hook.stream_batch_results(batch_id): + if entry.result.type == "succeeded": + text = next((b.text for b in entry.result.message.content if b.type == "text"), "") + summaries[entry.custom_id] = text + return summaries + + requests = build_requests(POKEMON) + + # [START howto_operator_anthropic_batch] + from airflow.providers.anthropic.operators.anthropic import AnthropicBatchOperator + + run_batch = AnthropicBatchOperator( + task_id="run_batch", + conn_id=ANTHROPIC_CONN_ID, + requests=requests, + deferrable=True, + ) + # [END howto_operator_anthropic_batch] + + collect_results(batch_id=run_batch.output) + + +anthropic_batch_messages() + + +from tests_common.test_utils.system_tests import get_test_run # noqa: E402 + +# Needed to run the example DAG with pytest (see: contributing-docs/testing/system_tests.rst) Review Comment: Applied in `260a157`. ########## providers/anthropic/tests/system/anthropic/example_anthropic_agent.py: ########## @@ -0,0 +1,65 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from airflow.sdk import dag, task + +ANTHROPIC_CONN_ID = "anthropic_default" + + +@dag(schedule=None, catchup=False) +def anthropic_managed_agent(): + @task + def setup_agent_and_environment() -> dict[str, str]: + # One-time setup helper — in production run this once and store the IDs, do not + # create a fresh agent every DAG run. Here we create them and pass the IDs via XCom. + from airflow.providers.anthropic.hooks.anthropic import AnthropicHook + + hook = AnthropicHook(conn_id=ANTHROPIC_CONN_ID) + agent = hook.create_agent( + name="airflow-research-agent", + system="You are a concise research assistant.", + tools=[{"type": "agent_toolset_20260401"}], + ) + environment = hook.create_environment(name="airflow-agent-env") + return {"agent_id": agent.id, "environment_id": environment.id} + + setup = setup_agent_and_environment() + + # [START howto_operator_anthropic_agent_session] + from airflow.providers.anthropic.operators.agent import AnthropicAgentSessionOperator + + run_agent = AnthropicAgentSessionOperator( + task_id="run_agent", + conn_id=ANTHROPIC_CONN_ID, + agent_id=setup["agent_id"], + environment_id=setup["environment_id"], + message="Summarize the latest stable Apache Airflow release in two sentences.", + deferrable=True, + ) + # [END howto_operator_anthropic_agent_session] + + run_agent + + +anthropic_managed_agent() + + +from tests_common.test_utils.system_tests import get_test_run # noqa: E402 + +# Needed to run the example DAG with pytest (see: contributing-docs/testing/system_tests.rst) Review Comment: Applied in `260a157`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
