Repository navigation
Go: implement provider: DeepInfra, XunFei - #14978
Conversation
📝 WalkthroughWalkthroughThis PR introduces two new model providers—XunFei and DeepInfra—into the RAGFlow model ecosystem. Configuration files declare supported models and endpoint metadata. Go implementations provide complete drivers for both providers with chat, streaming, embeddings, audio transcription, and text-to-speech capabilities. The factory dispatch is updated to route both providers. Minor refinements improve region selection and URL handling in existing providers. ChangesXunFei and DeepInfra Model Providers
Sequence Diagram(s)sequenceDiagram
participant Client
participant DeepInfraModel
participant XunFeiModel
participant API as DeepInfra/XunFei API
Client->>DeepInfraModel: ChatWithMessages (non-streaming)
DeepInfraModel->>DeepInfraModel: Select region, build JSON request
DeepInfraModel->>API: POST /chat/completions with Bearer auth
API-->>DeepInfraModel: JSON response with choices[0].message
DeepInfraModel-->>Client: ChatResponse (content + reasoning_content)
Client->>XunFeiModel: ChatStreamlyWithSender (streaming)
XunFeiModel->>XunFeiModel: Select region, build streaming request with thinking
XunFeiModel->>API: POST with Bearer auth
API-->>XunFeiModel: SSE stream
loop Each SSE event
XunFeiModel->>XunFeiModel: Parse data: JSON line
XunFeiModel->>Client: Forward delta.content + delta.reasoning_content
end
XunFeiModel->>Client: Send [DONE] marker
Client->>DeepInfraModel: Embed
DeepInfraModel->>API: POST /embeddings
API-->>DeepInfraModel: Embedding array
DeepInfraModel-->>Client: []EmbeddingData
Client->>DeepInfraModel: TranscribeAudio
DeepInfraModel->>DeepInfraModel: Build multipart form with audio file
DeepInfraModel->>API: POST /transcribe
API-->>DeepInfraModel: {text: ...}
DeepInfraModel-->>Client: ASRResponse
Client->>DeepInfraModel: AudioSpeech (streaming)
DeepInfraModel->>API: POST /tts/stream with Bearer auth
API-->>DeepInfraModel: Audio byte stream
DeepInfraModel->>Client: Forward 4KB chunks via sender callback
DeepInfraModel->>Client: Send [DONE] marker
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly Related PRs
Suggested Labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 9
🤖 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 `@conf/models/xunfei.json`:
- Around line 3-8: The config's URL pieces cause a double-slash and missing
endpoint: change the "url" and "url_suffix" values so the base and suffix
compose properly (e.g., make "url" a proper base like
"https://spark-api-open.xf-yun.com" or remove the trailing slash and ensure each
suffix starts with a leading slash) and add the missing "models" key under
"url_suffix" because xunfei.go expects url_suffix.models; update the "chat" and
any other endpoint entries to match the chosen composition convention so
requests become valid.
In `@internal/entity/models/deepinfra.go`:
- Around line 823-826: The returned map uses the misspelled key "currence" which
breaks the expected schema; update the map literal returned in the function that
returns map[string]interface{} (the block returning {"balance": result.Balance,
"currence": "USD"}) to use the correct key "currency" instead, and run/adjust
any callers or tests that rely on the stable "currency" key to ensure
consistency with other providers.
- Line 135: Guard all pointer dereferences for apiConfig, apiConfig.ApiKey and
modelName before using them (e.g., before calling
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) and
anywhere modelName is dereferenced); if any are nil (or modelName is empty)
return a clear validation error (e.g., fmt.Errorf) instead of allowing a panic.
Update the functions/methods that set the Authorization header and those that
read modelName to perform these nil checks early and return the validation
error, and apply the same guards to the other occurrences noted (the other
dereference sites in this file) to prevent runtime panics.
- Around line 283-287: The code currently logs raw SSE lines via scanner.Scan()
-> line -> common.Info(line), which can leak prompts/responses; update the
streaming handler (the scanner loop reading resp.Body) to stop emitting raw
payloads to common.Info and instead either (a) remove the common.Info call, (b)
log only non-sensitive metadata (e.g., event type, byte count, or "stream chunk
received") or (c) gate full-line logging behind a debug flag so production logs
never contain raw SSE content; adjust the loop that uses scanner, resp.Body, and
common.Info accordingly and ensure any retained logs redact or summarize the
line content rather than printing it verbatim.
- Around line 420-423: In the Embed function remove the unreachable duplicate
return: there are two consecutive "return embeddings, nil" statements (one at
the end of Embed and an immediate duplicate after it); delete the second one so
Embed only returns once (keep the first return in the Embed function).
In `@internal/entity/models/xunfei.go`:
- Around line 338-376: Replace the panic stubs in XunFeiModel's unsupported
methods (Embed, Rerank, TranscribeAudio, TranscribeAudioWithSender, AudioSpeech,
AudioSpeechWithSender, OCRFile, ParseFile) with a consistent error return like
other providers: return nil, fmt.Errorf("%s no such method", x.Name()) (or the
appropriate nil/zero return values matching each method signature), so calling
these unsupported capabilities doesn't crash the process.
- Around line 425-427: In ListModels, avoid unchecked type assertions on
result["data"] and nested elements: first verify result is a
map[string]interface{}, then check result["data"] exists and is a []interface{}
(handle missing or wrong types by returning a clear error), then for each item
assert it is a map[string]interface{} before accessing modelMap["id"] and
confirm modelMap["id"] is a string; update the loop that currently uses
result["data"].([]interface{}) and
model.(map[string]interface{})/modelMap["id"].(string) to use safe, ok-style
assertions and return structured errors when types are unexpected.
- Around line 270-274: The loop that reads SSE chunks logs raw payloads via
common.Info(line), risking sensitive-data leakage; update the scanner loop (the
code using scanner, resp.Body and common.Info) to stop logging raw lines —
either remove the common.Info call entirely or replace it with a safe/loggable
alternative that does not include message content (e.g., log only metadata such
as chunk length, sequence number, or a redacted/sanitized version via a new
helper like redactSensitive) and ensure any debug logging is gated behind a
strict debug/trace flag.
- Around line 125-126: Guard pointer and slice accesses to avoid panics: check
that apiConfig is not nil and apiConfig.ApiKey is non-nil/non-empty before using
*apiConfig.ApiKey (used where req.Header.Set("Authorization",
fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) is called), and check that choices
is non-nil and len(choices) > 0 before accessing choices[0] (and similar
accesses around lines 144-150, 256-257, 400-401). If any of these guards fail,
return a proper driver error from the surrounding function (the callers that
build the request/parse responses), rather than dereferencing nil pointers or
out-of-range slices. Ensure all occurrences in xunfei.go use the same nil/empty
checks and consistent error returns.
🪄 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: 20fe97ab-f747-4879-855b-1ce78aeb1042
📒 Files selected for processing (8)
conf/models/deepinfra.jsonconf/models/xunfei.jsoninternal/entity/models/deepinfra.gointernal/entity/models/factory.gointernal/entity/models/minimax.gointernal/entity/models/openrouter.gointernal/entity/models/siliconflow.gointernal/entity/models/xunfei.go
| "url": { | ||
| "default": "https://" | ||
| }, | ||
| "url_suffix": { | ||
| "chat": "spark-api-open.xf-yun.com/v2/chat/completions" | ||
| }, |
There was a problem hiding this comment.
Fix URL composition for XunFei endpoints.
This config is incompatible with the current URL builder: default = "https://" plus chat = "spark-api-open.xf-yun.com/..." produces https:///spark-api-open..., which results in invalid requests. Also, xunfei.go reads url_suffix.models, but it is missing here.
🤖 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 `@conf/models/xunfei.json` around lines 3 - 8, The config's URL pieces cause a
double-slash and missing endpoint: change the "url" and "url_suffix" values so
the base and suffix compose properly (e.g., make "url" a proper base like
"https://spark-api-open.xf-yun.com" or remove the trailing slash and ensure each
suffix starts with a leading slash) and add the missing "models" key under
"url_suffix" because xunfei.go expects url_suffix.models; update the "chat" and
any other endpoint entries to match the chosen composition convention so
requests become valid.
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Add nil guards before dereferencing config/model pointers.
These dereferences can panic when apiConfig, apiConfig.ApiKey, or modelName is nil. Return validation errors instead of panicking on malformed inputs.
Also applies to: 269-269, 364-364, 383-383
🤖 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/deepinfra.go` at line 135, Guard all pointer
dereferences for apiConfig, apiConfig.ApiKey and modelName before using them
(e.g., before calling req.Header.Set("Authorization", fmt.Sprintf("Bearer %s",
*apiConfig.ApiKey)) and anywhere modelName is dereferenced); if any are nil (or
modelName is empty) return a clear validation error (e.g., fmt.Errorf) instead
of allowing a panic. Update the functions/methods that set the Authorization
header and those that read modelName to perform these nil checks early and
return the validation error, and apply the same guards to the other occurrences
noted (the other dereference sites in this file) to prevent runtime panics.
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| common.Info(line) | ||
|
|
There was a problem hiding this comment.
Avoid logging raw SSE payload lines in production paths.
This logs model stream content directly, which can leak prompts/responses (PII or secrets) into logs.
🤖 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/deepinfra.go` around lines 283 - 287, The code
currently logs raw SSE lines via scanner.Scan() -> line -> common.Info(line),
which can leak prompts/responses; update the streaming handler (the scanner loop
reading resp.Body) to stop emitting raw payloads to common.Info and instead
either (a) remove the common.Info call, (b) log only non-sensitive metadata
(e.g., event type, byte count, or "stream chunk received") or (c) gate full-line
logging behind a debug flag so production logs never contain raw SSE content;
adjust the loop that uses scanner, resp.Body, and common.Info accordingly and
ensure any retained logs redact or summarize the line content rather than
printing it verbatim.
| return embeddings, nil | ||
|
|
||
| return embeddings, nil | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify duplicate return sites in DeepInfra Embed implementation
rg -n 'return embeddings, nil' internal/entity/models/deepinfra.goRepository: infiniflow/ragflow
Length of output: 118
🏁 Script executed:
sed -n '410,425p' internal/entity/models/deepinfra.goRepository: infiniflow/ragflow
Length of output: 482
Remove unreachable duplicate return statement in Embed function.
Line 422 contains a duplicate return embeddings, nil immediately after the first return on line 420, making it unreachable. Delete the duplicate return statement.
🤖 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/deepinfra.go` around lines 420 - 423, In the Embed
function remove the unreachable duplicate return: there are two consecutive
"return embeddings, nil" statements (one at the end of Embed and an immediate
duplicate after it); delete the second one so Embed only returns once (keep the
first return in the Embed function).
| return map[string]interface{}{ | ||
| "balance": result.Balance, | ||
| "currence": "USD", | ||
| }, nil |
There was a problem hiding this comment.
Fix balance currency key typo.
"currence" is inconsistent with other providers’ "currency" key and can break consumers expecting a stable schema.
🤖 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/deepinfra.go` around lines 823 - 826, The returned map
uses the misspelled key "currence" which breaks the expected schema; update the
map literal returned in the function that returns map[string]interface{} (the
block returning {"balance": result.Balance, "currence": "USD"}) to use the
correct key "currency" instead, and run/adjust any callers or tests that rely on
the stable "currency" key to ensure consistency with other providers.
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
There was a problem hiding this comment.
Guard auth/config pointers and empty choices before access.
These paths can panic (*apiConfig.ApiKey, choices[0]) instead of returning normal driver errors.
Also applies to: 144-150, 256-257, 400-401
🤖 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/xunfei.go` around lines 125 - 126, Guard pointer and
slice accesses to avoid panics: check that apiConfig is not nil and
apiConfig.ApiKey is non-nil/non-empty before using *apiConfig.ApiKey (used where
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) is
called), and check that choices is non-nil and len(choices) > 0 before accessing
choices[0] (and similar accesses around lines 144-150, 256-257, 400-401). If any
of these guards fail, return a proper driver error from the surrounding function
(the callers that build the request/parse responses), rather than dereferencing
nil pointers or out-of-range slices. Ensure all occurrences in xunfei.go use the
same nil/empty checks and consistent error returns.
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| common.Info(line) | ||
|
|
There was a problem hiding this comment.
Avoid logging raw SSE payload lines.
Streaming lines contain model output and can leak sensitive user data to logs.
🤖 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/xunfei.go` around lines 270 - 274, The loop that reads
SSE chunks logs raw payloads via common.Info(line), risking sensitive-data
leakage; update the scanner loop (the code using scanner, resp.Body and
common.Info) to stop logging raw lines — either remove the common.Info call
entirely or replace it with a safe/loggable alternative that does not include
message content (e.g., log only metadata such as chunk length, sequence number,
or a redacted/sanitized version via a new helper like redactSensitive) and
ensure any debug logging is gated behind a strict debug/trace flag.
| func (x *XunFeiModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } | ||
|
|
||
| func (x *XunFeiModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } | ||
|
|
||
| func (x *XunFeiModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } | ||
|
|
||
| func (x *XunFeiModel) TranscribeAudioWithSender(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, sender func(*string, *string) error) error { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } | ||
|
|
||
| func (x *XunFeiModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } | ||
|
|
||
| func (x *XunFeiModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } | ||
|
|
||
| func (x *XunFeiModel) OCRFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, ocrConfig *OCRConfig) (*OCRFileResponse, error) { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } | ||
|
|
||
| func (x *XunFeiModel) ParseFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig) (*ParseFileResponse, error) { | ||
| //TODO implement me | ||
| panic("implement me") | ||
| } |
There was a problem hiding this comment.
Do not leave interface methods as panic("implement me").
These panics can crash the process when unsupported capabilities are called. Return fmt.Errorf("%s no such method", x.Name()) like other providers.
Also applies to: 434-452
🤖 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/xunfei.go` around lines 338 - 376, Replace the panic
stubs in XunFeiModel's unsupported methods (Embed, Rerank, TranscribeAudio,
TranscribeAudioWithSender, AudioSpeech, AudioSpeechWithSender, OCRFile,
ParseFile) with a consistent error return like other providers: return nil,
fmt.Errorf("%s no such method", x.Name()) (or the appropriate nil/zero return
values matching each method signature), so calling these unsupported
capabilities doesn't crash the process.
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) |
There was a problem hiding this comment.
Harden ListModels response parsing before type assertions.
result["data"].([]interface{}) and nested assertions will panic on API errors or schema drift. Add checked assertions and return structured errors.
🤖 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/xunfei.go` around lines 425 - 427, In ListModels,
avoid unchecked type assertions on result["data"] and nested elements: first
verify result is a map[string]interface{}, then check result["data"] exists and
is a []interface{} (handle missing or wrong types by returning a clear error),
then for each item assert it is a map[string]interface{} before accessing
modelMap["id"] and confirm modelMap["id"] is a string; update the loop that
currently uses result["data"].([]interface{}) and
model.(map[string]interface{})/modelMap["id"].(string) to use safe, ok-style
assertions and return structured errors when types are unexpected.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14978 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
This PR implement implement provider and Mistral, DeepInfra, XunFei
The following functionalities are now supported:
DeepInfra
RerankXunFei
Type of change