Skip to content

Go: implement TTS for MiniMax provider and CLI testing for TTS - #14911

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main
May 14, 2026
Merged

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

Conversation

@Haruko386

Copy link
Copy Markdown
Member

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:

  • Chat / Stream Chat
  • Embedding
  • Rerank
  • Model listing
  • Provider connection checking
  • Text To Speech
  • OCRFile
  • Audio To Text
  • Balance

Verified examples from the CLI:

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

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 14, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 14, 2026
@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Minimax TTS Feature

Layer / File(s) Summary
Token types and lexer support for TTS command options
internal/cli/types.go, internal/cli/lexer.go, internal/cli/parser.go
Adds TokenFormat, TokenParam, TokenPlay, and TokenSave as reserved keywords in the token list and lexer, enabling the parser to recognize TTS command options.
TTS request/response data shapes and API contracts
internal/entity/models/types.go, internal/handler/providers.go
Extends TTSResponse with Audio []byte, adds TTS endpoint suffix to URLSuffix, adds Params to TTSConfig, and replaces prior audio request fields with optional tts_config in AudioSpeechRequest.
Minimax provider TTS implementation
internal/entity/models/minimax.go
Implements AudioSpeech (non-streaming HEX audio decode) and AudioSpeechWithSender (SSE-style streaming with chunk forwarding), and adds encoding/hex import.
CLI TTS command parsing and execution
internal/cli/user_parser.go, internal/cli/user_command.go
Rewrites parseTTSCommand to parse PLAY, PARAM, SAVE, FORMAT options; TTSUserCommand builds tts_config from params with format inference, decodes base64 audio responses, writes audio files, optionally plays via aplay, and saves to configured directories.
Model configuration and documentation
conf/models/minimax.json, internal/development.md
Adds speech-2.8-hd TTS model config (max_tokens: 8192, model_types: ["tts"]) and documents the CLI tts command usage and example output.

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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • infiniflow/ragflow#14836: Introduces initial ASR/TTS CLI/provider plumbing and Minimax driver stubs that this PR extends with full Minimax TTS implementation and richer CLI handling.

Suggested labels

size:XXL

Poem

🐰 I hop through code with tiny paws,
I parse your tokens, mind the clause,
I turn your text to music bright,
Save, play, decode through day and night,
A rabbit sings — TTS takes flight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: implementing TTS for MiniMax provider and adding CLI testing for TTS.
Description check ✅ Passed The description follows the template with both required sections completed: problem statement explains TTS implementation for MiniMax, and type of change is marked as 'New Feature'.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

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.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Haruko386
Haruko386 marked this pull request as draft May 14, 2026 02:29
@Haruko386
Haruko386 marked this pull request as ready for review May 14, 2026 02:29
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 14, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 TTS flag is parsed but never used by the CLI execution path.

parseStreamCommand can set cmd.Params["stream"]=true, but TTSUserCommand always calls non-stream Request(...) 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 value

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between b2b6360 and c2fd8ea.

📒 Files selected for processing (10)
  • conf/models/minimax.json
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/development.md
  • internal/entity/models/minimax.go
  • internal/entity/models/types.go
  • internal/handler/providers.go

Comment thread conf/models/minimax.json
Comment on lines +103 to 109
{
"name": "speech-2.8-hd",
"max_tokens": 8192,
"model_types": [
"tts"
]
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 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:


🏁 Script executed:

# First, examine the full minimax.json file to understand context
wc -l conf/models/minimax.json

Repository: infiniflow/ragflow

Length of output: 91


🏁 Script executed:

# Show the full file with line numbers
cat -n conf/models/minimax.json

Repository: 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.json

Repository: 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 3

Repository: 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 js

Repository: 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 -100

Repository: 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 -100

Repository: 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 -20

Repository: 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 -10

Repository: 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 -20

Repository: 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 -10

Repository: 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 -10

Repository: infiniflow/ragflow

Length of output: 293


🏁 Script executed:

# Examine the TTS model implementation
cat -n rag/llm/tts_model.py

Repository: infiniflow/ragflow

Length of output: 22456


🏁 Script executed:

# Look for MiniMax TTS implementation
fd -name '*.py' -path '*minimax*' | head -10

Repository: 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 -20

Repository: 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 -80

Repository: 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 test

Repository: 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 -150

Repository: infiniflow/ragflow

Length of output: 8080


🏁 Script executed:

# Search for MiniMax class implementation
rg 'class.*MiniMax|_FACTORY_NAME.*MiniMax' rag/ --type py

Repository: 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 -100

Repository: 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 -20

Repository: 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 class

Repository: 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 -100

Repository: 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 -80

Repository: 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 -60

Repository: 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 -20

Repository: infiniflow/ragflow

Length of output: 1688


🏁 Script executed:

# Look for model factory or loader
fd -path '*/rag/llm*' -type f -name '*.py' | xargs ls

Repository: 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.py

Repository: 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 -10

Repository: 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 3

Repository: 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 -30

Repository: 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 3

Repository: 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 -5

Repository: infiniflow/ragflow

Length of output: 293


🏁 Script executed:

# Find the LLMBundle class definition
rg 'class LLMBundle' rag/ --type py -A 20

Repository: 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 10

Repository: 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 -100

Repository: infiniflow/ragflow

Length of output: 4195


🏁 Script executed:

# Check if there's a MiniMax implementation anywhere
rg -i 'minimax' rag/ --type py | head -20

Repository: 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 py

Repository: 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 -80

Repository: 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 -60

Repository: 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 py

Repository: 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 -100

Repository: 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 30

Repository: 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 2

Repository: 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 -100

Repository: infiniflow/ragflow

Length of output: 2199


🏁 Script executed:

# Check what methods are called on TTS models
rg 'tts_mdl\.' api/db/services/ --type py

Repository: 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.

Comment on lines +2013 to +2021
if explicitFormat != "" {
ttsConfigPayload["format"] = explicitFormat
} else {
explicitFormat = "mp3"
}

if len(ttsConfigPayload) > 0 {
payload["tts_config"] = ttsConfigPayload
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +2807 to +2815
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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

Suggested change
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()).

Comment thread internal/development.md

### 6.23 Text to Speech

```

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Comment on lines +633 to +639
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
internal/entity/models/minimax.go (1)

636-642: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't forward raw audio bytes through a string callback.

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 calling sender and 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

📥 Commits

Reviewing files that changed from the base of the PR and between c2fd8ea and ab85bb2.

📒 Files selected for processing (1)
  • internal/entity/models/minimax.go

Comment on lines +535 to +547
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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

codecov Bot commented May 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (b2b6360) to head (ab85bb2).
⚠️ Report is 3 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit ef46005 into infiniflow:main May 14, 2026
1 check passed
tmimmanuel pushed a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants