Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): give withheld final answers one bounded text-only retry (#2136)

Steven Huangd51e651ac373
diff --git a/README.md b/README.md
index fea40a283..fdefb485a 100644
--- a/README.md
+++ b/README.md
@@ -1350,6 +1350,12 @@ vibe-trading provider doctor # print redacted provider/proxy/package diagnostic
<details>
<summary><b>Single run & flags</b></summary>
+If the final text-only response contains tool-call markup, the agent gets one
+additional text-only turn beyond its iteration cap to re-emit the answer. This
+turn cannot execute tools or continue research, still obeys cancellation and
+goal token budgets, and is included in usage and iteration counts. If it also
+returns tool-call markup, the existing degraded fallback is returned.
+
```bash
vibe-trading run -p "Backtest BTC-USDT MACD strategy, last 30 days"
vibe-trading run -p "Analyze AAPL momentum" --json
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 6de3467e5..811525f68 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -174,7 +174,7 @@ class AgentLoop(ToolCallLifecycle):
registry: Tool registry.
llm: ChatLLM client.
memory: Workspace memory.
- max_iterations: Maximum number of iterations.
+ max_iterations: Maximum research iterations, plus one text-only answer retry.
"""
def __init__(
@@ -195,7 +195,7 @@ class AgentLoop(ToolCallLifecycle):
llm: ChatLLM client.
memory: Workspace memory (created fresh if not provided).
event_callback: Event callback (event_type, data).
- max_iterations: Maximum number of loop iterations.
+ max_iterations: Maximum research iterations, plus one text-only answer retry.
persistent_memory: PersistentMemory for cross-session recall.
cancel_event: Optional cancellation flag to share with long-running
tools (e.g. ``run_swarm``). The host session owns the event so a
@@ -564,8 +564,11 @@ class AgentLoop(ToolCallLifecycle):
watchdog.start()
stream_failure_streak = 0
+ final_answer_retry_pending = False
try:
- while iteration < self.max_iterations:
+ while iteration < self.max_iterations or final_answer_retry_pending:
+ final_answer_retry = final_answer_retry_pending
+ final_answer_retry_pending = False
self._tool_schema_tokens = estimate_tokens(request_definitions(self.registry))
if self._budget_stop_reason is not None:
break
@@ -671,7 +674,7 @@ class AgentLoop(ToolCallLifecycle):
# whose validator requested no explicit recovery is text-only too:
# the model must revise from evidence already gathered instead of
# starting another research/refetch loop merely to reformat a draft.
- is_last_iteration = (iteration == self.max_iterations)
+ is_last_iteration = iteration >= self.max_iterations
correction_text_only = grounding_correction_text_only
tool_defs = (
None
@@ -875,12 +878,21 @@ class AgentLoop(ToolCallLifecycle):
)
continue
- if forced_grounding_release or not response.has_tool_calls:
+ unoffered_retry_call = final_answer_retry and response.has_tool_calls
+ if (
+ forced_grounding_release
+ or unoffered_retry_call
+ or not response.has_tool_calls
+ ):
# At the cap, release the last actual draft through the
# existing gate. The forbidden call's text is not an answer.
- final_content = pending_grounding_draft if forced_grounding_release else response.content or ""
+ final_content = (
+ pending_grounding_draft
+ if forced_grounding_release
+ else response.content or ""
+ )
syntax_fallback_emitted = False
- if not final_content:
+ if not final_content and not unoffered_retry_call:
empty_model_response_iter = iteration
trace.write(
{
@@ -912,19 +924,27 @@ class AgentLoop(ToolCallLifecycle):
consecutive_empty_responses = 0
# A model can answer the forced-text final iteration with its
# native tool-call DSL as prose (see _looks_like_tool_call_syntax).
- # That is not an answer: retry once with a plain-text instruction,
- # and if no budget remains release a deterministic fallback instead
- # of leaking the raw markup to the user.
- if _looks_like_tool_call_syntax(final_content):
+ # That is not an answer: allow one text-only retry after the
+ # iteration cap, then use a deterministic fallback if it also
+ # fails. Cancellation and goal budgets still stop that retry.
+ if unoffered_retry_call or _looks_like_tool_call_syntax(
+ final_content
+ ):
+ if stream.streamed_chars:
+ self._emit(
+ "stream_reset",
+ {
+ "iter": current_iter,
+ "reason": "tool_call_syntax_in_answer",
+ },
+ )
trace.write(
{
"type": "tool_call_syntax_in_answer",
"iter": current_iter,
}
)
- messages.append(
- {"role": "assistant", "content": final_content}
- )
+ messages.append({"role": "assistant", "content": final_content})
messages.append(
{
"role": "system",
@@ -936,9 +956,14 @@ class AgentLoop(ToolCallLifecycle):
}
)
final_content = ""
- if iteration < self.max_iterations:
+ if iteration <= self.max_iterations:
+ # One extra text-only turn can re-emit a withheld final
+ # answer; it does not extend the research/tool budget.
+ final_answer_retry_pending = (
+ iteration == self.max_iterations
+ )
continue
- # No budget left: never leak the raw markup. The
+ # The bounded retry also failed: never leak the raw markup. The
# grounding safe-fallback talks about instrument identity,
# which is wrong for non-market tasks, so use a neutral
# message here instead.
@@ -980,7 +1005,13 @@ class AgentLoop(ToolCallLifecycle):
should_continue_goal = False
continuation_snapshot = None
_max_cont = _goal_max_continuations()
- if not forced_grounding_release and active_goal_id and session_id and _max_cont > 0:
+ if (
+ not final_answer_retry
+ and not forced_grounding_release
+ and active_goal_id
+ and session_id
+ and _max_cont > 0
+ ):
try:
if goal_store is None:
from src.goal import GoalStore
diff --git a/agent/tests/test_agent_loop_dsml_tool_calls.py b/agent/tests/test_agent_loop_dsml_tool_calls.py
index e3cca1fef..2cf1d41f3 100644
--- a/agent/tests/test_agent_loop_dsml_tool_calls.py
+++ b/agent/tests/test_agent_loop_dsml_tool_calls.py
@@ -4,13 +4,15 @@ from __future__ import annotations
import json
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
+
+import pytest
from src.agent.loop import AgentLoop
from src.agent.progress import emit_progress
from src.agent.tools import BaseTool, ToolRegistry
from src.memory.persistent import PersistentMemory
-from src.providers.chat import ChatLLM
+from src.providers.chat import ChatLLM, LLMResponse, ToolCallRequest
class _Chunk:
@@ -164,7 +166,7 @@ def test_agent_loop_never_releases_tool_call_syntax_as_a_final_answer(
events: list[tuple[str, dict[str, Any]]] = []
agent = AgentLoop(
registry=registry,
- llm=_chat_llm(_ScriptedStreamingLLM([garbage])),
+ llm=_chat_llm(_ScriptedStreamingLLM([garbage, garbage])),
event_callback=lambda event_type, payload: events.append((event_type, payload)),
max_iterations=1, # the single iteration is the forced-text last one
persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),
@@ -175,6 +177,7 @@ def test_agent_loop_never_releases_tool_call_syntax_as_a_final_answer(
assert result["status"] == "success"
assert result.get("degraded") is True
+ assert result["iterations"] == 2
assert "tool-call syntax" in result["content"]
assert "<" not in result["content"]
assert not any(
@@ -201,3 +204,229 @@ def test_closing_dsml_tags_alone_are_tool_call_syntax() -> None:
assert _looks_like_tool_call_syntax("Report.\n\n" + tail)
assert _looks_like_tool_call_syntax("done </||DSML||invoke>")
assert not _looks_like_tool_call_syntax("| 标的 | 权重 |\n|---|---|\n| 000001.SZ | 38.97% |")
+
+
[email protected]("max_iterations", [1, 3])
+def test_final_tool_syntax_gets_one_text_only_retry(
+ tmp_path: Path, max_iterations: int
+) -> None:
+ """A withheld final answer can be re-emitted after research hits its cap."""
+ dsml = (
+ '<||DSML||tool_calls><||DSML||invoke name="echo_probe">'
+ '<||DSML||parameter name="marker" string="true">ready</||DSML||parameter>'
+ "</||DSML||invoke></||DSML||tool_calls>"
+ )
+ garbage = '<││DSML││tool_calls><││invoke name="echo_probe">'
+ responses = [dsml] * (max_iterations - 1) + [garbage, "The report is ready."]
+ registry = ToolRegistry()
+ registry.register(_EchoProbeTool())
+ events: list[tuple[str, dict[str, Any]]] = []
+ agent = AgentLoop(
+ registry=registry,
+ llm=_chat_llm(_ScriptedStreamingLLM(responses)),
+ event_callback=lambda kind, payload: events.append((kind, payload)),
+ max_iterations=max_iterations,
+ persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),
+ )
+ agent.memory.run_dir = str(tmp_path / "run")
+
+ result = agent.run("use the probe and report")
+
+ assert result["status"] == "success"
+ assert result["content"] == "The report is ready."
+ assert result["iterations"] == max_iterations + 1
+ assert not result.get("degraded")
+ assert sum(kind == "tool_result" for kind, _ in events) == max_iterations - 1
+ assert not responses
+ shown = ""
+ for kind, payload in events:
+ if kind == "stream_reset":
+ shown = ""
+ elif kind == "text_delta":
+ shown += payload["delta"]
+ assert shown == "The report is ready."
+
+
+class _AnswerRetryLLM:
+ def __init__(self, responses: list[LLMResponse]) -> None:
+ self.responses = responses
+ self.offered_tools: list[list[dict[str, Any]] | None] = []
+
+ def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ on_text_chunk: Callable[[str], None] | None = None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ self.offered_tools.append(tools)
+ response = self.responses.pop(0)
+ if on_text_chunk and response.content:
+ on_text_chunk(response.content)
+ return response
+
+
+def test_final_answer_retry_cannot_execute_unoffered_tools(tmp_path: Path) -> None:
+ """A provider ignoring text-only mode cannot reopen tool execution."""
+ garbage = '<││DSML││tool_calls><││invoke name="echo_probe">'
+ llm = _AnswerRetryLLM(
+ [
+ LLMResponse(content=garbage),
+ LLMResponse(
+ content="",
+ tool_calls=[
+ ToolCallRequest(
+ id="retry-call",
+ name="echo_probe",
+ arguments={"marker": "unexpected"},
+ )
+ ],
+ ),
+ ]
+ )
+ registry = ToolRegistry()
+ registry.register(_EchoProbeTool())
+ events: list[tuple[str, dict[str, Any]]] = []
+ agent = AgentLoop(
+ registry=registry,
+ llm=llm,
+ event_callback=lambda kind, payload: events.append((kind, payload)),
+ max_iterations=1,
+ persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),
+ )
+ agent.memory.run_dir = str(tmp_path / "run")
+
+ result = agent.run("report")
+
+ assert not any(kind in {"tool_call", "tool_result"} for kind, _ in events)
+ assert llm.offered_tools == [None, None]
+ assert result["iterations"] == 2
+ assert result.get("degraded") is True
+ assert "tool-call syntax" in result["content"]
+
+
[email protected]("token_budget, expected_calls", [(10, 1), (100, 2)])
+def test_answer_retry_obeys_goal_budget_and_accounts_usage(
+ tmp_path: Path, monkeypatch, token_budget: int, expected_calls: int
+) -> None:
+ from src.goal import GoalStore
+
+ monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
+ monkeypatch.setattr("src.agent.loop.SESSIONS_DIR", tmp_path / "sessions")
+ monkeypatch.setattr("src.agent.tuning.GOAL_MAX_CONTINUATIONS", 1, raising=False)
+ store = GoalStore()
+ goal = store.replace_goal(
+ session_id="retry-session",
+ objective="Write a report.",
+ criteria=["Deliver the report"],
+ token_budget=token_budget,
+ )
+ garbage = '<││DSML││tool_calls><││invoke name="echo_probe">'
+ llm = _AnswerRetryLLM(
+ [
+ LLMResponse(content=garbage, usage_metadata={"total_tokens": 15}),
+ LLMResponse(
+ content="The report is ready.", usage_metadata={"total_tokens": 20}
+ ),
+ ]
+ )
+ agent = AgentLoop(
+ registry=ToolRegistry(),
+ llm=llm,
+ max_iterations=1,
+ persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),
+ )
+ agent.memory.run_dir = str(tmp_path / "run")
+
+ result = agent.run("Write a report.", session_id="retry-session")
+
+ assert len(llm.offered_tools) == expected_calls
+ updated = store.get_goal(goal.goal_id)
+ assert updated.tokens_used == (15 if expected_calls == 1 else 35)
+ assert updated.turns_used == 1
+ usage = json.loads((Path(result["run_dir"]) / "llm_usage.json").read_text())
+ assert usage["totals"]["calls"] == expected_calls
+ assert usage["totals"]["total_tokens"] == updated.tokens_used
+ if expected_calls == 1:
+ assert "budget" in result["reason"]
+ assert not result["content"]
+ else:
+ assert result["content"] == "The report is ready."
+ assert [row["iter"] for row in usage["per_iteration"]] == [1, 2]
+
+
+def test_cancel_after_rejected_answer_prevents_retry(tmp_path: Path) -> None:
+ garbage = '<││DSML││tool_calls><││invoke name="echo_probe">'
+ llm = _AnswerRetryLLM([LLMResponse(content=garbage)])
+ agent = AgentLoop(
+ registry=ToolRegistry(),
+ llm=llm,
+ max_iterations=1,
+ persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),
+ event_callback=lambda kind, payload: (
+ agent.cancel() if kind == "stream_reset" else None
+ ),
+ )
+ agent.memory.run_dir = str(tmp_path / "run")
+
+ result = agent.run("Write a report.")
+
+ assert result["status"] == "cancelled"
+ assert len(llm.offered_tools) == 1
+
+
+def test_retried_answer_still_passes_grounding(tmp_path: Path) -> None:
+ garbage = '<││DSML││tool_calls><││invoke name="echo_probe">'
+ llm = _AnswerRetryLLM(
+ [
+ LLMResponse(content=garbage),
+ LLMResponse(content="AAPL is trading at $999.00."),
+ ]
+ )
+ agent = AgentLoop(
+ registry=ToolRegistry(),
+ llm=llm,
+ max_iterations=1,
+ persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),
+ )
+ agent.memory.run_dir = str(tmp_path / "run")
+
+ result = agent.run("What is the AAPL stock price?")
+
+ assert result.get("degraded") is True
+ assert "$999.00" not in result["content"]
+ assert llm.offered_tools == [None, None]
+
+
+def test_answer_retry_blocks_calls_after_grounding_correction(tmp_path: Path) -> None:
+ garbage = '<││DSML││tool_calls><││invoke name="echo_probe">'
+ llm = _AnswerRetryLLM(
+ [
+ LLMResponse(content="The return was 9.99%."),
+ LLMResponse(content=garbage),
+ LLMResponse(
+ content="",
+ tool_calls=[
+ ToolCallRequest(id="retry", name="echo_probe", arguments={})
+ ],
+ ),
+ ]
+ )
+ registry = ToolRegistry()
+ registry.register(_EchoProbeTool())
+ events: list[tuple[str, dict[str, Any]]] = []
+ agent = AgentLoop(
+ registry=registry,
+ llm=llm,
+ max_iterations=2,
+ event_callback=lambda kind, payload: events.append((kind, payload)),
+ persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),
+ )
+ agent.memory.run_dir = str(tmp_path / "run")
+
+ result = agent.run("Summarize the returns.")
+
+ assert result["iterations"] == 3
+ assert result.get("degraded") is True
+ assert "tool-call syntax" in result["content"]
+ assert not any(kind in {"tool_call", "tool_result"} for kind, _ in events)