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`](https://github.com/apache/airflow/pull/69003/commits/260a157f944e129f2857c147362e202856041f04).



-- 
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]

Reply via email to