Skip to content

Go: implement provider: DeepInfra, XunFei - #14978

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main
May 18, 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 implement implement provider and Mistral, DeepInfra, XunFei

The following functionalities are now supported:

DeepInfra

  • chat / think chat / stream chat / stream think chat
  • Embedding
  • ASR
  • TTS
  • ListModels
  • Provider connection checking
  • Balance
  • Rerank

XunFei

  • chat / think chat / stream chat / stream think chat

Type of change

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

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label May 18, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels May 18, 2026
@Haruko386
Haruko386 marked this pull request as draft May 18, 2026 08:27
@Haruko386
Haruko386 marked this pull request as ready for review May 18, 2026 08:27
@coderabbitai

coderabbitai Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

XunFei and DeepInfra Model Providers

Layer / File(s) Summary
Model Provider Configuration
conf/models/deepinfra.json, conf/models/xunfei.json
Configuration files declare provider metadata (base URLs, endpoint suffixes for chat/embeddings/ASR/TTS) and supported model entries with token limits and optional thinking/reasoning settings for both XunFei and DeepInfra providers.
DeepInfra Model Driver Implementation
internal/entity/models/deepinfra.go
Complete driver with HTTP client, region-based URL selection, structured chat (non-streaming and SSE streaming with reasoning content), embeddings, multipart ASR, TTS (streaming and non-streaming), model listing, balance queries, and stub methods for unsupported operations.
XunFei Model Driver Implementation
internal/entity/models/xunfei.go
Complete driver with HTTP client, region-based URL selection, structured chat with thinking support (non-streaming and SSE streaming), model listing, and stub methods for embeddings, audio, OCR, and administrative operations.
Provider Factory Integration
internal/entity/models/factory.go
Factory's CreateModelDriver switch extended with cases for "xunfei" and "deepinfra" provider names, routing to their respective constructors.
Existing Provider Refinements
internal/entity/models/minimax.go, internal/entity/models/openrouter.go, internal/entity/models/siliconflow.go
Minimax region selection now validates non-empty Region; OpenRouter reasoning field conditionally included when Effort config provided; SiliconFlow streaming endpoint URL uses configured suffix instead of hardcoded path.

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
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

  • infiniflow/ragflow#14623: Both PRs modify internal/entity/models/factory.go to route newly added provider drivers through the same switch statement.
  • infiniflow/ragflow#14838: Both PRs update factory dispatch in internal/entity/models/factory.go to register new model drivers at the provider routing level.
  • infiniflow/ragflow#14652: Both PRs implement SSE-based streaming chat with incremental content/reasoning forwarding, with overlapping changes to internal/entity/models/openrouter.go.

Suggested Labels

💞 feature, ☯️ refactor, size:XL

Poem

🐰 Two new providers hop into the fold,
XunFei and DeepInfra, bold and swift,
SSE streams flow with reasoning and thought,
Chat, embeddings, voices—a comprehensive gift.
The factory routes them true, no longer left bereft,
RAGFlow now richer, with each model's heft! 🚀

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: implementing two new provider integrations (DeepInfra and XunFei) in Go.
Description check ✅ Passed The description covers the problem statement, lists supported functionalities for both providers, and specifies the change type. However, it mentions 'Mistral' in the opening sentence despite no Mistral changes in the PR files, and contains a typo ('implement implement').
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.

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label May 18, 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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 13b4220 and a6b0984.

📒 Files selected for processing (8)
  • conf/models/deepinfra.json
  • conf/models/xunfei.json
  • internal/entity/models/deepinfra.go
  • internal/entity/models/factory.go
  • internal/entity/models/minimax.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/xunfei.go

Comment thread conf/models/xunfei.json
Comment on lines +3 to +8
"url": {
"default": "https://"
},
"url_suffix": {
"chat": "spark-api-open.xf-yun.com/v2/chat/completions"
},

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

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))

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

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.

Comment on lines +283 to +287
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
common.Info(line)

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 | 🟠 Major | ⚡ Quick win

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.

Comment on lines +420 to +423
return embeddings, nil

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify duplicate return sites in DeepInfra Embed implementation
rg -n 'return embeddings, nil' internal/entity/models/deepinfra.go

Repository: infiniflow/ragflow

Length of output: 118


🏁 Script executed:

sed -n '410,425p' internal/entity/models/deepinfra.go

Repository: 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).

Comment on lines +823 to +826
return map[string]interface{}{
"balance": result.Balance,
"currence": "USD",
}, 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

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.

Comment on lines +125 to +126
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))

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

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.

Comment on lines +270 to +274
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
common.Info(line)

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 | 🟠 Major | ⚡ Quick win

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.

Comment on lines +338 to +376
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")
}

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

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.

Comment on lines +425 to +427
for _, model := range result["data"].([]interface{}) {
modelMap := model.(map[string]interface{})
modelName := modelMap["id"].(string)

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 | 🟠 Major | ⚡ Quick win

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

codecov Bot commented May 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (b40b0bf) to head (a6b0984).
⚠️ Report is 3 commits behind head on main.

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.
📢 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 size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants