"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(agent): persist AgentLoop usage artifacts (#223)
LemonCANDY428678c289ce8b
diff --git a/agent/api_server.py b/agent/api_server.pyindex 8c4fdd700..10e921ce4 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -114,6 +114,7 @@ class RunResponse(BaseModel):metrics: Optional[BacktestMetrics] = Field(None, description="Backtest metrics")artifacts: List[Artifact] = Field(default_factory=list, description="Run artifacts")run_card: Optional[Dict[str, Any]] = Field(None, description="Trust Layer run card payload")+ llm_usage: Optional[Dict[str, Any]] = Field(None, description="Provider-reported AgentLoop usage summary")equity_curve: Optional[List[Dict[str, Any]]] = Field(None, description="Equity preview")trade_log: Optional[List[Dict[str, Any]]] = Field(None, description="Trade preview")@@ -1115,6 +1116,13 @@ def _build_response_from_run_dir(run_dir: Path, elapsed: float, *, include_analyexcept (json.JSONDecodeError, OSError):pass+ llm_usage_path = run_dir / "llm_usage.json"+ if llm_usage_path.exists():+ try:+ response.llm_usage = json.loads(llm_usage_path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError):+ pass+trades_path = run_dir / "artifacts" / "trades.csv"if trades_path.exists():response.artifacts_trades_csv = _load_csv_to_dict(trades_path)diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 41c5167f0..fd4d7e3a0 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -20,6 +20,7 @@ import osimport queueimport threadingimport time as _time+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional@@ -49,6 +50,7 @@ REASONING_DELTA_MIN_INTERVAL_S = float(os.getenv("VT_REASONING_DELTA_MIN_INTERVASTREAM_RETRY_DELAY_S = float(os.getenv("VT_STREAM_RETRY_DELAY_S", "1.0"))TOOL_TIMEOUT_SECONDS = float(os.getenv("VIBE_TRADING_TOOL_TIMEOUT_SECONDS", "1800"))GOAL_MAX_CONTINUATIONS = int(os.getenv("VIBE_TRADING_GOAL_MAX_CONTINUATIONS", "3"))+LLM_USAGE_ARTIFACT = "llm_usage.json"# Layer 2: Context collapse thresholdsCOLLAPSE_THRESHOLD = int(TOKEN_THRESHOLD * 0.7)@@ -63,6 +65,88 @@ TAIL_TOKEN_BUDGET = 20_000logger = logging.getLogger(__name__)+def _coerce_usage_int(value: Any) -> int:+ """Coerce provider token counts to non-negative ints."""+ try:+ return max(0, int(value or 0))+ except (TypeError, ValueError):+ return 0+++def _normalize_llm_usage(usage: Any) -> dict[str, int] | None:+ """Normalize provider-reported usage metadata without estimating tokens."""+ if usage is None:+ return None+ if not isinstance(usage, dict):+ try:+ usage = dict(usage)+ except (TypeError, ValueError):+ return None++ input_tokens = _coerce_usage_int(usage.get("input_tokens"))+ output_tokens = _coerce_usage_int(usage.get("output_tokens"))+ total_tokens = _coerce_usage_int(usage.get("total_tokens"))+ if total_tokens == 0 and (input_tokens or output_tokens):+ total_tokens = input_tokens + output_tokens+ if not (input_tokens or output_tokens or total_tokens):+ return None+ return {+ "input_tokens": input_tokens,+ "output_tokens": output_tokens,+ "total_tokens": total_tokens,+ }+++def _new_llm_usage_summary(llm: Any) -> dict[str, Any]:+ """Create the run-scoped provider usage accumulator."""+ provider = os.getenv("LANGCHAIN_PROVIDER", "openai").strip() or "openai"+ model = getattr(llm, "model_name", None) or os.getenv("LANGCHAIN_MODEL_NAME", "").strip()+ return {+ "provider": provider,+ "model": model,+ "totals": {+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ "calls": 0,+ },+ "per_iteration": [],+ }+++def _record_llm_usage(+ run_dir: Path,+ summary: dict[str, Any],+ usage: Any,+ iteration: int,+) -> dict[str, int] | None:+ """Accumulate and persist one provider-reported usage event."""+ normalized = _normalize_llm_usage(usage)+ if normalized is None:+ return None++ totals = summary.setdefault("totals", {})+ totals["input_tokens"] = int(totals.get("input_tokens") or 0) + normalized["input_tokens"]+ totals["output_tokens"] = int(totals.get("output_tokens") or 0) + normalized["output_tokens"]+ totals["total_tokens"] = int(totals.get("total_tokens") or 0) + normalized["total_tokens"]+ totals["calls"] = int(totals.get("calls") or 0) + 1+ summary.setdefault("per_iteration", []).append({"iter": iteration, **normalized})+ summary["updated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")++ try:+ path = run_dir / LLM_USAGE_ARTIFACT+ tmp_path = path.with_suffix(path.suffix + ".tmp")+ tmp_path.write_text(+ json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",+ encoding="utf-8",+ )+ tmp_path.replace(path)+ except OSError as exc:+ logger.debug("LLM usage artifact write skipped: %s", exc)++ return normalized++def _redact_trace_result(result: str) -> str:"""Redact structured sensitive fields before persisting trace/event previews.@@ -446,6 +530,7 @@ class AgentLoop:iteration = 0final_content = ""empty_model_response_iter: int | None = None+ llm_usage_summary = _new_llm_usage_summary(self.llm)goal_continuations = 0goal_last_progress: tuple[int, int] | None = Nonewrap_up_at = max(1, int(self.max_iterations * 0.8))@@ -576,19 +661,23 @@ class AgentLoop:on_text_chunk=_on_text_chunk,on_reasoning_chunk=_on_reasoning_chunk,)- usage = getattr(response, "usage_metadata", None) or {}- if usage:+ usage = getattr(response, "usage_metadata", None)+ usage_delta = _record_llm_usage(+ run_dir,+ llm_usage_summary,+ usage,+ current_iter,+ )+ if usage_delta:self._emit("llm_usage",{- "input_tokens": int(usage.get("input_tokens") or 0),- "output_tokens": int(usage.get("output_tokens") or 0),- "total_tokens": int(usage.get("total_tokens") or 0),+ **usage_delta,"iter": current_iter,},)if active_goal_id and session_id:- token_delta = int(usage.get("total_tokens") or 0) if usage else 0+ token_delta = int(usage_delta.get("total_tokens") or 0) if usage_delta else 0turn_delta = 0 if goal_turn_accounted else 1if token_delta or turn_delta:try:diff --git a/agent/tests/test_agent_loop_terminal_state.py b/agent/tests/test_agent_loop_terminal_state.pyindex c10e0670f..d65e6740b 100644--- a/agent/tests/test_agent_loop_terminal_state.py+++ b/agent/tests/test_agent_loop_terminal_state.py@@ -11,6 +11,7 @@ exits without hitting any real API.from __future__ import annotations+import jsonfrom pathlib import Pathfrom typing import Any, Callable@@ -50,6 +51,25 @@ class _StubLLMNoFinal:return _StubLLMResponse()+class _StubLLMWithUsage:+ model_name = "stub-model"++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ ) -> _StubLLMResponse:+ response = _StubLLMResponse()+ response.content = "done"+ response.usage_metadata = {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15}+ return response++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:+ return _StubLLMResponse()++class _StubLLMCancelMidStream:"""LLM stub that cancels the loop from inside the LLM call.@@ -142,6 +162,30 @@ def test_session_service_renders_meaningful_error_from_result(tmp_path: Path) ->assert "iteration 1" in ui_error+def test_usage_metadata_is_persisted_to_run_artifact(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Provider usage should remain auditable after the live SSE event is gone."""+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "pytest-provider")+ agent = _build_agent(_StubLLMWithUsage(), max_iter=2, tmp_run_dir=tmp_path / "run")++ result = agent.run(user_message="anything")++ assert result["status"] == "success"+ usage_path = tmp_path / "run" / "llm_usage.json"+ payload = json.loads(usage_path.read_text(encoding="utf-8"))+ assert payload["provider"] == "pytest-provider"+ assert payload["model"] == "stub-model"+ assert payload["totals"] == {+ "input_tokens": 10,+ "output_tokens": 5,+ "total_tokens": 15,+ "calls": 1,+ }+ assert payload["per_iteration"] == [+ {"iter": 1, "input_tokens": 10, "output_tokens": 5, "total_tokens": 15}+ ]+ assert payload["updated_at"].endswith("Z")++class _StubLLMAlwaysToolCalls:"""LLM stub that returns tool calls until tools=None forces text."""diff --git a/agent/tests/test_run_card.py b/agent/tests/test_run_card.pyindex 2a8c9bcc7..4b59c58d1 100644--- a/agent/tests/test_run_card.py+++ b/agent/tests/test_run_card.py@@ -149,6 +149,26 @@ def test_api_run_response_includes_run_card(tmp_path: Path) -> None:assert response.run_card == run_card+def test_api_run_response_includes_llm_usage(tmp_path: Path) -> None:+ import api_server++ run_dir = tmp_path / "run_001"+ run_dir.mkdir()+ (run_dir / "state.json").write_text('{"status": "success"}\n', encoding="utf-8")+ llm_usage = {+ "provider": "deepseek",+ "model": "deepseek-v3.2",+ "totals": {"input_tokens": 100, "output_tokens": 25, "total_tokens": 125, "calls": 1},+ "per_iteration": [{"iter": 1, "input_tokens": 100, "output_tokens": 25, "total_tokens": 125}],+ "updated_at": "2026-06-14T00:00:00Z",+ }+ (run_dir / "llm_usage.json").write_text(json.dumps(llm_usage), encoding="utf-8")++ response = api_server._build_response_from_run_dir(run_dir, elapsed=0.0)++ assert response.llm_usage == llm_usage++def test_runner_artifact_spec_surfaces_run_card_paths() -> None:runner = Runner()