Skip to content

Go: implement provider: Baichuan - #14832

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main
May 12, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

This PR completes the Baichuan provider

The following functionalities are now supported:

Baichuan:

  • Chat / Stream Chat
  • Embedding
  • Rerank
  • Model listing
  • Provider connection checking
  • Balance

Verified examples from the CLI:

# Baichuan

RAGFlow(user)> embed text 'walkerwhat' 'jumperwho' with 'Baichuan-Text-Embedding@test@baichuan' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 1024      | 0     |
| 1024      | 1     |
+-----------+-------+

AGFlow(user)> chat with 'Baichuan-M2@test@baichuan' message 'who r u'
Answer: I'm BaiChuan, a helpful AI assistant created by Baichuan-AI. I'm designed to be a knowledgeable, friendly, and reliable assistant for various tasks like answering questions, explaining concepts, writing content, and more. Feel free to ask me anything! 😊
Time: 1.637975

RAGFlow(user)> stream chat with 'Baichuan-M2@test@baichuan' message 'who r u'
Answer: I'm BaiChuan-m2, an AI assistant developed by Baichuan-AI. My purpose is to help you with a wide range of tasks by providing information, answering questions, solving problems, and assisting with creative projects. Think of me as a helpful digital companion! If you have any questions or need assistance, just let me know.😊
Time: 1.692321

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactoring

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 12, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 12, 2026
@Haruko386
Haruko386 marked this pull request as draft May 12, 2026 06:58
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds comprehensive Baichuan model provider support to the system. A new provider configuration defines Baichuan's API endpoints and available models. A complete driver implementation provides chat, streaming chat, and embedding operations with proper error handling for unimplemented features. The factory is updated to dispatch "baichuan" requests to the new driver. Additionally, CoHere model methods are refactored to remove conditional URL suffix fallbacks.

Changes

Baichuan Provider Integration

Layer / File(s) Summary
Baichuan provider configuration
conf/models/baichuan.json
Defines the Baichuan registry with base URL, chat and embedding endpoint suffixes, provider class identifier, and model catalog including chat models and an embedding model with configured token limits.
Baichuan model type and initialization
internal/entity/models/baichuan.go (lines 1–57)
BaichuanModel struct with pooled HTTP client transport initialization; constructors create instances with 120s timeout; NewInstance clones with a new base URL; Name returns the provider identifier.
Baichuan chat operations
internal/entity/models/baichuan.go (lines 58–306)
ChatWithMessages validates API key and messages, selects region, applies config overrides, and returns the first choice's message content. ChatStreamlyWithSender POSTs with streaming enabled, parses SSE data: events, forwards content deltas to a sender callback, and signals completion with [DONE].
Baichuan embedding and stubs
internal/entity/models/baichuan.go (lines 308–393)
Embed validates input, POSTs the embedding request, and returns ordered EmbeddingData with indices. Rerank, ListModels, Balance, and CheckConnection are stubbed methods returning "no such method" errors.
Factory registration
internal/entity/models/factory.go (lines 78–79)
ModelFactory.CreateModelDriver recognizes "baichuan" (case-insensitive) and instantiates a new BaichuanModel driver.

CoHere URL Suffix Cleanup

Layer / File(s) Summary
CoHere URL suffix fallback removal
internal/entity/models/cohere.go (lines 341–343, 415–418, 496–498)
Embed, Rerank, and ListModels methods no longer conditionally substitute hardcoded default suffixes when URLSuffix config values are empty; they now use config values directly.

Minor Formatting

FishAudio whitespace adjustment in internal/entity/models/fishaudio.go (line 29).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14790: Adds CoHere and FishAudio model drivers and updates factory registration with similar patterns to this Baichuan provider addition.
  • infiniflow/ragflow#14605: Adds OpenAI model driver and factory registration, following the same model provider integration pattern as this PR.
  • infiniflow/ragflow#14395: Adds Google model provider implementation and factory dispatch, demonstrating a comparable model driver onboarding approach.

Suggested labels

💞 feature, size:L

Poem

