kaxil commented on code in PR #69003: URL: https://github.com/apache/airflow/pull/69003#discussion_r3481872689
########## providers/anthropic/src/airflow/providers/anthropic/operators/anthropic.py: ########## @@ -0,0 +1,236 @@ +# 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 logging +import time +from collections.abc import Sequence +from datetime import timedelta +from functools import cached_property +from typing import TYPE_CHECKING, Any + +from airflow.providers.anthropic.exceptions import AnthropicBatchJobError, AnthropicBatchTimeout +from airflow.providers.anthropic.hooks.anthropic import AnthropicHook +from airflow.providers.anthropic.triggers.anthropic import AnthropicBatchTrigger +from airflow.providers.common.compat.sdk import AirflowSkipException, BaseOperator, conf + +if TYPE_CHECKING: + from airflow.providers.common.compat.sdk import Context + +logger = logging.getLogger(__name__) + + +def evaluate_batch_counts( Review Comment: Good call. Moved it into the hook module (`hooks/anthropic.py`) so the sensor no longer imports from operators. Done in `260a157`. ########## providers/anthropic/tests/unit/anthropic/operators/test_agent.py: ########## @@ -0,0 +1,178 @@ +# 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 unittest import mock + +import pytest + +from airflow.exceptions import TaskDeferred +from airflow.providers.anthropic.exceptions import AnthropicAgentSessionError, AnthropicAgentSessionTimeout +from airflow.providers.anthropic.operators.agent import AnthropicAgentSessionOperator +from airflow.providers.anthropic.triggers.agent import AnthropicAgentSessionTrigger + +pytest.importorskip("anthropic") + + +def _context(): + return {"ti": mock.MagicMock()} + + +def test_requires_exactly_one_of_message_or_outcome(): + with pytest.raises(ValueError, match="exactly one"): + AnthropicAgentSessionOperator(task_id="a", agent_id="ag", environment_id="env") + with pytest.raises(ValueError, match="exactly one"): + AnthropicAgentSessionOperator( + task_id="a", agent_id="ag", environment_id="env", message="hi", outcome={"description": "x"} + ) + + +def test_outcome_requires_rubric(): + with pytest.raises(ValueError, match="rubric"): + AnthropicAgentSessionOperator( + task_id="a", agent_id="ag", environment_id="env", outcome={"description": "x"} + ) + + +class TestExecute: + @mock.patch.object(AnthropicAgentSessionOperator, "hook", new_callable=mock.PropertyMock) + def test_message_sends_user_message_and_waits(self, mock_hook_prop): + hook = mock.MagicMock() + hook.create_session.return_value.id = "sess_1" + mock_hook_prop.return_value = hook + + op = AnthropicAgentSessionOperator( + task_id="a", agent_id="ag", environment_id="env", message="summarize", deferrable=False + ) + context = _context() + assert op.execute(context) == "sess_1" + hook.create_session.assert_called_once_with(agent="ag", environment_id="env") + hook.send_event.assert_called_once_with( + "sess_1", {"type": "user.message", "content": [{"type": "text", "text": "summarize"}]} + ) + hook.wait_for_session.assert_called_once() + context["ti"].xcom_push.assert_called_once_with(key="session_id", value="sess_1") + + @mock.patch.object(AnthropicAgentSessionOperator, "hook", new_callable=mock.PropertyMock) + def test_outcome_sends_define_outcome(self, mock_hook_prop): + hook = mock.MagicMock() Review Comment: Added `spec=AnthropicHook` to the hook mocks across the operator and sensor tests (`260a157`). I left the SDK return-object mocks (batch/counts/session) as plain `MagicMock` for now, since speccing the pydantic SDK types is brittle. Happy to autospec those too if you'd prefer. ########## 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" Review Comment: Applied in `260a157`, thanks. ########## providers/anthropic/docs/index.rst: ########## @@ -0,0 +1,130 @@ + +.. 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. + +``apache-airflow-providers-anthropic`` +====================================== + + +.. toctree:: + :hidden: + :maxdepth: 1 + :caption: Basics + + Home <self> + Changelog <changelog> + Security <security> + +.. toctree:: + :hidden: + :maxdepth: 1 + :caption: Guides + + Connection types <connections> + Operators <operators/anthropic> + + +.. toctree:: + :hidden: + :maxdepth: 1 + :caption: Resources + + Python API <_api/airflow/providers/anthropic/index> + PyPI Repository <https://pypi.org/project/apache-airflow-providers-anthropic/> + Installing from sources <installing-providers-from-sources> + +.. toctree:: + :hidden: + :maxdepth: 1 + :caption: System tests + + System Tests <_api/tests/system/anthropic/index> + +.. THE REMAINDER OF THE FILE IS AUTOMATICALLY GENERATED. IT WILL BE OVERWRITTEN AT RELEASE TIME! + + +.. toctree:: + :hidden: + :maxdepth: 1 + :caption: Commits + + Detailed list of commits <commits> + + +apache-airflow-providers-anthropic package +------------------------------------------------------ + +`Anthropic <https://docs.claude.com/>`__ provider for Apache Airflow. +Wraps the official Anthropic Python SDK to run the Claude Message Batches API +asynchronously from Airflow, plus direct message and token-counting helpers. + + +Release: 0.1.0 + +Provider package +---------------- + +This package is for the ``anthropic`` provider. +All classes for this package are included in the ``airflow.providers.anthropic`` python package. + +Installation +------------ + +You can install this package on top of an existing Airflow installation via +``pip install apache-airflow-providers-anthropic``. +For the minimum Airflow version supported, see ``Requirements`` below. + +Requirements +------------ + +The minimum Apache Airflow version supported by this provider distribution is ``3.0.0``. + +========================================== ================== +PIP package Version required +========================================== ================== +``apache-airflow`` ``>=3.0.0`` +``apache-airflow-providers-common-compat`` ``>=1.12.0`` Review Comment: common.ai is deliberately provider-agnostic, a neutral surface across LLM providers. This provider exposes Anthropic-specific surfaces that don't fit a neutral interface: Message Batches, Managed Agents sessions, token counting, and the five platform clients (first-party / Bedrock / Vertex / AWS / Foundry) with Workload Identity Federation. There's no common.ai equivalent to reuse today, and folding these in would either leak Anthropic specifics into the neutral layer or pin it to a lowest common denominator. They're complementary: common.ai for portable LLM calls, this provider for direct Claude/SDK features. If a genuinely cross-provider primitive emerges later (e.g. a generic batch interface), that's the right thing to lift into common.ai at that point. ########## 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: Review Comment: Fair point. `canceling` is non-terminal (we poll until `ended`), so it returns True too, which reads oddly next to the `in_progress` enum value. The method really means "not yet terminal"; I kept the name to mirror the SDK's `processing_status` vocabulary. Happy to rename it to `is_not_terminal` (or add a docstring note) if you'd prefer, let me know. ########## providers/anthropic/docs/connections.rst: ########## @@ -0,0 +1,106 @@ + .. 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. + +.. _howto/connection:anthropic: + +Anthropic Connection +==================== + +The `Anthropic <https://www.anthropic.com/>`__ connection type enables access to the Claude API +through the official Anthropic Python SDK. + +Default Connection IDs +---------------------- + +The Anthropic hook points to the ``anthropic_default`` connection by default. + +Configuring the Connection +-------------------------- + +API Key + Your Anthropic API key. Required for the first-party API (``platform="anthropic"``), + and also used as the Microsoft Foundry API key (``platform="foundry"``, together with + the ``resource`` extra). Not required for the ``bedrock``, ``vertex`` or ``aws`` + platforms, which authenticate through the respective cloud provider's credential chain. + +Base URL (optional) + A custom base URL for the first-party API (for example, an LLM gateway or proxy). + +Extra (optional) + A JSON dictionary of additional parameters. All keys are optional: + + * ``platform`` — which client to build: ``anthropic`` (default), ``bedrock``, ``vertex``, + ``aws`` or ``foundry``. + * ``model`` — default model id used whenever an operator or hook call does not pass + ``model`` (e.g. ``hook.create_message(...)``, ``hook.create_agent(...)``). Set it here + to change the model without editing DAGs; falls back to the provider default + (``claude-opus-4-8``). + * ``aws_region`` — AWS region for the ``bedrock`` platform. + * ``project_id`` / ``region`` — GCP project and region for the ``vertex`` platform. + * ``resource`` — Azure resource name for the ``foundry`` platform. + * ``anthropic_client_kwargs`` — a nested dictionary forwarded verbatim to the client + constructor (for example ``timeout``, ``max_retries`` or ``default_headers``). + + For example, to set the client timeout: + + .. code-block:: json Review Comment: Agreed, leaving as-is for this PR. ########## providers/anthropic/docs/connections.rst: ########## @@ -0,0 +1,106 @@ + .. 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. + +.. _howto/connection:anthropic: + +Anthropic Connection +==================== + +The `Anthropic <https://www.anthropic.com/>`__ connection type enables access to the Claude API +through the official Anthropic Python SDK. + +Default Connection IDs +---------------------- + +The Anthropic hook points to the ``anthropic_default`` connection by default. + +Configuring the Connection +-------------------------- + +API Key + Your Anthropic API key. Required for the first-party API (``platform="anthropic"``), + and also used as the Microsoft Foundry API key (``platform="foundry"``, together with + the ``resource`` extra). Not required for the ``bedrock``, ``vertex`` or ``aws`` + platforms, which authenticate through the respective cloud provider's credential chain. + +Base URL (optional) + A custom base URL for the first-party API (for example, an LLM gateway or proxy). + +Extra (optional) + A JSON dictionary of additional parameters. All keys are optional: + + * ``platform`` — which client to build: ``anthropic`` (default), ``bedrock``, ``vertex``, + ``aws`` or ``foundry``. + * ``model`` — default model id used whenever an operator or hook call does not pass + ``model`` (e.g. ``hook.create_message(...)``, ``hook.create_agent(...)``). Set it here + to change the model without editing DAGs; falls back to the provider default 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]
