Token count discrepancy between tiktoken and API response when messages contain tool calls
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 19.3k
- Forks
- 1.6k
- PR merge metrics
- No merged PRs in 30d
Description
Description
I've encountered a significant discrepancy between token counts calculated by tiktoken locally and the actual token usage returned by the OpenAI API, specifically when messages contain tool calls.
Environment
- tiktoken version: 3.11
- Python version: 0.7.0
- Model: gpt-4.1-mini
Steps to Reproduce
- Prepare a message payload that includes tool calls (function calling)
- Calculate token count using tiktoken locally
- Send the same payload to OpenAI API
- Compare tiktoken's result with the
usagefield in API response
Expected Behavior
The token count calculated by tiktoken should be close to (or exactly match) the token usage reported by the API.
Actual Behavior
There is a large discrepancy between tiktoken's calculation and the API's reported token usage when tool calls are present in the message body.
tiktoken calculation
encoding = tiktoken.encoding_for_model("gpt-4")
Result
tiktoken_count = 47,194
API response shows: api_count = 140,384
Difference: -93,190
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No repository file or test is identified in the report. Start by reproducing the tool-call case using the payload described, compare tiktoken.encoding_for_model("gpt-4") with the API response's usage field, and determine the source of the discrepancy. Done means the reported mismatch is explained and the relevant counting behavior is corrected or documented with a reproducible test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Needs clarification
- Newbie friendliness
- 42/100