vatsrahul1001 commented on code in PR #73962:
URL: https://github.com/apache/airflow/pull/73962#discussion_r4267952853


##########
providers/common/ai/src/airflow/providers/common/ai/tools/anthropic.py:
##########
@@ -0,0 +1,264 @@
+# 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.
+"""
+Give Airflow tools to an agent loop run by the Anthropic SDK's tool runner.
+
+.. note:: Experimental; see :mod:`airflow.providers.common.ai.tools`.
+"""
+
+from __future__ import annotations
+
+import copy
+import logging
+from collections.abc import Callable, Coroutine, Iterator
+from contextlib import AbstractContextManager, contextmanager
+from contextvars import ContextVar
+from typing import TYPE_CHECKING, Any, TypeVar
+
+try:
+    from anthropic.lib.tools import (
+        BetaAsyncFunctionTool,
+        BetaAsyncToolRunner,
+        BetaFunctionTool,
+        BetaToolRunner,
+        ToolError,
+        beta_async_tool,
+        beta_tool,
+    )
+except ImportError as e:
+    from airflow.providers.common.compat.sdk import 
AirflowOptionalProviderFeatureException
+
+    raise AirflowOptionalProviderFeatureException(e)
+
+from airflow.providers.common.ai.tools import AirflowTool, ToolCallError, 
collect_tools
+from airflow.providers.common.ai.tools._from_toolset import tool_call_scope
+from airflow.providers.common.ai.utils.coroutines import run_coroutine_sync
+from airflow.providers.common.ai.utils.tool_definition import serialize_for_llm
+from airflow.providers.common.ai.utils.tool_metrics import calling_framework
+
+if TYPE_CHECKING:
+    from anthropic.types.beta import BetaMessage
+    from anthropic.types.beta.parsed_beta_message import ParsedBetaMessage
+
+    from airflow.providers.common.ai.tools import ToolProvider
+
+log = logging.getLogger(__name__)
+
+__all__ = ["AirflowTools", "AsyncAirflowTools"]
+
+# The ``output_format`` a runner parses its final message into.
+_OutputT = TypeVar("_OutputT")
+
+# The failures of the run in progress. ``run`` sets it, the tools append to it.
+_failures: ContextVar[list[ToolCallError] | None] = 
ContextVar("common_ai_anthropic_failures", default=None)
+
+
+class AirflowTools:
+    """
+    Airflow's tools for the tool runner of a synchronous ``Anthropic`` client.
+
+    Pass toolsets that implement
+    :class:`~airflow.providers.common.ai.tools.ToolProvider`, such as 
``SQLToolset``
+    and ``HookToolset``, or individual
+    :class:`~airflow.providers.common.ai.tools.AirflowTool` objects. Give 
:attr:`tools`
+    to ``client.beta.messages.tool_runner`` and drive the runner with 
:meth:`run`:
+
+    .. code-block:: python
+
+        from anthropic import Anthropic
+
+        from airflow.providers.common.ai.tools.anthropic import AirflowTools
+        from airflow.providers.common.ai.toolsets import SQLToolset
+
+        client = Anthropic()
+        tools = AirflowTools(SQLToolset("warehouse", 
allowed_tables=["orders"]))
+        runner = client.beta.messages.tool_runner(
+            model="claude-opus-5-5",
+            max_tokens=16000,
+            tools=tools.tools,
+            messages=[...],
+        )
+        message = tools.run(runner)
+
+    Each tool keeps the source tool's name, description and argument schema, 
and every
+    result passes through Airflow's secret masker first. A failure the model 
can
+    correct, such as a query naming a missing column, reaches it as a 
``tool_result``
+    with ``is_error: true``, counted against the tool's retry limit once per 
model
+    turn. A tool that is still failing once the limit is used up, or a failure 
the
+    model cannot fix, such as a hook raising, makes :meth:`run` raise
+    :class:`~airflow.providers.common.ai.tools.ToolCallError` before the next 
model
+    request, so the task fails and Airflow retries it. The runner on its own 
hands
+    every exception back to the model, so drive it with :meth:`run` rather than
+    ``until_done()``. A runner created with ``stream=True`` is not supported.
+
+    For an ``AsyncAnthropic`` client, use :class:`AsyncAirflowTools`.
+
+    :param sources: Toolsets and tools to add, in order.
+    """
+
+    def __init__(self, *sources: ToolProvider | AirflowTool) -> None:
+        self.tools: list[BetaFunctionTool[Callable[..., str]]] = [
+            _sync_tool(tool) for tool in collect_tools(sources)
+        ]
+
+    def run(self, runner: BetaToolRunner[_OutputT]) -> 
ParsedBetaMessage[_OutputT]:
+        """
+        Drive ``runner`` to its final message.
+
+        :raises ToolCallError: when a tool failed in a way the model cannot 
fix.
+        """
+        with _run() as turn:
+            for message in runner:
+                with turn(message.id):
+                    if _runs_tools(message):
+                        runner.generate_tool_call_response()
+        return runner.until_done()

Review Comment:
   If the runner stops at `max_iterations` while the model is still asking for 
tools, I think this returns that last `tool_use` message. Callers that join the 
text blocks then get `""`, and the task succeeds with no answer and nothing in 
the log (the example DAG does exactly this).
   
   Would it make sense to raise here when the final `stop_reason == 
"tool_use"`? That would cover the async `run()` below and any caller, not just 
the example. I didn't see a test for the exhaustion case either.



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