Skip to content

fix: gemini原生格式请求,非流情况下,不计算reasoning_tokens - #1254

Merged
creamlike1024 merged 1 commit into
QuantumNous:mainfrom
xqx121:main
Jun 19, 2025
Merged

fix: gemini原生格式请求,非流情况下,不计算reasoning_tokens#1254
creamlike1024 merged 1 commit into
QuantumNous:mainfrom
xqx121:main

Conversation

@xqx121

@xqx121 xqx121 commented Jun 18, 2025

Copy link
Copy Markdown
Contributor

fix: #1249

Summary by CodeRabbit

  • Bug Fixes
    • Improved accuracy of token usage reporting for Gemini text generation responses.

@coderabbitai

coderabbitai Bot commented Jun 18, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The code modifies the GeminiTextGenerationHandler function to update how CompletionTokens is calculated in the usage struct. Instead of assigning CandidatesTokenCount, it now computes CompletionTokens as the difference between TotalTokens and PromptTokens. No other logic or control flow is changed.

Changes

File(s) Change Summary
relay/channel/gemini/relay-gemini-native.go Modified calculation of CompletionTokens in usage struct to be TotalTokens - PromptTokens.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GeminiTextGenerationHandler
    participant UsageStruct

    Client->>GeminiTextGenerationHandler: Send text generation request
    GeminiTextGenerationHandler->>UsageStruct: Calculate TotalTokens, PromptTokens
    GeminiTextGenerationHandler->>UsageStruct: Set CompletionTokens = TotalTokens - PromptTokens
    GeminiTextGenerationHandler-->>Client: Return response with updated usage
Loading

Assessment against linked issues

Objective Addressed Explanation
Do not calculate reasoning_tokens for Gemini native format non-stream requests (#1249)

Assessment against linked issues: Out-of-scope changes

(No out-of-scope changes found.)

Poem

A hop, a skip, a token or two,
Now CompletionTokens are counted anew!
Subtract the prompt, let logic shine bright,
Gemini’s numbers are now just right.
With every request, the tally is clear—
The code hops forward, the bugs disappear!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
relay/channel/gemini/relay-gemini-native.go (1)

52-56: Redundant initialisation of CompletionTokens

CompletionTokens is assigned here with CandidatesTokenCount but is overwritten 15-20 lines later (line 69).
Keeping two conflicting assignments complicates reasoning and risks future regressions if the later block is moved or removed.

-	usage := dto.Usage{
-		PromptTokens:     geminiResponse.UsageMetadata.PromptTokenCount,
-		CompletionTokens: geminiResponse.UsageMetadata.CandidatesTokenCount,
-		TotalTokens:      geminiResponse.UsageMetadata.TotalTokenCount,
-	}
+	usage := dto.Usage{
+		PromptTokens: geminiResponse.UsageMetadata.PromptTokenCount,
+		TotalTokens:  geminiResponse.UsageMetadata.TotalTokenCount,
+	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b9b21e and edcdb37.

📒 Files selected for processing (1)
  • relay/channel/gemini/relay-gemini-native.go (1 hunks)
🔇 Additional comments (1)
relay/channel/gemini/relay-gemini-native.go (1)

58-66: ReasoningTokens still populated – verify business rule

The PR description says “非流情况下,不计算 reasoning_tokens” (do not count reasoning tokens for non-stream requests).
Even if the tokens are no longer added to CompletionTokens, you still expose them via CompletionTokenDetails.ReasoningTokens, which may be interpreted upstream as “countable”.

Confirm whether this field must be zeroed / omitted for non-stream responses; otherwise the objective is only half-met.

Comment on lines +67 to 70

// 计算最终使用量
usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Image token logic is clobbered in stream path

A similar Total-Prompt reassignment exists in the stream handler (lines 141-143).
When imageCount != 0, you set usage.CompletionTokens = imageCount * 258 (line 137) and then overwrite it with the diff, nullifying the special-case logic.

Guard the second assignment, e.g.:

-	usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
+	// Only overwrite when we have a normal text response
+	if imageCount == 0 {
+		usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
+	}

Apply the same guard (or remove the earlier assignment) in the non-stream block to keep semantics consistent.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 计算最终使用量
usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
// 计算最终使用量
// Only overwrite when we have a normal text response
if imageCount == 0 {
usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
}
🤖 Prompt for AI Agents
In relay/channel/gemini/relay-gemini-native.go around lines 67 to 70, the
assignment of usage.CompletionTokens as usage.TotalTokens minus
usage.PromptTokens overwrites the special-case logic for image tokens set
earlier in the stream handler (lines 137 and 141-143). To fix this, add a guard
condition around the second assignment so it only runs when imageCount is zero,
preserving the image token calculation. Also, apply the same guard or remove the
earlier assignment in the non-stream block to maintain consistent semantics.

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.

gemini原生格式请求,非流情况下,不计算reasoning_tokens

2 participants