From d11a1affdaa6f162a2671b2e336c852c8400b100 Mon Sep 17 00:00:00 2001 From: Sean McRae <49539762+seanmcrae@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:15:19 +0530 Subject: [PATCH 1/2] Reject negative token counts when calculating costs --- tokencost/costs.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tokencost/costs.py b/tokencost/costs.py index cc4680ff..7e276372 100644 --- a/tokencost/costs.py +++ b/tokencost/costs.py @@ -317,6 +317,9 @@ def calculate_cost_by_tokens(num_tokens: int, model: str, token_type: TokenType) Returns: Decimal: The calculated cost in USD. """ + if num_tokens < 0: + raise ValueError("num_tokens must be non-negative") + model = _normalize_model_for_pricing(model) if model not in TOKEN_COSTS: raise KeyError( From 1df7ebeab6dfc03054cbf72707c7824456baf2f0 Mon Sep 17 00:00:00 2001 From: Sean McRae <49539762+seanmcrae@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:15:33 +0530 Subject: [PATCH 2/2] Add negative-token cost regression test --- tests/test_costs.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/test_costs.py b/tests/test_costs.py index 96f5b86c..724214d0 100644 --- a/tests/test_costs.py +++ b/tests/test_costs.py @@ -271,3 +271,8 @@ def test_calculate_cached_tokens_cost(): # Assert that the costs match assert actual_cost == expected_cost assert actual_cost > 0, "Cache token cost should be greater than zero" + + +def test_calculate_cost_by_tokens_rejects_negative_token_counts(): + with pytest.raises(ValueError, match="num_tokens must be non-negative"): + calculate_cost_by_tokens(-1, "gpt-4o", "input")