"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(swarm): use real provider tokens for SwarmRun totals
Teerapat Vatpitak96dbdb80509f
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex b7fd9ff35..73b97779d 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -45,13 +45,20 @@ class LLMResponse:Attributes:content: Text content (final answer or thinking text).tool_calls: List of tool call requests.+ reasoning_content: Optional thinking trace surfaced by reasoning models.finish_reason: Finish reason string.+ usage_metadata: Real token counts reported by the provider, when+ available. Mirrors LangChain's ``AIMessage.usage_metadata`` —+ ``{"input_tokens": int, "output_tokens": int, "total_tokens": int}``.+ ``None`` if the provider did not return usage information; callers+ should fall back to a heuristic in that case."""content: Optional[str] = Nonetool_calls: List[ToolCallRequest] = field(default_factory=list)reasoning_content: Optional[str] = Nonefinish_reason: str = "stop"+ usage_metadata: Optional[Dict[str, int]] = None@propertydef has_tool_calls(self) -> bool:@@ -150,7 +157,24 @@ class ChatLLM:Single source for reasoning: ``additional_kwargs["reasoning_content"]``,populated by ``ChatOpenAIWithReasoning`` on both stream and non-stream paths.++ ``usage_metadata`` is forwarded as-is from the underlying message so+ downstream cost / billing audit code (e.g. swarm worker token totals)+ can use real provider tokens instead of a character-count heuristic.+ For ``AIMessageChunk`` the metadata accumulates via the ``__add__``+ merge LangChain performs while the response is being streamed; the+ final aggregate carries the same shape as the non-stream path."""+ usage = getattr(ai_message, "usage_metadata", None)+ # Some providers / older LangChain versions surface a ``UsageMetadata``+ # TypedDict that doesn't json-serialise without a cast. Normalise to a+ # plain ``dict[str, int]`` so the value can be persisted alongside the+ # rest of the run state without surprises.+ if usage is not None and not isinstance(usage, dict):+ try:+ usage = dict(usage)+ except (TypeError, ValueError):+ usage = Nonereturn LLMResponse(content=ai_message.content,tool_calls=[@@ -161,4 +185,5 @@ class ChatLLM:finish_reason=_dedupe_finish_reason(ai_message.response_metadata.get("finish_reason", "stop")),+ usage_metadata=usage,)diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex 12eeac1a9..a5969523c 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -86,26 +86,41 @@ def _estimate_tokens(messages: list[dict],response: object,) -> tuple[int, int]:- """Estimate token usage for a single LLM call.+ """Return token usage for a single LLM call, real if available.- Tries to read actual token counts from the LLM response metadata- (LangChain's usage_metadata). Falls back to character-length estimation- (len // 4) if metadata is unavailable.+ Prefers the provider-reported counts attached to the response by+ :func:`ChatLLM._parse_response` (``usage_metadata``). Falls back to a+ character-length heuristic (``len // 4``) only when the provider+ didn't return usage data — keeps the behaviour contract for legacy+ or partial responses while making per-run totals (which feed+ ``SwarmRun.total_input_tokens`` / ``total_output_tokens``) reflect+ real billing instead of a CJK-hostile char-count guess.Args:- messages: Messages sent to the LLM for this call.- response: LLMResponse from ChatLLM.chat().+ messages: Messages sent to the LLM for this call. Used only for+ the fallback estimate when ``response.usage_metadata`` is+ missing.+ response: ``LLMResponse`` from ``ChatLLM.chat`` /+ ``ChatLLM.stream_chat``.Returns:- Tuple of (input_tokens, output_tokens).+ Tuple of (input_tokens, output_tokens). Either component may be+ zero — that simply means the provider didn't report it and the+ fallback couldn't compute it either (e.g. binary content)."""from src.providers.chat import LLMResponse- input_tokens = 0- output_tokens = 0-- # response is an LLMResponse; it doesn't carry raw metadata.- # Estimate: input = serialized messages length // 4, output = content length // 4+ if isinstance(response, LLMResponse) and response.usage_metadata:+ usage = response.usage_metadata+ real_input = int(usage.get("input_tokens") or 0)+ real_output = int(usage.get("output_tokens") or 0)+ if real_input or real_output:+ return real_input, real_output++ # Fallback: provider didn't return usage_metadata. Estimate from+ # serialized message length and response content length. ~4 chars per+ # English token; under-counts for CJK / Thai / emoji-heavy prompts but+ # at least preserves the prior behaviour.try:input_tokens = len(json.dumps(messages, ensure_ascii=False)) // 4except Exception:diff --git a/agent/tests/test_swarm_token_tracking.py b/agent/tests/test_swarm_token_tracking.pynew file mode 100644index 000000000..102c51824--- /dev/null+++ b/agent/tests/test_swarm_token_tracking.py@@ -0,0 +1,156 @@+"""Tests for real-token propagation from LangChain through to swarm totals.++The swarm's ``total_input_tokens`` / ``total_output_tokens`` used to be+character-count guesses (``len(json.dumps(messages)) // 4``) — wrong by+20-50% for English prompts and dramatically wrong for CJK / Thai /+emoji-heavy traffic. LangChain already attaches real provider token+counts on every ``AIMessage.usage_metadata``; the swarm just wasn't+reading them. These tests pin down both ends of the new contract:++* :class:`LLMResponse` carries ``usage_metadata`` straight off the+ parsed message (covered by exercising :meth:`ChatLLM._parse_response`+ on a fake AIMessage).+* :func:`worker._estimate_tokens` prefers those real counts when present+ and only falls back to the legacy heuristic when the provider didn't+ report usage.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from src.providers.chat import ChatLLM, LLMResponse+from src.swarm.worker import _estimate_tokens+++# --------------------------------------------------------------------------- #+# ChatLLM._parse_response — usage_metadata propagation+# --------------------------------------------------------------------------- #+++def _fake_ai_message(usage_metadata=None, content="hello", finish="stop"):+ """Build the smallest object that quacks like a LangChain AIMessage."""+ return SimpleNamespace(+ content=content,+ tool_calls=[],+ additional_kwargs={},+ response_metadata={"finish_reason": finish},+ usage_metadata=usage_metadata,+ )+++def test_parse_response_propagates_usage_metadata_dict() -> None:+ msg = _fake_ai_message(+ usage_metadata={"input_tokens": 1234, "output_tokens": 56, "total_tokens": 1290}+ )+ parsed = ChatLLM._parse_response(msg)+ assert parsed.usage_metadata == {+ "input_tokens": 1234,+ "output_tokens": 56,+ "total_tokens": 1290,+ }+++def test_parse_response_normalises_typed_dict_like_usage_to_plain_dict() -> None:+ """Some LangChain versions return a TypedDict; we want a plain dict on the wire."""++ class _UsageLike:+ def __iter__(self):+ return iter([("input_tokens", 7), ("output_tokens", 11)])++ msg = _fake_ai_message(usage_metadata=_UsageLike())+ parsed = ChatLLM._parse_response(msg)+ assert isinstance(parsed.usage_metadata, dict)+ assert parsed.usage_metadata == {"input_tokens": 7, "output_tokens": 11}+++def test_parse_response_keeps_usage_metadata_none_when_provider_omits_it() -> None:+ msg = _fake_ai_message(usage_metadata=None)+ parsed = ChatLLM._parse_response(msg)+ assert parsed.usage_metadata is None+++def test_parse_response_handles_unconvertible_usage_gracefully() -> None:+ """A non-iterable, non-dict usage object should degrade to None, not crash."""+ msg = _fake_ai_message(usage_metadata=object())+ parsed = ChatLLM._parse_response(msg)+ assert parsed.usage_metadata is None+++# --------------------------------------------------------------------------- #+# worker._estimate_tokens — prefers real counts, falls back otherwise+# --------------------------------------------------------------------------- #+++def test_estimate_tokens_uses_real_usage_metadata_when_present() -> None:+ response = LLMResponse(+ content="ignored for this assertion",+ usage_metadata={"input_tokens": 980_137, "output_tokens": 15_868},+ )+ in_tok, out_tok = _estimate_tokens(messages=[{"role": "user", "content": "x" * 1_000_000}], response=response)+ # Real provider counts win even though the heuristic would over-estimate+ # massively from the bogus 1M-char message payload above.+ assert in_tok == 980_137+ assert out_tok == 15_868+++def test_estimate_tokens_falls_back_when_usage_metadata_is_none() -> None:+ messages = [{"role": "user", "content": "hello world"}]+ response = LLMResponse(content="howdy", usage_metadata=None)+ in_tok, out_tok = _estimate_tokens(messages, response)+ # Heuristic: roughly len(json.dumps(messages)) // 4 and len(content) // 4.+ # We don't pin exact numbers (they depend on json formatting) but they+ # must be positive and proportional to length.+ assert in_tok > 0+ assert out_tok == len("howdy") // 4+++def test_estimate_tokens_falls_back_when_usage_metadata_is_all_zero() -> None:+ """A provider that returns ``{"input_tokens": 0, "output_tokens": 0}`` is+ treated as 'no real data' so we don't pin per-run totals at zero."""+ messages = [{"role": "user", "content": "hello"}]+ response = LLMResponse(+ content="hi back",+ usage_metadata={"input_tokens": 0, "output_tokens": 0},+ )+ in_tok, out_tok = _estimate_tokens(messages, response)+ assert in_tok > 0+ assert out_tok > 0+++def test_estimate_tokens_partial_usage_metadata_is_used_directly() -> None:+ """If the provider reports input but not output, take input verbatim and+ let output drop to 0 — better than silently mixing real + heuristic."""+ response = LLMResponse(+ content="some text",+ usage_metadata={"input_tokens": 500, "output_tokens": 0},+ )+ in_tok, out_tok = _estimate_tokens([], response)+ assert in_tok == 500+ assert out_tok == 0+++def test_estimate_tokens_handles_non_llmresponse_object_safely() -> None:+ """Defensive: callers from older code paths might pass a raw string."""+ in_tok, out_tok = _estimate_tokens([{"role": "user", "content": "abc"}], "not-an-LLMResponse")+ # Input falls through to the heuristic; output can't be derived without+ # an LLMResponse, so it's 0 — same as the old behaviour.+ assert in_tok > 0+ assert out_tok == 0++[email protected]("metadata_keys_extra", [+ {},+ {"total_tokens": 12345},+ {"input_token_details": {"cached": 100}, "output_token_details": {"reasoning": 50}},+])+def test_estimate_tokens_ignores_extra_metadata_fields(metadata_keys_extra: dict) -> None:+ """LangChain occasionally returns extra fields (cache hits, reasoning+ sub-counts). They should not interfere with the bare input/output read."""+ metadata = {"input_tokens": 100, "output_tokens": 20, **metadata_keys_extra}+ response = LLMResponse(content="x", usage_metadata=metadata)+ in_tok, out_tok = _estimate_tokens([], response)+ assert in_tok == 100+ assert out_tok == 20