"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): don't halt live decisions on unreported auxiliary usage; release over-budget answers
Haozhe Wu6208424a1fe6
diff --git a/agent/src/agent/llm_usage.py b/agent/src/agent/llm_usage.pyindex 7cf7b4bb5..65113d819 100644--- a/agent/src/agent/llm_usage.py+++ b/agent/src/agent/llm_usage.py@@ -113,8 +113,25 @@ def _record_llm_usage(if purpose is not None:entry["purpose"] = purposesummary.setdefault("per_iteration", []).append(entry)- summary["updated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ _write_llm_usage(run_dir, summary)+ return normalized+++def _record_unreported_llm_call(run_dir: Path, summary: dict[str, Any]) -> None:+ """Count a call whose provider reported no usage, without inventing tokens.++ Args:+ run_dir: Active run's artifact directory.+ summary: The run's usage summary, updated in place.+ """+ totals = summary.setdefault("totals", {})+ totals["unreported_calls"] = int(totals.get("unreported_calls") or 0) + 1+ _write_llm_usage(run_dir, summary)++def _write_llm_usage(run_dir: Path, summary: dict[str, Any]) -> None:+ """Stamp and atomically persist the usage summary; a write failure is logged."""+ summary["updated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")try:path = run_dir / LLM_USAGE_ARTIFACTtmp_path = path.with_suffix(path.suffix + ".tmp")@@ -125,5 +142,3 @@ def _record_llm_usage(tmp_path.replace(path)except OSError as exc:logger.debug("LLM usage artifact write skipped: %s", exc)-- return normalizeddiff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 8983fe10d..ca8bed1bd 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -163,6 +163,7 @@ from src.agent.llm_usage import ( # noqa: E402_normalize_llm_usage as _normalize_llm_usage,_new_llm_usage_summary as _new_llm_usage_summary,_record_llm_usage as _record_llm_usage,+ _record_unreported_llm_call as _record_unreported_llm_call,)@@ -478,7 +479,8 @@ class AgentLoop(ToolCallLifecycle):if limit is not None and int(goal.get("tokens_used") or 0) >= limit:self._budget_stop_reason = ("goal_token_budget_exhausted: the research goal's token budget "- "has been reached. Increase its budget or end the goal before continuing."+ "has been reached. End the goal to continue; a new goal can set a "+ "larger budget.")if active_goal_id and session_id:@@ -759,8 +761,11 @@ class AgentLoop(ToolCallLifecycle):last_response_model = current_response_modelself._account_llm_usage(run_dir, usage, current_iter)# A caller's spending monitor can cancel synchronously on the- # usage event. Do not execute tools from that paid response.- if self._cancel_event.is_set() or self._budget_stop_reason is not None:+ # usage event. Do not execute tools from that paid response; a+ # text-only answer that crossed a goal budget is still released.+ if self._cancel_event.is_set() or (+ self._budget_stop_reason is not None and response.has_tool_calls+ ):breakthinking_text = "".join(stream.thinking_chunks)if thinking_text:@@ -1139,6 +1144,7 @@ class AgentLoop(ToolCallLifecycle):empty_response_model=self._llm_runtime.configured_model or "(unset)",max_iterations=self.max_iterations,budget_reason=self._budget_stop_reason,+ answer_released=bool(final_content),))final_reason = outcome.reason@@ -1445,8 +1451,14 @@ class AgentLoop(ToolCallLifecycle):**delta, **metadata,"call_index": self._llm_usage_summary["totals"]["calls"],})- else:+ elif purpose is None and not self._cancel_event.is_set():self._emit("llm_usage_unavailable", metadata)+ else:+ # A failed stream, a compaction call or a cancelled response that+ # reported nothing is counted as unreported, not announced as a+ # missing bill: the live decision budget halts on that event, so a+ # retried connection reset stopped live decisions for the day.+ _record_unreported_llm_call(run_dir, self._llm_usage_summary)# -- Context compression ---------------------------------------------------diff --git a/agent/src/agent/run_outcome.py b/agent/src/agent/run_outcome.pyindex 6b98ee861..845c2d618 100644--- a/agent/src/agent/run_outcome.py+++ b/agent/src/agent/run_outcome.py@@ -75,6 +75,8 @@ class OutcomeInputs:max_iterations: The run's iteration budget (for the failuremessage).budget_reason: An exhausted research-goal token budget, if any.+ answer_released: Whether a final answer was released to the user.+ One that crossed the budget is a degraded success, not a failure."""stall_reason: Optional[str]@@ -91,6 +93,7 @@ class OutcomeInputs:empty_response_model: strmax_iterations: intbudget_reason: Optional[str] = None+ answer_released: bool = False@dataclass@@ -130,7 +133,7 @@ def resolve_final_status(inputs: OutcomeInputs) -> RunOutcome:return RunOutcome("failed", inputs.stall_reason, None, False)if inputs.cancelled:return RunOutcome("cancelled", "cancelled by user", "cancelled", False)- if inputs.budget_reason is not None:+ if inputs.budget_reason is not None and not inputs.answer_released:return RunOutcome("failed", inputs.budget_reason, "failure", False)if inputs.no_progress_reason is not None:return RunOutcome("failed", inputs.no_progress_reason, "failure", False)@@ -142,6 +145,9 @@ def resolve_final_status(inputs: OutcomeInputs) -> RunOutcome:)return RunOutcome("failed", reason, "failure", False)if inputs.has_output:+ if inputs.budget_reason is not None:+ # The answer that crossed a goal's token budget was released.+ return RunOutcome("success", inputs.budget_reason, "success", True)if inputs.released_fallback:reason = inputs.released_fallback_reason or ("final answer degraded to the deterministic fallback after "diff --git a/agent/tests/test_llm_cost_accounting.py b/agent/tests/test_llm_cost_accounting.pyindex 2a8487c55..57119c67a 100644--- a/agent/tests/test_llm_cost_accounting.py+++ b/agent/tests/test_llm_cost_accounting.py@@ -114,8 +114,12 @@ def test_failed_summary_without_timeout_reports_unknown_usage(tmp_path, monkeypaagent._auto_compact(_messages(), tmp_path, trace, iteration=7)finally:trace.close()- assert ("llm_usage_unavailable", {"iter": 7, "purpose": "compaction"}) in events- assert not (tmp_path / "llm_usage.json").exists()+ # Counted as unreported rather than announced: the live decision budget+ # halts on llm_usage_unavailable (see the live-budget test below).+ assert not [event for event in events if event[0] == "llm_usage_unavailable"]+ report = json.loads((tmp_path / "llm_usage.json").read_text())+ assert report["totals"]["unreported_calls"] == 1+ assert report["totals"]["calls"] == report["totals"]["total_tokens"] == 0def test_cancelled_agent_response_keeps_reported_usage(tmp_path):@@ -291,3 +295,79 @@ def test_failed_stream_usage_is_counted_before_retry(tmp_path, monkeypatch, recoassert report["totals"]["calls"] == 2assert report["totals"]["total_tokens"] == USAGE["total_tokens"] * 2assert report["per_iteration"][0]["purpose"] == "failed_stream"+++def _usage_events(events):+ return [(kind, data) for kind, data in events if kind.startswith("llm_usage")]+++def test_failed_stream_without_usage_is_counted_not_announced(tmp_path, monkeypatch):+ from src.providers.chat import ProviderStreamError++ events = []+ agent, llm = _agent(tmp_path, lambda kind, data: events.append((kind, data)))+ monkeypatch.setattr("src.agent.loop._stream_retry_backoff_s", lambda _: 0)+ llm.stream_chat.side_effect = [+ ProviderStreamError(provider="deepseek", model="m", original=ConnectionError("reset")),+ LLMResponse(content="Hello", usage_metadata=USAGE),+ ]+ result = agent.run("Say hello.")+ assert result["status"] == "success"+ assert [kind for kind, _ in _usage_events(events)] == ["llm_usage"]+ report = json.loads((tmp_path / "llm_usage.json").read_text())+ assert report["totals"]["calls"] == 1+ assert report["totals"]["unreported_calls"] == 1+++def test_live_decision_budget_survives_a_retried_connection_reset(tmp_path, monkeypatch):+ """A reset then a successful retry used to halt live decisions for the day."""+ from datetime import datetime, timezone++ from src.live.runtime.decision_budget import DecisionBudget+ from src.providers.chat import ProviderStreamError++ events = []+ agent, llm = _agent(tmp_path, lambda kind, data: events.append((kind, data)))+ monkeypatch.setattr("src.agent.loop._stream_retry_backoff_s", lambda _: 0)+ llm.stream_chat.side_effect = [+ ProviderStreamError(provider="deepseek", model="m", original=ConnectionError("reset")),+ LLMResponse(content="Hold.", usage_metadata=USAGE),+ ]+ agent.run("Decide.")+ budget = DecisionBudget("alpaca", path=tmp_path / "budget.db")+ settings, now = budget.settings(), datetime.now(timezone.utc)+ decision = budget.begin(settings, now)+ for kind, data in _usage_events(events):+ # The way live_routes forwards events to the budget.+ budget.record(decision, data if kind == "llm_usage" else {}, settings, now)+ budget.finish(decision, settings, now)+++def test_an_ordinary_response_without_usage_is_still_announced(tmp_path):+ events = []+ agent, llm = _agent(tmp_path, lambda kind, data: events.append((kind, data)))+ llm.stream_chat.return_value = LLMResponse(content="Hello", usage_metadata=None)+ agent.run("Say hello.")+ assert ("llm_usage_unavailable", {"iter": 1}) in _usage_events(events)+++def test_a_text_answer_that_crosses_the_goal_budget_is_released(tmp_path, monkeypatch):+ from src.goal import GoalStore++ monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))+ store = GoalStore()+ goal = store.replace_goal(+ session_id="cost-test", objective="Answer.", criteria=["answer"], token_budget=1000,+ )+ agent, llm = _agent(tmp_path)+ llm.stream_chat.return_value = LLMResponse(content="Here is the full answer.", usage_metadata=USAGE)+ result = agent.run("Answer it.", session_id="cost-test")+ assert result["status"] == "success"+ assert result["content"] == "Here is the full answer."+ assert "goal_token_budget_exhausted" in result["reason"]+ assert store.get_goal(goal.goal_id).tokens_used == 1100++ # The exhausted goal still refuses further spending.+ agent.run("Continue.", session_id="cost-test")+ llm.stream_chat.assert_called_once()+