Skip to content

feat: Grok 适配完善 — 防御性 usage 合并 + thinking 自动检测#1234

Merged
claude-code-best merged 2 commits into
claude-code-best:mainfrom
Evsdrg:feat/grok-full-adapt
May 16, 2026
Merged

feat: Grok 适配完善 — 防御性 usage 合并 + thinking 自动检测#1234
claude-code-best merged 2 commits into
claude-code-best:mainfrom
Evsdrg:feat/grok-full-adapt

Conversation

@Evsdrg
Copy link
Copy Markdown
Contributor

@Evsdrg Evsdrg commented May 16, 2026

Summary

完善 Grok (xAI) API 适配,消除与 OpenAI 路径之间不必要的代码重复和漏洞。

1. 提取共享的 updateOpenAIUsageopenaiShared.ts

  • 新建 src/services/api/openai/openaiShared.ts 模块
  • OpenAI 和 Grok 两条路径现在使用同一个防御性 usage 合并函数
  • 消除了 Grok 路径中 message_startmessage_delta 处理器的裸 spread 漏洞

2. Grok thinking mode 自动检测

  • isOpenAIThinkingEnabled() 现在自动检测模型名包含 "grok" 的模型
  • Grok 的 reasoning_content 字段与 DeepSeek/MiMo 共享相同的协议
  • 已有 openaiStreamAdapteropenaiConvertMessages 无需修改

3. 无需修改的部分

  • openaiStreamAdapter.ts — 已正确处理 reasoning_content → thinking block 映射
  • openaiConvertMessages.ts — 已正确保留 reasoning_content 用于多轮回传
  • cost_in_usd_ticks — Grok 独有的精确计费字段,预留后续处理

Context7 API 文档验证

根据 xAI 官方 API 文档确认:

  • Grok 的 usage 对象格式与 OpenAI 完全一致(prompt_tokens, completion_tokens, prompt_tokens_details.cached_tokens
  • Grok 的 reasoning_content 字段与 DeepSeek 使用相同的协议
  • 无需为 Grok 单独实现缓存解析逻辑

Test plan

  • tsc --noEmit 零错误
  • biome format 零差异
  • biome lint 零违规
  • 4 文件变更,新建 1 个共享模块

🤖 Generated with Claude Code Best

Summary by CodeRabbit

  • Bug Fixes

    • Prevent streaming events from zeroing accumulated cache token counters during usage aggregation.
  • Refactor

    • Token usage aggregation in API services consolidated into a shared utility for consistent streaming merges.
  • New Features

    • (No changes) Grok models do not enable thinking mode by default.

Review Change Stack

1. 提取 updateOpenAIUsage 到共享模块 openaiShared.ts,供 OpenAI 和
   Grok 两条路径复用,消除 Grok 中重复的 spread 漏洞。

2. 在 requestBody.ts 的 isOpenAIThinkingEnabled() 中增加 Grok 模型
   自动检测(模型名含 "grok"),与 DeepSeek/MiMo 并列。

3. messaging 层的 reasoning_content 回传(openaiConvertMessages.ts)
   和流解析(openaiStreamAdapter.ts)无需修改,Grok 与 DeepSeek/MiMo
   共用相同的 reasoning_content 字段协议。

Co-Authored-By: deepseek-v4-pro[1m] <deepseek-ai@claude-code-best.win>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 16, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5c3283db-7b6c-495a-b94d-f7fbcdb23ea1

📥 Commits

Reviewing files that changed from the base of the PR and between ed1bea9 and 13b5ec4.

📒 Files selected for processing (1)
  • src/services/api/openai/requestBody.ts
✅ Files skipped from review due to trivial changes (1)
  • src/services/api/openai/requestBody.ts

📝 Walkthrough

Walkthrough

Extracts streaming token-usage merging into a shared updateOpenAIUsage helper and replaces direct object-spread merges in OpenAI and Grok streaming handlers; also updates a comment to state that grok is intentionally excluded from thinking-mode auto-detection.

Changes

Streaming Token Usage Unification

Layer / File(s) Summary
Shared token usage merge utility
src/services/api/openai/openaiShared.ts
Adds updateOpenAIUsage to merge streaming delta usage into accumulated usage with nullish coalescing for standard tokens and preservation rules for cache token counters.
OpenAI streaming usage accumulation
src/services/api/openai/index.ts
Imports and calls updateOpenAIUsage in the streaming loop (message_delta) instead of merging with { ...usage, ...deltaUsage }.
Grok streaming usage accumulation
src/services/api/grok/index.ts
Imports and calls updateOpenAIUsage to replace direct merges for incoming usage (message_start) and incremental usage (message_delta).
Thinking-mode comment clarification
src/services/api/openai/requestBody.ts
Updates an inline comment to explicitly state that grok is intentionally excluded from thinking-mode auto-detection.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I nibbled at tokens, merging each tiny crumb,

Preserved the cache-counts so none would go numb,
From OpenAI to Grok the helper hops through,
Quietly counting — a rabbit's careful view. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title in Chinese summarizes the main changes: Grok adaptation improvements with defensive usage merging and thinking auto-detection, which accurately reflects the core modifications to the Grok API handling, shared utilities, and thinking mode detection.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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.

Grok 推理模型(如 grok-4.20-reasoning)自动进行推理,不需要
thinking/enable_thinking 请求参数。发送这些参数虽大概率被忽略
(OpenAI SDK 透传 unknown keys),但属于不正确行为。

Co-Authored-By: deepseek-v4-pro[1m] <deepseek-ai@claude-code-best.win>
@claude-code-best claude-code-best merged commit 5157b09 into claude-code-best:main May 16, 2026
3 checks passed
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