gopidesupavan commented on code in PR #67438:
URL: https://github.com/apache/airflow/pull/67438#discussion_r3299427927


##########
providers/common/ai/src/airflow/providers/common/ai/hooks/base_ai.py:
##########
@@ -0,0 +1,353 @@
+# 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.
+"""Shared contract for agent-framework hooks used by 
:class:`~airflow.providers.common.ai.operators.agent.AgentOperator`."""
+
+from __future__ import annotations
+
+import functools
+import inspect
+import json
+import time
+from abc import ABCMeta, abstractmethod
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import Any, ClassVar
+
+from airflow.providers.common.compat.sdk import BaseHook
+
+
+@dataclass
+class AgentUsage:
+    """Token and request usage from an agent run, when the backend exposes 
it."""
+
+    requests: int = 0
+    tool_calls: int = 0
+    input_tokens: int = 0
+    output_tokens: int = 0
+    total_tokens: int = 0
+
+
+@dataclass
+class DurableStats:
+    """Step-level cache statistics from a durable agent run."""
+
+    replayed_model: int = 0
+    replayed_tool: int = 0
+    cached_model: int = 0
+    cached_tool: int = 0
+
+
+@dataclass
+class AgentRunResult:
+    """
+    Backend-neutral result from :meth:`BaseAIHook.run_agent`.
+
+    :param output: Final agent output (``str``, Pydantic model instance, etc.).
+    :param message_history: Opaque conversation state for HITL regeneration; 
only pass back to the
+        same hook implementation that produced it.
+    :param model_name: Resolved model identifier, when available.
+    :param usage: Usage counters when the backend exposes them.
+    :param tool_names: Ordered tool names invoked during the run, when known.
+    :param durable_stats: Durable step-cache statistics, populated when 
durable execution is enabled.
+    """
+
+    output: Any
+    message_history: Any = None
+    model_name: str | None = None
+    usage: AgentUsage | None = None
+    tool_names: list[str] | None = None
+    durable_stats: DurableStats | None = None
+
+
+@dataclass
+class ToolSpec:
+    """
+    Framework-neutral tool descriptor.
+
+    Toolsets produce :class:`ToolSpec` objects; each hook converts them to its
+    native tool representation via :meth:`BaseAIHook._tool_spec_to_native`.
+
+    :param name: Tool name exposed to the LLM.
+    :param description: Human-readable description used by the LLM to decide 
when to call this tool.
+    :param parameters: JSON Schema ``object`` describing the tool's parameters.
+    :param fn: Callable that implements the tool. Must accept keyword 
arguments matching *parameters*.
+    """
+
+    name: str
+    description: str
+    parameters: dict[str, Any]
+    fn: Callable[..., Any]
+
+
+@dataclass
+class DurableContext:
+    """Framework-neutral identity of the running task, used to locate the 
durable cache file."""
+
+    dag_id: str
+    task_id: str
+    run_id: str
+    map_index: int = -1
+
+
+@dataclass
+class AgentRunRequest:
+    """
+    Parameter object passed to :meth:`BaseAIHook.create_agent` and 
:meth:`BaseAIHook.run_agent`.
+
+    Encapsulates everything the hook needs to build and run an agent in a 
single
+    framework-neutral structure, so that 
:class:`~airflow.providers.common.ai.operators.agent.AgentOperator`
+    has zero framework-specific imports.
+
+    :param prompt: User prompt for this invocation.
+    :param output_type: Expected structured output type (default: ``str``).
+    :param instructions: System-level instructions for the agent.
+    :param toolsets: List of :class:`BaseToolset` instances the agent may call.
+    :param usage_limits: Backend-specific usage limits; ignored if the hook 
does not support them.
+    :param message_history: Prior conversation state from a previous 
:class:`AgentRunResult`.
+    :param enable_tool_logging: When ``True`` (default), wraps each tool 
callable with a logging shim.
+    :param durable_context: When set, enables step-level durable caching for 
the run.
+    :param agent_params: Extra keyword arguments forwarded to the underlying 
agent constructor.
+        Use this escape hatch for framework-specific options.
+    """
+
+    prompt: str
+    output_type: type[Any] = str
+    instructions: str = ""
+    toolsets: list[Any] | None = None
+    usage_limits: Any = None
+    message_history: Any = None
+    enable_tool_logging: bool = True
+    durable_context: DurableContext | None = None
+    agent_params: dict[str, Any] = field(default_factory=dict)
+
+
+class BaseToolset(metaclass=ABCMeta):
+    """
+    Abstract base for framework-agnostic toolsets.
+
+    Subclasses implement :meth:`as_tools` to return a list of :class:`ToolSpec`
+    objects.  Each hook converts those specs to its native tool representation
+    via :meth:`BaseAIHook._tool_spec_to_native`.
+    """
+
+    @abstractmethod
+    def as_tools(self) -> list[ToolSpec]:
+        """Return the list of tools this toolset exposes."""
+
+
+class BaseAIHook(BaseHook, metaclass=ABCMeta):
+    """
+    Abstract hook for multi-turn LLM agents.
+
+    :class:`~airflow.providers.common.ai.operators.agent.AgentOperator` 
resolves the concrete hook
+    from the Airflow connection ``conn_type`` (for example ``pydanticai`` or 
``pydanticai-bedrock``).
+
+    Subclasses implement :meth:`get_model`, :meth:`create_agent`, 
:meth:`run_agent`, and
+    :meth:`_tool_spec_to_native`.
+
+    Shared helpers :meth:`_init_durable`, :meth:`_resolve_tools`, 
:meth:`_logged_callable`, and
+    :meth:`_cached_callable` are provided for all hooks.
+    """
+
+    conn_name_attr = "llm_conn_id"
+
+    supports_toolsets: ClassVar[bool] = False
+    supports_durable: ClassVar[bool] = False
+    supports_usage_limits: ClassVar[bool] = False
+
+    @classmethod
+    def get_agent_hook(cls, conn_id: str, *, hook_params: dict[str, Any] | 
None = None) -> BaseAIHook:
+        """
+        Return an agent hook for *conn_id*, verifying it implements this 
contract.
+
+        Uses the connection's ``conn_type`` to select the hook class 
registered in
+        ``provider.yaml``.
+        """
+        hook = cls.get_hook(conn_id, hook_params=hook_params)

Review Comment:
   agree updated 



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