Skip to content

feat: 改进 RequestOpenAI2ClaudeMessage 和添加 claude web search 计费 - #1384

Merged
Calcium-Ion merged 2 commits into
alphafrom
RequestOpenAI2ClaudeMessage
Jul 17, 2025
Merged

feat: 改进 RequestOpenAI2ClaudeMessage 和添加 claude web search 计费#1384
Calcium-Ion merged 2 commits into
alphafrom
RequestOpenAI2ClaudeMessage

Conversation

@creamlike1024

@creamlike1024 creamlike1024 commented Jul 16, 2025

Copy link
Copy Markdown
Collaborator

参考 litellm 改进了 RequestOpenAI2ClaudeMessage:

  1. 处理 tool_choice 和 parallel_tool_calls.
    "auto" 对应 {"type": "auto"}
    "required" 对应 {"type": "any"}
    "none" 对应 {"type": "none"}
    转换 openai 的 parallel_tool_calls 到 Anthropic disable_parallel_tool_use

  2. 支持 claude web search tool 计费

  3. 支持 chat completion 的 web_search_options 转换为 claude web search tool 调用
    openai search_context_size 和 Anthropic max_uses 的对应关系为:"low" 对应 1"medium"对应5"high"对应10

  4. 转换 reasoning_effort 为 thinking 的 budget_tokens,对应关系为:"low" 对应 1280"medium"对应2048"high"对应4096

Summary by CodeRabbit

  • New Features

    • Added support for Claude Web Search tool, including integration with user location and configurable usage limits.
    • Enhanced tool choice options and reasoning effort settings for Claude requests.
    • Web search usage metrics are now tracked and exposed in responses.
  • Bug Fixes

    • Accurate billing and quota calculation for Claude Web Search tool usage.
  • Chores

    • Introduced new pricing constant and retrieval function for Claude Web Search.

@coderabbitai

coderabbitai Bot commented Jul 16, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes add support for Claude web search tool integration, tool choice handling, and reasoning effort configuration. New data structures and methods are introduced for managing tools, tracking web search usage, and billing for web search calls. Constants and functions for web search pricing are also added across relevant modules.

Changes

Files/Paths Change Summary
dto/claude.go Added structs for Claude web search tool, tool choice, server tool use; utility methods for tool handling.
relay/channel/claude/relay-claude.go Updated to support web search tool, tool choice mapping, reasoning effort, and web search usage tracking.
relay/relay-text.go Integrated Claude web search billing into quota calculation and usage logging.
setting/operation_setting/tools.go Added constant and getter for Claude web search price per thousand calls.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Relay
    participant ClaudeAPI

    Client->>Relay: Send request (may include web search/tool choice/reasoning)
    Relay->>Relay: Map tools, tool choice, and reasoning effort
    alt WebSearchOptions present
        Relay->>Relay: Add ClaudeWebSearchTool to request
    end
    Relay->>ClaudeAPI: Forward constructed ClaudeRequest
    ClaudeAPI-->>Relay: Respond with ClaudeUsage (may include web search usage)
    Relay->>Relay: Extract web search usage and set in context
    Relay->>Relay: Calculate billing for Claude web search
    Relay-->>Client: Return response with usage and billing info
Loading

Possibly related PRs

Poem

In the warren of code, a new tool appears,
Claude's web search now hops with cheers!
Billing and usage, all neatly tracked,
With tool choices and reasoning, nothing lacks.
A bunny's delight in every patch—
🐇 Searching, thinking, billing—all in a batch!

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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: 0

🧹 Nitpick comments (2)
relay/channel/claude/relay-claude.go (2)

106-132: Consider adding validation for user location fields.

The user location parsing is well-structured, but consider adding validation for the string fields to ensure they meet any API requirements (e.g., timezone format, country codes).

You could add basic validation:

 if timezone, ok := approximateData["timezone"].(string); ok && timezone != "" {
+    // Validate timezone format if needed
     anthropicUserLocation.Timezone = timezone
 }
 if country, ok := approximateData["country"].(string); ok && country != "" {
+    // Consider validating country code format (e.g., ISO 3166)
     anthropicUserLocation.Country = country
 }

785-798: Consider adding validation for unknown tool choice values.

While the current implementation handles the documented values, consider adding a default case or validation for unexpected string values.

 switch toolChoiceStr {
 case "auto":
     claudeToolChoice = &dto.ClaudeToolChoice{
         Type: "auto",
     }
 case "required":
     claudeToolChoice = &dto.ClaudeToolChoice{
         Type: "any",
     }
 case "none":
     claudeToolChoice = &dto.ClaudeToolChoice{
         Type: "none",
     }
+default:
+    // Log warning or return error for unknown values
+    common.LogWarn(nil, fmt.Sprintf("Unknown tool_choice value: %s, defaulting to auto", toolChoiceStr))
+    claudeToolChoice = &dto.ClaudeToolChoice{
+        Type: "auto",
+    }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3bf0748 and 961bc87.

📒 Files selected for processing (4)
  • dto/claude.go (3 hunks)
  • relay/channel/claude/relay-claude.go (7 hunks)
  • relay/relay-text.go (3 hunks)
  • setting/operation_setting/tools.go (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
relay/relay-text.go (1)
Learnt from: 9Ninety
PR: QuantumNous/new-api#1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
relay/channel/claude/relay-claude.go (1)
Learnt from: 9Ninety
PR: QuantumNous/new-api#1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🧬 Code Graph Analysis (2)
relay/relay-text.go (1)
setting/operation_setting/tools.go (1)
  • GetClaudeWebSearchPricePerThousand (31-33)
relay/channel/claude/relay-claude.go (3)
dto/openai_request.go (1)
  • WebSearchOptions (600-603)
dto/claude.go (4)
  • ClaudeWebSearchTool (161-166)
  • ClaudeWebSearchUserLocation (168-174)
  • Thinking (253-256)
  • ClaudeToolChoice (176-180)
common/utils.go (1)
  • GetPointer (218-220)
🔇 Additional comments (7)
setting/operation_setting/tools.go (1)

26-33: LGTM! The Claude web search pricing is well-structured.

The constant and getter function follow the established patterns in this file and integrate cleanly with the existing pricing system.

relay/relay-text.go (1)

409-418: Well-implemented Claude web search billing integration!

The billing logic correctly:

  • Retrieves the web search request count from the Gin context
  • Calculates quota using the appropriate price function and multipliers
  • Follows the established pattern for tool billing
  • Properly updates the usage tracking in the other map

Also applies to: 542-546

dto/claude.go (1)

161-180: Excellent data structure design for Claude tool support!

The new types and methods are well-structured:

  • ClaudeWebSearchTool and ClaudeWebSearchUserLocation properly model the Anthropic API
  • ClaudeToolChoice correctly represents tool selection options
  • The AddTool/GetTools methods handle type safety gracefully
  • ProcessTools function elegantly separates different tool types
  • ClaudeServerToolUse provides clean usage tracking

Also applies to: 200-251, 327-336

relay/channel/claude/relay-claude.go (4)

20-24: Clear and reasonable web search usage limits.

The constants align well with the low/medium/high context size mapping.


160-166: Tool choice mapping is correctly implemented!

The implementation properly handles:

  • String values mapping ("auto" → "auto", "required" → "any", "none" → "none")
  • Object form for specific tool selection
  • Correct inversion of parallel_tool_calls to disable_parallel_tool_use

This aligns perfectly with the PR objectives referencing litellm behavior.

Also applies to: 780-826


192-211: Reasoning effort mapping matches PR objectives.

The budget token mappings are correctly implemented:

  • low: 1280 tokens
  • medium: 2048 tokens
  • high: 4096 tokens

748-750: Web search usage tracking properly integrated.

The code correctly extracts the web search request count from the Claude response and sets it in the Gin context for downstream billing calculations.

@liaokaime

Copy link
Copy Markdown

我正在寻找以claude messages格式请求openai模型的方法,请问这个issus是在实现这个功能吗,还是说我必须去别的地方寻找答案?

@Calcium-Ion

Copy link
Copy Markdown
Member

我正在寻找以claude messages格式请求openai模型的方法,请问这个issus是在实现这个功能吗,还是说我必须去别的地方寻找答案?

alpha版本已经可以实现

@Calcium-Ion
Calcium-Ion merged commit 6b3f1ab into alpha Jul 17, 2025
3 checks passed
@liaokaime

liaokaime commented Jul 26, 2025

Copy link
Copy Markdown

我正在寻找以claude messages格式请求openai模型的方法,请问这个issus是在实现这个功能吗,还是说我必须去别的地方寻找答案?

alpha版本已经可以实现

@Calcium-Ion 在哪里设置?

@Calcium-Ion
Calcium-Ion deleted the RequestOpenAI2ClaudeMessage branch July 26, 2025 06:07
@coderabbitai coderabbitai Bot mentioned this pull request Aug 29, 2025
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
…audeMessage

feat: 改进 RequestOpenAI2ClaudeMessage 和添加 claude web search 计费
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.

3 participants