Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions tests/test_costs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
3 changes: 3 additions & 0 deletions tokencost/costs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down