Repository navigation
Go: implement TTS for fishaudio, openrouter and asr for fishaudio - #14926
Conversation
📝 WalkthroughWalkthroughThis PR implements complete ASR (automatic speech recognition) and TTS (text-to-speech) audio provider support for FishAudio and OpenRouter. It introduces type contracts with JSON serialization, configuration mappings for audio endpoints, enhanced CLI command parsing and execution, HTTP handler integration, and full provider-specific implementations including streaming response parsing. ChangesAudio Provider Integration
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 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: 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/cli/user_command.go`:
- Around line 2183-2199: The assignment to result.Message uses an unsafe type
assertion rawResult.Data["text"].(string) which can panic if the "text" key is
missing or not a string; in the function handling the ASR response, replace that
with a safe two-value assertion (v, ok := rawResult.Data["text"].(string)),
check ok (and presence), and handle the failure path by returning a clear error
(e.g., fmt.Errorf("ASR document invalid: missing or non-string text field")) or
assigning a sensible default before setting result.Message on the CommonResponse
variable.
In `@internal/entity/models/fishaudio.go`:
- Around line 224-227: Guard the modelName pointer before dereferencing: check
if modelName == nil or *modelName == "" before calling req.Header.Set("model",
*modelName) (and the other occurrence around lines 286-289), and either skip
setting the "model" header or use a safe default; ensure the Authorization
header still uses apiConfig.ApiKey safely (validate apiConfig.ApiKey != nil) and
update the request-building code where req.Header.Set is called so no nil
pointer is dereferenced.
- Around line 88-89: The code constructs provider URLs using f.BaseURL[region]
(e.g., url := fmt.Sprintf("%s/%s", f.BaseURL[region], f.URLSuffix.ASR)) without
validating that region exists; add a region fallback lookup before any URL
construction: determine regionKey := apiConfig.Region (or computed region) and
if f.BaseURL[regionKey] is missing, fall back to f.BaseURL["default"] (or
another configured fallback) and return a clear config error if no fallback
exists; apply the same guard/fallback logic to the other occurrences that build
URLs (the lines using f.BaseURL at the other sites referenced around 199-200 and
260) so URL construction is never attempted with a missing map key.
In `@internal/entity/models/minimax.go`:
- Around line 491-495: The current code unconditionally replaces
reqBody["audio_setting"] with a new map when asrConfig.Format is set, dropping
any existing fields injected via ttsConfig/asrConfig.Params; instead detect
whether reqBody["audio_setting"] already exists and is a map[string]interface{}
and then merge/assign the "format" key into that map (e.g., retrieve
reqBody["audio_setting"], type-assert to map[string]interface{} and set
m["format"]=asrConfig.Format) otherwise create the map as before; apply the same
merge logic to the other occurrence handling audio_setting (the block around the
later lines 589-593) so existing voice/speed/sample-rate fields are preserved.
In `@internal/entity/models/openrouter.go`:
- Around line 563-566: The code builds reqBody with "model": modelName without
validating modelName, which can serialize nil to null; before constructing
reqBody (in the function that assembles reqBody using modelName and audioContent
in openrouter.go), check that modelName is non-nil and non-empty (if it's a
*string check for nil then dereference; if string check for ""), and return a
clear error if invalid; only include "model" in reqBody when valid so the
serialized payload never contains null and upstream errors are avoided.
- Around line 555-561: The code picks region from apiConfig.Region into the
local variable region and then indexes o.BaseURL[region] without handling
unknown keys, which can yield an empty string; update the logic where region is
computed and URL is built (referencing region, apiConfig.Region, o.BaseURL, and
o.URLSuffix.TTS) to check whether o.BaseURL contains the chosen region key and,
if not, fall back to "default" (or return a clear config error). Ensure the
final url uses the resolved/fallback region key when formatting
fmt.Sprintf("%s/%s", ...) so requests never use an empty base URL.
🪄 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: 95b5b454-7834-4887-a3c5-d1598310c650
📒 Files selected for processing (9)
conf/models/fishaudio.jsonconf/models/openrouter.jsoninternal/cli/user_command.gointernal/cli/user_parser.gointernal/entity/models/fishaudio.gointernal/entity/models/minimax.gointernal/entity/models/openrouter.gointernal/entity/models/types.gointernal/handler/providers.go
| var rawResult struct { | ||
| Code int `json:"code"` | ||
| Message string `json:"message"` | ||
| Data map[string]interface{} `json:"data"` | ||
| } | ||
|
|
||
| if err = json.Unmarshal(resp.Body, &rawResult); err != nil { | ||
| return nil, fmt.Errorf("ASR document failed: invalid JSON (%w)", err) | ||
| } | ||
| if result.Code != 0 { | ||
| return nil, fmt.Errorf("%s", result.Message) | ||
|
|
||
| if rawResult.Code != 0 { | ||
| return nil, fmt.Errorf("%s", rawResult.Message) | ||
| } | ||
|
|
||
| var result CommonResponse | ||
| result.Code = rawResult.Code | ||
| result.Message = rawResult.Data["text"].(string) // TODO |
There was a problem hiding this comment.
Missing type-assertion safety guard.
Line 2199 performs an unsafe type assertion rawResult.Data["text"].(string) that will panic if the "text" key is missing or holds a non-string value. Add a safe two-value assertion to handle unexpected response formats gracefully.
🛡️ Proposed fix
var rawResult struct {
Code int `json:"code"`
Message string `json:"message"`
Data map[string]interface{} `json:"data"`
}
if err = json.Unmarshal(resp.Body, &rawResult); err != nil {
return nil, fmt.Errorf("ASR document failed: invalid JSON (%w)", err)
}
if rawResult.Code != 0 {
return nil, fmt.Errorf("%s", rawResult.Message)
}
var result CommonResponse
result.Code = rawResult.Code
- result.Message = rawResult.Data["text"].(string) // TODO
+ text, ok := rawResult.Data["text"].(string)
+ if !ok {
+ return nil, fmt.Errorf("ASR response missing or invalid 'text' field")
+ }
+ result.Message = text
result.Duration = resp.Duration
return &result, nil📝 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.
| var rawResult struct { | |
| Code int `json:"code"` | |
| Message string `json:"message"` | |
| Data map[string]interface{} `json:"data"` | |
| } | |
| if err = json.Unmarshal(resp.Body, &rawResult); err != nil { | |
| return nil, fmt.Errorf("ASR document failed: invalid JSON (%w)", err) | |
| } | |
| if result.Code != 0 { | |
| return nil, fmt.Errorf("%s", result.Message) | |
| if rawResult.Code != 0 { | |
| return nil, fmt.Errorf("%s", rawResult.Message) | |
| } | |
| var result CommonResponse | |
| result.Code = rawResult.Code | |
| result.Message = rawResult.Data["text"].(string) // TODO | |
| var rawResult struct { | |
| Code int `json:"code"` | |
| Message string `json:"message"` | |
| Data map[string]interface{} `json:"data"` | |
| } | |
| if err = json.Unmarshal(resp.Body, &rawResult); err != nil { | |
| return nil, fmt.Errorf("ASR document failed: invalid JSON (%w)", err) | |
| } | |
| if rawResult.Code != 0 { | |
| return nil, fmt.Errorf("%s", rawResult.Message) | |
| } | |
| var result CommonResponse | |
| result.Code = rawResult.Code | |
| text, ok := rawResult.Data["text"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("ASR response missing or invalid 'text' field") | |
| } | |
| result.Message = text |
🤖 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/cli/user_command.go` around lines 2183 - 2199, The assignment to
result.Message uses an unsafe type assertion rawResult.Data["text"].(string)
which can panic if the "text" key is missing or not a string; in the function
handling the ASR response, replace that with a safe two-value assertion (v, ok
:= rawResult.Data["text"].(string)), check ok (and presence), and handle the
failure path by returning a clear error (e.g., fmt.Errorf("ASR document invalid:
missing or non-string text field")) or assigning a sensible default before
setting result.Message on the CommonResponse variable.
| url := fmt.Sprintf("%s/%s", f.BaseURL[region], f.URLSuffix.ASR) | ||
|
|
There was a problem hiding this comment.
Add region fallback before building provider URLs.
These new paths use f.BaseURL[region] directly. If apiConfig.Region is set to an unknown key, URL construction becomes invalid and requests fail with transport errors instead of clean config errors/fallback.
Proposed fix
- url := fmt.Sprintf("%s/%s", f.BaseURL[region], f.URLSuffix.ASR)
+ baseURL := f.BaseURL[region]
+ if baseURL == "" {
+ baseURL = f.BaseURL["default"]
+ }
+ url := fmt.Sprintf("%s/%s", baseURL, f.URLSuffix.ASR)Also applies to: 199-200, 260-260
🤖 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/fishaudio.go` around lines 88 - 89, The code
constructs provider URLs using f.BaseURL[region] (e.g., url :=
fmt.Sprintf("%s/%s", f.BaseURL[region], f.URLSuffix.ASR)) without validating
that region exists; add a region fallback lookup before any URL construction:
determine regionKey := apiConfig.Region (or computed region) and if
f.BaseURL[regionKey] is missing, fall back to f.BaseURL["default"] (or another
configured fallback) and return a clear config error if no fallback exists;
apply the same guard/fallback logic to the other occurrences that build URLs
(the lines using f.BaseURL at the other sites referenced around 199-200 and 260)
so URL construction is never attempted with a missing map key.
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
| req.Header.Set("model", *modelName) | ||
|
|
There was a problem hiding this comment.
Guard modelName before dereferencing to avoid panic.
Line 226 and Line 288 dereference *modelName without nil/empty validation. A nil modelName will panic before any API error handling.
Proposed fix
func (f *FishAudioModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, asrConfig *TTSConfig) (*TTSResponse, error) {
+ if modelName == nil || *modelName == "" {
+ return nil, fmt.Errorf("model name is missing")
+ }
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return nil, fmt.Errorf("FishAudio API key is missing")
}
@@
func (f *FishAudioModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, asrConfig *TTSConfig, sender func(*string, *string) error) error {
+ if modelName == nil || *modelName == "" {
+ return fmt.Errorf("model name is missing")
+ }
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return fmt.Errorf("FishAudio API key is missing")
}Also applies to: 286-289
🤖 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/fishaudio.go` around lines 224 - 227, Guard the
modelName pointer before dereferencing: check if modelName == nil or *modelName
== "" before calling req.Header.Set("model", *modelName) (and the other
occurrence around lines 286-289), and either skip setting the "model" header or
use a safe default; ensure the Authorization header still uses apiConfig.ApiKey
safely (validate apiConfig.ApiKey != nil) and update the request-building code
where req.Header.Set is called so no nil pointer is dereferenced.
| if asrConfig != nil && asrConfig.Format != "" { | ||
| reqBody["audio_setting"] = map[string]interface{}{ | ||
| "format": asrConfig.Format, | ||
| } | ||
| } |
There was a problem hiding this comment.
Avoid overwriting audio_setting from caller params.
The new audio_setting assignment replaces any existing audio_setting object injected via ttsConfig/asrConfig.Params, which can drop fields (voice, speed, sample rate, etc.). Merge format into an existing map instead of replacing it.
Proposed fix
if asrConfig != nil && asrConfig.Format != "" {
- reqBody["audio_setting"] = map[string]interface{}{
- "format": asrConfig.Format,
- }
+ audioSetting, _ := reqBody["audio_setting"].(map[string]interface{})
+ if audioSetting == nil {
+ audioSetting = map[string]interface{}{}
+ }
+ audioSetting["format"] = asrConfig.Format
+ reqBody["audio_setting"] = audioSetting
}Also applies to: 589-593
🤖 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/minimax.go` around lines 491 - 495, The current code
unconditionally replaces reqBody["audio_setting"] with a new map when
asrConfig.Format is set, dropping any existing fields injected via
ttsConfig/asrConfig.Params; instead detect whether reqBody["audio_setting"]
already exists and is a map[string]interface{} and then merge/assign the
"format" key into that map (e.g., retrieve reqBody["audio_setting"], type-assert
to map[string]interface{} and set m["format"]=asrConfig.Format) otherwise create
the map as before; apply the same merge logic to the other occurrence handling
audio_setting (the block around the later lines 589-593) so existing
voice/speed/sample-rate fields are preserved.
| var region = "default" | ||
| if apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.TTS) | ||
|
|
There was a problem hiding this comment.
Add base URL fallback for unknown region keys.
If a non-existent region key is provided, o.BaseURL[region] is empty and the request fails before reaching OpenRouter. Falling back to default (or returning explicit config error) makes this path robust.
🤖 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/openrouter.go` around lines 555 - 561, The code picks
region from apiConfig.Region into the local variable region and then indexes
o.BaseURL[region] without handling unknown keys, which can yield an empty
string; update the logic where region is computed and URL is built (referencing
region, apiConfig.Region, o.BaseURL, and o.URLSuffix.TTS) to check whether
o.BaseURL contains the chosen region key and, if not, fall back to "default" (or
return a clear config error). Ensure the final url uses the resolved/fallback
region key when formatting fmt.Sprintf("%s/%s", ...) so requests never use an
empty base URL.
| reqBody := map[string]interface{}{ | ||
| "model": modelName, | ||
| "input": audioContent, | ||
| } |
There was a problem hiding this comment.
Validate modelName before request serialization.
modelName is not validated in this method. A nil pointer serializes to null, causing avoidable upstream errors and harder debugging.
🤖 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/openrouter.go` around lines 563 - 566, The code builds
reqBody with "model": modelName without validating modelName, which can
serialize nil to null; before constructing reqBody (in the function that
assembles reqBody using modelName and audioContent in openrouter.go), check that
modelName is non-nil and non-empty (if it's a *string check for nil then
dereference; if string check for ""), and return a clear error if invalid; only
include "model" in reqBody when valid so the serialized payload never contains
null and upstream errors are avoided.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14926 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
…finiflow#14926) ### What problem does this PR solve? This PR implement TTS for FishAudio and MiniMax provider and ASR for FishAudio **The following functionalities are now supported:** **FishAudio:** - [x] Text To Speech - [x] Stream Text To Speech - [x] Audio To Text **OpenRouter:** - [x] Text To Speech **Verified examples from the CLI:** ```plaintext **FishAudio** RAGFlow(user)> tts with 's1@test@fishaudio' text 'He who desires but acts not, breeds pestilence.' play format 'wav' save './internal' param '{"reference_id": "90e65eaaf50e4470b8e6d43ee6afd7d5", "temperature": 0.7, "top_p": 0.7, "prosody": {"speed": 1, "volume": 0, "normalize_loudness": true}, "chunk_length": 300, "normalize": true, "sample_rate": 44100, "mp3_bitrate": 128, "latency": "normal", "max_new_tokens": 1024, "repetition_penalty": 1.2, "min_chunk_length": 50, "condition_on_previous_chunks": true, "early_stop_threshold": 1}' Saved to directory: /home/infiniflow/Documents/development/ragflow/internal/s1_output.wav SUCCESS RAGFlow(user)> stream tts with 's1@test@fishaudio' text 'He who desires but acts not, breeds pestilence.' play format 'wav' save './internal' param '{"reference_id": "90e65eaaf50e4470b8e6d43ee6afd7d5", "temperature": 0.7, "top_p": 0.7, "prosody": {"speed": 1, "volume": 0, "normalize_loudness": true}, "chunk_length": 300, "normalize": true, "sample_rate": 44100, "mp3_bitrate": 128, "latency": "normal", "max_new_tokens": 1024, "repetition_penalty": 1.2, "min_chunk_length": 50, "condition_on_previous_chunks": true, "early_stop_threshold": 1}' Saved to directory: /home/infiniflow/Documents/development/ragflow/internal/s1_output.wav SUCCESS RAGFlow(user)> asr with 'transcribe-1@test@fishaudio' audio './internal/test.wav' param '{"language": "en", "ignore_timestamps": true}' +----------------------------------------------------------------------------------------------------------------------+ | text | +----------------------------------------------------------------------------------------------------------------------+ | The examination and testimony of the experts enabled the commission to conclude that five shots may have been fired. | +----------------------------------------------------------------------------------------------------------------------+ ``` ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [x] Refactoring
What problem does this PR solve?
This PR implement TTS for FishAudio and MiniMax provider and ASR for FishAudio
The following functionalities are now supported:
FishAudio:
OpenRouter:
Verified examples from the CLI:
Type of change