Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge PR #2109: carry cache details and count retry usage separately from context size

Haozhe Wu19e06c56f8fd
diff --cc agent/src/agent/llm_usage.py
index 65113d819,65113d819..8b1349cdd
--- a/agent/src/agent/llm_usage.py
+++ b/agent/src/agent/llm_usage.py
@@@ -54,6 -54,6 +54,10 @@@ def _normalize_llm_usage(usage: Any) -
"output_tokens": output_tokens,
"total_tokens": total_tokens,
}
++ if "calls" in usage:
++ normalized["calls"] = max(1, _coerce_usage_int(usage["calls"]))
++ if "context_input_tokens" in usage:
++ normalized["context_input_tokens"] = _coerce_usage_int(usage["context_input_tokens"])
details = usage.get("input_token_details")
if isinstance(details, dict):
if details.get("cache_read") is not None:
@@@ -105,7 -105,7 +109,7 @@@ def _record_llm_usage
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
++ totals["calls"] = int(totals.get("calls") or 0) + normalized.get("calls", 1)
for key in ("cache_read_tokens", "cache_creation_tokens", "reasoning_tokens"):
if key in normalized:
totals[key] = int(totals.get(key) or 0) + normalized[key]
diff --cc agent/src/agent/loop.py
index e0eb5dac6,e0eb5dac6..cae56ab31
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@@ -770,7 -770,7 +770,7 @@@ class AgentLoop(ToolCallLifecycle)
current_response_model = getattr(response, "response_model", None)
# `messages` is still exactly what this request sent.
self._context_meter.observe(
-- usage.get("input_tokens") if isinstance(usage, dict) else None,
++ usage.get("context_input_tokens", usage.get("input_tokens")) if isinstance(usage, dict) else None,
messages,
tool_schema_tokens=estimate_tokens(tool_defs) if tool_defs else 0,
)
diff --cc agent/src/providers/chat.py
index 5fe2726d9,d250a1d46..cc2517ef5
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@@ -630,7 -601,7 +630,8 @@@ class ChatLLM
model = self.model_name or _cfg.llm.langchain_model_name.strip() or "(unset)"
raise ProviderStreamError(
provider=provider, model=model, original=exc,
-- usage_metadata=getattr(accumulated, "usage_metadata", None),
++ usage_metadata=(getattr(exc, "usage_metadata", None)
++ or getattr(accumulated, "usage_metadata", None)),
) from exc
@staticmethod
diff --cc agent/src/providers/claude_cli.py
index 4db0ec957,1e5a14c9b..81c5094cf
--- a/agent/src/providers/claude_cli.py
+++ b/agent/src/providers/claude_cli.py
@@@ -247,7 -247,7 +247,7 @@@ def _schema(allow_tools: bool) -> dict[
class _Decision:
content: str = ""
tool_calls: list[dict[str, Any]] = field(default_factory=list)
-- usage: dict[str, int] = field(
++ usage: dict[str, Any] = field(
default_factory=lambda: {
"input_tokens": 0,
"output_tokens": 0,
@@@ -335,18 -335,17 +335,19 @@@ def _run_cli
return payload
- def _usage(payload: dict[str, Any]) -> dict[str, int]:
+ def _usage(payload: dict[str, Any]) -> dict[str, Any]:
usage = payload.get("usage") or {}
- tokens_in = sum(
- int(usage.get(k) or 0)
- for k in (
- "input_tokens",
- "cache_creation_input_tokens",
- "cache_read_input_tokens",
- cache_creation = int(
- (usage.get("cache_creation_input_tokens") or 0)
- + (usage.get("ephemeral_5m_input_tokens") or 0)
- + (usage.get("ephemeral_1h_input_tokens") or 0)
- )
++ creation = usage.get("cache_creation") or {}
++ cache_creation = int(usage.get("cache_creation_input_tokens") or 0)
++ if "cache_creation_input_tokens" not in usage:
++ cache_creation = sum(
++ int(creation.get(key, usage.get(key)) or 0)
++ for key in ("ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens")
+ )
- )
+ cache_read = int(usage.get("cache_read_input_tokens") or 0)
+ tokens_in = int(usage.get("input_tokens") or 0) + cache_creation + cache_read
tokens_out = int(usage.get("output_tokens") or 0)
- return {
+ result: dict[str, Any] = {
"input_tokens": tokens_in,
"output_tokens": tokens_out,
"total_tokens": tokens_in + tokens_out,
@@@ -394,26 -399,26 +401,36 @@@ def _decide
for _ in range(_MAX_RETRIES + 1):
remaining = deadline - time.monotonic()
if remaining <= 0:
-- raise RuntimeError(f"claude-cli: decision exceeded {timeout:.0f}s")
-- payload = _run_cli(
-- system=system,
-- user_input=user_input,
-- allow_tools=allow_tools,
-- model=model,
-- effort=effort,
-- timeout=remaining,
-- cancel_event=cancel_event,
-- )
++ error = RuntimeError(f"claude-cli: decision exceeded {timeout:.0f}s")
++ error.usage_metadata = decision.usage
++ raise error
++ try:
++ payload = _run_cli(
++ system=system,
++ user_input=user_input,
++ allow_tools=allow_tools,
++ model=model,
++ effort=effort,
++ timeout=remaining,
++ cancel_event=cancel_event,
++ )
++ except Exception as exc:
++ exc.usage_metadata = decision.usage
++ raise
if payload.get("cancelled"):
return None
-- # The loop reads input_tokens as the current context size; summing the
-- # re-sent prompt over feedback retries would double it and compact early.
attempt = _usage(payload)
-- decision.usage["input_tokens"] = attempt["input_tokens"]
-- decision.usage["output_tokens"] += attempt["output_tokens"]
-- decision.usage["total_tokens"] = (
-- decision.usage["input_tokens"] + decision.usage["output_tokens"]
-- )
++ # Billing accumulates every invocation; compaction uses only the last
++ # prompt, not the sum of prompts resent during feedback retries.
++ decision.usage["context_input_tokens"] = attempt["input_tokens"]
++ decision.usage["calls"] = decision.usage.get("calls", 0) + 1
++ for key in ("input_tokens", "output_tokens", "total_tokens"):
++ decision.usage[key] += attempt[key]
++ for key in ("input_token_details", "output_token_details"):
++ if key in attempt:
++ details = decision.usage.setdefault(key, {})
++ for name, count in attempt[key].items():
++ details[name] = details.get(name, 0) + count
output = payload["structured_output"]
calls = (
(output.get("tool_calls") or [])
@@@ -462,7 -467,7 +479,9 @@@
+ "\nChoose different calls or answer with what you have."
)
failure = "tool calls kept violating the host policy: " + "; ".join(notes)
-- raise RuntimeError(f"claude-cli: {failure}")
++ error = RuntimeError(f"claude-cli: {failure}")
++ error.usage_metadata = decision.usage
++ raise error
class ClaudeCliLLM:
diff --cc agent/tests/test_claude_cli_provider.py
index 0b6a2f9e2,3e1a16ba6..297c9350c
--- a/agent/tests/test_claude_cli_provider.py
+++ b/agent/tests/test_claude_cli_provider.py
@@@ -130,9 -130,9 +130,10 @@@ def test_final_without_content_is_fed_b
assert message.content == "order 42 cancelled"
assert "no tool calls and no content" in calls()[1]["stdin"]
-- # input_tokens is the last prompt's size (what the context meter reads);
-- # output_tokens is what both attempts generated.
-- assert message.usage_metadata["input_tokens"] == 10
++ # Billing includes both attempts, while compaction sees the last prompt.
++ assert message.usage_metadata["input_tokens"] == 20
++ assert message.usage_metadata["context_input_tokens"] == 10
++ assert message.usage_metadata["calls"] == 2
assert message.usage_metadata["output_tokens"] == 10
@@@ -524,3 -524,31 +525,76 @@@ def test_preflight_uses_cli_login(monke
assert result.status == "not_configured"
assert "claude auth login" in result.impact
+
+
+ def test_usage_preserves_cache_split_as_input_token_details() -> None:
+ result = claude_cli._usage({
+ "usage": {
+ "input_tokens": 10,
+ "cache_creation_input_tokens": 5,
+ "cache_read_input_tokens": 20,
+ "output_tokens": 3,
+ },
+ })
+ assert result == {
+ "input_tokens": 35,
+ "output_tokens": 3,
+ "total_tokens": 38,
+ "input_token_details": {"cache_read": 20, "cache_creation": 5},
+ }
+
+
+ def test_usage_omits_details_when_no_cache() -> None:
+ result = claude_cli._usage({
+ "usage": {"input_tokens": 10, "output_tokens": 3},
+ })
+ assert result == {
+ "input_tokens": 10,
+ "output_tokens": 3,
+ "total_tokens": 13,
+ }
++
++
[email protected]("streaming", [False, True])
++def test_retry_details_reach_persisted_usage(fake_cli, monkeypatch, tmp_path, streaming):
++ from src.agent.llm_usage import _new_llm_usage_summary, _record_llm_usage
++ set_replies, _ = fake_cli
++ replies = []
++ for content, tokens in [("", 10), ("done", 20)]:
++ reply = payload({"action": "final", "content": content})
++ reply["usage"] = {"input_tokens": tokens, "output_tokens": 3,
++ "cache_creation_input_tokens": 5, "cache_read_input_tokens": 7}
++ replies.append({"payload": reply})
++ set_replies(*replies)
++ use_provider(monkeypatch)
++ client = ChatLLM()
++ response = (client.stream_chat if streaming else client.chat)([{"role": "user", "content": "hi"}])
++ usage = response.usage_metadata
++ assert usage["input_tokens"] == 54
++ assert usage["context_input_tokens"] == 32
++ summary = _new_llm_usage_summary(client)
++ _record_llm_usage(tmp_path, summary, usage, 1)
++ saved = json.loads((tmp_path / "llm_usage.json").read_text())
++ assert saved["totals"] == {"input_tokens": 54, "output_tokens": 6,
++ "total_tokens": 60, "calls": 2, "cache_read_tokens": 14, "cache_creation_tokens": 10}
++
++
++def test_cache_creation_total_is_not_added_to_its_breakdown():
++ usage = claude_cli._usage({"usage": {"input_tokens": 10,
++ "cache_creation_input_tokens": 5, "ephemeral_5m_input_tokens": 5,
++ "cache_creation": {"ephemeral_5m_input_tokens": 5}}})
++ assert usage["input_tokens"] == 15
++ assert usage["input_token_details"]["cache_creation"] == 5
++
++
++def test_exhausted_feedback_retries_keep_their_paid_usage(fake_cli, monkeypatch):
++ set_replies, _ = fake_cli
++ set_replies(*[{"payload": payload({"action": "final", "content": ""})}
++ for _ in range(claude_cli._MAX_RETRIES + 1)])
++ use_provider(monkeypatch)
++ with pytest.raises(Exception, match="without content") as failure:
++ ChatLLM().stream_chat([{"role": "user", "content": "hi"}])
++ usage = failure.value.usage_metadata
++ assert usage["calls"] == 4
++ assert usage["input_tokens"] == 40
++ assert usage["output_tokens"] == 20
diff --cc agent/tests/test_llm_cost_accounting.py
index 57119c67a,57119c67a..0afa22af2
--- a/agent/tests/test_llm_cost_accounting.py
+++ b/agent/tests/test_llm_cost_accounting.py
@@@ -141,13 -141,13 +141,16 @@@ def test_cancelled_agent_response_keeps
def test_cancelled_stream_keeps_usage_from_already_received_chunk():
client = object.__new__(ChatLLM)
-- client._llm = SimpleNamespace(stream=lambda *args, **kwargs: iter([
-- AIMessageChunk(content="", usage_metadata=USAGE),
-- ]))
++ import threading
++ cancel = threading.Event()
++ def stream(*args, **kwargs):
++ cancel.set() # Usage arrived before cancellation was observed by the host.
++ yield AIMessageChunk(content="", usage_metadata=USAGE)
++ client._llm = SimpleNamespace(stream=stream)
client._prompt_cache_request = lambda messages: (messages, {})
on_text = Mock()
response = client.stream_chat(
-- [{"role": "user", "content": "hello"}], should_cancel=lambda: True,
++ [{"role": "user", "content": "hello"}], should_cancel=cancel.is_set,
on_text_chunk=on_text,
)
assert response.usage_metadata == USAGE
@@@ -371,3 -371,3 +374,17 @@@ def test_a_text_answer_that_crosses_the
agent.run("Continue.", session_id="cost-test")
llm.stream_chat.assert_called_once()
++
++
++def test_retry_billing_does_not_inflate_context_meter(tmp_path, monkeypatch):
++ agent, llm = _agent(tmp_path, lambda *args: None)
++ llm.stream_chat.side_effect = lambda *args, **kwargs: LLMResponse(
++ content="Hello.", usage_metadata={"input_tokens": 3000, "output_tokens": 90,
++ "total_tokens": 3090, "calls": 3, "context_input_tokens": 1000})
++ observed = []
++ monkeypatch.setattr(type(agent._context_meter), "observe", lambda self, n, *a, **kw: observed.append(n))
++ agent.run("Say hello.")
++ assert observed == [1000]
++ report = json.loads((tmp_path / "llm_usage.json").read_text())
++ assert report["totals"]["input_tokens"] == 3000
++ assert report["totals"]["calls"] == 3