Skip to content

Agent Zero AI framework

Restore full-response repeat checks for native tool calls

Alessandro27b7df8917a4
diff --git a/AGENTS.md b/AGENTS.md
index 35cdcc7c2..ed88cc9c7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,7 +19,7 @@
- `Agent.hist_add_ai_response` owns Responses-API state advancement: it calls `_remember_llm_result_state` internally. Model turns pass an `LLMResult`; omitted results and legacy positional string IDs use the non-LLM sentinel. Callers must not invoke `_remember_llm_result_state` manually.
- Prepared local Responses input may project intact native history through `helpers/responses_history.py`; retain original Chat/fallback messages, current protocol/extras, summaries and masking. Durable capability metadata stores only a stable-prefix digest for eligibility.
- `Agent.call_chat_model_turn` builds native function tools only when the chat model's `a0_api_mode` selects Responses; Chat Completions turns pass an empty tool list and name map, since that transport drops them.
-- Native function calls use canonical call content for history and repeat comparison, even when accompanied by commentary. The canonical content passes through the normal history template/masking hook; provider output metadata remains intact.
+- Native function calls use canonical call content for history and combine public response text with calls for repeat comparison. The canonical history content passes through the normal history template/masking hook; provider output metadata remains intact.
- `initialize.py` owns framework initialization.
- `models.py` owns model-provider configuration and LiteLLM integration. `get_api_key_raw()` reads the stored key or key list for settings/editing; `get_api_key()` selects a runtime key and runs provider extension hooks.
- `models.apply_rate_limiter` skips token counting and returns no limiter when all request, input, and output limits are unset; any configured limit retains normal accounting.
diff --git a/agent.py b/agent.py
index 622ca2af5..c7384ac7f 100644
--- a/agent.py
+++ b/agent.py
@@ -783,8 +783,10 @@ class Agent:
id, llm_result = llm_result, None
if llm_result is None:
llm_result = LLMResult.non_llm()
+ self.loop_data.last_response = (
+ llm_result.repeat_response_text() if llm_result.function_calls else message
+ )
message = llm_result.function_calls_text() or message
- self.loop_data.last_response = message
content = self.parse_prompt("fw.ai_response.md", message=message)
msg = self.hist_add_message(
True,
diff --git a/extensions/python/message_loop_result/AGENTS.md b/extensions/python/message_loop_result/AGENTS.md
index 6453e7924..7ad642722 100644
--- a/extensions/python/message_loop_result/AGENTS.md
+++ b/extensions/python/message_loop_result/AGENTS.md
@@ -9,8 +9,8 @@
- Extensions receive mutable `result_data` with `llm_result` and may set `skip_default_processing` after fully handling the turn.
- `_20_empty_response.py` retries fully empty turns (no response and no reasoning): count them toward the unusable-response limit without adding a warning to model history, and use `fw.msg_empty_response.md` for agent-prefixed UI warning text only.
- `_20_empty_response.py` retries reasoning-only turns: add an agent-facing `fw.msg_reasoning_only.md` history warning with a separate `fw.msg_reasoning_only_response.md` user notice, and count them through the stop-unusable-response-loop extension.
-- `_30_repeat_response.py` compares canonical function-call content when native calls exist, otherwise response text; it retries content that exactly matches `loop_data.last_response`, regardless of reasoning, using `fw.msg_repeat.md` for history and `fw.msg_repeat_response.md` for the agent-prefixed UI warning text. State advancement is owned by `hist_add_ai_response`; do not call `_remember_llm_result_state` manually.
-- `_40_native_thoughts.py` folds public commentary accompanying native function calls into the existing completed-generation log `thoughts` array. It preserves provider output items, canonical history/repeat comparison and dispatch. It respects handled results and excludes reasoning/encrypted items and explicit final-answer messages. Normal log masking applies.
+- `_30_repeat_response.py` compares `LLMResult.repeat_response_text()` for native calls (public text plus all calls), otherwise full response text. It retries content that exactly matches `loop_data.last_response`, regardless of separate reasoning or provider IDs, using `fw.msg_repeat.md` for history and `fw.msg_repeat_response.md` for the agent-prefixed UI warning text. State advancement is owned by `hist_add_ai_response`; do not call `_remember_llm_result_state` manually.
+- `_40_native_thoughts.py` folds public commentary accompanying native function calls into the existing completed-generation log `thoughts` array. It preserves provider output items, canonical history, repeat comparison and dispatch. It respects handled results and excludes reasoning/encrypted items and explicit final-answer messages. Normal log masking applies.
## Local Contracts
diff --git a/extensions/python/message_loop_result/_30_repeat_response.py b/extensions/python/message_loop_result/_30_repeat_response.py
index a9ca0780e..f2a404515 100644
--- a/extensions/python/message_loop_result/_30_repeat_response.py
+++ b/extensions/python/message_loop_result/_30_repeat_response.py
@@ -17,9 +17,11 @@ class RepeatResponse(Extension):
llm_result = result_data.get("llm_result")
response = getattr(llm_result, "response", "")
- if getattr(llm_result, "function_calls", None):
- response = llm_result.function_calls_text()
- if not isinstance(response, str) or response != self.agent.loop_data.last_response:
+ repeat_response = (
+ llm_result.repeat_response_text()
+ if getattr(llm_result, "function_calls", None) else response
+ )
+ if not isinstance(repeat_response, str) or repeat_response != self.agent.loop_data.last_response:
return
warning = self.agent.read_prompt("fw.msg_repeat.md")
diff --git a/helpers/llm_result.py b/helpers/llm_result.py
index 033371b40..474b3ce31 100644
--- a/helpers/llm_result.py
+++ b/helpers/llm_result.py
@@ -208,6 +208,13 @@ class LLMResult:
ensure_ascii=False,
)
+ def repeat_response_text(self) -> str:
+ """Compare public text and calls, excluding provider IDs and reasoning."""
+ calls = self.function_calls_text()
+ if not calls:
+ return self.response
+ return json.dumps([output_text(self.raw, self.output_items), calls], ensure_ascii=False)
+
def to_dict(self) -> dict[str, Any]:
return {
"response": self.response,
diff --git a/helpers/llm_result.py.dox.md b/helpers/llm_result.py.dox.md
index 09f81c55c..5a61e2dc1 100644
--- a/helpers/llm_result.py.dox.md
+++ b/helpers/llm_result.py.dox.md
@@ -22,6 +22,7 @@
- `from_dict(...)` preserves explicit modes, including the empty non-LLM sentinel; only missing or null modes use the legacy `responses` default.
- `from_chat(...)` must produce an equivalent chat-completions result with `mode="chat_completions"` and `state="off"`, preserving optional function-call output items and provider usage when the chat transport supplies them.
- Function-call output items must preserve `call_id` and optional acknowledged safety checks.
+- `repeat_response_text()` combines response text and canonical calls for native repeat detection, excluding provider IDs, usage and separate reasoning. Non-native replies retain their full response text. This comparison value is transient and does not replace canonical call history or provider metadata.
- Argument parsing must tolerate JSON strings, dictionaries, and malformed values without throwing.
## Work Guidance
diff --git a/tests/test_message_loop_result.py b/tests/test_message_loop_result.py
index 320694d31..2757097a9 100644
--- a/tests/test_message_loop_result.py
+++ b/tests/test_message_loop_result.py
@@ -1,5 +1,8 @@
+import json
from types import SimpleNamespace
+import pytest
+
from extensions.python.message_loop_result import _20_empty_response as empty_response
from extensions.python.message_loop_result._20_empty_response import EmptyResponse
from extensions.python.message_loop_result._30_repeat_response import RepeatResponse
@@ -142,27 +145,82 @@ def test_reasoning_only_retries_with_agent_warning():
]
-def test_native_repeat_detection_compares_calls_instead_of_commentary():
- from helpers.llm_result import LLMResult
-
- def result(query, commentary):
- return LLMResult.from_response({
- "output_text": commentary,
- "output": [{
- "type": "function_call", "name": "lookup", "call_id": "call",
- "arguments": {"q": query},
- }],
- })
-
- previous = result("first", "Working.")
- agent = FakeAgent("", last_response=previous.function_calls_text())
- changed_call = {"llm_result": result("second", "Working.")}
- RepeatResponse(agent).execute(changed_call)
- assert not changed_call.get("skip_default_processing")
- assert agent.warnings == []
-
- repeated_call = {"llm_result": result("first", "Different commentary.")}
- RepeatResponse(agent).execute(repeated_call)
- assert repeated_call["skip_default_processing"] is True
- assert agent.history == [previous.function_calls_text()]
- assert agent.warnings == ["repeat"]
[email protected]("old_text,new_text,old_query,new_query,old_batch,new_batch,repeated", [
+ ("Working.", "Working.", "first", "first", False, False, True),
+ ("Working.", "Different commentary.", "first", "first", False, False, False),
+ ("Working.", None, "first", "first", False, False, False),
+ (None, "Working.", "first", "first", False, False, False),
+ (json.dumps({"tool_name": "lookup", "tool_args": {"q": "first"}}),
+ None, "first", "first", False, False, False),
+ (None, None, "first", "first", False, False, True),
+ ("Working.", "Working.", "first", "second", False, False, False),
+ (None, None, "first", "second", False, False, False),
+ ("Working.", "Working.", "first", "first", False, True, False),
+ ("Working.", "Working.", "first", "first", True, True, True),
+ ("Working.", "Different commentary.", "first", "first", True, True, False),
+])
+def test_native_repeat_compares_complete_public_turn(
+ monkeypatch, old_text, new_text, old_query, new_query, old_batch, new_batch, repeated
+):
+ from agent import Agent, LoopData
+ from helpers import extension, history
+ from helpers.llm_result import LLMResult, result_from_metadata
+
+ def result(query, commentary, batch, identifier):
+ items = [{"type": "reasoning", "encrypted_content": identifier,
+ "summary": [{"type": "summary_text", "text": identifier}]}]
+ if commentary is not None:
+ items.append({"type": "message", "phase": "commentary", "content": [
+ {"type": "output_text", "text": commentary}]})
+ items.append({"type": "function_call", "name": "lookup", "call_id": identifier,
+ "arguments": {"q": query}})
+ if batch:
+ items.append({"type": "function_call", "name": "lookup", "call_id": identifier + "-2",
+ "arguments": {"q": "another"}})
+ return LLMResult.from_response({"id": identifier, "output": items})
+
+ monkeypatch.setattr(extension, "call_extensions_sync", lambda *args, **kwargs: None)
+ agent = object.__new__(Agent)
+ agent.agent_name = "A0"
+ agent.data = {}
+ agent.loop_data = LoopData()
+ agent.history = history.History(agent)
+ agent.parse_prompt = lambda name, **kwargs: kwargs["message"]
+ agent.hist_add_message = agent.history.add_message
+ agent._remember_llm_result_state = lambda *args: None
+ agent.read_prompt = lambda *args, **kwargs: "repeat"
+ agent.context = SimpleNamespace(log=SimpleNamespace(log=lambda **kwargs: None))
+ previous = result(old_query, old_text, old_batch, "old")
+ current = result(new_query, new_text, new_batch, "new")
+ original = current.to_dict()
+ message = agent.hist_add_ai_response(previous.response, llm_result=previous)
+ data = {"llm_result": current}
+
+ RepeatResponse(agent).execute(data)
+
+ assert bool(data.get("skip_default_processing")) is repeated
+ assert message.content == previous.function_calls_text()
+ assert current.to_dict() == original
+ assert result_from_metadata(current.metadata()).repeat_response_text() == current.repeat_response_text()
+ messages = agent.history.all_messages()
+ assert len(messages) == (3 if repeated else 1)
+ if repeated:
+ assert messages[1].content == current.function_calls_text()
+ assert messages[1].metadata == current.metadata()
+
+
[email protected]("field", ["thoughts", "headline"])
[email protected]("change", ["same", "changed", "removed", "added"])
+def test_chat_repeat_includes_public_planning_fields(field, change):
+ previous = {"thoughts": ["Wait"], "headline": "Checking", "tool_name": "code_execution_tool",
+ "tool_args": {"runtime": "output", "session": 0}}
+ current = dict(previous)
+ if change == "changed":
+ current[field] = ["Still waiting"] if field == "thoughts" else "Checking again"
+ elif change == "removed":
+ current.pop(field)
+ elif change == "added":
+ previous.pop(field)
+ agent = FakeAgent(json.dumps(current), last_response=json.dumps(previous))
+
+ assert bool(_run(agent).get("skip_default_processing")) is (change == "same")
diff --git a/tests/test_responses_architecture.py b/tests/test_responses_architecture.py
index f2377159c..d5cc83e1a 100644
--- a/tests/test_responses_architecture.py
+++ b/tests/test_responses_architecture.py
@@ -239,7 +239,9 @@ def test_history_response_call_compatibility_preserves_state(monkeypatch, call_f
assert result_from_metadata(message.metadata).metadata() == expected.metadata()
assert agent.history.all_messages() == [message]
assert message.content == (expected.function_calls_text() or "hello")
- assert agent.loop_data.last_response == message.content
+ assert agent.loop_data.last_response == (
+ expected.repeat_response_text() if call_form == "native" else "hello"
+ )
if call_form == "native":
assert result.response == "hello"
if call_form not in {"message", "result"}: