You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "br413 (via GitHub)" <gi...@apache.org> on 2026/07/21 11:34:55 UTC

[PR] Add deferrable LLMOperator with LLMTrigger [airflow]

br413 opened a new pull request, #70184:
URL: https://github.com/apache/airflow/pull/70184

   ## Summary
   - Add `LLMTrigger` to run pydantic-ai `agent.run()` in the triggerer
   - Add `deferrable=True` on `LLMOperator` to free worker slots during LLM API calls
   - Rehydrate `output_type` on resume; `require_approval` chains after deferrable completion
   
   Step 1 of #70093
   
   ## Test plan
   - [ ] `pytest providers/common/ai/tests/unit/common/ai/triggers/test_llm.py`
   - [ ] `pytest providers/common/ai/tests/unit/common/ai/operators/test_llm.py -k Deferrable`
   - [ ] `pytest providers/common/ai/tests/unit/common/ai/utils/test_output_type.py -k Serialization`
   - [ ] CI provider-common-ai checks pass


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add deferrable LLMOperator with LLMTrigger [airflow]

Posted by "br413 (via GitHub)" <gi...@apache.org>.
br413 commented on code in PR #70184:
URL: https://github.com/apache/airflow/pull/70184#discussion_r3623026162


##########
providers/common/ai/src/airflow/providers/common/ai/operators/llm.py:
##########
@@ -154,6 +164,25 @@ def llm_hook(self) -> PydanticAIHook:
         }
         return PydanticAIHook.get_hook(self.llm_conn_id, hook_params=hook_params)
 
+    def _finalize_output(self, output: Any) -> Any:
+        if self._serialize_model_output and isinstance(output, BaseModel):
+            return output.model_dump()
+        return output
+
+    def _defer_llm_call(self) -> None:

Review Comment:
   Agreed — those helpers did not carry enough logic to justify the indirection. I inlined the defer call in execute() and the output serialization at each return path in 061ad47.



##########
providers/common/ai/src/airflow/providers/common/ai/operators/llm.py:
##########
@@ -173,17 +206,31 @@ def execute(self, context: Context) -> Any:
         if self.require_approval:
             self.defer_for_approval(context, output)  # type: ignore[misc]
 
-        if self._serialize_model_output and isinstance(output, BaseModel):
-            # ``serialize_output=True``, or a core without the worker-side
-            # deserialization-class walk: dump to a dict so XCom carries a plain
-            # JSON payload that deserializes without an allow-list entry.
-            output = output.model_dump()
+        return self._finalize_output(output)
 
-        return output
+    def execute_complete(
+        self,
+        context: Context,
+        event: dict[str, Any],
+        generated_output: str | None = None,
+    ) -> Any:
+        """Resume after deferrable LLM execution or human review."""
+        if generated_output is not None:
+            output = super().execute_complete(context, generated_output, event)
+            return rehydrate_pydantic_output(
+                self.output_type, output, serialize_output=self._serialize_model_output
+            )
 
