Skip to content

Reject negative token counts when calculating costs - #239

Open
seanmcrae wants to merge 2 commits into
AgentOps-AI:mainfrom
seanmcrae:main
Open

seanmcrae wants to merge 2 commits into
AgentOps-AI:mainfrom
seanmcrae:main

Conversation

@seanmcrae

Copy link
Copy Markdown

Summary

Reject negative token counts in calculate_cost_by_tokens instead of silently returning a negative USD cost. Token counts represent usage quantities and cannot be negative; accepting them can invert a spend estimate and corrupt accounting.

Changes

  • Raise ValueError with a clear message when num_tokens < 0.
  • Add a regression test that asserts the invalid input is rejected.

Validation

  • Regression test fails on base e7f7c1928084af55bb4955102327982401ed8649 because the function returns a negative cost instead of raising.
  • PYTHONPATH=. .venv/bin/pytest -q tests/test_costs.py -k 'not claude': 94 passed, 2 deselected. The excluded pre-existing Claude cases invoke Anthropic's remote token-count API and require credentials.
  • python -m compileall and git diff --check pass.
  • flake8 tokencost/ tests/test_costs.py reports 8 existing findings, all reproduced against unchanged base files; the patch adds no lint finding. A full lint pass is not claimed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant