Skip to content

fix: emit claude message_delta for usage-only final stream chunk - #4090

Merged
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
seefs001:fix/claude2openai-usage
Apr 4, 2026
Merged

Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
seefs001:fix/claude2openai-usage

Conversation

@seefs001

@seefs001 seefs001 commented Apr 4, 2026 •

Copy link
Copy Markdown
Collaborator

⚠️ 提交警告 / PR Warning

请注意: 请提供人工撰写的简洁摘要。包含大量 AI 灌水内容、逻辑混乱或无视模版的 PR 可能会被无视或直接关闭。


💡 沟通提示 / Pre-submission

重大功能变更? 请先提交 Issue 交流,避免无效劳动。

📝 变更描述 / Description

修复 Claude Messages -> OpenAI Compatible 情况下,message_delta的chunk块在部分情况下会丢失的问题。
仅返回给客户端的响应usage问题,后台日志计费仍正常。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature) - 重大特性建议先 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自撰写此描述,去除了 AI 原始输出的冗余。
  • 深度理解: 我已完全理解这些更改的工作原理及潜在影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过了测试或手动验证。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

image

Summary by CodeRabbit

  • Bug Fixes

    • Improved cache creation token accounting: when split allocation isn't specified, tokens now default to the 5-minute period for consistent measurement
    • Enhanced streaming response handling with robust fallback logic to preserve usage data when not immediately available
  • Tests

    • Added test coverage for cache token normalization and streaming response scenarios

@coderabbitai

coderabbitai Bot commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

Pull request was closed or merged during review

Walkthrough

This PR introduces cache-creation token normalization across the Claude relay layer and service conversion code. A new utility function NormalizeCacheCreationSplit is added to reallocate missing cache-creation tokens to the 5m bucket, and both the relay message-delta patching and OpenAI→Claude usage conversion are refactored to use this normalization instead of raw values.

Changes

Cohort / File(s) Summary
Cache Creation Split Normalization
service/convert.go
Added NormalizeCacheCreationSplit() utility function to normalize 5m/1h cache-creation token splits by reallocating missing portions to the 5m bucket. Integrated into buildClaudeUsageFromOpenAIUsage() and enhanced StreamResponseOpenAI2Claude() to handle SSE chunks with zero choices and defer final stop/usage emission when usage data is missing.
Claude Relay Cache Handling
relay/channel/claude/relay-claude.go
Refactored buildOpenAIStyleUsageFromClaudeUsage() and buildMessageDeltaPatchUsage() to normalize cache-creation token splits via the new utility function instead of using raw values. Cache creation is now derived from either usage.CacheCreation or claudeInfo.Usage, then normalized and conditionally initialized.
Test Coverage
relay/channel/claude/relay_claude_test.go, relay/channel/claude/message_delta_usage_patch_test.go
Added new unit test for default aggregation of cache-creation tokens to 5m bucket. Updated existing test assertions to reflect normalized cache-creation token values (Ephemeral5mInputTokens: 10→30).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 A rabbit hops through token streams so bright,
Normalizing caches left and right,
Five-minute buckets fill with care,
Missing fragments now split fair! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the main change: fixing the emission of Claude message_delta chunks for usage-only final stream chunks in the Messages-to-OpenAI Compatible API conversion.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@seefs001 seefs001 closed this Apr 4, 2026
@seefs001 seefs001 reopened this Apr 4, 2026
@Calcium-Ion
Calcium-Ion merged commit 873067f into QuantumNous:main Apr 4, 2026
Jinxuans referenced this pull request in TokFlux-Org/TokFlux May 9, 2026
fix: emit claude message_delta for usage-only final stream chunk
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
…sage

fix: emit claude message_delta for usage-only final stream chunk
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
…sage

fix: emit claude message_delta for usage-only final stream chunk
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.

2 participants