-    def execute_complete(self, context: Context, generated_output: str, event: dict[str, Any]) -> Any:
-        """Resume after human review and restore the Pydantic model for XCom consumers."""
-        output = super().execute_complete(context, generated_output, event)
-        return rehydrate_pydantic_output(
-            self.output_type, output, serialize_output=self._serialize_model_output
+        if event.get("status") == "error":
+            raise AirflowException(event.get("message", "LLM call failed in deferrable mode"))

Review Comment:
   Thanks for the pointer to the contributing guide. I added LLMOperatorException under providers/common/ai/exceptions.py (same pattern as OpenAIBatchJobException) and use that in execute_complete instead of raising AirflowException directly. Updated in 061ad47.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add deferrable LLMOperator with LLMTrigger [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on PR #70184:
URL: https://github.com/apache/airflow/pull/70184#issuecomment-5037269704

   Thanks for the work here, and for turning the review comments around quickly.
   
   I'm going to close this along with #70093. The short version: the triggerer is the wrong home for an LLM/agent call. A trigger's `run()` has to be idempotent and side-effect-free because it re-runs on any triggerer restart or redistribution, and a billed, non-deterministic `agent.run()` with tools executing in-process is neither. `LLMTrigger.run()` here re-issues the whole call from scratch on every relaunch, so a restart mid-flight re-bills it, which is the opposite of the "no re-billed calls" property the issue is after. I've left the full reasoning, and the primitives that do fit (3.2 async tasks for slot-free concurrency, `AgentOperator(durable=True)` for replay-safe long runs), on #70093.
   
   Appreciate the effort, and sorry to send it back. This one's an architecture-direction call, not a comment on the code itself.
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add deferrable LLMOperator with LLMTrigger [airflow]

Posted by "br413 (via GitHub)" <gi...@apache.org>.
br413 commented on code in PR #70184:
URL: https://github.com/apache/airflow/pull/70184#discussion_r3623024173


##########
providers/common/ai/src/airflow/providers/common/ai/triggers/llm.py:
##########
@@ -0,0 +1,112 @@
+# 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 collections.abc import AsyncIterator
+from typing import Any
+
+from airflow.providers.common.ai.hooks.pydantic_ai import PydanticAIHook
+from airflow.providers.common.ai.utils.logging import log_run_summary
+from airflow.providers.common.ai.utils.output_type import (
+    deserialize_output_type,
+    serialize_llm_output,
+)
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+def serialize_usage_limits(usage_limits: Any | None) -> dict[str, Any] | None:
+    """Serialize pydantic-ai ``UsageLimits`` for trigger persistence."""
+    if usage_limits is None:
+        return None
+    return usage_limits.model_dump(exclude_defaults=True)
+
+
+def deserialize_usage_limits(data: dict[str, Any] | None) -> Any | None:
+    """Restore pydantic-ai ``UsageLimits`` from trigger persistence."""
+    if data is None:
+        return None
+    from pydantic_ai.usage import UsageLimits

Review Comment:
   Good catch — there was no need for a lazy import here. pydantic-ai is already a provider dependency, so I moved UsageLimits to the module level in 061ad47.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add deferrable LLMOperator with LLMTrigger [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #70184:
URL: https://github.com/apache/airflow/pull/70184#discussion_r3622885796


##########
providers/common/ai/src/airflow/providers/common/ai/operators/llm.py:
##########
@@ -154,6 +164,25 @@ def llm_hook(self) -> PydanticAIHook:
         }
         return PydanticAIHook.get_hook(self.llm_conn_id, hook_params=hook_params)
 
+    def _finalize_output(self, output: Any) -> Any:
+        if self._serialize_model_output and isinstance(output, BaseModel):
+            return output.model_dump()
+        return output
+
+    def _defer_llm_call(self) -> None:

Review Comment:
   why do we need to make it a separate method



##########
providers/common/ai/src/airflow/providers/common/ai/triggers/llm.py:
##########
@@ -0,0 +1,112 @@
+# 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 collections.abc import AsyncIterator
+from typing import Any
+
+from airflow.providers.common.ai.hooks.pydantic_ai import PydanticAIHook
+from airflow.providers.common.ai.utils.logging import log_run_summary
+from airflow.providers.common.ai.utils.output_type import (
+    deserialize_output_type,
+    serialize_llm_output,
+)
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+def serialize_usage_limits(usage_limits: Any | None) -> dict[str, Any] | None:
+    """Serialize pydantic-ai ``UsageLimits`` for trigger persistence."""
+    if usage_limits is None:
+        return None
+    return usage_limits.model_dump(exclude_defaults=True)
+
+
+def deserialize_usage_limits(data: dict[str, Any] | None) -> Any | None:
+    """Restore pydantic-ai ``UsageLimits`` from trigger persistence."""
+    if data is None:
+        return None
+    from pydantic_ai.usage import UsageLimits

Review Comment:
   why do we need to do inline import here



##########
providers/common/ai/src/airflow/providers/common/ai/operators/llm.py:
##########
@@ -173,17 +206,31 @@ def execute(self, context: Context) -> Any:
         if self.require_approval:
             self.defer_for_approval(context, output)  # type: ignore[misc]
 
-        if self._serialize_model_output and isinstance(output, BaseModel):
-            # ``serialize_output=True``, or a core without the worker-side
-            # deserialization-class walk: dump to a dict so XCom carries a plain
-            # JSON payload that deserializes without an allow-list entry.
-            output = output.model_dump()
+        return self._finalize_output(output)
 
-        return output
+    def execute_complete(
+        self,
+        context: Context,
+        event: dict[str, Any],
+        generated_output: str | None = None,
+    ) -> Any:
+        """Resume after deferrable LLM execution or human review."""
+        if generated_output is not None:
+            output = super().execute_complete(context, generated_output, event)
+            return rehydrate_pydantic_output(
+                self.output_type, output, serialize_output=self._serialize_model_output
+            )
 
-    def execute_complete(self, context: Context, generated_output: str, event: dict[str, Any]) -> Any:
-        """Resume after human review and restore the Pydantic model for XCom consumers."""
-        output = super().execute_complete(context, generated_output, event)
-        return rehydrate_pydantic_output(
-            self.output_type, output, serialize_output=self._serialize_model_output
+        if event.get("status") == "error":
+            raise AirflowException(event.get("message", "LLM call failed in deferrable mode"))

Review Comment:
   We decided not to raise AirflowException directly https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#don-t-raise-airflowexception-directly



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add deferrable LLMOperator with LLMTrigger [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil closed pull request #70184: Add deferrable LLMOperator with LLMTrigger
URL: https://github.com/apache/airflow/pull/70184


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org