Repository navigation
feat(completions): ensure prompt tokens are always calculated #588
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
steebchen
merged 6 commits into
main
from
cursor/ensure-prompt-tokens-are-always-calculated-d64b
Aug 8, 2025
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f730412
Ensure prompt tokens are never zero, add fallback token calculation
cursoragent 3558f62
fix: ensure prompt tokens are never zero and manually calculated when…
cursoragent 2d58105
chore: gen
steebchen d1a1fe7
fix(api): replace mock token with real token in e2e tests
steebchen 44670c5
fix(models): remove test skip flags for Zai providers
steebchen 14becd8
Merge branch 'main' into cursor/ensure-prompt-tokens-are-always-calcu…
steebchen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { describe, it, expect } from "vitest"; | ||
|
|
||
| describe("Prompt token calculation", () => { | ||
| it("should calculate prompt tokens when provider returns 0", () => { | ||
| // Mock message | ||
| const messages = [ | ||
| { | ||
| role: "user", | ||
| content: "This is a test message to calculate tokens", | ||
| name: undefined, | ||
| }, | ||
| ]; | ||
|
|
||
| // Simulate calculation logic (similar to what we implemented) | ||
| const calculatePromptTokens = ( | ||
| promptTokenCount: number, | ||
| messages: any[], | ||
| ): number => { | ||
| if (promptTokenCount > 0) { | ||
| return promptTokenCount; | ||
| } | ||
|
|
||
| // Calculate prompt tokens if missing or 0 | ||
| try { | ||
| // Simple estimation fallback (as in our implementation) | ||
| const totalChars = messages.reduce( | ||
| (acc, m) => acc + (m.content?.length || 0), | ||
| 0, | ||
| ); | ||
| return Math.max(1, Math.round(totalChars / 4)); | ||
| } catch (error) { | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| return 1; // Minimum fallback | ||
| } | ||
| }; | ||
|
|
||
| // Test that 0 prompt tokens are calculated | ||
| const result = calculatePromptTokens(0, messages); | ||
| expect(result).toBeGreaterThan(0); | ||
| expect(typeof result).toBe("number"); | ||
|
|
||
| // Test that existing prompt tokens are preserved | ||
| const result2 = calculatePromptTokens(50, messages); | ||
| expect(result2).toBe(50); | ||
| }); | ||
|
|
||
| it("should always return at least 1 token", () => { | ||
| const calculateMinTokens = (promptTokens: number | null): number => { | ||
| return Math.max(1, promptTokens || 1); | ||
| }; | ||
|
|
||
| expect(calculateMinTokens(0)).toBe(1); | ||
| expect(calculateMinTokens(null)).toBe(1); | ||
| expect(calculateMinTokens(undefined as any)).toBe(1); | ||
| expect(calculateMinTokens(10)).toBe(10); | ||
| }); | ||
|
|
||
| it("should handle empty messages gracefully", () => { | ||
| const calculatePromptTokens = ( | ||
| promptTokenCount: number, | ||
| messages: any[], | ||
| ): number => { | ||
| if (promptTokenCount > 0) { | ||
| return promptTokenCount; | ||
| } | ||
|
|
||
| const totalChars = messages.reduce( | ||
| (acc, m) => acc + (m.content?.length || 0), | ||
| 0, | ||
| ); | ||
| return Math.max(1, Math.round(totalChars / 4)); | ||
| }; | ||
|
|
||
| const result = calculatePromptTokens(0, []); | ||
| expect(result).toBe(1); // Should return minimum of 1 | ||
|
|
||
| const result2 = calculatePromptTokens(0, [{ role: "user", content: "" }]); | ||
| expect(result2).toBe(1); // Should return minimum of 1 for empty content | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Refactor repeated token normalization logic
The same token normalization pattern is repeated across multiple providers. Consider extracting this into a helper function to follow DRY principles.
Create a helper function:
Then use it in all provider cases:
usage: { - prompt_tokens: Math.max(1, promptTokens || 1), - completion_tokens: completionTokens || 0, - total_tokens: Math.max(1, totalTokens || Math.max(1, promptTokens || 1)), + ...normalizeTokenUsage(promptTokens, completionTokens, totalTokens), // ... other fields },🤖 Prompt for AI Agents