Skip to content

Conversation

wans10
Copy link
Contributor

@wans10 wans10 commented Aug 11, 2025

支持 Anthropic API 拉取模型列表(新结构体和认证头处理)

Summary by CodeRabbit

  • New Features
    • Added support for listing models from the Anthropic provider.
    • Channel-aware model fetching across providers (Anthropic, Gemini, Ali) with correct endpoints and headers.
    • Consistent model IDs displayed across providers (e.g., Gemini prefixes removed).
    • Improved reliability and responsiveness when retrieving model lists.

wans10 added 5 commits August 10, 2025 11:31
重构 FetchUpstreamModels 和 FetchModels,通过辅助函数(getChannelBaseURL、buildModelsURL、getAuthHeaders、parseModelsResponse)提高了代码复用性和可维护性。
新 FetchModels 改进了错误处理(更明确的错误信息)和类型检查。
使用已有的 getChannelBaseURL 函数,避免重复实现相同的逻辑
Copy link
Contributor

coderabbitai bot commented Aug 11, 2025

Walkthrough

Adds Anthropic channel support and channel-aware model-fetching logic in controller/channel.go, including new Anthropic response types, an Anthropic-specific HTTP request helper, and branched URL/header/parsing paths for Anthropic, Gemini, Ali, and default channels. Also updates imports and centralizes ID normalization (e.g., trimming Gemini “models/” prefixes).

Changes

Cohort / File(s) Summary of changes
Anthropic support: types & HTTP helper
controller/channel.go
Added public types AnthropicModel, AnthropicModelsResponse; introduced GetAnthropicResponseBody(method, url, apiKey) with Anthropic headers (x-api-key, anthropic-version) and timeout; imported io/ioutil and time.
FetchUpstreamModels branching & parsing
controller/channel.go
Added channel branching: Anthropic uses GetAnthropicResponseBody; Gemini continues via existing path; others generic. Implemented Anthropic unmarshal to AnthropicModelsResponse; Gemini IDs trimmed of “models/” prefix; retained other parsing.
FetchModels URL/header/parsing
controller/channel.go
Channel-aware URL paths: Gemini /v1beta/openai/models; Ali /compatible-mode/v1/models; default /v1/models. Headers: Anthropic-specific vs Authorization Bearer for others. Parsing: Anthropic → AnthropicModelsResponse; non-Anthropic → OpenAIModelsResponse; Gemini ID prefix trimmed.
Public API surface
controller/channel.go
Exported AnthropicModel, AnthropicModelsResponse, GetAnthropicResponseBody.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Controller
  participant Anthropic as Anthropic API
  participant Gemini as Gemini API
  participant Other as Other Upstream

  Client->>Controller: FetchModels / FetchUpstreamModels(channel, key)
  alt channel == Anthropic
    Controller->>Anthropic: GET models (x-api-key, anthropic-version)
    Anthropic-->>Controller: AnthropicModelsResponse
    Controller-->>Client: model IDs (from Data)
  else channel == Gemini
    Controller->>Gemini: GET /v1beta/openai/models (Bearer)
    Gemini-->>Controller: OpenAI-compatible response
    Controller-->>Client: model IDs (trim "models/" prefix)
  else channel == Ali or default
    Controller->>Other: GET channel-specific URL (Bearer)
    Other-->>Controller: OpenAI-compatible response
    Controller-->>Client: model IDs
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

Poem

I twitch my nose at models tall,
Hop hop—now Anthropic joins the call!
Headers snug, URLs aligned,
Trimmed IDs neatly undefined.
Across the fields, the channels sing—
A rabbit stamps: “Ship this thing!” 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
  • 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.

Support

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

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 generate unit tests to generate unit tests for 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
controller/channel.go (3)

236-237: Consider using consistent error message language

The error messages use Chinese ("解析响应失败") while other parts of the codebase might use English. Consider maintaining consistency across error messages.

-				"message": fmt.Sprintf("解析响应失败: %s", err.Error()),
+				"message": fmt.Sprintf("Failed to parse response: %s", err.Error()),

Also applies to: 256-257


291-291: Consider making the Anthropic API version configurable

The API version "2023-06-01" is hardcoded. Consider making this configurable or at least defining it as a constant for easier maintenance.

+const AnthropicAPIVersion = "2023-06-01"
+
 func GetAnthropicResponseBody(method, url, apiKey string) ([]byte, error) {
 	// ... 
-	req.Header.Set("anthropic-version", "2023-06-01")
+	req.Header.Set("anthropic-version", AnthropicAPIVersion)

279-306: Consider reusing existing GetResponseBody function to reduce code duplication

The GetAnthropicResponseBody function duplicates logic from the existing GetResponseBody function in controller/channel-billing.go. Consider refactoring to reuse the existing function by passing appropriate headers.

Instead of creating a new function, you could modify the calling code to use the existing GetResponseBody:

// In FetchUpstreamModels
if channel.Type == constant.ChannelTypeAnthropic {
    headers := http.Header{}
    headers.Set("x-api-key", key)
    headers.Set("anthropic-version", "2023-06-01")
    headers.Set("Content-Type", "application/json")
    body, err = GetResponseBody("GET", url, channel, headers)
}

This would eliminate the need for the separate GetAnthropicResponseBody function and reduce code duplication.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9810231 and 00d648a.

📒 Files selected for processing (1)
  • controller/channel.go (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
controller/channel.go (3)
constant/channel.go (3)
  • ChannelTypeAnthropic (18-18)
  • ChannelTypeGemini (28-28)
  • ChannelTypeAli (21-21)
controller/channel-billing.go (2)
  • GetResponseBody (130-154)
  • GetAuthHeader (124-128)
common/gin.go (1)
  • ApiError (94-99)
🔇 Additional comments (2)
controller/channel.go (2)

46-58: LGTM! Well-structured Anthropic model types.

The new struct definitions properly represent the Anthropic API response format with appropriate JSON tags and pagination support.


915-1017: LGTM! Consistent implementation of Anthropic support in FetchModels.

The modifications properly handle:

  • URL construction for different channel types
  • Anthropic-specific headers
  • Response parsing for both Anthropic and non-Anthropic formats
  • Consistent Gemini ID prefix trimming

The implementation aligns well with the FetchUpstreamModels function.

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.

1 participant