kaxil commented on code in PR #76916:
URL: https://github.com/apache/airflow/pull/76916#discussion_r4573333083


##########
providers/common/ai/src/airflow/providers/common/ai/operators/agent.py:
##########
@@ -1824,6 +1852,141 @@ def _emit_run_metadata(self, context: Context, result: 
Any, *, usage: RunUsage)
         if (model_name := getattr(result.response, "model_name", None)) is not 
None:
             ti.xcom_push(key=MODEL_NAME_XCOM_KEY, value=model_name)
 
+    def dump_review_state(self, message_history: Any) -> str:
+        """Save the conversation, and what the task returns if the output 
under review is approved."""
+        output = self._output_under_review
+        state: dict[str, Any] = {
+            "messages": ModelMessagesTypeAdapter.dump_python(message_history, 
mode="json")
+        }
+        output_json = dump_output_to_json(output)
+        if (
+            rehydrate_pydantic_output(self.output_type, output_json, 
serialize_output=False, is_edited=False)
+            == output
+        ):
+            state["output_json"] = output_json
+        else:
+            # Reading the JSON back would give a different value: an output 
function's or an output
+            # marker's result stays text, and "42" under ``str | int`` becomes 
42. Save the result instead.
+            state["result"] = 
to_jsonable_python(self._convert_output_for_xcom(output))
+        return json.dumps(state)
+
+    def load_review_state(self, context: Context, state: str) -> Any:
+        """Restore the conversation and the usage budget before regenerating 
in the resumed task."""
+        ti = context["task_instance"]
+        # The regeneration shares the budget the paused rounds spent, as it 
does without a pause.
+        self._usage_budget = self._build_usage_budget(context, 
coerce_usage_limits(self.usage_limits), ti=ti)
+        self._run_usage = self._usage_budget.load() if self._usage_budget else 
None
+        self._run_identity_attrs = build_run_identity_attributes(ti)
+        return 
ModelMessagesTypeAdapter.validate_python(json.loads(state)["messages"])
+
+    def complete_hitl_review(self, context: Context, approved_output: str, *, 
state: str | None) -> Any:
+        """Return the approved output as the agent returned it; 
``approved_output`` is only its display text."""
+        # The reviewer can approve, reject, or ask for a new answer, but 
cannot edit the answer text.
+        # So the approved answer is the last answer the agent returned.
+        if state is None:
+            result = self._convert_output_for_xcom(self._output_under_review)
+        elif "result" in (saved := json.loads(state)):
+            result = saved["result"]
+        else:
+            result = self._convert_output_for_xcom(
+                rehydrate_pydantic_output(
+                    self.output_type, saved["output_json"], 
serialize_output=False, is_edited=False
+                )
+            )
+        if self._durable_journal is not None:
+            # The approved output is the task's result, so nothing replays the 
review again.
+            self._durable_journal.cleanup()
+            self._delete_review_answers(context)
+        self._clear_usage_budget(context)
+        return result
+
+    def resume_hitl_review(
+        self,
+        context: Context,
+        iteration: int,
+        deadline: str | None,
+        state_sha256: str,
+        event: dict[str, Any],
+    ) -> Any:
+        if self.durable:
+            # The regeneration after round ``iteration`` is the journal's run 
``iteration``, in this
+            # process as on a retry that replays the rounds before it; run 0 
made the first output.
+            self._durable_journal = 
DurableJournal(self._build_durable_storage(context), first_run=iteration)
+        with self._durable_review(context):
+            return super().resume_hitl_review(context, iteration, deadline, 
state_sha256, event)
+
+    @contextmanager
+    def _durable_review(self, context: Context) -> Iterator[None]:
+        """Under durable, make a review that ends in a reject or 
``max_hitl_iterations`` start over on retry."""
+        try:
+            yield
+        except (HITLRejectException, HITLMaxIterationsError):
+            if (journal := self._durable_journal) is not None:
+                # Replaying would show the reviewer the outputs of this review 
again. The retry asks
+                # the model again for the first output, replaying the tool 
calls before it, and
+                # regenerates from there.
+                self.log.info(
+                    "The review ended without an approved output; a retry asks 
the model again for "
+                    "the first output and starts the review over."
+                )
+                journal.ask_model_again(0)
+                self._delete_review_answers(context)
+            raise
+
+    @staticmethod
+    def _stored_review_answers(context: Context) -> list[_ReviewAnswer]:
+        return _REVIEW_ANSWERS_ADAPTER.validate_python(
+            context["task_state_store"].get(_HITL_REVIEW_ANSWERS_KEY) or []
+        )
+
+    def _recorded_review_feedback(self, context: Context, session: 
AgentSessionData) -> str | None:

Review Comment:
   Done in dfd4de31f5c.



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