fast-agent-mcp 0.2.33__py3-none-any.whl → 0.2.35__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,6 +31,7 @@ from mcp_agent.llm.providers.multipart_converter_openai import OpenAIConverter,
31
31
  from mcp_agent.llm.providers.sampling_converter_openai import (
32
32
  OpenAISamplingConverter,
33
33
  )
34
+ from mcp_agent.llm.usage_tracking import TurnUsage
34
35
  from mcp_agent.logging.logger import get_logger
35
36
  from mcp_agent.mcp.prompt_message_multipart import PromptMessageMultipart
36
37
 
@@ -90,15 +91,14 @@ class OpenAIAugmentedLLM(AugmentedLLM[ChatCompletionMessageParam, ChatCompletion
90
91
 
91
92
  def _initialize_default_params(self, kwargs: dict) -> RequestParams:
92
93
  """Initialize OpenAI-specific default parameters"""
94
+ # Get base defaults from parent (includes ModelDatabase lookup)
95
+ base_params = super()._initialize_default_params(kwargs)
96
+
97
+ # Override with OpenAI-specific settings
93
98
  chosen_model = kwargs.get("model", DEFAULT_OPENAI_MODEL)
99
+ base_params.model = chosen_model
94
100
 
95
- return RequestParams(
96
- model=chosen_model,
97
- systemPrompt=self.instruction,
98
- parallel_tool_calls=True,
99
- max_iterations=20,
100
- use_history=True,
101
- )
101
+ return base_params
102
102
 
103
103
  def _base_url(self) -> str:
104
104
  return self.context.config.openai.base_url if self.context.config.openai else None
@@ -166,6 +166,19 @@ class OpenAIAugmentedLLM(AugmentedLLM[ChatCompletionMessageParam, ChatCompletion
166
166
 
167
167
  response = executor_result[0]
168
168
 
169
+ # Track usage if response is valid and has usage data
170
+ if (
171
+ hasattr(response, "usage")
172
+ and response.usage
173
+ and not isinstance(response, BaseException)
174
+ ):
175
+ try:
176
+ model_name = self.default_request_params.model or DEFAULT_OPENAI_MODEL
177
+ turn_usage = TurnUsage.from_openai(response.usage, model_name)
178
+ self.usage_accumulator.add_turn(turn_usage)
179
+ except Exception as e:
180
+ self.logger.warning(f"Failed to track usage: {e}")
181
+
169
182
  self.logger.debug(
170
183
  "OpenAI completion response:",
171
184
  data=response,
@@ -0,0 +1,402 @@
1
+ """
2
+ Usage tracking system for LLM providers with comprehensive cache support.
3
+
4
+ This module provides unified usage tracking across Anthropic, OpenAI, and Google providers,
5
+ including detailed cache metrics and context window management.
6
+ """
7
+
8
+ import time
9
+ from typing import List, Optional, Union
10
+
11
+ # Proper type imports for each provider
12
+ from anthropic.types import Usage as AnthropicUsage
13
+ from google.genai.types import GenerateContentResponseUsageMetadata as GoogleUsage
14
+ from openai.types.completion_usage import CompletionUsage as OpenAIUsage
15
+ from pydantic import BaseModel, Field, computed_field
16
+
17
+ from mcp_agent.llm.model_database import ModelDatabase
18
+ from mcp_agent.llm.provider_types import Provider
19
+
20
+
21
+ # Fast-agent specific usage type for synthetic providers
22
+ class FastAgentUsage(BaseModel):
23
+ """Usage data for fast-agent providers (passthrough, playback, slow)"""
24
+
25
+ input_chars: int = Field(description="Characters in input messages")
26
+ output_chars: int = Field(description="Characters in output messages")
27
+ model_type: str = Field(description="Type of fast-agent model (passthrough/playbook/slow)")
28
+ tool_calls: int = Field(default=0, description="Number of tool calls made")
29
+ delay_seconds: float = Field(default=0.0, description="Artificial delays added")
30
+
31
+
32
+ # Union type for raw usage data from any provider
33
+ ProviderUsage = Union[AnthropicUsage, OpenAIUsage, GoogleUsage, FastAgentUsage]
34
+
35
+
36
+ class ModelContextWindows:
37
+ """Context window sizes and cache configurations for various models"""
38
+
39
+ @classmethod
40
+ def get_context_window(cls, model: str) -> Optional[int]:
41
+ return ModelDatabase.get_context_window(model)
42
+
43
+
44
+ class CacheUsage(BaseModel):
45
+ """Cache-specific usage metrics"""
46
+
47
+ cache_read_tokens: int = Field(default=0, description="Tokens read from cache")
48
+ cache_write_tokens: int = Field(default=0, description="Tokens written to cache")
49
+ cache_hit_tokens: int = Field(default=0, description="Total tokens served from cache")
50
+
51
+ @computed_field
52
+ @property
53
+ def total_cache_tokens(self) -> int:
54
+ """Total cache-related tokens"""
55
+ return self.cache_read_tokens + self.cache_write_tokens + self.cache_hit_tokens
56
+
57
+ @computed_field
58
+ @property
59
+ def has_cache_activity(self) -> bool:
60
+ """Whether any cache activity occurred"""
61
+ return self.total_cache_tokens > 0
62
+
63
+
64
+ class TurnUsage(BaseModel):
65
+ """Usage data for a single turn/completion with cache support"""
66
+
67
+ provider: Provider
68
+ model: str
69
+ input_tokens: int
70
+ output_tokens: int
71
+ total_tokens: int
72
+ timestamp: float = Field(default_factory=time.time)
73
+
74
+ # Cache-specific metrics
75
+ cache_usage: CacheUsage = Field(default_factory=CacheUsage)
76
+
77
+ # Provider-specific token types
78
+ tool_use_tokens: int = Field(default=0, description="Tokens used for tool calling prompts")
79
+ reasoning_tokens: int = Field(default=0, description="Tokens used for reasoning/thinking")
80
+
81
+ # Raw usage data from provider (preserves all original data)
82
+ raw_usage: ProviderUsage
83
+
84
+ @computed_field
85
+ @property
86
+ def current_context_tokens(self) -> int:
87
+ """Current context size after this turn (total input including cache + output)"""
88
+ # For Anthropic: input_tokens + cache_read_tokens represents total input context
89
+ total_input = self.input_tokens + self.cache_usage.cache_read_tokens + self.cache_usage.cache_write_tokens
90
+ return total_input + self.output_tokens
91
+
92
+ @computed_field
93
+ @property
94
+ def effective_input_tokens(self) -> int:
95
+ """Input tokens actually processed (new tokens, not from cache)"""
96
+ # For Anthropic: input_tokens already excludes cached content
97
+ # For other providers: subtract cache hits from input_tokens
98
+ if self.provider == Provider.ANTHROPIC:
99
+ return self.input_tokens
100
+ else:
101
+ return max(0, self.input_tokens - self.cache_usage.cache_hit_tokens)
102
+
103
+ @computed_field
104
+ @property
105
+ def display_input_tokens(self) -> int:
106
+ """Input tokens to display for 'Last turn' (total submitted tokens)"""
107
+ # For Anthropic: input_tokens excludes cache, so add cache tokens
108
+ if self.provider == Provider.ANTHROPIC:
109
+ return self.input_tokens + self.cache_usage.cache_read_tokens + self.cache_usage.cache_write_tokens
110
+ else:
111
+ # For OpenAI/Google: input_tokens already includes cached tokens
112
+ return self.input_tokens
113
+
114
+ @classmethod
115
+ def from_anthropic(cls, usage: AnthropicUsage, model: str) -> "TurnUsage":
116
+ # Extract cache tokens with proper null handling
117
+ cache_creation_tokens = getattr(usage, "cache_creation_input_tokens", 0) or 0
118
+ cache_read_tokens = getattr(usage, "cache_read_input_tokens", 0) or 0
119
+
120
+ cache_usage = CacheUsage(
121
+ cache_read_tokens=cache_read_tokens, # Tokens read from cache (90% discount)
122
+ cache_write_tokens=cache_creation_tokens, # Tokens written to cache (25% surcharge)
123
+ )
124
+
125
+ return cls(
126
+ provider=Provider.ANTHROPIC,
127
+ model=model,
128
+ input_tokens=usage.input_tokens,
129
+ output_tokens=usage.output_tokens,
130
+ total_tokens=usage.input_tokens + usage.output_tokens,
131
+ cache_usage=cache_usage,
132
+ raw_usage=usage, # Store the original Anthropic usage object
133
+ )
134
+
135
+ @classmethod
136
+ def from_openai(cls, usage: OpenAIUsage, model: str) -> "TurnUsage":
137
+ # Extract cache tokens with proper null handling
138
+ cached_tokens = 0
139
+ if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details:
140
+ cached_tokens = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0
141
+
142
+ cache_usage = CacheUsage(
143
+ cache_hit_tokens=cached_tokens # These are tokens served from cache (50% discount)
144
+ )
145
+
146
+ return cls(
147
+ provider=Provider.OPENAI,
148
+ model=model,
149
+ input_tokens=usage.prompt_tokens,
150
+ output_tokens=usage.completion_tokens,
151
+ total_tokens=usage.total_tokens,
152
+ cache_usage=cache_usage,
153
+ raw_usage=usage, # Store the original OpenAI usage object
154
+ )
155
+
156
+ @classmethod
157
+ def from_google(cls, usage: GoogleUsage, model: str) -> "TurnUsage":
158
+ # Extract token counts with proper null handling
159
+ prompt_tokens = getattr(usage, "prompt_token_count", 0) or 0
160
+ candidates_tokens = getattr(usage, "candidates_token_count", 0) or 0
161
+ total_tokens = getattr(usage, "total_token_count", 0) or 0
162
+ cached_content_tokens = getattr(usage, "cached_content_token_count", 0) or 0
163
+
164
+ # Extract additional Google-specific token types
165
+ tool_use_tokens = getattr(usage, "tool_use_prompt_token_count", 0) or 0
166
+ thinking_tokens = getattr(usage, "thoughts_token_count", 0) or 0
167
+
168
+ # Google cache tokens are read hits (75% discount on Gemini 2.5)
169
+ cache_usage = CacheUsage(cache_hit_tokens=cached_content_tokens)
170
+
171
+ return cls(
172
+ provider=Provider.GOOGLE,
173
+ model=model,
174
+ input_tokens=prompt_tokens,
175
+ output_tokens=candidates_tokens,
176
+ total_tokens=total_tokens,
177
+ cache_usage=cache_usage,
178
+ tool_use_tokens=tool_use_tokens,
179
+ reasoning_tokens=thinking_tokens,
180
+ raw_usage=usage, # Store the original Google usage object
181
+ )
182
+
183
+ @classmethod
184
+ def from_fast_agent(cls, usage: FastAgentUsage, model: str) -> "TurnUsage":
185
+ # For fast-agent providers, we use characters as "tokens"
186
+ # This provides a consistent unit of measurement across all providers
187
+ input_tokens = usage.input_chars
188
+ output_tokens = usage.output_chars
189
+ total_tokens = input_tokens + output_tokens
190
+
191
+ # Fast-agent providers don't have cache functionality
192
+ cache_usage = CacheUsage()
193
+
194
+ return cls(
195
+ provider=Provider.FAST_AGENT,
196
+ model=model,
197
+ input_tokens=input_tokens,
198
+ output_tokens=output_tokens,
199
+ total_tokens=total_tokens,
200
+ cache_usage=cache_usage,
201
+ raw_usage=usage, # Store the original FastAgentUsage object
202
+ )
203
+
204
+
205
+ class UsageAccumulator(BaseModel):
206
+ """Accumulates usage data across multiple turns with cache analytics"""
207
+
208
+ turns: List[TurnUsage] = Field(default_factory=list)
209
+ model: Optional[str] = None
210
+
211
+ def add_turn(self, turn: TurnUsage) -> None:
212
+ """Add a new turn to the accumulator"""
213
+ self.turns.append(turn)
214
+ if self.model is None:
215
+ self.model = turn.model
216
+
217
+ @computed_field
218
+ @property
219
+ def cumulative_input_tokens(self) -> int:
220
+ """Total input tokens charged across all turns (including cache tokens)"""
221
+ return sum(
222
+ turn.input_tokens + turn.cache_usage.cache_read_tokens + turn.cache_usage.cache_write_tokens
223
+ for turn in self.turns
224
+ )
225
+
226
+ @computed_field
227
+ @property
228
+ def cumulative_output_tokens(self) -> int:
229
+ """Total output tokens charged across all turns"""
230
+ return sum(turn.output_tokens for turn in self.turns)
231
+
232
+ @computed_field
233
+ @property
234
+ def cumulative_billing_tokens(self) -> int:
235
+ """Total tokens charged across all turns (including cache tokens)"""
236
+ return self.cumulative_input_tokens + self.cumulative_output_tokens
237
+
238
+ @computed_field
239
+ @property
240
+ def cumulative_cache_read_tokens(self) -> int:
241
+ """Total tokens read from cache across all turns"""
242
+ return sum(turn.cache_usage.cache_read_tokens for turn in self.turns)
243
+
244
+ @computed_field
245
+ @property
246
+ def cumulative_cache_write_tokens(self) -> int:
247
+ """Total tokens written to cache across all turns"""
248
+ return sum(turn.cache_usage.cache_write_tokens for turn in self.turns)
249
+
250
+ @computed_field
251
+ @property
252
+ def cumulative_cache_hit_tokens(self) -> int:
253
+ """Total tokens served from cache across all turns"""
254
+ return sum(turn.cache_usage.cache_hit_tokens for turn in self.turns)
255
+
256
+ @computed_field
257
+ @property
258
+ def cumulative_effective_input_tokens(self) -> int:
259
+ """Total input tokens excluding cache reads across all turns"""
260
+ return sum(turn.effective_input_tokens for turn in self.turns)
261
+
262
+ @computed_field
263
+ @property
264
+ def cumulative_tool_use_tokens(self) -> int:
265
+ """Total tokens used for tool calling prompts across all turns"""
266
+ return sum(turn.tool_use_tokens for turn in self.turns)
267
+
268
+ @computed_field
269
+ @property
270
+ def cumulative_reasoning_tokens(self) -> int:
271
+ """Total tokens used for reasoning/thinking across all turns"""
272
+ return sum(turn.reasoning_tokens for turn in self.turns)
273
+
274
+ @computed_field
275
+ @property
276
+ def cache_hit_rate(self) -> Optional[float]:
277
+ """Percentage of total input context served from cache"""
278
+ cache_tokens = self.cumulative_cache_read_tokens + self.cumulative_cache_hit_tokens
279
+ total_input_context = self.cumulative_input_tokens + cache_tokens
280
+ if total_input_context == 0:
281
+ return None
282
+ return (cache_tokens / total_input_context) * 100
283
+
284
+ @computed_field
285
+ @property
286
+ def current_context_tokens(self) -> int:
287
+ """Current context usage (last turn's context tokens)"""
288
+ if not self.turns:
289
+ return 0
290
+ return self.turns[-1].current_context_tokens
291
+
292
+ @computed_field
293
+ @property
294
+ def context_window_size(self) -> Optional[int]:
295
+ """Get context window size for current model"""
296
+ if self.model:
297
+ return ModelContextWindows.get_context_window(self.model)
298
+ return None
299
+
300
+ @computed_field
301
+ @property
302
+ def context_usage_percentage(self) -> Optional[float]:
303
+ """Percentage of context window used"""
304
+ window_size = self.context_window_size
305
+ if window_size and window_size > 0:
306
+ return (self.current_context_tokens / window_size) * 100
307
+ return None
308
+
309
+ @computed_field
310
+ @property
311
+ def turn_count(self) -> int:
312
+ """Number of turns accumulated"""
313
+ return len(self.turns)
314
+
315
+ def get_cache_summary(self) -> dict[str, Union[int, float, None]]:
316
+ """Get cache-specific metrics summary"""
317
+ return {
318
+ "cumulative_cache_read_tokens": self.cumulative_cache_read_tokens,
319
+ "cumulative_cache_write_tokens": self.cumulative_cache_write_tokens,
320
+ "cumulative_cache_hit_tokens": self.cumulative_cache_hit_tokens,
321
+ "cache_hit_rate_percent": self.cache_hit_rate,
322
+ "cumulative_effective_input_tokens": self.cumulative_effective_input_tokens,
323
+ }
324
+
325
+ def get_summary(self) -> dict[str, Union[int, float, str, None]]:
326
+ """Get comprehensive usage statistics"""
327
+ cache_summary = self.get_cache_summary()
328
+ return {
329
+ "model": self.model,
330
+ "turn_count": self.turn_count,
331
+ "cumulative_input_tokens": self.cumulative_input_tokens,
332
+ "cumulative_output_tokens": self.cumulative_output_tokens,
333
+ "cumulative_billing_tokens": self.cumulative_billing_tokens,
334
+ "cumulative_tool_use_tokens": self.cumulative_tool_use_tokens,
335
+ "cumulative_reasoning_tokens": self.cumulative_reasoning_tokens,
336
+ "current_context_tokens": self.current_context_tokens,
337
+ "context_window_size": self.context_window_size,
338
+ "context_usage_percentage": self.context_usage_percentage,
339
+ **cache_summary,
340
+ }
341
+
342
+
343
+ # Utility functions for fast-agent integration
344
+ def create_fast_agent_usage(
345
+ input_content: str,
346
+ output_content: str,
347
+ model_type: str,
348
+ tool_calls: int = 0,
349
+ delay_seconds: float = 0.0,
350
+ ) -> FastAgentUsage:
351
+ """
352
+ Create FastAgentUsage from message content.
353
+
354
+ Args:
355
+ input_content: Input message content
356
+ output_content: Output message content
357
+ model_type: Type of fast-agent model (passthrough/playback/slow)
358
+ tool_calls: Number of tool calls made
359
+ delay_seconds: Artificial delays added
360
+
361
+ Returns:
362
+ FastAgentUsage object with character counts
363
+ """
364
+ return FastAgentUsage(
365
+ input_chars=len(input_content),
366
+ output_chars=len(output_content),
367
+ model_type=model_type,
368
+ tool_calls=tool_calls,
369
+ delay_seconds=delay_seconds,
370
+ )
371
+
372
+
373
+ def create_turn_usage_from_messages(
374
+ input_content: str,
375
+ output_content: str,
376
+ model: str,
377
+ model_type: str,
378
+ tool_calls: int = 0,
379
+ delay_seconds: float = 0.0,
380
+ ) -> TurnUsage:
381
+ """
382
+ Create TurnUsage directly from message content for fast-agent providers.
383
+
384
+ Args:
385
+ input_content: Input message content
386
+ output_content: Output message content
387
+ model: Model name (e.g., "passthrough", "playback", "slow")
388
+ model_type: Type for internal tracking
389
+ tool_calls: Number of tool calls made
390
+ delay_seconds: Artificial delays added
391
+
392
+ Returns:
393
+ TurnUsage object ready for accumulation
394
+ """
395
+ usage = create_fast_agent_usage(
396
+ input_content=input_content,
397
+ output_content=output_content,
398
+ model_type=model_type,
399
+ tool_calls=tool_calls,
400
+ delay_seconds=delay_seconds,
401
+ )
402
+ return TurnUsage.from_fast_agent(usage, model)
@@ -117,3 +117,27 @@ class SamplingFilter(EventFilter):
117
117
  if not super().matches(event):
118
118
  return False
119
119
  return random.random() < self.sample_rate
120
+
121
+
122
+ class StreamingExclusionFilter(EventFilter):
123
+ """
124
+ Event filter that excludes streaming progress events from logs.
125
+ This prevents token count updates from flooding the logs when info level is enabled.
126
+ """
127
+
128
+ def matches(self, event: Event) -> bool:
129
+ # First check if it passes the base filter
130
+ if not super().matches(event):
131
+ return False
132
+
133
+ # Exclude events with "Streaming progress" message
134
+ if event.message == "Streaming progress":
135
+ return False
136
+
137
+ # Also check for events with progress_action = STREAMING in data
138
+ if event.data and isinstance(event.data.get("data"), dict):
139
+ event_data = event.data["data"]
140
+ if event_data.get("progress_action") == "Streaming":
141
+ return False
142
+
143
+ return True
@@ -73,6 +73,7 @@ class RichProgressDisplay:
73
73
  ProgressAction.LOADED: "dim green",
74
74
  ProgressAction.INITIALIZED: "dim green",
75
75
  ProgressAction.CHATTING: "bold blue",
76
+ ProgressAction.STREAMING: "bold blue", # Same color as chatting
76
77
  ProgressAction.ROUTING: "bold blue",
77
78
  ProgressAction.PLANNING: "bold blue",
78
79
  ProgressAction.READY: "dim green",
@@ -100,9 +101,16 @@ class RichProgressDisplay:
100
101
  task_id = self._taskmap[task_name]
101
102
 
102
103
  # Ensure no None values in the update
104
+ # For streaming, use custom description immediately to avoid flashing
105
+ if event.action == ProgressAction.STREAMING and event.streaming_tokens:
106
+ formatted_tokens = f"↓ {event.streaming_tokens.strip()}".ljust(15)
107
+ description = f"[{self._get_action_style(event.action)}]{formatted_tokens}"
108
+ else:
109
+ description = f"[{self._get_action_style(event.action)}]{event.action.value:<15}"
110
+
103
111
  self._progress.update(
104
112
  task_id,
105
- description=f"[{self._get_action_style(event.action)}]{event.action.value:<15}",
113
+ description=description,
106
114
  target=event.target or task_name, # Use task_name as fallback for target
107
115
  details=event.details or "",
108
116
  task_name=task_name,
@@ -5,6 +5,7 @@ This module defines protocols (interfaces) that can be used to break circular de
5
5
 
6
6
  from datetime import timedelta
7
7
  from typing import (
8
+ TYPE_CHECKING,
8
9
  Any,
9
10
  AsyncContextManager,
10
11
  Callable,
@@ -31,6 +32,9 @@ from mcp_agent.core.agent_types import AgentType
31
32
  from mcp_agent.core.request_params import RequestParams
32
33
  from mcp_agent.mcp.prompt_message_multipart import PromptMessageMultipart
33
34
 
35
+ if TYPE_CHECKING:
36
+ from mcp_agent.llm.usage_tracking import UsageAccumulator
37
+
34
38
 
35
39
  @runtime_checkable
36
40
  class MCPConnectionManagerProtocol(Protocol):
@@ -132,6 +136,8 @@ class AugmentedLLMProtocol(Protocol):
132
136
  """
133
137
  ...
134
138
 
139
+ usage_accumulator: "UsageAccumulator"
140
+
135
141
 
136
142
  class AgentProtocol(AugmentedLLMProtocol, Protocol):
137
143
  """Protocol defining the standard agent interface"""