Repository navigation
Go: implement TTS and ASR for Cometapi - #15001
Conversation
📝 WalkthroughWalkthroughThis PR adds audio capability to CometAPI by registering ASR (whisper-1) and TTS (tts-1) endpoints and models in the configuration, expanding imports for multipart and file operations, and implementing the ChangesCometAPI Audio Support
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 5
🤖 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/cometapi.json`:
- Around line 118-119: Remove the unused "max_tokens" field from the TTS model
entry "tts-1" in conf/models/cometapi.json because AudioSpeech (function
AudioSpeech in cometapi.go) never reads or uses it; edit the JSON to delete the
"max_tokens" property for the "tts-1" model so the config accurately reflects
the parameters the TTS request builder uses (model, input, custom parameters,
format).
In `@internal/entity/models/cometapi.go`:
- Around line 721-726: The error string returned when the CometAPI upstream
returns a non-200 (the resp.StatusCode != http.StatusOK branch that calls
fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody)))
incorrectly names "SiliconFlow"; change that message to reference "CometAPI"
(e.g., "CometAPI ASR error: ...") so the returned error and logs correctly
identify the CometAPI driver/endpoint (update the fmt.Errorf call in that
resp.StatusCode check).
- Around line 632-638: Replace the ad-hoc region/url construction that sets
region := "default" and uses fmt.Sprintf("%s/%s", m.BaseURL[region],
m.URLSuffix.ASR) with the existing helpers: call
endpointURL(cometapiRegion(apiConfig), m.URLSuffix.ASR) so you reuse the
cometapiRegion logic (which picks and validates the region against m.BaseURL)
and endpointURL (which trims slashes and preserves fast-fail behavior); do the
same replacement for the analogous block around m.URLSuffix.ASR at lines
~747-752, referencing m.BaseURL and m.URLSuffix.ASR as the target components to
build the endpoint.
- Around line 627-629: The TranscribeAudio method currently dereferences
modelName and apiConfig.ApiKey directly and can panic; call
validateCometAPIModelName(modelName) and validateCometAPIAPIKey(apiConfig) at
the start of TranscribeAudio (and the other CometAPI methods flagged) to perform
nil checks and return the same validation errors, then use the validated
modelName value and the validated apiConfig.ApiKey value for subsequent
dereferences (replace direct uses of *modelName and *apiConfig.ApiKey with the
validated variables).
- Around line 699-710: TranscribeAudio and AudioSpeech create requests with
http.NewRequest and lack the context deadline; update both to create the request
with context using context.WithTimeout(ctx, nonStreamCallTimeout) and
http.NewRequestWithContext so the overall non-stream timeout is enforced before
calling m.httpClient.Do; locate the request creation in the TranscribeAudio and
AudioSpeech methods (where req, err := http.NewRequest(...) is used), wrap the
provided ctx with nonStreamCallTimeout, use that context in
NewRequestWithContext, and ensure defers/cancel are handled correctly.
🪄 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: b30912fb-2851-4c36-9877-fa8b97b2398a
⛔ Files ignored due to path filters (2)
internal/test.pdfis excluded by!**/*.pdfinternal/test.wavis excluded by!**/*.wav
📒 Files selected for processing (2)
conf/models/cometapi.jsoninternal/entity/models/cometapi.go
| "name": "tts-1", | ||
| "max_tokens": 8192, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Search for max_tokens usage in TTS/audio context
# Search for max_tokens field access in audio/TTS related code
rg -n -C5 'max_tokens' --type=go -g '*audio*' -g '*tts*' -g '*cometapi*'
# Search for TTS model configuration loading
ast-grep --pattern 'model_types.*tts'
# Search for how model fields are accessed for TTS
rg -n -C5 'model_types.*tts|tts.*model_types' --type=goRepository: infiniflow/ragflow
Length of output: 7938
🏁 Script executed:
# Search for TTS request struct definitions
rg -n -C5 'type.*tts.*[Rr]equest|type.*audio.*[Rr]equest' --type=go
# Search for how cometapi handles TTS model requests
rg -n -C10 'tts|audio' internal/entity/models/cometapi.go
# Check if max_tokens is accessed from model config for TTS
rg -n -C5 'GetMaxTokens|maxTokens|max_tokens.*model' --type=go
# Look for model field access patterns
ast-grep --pattern 'model\["max_tokens"\]|model\.MaxTokens'Repository: infiniflow/ragflow
Length of output: 34326
Remove unused max_tokens field from TTS model configuration.
The max_tokens field for the tts-1 model is defined in the config but never used in the TTS request construction. The AudioSpeech function (cometapi.go:742-797) builds requests using only the model name, input text, custom parameters, and format—it does not access max_tokens from the model config. Unlike embedding models which explicitly document and use max_tokens for text truncation, TTS models should not include this unused field.
🤖 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/cometapi.json` around lines 118 - 119, Remove the unused
"max_tokens" field from the TTS model entry "tts-1" in conf/models/cometapi.json
because AudioSpeech (function AudioSpeech in cometapi.go) never reads or uses
it; edit the JSON to delete the "max_tokens" property for the "tts-1" model so
the config accurately reflects the parameters the TTS request builder uses
(model, input, custom parameters, format).
| func (m *CometAPIModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", m.Name()) | ||
| if file == nil || *file == "" { | ||
| return nil, fmt.Errorf("file is missing") |
There was a problem hiding this comment.
Validate modelName and apiConfig before dereferencing them.
Line 662 and Line 705, plus Line 755 and Line 779, dereference *modelName and *apiConfig.ApiKey without any guard. A nil modelName, nil apiConfig, or nil apiConfig.ApiKey will panic the driver instead of returning the same validation errors used by the other CometAPI methods. Please run validateCometAPIAPIKey / validateCometAPIModelName up front in both methods and use the validated values afterwards.
Also applies to: 661-705, 742-745, 754-779
🤖 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/cometapi.go` around lines 627 - 629, The
TranscribeAudio method currently dereferences modelName and apiConfig.ApiKey
directly and can panic; call validateCometAPIModelName(modelName) and
validateCometAPIAPIKey(apiConfig) at the start of TranscribeAudio (and the other
CometAPI methods flagged) to perform nil checks and return the same validation
errors, then use the validated modelName value and the validated
apiConfig.ApiKey value for subsequent dereferences (replace direct uses of
*modelName and *apiConfig.ApiKey with the validated variables).
| region := "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", m.BaseURL[region], m.URLSuffix.ASR) | ||
|
|
There was a problem hiding this comment.
Reuse cometapiRegion / endpointURL instead of open-coding the endpoint.
These blocks duplicate logic that already exists in this file, and they also drop the fast-fail behavior from baseURLForRegion. If apiConfig.Region points to a region missing from m.BaseURL, fmt.Sprintf("%s/%s", m.BaseURL[region], ...) produces a path-only URL and the transport fails later with an opaque scheme error. Calling endpointURL(cometapiRegion(apiConfig), ...) keeps the error consistent and trims slashes correctly.
Also applies to: 747-752
🤖 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/cometapi.go` around lines 632 - 638, Replace the
ad-hoc region/url construction that sets region := "default" and uses
fmt.Sprintf("%s/%s", m.BaseURL[region], m.URLSuffix.ASR) with the existing
helpers: call endpointURL(cometapiRegion(apiConfig), m.URLSuffix.ASR) so you
reuse the cometapiRegion logic (which picks and validates the region against
m.BaseURL) and endpointURL (which trims slashes and preserves fast-fail
behavior); do the same replacement for the analogous block around
m.URLSuffix.ASR at lines ~747-752, referencing m.BaseURL and m.URLSuffix.ASR as
the target components to build the endpoint.
| // build 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()) | ||
| req.Header.Set("Accept", "application/json") | ||
|
|
||
| // send request | ||
| resp, err := m.httpClient.Do(req) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
wc -l internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 101
🏁 Script executed:
head -100 internal/entity/models/cometapi.go | tail -20Repository: infiniflow/ragflow
Length of output: 630
🏁 Script executed:
sed -n '1,50p' internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 1442
🏁 Script executed:
# Search for NewCometAPIModel function
rg -n "func NewCometAPIModel" internal/entity/models/cometapi.go -A 20Repository: infiniflow/ragflow
Length of output: 738
🏁 Script executed:
# Search for httpClient initialization
rg -n "httpClient" internal/entity/models/cometapi.go | head -20Repository: infiniflow/ragflow
Length of output: 277
🏁 Script executed:
# Check for nonStreamCallTimeout definition
rg -n "nonStreamCallTimeout" internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 398
🏁 Script executed:
sed -n '310,330p' internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 651
🏁 Script executed:
sed -n '490,510p' internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 541
🏁 Script executed:
sed -n '550,570p' internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 668
🏁 Script executed:
sed -n '580,600p' internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 706
🏁 Script executed:
sed -n '690,715p' internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 752
🏁 Script executed:
sed -n '765,790p' internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 784
🏁 Script executed:
# Find nonStreamCallTimeout definition
rg -n "nonStreamCallTimeout\s*=" internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Find ASR/TTS method names
rg -n "func.*ASR|func.*TTS|func.*Asr|func.*Tts" internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 712
🏁 Script executed:
rg -n "nonStreamCallTimeout" internal/entity/models/cometapi.go -B 2 -A 2Repository: infiniflow/ragflow
Length of output: 634
🏁 Script executed:
# Check if it's defined at package level (near top of file)
sed -n '1,100p' internal/entity/models/cometapi.go | grep -n "nonStreamCallTimeout\|timeout\|Timeout"Repository: infiniflow/ragflow
Length of output: 375
🏁 Script executed:
# Look for const definitions in the file
rg -n "const " internal/entity/models/cometapi.goRepository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search for nonStreamCallTimeout across the entire codebase
rg -n "nonStreamCallTimeout" --type go -B 2 -A 2Repository: infiniflow/ragflow
Length of output: 13092
Use http.NewRequestWithContext with nonStreamCallTimeout for TranscribeAudio and AudioSpeech methods.
TranscribeAudio (lines 699-710) and AudioSpeech (lines 773-781) build plain http.NewRequest requests without context, while ChatWithMessages, Embed, ListModels, and Balance all wrap non-stream calls in context.WithTimeout with nonStreamCallTimeout (120 seconds). Since httpClient.Timeout is intentionally unset in NewCometAPIModel, the context timeout is the required overall deadline for non-streaming requests. Update both methods to use http.NewRequestWithContext to prevent stalled uploads or responses from blocking indefinitely.
🤖 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/cometapi.go` around lines 699 - 710, TranscribeAudio
and AudioSpeech create requests with http.NewRequest and lack the context
deadline; update both to create the request with context using
context.WithTimeout(ctx, nonStreamCallTimeout) and http.NewRequestWithContext so
the overall non-stream timeout is enforced before calling m.httpClient.Do;
locate the request creation in the TranscribeAudio and AudioSpeech methods
(where req, err := http.NewRequest(...) is used), wrap the provided ctx with
nonStreamCallTimeout, use that context in NewRequestWithContext, and ensure
defers/cancel are handled correctly.
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody)) | ||
| } | ||
|
|
||
| // SiliconFlow response | ||
| var result struct { |
There was a problem hiding this comment.
Fix the copied provider name in the ASR error path.
Line 722 returns "SiliconFlow ASR error" from the CometAPI driver. That will mislead debugging and alerting when the CometAPI upstream is the one failing.
🤖 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/cometapi.go` around lines 721 - 726, The error string
returned when the CometAPI upstream returns a non-200 (the resp.StatusCode !=
http.StatusOK branch that calls fmt.Errorf("SiliconFlow ASR error: %s - %s",
resp.Status, string(respBody))) incorrectly names "SiliconFlow"; change that
message to reference "CometAPI" (e.g., "CometAPI ASR error: ...") so the
returned error and logs correctly identify the CometAPI driver/endpoint (update
the fmt.Errorf call in that resp.StatusCode check).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15001 +/- ##
=======================================
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?
Verified from CLI
Type of change