Repository navigation
Go: implement ASR and TTS for Xinference - #15096
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughImplements 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. ChangesProvider Feature Implementation and Fixes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
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: 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
📒 Files selected for processing (5)
conf/models/novita.jsoninternal/entity/models/fishaudio.gointernal/entity/models/moonshot.gointernal/entity/models/novita.gointernal/entity/models/xinference.go
| 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)) |
There was a problem hiding this comment.
Missing nil-safety checks will cause panics.
The Balance method lacks the validation guards present in other methods in this file:
- Line 848: Accesses
apiConfig.Regionwithout checking ifapiConfigis nil first - Line 868: Dereferences
*apiConfig.ApiKeywithout checking ifApiKeyis 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) |
There was a problem hiding this comment.
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.
| // 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)) |
There was a problem hiding this comment.
Add request timeout and remove unnecessary body.
- GET requests don't need a body - the empty JSON is unnecessary overhead
- Missing
context.WithTimeoutmeans the request could hang indefinitely (other methods usenonStreamCallTimeout)
🔧 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.
| 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) |
There was a problem hiding this comment.
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.
| // 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) |
There was a problem hiding this comment.
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.
| // 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.
| 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)) |
There was a problem hiding this comment.
Same nil-safety and timeout issues as TranscribeAudio.
This method has identical issues:
- Line 707:
apiConfig.Regionaccessed without checking ifapiConfigis nil - Line 714:
*modelNamedereferenced without validation - Line 738:
*apiConfig.ApiKeywithout nil checks - Line 711: Direct
BaseURL[region]access bypassesbaseURLForRegion()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).
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (2)
internal/entity/models/xinference.go (2)
659-668:⚠️ Potential issue | 🟠 Major | ⚡ Quick winAdd an overall deadline to these audio HTTP calls.
These requests use
http.NewRequestwithout a context, and this client only hasResponseHeaderTimeout. A stalled upload or response-body read can still block indefinitely here; usehttp.NewRequestWithContextwith 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.Timeoutis intentionally unset and onlytransport.ResponseHeaderTimeoutis configured,context.WithTimeoutper 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 winUse the shared Xinference helpers here instead of dereferencing config directly.
Both methods can panic on nil
apiConfig/modelName, andx.BaseURL[region]+ manualAuthorizationskips 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
📒 Files selected for processing (5)
conf/models/novita.jsoninternal/entity/models/fishaudio.gointernal/entity/models/moonshot.gointernal/entity/models/novita.gointernal/entity/models/xinference.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/novita.json
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } |
There was a problem hiding this comment.
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.
| if apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("FishAudio ASR error: %s - %s", resp.Status, string(respBody)) |
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
implement ASR and TTS for Xinference
Type of change