A Baichuan springs forth in the model garden,
Chat flows swift and embeddings flourish fair,
Factory gates swing open without pardon,
CoHere's hardcodes vanish into air. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'Go: implement provider: Baichuan' clearly and specifically summarizes the main change—adding Baichuan provider implementation in Go.
Description check ✅ Passed The PR description follows the template with complete 'What problem does this PR solve?' section and properly selected Type of change checkboxes; it includes verified CLI examples and clear feature status.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@Haruko386
Haruko386 marked this pull request as ready for review May 12, 2026 06:58
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels May 12, 2026

@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

🧹 Nitpick comments (2)
internal/entity/models/baichuan.go (2)

22-52: ⚡ Quick win

Extract duplicated httpClient initialization to a helper function.

The httpClient configuration is identical in both NewBaichuanModel and NewInstance. Consider extracting it to a helper function to improve maintainability.

♻️ Proposed refactor
+func newBaichuanHTTPClient() *http.Client {
+	return &http.Client{
+		Timeout: 120 * time.Second,
+		Transport: &http.Transport{
+			MaxIdleConns:        100,
+			MaxIdleConnsPerHost: 10,
+			IdleConnTimeout:     90 * time.Second,
+			DisableCompression:  false,
+		},
+	}
+}
+
 func NewBaichuanModel(baseURL map[string]string, urlSuffix URLSuffix) *BaichuanModel {
 	return &BaichuanModel{
 		BaseURL:   baseURL,
 		URLSuffix: urlSuffix,
-		httpClient: &http.Client{
-			Timeout: 120 * time.Second,
-			Transport: &http.Transport{
-				MaxIdleConns:        100,
-				MaxIdleConnsPerHost: 10,
-				IdleConnTimeout:     90 * time.Second,
-				DisableCompression:  false,
-			},
-		},
+		httpClient: newBaichuanHTTPClient(),
 	}
 }

 func (b *BaichuanModel) NewInstance(baseURL map[string]string) ModelDriver {
 	return &BaichuanModel{
 		BaseURL:   baseURL,
 		URLSuffix: b.URLSuffix,
-		httpClient: &http.Client{
-			Timeout: 120 * time.Second,
-			Transport: &http.Transport{
-				MaxIdleConns:        100,
-				MaxIdleConnsPerHost: 10,
-				IdleConnTimeout:     90 * time.Second,
-				DisableCompression:  false,
-			},
-		},
+		httpClient: newBaichuanHTTPClient(),
 	}
 }
