This is an automated email from the ASF dual-hosted git repository.
guan404ming pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 020259387b9 Support multimodal prompts with enable_hitl_review in
AgentOperator (#74389)
020259387b9 is described below
commit 020259387b9bd4133ff3492e363196862c400401
Author: Guan-Ming Chiu <[email protected]>
AuthorDate: Thu Nov 5 17:10:31 2026 +0000
Support multimodal prompts with enable_hitl_review in AgentOperator (#74389)
* Support multimodal prompts with enable_hitl_review in AgentOperator
* Fix mypy error on run_hitl_review in AgentOperator
* Make HITL review prompt a read-only property
---
providers/common/ai/docs/operators/agent.rst | 7 ++--
.../providers/common/ai/decorators/agent.py | 7 ----
.../providers/common/ai/mixins/hitl_review.py | 15 ++++++---
.../airflow/providers/common/ai/operators/agent.py | 8 -----
.../providers/common/ai/utils/validation.py | 24 -------------
.../tests/unit/common/ai/decorators/test_agent.py | 16 +++++----
.../unit/common/ai/mixins/test_hitl_review.py | 39 +++++++++++++++++++++-
.../tests/unit/common/ai/operators/test_agent.py | 30 ++++++++---------
.../tests/unit/common/ai/utils/test_validation.py | 32 +-----------------
9 files changed, 74 insertions(+), 104 deletions(-)
diff --git a/providers/common/ai/docs/operators/agent.rst
b/providers/common/ai/docs/operators/agent.rst
index c1e587c5b42..095914469fa 100644
--- a/providers/common/ai/docs/operators/agent.rst
+++ b/providers/common/ai/docs/operators/agent.rst
@@ -103,11 +103,8 @@ to the model. This mirrors the input types accepted by
pydantic-ai's
def analyze_review(image_url: str):
return ["Describe what you see:", ImageUrl(url=image_url)]
-.. note::
-
- Combining a non-string prompt with ``enable_hitl_review=True`` is not
- currently supported -- the HITL session model stores the prompt as a
- string, so a ``Sequence`` prompt will raise at the review boundary.
+With ``enable_hitl_review=True``, the review session stores the prompt's text
+and a placeholder such as ``[image/png, 2048 bytes]`` for each non-text part.
Structured output
-----------------
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/decorators/agent.py
b/providers/common/ai/src/airflow/providers/common/ai/decorators/agent.py
index 39070e90cb1..9721c865cbf 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/decorators/agent.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/decorators/agent.py
@@ -30,7 +30,6 @@ from typing import TYPE_CHECKING, Any, ClassVar
from airflow.providers.common.ai.operators.agent import AgentOperator
from airflow.providers.common.ai.utils.prompt import call_arguments
from airflow.providers.common.ai.utils.validation import (
- reject_sequence_with_unsupported_feature,
validate_prompt,
)
from airflow.providers.common.compat.sdk import (
@@ -92,12 +91,6 @@ class _AgentDecoratedOperator(DecoratedOperator,
AgentOperator):
self.prompt = self.python_callable(*self.op_args, **kwargs)
validate_prompt(self.prompt, decorator_name="@task.agent")
- reject_sequence_with_unsupported_feature(
- self.prompt,
- decorator_name="@task.agent",
- feature_name="enable_hitl_review",
- feature_enabled=self.enable_hitl_review,
- )
# Render only the prompt the callable returned. The other template
fields were already
# rendered before execute().
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py
b/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py
index 3a924fbc78f..6a89ff774b9 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/mixins/hitl_review.py
@@ -31,6 +31,7 @@ from airflow.providers.common.ai.utils.hitl_review import (
SessionStatus,
)
from airflow.providers.common.ai.utils.output_type import
dump_output_for_display
+from airflow.providers.common.ai.utils.prompt import describe_prompt
log = logging.getLogger(__name__)
@@ -38,6 +39,8 @@ log = logging.getLogger(__name__)
_MAX_CONSECUTIVE_XCOM_PULL_FAILURES = 10
if TYPE_CHECKING:
+ from collections.abc import Sequence
+
from airflow.sdk import Context
@@ -48,10 +51,12 @@ class HITLReviewProtocol(Protocol):
max_hitl_iterations: int
hitl_timeout: timedelta | None
hitl_poll_interval: float
- prompt: str
task_id: str
log: Any
+ @property
+ def prompt(self) -> str | Sequence[Any]: ...
+
class HITLReviewMixin:
"""
@@ -87,7 +92,7 @@ class HITLReviewMixin:
- ``enable_hitl_review`` (``bool``)
- ``hitl_timeout`` (``timedelta | None``)
- ``hitl_poll_interval`` (``float``, seconds)
- - ``prompt`` (``str``)
+ - ``prompt`` (``str`` or ``Sequence[UserContent]``)
And must implement: meth:`regenerate_with_feedback`.
"""
@@ -121,7 +126,7 @@ class HITLReviewMixin:
status=SessionStatus.PENDING_REVIEW,
iteration=1,
max_iterations=self.max_hitl_iterations,
- prompt=self.prompt,
+ prompt=describe_prompt(self.prompt),
current_output=output_str,
)
@@ -238,7 +243,7 @@ class HITLReviewMixin:
status=SessionStatus.MAX_ITERATIONS_EXCEEDED,
iteration=session.iteration,
max_iterations=self.max_hitl_iterations,
- prompt=self.prompt,
+ prompt=session.prompt,
current_output=session.current_output,
)
ti.xcom_push(key=XCOM_AGENT_SESSION,
value=_session_max.model_dump(mode="json"))
@@ -261,7 +266,7 @@ class HITLReviewMixin:
status=SessionStatus.PENDING_REVIEW,
iteration=new_iteration,
max_iterations=self.max_hitl_iterations,
- prompt=self.prompt,
+ prompt=session.prompt,
current_output=new_output,
)
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/operators/agent.py
b/providers/common/ai/src/airflow/providers/common/ai/operators/agent.py
index 590ee28301b..94d86d57e76 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/operators/agent.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/operators/agent.py
@@ -1029,14 +1029,6 @@ class AgentOperator(CancellableAgentRunMixin,
BaseOperator, HITLReviewMixin, Usa
raise
def execute(self, context: Context) -> Any:
- if self.enable_hitl_review and not isinstance(self.prompt, str):
- raise TypeError(
- f"{type(self).__name__}: enable_hitl_review=True is not
supported "
- f"with a non-string prompt (got {type(self.prompt).__name__}).
"
- f"The HITL session model requires a string prompt. Return a
str "
- f"prompt, or disable enable_hitl_review."
- )
-
# Coerced first so a bad rendered value fails before the expensive
setup below.
usage_limits = coerce_usage_limits(self.usage_limits)
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/utils/validation.py
b/providers/common/ai/src/airflow/providers/common/ai/utils/validation.py
index 2c06f31b81b..64d5872bb3e 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/utils/validation.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/utils/validation.py
@@ -65,27 +65,3 @@ def validate_prompt(value: Any, *, decorator_name: str) ->
None:
f"The returned value from the {decorator_name} callable must be "
f"str or Sequence[UserContent], got {type(value).__name__}."
)
-
-
-def reject_sequence_with_unsupported_feature(
- value: Any,
- *,
- decorator_name: str,
- feature_name: str,
- feature_enabled: bool,
-) -> None:
- """
- Preflight check raised before the agent runs.
-
- Raises ``TypeError`` when *value* is a non-string Sequence and
- *feature_enabled* is True. Used to fail fast on combinations
- (e.g., ``enable_hitl_review=True`` + Sequence prompt) that would
- otherwise fail later -- after the LLM call -- when the downstream
- HITL/approval consumer tries to stringify the prompt.
- """
- if feature_enabled and not isinstance(value, str):
- raise TypeError(
- f"{decorator_name}: Sequence[UserContent] prompts are not
supported "
- f"with {feature_name}=True. Return a str prompt, or disable "
- f"{feature_name}."
- )
diff --git a/providers/common/ai/tests/unit/common/ai/decorators/test_agent.py
b/providers/common/ai/tests/unit/common/ai/decorators/test_agent.py
index 00e017f068c..6ef560f42f7 100644
--- a/providers/common/ai/tests/unit/common/ai/decorators/test_agent.py
+++ b/providers/common/ai/tests/unit/common/ai/decorators/test_agent.py
@@ -114,27 +114,31 @@ class TestAgentDecoratedOperator:
prompt, usage_limits=None, run_id="ti-1", cancellation_token=ANY,
usage=ANY
)
+
@patch("airflow.providers.common.ai.operators.agent.AgentOperator.run_hitl_review",
autospec=True)
@patch("airflow.providers.common.ai.operators.agent.PydanticAIHook",
autospec=True)
- def test_sequence_prompt_with_hitl_review_raises_before_run_sync(self,
mock_hook_cls):
- """Sequence prompt + enable_hitl_review=True fails before the agent
runs."""
+ def test_sequence_prompt_with_hitl_review_reaches_the_review(
+ self, mock_hook_cls, mock_run_hitl, make_mock_run_result
+ ):
from tests_common.test_utils.version_compat import AIRFLOW_V_3_1_PLUS
if not AIRFLOW_V_3_1_PLUS:
pytest.skip("enable_hitl_review requires Airflow >= 3.1.0")
mock_agent = MagicMock(spec=["run_sync", "instrument"])
+ mock_agent.run_sync.return_value = make_mock_run_result("Initial
output")
mock_hook_cls.get_hook.return_value.create_agent.return_value =
mock_agent
+ prompt = ["x", ImageUrl(url="https://example.com/x.png")]
op = _AgentDecoratedOperator(
task_id="test",
- python_callable=lambda: ["x",
ImageUrl(url="https://example.com/x.png")],
+ python_callable=lambda: prompt,
llm_conn_id="my_llm",
enable_hitl_review=True,
)
- with pytest.raises(TypeError, match="enable_hitl_review=True"):
- op.execute(context={})
- mock_agent.run_sync.assert_not_called()
+ assert op.execute(context=_make_context()) == "Initial output"
+ mock_run_hitl.assert_called_once()
+ assert mock_agent.run_sync.call_args.args[0] == prompt
@patch("airflow.providers.common.ai.operators.agent.PydanticAIHook",
autospec=True)
def test_execute_merges_op_kwargs_into_callable(self, mock_hook_cls,
make_mock_run_result):
diff --git
a/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py
b/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py
index 98839df5ec2..1cfa76f566d 100644
--- a/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py
+++ b/providers/common/ai/tests/unit/common/ai/mixins/test_hitl_review.py
@@ -16,6 +16,7 @@
# under the License.
from __future__ import annotations
+from collections.abc import Sequence
from dataclasses import dataclass
import pytest
@@ -29,6 +30,8 @@ if not AIRFLOW_V_3_1_PLUS:
from datetime import timedelta
from unittest.mock import MagicMock, patch
+from pydantic_ai.messages import BinaryContent, UserContent
+
from airflow.providers.common.ai.exceptions import HITLMaxIterationsError
from airflow.providers.common.ai.mixins.hitl_review import (
_MAX_CONSECUTIVE_XCOM_PULL_FAILURES,
@@ -52,7 +55,7 @@ class FakeAgenticOperator(HITLReviewMixin):
def __init__(
self,
*,
- prompt: str = "Summarize this",
+ prompt: str | Sequence[UserContent] = "Summarize this",
task_id: str = "test_task",
hitl_timeout: timedelta | None = None,
hitl_poll_interval: float = 0.1,
@@ -267,6 +270,40 @@ class TestHITLReviewMixin:
assert "airflow_hitl_review_agent_output_2" in output_pushes
assert output_pushes["airflow_hitl_review_agent_output_2"] ==
"Revised: Add more detail"
+ @patch.object(FakeAgenticOperator, "regenerate_with_feedback")
+ @patch("airflow.providers.common.ai.mixins.hitl_review.time.sleep",
autospec=True)
+ def test_session_renders_a_sequence_prompt(
+ self, mock_sleep, mock_regenerate, mock_ti, context,
mock_supervisor_comms
+ ):
+ mock_regenerate.return_value = ("Revised", None)
+ mock_supervisor_comms.send.side_effect = [
+ XComResult(
+ key=XCOM_HUMAN_ACTION,
+ value=HumanActionData(
+ action="changes_requested", feedback="More detail",
iteration=1
+ ).model_dump(mode="json"),
+ ),
+ XComResult(
+ key=XCOM_HUMAN_ACTION,
+ value=HumanActionData(
+ action="changes_requested", feedback="Even more",
iteration=2
+ ).model_dump(mode="json"),
+ ),
+ ]
+ prompt = ["Describe this:", BinaryContent(data=b"\x89PNG",
media_type="image/png")]
+ op = FakeAgenticOperator(prompt=prompt)
+ op.max_hitl_iterations = 2
+
+ with pytest.raises(HITLMaxIterationsError, match="Task exceeded max
iterations"):
+ op.run_hitl_review(context, "Initial")
+
+ prompts = [
+ c[1]["value"]["prompt"]
+ for c in mock_ti.xcom_push.call_args_list
+ if c[1]["key"] == XCOM_AGENT_SESSION
+ ]
+ assert prompts == ["Describe this:\n[image/png, 4 bytes]"] * 3
+
@patch("airflow.providers.common.ai.mixins.hitl_review.time.monotonic",
autospec=True)
@patch("airflow.providers.common.ai.mixins.hitl_review.time.sleep",
autospec=True)
def test_timeout_raises_hitl_timeout_error(
diff --git a/providers/common/ai/tests/unit/common/ai/operators/test_agent.py
b/providers/common/ai/tests/unit/common/ai/operators/test_agent.py
index 877edcaeded..66ed0f025da 100644
--- a/providers/common/ai/tests/unit/common/ai/operators/test_agent.py
+++ b/providers/common/ai/tests/unit/common/ai/operators/test_agent.py
@@ -46,6 +46,7 @@ from pydantic_ai.capabilities import (
)
from pydantic_ai.exceptions import ApprovalRequired, ModelRetry, ToolFailed,
UsageLimitExceeded
from pydantic_ai.messages import (
+ BinaryContent,
ModelMessage,
ModelMessagesTypeAdapter,
ModelRequest,
@@ -2323,28 +2324,23 @@ class TestAgentOperatorDurable:
@pytest.mark.skipif(
not AIRFLOW_V_3_1_PLUS, reason="Human in the loop is only compatible with
Airflow >= 3.1.0"
)
-class TestAgentOperatorMultimodalPromptGuard:
- """AgentOperator.execute raises before agent.run_sync when
enable_hitl_review=True
- and self.prompt is not a string -- covering direct construction and the
native
- template rendering escape (where a string template renders to a
Sequence)."""
-
+class TestAgentOperatorMultimodalPromptReview:
+
@patch("airflow.providers.common.ai.operators.agent.AgentOperator.run_hitl_review",
autospec=True)
@patch("airflow.providers.common.ai.operators.agent.PydanticAIHook",
autospec=True)
- def test_execute_rejects_sequence_prompt_with_hitl_review(self,
mock_hook_cls):
+ def test_execute_with_hitl_review_accepts_a_sequence_prompt(
+ self, mock_hook_cls, mock_run_hitl, make_mock_run_result
+ ):
+ prompt = ["Describe this:", BinaryContent(data=b"\x89PNG",
media_type="image/png")]
mock_agent = MagicMock(spec=["run_sync", "instrument"])
+ mock_agent.run_sync.return_value = make_mock_run_result("Initial
output")
mock_hook_cls.get_hook.return_value.create_agent.return_value =
mock_agent
+ mock_run_hitl.return_value = "Initial output"
- op = AgentOperator(
- task_id="t",
- prompt="placeholder",
- llm_conn_id="c",
- enable_hitl_review=True,
- )
- op.prompt = ["x", object()] # simulate post-template-render value
-
- with pytest.raises(TypeError, match="enable_hitl_review=True"):
- op.execute(context=MagicMock())
+ op = AgentOperator(task_id="t", prompt="placeholder", llm_conn_id="c",
enable_hitl_review=True)
+ op.prompt = prompt
- mock_agent.run_sync.assert_not_called()
+ assert op.execute(context=MagicMock()) == "Initial output"
+ assert mock_agent.run_sync.call_args.args[0] == prompt
def _sample_history():
diff --git a/providers/common/ai/tests/unit/common/ai/utils/test_validation.py
b/providers/common/ai/tests/unit/common/ai/utils/test_validation.py
index 2a927415ec1..413109df3f4 100644
--- a/providers/common/ai/tests/unit/common/ai/utils/test_validation.py
+++ b/providers/common/ai/tests/unit/common/ai/utils/test_validation.py
@@ -18,10 +18,7 @@ from __future__ import annotations
import pytest
-from airflow.providers.common.ai.utils.validation import (
- reject_sequence_with_unsupported_feature,
- validate_prompt,
-)
+from airflow.providers.common.ai.utils.validation import validate_prompt
class TestValidatePrompt:
@@ -100,30 +97,3 @@ class TestValidatePrompt:
def test_rejects_bytes_like_in_sequence(self, value):
with pytest.raises(TypeError, match="raw bytes are not a valid
UserContent"):
validate_prompt(value, decorator_name="@task.agent")
-
-
-class TestRejectSequenceWithUnsupportedFeature:
- def test_noop_when_feature_disabled(self):
- reject_sequence_with_unsupported_feature(
- ["x", object()],
- decorator_name="@task.agent",
- feature_name="enable_hitl_review",
- feature_enabled=False,
- )
-
- def test_noop_when_value_is_string(self):
- reject_sequence_with_unsupported_feature(
- "hello",
- decorator_name="@task.agent",
- feature_name="enable_hitl_review",
- feature_enabled=True,
- )
-
- def test_raises_for_sequence_with_feature_enabled(self):
- with pytest.raises(TypeError, match="enable_hitl_review=True"):
- reject_sequence_with_unsupported_feature(
- ["x", object()],
- decorator_name="@task.agent",
- feature_name="enable_hitl_review",
- feature_enabled=True,
- )