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 makes model-fetching channel-aware in controller/channel.go: new Anthropic types and an Anthropic-specific HTTP helper; branched URL/header selection and response parsing for Anthropic, Gemini, Ali, and default channels; adjusts ID normalization and imports.

Changes

Cohort / File(s) Summary of changes
Anthropic support: types & HTTP helper
controller/channel.go
Added exported types AnthropicModel, AnthropicModelsResponse and exported GetAnthropicResponseBody(method string, url string, apiKey string) ([]byte, error) implementing Anthropic headers (x-api-key, anthropic-version, Content-Type) and timeout; added io/ioutil and time imports.
FetchUpstreamModels branching & parsing
controller/channel.go
Branches by channel: Anthropic requests use GetAnthropicResponseBody; other channels use existing helpers. Parses Anthropic responses into AnthropicModelsResponse and extracts Data IDs; preserves Gemini parsing and trims models/ prefix where applicable.
FetchModels URL/header/parsing
controller/channel.go
Constructs channel-aware URLs (Gemini: /v1beta/openai/models, Ali: /compatible-mode/v1/models, default: /v1/models). Uses Anthropic headers for Anthropic and Authorization: Bearer <key> otherwise. Parses Anthropic into AnthropicModelsResponse; non-Anthropic into OpenAIModelsResponse; trims Gemini models/ prefix.
Public API surface
controller/channel.go
Exported AnthropicModel, AnthropicModelsResponse, and GetAnthropicResponseBody from package controller.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Controller
  participant AnthropicAPI as Anthropic API
  participant GeminiAPI as Gemini API
  participant OtherAPI as Other Upstream

  Client->>Controller: FetchModels / FetchUpstreamModels(channel, apiKey)
  alt channel == Anthropic
    Controller->>AnthropicAPI: GET /models (x-api-key, anthropic-version, Content-Type)
    AnthropicAPI-->>Controller: AnthropicModelsResponse (Data[])
    Controller-->>Client: return model IDs (Data)
  else channel == Gemini
    Controller->>GeminiAPI: GET /v1beta/openai/models (Authorization: Bearer)
    GeminiAPI-->>Controller: OpenAIModelsResponse
    Controller-->>Client: return model IDs (trim "models/" prefixes)
  else channel == Ali or default
    Controller->>OtherAPI: GET channel-specific URL (Authorization: Bearer)
    OtherAPI-->>Controller: OpenAIModelsResponse
    Controller-->>Client: return model IDs
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

I twitch my whiskers, nose so spry—
Anthropic joins the model sky.
Headers set and IDs trimmed neat,
Channels hum a tidy beat.
Hop, hop—new routes and code complete! 🥕

Pre-merge checks and finishing touches

❌ 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%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "支持 Anthropic API 拉取模型列表(新结构体和认证头处理)" concisely and accurately describes the primary change: adding support to fetch Anthropic model lists along with new structs and authentication header handling, which matches the modifications in controller/channel.go and the PR objectives. It is specific, focused on the main feature, and contains no noisy or irrelevant information.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

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

📒 Files selected for processing (1)
  • controller/channel.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • controller/channel.go

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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.

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