🤖 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/baichuan.go` around lines 22 - 52, The http.Client
construction is duplicated in NewBaichuanModel and BaichuanModel.NewInstance;
extract that logic into a single helper function (e.g., newBaichuanHTTPClient or
buildHTTPClient) that returns *http.Client and replace the inline client
initializations in both NewBaichuanModel and NewInstance with calls to that
helper, keeping the same Timeout and Transport settings (MaxIdleConns,
MaxIdleConnsPerHost, IdleConnTimeout, DisableCompression) so behavior is
unchanged.

309-311: 💤 Low value

Consider making empty input validation consistent.

Embed returns an empty slice for empty texts (line 310), while ChatWithMessages returns an error for empty messages (line 63). Consider whether both methods should handle empty inputs consistently, either by returning errors or empty results.

🤖 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/baichuan.go` around lines 309 - 311, Embed currently
returns an empty slice for empty texts while ChatWithMessages returns an error
for empty messages; make behavior consistent by having Embed return an error for
empty input like ChatWithMessages does. Replace the early-return in Embed
(function Embed) to return (nil, fmt.Errorf("texts must not be empty")) or the
same error type/message used by ChatWithMessages, update any callers/tests that
expect an empty slice, and ensure the function signature and imports support
returning an error.
🤖 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/baichuan.go`:
- Line 15: Remove the hardcoded API key string
"sk-6e16f0a6bfaa7fc58e30a50962665d1d" from the comment in
internal/entity/models/baichuan.go: delete the key or replace it with a
non-secret placeholder like "<REDACTED_API_KEY>" so no real key remains in
source, then search the repo for any other occurrences of that key and remove
them; ensure the application uses a secure secret source (environment variable
or secret manager) instead of embedding keys in comments or code.

---

Nitpick comments:
In `@internal/entity/models/baichuan.go`:
- Around line 22-52: The http.Client construction is duplicated in
NewBaichuanModel and BaichuanModel.NewInstance; extract that logic into a single
helper function (e.g., newBaichuanHTTPClient or buildHTTPClient) that returns
*http.Client and replace the inline client initializations in both
NewBaichuanModel and NewInstance with calls to that helper, keeping the same
Timeout and Transport settings (MaxIdleConns, MaxIdleConnsPerHost,
IdleConnTimeout, DisableCompression) so behavior is unchanged.
- Around line 309-311: Embed currently returns an empty slice for empty texts
while ChatWithMessages returns an error for empty messages; make behavior
consistent by having Embed return an error for empty input like ChatWithMessages
does. Replace the early-return in Embed (function Embed) to return (nil,
fmt.Errorf("texts must not be empty")) or the same error type/message used by
ChatWithMessages, update any callers/tests that expect an empty slice, and
ensure the function signature and imports support returning an error.
🪄 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: ef1c7163-c7ab-48c4-b877-211c60516570

📥 Commits

Reviewing files that changed from the base of the PR and between f85e18a and 1e8437a.

📒 Files selected for processing (5)
  • conf/models/baichuan.json
  • internal/entity/models/baichuan.go
  • internal/entity/models/cohere.go
  • internal/entity/models/factory.go
  • internal/entity/models/fishaudio.go
💤 Files with no reviewable changes (1)
  • internal/entity/models/cohere.go

"time"
)

// sk-6e16f0a6bfaa7fc58e30a50962665d1d

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 | 🔴 Critical | ⚡ Quick win

Remove the hardcoded API key from the comment.

This commented API key is a security risk and should not be committed to the repository, even in a comment.

🔐 Proposed fix
-// sk-6e16f0a6bfaa7fc58e30a50962665d1d
 type BaichuanModel struct {
📝 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
// sk-6e16f0a6bfaa7fc58e30a50962665d1d
type BaichuanModel struct {
🤖 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/baichuan.go` at line 15, Remove the hardcoded API key
string "sk-6e16f0a6bfaa7fc58e30a50962665d1d" from the comment in
internal/entity/models/baichuan.go: delete the key or replace it with a
non-secret placeholder like "<REDACTED_API_KEY>" so no real key remains in
source, then search the repo for any other occurrences of that key and remove
them; ensure the application uses a secure secret source (environment variable
or secret manager) instead of embedding keys in comments or code.

@codecov

codecov Bot commented May 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (f85e18a) to head (1e8437a).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14832   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

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

@JinHai-CN
JinHai-CN merged commit ebab351 into infiniflow:main May 12, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 27, 2026
8 tasks done
@coderabbitai coderabbitai Bot mentioned this pull request Jun 5, 2026
1 of 6 tasks
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

This PR completes the Baichuan provider

**The following functionalities are now supported:**

**Baichuan:**
- [x] Chat / Stream Chat
- [x] Embedding
- [ ] ~~Rerank~~
- [ ] ~~Model listing~~
- [ ] ~~Provider connection checking~~
- [ ] ~~Balance~~

**Verified examples from the CLI:**

```plaintext
# Baichuan

RAGFlow(user)> embed text 'walkerwhat' 'jumperwho' with 'Baichuan-Text-Embedding@test@baichuan' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 1024      | 0     |
| 1024      | 1     |
+-----------+-------+

AGFlow(user)> chat with 'Baichuan-M2@test@baichuan' message 'who r u'
Answer: I'm BaiChuan, a helpful AI assistant created by Baichuan-AI. I'm designed to be a knowledgeable, friendly, and reliable assistant for various tasks like answering questions, explaining concepts, writing content, and more. Feel free to ask me anything! 😊
Time: 1.637975

RAGFlow(user)> stream chat with 'Baichuan-M2@test@baichuan' message 'who r u'
Answer: I'm BaiChuan-m2, an AI assistant developed by Baichuan-AI. My purpose is to help you with a wide range of tasks by providing information, answering questions, solving problems, and assisting with creative projects. Think of me as a helpful digital companion! If you have any questions or need assistance, just let me know.😊
Time: 1.692321
```

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants