(
content: bytes,
model: str,
pricing: dict[str, ModelPricing],
)
| 202 | |
| 203 | |
| 204 | def parse_usage_metrics( |
| 205 | content: bytes, |
| 206 | model: str, |
| 207 | pricing: dict[str, ModelPricing], |
| 208 | ) -> UsageMetrics | None: |
| 209 | try: |
| 210 | data = json.loads(content) |
| 211 | except (json.JSONDecodeError, TypeError): |
| 212 | return None |
| 213 | |
| 214 | usage = data.get("usage") or {} |
| 215 | if not isinstance(usage, dict): |
| 216 | return None |
| 217 | |
| 218 | prompt_details = usage.get("prompt_tokens_details") or usage.get("input_tokens_details") or {} |
| 219 | output_details = usage.get("completion_tokens_details") or usage.get("output_tokens_details") or {} |
| 220 | |
| 221 | raw_prompt_tokens = _as_int(usage.get("prompt_tokens", usage.get("input_tokens", 0))) |
| 222 | output_tokens = _as_int(usage.get("completion_tokens", usage.get("output_tokens", 0))) |
| 223 | total_tokens = _as_int(usage.get("total_tokens", 0)) |
| 224 | |
| 225 | prompt_cache_hit = _as_int( |
| 226 | usage.get("prompt_cache_hit_tokens", prompt_details.get("prompt_cache_hit_tokens", 0)), |
| 227 | ) |
| 228 | prompt_cache_miss = _as_int( |
| 229 | usage.get("prompt_cache_miss_tokens", prompt_details.get("prompt_cache_miss_tokens", 0)), |
| 230 | ) |
| 231 | cache_read_input_tokens = _first_positive_int( |
| 232 | usage.get("cache_read_input_tokens"), |
| 233 | prompt_details.get("cache_read_input_tokens"), |
| 234 | usage.get("cached_tokens"), |
| 235 | prompt_details.get("cached_tokens"), |
| 236 | prompt_cache_hit, |
| 237 | ) |
| 238 | cache_write_input_tokens = _first_positive_int( |
| 239 | usage.get("cache_creation_input_tokens"), |
| 240 | prompt_details.get("cache_creation_input_tokens"), |
| 241 | usage.get("cache_write_tokens"), |
| 242 | prompt_details.get("cache_write_tokens"), |
| 243 | ) |
| 244 | |
| 245 | if prompt_cache_hit or prompt_cache_miss: |
| 246 | input_tokens_uncached = prompt_cache_miss |
| 247 | input_tokens_total = prompt_cache_hit + prompt_cache_miss |
| 248 | elif "input_tokens" in usage and "prompt_tokens" not in usage: |
| 249 | input_tokens_uncached = raw_prompt_tokens |
| 250 | input_tokens_total = raw_prompt_tokens + cache_read_input_tokens + cache_write_input_tokens |
| 251 | else: |
| 252 | input_tokens_total = max(raw_prompt_tokens, raw_prompt_tokens + cache_write_input_tokens) |
| 253 | input_tokens_uncached = max(raw_prompt_tokens - cache_read_input_tokens, 0) |
| 254 | |
| 255 | if total_tokens <= 0: |
| 256 | total_tokens = input_tokens_total + output_tokens |
| 257 | |
| 258 | if ( |
| 259 | input_tokens_total <= 0 |
| 260 | and input_tokens_uncached <= 0 |
| 261 | and output_tokens <= 0 |
no test coverage detected