Skip to content

feat: openrouter format for claude request - #1235

Merged
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
prnake:thinking-fix-0616
Jun 21, 2025
Merged

Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
prnake:thinking-fix-0616

Conversation

@prnake

@prnake prnake commented Jun 16, 2025 •

Copy link
Copy Markdown
Contributor

之前的 PR: #1112
#983 实现了 openrouter 的 reasoning 字段透传和 /messages -> openrouter,没有实现 /chat/completions -> claude
这个 pr 支持 openrouter 格式请求 "reasoning": {"max_tokens": 16000} ,转换成 ClaudeRequest

Summary by CodeRabbit

  • New Features
    • Added support for processing an optional "Reasoning" field in relevant requests, enabling enhanced handling of reasoning-related parameters when provided.

@coderabbitai

coderabbitai Bot commented Jun 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update enhances the RequestOpenAI2ClaudeMessage function to process an optional Reasoning field from incoming requests. If present and valid, this field influences the construction of the Thinking property in the outgoing Claude API request, using values from the parsed reasoning data.

Changes

File(s) Change Summary
relay/channel/claude/relay-claude.go Added logic to handle an optional Reasoning field, importing openrouter for struct support.

Poem

In the warren of code where the clever bits dwell,
A new path for Reasoning now weaves its own spell.
If tokens are granted and logic is sound,
The Thinking is enabled, with budget profound.
Hop, hop, hooray—our relay grows wise,
As rabbits and code together arise!

✨ 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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between af9cc5c and 296da5d.

📒 Files selected for processing (1)
  • relay/channel/claude/relay-claude.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
relay/channel/claude/relay-claude.go (3)
dto/openai_request.go (1)
  • Reasoning (623-626)
relay/channel/openrouter/dto.go (1)
  • RequestReasoning (3-9)
dto/claude.go (1)
  • Thinking (179-182)

Comment on lines +126 to +139
if textRequest.Reasoning != nil {
var reasoning openrouter.RequestReasoning
if err := json.Unmarshal(textRequest.Reasoning, &reasoning); err != nil {
return nil, err
}

budgetTokens := reasoning.MaxTokens
if budgetTokens > 0 {
claudeRequest.Thinking = &dto.Thinking{
Type: "enabled",
BudgetTokens: budgetTokens,
}
}
}

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.

💡 Verification agent

🧩 Analysis chain

Reasoning handling ignores effort, exclude, and mutual-exclusion rules

Good to see the OpenRouter reasoning field being parsed, but a couple of gaps remain:

  1. The OpenRouter spec states that exactly one of effort or max_tokens should be set. We silently accept invalid payloads (effort+max_tokens or none) instead of validating and returning a 400.
  2. effort (low/medium/high) and exclude are discarded. Consumers expecting Claude’s extended‐thinking behaviour driven by effort, or expecting the reasoning content to be suppressed when exclude=true, will get surprising results.
  3. This block runs after the “-thinking” adapter logic, so a reasoning.max_tokens field will overwrite the budget calculated earlier, whereas an effort field will not. The precedence feels accidental – consider parsing Reasoning before the adapter section and using its values when calculating the budget.

Minimal validation + support for effort/exclude:

+// validate and map openrouter reasoning
+if textRequest.Reasoning != nil {
+    var r openrouter.RequestReasoning
+    if err := json.Unmarshal(textRequest.Reasoning, &r); err != nil {
+        return nil, err
+    }
+    // spec: exactly one of effort/max_tokens
+    if (r.Effort != "" && r.MaxTokens > 0) || (r.Effort == "" && r.MaxTokens == 0) {
+        return nil, fmt.Errorf("invalid reasoning payload: set either effort or max_tokens")
+    }
+
+    // derive budget
+    budget := r.MaxTokens
+    if budget == 0 { // use effort mapping if provided
+        switch strings.ToLower(r.Effort) {
+        case "low":
+            budget = 1024
+        case "medium":
+            budget = 4096
+        case "high":
+            budget = 8192
+        }
+    }
+
+    claudeRequest.Thinking = &dto.Thinking{
+        Type:         "enabled",
+        BudgetTokens: budget,
+    }
+    if r.Exclude {
+        // implementation-specific: propagate a flag or strip reasoning later
+    }
+}

This keeps behaviour predictable and aligned with OpenRouter’s contract.


🏁 Script executed:

#!/bin/bash
# Locate the relay-claude.go file
fd relay-claude.go

# Show context around the Reasoning handling (lines ~120–140)
rg -n 'textRequest\.Reasoning' -A5 -B5 relay/channel/claude/relay-claude.go

# Find all earlier occurrences of Thinking setup (to see adapter logic)
rg -n 'claudeRequest\.Thinking' -C3 relay/channel/claude/relay-claude.go

Length of output: 1146


Validate and Apply Reasoning Fields Before Adapter Logic

The current code at lines 112–117 and 126–137

  • Unconditionally applies a “-thinking” adapter budget first (claudeRequest.Thinking at line 114)
  • Parses textRequest.Reasoning only afterward, ignores Effort and Exclude, and only uses MaxTokens if > 0
  • Allows invalid combos (both or neither of effort/max_tokens) without error

This leads to unpredictable precedence and silent drops of effort/exclude. To align with the OpenRouter spec:

  1. Move Reasoning parsing & validation before the adapter logic
  2. Enforce exactly one of r.Effort or r.MaxTokens (else return 400)
  3. Map effort → token budget (low=1024, medium=4096, high=8192) when MaxTokens==0
  4. Honor r.Exclude by propagating a flag or suppressing reasoning output
  5. Only if textRequest.Reasoning==nil fall back to the adapter‐computed budget

Example diff:

-  // BudgetTokens 为 max_tokens 的 80%
-  claudeRequest.Thinking = &dto.Thinking{
-      Type:         "enabled",
-      BudgetTokens: int(float64(claudeRequest.MaxTokens) * model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage),
-  }
+  // 1) parse + validate OpenRouter reasoning
+  if textRequest.Reasoning != nil {
+      var r openrouter.RequestReasoning
+      if err := json.Unmarshal(textRequest.Reasoning, &r); err != nil {
+          return nil, err
+      }
+      // spec: exactly one of effort or max_tokens
+      if (r.Effort != "" && r.MaxTokens > 0) || (r.Effort == "" && r.MaxTokens == 0) {
+          return nil, fmt.Errorf("invalid reasoning payload: set either effort or max_tokens")
+      }
+
+      // derive budget from max_tokens or effort
+      budget := r.MaxTokens
+      if budget == 0 {
+          switch strings.ToLower(r.Effort) {
+          case "low":
+              budget = 1024
+          case "medium":
+              budget = 4096
+          case "high":
+              budget = 8192
+          }
+      }
+
+      claudeRequest.Thinking = &dto.Thinking{
+          Type:         "enabled",
+          BudgetTokens: budget,
+      }
+      if r.Exclude {
+          // TODO: implement exclusion behavior
+      }
+  } else {
+      // 2) fall back to adapter‐calculated budget
+      claudeRequest.Thinking = &dto.Thinking{
+          Type:         "enabled",
+          BudgetTokens: int(float64(claudeRequest.MaxTokens) *
+                             model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage),
+      }
+  }

This ensures mutual‐exclusion, full support for effort/exclude, and consistent precedence.

📝 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
if textRequest.Reasoning != nil {
var reasoning openrouter.RequestReasoning
if err := json.Unmarshal(textRequest.Reasoning, &reasoning); err != nil {
return nil, err
}
budgetTokens := reasoning.MaxTokens
if budgetTokens > 0 {
claudeRequest.Thinking = &dto.Thinking{
Type: "enabled",
BudgetTokens: budgetTokens,
}
}
}
// 1) parse + validate OpenRouter reasoning
if textRequest.Reasoning != nil {
var r openrouter.RequestReasoning
if err := json.Unmarshal(textRequest.Reasoning, &r); err != nil {
return nil, err
}
// spec: exactly one of effort or max_tokens
if (r.Effort != "" && r.MaxTokens > 0) || (r.Effort == "" && r.MaxTokens == 0) {
return nil, fmt.Errorf("invalid reasoning payload: set either effort or max_tokens")
}
// derive budget from max_tokens or effort
budget := r.MaxTokens
if budget == 0 {
switch strings.ToLower(r.Effort) {
case "low":
budget = 1024
case "medium":
budget = 4096
case "high":
budget = 8192
}
}
claudeRequest.Thinking = &dto.Thinking{
Type: "enabled",
BudgetTokens: budget,
}
if r.Exclude {
// TODO: implement exclusion behavior
}
} else {
// 2) fall back to adapter‐calculated budget (80% of MaxTokens)
claudeRequest.Thinking = &dto.Thinking{
Type: "enabled",
BudgetTokens: int(float64(claudeRequest.MaxTokens) *
model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage),
}
}
🤖 Prompt for AI Agents
In relay/channel/claude/relay-claude.go around lines 112 to 139, the current
handling of textRequest.Reasoning parses and applies MaxTokens after the
"-thinking" adapter logic, ignores Effort and Exclude fields, and does not
validate that exactly one of Effort or MaxTokens is set. To fix this, move the
parsing and validation of Reasoning before the adapter logic, enforce that
exactly one of Effort or MaxTokens is provided (return a 400 error if not), map
Effort values (low=1024, medium=4096, high=8192) to token budgets when MaxTokens
is zero, handle the Exclude flag appropriately (e.g., suppress reasoning output
or propagate a flag), and only use the adapter-computed budget if Reasoning is
nil. This will ensure correct precedence, validation, and full support for the
Reasoning fields per the OpenRouter spec.

@Calcium-Ion
Calcium-Ion changed the base branch from main to alpha June 21, 2025 17:07
@Calcium-Ion
Calcium-Ion merged commit ea79d59 into QuantumNous:alpha Jun 21, 2025
This was referenced Feb 6, 2026
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
feat: openrouter format for claude request
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
feat: openrouter format for claude request
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
feat: openrouter format for claude request
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