Skip to content

Go: implement ASR and TTS for Xinference - #15096

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:main
May 21, 2026
Merged

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

Conversation

@Haruko386

@Haruko386 Haruko386 commented May 21, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

implement ASR and TTS for Xinference

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 21, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 21, 2026
@Haruko386
Haruko386 marked this pull request as draft May 21, 2026 06:21
@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 132be390-ccd2-4485-84be-5ab914ce8524

📥 Commits

Reviewing files that changed from the base of the PR and between 80add8a and f317985.

📒 Files selected for processing (1)
  • test/testcases/restful_api/test_dify_retrieval_routes_unit.py

📝 Walkthrough

Walkthrough

Implements Novita balance querying and config, adds Xinference ASR/TTS, fixes Moonshot chat URL and region checks, simplifies FishAudio error formatting, and updates document-service test stubs.

Changes

Provider Feature Implementation and Fixes

Layer / File(s) Summary
Moonshot URL and region handling fixes
internal/entity/models/moonshot.go
ChatStreamlyWithSender uses URLSuffix.Chat with BaseURL[region] and guards chatModelConfig overrides; ListModels and Balance require apiConfig.Region != nil && *apiConfig.Region != "" before using region.
Novita Balance endpoint implementation
conf/models/novita.json, internal/entity/models/novita.go
Adds url_suffix.balance and implements NovitaModel.Balance: region selection, GET to BaseURL[region]+URLSuffix.Balance with Bearer auth, require HTTP 200, parse availableBalance string to float64, return {"balance": <float>, "currency":"USD"} with explicit error messages.
Xinference TranscribeAudio and AudioSpeech implementations
internal/entity/models/xinference.go
Adds multipart/form-data and file/path/strconv imports; implements TranscribeAudio to upload audio and typed ASR params to URLSuffix.ASR and parse JSON text; implements AudioSpeech to POST JSON to URLSuffix.TTS with optional TTS params/format and return raw audio bytes.
FishAudio error handling simplification
internal/entity/models/fishaudio.go
Non-200 HTTP error handling in TranscribeAudio changed to a single-line fmt.Errorf including resp.Status and response body.
Test stub adjustments
test/unit_test/api/apps/sdk/test_dify_retrieval.py, test/testcases/restful_api/test_dify_retrieval_routes_unit.py
DocumentService.get_by_id test stub now returns an object with id and meta_fields; another test was updated to mock get_by_ids returning per-doc meta_fields.origin.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14926: Modifies internal/entity/models/fishaudio.go and overlaps on TranscribeAudio error handling.

Suggested reviewers

  • JinHai-CN
  • yuzhichang

Poem

🐰 I hop through code, a tiny guide,
Novita counts what wallets hide,
Xinference listens, speaks in tune,
Moonshot steers the streaming rune,
FishAudio trims errors—short and wide.

🚥 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 ASR and TTS functionality for Xinference in Go, which aligns with the primary changes in xinference.go.
Description check ✅ Passed The description follows the required template with both sections completed, though the 'What problem does this PR solve?' section is minimal and lacks detailed context about the purpose and rationale.
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 21, 2026 06:21

@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: 6

🤖 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/novita.go`:
- Around line 854-862: Remove the unnecessary empty JSON body and add a
per-request timeout using context.WithTimeout: drop the reqBody/json.Marshal
block and create the request with http.NewRequestWithContext(ctx, "GET", url,
nil) where ctx is created from context.WithTimeout(context.Background(),
nonStreamCallTimeout) (remember to defer cancel()). Update any subsequent uses
of req to use this new req and leave the client call (e.g., httpClient.Do)
unchanged; reference the existing nonStreamCallTimeout symbol and replace
http.NewRequest invocation with http.NewRequestWithContext and the removed
jsonMarshal logic.
- Around line 846-868: The Balance method (NovitaModel.Balance) is missing
nil-safety for apiConfig and ApiKey; add an early guard that returns an error if
apiConfig == nil, then validate apiConfig.ApiKey != nil and non-empty before
dereferencing, and only read apiConfig.Region after confirming apiConfig is
non-nil; update the function to perform these checks and return descriptive
errors rather than allowing a nil pointer panic when accessing apiConfig.Region
or *apiConfig.ApiKey.
- Line 852: Replace the direct map access n.BaseURL[region] when building url
with the baseURLForRegion(region) helper used elsewhere to validate region
existence; call baseURLForRegion(region) and handle the returned error, then use
the returned base URL combined with n.URLSuffix.Balance to construct the url
variable so you never build a malformed URL from a missing region.

In `@internal/entity/models/xinference.go`:
- Around line 659-668: The POST request in xinference.go creates req with
http.NewRequest and calls x.httpClient.Do without a timeout; wrap the call in a
context.WithTimeout (use the existing nonStreamCallTimeout or a larger duration
for audio transcription), create the request with
http.NewRequestWithContext(ctx, "POST", url, &body), ensure you call cancel()
after the request, and keep the existing header and Do call using
x.httpClient.Do(req) so the request respects the deadline; update any imports if
necessary to include context.
- Around line 596-605: Add nil checks for apiConfig and apiConfig.ApiKey at the
start of the ASR flow in xinference.go (the block that builds url using
x.BaseURL[region] and later reads *apiConfig.ApiKey) to avoid nil pointer
dereferences; mirror the validation pattern used in
FishAudioModel.TranscribeAudio by returning an error if apiConfig is nil or if
apiConfig.ApiKey is nil/empty before accessing apiConfig.Region or
*apiConfig.ApiKey, then proceed to compute region and url only after those
checks pass.
- Around line 701-738: In XinferenceModel.AudioSpeech ensure nil-safety and add
a request timeout: validate apiConfig is non-nil before accessing
apiConfig.Region and apiConfig.ApiKey, validate modelName is non-nil and
non-empty before dereferencing, use baseURLForRegion(region, x.BaseURL,
x.URLSuffix) (or call the existing baseURLForRegion helper) instead of direct
x.BaseURL[region] access, and create the HTTP request with a context that has a
timeout (use context.WithTimeout and http.NewRequestWithContext) so the call is
cancellable; return clear errors when required values are missing (e.g.,
apiConfig or ApiKey or modelName).
🪄 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: 2bc7542b-d5f1-46f1-8352-815e12cb8038

📥 Commits

Reviewing files that changed from the base of the PR and between 17bcc3f and a37e02c.

📒 Files selected for processing (5)
  • conf/models/novita.json
  • internal/entity/models/fishaudio.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/novita.go
  • internal/entity/models/xinference.go

Comment on lines 846 to +868
func (n *NovitaModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
return nil, fmt.Errorf("%s, no such method", n.Name())
var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

url := fmt.Sprintf("%s/%s", n.BaseURL[region], n.URLSuffix.Balance)

// Build request body
reqBody := map[string]interface{}{}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

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

Missing nil-safety checks will cause panics.

The Balance method lacks the validation guards present in other methods in this file:

  1. Line 848: Accesses apiConfig.Region without checking if apiConfig is nil first
  2. Line 868: Dereferences *apiConfig.ApiKey without checking if ApiKey is nil

Both will cause nil pointer panics when callers pass nil or incomplete config.

🐛 Proposed fix to add validation
 func (n *NovitaModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is required")
+	}
+
 	var region = "default"
 	if apiConfig.Region != nil && *apiConfig.Region != "" {
 		region = *apiConfig.Region
 	}
🤖 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/novita.go` around lines 846 - 868, The Balance method
(NovitaModel.Balance) is missing nil-safety for apiConfig and ApiKey; add an
early guard that returns an error if apiConfig == nil, then validate
apiConfig.ApiKey != nil and non-empty before dereferencing, and only read
apiConfig.Region after confirming apiConfig is non-nil; update the function to
perform these checks and return descriptive errors rather than allowing a nil
pointer panic when accessing apiConfig.Region or *apiConfig.ApiKey.

region = *apiConfig.Region
}

url := fmt.Sprintf("%s/%s", n.BaseURL[region], n.URLSuffix.Balance)

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

Use baseURLForRegion helper for consistent validation.

Direct map access n.BaseURL[region] returns empty string for missing regions, producing malformed URLs. Other methods in this file use baseURLForRegion(region) which validates the region exists and returns a clear error.

🔧 Proposed fix
-	url := fmt.Sprintf("%s/%s", n.BaseURL[region], n.URLSuffix.Balance)
+	baseURL, err := n.baseURLForRegion(region)
+	if err != nil {
+		return nil, err
+	}
+	url := fmt.Sprintf("%s/%s", baseURL, n.URLSuffix.Balance)
🤖 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/novita.go` at line 852, Replace the direct map access
n.BaseURL[region] when building url with the baseURLForRegion(region) helper
used elsewhere to validate region existence; call baseURLForRegion(region) and
handle the returned error, then use the returned base URL combined with
n.URLSuffix.Balance to construct the url variable so you never build a malformed
URL from a missing region.

Comment on lines +854 to +862
// Build request body
reqBody := map[string]interface{}{}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))

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

Add request timeout and remove unnecessary body.

  1. GET requests don't need a body - the empty JSON is unnecessary overhead
  2. Missing context.WithTimeout means the request could hang indefinitely (other methods use nonStreamCallTimeout)
🔧 Proposed fix
-	// Build request body
-	reqBody := map[string]interface{}{}
-
-	jsonData, err := json.Marshal(reqBody)
-	if err != nil {
-		return nil, fmt.Errorf("failed to marshal request: %w", err)
-	}
-
-	req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))
+	ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+	defer cancel()
+
+	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)

Based on learnings: When httpClient.Timeout is unset but transport.ResponseHeaderTimeout is configured, using context.WithTimeout per request as the sole overall deadline is legitimate.

🤖 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/novita.go` around lines 854 - 862, Remove the
unnecessary empty JSON body and add a per-request timeout using
context.WithTimeout: drop the reqBody/json.Marshal block and create the request
with http.NewRequestWithContext(ctx, "GET", url, nil) where ctx is created from
context.WithTimeout(context.Background(), nonStreamCallTimeout) (remember to
defer cancel()). Update any subsequent uses of req to use this new req and leave
the client call (e.g., httpClient.Do) unchanged; reference the existing
nonStreamCallTimeout symbol and replace http.NewRequest invocation with
http.NewRequestWithContext and the removed jsonMarshal logic.

Comment on lines +596 to +605
if file == nil || *file == "" {
return nil, fmt.Errorf("file is missing")
}

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

url := fmt.Sprintf("%s/%s", x.BaseURL[region], x.URLSuffix.ASR)

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

Nil pointer dereferences: validate apiConfig before access.

Line 601 dereferences apiConfig.Region without checking if apiConfig is nil. Line 665 dereferences *apiConfig.ApiKey without nil checks on both apiConfig and ApiKey. Compare with FishAudioModel.TranscribeAudio which validates these at the start.

🐛 Proposed fix
 func (x *XinferenceModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("xinference: API key is missing")
+	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
 	if file == nil || *file == "" {
 		return nil, fmt.Errorf("file is missing")
 	}
 
-	region := "default"
-	if apiConfig.Region != nil && *apiConfig.Region != "" {
-		region = *apiConfig.Region
-	}
-
-	url := fmt.Sprintf("%s/%s", x.BaseURL[region], x.URLSuffix.ASR)
+	baseURL, err := x.baseURLForRegion(xinferenceRegion(apiConfig))
+	if err != nil {
+		return nil, err
+	}
+	url := fmt.Sprintf("%s/%s", baseURL, x.URLSuffix.ASR)
🤖 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/xinference.go` around lines 596 - 605, Add nil checks
for apiConfig and apiConfig.ApiKey at the start of the ASR flow in xinference.go
(the block that builds url using x.BaseURL[region] and later reads
*apiConfig.ApiKey) to avoid nil pointer dereferences; mirror the validation
pattern used in FishAudioModel.TranscribeAudio by returning an error if
apiConfig is nil or if apiConfig.ApiKey is nil/empty before accessing
apiConfig.Region or *apiConfig.ApiKey, then proceed to compute region and url
only after those checks pass.

Comment on lines +659 to +668
// request
req, err := http.NewRequest("POST", url, &body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
req.Header.Set("Content-Type", writer.FormDataContentType())

resp, err := x.httpClient.Do(req)

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

Missing request timeout context.

Other methods in this file use context.WithTimeout for request deadlines. Since httpClient.Timeout is not set, this request could hang indefinitely. Audio transcription of large files may need a longer timeout than the default nonStreamCallTimeout.

🛡️ Proposed fix
-	// request
-	req, err := http.NewRequest("POST", url, &body)
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+	defer cancel()
+
+	req, err := http.NewRequestWithContext(ctx, "POST", url, &body)
📝 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
// request
req, err := http.NewRequest("POST", url, &body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := x.httpClient.Do(req)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", url, &body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := x.httpClient.Do(req)
🤖 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/xinference.go` around lines 659 - 668, The POST
request in xinference.go creates req with http.NewRequest and calls
x.httpClient.Do without a timeout; wrap the call in a context.WithTimeout (use
the existing nonStreamCallTimeout or a larger duration for audio transcription),
create the request with http.NewRequestWithContext(ctx, "POST", url, &body),
ensure you call cancel() after the request, and keep the existing header and Do
call using x.httpClient.Do(req) so the request respects the deadline; update any
imports if necessary to include context.

Comment on lines +701 to +738
func (x *XinferenceModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("text content is missing")
}

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

url := fmt.Sprintf("%s/%s", x.BaseURL[region], x.URLSuffix.TTS)

reqBody := map[string]interface{}{
"model": *modelName,
"input": *audioContent,
}

if ttsConfig != nil && ttsConfig.Params != nil {
for key, value := range ttsConfig.Params {
reqBody[key] = value
}
}
if ttsConfig != nil && ttsConfig.Format != "" {
reqBody["format"] = ttsConfig.Format
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

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

Same nil-safety and timeout issues as TranscribeAudio.

This method has identical issues:

  • Line 707: apiConfig.Region accessed without checking if apiConfig is nil
  • Line 714: *modelName dereferenced without validation
  • Line 738: *apiConfig.ApiKey without nil checks
  • Line 711: Direct BaseURL[region] access bypasses baseURLForRegion() fallback logic
  • Line 732: Missing context timeout
🐛 Proposed fix
 func (x *XinferenceModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("xinference: API key is missing")
+	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
 	if audioContent == nil || *audioContent == "" {
 		return nil, fmt.Errorf("text content is missing")
 	}
 
-	var region = "default"
-	if apiConfig.Region != nil && *apiConfig.Region != "" {
-		region = *apiConfig.Region
-	}
-
-	url := fmt.Sprintf("%s/%s", x.BaseURL[region], x.URLSuffix.TTS)
+	baseURL, err := x.baseURLForRegion(xinferenceRegion(apiConfig))
+	if err != nil {
+		return nil, err
+	}
+	url := fmt.Sprintf("%s/%s", baseURL, x.URLSuffix.TTS)
 
 	reqBody := map[string]interface{}{
 		"model": *modelName,

And for the request creation:

-	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+	ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+	defer cancel()
+
+	req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
🤖 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/xinference.go` around lines 701 - 738, In
XinferenceModel.AudioSpeech ensure nil-safety and add a request timeout:
validate apiConfig is non-nil before accessing apiConfig.Region and
apiConfig.ApiKey, validate modelName is non-nil and non-empty before
dereferencing, use baseURLForRegion(region, x.BaseURL, x.URLSuffix) (or call the
existing baseURLForRegion helper) instead of direct x.BaseURL[region] access,
and create the HTTP request with a context that has a timeout (use
context.WithTimeout and http.NewRequestWithContext) so the call is cancellable;
return clear errors when required values are missing (e.g., apiConfig or ApiKey
or modelName).

@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: 4

♻️ Duplicate comments (2)
internal/entity/models/xinference.go (2)

659-668: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add an overall deadline to these audio HTTP calls.

These requests use http.NewRequest without a context, and this client only has ResponseHeaderTimeout. A stalled upload or response-body read can still block indefinitely here; use http.NewRequestWithContext with an audio-appropriate timeout.

🛡️ Minimal change
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
- req, err := http.NewRequest("POST", url, &body)
+ req, err := http.NewRequestWithContext(ctx, "POST", url, &body)

Based on learnings: if httpClient.Timeout is intentionally unset and only transport.ResponseHeaderTimeout is configured, context.WithTimeout per request is the right place to enforce the overall deadline.

Also applies to: 732-740

🤖 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/xinference.go` around lines 659 - 668, The POST
requests that build req with http.NewRequest should use a context with a
deadline to enforce an overall timeout for audio uploads/reads: create a ctx,
cancel := context.WithTimeout(context.Background(), <audioTimeout>) and defer
cancel(), then call http.NewRequestWithContext(ctx, "POST", url, &body) instead
of http.NewRequest; keep the existing header setup and x.httpClient.Do(req)
unchanged. Apply the same change to the second request block around lines
732-740 so both request constructions (the one that creates req and the other
similar block) use context.WithTimeout and http.NewRequestWithContext to bound
stalled uploads or response-body reads.

595-666: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Use the shared Xinference helpers here instead of dereferencing config directly.

Both methods can panic on nil apiConfig/modelName, and x.BaseURL[region] + manual Authorization skips the normalization, default fallback, and optional-auth behavior the rest of this driver already uses.

🐛 Minimal pattern to apply in both methods
+ if modelName == nil || *modelName == "" {
+ 	return nil, fmt.Errorf("model name is required")
+ }
- region := "default"
- if apiConfig.Region != nil && *apiConfig.Region != "" {
- 	region = *apiConfig.Region
- }
- url := fmt.Sprintf("%s/%s", x.BaseURL[region], x.URLSuffix.ASR)
+ baseURL, err := x.baseURLForRegion(xinferenceRegion(apiConfig))
+ if err != nil {
+ 	return nil, err
+ }
+ url := fmt.Sprintf("%s/%s", baseURL, x.URLSuffix.ASR)
...
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+ setXinferenceAuth(req, apiConfig)

Also applies to: 701-738

🤖 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/xinference.go` around lines 595 - 666, TranscribeAudio
on XinferenceModel dereferences apiConfig and modelName and manually builds
URL/Authorization (x.BaseURL[region], x.URLSuffix.ASR, apiConfig.ApiKey), which
can panic and bypass existing normalization and optional-auth logic; fix by
guarding nil for modelName and apiConfig, then use the shared Xinference helper
methods to resolve URL and auth (e.g., call the XinferenceModel helper that
normalizes APIConfig/region and returns the endpoint for x.URLSuffix.ASR and the
helper that sets auth headers on an *http.Request) instead of directly indexing
x.BaseURL or setting Authorization manually, and keep the rest of the multipart
logic unchanged; also apply the same pattern to the other ASR method referenced
in the review.
🤖 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/moonshot.go`:
- Around line 369-370: ListModels and Balance currently dereference
apiConfig.Region without checking apiConfig, which can cause a panic when
apiConfig is nil; update both methods (ListModels and Balance) to first guard
against a nil apiConfig (e.g., if apiConfig == nil { /* set region default or
skip region logic */ }) before accessing apiConfig.Region, then only read
*apiConfig.Region when apiConfig != nil and apiConfig.Region != nil and
non-empty; make the same nil-check change at the other occurrence referenced in
the review.
- Around line 232-234: The method ChatStreamlyWithSender currently copies
chatModelConfig.Stream into the request body which allows Stream=false and
causes the client to treat a non-stream response as SSE; force streaming by
always setting reqBody["stream"]=true (ignore or override
chatModelConfig.Stream) so the request is explicitly streaming, and remove/avoid
the conditional that writes the possibly-false value from
chatModelConfig.Stream.

In `@internal/entity/models/xinference.go`:
- Around line 679-680: The error message in the HTTP response handling
incorrectly references "FishAudio ASR error"; locate the non-OK response branch
inside the Xinference driver (the block checking if resp.StatusCode !=
http.StatusOK) and change the fmt.Errorf call to use the correct provider name
(e.g., "Xinference ASR error") or the driver/provider identifier used elsewhere
(use the driver struct's name/const if available) so the error message points to
the Xinference integration instead of FishAudio.
- Around line 607-623: The current implementation builds the multipart payload
in memory by using bytes.Buffer with multipart.NewWriter(&body) and
io.Copy(part, audioFile); refactor to stream the upload using io.Pipe: create
pr, pw := io.Pipe(), start a goroutine that creates multipart.NewWriter(pw),
calls CreateFormFile("file", filepath.Base(*file)) and io.Copy(part, audioFile)
(closing the writer and pw on completion or error), and pass pr as the HTTP
request body so the request streams directly from disk without buffering the
entire file; update any error handling around audioFile, the multipart writer,
and the pipe to close/propagate errors correctly.

---

Duplicate comments:
In `@internal/entity/models/xinference.go`:
- Around line 659-668: The POST requests that build req with http.NewRequest
should use a context with a deadline to enforce an overall timeout for audio
uploads/reads: create a ctx, cancel := context.WithTimeout(context.Background(),
<audioTimeout>) and defer cancel(), then call http.NewRequestWithContext(ctx,
"POST", url, &body) instead of http.NewRequest; keep the existing header setup
and x.httpClient.Do(req) unchanged. Apply the same change to the second request
block around lines 732-740 so both request constructions (the one that creates
req and the other similar block) use context.WithTimeout and
http.NewRequestWithContext to bound stalled uploads or response-body reads.
- Around line 595-666: TranscribeAudio on XinferenceModel dereferences apiConfig
and modelName and manually builds URL/Authorization (x.BaseURL[region],
x.URLSuffix.ASR, apiConfig.ApiKey), which can panic and bypass existing
normalization and optional-auth logic; fix by guarding nil for modelName and
apiConfig, then use the shared Xinference helper methods to resolve URL and auth
(e.g., call the XinferenceModel helper that normalizes APIConfig/region and
returns the endpoint for x.URLSuffix.ASR and the helper that sets auth headers
on an *http.Request) instead of directly indexing x.BaseURL or setting
Authorization manually, and keep the rest of the multipart logic unchanged; also
apply the same pattern to the other ASR method referenced in the review.
🪄 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: 6f652c88-4022-4e0e-801d-b308251ec235

📥 Commits

Reviewing files that changed from the base of the PR and between a37e02c and 5277baf.

📒 Files selected for processing (5)
  • conf/models/novita.json
  • internal/entity/models/fishaudio.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/novita.go
  • internal/entity/models/xinference.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/novita.json

Comment on lines +232 to +234
if chatModelConfig.Stream != nil {
reqBody["stream"] = *chatModelConfig.Stream
}

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

Enforce streaming mode in ChatStreamlyWithSender.

Allowing chatModelConfig.Stream=false here makes the method parse a non-stream response as SSE and can return an empty streamed result.

🔧 Suggested fix
-		if chatModelConfig.Stream != nil {
-			reqBody["stream"] = *chatModelConfig.Stream
-		}
+		if chatModelConfig.Stream != nil && !*chatModelConfig.Stream {
+			return fmt.Errorf("stream must be true in ChatStreamlyWithSender")
+		}
🤖 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/moonshot.go` around lines 232 - 234, The method
ChatStreamlyWithSender currently copies chatModelConfig.Stream into the request
body which allows Stream=false and causes the client to treat a non-stream
response as SSE; force streaming by always setting reqBody["stream"]=true
(ignore or override chatModelConfig.Stream) so the request is explicitly
streaming, and remove/avoid the conditional that writes the possibly-false value
from chatModelConfig.Stream.

Comment on lines +369 to 370
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region

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 apiConfig before reading Region in both methods.

ListModels and Balance can panic when apiConfig is nil due to direct apiConfig.Region access.

🛡️ Suggested fix
 func (z *MoonshotModel) ListModels(apiConfig *APIConfig) ([]string, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is required")
+	}
 	var region = "default"
 	if apiConfig.Region != nil && *apiConfig.Region != "" {
 		region = *apiConfig.Region
 	}
@@
 func (z *MoonshotModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is required")
+	}
 	var region = "default"
 	if apiConfig.Region != nil && *apiConfig.Region != "" {
 		region = *apiConfig.Region
 	}

Also applies to: 425-426

🤖 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/moonshot.go` around lines 369 - 370, ListModels and
Balance currently dereference apiConfig.Region without checking apiConfig, which
can cause a panic when apiConfig is nil; update both methods (ListModels and
Balance) to first guard against a nil apiConfig (e.g., if apiConfig == nil { /*
set region default or skip region logic */ }) before accessing apiConfig.Region,
then only read *apiConfig.Region when apiConfig != nil and apiConfig.Region !=
nil and non-empty; make the same nil-check change at the other occurrence
referenced in the review.

Comment on lines +607 to +623
var body bytes.Buffer
writer := multipart.NewWriter(&body)

// audio file
audioFile, err := os.Open(*file)
if err != nil {
return nil, fmt.Errorf("failed to open audio file: %w", err)
}
defer audioFile.Close()

part, err := writer.CreateFormFile("file", filepath.Base(*file))
if err != nil {
return nil, fmt.Errorf("failed to create multipart file: %w", err)
}

if _, err = io.Copy(part, audioFile); err != nil {
return nil, fmt.Errorf("failed to copy audio data: %w", err)

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 | 🏗️ Heavy lift

Avoid buffering the entire audio upload in memory.

In internal/entity/models/xinference.go (around lines 607-623), the multipart payload is written to multipart.NewWriter(&body) where body is a bytes.Buffer, and io.Copy(part, audioFile) writes the full audio content into that buffer before the HTTP request is sent. This keeps memory usage proportional to the full upload size (plus multipart overhead) per concurrent request.

Consider switching to a streaming multipart implementation (e.g., io.Pipe with a goroutine writing to the multipart writer, and using the pipe reader as the request body) to avoid buffering the entire payload in RAM.

🤖 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/xinference.go` around lines 607 - 623, The current
implementation builds the multipart payload in memory by using bytes.Buffer with
multipart.NewWriter(&body) and io.Copy(part, audioFile); refactor to stream the
upload using io.Pipe: create pr, pw := io.Pipe(), start a goroutine that creates
multipart.NewWriter(pw), calls CreateFormFile("file", filepath.Base(*file)) and
io.Copy(part, audioFile) (closing the writer and pw on completion or error), and
pass pr as the HTTP request body so the request streams directly from disk
without buffering the entire file; update any error handling around audioFile,
the multipart writer, and the pipe to close/propagate errors correctly.

Comment on lines +679 to +680
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("FishAudio ASR error: %s - %s", resp.Status, string(respBody))

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 the stale provider name in this error message.

Returning "FishAudio ASR error" from the Xinference driver will send people to the wrong integration when this fails.

🤖 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/xinference.go` around lines 679 - 680, The error
message in the HTTP response handling incorrectly references "FishAudio ASR
error"; locate the non-OK response branch inside the Xinference driver (the
block checking if resp.StatusCode != http.StatusOK) and change the fmt.Errorf
call to use the correct provider name (e.g., "Xinference ASR error") or the
driver/provider identifier used elsewhere (use the driver struct's name/const if
available) so the error message points to the Xinference integration instead of
FishAudio.

@codecov

codecov Bot commented May 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (440153c) to head (f317985).
⚠️ Report is 18 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15096   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  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.

@JinHai-CN
JinHai-CN merged commit a725e11 into infiniflow:main May 21, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 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