Skip to content

Go: refactor model provider - #15568

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix443
Jun 3, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix443

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. Add license announcement
  2. Add sanity check on API config
  3. Add base class: BaseModel
  4. Add GetBaseURL

Type of change

  • Refactoring

Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR standardizes Apache 2.0 license headers across 22 model provider files and introduces a BaseModel abstraction for shared API configuration, validation, and HTTP client management. ZhipuAIModel is refactored to embed BaseModel, consolidating region-to-base-URL resolution and API key validation logic across all its methods.

Changes

License Header Standardization

Layer / File(s) Summary
License headers for 22 model providers
internal/entity/models/{302ai,baichuan,baidu,cohere,deepinfra,fishaudio,huaweicloud,huggingface,jiekouai,jina,lmstudio,mineru,mineru_local,nvidia,ollama,openrouter,orcarouter,paddleocr,paddleocr_local,qiniu,tokenhub,xunfei}.go
Apache 2.0 copyright and license comment blocks added to the beginning of each file; no functional code changes.

BaseModel Abstraction and ZhipuAIModel Refactoring

Layer / File(s) Summary
BaseModel type, validation, and URL resolution
internal/entity/models/base_model.go
New BaseModel struct with region-to-base-URL mapping, URLSuffix, and internal HTTP client. APIConfigCheck validates that APIConfig has a non-empty API key and either a direct BaseURL or a non-empty Region. GetBaseURL returns the configured base URL (trimmed) or resolves it from the model's region map (defaulting to "default"), returning an error if the region mapping is missing.
ZhipuAIModel constructor and BaseModel embedding
internal/entity/models/zhipu-ai.go (lines 38–53)
ZhipuAIModel refactored to embed BaseModel instead of directly managing BaseURL, URLSuffix, and httpClient fields. Constructor initializes the embedded BaseModel with region-to-base-URL mappings, URL suffix endpoints, and a reusable HTTP client transport.
Core API methods refactored to use BaseModel
internal/entity/models/zhipu-ai.go (ChatWithMessages, ChatStreamlyWithSender, Embed, ListModels, CheckConnection)
ChatWithMessages, ChatStreamlyWithSender, Embed, ListModels, and CheckConnection replaced manual API key/region validation and base-URL selection with baseModel.APIConfigCheck and baseModel.GetBaseURL; construct request URLs using baseModel.URLSuffix.* endpoints; execute requests via baseModel.httpClient.Do(req). In ListModels, the model-name derivation no longer appends @<owned_by> suffix; it now uses model.ID directly.
Rerank, audio transcription, and TTS/OCR helper method refactoring
internal/entity/models/zhipu-ai.go (Rerank, TranscribeAudio, AudioSpeech, AudioSpeechWithSender, buildTTSRequest, OCRFile)
Rerank, TranscribeAudio, AudioSpeech, AudioSpeechWithSender, buildTTSRequest, and OCRFile updated to use baseModel.APIConfigCheck, baseModel.GetBaseURL, and validate required URL suffix fields via baseModel.URLSuffix; all HTTP requests switched to baseModel.httpClient.Do(req); TTS and OCR request builders validate endpoint suffixes before constructing request URLs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15382: Both PRs modify ChatStreamlyWithSender in zhipu-ai.go; this PR refactors it to use BaseModel, while that PR adjusts bufio.Scanner buffer limits.
  • infiniflow/ragflow#14886: Both PRs modify ListModels in zhipu-ai.go; the related PR added @owned_by formatting, and this PR removes it in favor of plain model.ID.
  • infiniflow/ragflow#14836: Both PRs involve TranscribeAudio, AudioSpeech, and OCRFile methods in zhipu-ai.go; the related PR introduced those stubs, and this PR refactors them to delegate to BaseModel for config and URL handling.

Suggested labels

ci, size:XL

Suggested reviewers

  • Haruko386

Poem

🐰 A rabbit hops through licensing land,
Base URLs now neatly planned,
ZhipuAI delegates with care,
Config checks float everywhere,
Refactoring makes models fair! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Go: refactor model provider' is vague and overly broad, using generic language that doesn't convey the specific changes made in the changeset. Revise the title to be more specific about the main changes, such as 'Add BaseModel for API configuration and URL management' or 'Refactor model providers with base class and license headers'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description is mostly complete, addressing all the key objectives (license announcement, API config sanity checks, BaseModel class, GetBaseURL method) and specifying the refactoring type, though it could be more detailed.
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.


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.

