"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(loop): graceful exit on max iterations with wrap-up nudge + forced text-only (#148)
Thiên Toán002e042d449d
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex b2ac6667d..52bac772f 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -365,6 +365,7 @@ class AgentLoop:final_content = ""goal_continuations = 0goal_last_progress: tuple[int, int] | None = None+ wrap_up_at = max(1, int(self.max_iterations * 0.8))try:while iteration < self.max_iterations:@@ -399,6 +400,19 @@ class AgentLoop:logger.info(f"ReAct iteration {iteration}/{self.max_iterations}")+ # Inject wrap-up nudge when approaching iteration limit+ if iteration == wrap_up_at:+ remaining = self.max_iterations - iteration+ messages.append({+ "role": "user",+ "content": (+ f"[SYSTEM] You have {remaining} iterations remaining out of "+ f"{self.max_iterations}. Please wrap up your work. "+ "Stop calling tools and provide your final answer as plain text. "+ "If you have partial results, summarize what you have so far."+ ),+ })+# Streaming output + collect thinking textthinking_chunks: List[str] = []@@ -406,9 +420,15 @@ class AgentLoop:thinking_chunks.append(delta)self._emit("text_delta", {"delta": delta, "iter": iteration})+ # On last iteration, drop tool definitions to force text output+ is_last_iteration = (iteration == self.max_iterations)+ tool_defs = None if is_last_iteration else self.registry.get_definitions()+ if is_last_iteration:+ trace.write({"type": "forced_text_only", "iter": iteration})+response = self.llm.stream_chat(messages,- tools=self.registry.get_definitions(),+ tools=tool_defs,on_text_chunk=_on_text_chunk,)usage = getattr(response, "usage_metadata", None) or {}diff --git a/agent/tests/test_agent_loop_terminal_state.py b/agent/tests/test_agent_loop_terminal_state.pyindex e2836198f..e3d001f79 100644--- a/agent/tests/test_agent_loop_terminal_state.py+++ b/agent/tests/test_agent_loop_terminal_state.py@@ -138,3 +138,44 @@ def test_session_service_renders_meaningful_error_from_result(tmp_path: Path) ->assert ui_error != "unknown"assert "max iterations" in ui_errorassert "2" in ui_error+++class _StubLLMAlwaysToolCalls:+ """LLM stub that returns tool calls until tools=None forces text."""++ def __init__(self) -> None:+ self._counter = 0++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ ) -> _StubLLMResponse:+ resp = _StubLLMResponse()+ if tools is not None:+ self._counter += 1+ resp.has_tool_calls = True+ resp.tool_calls = [+ type("TC", (), {"id": f"tc_{self._counter}", "name": "compact", "arguments": {}})()+ ]+ else:+ resp.content = "Final answer from forced text-only."+ resp.has_tool_calls = False+ return resp++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:+ return _StubLLMResponse()+++def test_force_text_only_on_last_iteration(tmp_path: Path) -> None:+ """When the LLM keeps calling tools, the last iteration forces text-only+ output by passing tools=None, producing a final answer instead of failure."""+ agent = _build_agent(+ _StubLLMAlwaysToolCalls(), max_iter=5, tmp_run_dir=tmp_path / "run"+ )+ result = agent.run(user_message="do something")++ assert result["status"] == "success"+ assert "Final answer" in result["content"]+ assert result["iterations"] == 5