kaxil commented on code in PR #76015:
URL: https://github.com/apache/airflow/pull/76015#discussion_r4485831626
##########
providers/common/ai/tests/unit/common/ai/durable/test_openai_agents.py:
##########
@@ -139,6 +153,97 @@ async def function(arguments: dict[str, Any]) ->
ToolResult:
)
+class _ParallelModel(Model):
+ """
+ Asks for one ``lookup`` per key in a single response, then answers with
their results.
+
+ The calls get the ids ``call-<key>``. ``fail_on_answer`` makes the request
that would
+ answer raise, as a crashed worker would leave it.
+ """
+
+ def __init__(self, keys: tuple[str, ...] = ("a", "b"), *, fail_on_answer:
bool = False) -> None:
+ self.keys = keys
+ self.fail_on_answer = fail_on_answer
+ self.calls = 0
+
+ async def get_response(self, system_instructions, input, *args: Any,
**kwargs: Any) -> ModelResponse:
+ self.calls += 1
+ outputs = [
+ item["output"]
+ for item in (input if isinstance(input, list) else [])
+ if isinstance(item, dict) and item.get("type") ==
"function_call_output"
+ ]
+ output: list[ResponseFunctionToolCall | ResponseOutputMessage]
+ if not outputs:
+ output = [
+ ResponseFunctionToolCall(
+ id=f"fc-{key}",
+ call_id=f"call-{key}",
+ name="lookup",
+ arguments=json.dumps({"key": key}),
+ type="function_call",
+ )
+ for key in self.keys
+ ]
+ else:
+ if self.fail_on_answer:
+ raise RuntimeError("worker lost")
+ text = ResponseOutputText(text=f"answer: {sorted(outputs)}",
type="output_text", annotations=[])
+ output = [
+ ResponseOutputMessage(
+ id="msg", role="assistant", status="completed",
type="message", content=[text]
+ )
+ ]
+ return ModelResponse(output=list(output), usage=Usage(),
response_id=f"resp-{self.calls}")
+
+ def stream_response(self, *args: Any, **kwargs: Any):
+ raise NotImplementedError
+
+
+class _SleepingTools:
+ """A ``lookup`` tool that sleeps ``body_delays[key]`` seconds, fails for
the keys in ``failing``, and counts the calls per key."""
Review Comment:
Split into a summary line and a description in 925c7869bda.
##########
providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py:
##########
@@ -345,24 +376,50 @@ async def get_response(
)
if step.replayed:
try:
- return ModelResponse(
+ replayed = ModelResponse(
output=_OUTPUT_ITEMS.validate_python(step.payload["output"]),
usage=Usage(),
response_id=step.payload.get("response_id"),
)
except (ValidationError, KeyError, TypeError) as error:
self.durable_run.reject(step, reason=f"the recorded model
response cannot be read: {error}")
+ else:
+ self._reserve_tool_steps(replayed, tools)
+ return replayed
async def call() -> ModelResponse:
return await self.wrapped.get_response(
system_instructions, input, model_settings, tools,
output_schema, handoffs, tracing, **kwargs
)
try:
- return await step.run(call, to_record=_record_response)
+ response = await step.run(call, to_record=_record_response)
except Exception:
self.failed_step = step
raise
+ self._reserve_tool_steps(response, tools)
+ return response
+
+ def _reserve_tool_steps(self, response: ModelResponse, tools: list[Tool])
-> None:
+ """
+ Claim a position for each of the response's tool calls, in the order
the model made them.
+
+ A call whose tool never runs (held for approval, stopped by a
guardrail) leaves its position
+ empty, which a retry runs live without disturbing the positions after
it.
+ """
+ durable_names = {tool.name for tool in tools if getattr(tool,
_DURABLE_MARKER, False)}
+ reserved = _RESERVED_TOOL_STEPS.setdefault(self.durable_run, {})
+ for item in response.output:
+ if (
+ isinstance(item, ResponseFunctionToolCall)
+ and item.name in durable_names
+ and item.call_id not in reserved
Review Comment:
Fixed in 78f60663db2: each `reserve` replaces what the previous response
left untaken, so a later call that reuses the id gets a fresh reservation
instead of the stale step.
`test_a_later_response_reserves_a_new_step_for_a_call_with_the_same_id_and_arguments`
(52555405efa) pins it.
##########
providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py:
##########
@@ -103,6 +104,16 @@
# Arguments that keep the conversation on OpenAI's servers, which a replayed
model call never reaches.
_SERVER_SIDE_STATE = ("previous_response_id", "conversation_id",
"auto_previous_response_id")
+# Tool steps a model response claimed, by tool call id, until the tool takes
its own. The tools of
+# one response start in model order but reach their wrapper after guardrails
and hooks of varying
+# duration, so claiming there would number them by completion order.
+# Removed when ``run_durably`` ends: the steps hold their run, so a weak
reference would not free it.
Review Comment:
The module-level dict this comment described is gone in 78f60663db2 (the
reservations now live on the `DurableRun`), so the comment went with it.
##########
providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py:
##########
@@ -268,6 +282,23 @@ async def on_invoke_tool(ctx: ToolContext[Any], arguments:
str) -> Any:
return durable_tool
+def _is_durable_tool(tool: Tool) -> TypeGuard[FunctionTool]:
+ return isinstance(tool, FunctionTool) and not callable(tool.needs_approval)
Review Comment:
Folded into `_get_durable_tool` in 8fe74c7a302.
--
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]