Coverage for app / inference / monitor.py: 67%

30 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2UsageAccumulator — tracks token counts and cost across a multi-step inference. 

3 

4Multi-step graphs re-send the full accumulated context window on every LLM call, 

5so naively summing input_tokens counts the same tokens multiple times. Instead 

6we accumulate the *delta* — new tokens added since the previous call — matching 

7the logic in the legacy executor and streaming router. 

8""" 

9 

10from __future__ import annotations 

11 

12from dataclasses import dataclass, field 

13from typing import Any 

14 

15 

16@dataclass 

17class UsageAccumulator: 

18 """ 

19 Accumulates token usage and cost for one engine invocation. 

20 

21 Usage:: 

22 

23 acc = UsageAccumulator() 

24 # After each LLM call: 

25 acc.add_call(input_tokens=1200, output_tokens=80, model="openai/gpt-4o") 

26 # At the end: 

27 usage_dict = acc.to_dict() 

28 """ 

29 

30 prompt_tokens: int = 0 

31 completion_tokens: int = 0 

32 cost_usd: float = 0.0 

33 

34 _prev_input: int = field(default=0, repr=False) 

35 

36 def add_call( 

37 self, 

38 input_tokens: int, 

39 output_tokens: int, 

40 model: str = "", 

41 ) -> None: 

42 """ 

43 Record one LLM invocation. 

44 

45 ``input_tokens`` is the *full* context window size reported by the 

46 provider. We compute the delta vs the previous call so we only count 

47 genuinely new tokens, then accumulate completion tokens directly. 

48 

49 ``model`` should be the litellm model string (``"provider/name"``). 

50 When provided, cost is calculated via ``litellm.cost_per_token``. 

51 """ 

52 delta_in = max(0, input_tokens - self._prev_input) 

53 self._prev_input = input_tokens 

54 self.prompt_tokens += delta_in 

55 self.completion_tokens += output_tokens 

56 

57 if model: 

58 try: 

59 import litellm 

60 

61 p, c = litellm.cost_per_token( 

62 model=model, 

63 prompt_tokens=input_tokens, 

64 completion_tokens=output_tokens, 

65 ) 

66 self.cost_usd += p + c 

67 except Exception: 

68 pass 

69 

70 def add_usage_dict(self, usage: dict[str, Any], model: str = "") -> None: 

71 """Convenience wrapper accepting a litellm-shaped usage dict.""" 

72 self.add_call( 

73 input_tokens=usage.get("prompt_tokens", 0), 

74 output_tokens=usage.get("completion_tokens", 0), 

75 model=model, 

76 ) 

77 # Accept pre-computed cost when litellm already calculated it 

78 if "estimated_cost_usd" in usage and not model: 

79 self.cost_usd += float(usage["estimated_cost_usd"] or 0) 

80 

81 def to_dict(self) -> dict[str, Any]: 

82 d: dict[str, Any] = { 

83 "prompt_tokens": self.prompt_tokens, 

84 "completion_tokens": self.completion_tokens, 

85 "total_tokens": self.prompt_tokens + self.completion_tokens, 

86 } 

87 if self.cost_usd: 

88 d["estimated_cost_usd"] = self.cost_usd 

89 return d