@JinHai-CN
JinHai-CN marked this pull request as ready for review June 3, 2026 07:11
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Jun 3, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft June 3, 2026 07:11
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 3, 2026 07:11
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 3, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft June 3, 2026 07:12
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 3, 2026 07:12

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/entity/models/base_model.go`:
- Around line 47-61: The mapped base URL returned from b.BaseURL[region] isn't
normalized like apiConfig.BaseURL (which trims trailing '/'), causing double
slashes; update the code that reads baseURL from b.BaseURL (the branch that uses
baseURL, ok := b.BaseURL[region]) to apply the same normalization (e.g.,
strings.TrimSuffix(baseURL, "/")) before returning so callers using
fmt.Sprintf("%s/%s", ...) get a canonical base URL; change the return from
returning raw baseURL to the trimmed value and keep the same error behavior for
missing entries.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 95f2a9c3-a71b-444d-b9ba-c71fbecc558f

📥 Commits

Reviewing files that changed from the base of the PR and between c0e00a7 and 801dbad.

📒 Files selected for processing (24)
  • internal/entity/models/302ai.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/base_model.go
  • internal/entity/models/cohere.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jina.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/mineru.go
  • internal/entity/models/mineru_local.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/paddleocr.go
  • internal/entity/models/paddleocr_local.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/xunfei.go
  • internal/entity/models/zhipu-ai.go

Comment on lines +47 to +61
if apiConfig.BaseURL != nil && *apiConfig.BaseURL != "" {
return strings.TrimSuffix(*apiConfig.BaseURL, "/"), nil
}

region := "default"
if apiConfig.Region != nil {
region = *apiConfig.Region
}

baseURL, ok := b.BaseURL[region]
if !ok || baseURL == "" {
return "", fmt.Errorf("no base URL configured for region %q", region)
}

return baseURL, nil

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Normalize mapped base URLs the same way as explicit ones.

The explicit apiConfig.BaseURL branch strips a trailing /, but the b.BaseURL[region] branch returns the raw string. A mapped value like https://host/ will produce https://host//... in every caller that does fmt.Sprintf("%s/%s", ...).

💡 Suggested fix
 func (b *BaseModel) GetBaseURL(apiConfig *APIConfig) (string, error) {
 
 	if apiConfig.BaseURL != nil && *apiConfig.BaseURL != "" {
 		return strings.TrimSuffix(*apiConfig.BaseURL, "/"), nil
 	}
@@
 	baseURL, ok := b.BaseURL[region]
 	if !ok || baseURL == "" {
 		return "", fmt.Errorf("no base URL configured for region %q", region)
 	}
 
-	return baseURL, nil
+	return strings.TrimSuffix(baseURL, "/"), nil
 }
📝 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 apiConfig.BaseURL != nil && *apiConfig.BaseURL != "" {
return strings.TrimSuffix(*apiConfig.BaseURL, "/"), nil
}
region := "default"
if apiConfig.Region != nil {
region = *apiConfig.Region
}
baseURL, ok := b.BaseURL[region]
if !ok || baseURL == "" {
return "", fmt.Errorf("no base URL configured for region %q", region)
}
return baseURL, nil
func (b *BaseModel) GetBaseURL(apiConfig *APIConfig) (string, error) {
if apiConfig.BaseURL != nil && *apiConfig.BaseURL != "" {
return strings.TrimSuffix(*apiConfig.BaseURL, "/"), nil
}
region := "default"
if apiConfig.Region != nil {
region = *apiConfig.Region
}
baseURL, ok := b.BaseURL[region]
if !ok || baseURL == "" {
return "", fmt.Errorf("no base URL configured for region %q", region)
}
return strings.TrimSuffix(baseURL, "/"), nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/base_model.go` around lines 47 - 61, The mapped base
URL returned from b.BaseURL[region] isn't normalized like apiConfig.BaseURL
(which trims trailing '/'), causing double slashes; update the code that reads
baseURL from b.BaseURL (the branch that uses baseURL, ok := b.BaseURL[region])
to apply the same normalization (e.g., strings.TrimSuffix(baseURL, "/")) before
returning so callers using fmt.Sprintf("%s/%s", ...) get a canonical base URL;
change the return from returning raw baseURL to the trimmed value and keep the
same error behavior for missing entries.

@codecov

codecov Bot commented Jun 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (ff59714) to head (801dbad).
⚠️ Report is 8 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15568   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant