Repository navigation
Go: implement TTS for MiniMax provider and CLI testing for TTS - #14911
Conversation
📝 WalkthroughWalkthroughAdds Minimax Text-to-Speech: model configuration, types/handler changes, full provider implementations (non-streaming and streaming), CLI parsing/execution for TTS (play/save/params/format), and development documentation. ChangesMinimax TTS Feature
Sequence Diagram(s)sequenceDiagram
participant CLI
participant Handler as AudioHandler
participant Minimax as MinimaxModel
participant FS as FileSystem
participant Player as Aplay
CLI->>AudioHandler: POST /audio/speech {model, text, tts_config}
AudioHandler->>MinimaxModel: AudioSpeech / AudioSpeechWithSender request (model, text, params, stream flag)
MinimaxModel-->>AudioHandler: HTTP 200 + {base_resp, data.audio (HEX) / SSE data: events}
AudioHandler->>FS: write temp audio file (decoded bytes)
CLI->>Player: (if play) execute `aplay` on temp file
CLI->>FS: (if save) move temp file -> save_path (create dirs)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 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. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/cli/user_command.go (1)
2023-2026:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
STREAM TTSflag is parsed but never used by the CLI execution path.
parseStreamCommandcan setcmd.Params["stream"]=true, butTTSUserCommandalways calls non-streamRequest(...)and never handles streaming response chunks. This makes STREAM TTS CLI behavior incorrect.🤖 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 2023 - 2026, The STREAM TTS flag is parsed into cmd.Params["stream"] by parseStreamCommand but TTSUserCommand ignores it and always calls c.HTTPClient.Request, so streaming responses are never handled; update TTSUserCommand to check cmd.Params["stream"] (or a typed param) and when true call the HTTP client's streaming method (e.g., RequestStream / RequestWithStream / similar streaming API on c.HTTPClient) and process chunks as they arrive (invoking the same payload handling logic per chunk), otherwise keep the existing non-stream Request flow; ensure you reference TTSUserCommand, parseStreamCommand, and c.HTTPClient.Request/RequestStream to locate changes.
🧹 Nitpick comments (1)
internal/development.md (1)
363-364: 💤 Low valueConsider using a clearer example directory.
The example uses
'./internal'as the save directory, which refers to the project's source code directory and may confuse users. Additionally, the output path shows a user-specific absolute path. Consider using a more typical example directory like'./output'or'./audio_files'and documenting the expected relative output path.📝 Suggested improvement
-RAGFlow(user)> tts with 'speech-2.8-hd@test@minimax' text 'He who desires but acts not, breeds pestilence.' play format 'wav' save './internal' param '{"voice_setting": {"voice_id": "English_radiant_girl", "speed": 1, "vol": 1, "pitch": 0}, "audio_setting": {"sample_rate": 32000, "bitrate": 128000, "format": "wav", "channel": 1}, "output_format": "hex"}' -Saved to directory: /home/infiniflow/Documents/development/ragflow/internal/speech-2.8-hd_output.wav +RAGFlow(user)> tts with 'speech-2.8-hd@test@minimax' text 'He who desires but acts not, breeds pestilence.' play format 'wav' save './output' param '{"voice_setting": {"voice_id": "English_radiant_girl", "speed": 1, "vol": 1, "pitch": 0}, "audio_setting": {"sample_rate": 32000, "bitrate": 128000, "format": "wav", "channel": 1}, "output_format": "hex"}' +Saved to directory: ./output/speech-2.8-hd_output.wav SUCCESS🤖 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/development.md` around lines 363 - 364, Update the example TTS usage to save to a non-source directory and show a relative output path: change the save directory in the example command string (the RAGFlow(user)> tts ... save './internal' line) to a clearer directory such as './output' or './audio_files' and update the example output path (the Saved to directory: ... speech-2.8-hd_output.wav line) to a corresponding relative path (e.g., ./output/speech-2.8-hd_output.wav) so users aren’t pointed at the project source tree or a user-specific absolute path.
🤖 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/minimax.json`:
- Around line 103-109: Remove the unnecessary token limit from the TTS model
entry: delete the "max_tokens" property from the "speech-2.8-hd" model
definition so the configuration only contains "name" and "model_types" (and any
TTS-specific fields if present); this avoids misleading use of max_length
derived from max_tokens (used in encode()) since tts() does not consult it and
MiniMax uses a character limit instead.
In `@internal/cli/user_command.go`:
- Around line 2013-2021: The CLI sets explicitFormat into
ttsConfigPayload["format"] but backend expects models.TTSConfig.Params, so the
format is never sent; update the payload shape by placing the chosen format into
the ttsConfigPayload.Params map (e.g., ensure
ttsConfigPayload["params"]["format"] = explicitFormat) before assigning
payload["tts_config"] = ttsConfigPayload, and keep the defaulting logic for
explicitFormat ("mp3") so file extension and provider format remain consistent;
adjust any creation of ttsConfigPayload and references to explicitFormat
accordingly.
In `@internal/cli/user_parser.go`:
- Around line 2807-2815: The TokenParam branch advances tokens one time too many
and skips the next option: after matching TokenParam and consuming the quoted
value into cmd.Params["param_str"], remove the extra p.nextToken() so you only
call p.nextToken() once to move past the quoted string (i.e., keep a single
p.nextToken() after assigning to cmd.Params["param_str"] and delete the second
p.nextToken()); this fixes parsing for subsequent options (look at the
TokenParam case and uses of p.nextToken()).
In `@internal/development.md`:
- Line 362: The fenced code block containing the shell command starting with
"RAGFlow(user)> tts with 'speech-2.8-hd@test@minimax' ..." is missing a language
identifier; update the code fence in internal/development.md to include a
shell/bash language tag (e.g., change ``` to ```bash) so the block is correctly
marked for MD040 and syntax highlighting.
In `@internal/entity/models/minimax.go`:
- Around line 633-639: The code in the event.Data.Audio handling block currently
converts binary audioBytes to a raw string (chunk := string(audioBytes)) which
is not binary-safe for SSE; instead, Base64-encode the audioBytes and send that
Base64 string via sender (refer to event.Data.Audio, audioBytes, chunk and
sender in minimax.go), and update the CLI receiving path to Base64-decode before
writing/playing the file so non-UTF8 bytes aren’t corrupted.
---
Outside diff comments:
In `@internal/cli/user_command.go`:
- Around line 2023-2026: The STREAM TTS flag is parsed into cmd.Params["stream"]
by parseStreamCommand but TTSUserCommand ignores it and always calls
c.HTTPClient.Request, so streaming responses are never handled; update
TTSUserCommand to check cmd.Params["stream"] (or a typed param) and when true
call the HTTP client's streaming method (e.g., RequestStream / RequestWithStream
/ similar streaming API on c.HTTPClient) and process chunks as they arrive
(invoking the same payload handling logic per chunk), otherwise keep the
existing non-stream Request flow; ensure you reference TTSUserCommand,
parseStreamCommand, and c.HTTPClient.Request/RequestStream to locate changes.
---
Nitpick comments:
In `@internal/development.md`:
- Around line 363-364: Update the example TTS usage to save to a non-source
directory and show a relative output path: change the save directory in the
example command string (the RAGFlow(user)> tts ... save './internal' line) to a
clearer directory such as './output' or './audio_files' and update the example
output path (the Saved to directory: ... speech-2.8-hd_output.wav line) to a
corresponding relative path (e.g., ./output/speech-2.8-hd_output.wav) so users
aren’t pointed at the project source tree or a user-specific absolute path.
🪄 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: bd9e1a5a-9d62-4ca5-af63-7931ca68df21
📒 Files selected for processing (10)
conf/models/minimax.jsoninternal/cli/lexer.gointernal/cli/parser.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/development.mdinternal/entity/models/minimax.gointernal/entity/models/types.gointernal/handler/providers.go
| { | ||
| "name": "speech-2.8-hd", | ||
| "max_tokens": 8192, | ||
| "model_types": [ | ||
| "tts" | ||
| ] | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
What is the max_tokens or input text limit for MiniMax speech-2.8-hd TTS model?
💡 Result:
The MiniMax speech-2.8-hd TTS model has no documented max_tokens limit or input measured in tokens across official and third-party API docs. Instead, the input text limit is consistently 10,000 characters for synchronous requests [1][2][3][4][5]. For longer text (e.g., up to 1M characters), use asynchronous TTS [6]. One third-party source claims a 50,000 token context window [7], but this is not corroborated by API providers like MiniMax platform [8][6][3][5], Replicate [2][9], Novita [1], or Cloudflare [4], which all specify character limits.
Citations:
- 1: https://novita.ai/docs/api-reference/model-apis-minimax-speech-2.8-hd
- 2: https://replicate.com/minimax/speech-2.8-hd
- 3: https://platform.minimax.io/docs/api-reference/speech-t2a-intro
- 4: https://developers.cloudflare.com/ai/models/minimax/speech-2.8-hd/
- 5: https://platform.minimax.io/docs/guides/speech-t2a-websocket
- 6: https://platform.minimax.io/docs/guides/speech-t2a-async
- 7: https://www.mindstudio.ai/models/minimax-speech-2-8-hd/
- 8: https://platform.minimax.io/docs/guides/rate-limits
- 9: https://replicate.com/minimax/speech-2.6-hd/readme
🏁 Script executed:
# First, examine the full minimax.json file to understand context
wc -l conf/models/minimax.jsonRepository: infiniflow/ragflow
Length of output: 91
🏁 Script executed:
# Show the full file with line numbers
cat -n conf/models/minimax.jsonRepository: infiniflow/ragflow
Length of output: 2954
🏁 Script executed:
# Search for other TTS models and their max_tokens values
rg -A 5 '"tts"' conf/models/minimax.jsonRepository: infiniflow/ragflow
Length of output: 199
🏁 Script executed:
# Search codebase for how max_tokens is used, especially for TTS
rg -i 'max_tokens.*tts|tts.*max_tokens' -A 3 -B 3Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Check if there's any token/character conversion logic or documentation
rg -i 'character.*token|token.*character|tts.*limit|speech.*limit' --type json --type md --type ts --type jsRepository: infiniflow/ragflow
Length of output: 50376
🏁 Script executed:
# Search for how max_tokens is used in the codebase
rg 'max_tokens' --type ts --type js -A 2 -B 2 | head -100Repository: infiniflow/ragflow
Length of output: 6660
🏁 Script executed:
# Look for TTS-specific configuration handling
rg 'tts|speech' --type ts --type js -i -A 2 -B 2 | head -100Repository: infiniflow/ragflow
Length of output: 7025
🏁 Script executed:
# Find how model configuration files are loaded and used
rg 'minimax\.json|models\..*json' --type ts --type js | head -20Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search for LLM/model client implementations that might use max_tokens
fd -e ts -e js | xargs grep -l 'max_tokens\|model.*config' | grep -i minimax | head -10Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search for where TTS API is called and how parameters are passed
rg -i 'speech\|tts' web/src -A 5 -B 5 --type ts --type js | grep -A 10 -B 10 'max_tokens\|t2a'Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Look for backend code that handles TTS
fd -e py -e ts -e js | xargs grep -l 'speech\|t2a\|tts' | head -20Repository: infiniflow/ragflow
Length of output: 969
🏁 Script executed:
# Find the backend service that calls MiniMax API
fd -name '*.py' | xargs grep -l 'minimax\|speech' | head -10Repository: infiniflow/ragflow
Length of output: 293
🏁 Script executed:
# Check how model configuration is used in backend
fd -name '*.py' | xargs grep -l 'max_tokens' | head -10Repository: infiniflow/ragflow
Length of output: 293
🏁 Script executed:
# Examine the TTS model implementation
cat -n rag/llm/tts_model.pyRepository: infiniflow/ragflow
Length of output: 22456
🏁 Script executed:
# Look for MiniMax TTS implementation
fd -name '*.py' -path '*minimax*' | head -10Repository: infiniflow/ragflow
Length of output: 293
🏁 Script executed:
# Search in backend for how model config is loaded
rg 'minimax\.json|models.*json' rag/ --type py | head -20Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Check how max_tokens is used in TTS calls
rg 'max_tokens' rag/ --type py -B 3 -A 3 | head -80Repository: infiniflow/ragflow
Length of output: 4707
🏁 Script executed:
# Look for MiniMax-specific implementations in the codebase
fd -name '*.py' | xargs grep -l 'minimax\|speech' | grep -v testRepository: infiniflow/ragflow
Length of output: 293
🏁 Script executed:
# Search for any MiniMax TTS or chat implementation
fd -name '*.py' | xargs grep -i 'class.*minimax\|speech.*2\.8'Repository: infiniflow/ragflow
Length of output: 295
🏁 Script executed:
# Check if model config is ever loaded and how max_tokens is used
rg 'def.*chat|def.*tts' rag/llm/ --type py -A 10 | head -150Repository: infiniflow/ragflow
Length of output: 8080
🏁 Script executed:
# Search for MiniMax class implementation
rg 'class.*MiniMax|_FACTORY_NAME.*MiniMax' rag/ --type pyRepository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Look for how the model config JSON files are parsed and used
rg 'conf/models|models\..*json' rag/ --type py -A 5 -B 5 | head -100Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Check for any reference to model max_tokens in the LLM factory or loader
rg 'max_tokens.*from|read.*max_tokens' rag/ --type py | head -20Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search for where models are instantiated from config
rg 'model_name|tts.*model|speech' rag/llm/ --type py | grep -i classRepository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search for where TTS models are instantiated from the config
rg 'tts.*factory|model.*factory' rag/ --type py -A 3 -B 3 | head -100Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Look for the LLM factory that loads models from config files
fd -name '*factory*' -o -name '*loader*' | grep -E '\.py$'Repository: infiniflow/ragflow
Length of output: 293
🏁 Script executed:
# Search for where TTS models are created
rg 'TTSModel|get_tts|TTS\(' rag/ --type py -A 2 -B 2 | head -80Repository: infiniflow/ragflow
Length of output: 2478
🏁 Script executed:
# Check if max_tokens is ever passed to TTS model instantiation
rg 'def.*init.*tts|class.*TTS' rag/llm/tts_model.py -A 5 | head -60Repository: infiniflow/ragflow
Length of output: 1875
🏁 Script executed:
# Search for where models are loaded from JSON configs
rg 'json.*load|load.*json' rag/ --type py | grep -i model | head -20Repository: infiniflow/ragflow
Length of output: 1688
🏁 Script executed:
# Look for model factory or loader
fd -path '*/rag/llm*' -type f -name '*.py' | xargs lsRepository: infiniflow/ragflow
Length of output: 755
🏁 Script executed:
# Check the chat_model.py to see how it uses configuration
head -100 rag/llm/chat_model.pyRepository: infiniflow/ragflow
Length of output: 3700
🏁 Script executed:
# Search for where TTS models are created in the codebase
rg 'get_model|model.*factory|create.*model' rag/ --type py | grep -i tts | head -10Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Look for where the model configs directory is used
rg 'conf/models' rag/ --type py -B 3 -A 3Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search for how model metadata is loaded
rg 'model.*config|ModelConfig|load.*config' rag/ --type py | head -30Repository: infiniflow/ragflow
Length of output: 3796
🏁 Script executed:
# Check the API endpoints that might use TTS
rg '/chat/audio/speech|tts.*endpoint' rag/ --type py -B 3 -A 3Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search in the web/backend integration
fd -name '*.py' -path '*/rag/*' | xargs grep -l 'speech\|audio' | head -5Repository: infiniflow/ragflow
Length of output: 293
🏁 Script executed:
# Find the LLMBundle class definition
rg 'class LLMBundle' rag/ --type py -A 20Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Look for get_model_config_by_type_and_name function
rg 'def get_model_config_by_type_and_name' --type py -A 10Repository: infiniflow/ragflow
Length of output: 1247
🏁 Script executed:
# Search for TTS model usage in the codebase
rg 'LLMType\.TTS|tts_id|speech' rag/ --type py -B 3 -A 3 | head -100Repository: infiniflow/ragflow
Length of output: 4195
🏁 Script executed:
# Check if there's a MiniMax implementation anywhere
rg -i 'minimax' rag/ --type py | head -20Repository: infiniflow/ragflow
Length of output: 729
🏁 Script executed:
# Verify if max_tokens is actually used when instantiating TTS models
rg 'class.*MiniMax|minimax' rag/llm/ --type pyRepository: infiniflow/ragflow
Length of output: 151
🏁 Script executed:
# Check how the model config is loaded and if extra fields cause issues
rg 'json.*model|model.*json' api/ --type py -B 2 -A 5 | head -80Repository: infiniflow/ragflow
Length of output: 1088
🏁 Script executed:
# Search for where the model metadata from config is actually used
rg 'max_tokens' api/ --type py -B 3 -A 3 | head -60Repository: infiniflow/ragflow
Length of output: 4246
🏁 Script executed:
# Check if max_tokens from config is ever used for TTS models
rg 'max_length.*tts|tts.*max_length|max_tokens.*tts' api/ rag/ --type pyRepository: infiniflow/ragflow
Length of output: 336
🏁 Script executed:
# Look at how the TTS endpoint uses the model config
rg -i 'audio/speech|chat.*tts|speech.*chat' api/ --type py -B 5 -A 5 | head -100Repository: infiniflow/ragflow
Length of output: 5798
🏁 Script executed:
# Check LLMBundle to see if max_length is used for TTS
rg 'class LLMBundle' api/db/services/ --type py -A 30Repository: infiniflow/ragflow
Length of output: 2714
🏁 Script executed:
# Find where max_length is used in LLMBundle
rg 'self.max_length' api/db/services/ --type py -B 2 -A 2Repository: infiniflow/ragflow
Length of output: 1034
🏁 Script executed:
# Verify if max_length is ever used for TTS models by checking tts() method
rg 'def tts\(' api/db/services/ --type py -A 15 | head -100Repository: infiniflow/ragflow
Length of output: 2199
🏁 Script executed:
# Check what methods are called on TTS models
rg 'tts_mdl\.' api/db/services/ --type pyRepository: infiniflow/ragflow
Length of output: 136
Remove max_tokens from the TTS model configuration; it is not used for text-to-speech models.
The max_tokens field at lines 103-109 should be removed. Analysis of the codebase shows that max_length (derived from max_tokens in model config) is only used in the encode() method for embedding models to validate token counts. The tts() method passes text directly to the underlying TTS implementation without checking this value. Additionally, the official MiniMax documentation specifies a 10,000 character limit for speech-2.8-hd, not a token-based limit. Keeping this field in the configuration will only create unnecessary confusion.
🤖 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/minimax.json` around lines 103 - 109, Remove the unnecessary
token limit from the TTS model entry: delete the "max_tokens" property from the
"speech-2.8-hd" model definition so the configuration only contains "name" and
"model_types" (and any TTS-specific fields if present); this avoids misleading
use of max_length derived from max_tokens (used in encode()) since tts() does
not consult it and MiniMax uses a character limit instead.
| if explicitFormat != "" { | ||
| ttsConfigPayload["format"] = explicitFormat | ||
| } else { | ||
| explicitFormat = "mp3" | ||
| } | ||
|
|
||
| if len(ttsConfigPayload) > 0 { | ||
| payload["tts_config"] = ttsConfigPayload | ||
| } |
There was a problem hiding this comment.
FORMAT is not propagated to provider due to tts_config shape mismatch.
payload["tts_config"]["format"] is ignored by the backend contract (models.TTSConfig only has Params). So CLI file extension may say wav, while generated audio can still be default format.
Suggested fix
- if explicitFormat != "" {
- ttsConfigPayload["format"] = explicitFormat
- } else {
+ if explicitFormat != "" {
+ params, _ := ttsConfigPayload["params"].(map[string]interface{})
+ if params == nil {
+ params = map[string]interface{}{}
+ }
+ params["format"] = explicitFormat
+ ttsConfigPayload["params"] = params
+ } else {
explicitFormat = "mp3"
}📝 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.
| if explicitFormat != "" { | |
| ttsConfigPayload["format"] = explicitFormat | |
| } else { | |
| explicitFormat = "mp3" | |
| } | |
| if len(ttsConfigPayload) > 0 { | |
| payload["tts_config"] = ttsConfigPayload | |
| } | |
| if explicitFormat != "" { | |
| params, _ := ttsConfigPayload["params"].(map[string]interface{}) | |
| if params == nil { | |
| params = map[string]interface{}{} | |
| } | |
| params["format"] = explicitFormat | |
| ttsConfigPayload["params"] = params | |
| } else { | |
| explicitFormat = "mp3" | |
| } | |
| if len(ttsConfigPayload) > 0 { | |
| payload["tts_config"] = ttsConfigPayload | |
| } |
🤖 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 2013 - 2021, The CLI sets
explicitFormat into ttsConfigPayload["format"] but backend expects
models.TTSConfig.Params, so the format is never sent; update the payload shape
by placing the chosen format into the ttsConfigPayload.Params map (e.g., ensure
ttsConfigPayload["params"]["format"] = explicitFormat) before assigning
payload["tts_config"] = ttsConfigPayload, and keep the defaulting logic for
explicitFormat ("mp3") so file extension and provider format remain consistent;
adjust any creation of ttsConfigPayload and references to explicitFormat
accordingly.
| case TokenParam: | ||
| p.nextToken() | ||
| if p.curToken.Type != TokenQuotedString { | ||
| return nil, fmt.Errorf("expect quoted string after 'param'") | ||
| } | ||
| cmd.Params["param_str"] = strings.Trim(p.curToken.Value, "\"'") | ||
| p.nextToken() | ||
| p.nextToken() | ||
| case TokenSave: |
There was a problem hiding this comment.
PARAM branch over-advances tokens and breaks option parsing.
After reading PARAM '...', two consecutive p.nextToken() calls skip the next option keyword, causing malformed parsing for subsequent options.
Suggested fix
case TokenParam:
p.nextToken()
if p.curToken.Type != TokenQuotedString {
return nil, fmt.Errorf("expect quoted string after 'param'")
}
cmd.Params["param_str"] = strings.Trim(p.curToken.Value, "\"'")
- p.nextToken()
- p.nextToken()
+ p.nextToken()📝 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.
| case TokenParam: | |
| p.nextToken() | |
| if p.curToken.Type != TokenQuotedString { | |
| return nil, fmt.Errorf("expect quoted string after 'param'") | |
| } | |
| cmd.Params["param_str"] = strings.Trim(p.curToken.Value, "\"'") | |
| p.nextToken() | |
| p.nextToken() | |
| case TokenSave: | |
| case TokenParam: | |
| p.nextToken() | |
| if p.curToken.Type != TokenQuotedString { | |
| return nil, fmt.Errorf("expect quoted string after 'param'") | |
| } | |
| cmd.Params["param_str"] = strings.Trim(p.curToken.Value, "\"'") | |
| p.nextToken() | |
| case TokenSave: |
🤖 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_parser.go` around lines 2807 - 2815, The TokenParam branch
advances tokens one time too many and skips the next option: after matching
TokenParam and consuming the quoted value into cmd.Params["param_str"], remove
the extra p.nextToken() so you only call p.nextToken() once to move past the
quoted string (i.e., keep a single p.nextToken() after assigning to
cmd.Params["param_str"] and delete the second p.nextToken()); this fixes parsing
for subsequent options (look at the TokenParam case and uses of p.nextToken()).
|
|
||
| ### 6.23 Text to Speech | ||
|
|
||
| ``` |
There was a problem hiding this comment.
Add language identifier to code fence.
The fenced code block is missing a language identifier. Based on the content, this should be marked as a shell/bash code block.
📝 Proposed fix
-```
+```bash
RAGFlow(user)> tts with 'speech-2.8-hd@test@minimax' text 'He who desires but acts not, breeds pestilence.' play format 'wav' save './internal' param '{"voice_setting": {"voice_id": "English_radiant_girl", "speed": 1, "vol": 1, "pitch": 0}, "audio_setting": {"sample_rate": 32000, "bitrate": 128000, "format": "wav", "channel": 1}, "output_format": "hex"}'As per coding guidelines, the static analysis tool flagged this as MD040 (fenced-code-language).
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)
[warning] 362-362: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🤖 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/development.md` at line 362, The fenced code block containing the
shell command starting with "RAGFlow(user)> tts with
'speech-2.8-hd@test@minimax' ..." is missing a language identifier; update the
code fence in internal/development.md to include a shell/bash language tag
(e.g., change ``` to ```bash) so the block is correctly marked for MD040 and
syntax highlighting.
| if event.Data.Audio != "" { | ||
| audioBytes, err := hex.DecodeString(event.Data.Audio) | ||
| if err == nil && len(audioBytes) > 0 { | ||
| chunk := string(audioBytes) | ||
| if errSend := sender(&chunk, nil); errSend != nil { | ||
| return errSend | ||
| } |
There was a problem hiding this comment.
Streamed audio chunks are sent as raw string bytes and can be corrupted.
hex.DecodeString gives binary audio, but converting it to string and pushing via SSE text frames is not binary-safe. This can mangle non-UTF8 bytes and break streamed audio playback.
Suggested direction
- chunk := string(audioBytes)
- if errSend := sender(&chunk, nil); errSend != nil {
+ chunkB64 := base64.StdEncoding.EncodeToString(audioBytes)
+ if errSend := sender(&chunkB64, nil); errSend != nil {
return errSend
}Then decode Base64 on the receiving CLI stream path before file write/playback.
🤖 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 633 - 639, The code in the
event.Data.Audio handling block currently converts binary audioBytes to a raw
string (chunk := string(audioBytes)) which is not binary-safe for SSE; instead,
Base64-encode the audioBytes and send that Base64 string via sender (refer to
event.Data.Audio, audioBytes, chunk and sender in minimax.go), and update the
CLI receiving path to Base64-decode before writing/playing the file so non-UTF8
bytes aren’t corrupted.
Replaced buildTTSPayload method calls with inline payload construction.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
internal/entity/models/minimax.go (1)
636-642:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon't forward raw audio bytes through a
stringcallback.
string(audioBytes)makes this stream depend on a text-shaped transport for binary data. That is fragile once the chunk crosses JSON/SSE/logging boundaries and can corrupt playback. Encode the chunk before callingsenderand decode it at the receiving edge.Suggested direction
+// add `encoding/base64` to the imports above if event.Data.Audio != "" { audioBytes, err := hex.DecodeString(event.Data.Audio) if err == nil && len(audioBytes) > 0 { - chunk := string(audioBytes) + chunk := base64.StdEncoding.EncodeToString(audioBytes) if errSend := sender(&chunk, nil); errSend != nil { return errSend } } }To verify the downstream path is binary-safe end to end, inspect the TTS streaming caller and confirm it Base64-decodes before writing or playing audio:
#!/bin/bash set -euo pipefail rg -n -C3 --type go '\bAudioSpeechWithSender\b|\bbase64\.(StdEncoding|RawStdEncoding)\.(EncodeToString|DecodeString)\b|\bsender\(' internal🤖 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 636 - 642, The code is currently converting raw audioBytes into a string via string(audioBytes) and passing it to sender, which risks corruption; instead keep the data binary-safe by Base64-encoding audioBytes before calling sender (replace the string(audioBytes) usage with a Base64-encoded string) and update the receiving side to Base64-decode before playback; locate the audio handling in minimax.go where event.Data.Audio is decoded and sender invoked, and also update the TTS streaming caller that consumes sender to call base64.StdEncoding.DecodeString (or equivalent) before writing/playing the audio.
🤖 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/minimax.go`:
- Around line 535-547: The code currently decodes result.Data.Audio without
validating it, and hex.DecodeString("") succeeds producing a zero-length audio;
update the logic in the MiniMax TTS handling (the block that checks
result.BaseResp.StatusCode and then decodes result.Data.Audio) to explicitly
reject empty or missing audio by returning an error when result.Data.Audio == ""
(include a clear message like "empty audio from MiniMax" and return nil, error)
before calling hex.DecodeString, so TTSResponse.Audio is never a zero-byte
success.
---
Duplicate comments:
In `@internal/entity/models/minimax.go`:
- Around line 636-642: The code is currently converting raw audioBytes into a
string via string(audioBytes) and passing it to sender, which risks corruption;
instead keep the data binary-safe by Base64-encoding audioBytes before calling
sender (replace the string(audioBytes) usage with a Base64-encoded string) and
update the receiving side to Base64-decode before playback; locate the audio
handling in minimax.go where event.Data.Audio is decoded and sender invoked, and
also update the TTS streaming caller that consumes sender to call
base64.StdEncoding.DecodeString (or equivalent) before writing/playing the
audio.
🪄 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: 74c4b344-1be1-466d-90e0-94368ab1d102
📒 Files selected for processing (1)
internal/entity/models/minimax.go
| if result.BaseResp.StatusCode != 0 { | ||
| return nil, fmt.Errorf("MiniMax TTS returned error: %d - %s", result.BaseResp.StatusCode, result.BaseResp.StatusMsg) | ||
| } | ||
|
|
||
| // format HEX | ||
| audioBytes, err := hex.DecodeString(result.Data.Audio) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to decode MiniMax hex audio: %w", err) | ||
| } | ||
|
|
||
| return &TTSResponse{ | ||
| Audio: audioBytes, | ||
| }, nil |
There was a problem hiding this comment.
Reject empty data.audio responses.
hex.DecodeString("") succeeds, so a missing or empty audio field currently returns a zero-byte success response. That can turn a provider-side failure into an empty saved/played file.
Suggested fix
if result.BaseResp.StatusCode != 0 {
return nil, fmt.Errorf("MiniMax TTS returned error: %d - %s", result.BaseResp.StatusCode, result.BaseResp.StatusMsg)
}
+
+ if strings.TrimSpace(result.Data.Audio) == "" {
+ return nil, fmt.Errorf("MiniMax TTS returned empty audio")
+ }
// format HEX
audioBytes, err := hex.DecodeString(result.Data.Audio)
if err != nil {
return nil, fmt.Errorf("failed to decode MiniMax hex audio: %w", err)
}
+ if len(audioBytes) == 0 {
+ return nil, fmt.Errorf("MiniMax TTS returned empty audio")
+ }📝 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.
| if result.BaseResp.StatusCode != 0 { | |
| return nil, fmt.Errorf("MiniMax TTS returned error: %d - %s", result.BaseResp.StatusCode, result.BaseResp.StatusMsg) | |
| } | |
| // format HEX | |
| audioBytes, err := hex.DecodeString(result.Data.Audio) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to decode MiniMax hex audio: %w", err) | |
| } | |
| return &TTSResponse{ | |
| Audio: audioBytes, | |
| }, nil | |
| if result.BaseResp.StatusCode != 0 { | |
| return nil, fmt.Errorf("MiniMax TTS returned error: %d - %s", result.BaseResp.StatusCode, result.BaseResp.StatusMsg) | |
| } | |
| if strings.TrimSpace(result.Data.Audio) == "" { | |
| return nil, fmt.Errorf("MiniMax TTS returned empty audio") | |
| } | |
| // format HEX | |
| audioBytes, err := hex.DecodeString(result.Data.Audio) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to decode MiniMax hex audio: %w", err) | |
| } | |
| if len(audioBytes) == 0 { | |
| return nil, fmt.Errorf("MiniMax TTS returned empty audio") | |
| } | |
| return &TTSResponse{ | |
| Audio: audioBytes, | |
| }, nil |
🤖 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 535 - 547, The code currently
decodes result.Data.Audio without validating it, and hex.DecodeString("")
succeeds producing a zero-length audio; update the logic in the MiniMax TTS
handling (the block that checks result.BaseResp.StatusCode and then decodes
result.Data.Audio) to explicitly reject empty or missing audio by returning an
error when result.Data.Audio == "" (include a clear message like "empty audio
from MiniMax" and return nil, error) before calling hex.DecodeString, so
TTSResponse.Audio is never a zero-byte success.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14911 +/- ##
=======================================
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:
|
…iflow#14911) ### What problem does this PR solve? This PR implement TTS for MiniMax provider and CLI testing for TTS **The following functionalities are now supported:** **MiniMax:** - [x] Chat / Stream Chat - [x] Embedding - [x] Rerank - [x] Model listing - [x] Provider connection checking - [x] Text To Speech - [ ] OCRFile - [ ] ~~Audio To Text~~ - [ ] ~~Balance~~ **Verified examples from the CLI:** ```plaintext RAGFlow(user)> tts with 'speech-2.8-hd@test@minimax' text 'He who desires but acts not, breeds pestilence.' play format 'wav' save './internal' param '{"voice_setting": {"voice_id": "English_radiant_girl", "speed": 1, "vol": 1, "pitch": 0}, "audio_setting": {"sample_rate": 32000, "bitrate": 128000, "format": "wav", "channel": 1}, "output_format": "hex"}' Saved to directory: /home/infiniflow/Documents/development/ragflow/internal/speech-2.8-hd_output.wav SUCCESS RAGFlow(user)> stream tts with 'speech-2.8-hd@test@minimax' text 'He who desires but acts not, breeds pestilence.' play format 'wav' save './internal' param '{"voice_setting": {"voice_id": "English_radiant_girl", "speed": 1, "vol": 1, "pitch": 0}, "audio_setting": {"sample_rate": 32000, "bitrate": 128000, "format": "wav", "channel": 1}, "output_format": "hex"}' Saved to directory: /home/infiniflow/Documents/development/ragflow/internal/speech-2.8-hd_output.wav SUCCESS ``` Set `Play` to play audio in CLI Set `Save` `PATH_TO_SAVE` to save file Set `format` to save file in wav or mp3 Set `Param` align with official request body ### Type of change - [x] New Feature (non-breaking change which adds functionality)
What problem does this PR solve?
This PR implement TTS for MiniMax provider and CLI testing for TTS
The following functionalities are now supported:
MiniMax:
Audio To TextBalanceVerified examples from the CLI:
Set
Playto play audio in CLISet
SavePATH_TO_SAVEto save fileSet
formatto save file in wav or mp3Set
Paramalign with official request bodyType of change