From 900d10546c13ccaaee67a8aeee620183ca220147 Mon Sep 17 00:00:00 2001 From: AoHanBei Date: Wed, 16 Sep 2026 22:08:33 +0800 Subject: [PATCH] fix(usage): prefer exact model pricing matches --- deeptutor/logging/stats/llm_stats.py | 15 ++++++++++---- tests/logging/test_llm_stats.py | 30 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 tests/logging/test_llm_stats.py diff --git a/deeptutor/logging/stats/llm_stats.py b/deeptutor/logging/stats/llm_stats.py index 242e6551b..3debc1170 100644 --- a/deeptutor/logging/stats/llm_stats.py +++ b/deeptutor/logging/stats/llm_stats.py @@ -41,11 +41,18 @@ MODEL_PRICING = { def get_pricing(model: str) -> dict[str, float]: - """Get pricing for a model (fuzzy match).""" + """Get pricing for a model, preferring the most specific match.""" model_lower = model.lower() - for key, pricing in MODEL_PRICING.items(): - if key in model_lower or model_lower in key: - return pricing + + exact_match = MODEL_PRICING.get(model_lower) + if exact_match is not None: + return exact_match + + fuzzy_matches = ((key, pricing) for key, pricing in MODEL_PRICING.items() if key in model_lower) + most_specific = max(fuzzy_matches, key=lambda item: len(item[0]), default=None) + if most_specific is not None: + return most_specific[1] + return MODEL_PRICING.get("gpt-4o-mini", {"input": 0.00015, "output": 0.0006}) diff --git a/tests/logging/test_llm_stats.py b/tests/logging/test_llm_stats.py new file mode 100644 index 000000000..351c60388 --- /dev/null +++ b/tests/logging/test_llm_stats.py @@ -0,0 +1,30 @@ +import pytest + +from deeptutor.logging.stats.llm_stats import MODEL_PRICING, get_pricing +from deeptutor.runtime.agentic.usage import UsageTracker + + +@pytest.mark.parametrize( + ("model", "pricing_key"), + [ + ("gpt-4o-mini", "gpt-4o-mini"), + ("gpt-4", "gpt-4"), + ("openai/gpt-4o-mini", "gpt-4o-mini"), + ("gpt-4o-mini-2024-07-18", "gpt-4o-mini"), + ], +) +def test_get_pricing_prefers_the_most_specific_model(model: str, pricing_key: str) -> None: + assert get_pricing(model) == MODEL_PRICING[pricing_key] + + +def test_get_pricing_falls_back_for_an_unknown_model() -> None: + assert get_pricing("unknown-model") == MODEL_PRICING["gpt-4o-mini"] + + +def test_usage_tracker_uses_gpt_4o_mini_pricing() -> None: + tracker = UsageTracker(model="gpt-4o-mini") + tracker.add_from_response( + {"prompt_tokens": 1000, "completion_tokens": 1000, "total_tokens": 2000} + ) + + assert tracker.summary()["total_cost_usd"] == pytest.approx(0.00075)