Repository navigation
Go: add token usage for baidu, minimax, moonshot and mistral - #17413
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughBaidu, MiniMax, Moonshot, and Mistral now parse chat responses through typed schemas with normalized reasoning, tool calls, token usage, and streaming usage. Mistral also implements audio transcription and speech generation, with related model and endpoint configuration updates. ChangesProvider model capabilities
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant TranscribeAudio
participant MistralASR
Client->>TranscribeAudio: provide audio file and options
TranscribeAudio->>MistralASR: send multipart transcription request
MistralASR-->>TranscribeAudio: return JSON text
TranscribeAudio-->>Client: return ASRResponse
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
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: 4
🧹 Nitpick comments (3)
internal/entity/models/minimax.go (1)
89-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate error-extraction logic alongside
extractMinimaxAPIError.
extractMinimaxAPIError(Line 120) implements the samebase_resp/error.messageprecedence over the untyped event map. Consider having the streaming path re-marshal/decode into the typed struct (or share a small typedbaseResp/errorvalue) so the precedence rules live in one place.As per coding guidelines: "Prefer one implementation path instead of preserving old and new versions side by side".
🤖 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 89 - 100, Consolidate the duplicate error-precedence logic between extractMinimaxChatResponseError and extractMinimaxAPIError. Make the streaming path reuse the typed response extraction or a shared base_resp/error helper, preserving status message, status code, and error.message precedence while leaving only one implementation of these rules.Source: Coding guidelines
internal/entity/models/baidu.go (2)
53-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winResponse schemas are exported but only consumed by their own package-private extractors. Each new provider schema is a
type XxxChatResponse structreachable from outside the package with no external consumer, widening the public surface for internal decoding types.
internal/entity/models/baidu.go#L53-L82: renameBaiduChatResponsetobaiduChatResponse.internal/entity/models/minimax.go#L55-L87: renameMinimaxChatResponsetominimaxChatResponse(and the*MinimaxChatResponseparameter ofextractMinimaxChatResponseError).internal/entity/models/mistral.go#L57-L82: renameMistralChatResponsetomistralChatResponse.internal/entity/models/moonshot.go#L54-L75: renameMoonshotChatResponsetomoonshotChatResponse.As per coding guidelines: "Reduce public surface area by making helpers private or internal when external access is unnecessary."
#!/bin/bash # Confirm no out-of-package references to the new response types rg -nP --type=go '\b(Baidu|Minimax|Mistral|Moonshot)ChatResponse\b' -C1🤖 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/baidu.go` around lines 53 - 82, Make the provider response schemas package-private: rename BaiduChatResponse to baiduChatResponse in internal/entity/models/baidu.go, MinimaxChatResponse to minimaxChatResponse and update the *MinimaxChatResponse parameter of extractMinimaxChatResponseError in internal/entity/models/minimax.go, MistralChatResponse to mistralChatResponse in internal/entity/models/mistral.go, and MoonshotChatResponse to moonshotChatResponse in internal/entity/models/moonshot.go. Update all in-package references while preserving decoding behavior; no direct change is required beyond these renames.Source: Coding guidelines
202-213: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winIdentical total-token fallback block copied into all four extractors. The same "use
total_tokens, else prompt+completion, else nil" logic is repeated verbatim; it belongs next toparseChatCompletionResponseininternal/entity/models/base_model.goas a small helper such asnewTokenUsage(prompt, completion, total int) *TokenUsage.
internal/entity/models/baidu.go#L202-L213: replace with a call to the shared helper usingresult.Usagefields.internal/entity/models/minimax.go#L252-L263: replace with the same helper call.internal/entity/models/mistral.go#L151-L162: replace with the same helper call.internal/entity/models/moonshot.go#L176-L187: replace with the same helper call.🤖 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/baidu.go` around lines 202 - 213, Centralize the repeated total-token fallback by adding a helper such as newTokenUsage near parseChatCompletionResponse in internal/entity/models/base_model.go; it should use total when positive, otherwise prompt plus completion, and return nil when the resulting total is not positive. Replace the duplicated blocks with helper calls in internal/entity/models/baidu.go:202-213, internal/entity/models/minimax.go:252-263, internal/entity/models/mistral.go:151-162, and internal/entity/models/moonshot.go:176-187, passing each result.Usage prompt, completion, and total fields.
🤖 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/longcat.json`:
- Line 13: Align the LongCat model identifiers across the provider metadata and
tests: update conf/llm_factories.json, conf/all_models.json, and the LongCat
tests in internal/entity/models/longcat_test.go to consistently retain the
existing LongCat-Flash-* models or remove them alongside the LongCat-2.0
replacement. Ensure no stale identifiers remain and the chosen model set matches
the supported API models.
In `@conf/models/minimax.json`:
- Around line 5-12: Update the MiniMax URL suffix values under url_suffix so
each begins with a slash, ensuring direct concatenation with the default and
global base URLs produces valid paths such as /v1/text/chatcompletion_v2 and
/v1/models. Apply this consistently to chat, models, tts, and files.
In `@internal/entity/models/baidu.go`:
- Around line 186-200: Update the response parsing around choice.Message.Content
and choice.Message.ReasoningContent to treat nil values as empty strings instead
of returning errors. Preserve the existing reasoning-content trimming behavior,
and ensure tool-call completions continue through parsing so their tool calls
are retained.
In `@internal/entity/models/mistral.go`:
- Around line 76-78: Update PromptTokenDetails to use Mistral’s
prompt_tokens_details JSON key so unmarshalling binds the nested data correctly;
if the field is not needed anywhere, remove PromptTokenDetails instead.
---
Nitpick comments:
In `@internal/entity/models/baidu.go`:
- Around line 53-82: Make the provider response schemas package-private: rename
BaiduChatResponse to baiduChatResponse in internal/entity/models/baidu.go,
MinimaxChatResponse to minimaxChatResponse and update the *MinimaxChatResponse
parameter of extractMinimaxChatResponseError in
internal/entity/models/minimax.go, MistralChatResponse to mistralChatResponse in
internal/entity/models/mistral.go, and MoonshotChatResponse to
moonshotChatResponse in internal/entity/models/moonshot.go. Update all
in-package references while preserving decoding behavior; no direct change is
required beyond these renames.
- Around line 202-213: Centralize the repeated total-token fallback by adding a
helper such as newTokenUsage near parseChatCompletionResponse in
internal/entity/models/base_model.go; it should use total when positive,
otherwise prompt plus completion, and return nil when the resulting total is not
positive. Replace the duplicated blocks with helper calls in
internal/entity/models/baidu.go:202-213,
internal/entity/models/minimax.go:252-263,
internal/entity/models/mistral.go:151-162, and
internal/entity/models/moonshot.go:176-187, passing each result.Usage prompt,
completion, and total fields.
In `@internal/entity/models/minimax.go`:
- Around line 89-100: Consolidate the duplicate error-precedence logic between
extractMinimaxChatResponseError and extractMinimaxAPIError. Make the streaming
path reuse the typed response extraction or a shared base_resp/error helper,
preserving status message, status code, and error.message precedence while
leaving only one implementation of these rules.
🪄 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 Plus
Run ID: 1158a7e2-0ac9-41c8-958b-75d21c8e76b1
📒 Files selected for processing (8)
conf/models/longcat.jsonconf/models/minimax.jsoninternal/entity/models/baidu.gointernal/entity/models/base_model.gointernal/entity/models/minimax.gointernal/entity/models/mistral.gointernal/entity/models/moonshot.gointernal/entity/models/moonshot_test.go
| }, | ||
| { | ||
| "name": "LongCat-2.0-Preview", | ||
| "name": "LongCat-2.0", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -n 'LongCat-(Flash|2\.0)' .Repository: infiniflow/ragflow
Length of output: 3703
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- longcat model config ---\n'
sed -n '1,60p' conf/models/longcat.json
printf '\n--- key source files ---\n'
for f in \
internal/entity/models/longcat.go \
internal/entity/models/longcat_test.go \
internal/llm_factories.json \
conf/llm_factories.json \
conf/all_models.json \
docs/release_notes.md
do
if [ -f "$f" ]; then
echo "### $f"
wc -l "$f"
fi
done
printf '\n--- longcat.go outline and relevant sections ---\n'
ast-grep outline internal/entity/models/longcat.go --view expanded || true
sed -n '1,220p' internal/entity/models/longcat.go
printf '\n--- all_models longcat surrounding lines ---\n'
sed -n '33660,33710p' conf/all_models.json
printf '\n--- llm_factories LongCat relevant sections ---\n'
sed -n '6660,6695p' conf/llm_factories.jsonRepository: infiniflow/ragflow
Length of output: 247
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- longcat model config ---'
sed -n '1,60p' conf/models/longcat.json
echo
echo '--- key source files line counts ---'
for f in \
internal/entity/models/longcat.go \
internal/entity/models/longcat_test.go \
conf/llm_factories.json \
conf/all_models.json \
docs/release_notes.md
do
if [ -f "$f" ]; then
wc -l "$f"
fi
done
echo
echo '--- longcat.go relevant sections ---'
ast-grep outline internal/entity/models/longcat.go --view expanded || true
sed -n '1,220p' internal/entity/models/longcat.go
echo
echo '--- all_models longcat surrounding lines ---'
sed -n '33660,33710p' conf/all_models.json
echo
echo '--- llm_factories LongCat relevant sections ---'
sed -n '6660,6695p' conf/llm_factories.jsonRepository: infiniflow/ragflow
Length of output: 12844
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- get model URL / model lookup usages ---'
rg -n 'func \w+.*GetModel|GetModelUrl|model url|model_url|llm_name|models/|LongCat' internal common conf -g '*.go' -g '*.json' -g '!conf/all_models.json' | head -n 200
echo
echo '--- model source names for LongCat config/class ---'
python3 - <<'PY'
import json, pathlib
for p in pathlib.Path('config,')rg -n 'func \w+.*GetModel|GetModelUrl|model url|model_url|llm_name|models/|LongCat' internal common conf -g '*.go' -g '*.json' -g '!conf/all_models.json' | head -n 200
print
print('--- model source names for LongCat configuration files ---')import json, pathlib
for p in [
pathlib.Path('internal/entity/models/longcat.go'),
pathlib.Path('internal/llm_factories.json'),
pathlib.Path('conf/llm_factories.json'),
pathlib.Path('conf/models/longcat.json'),
]:
if not p.exists():
print(f'MISSING {p}')
continue
s=p.read_text()
lines=s.splitlines()
if p.suffix=='.go':
print(f'\n--- {p} ---')
out=[]
for i,l in enumerate(lines,1):
if 'LongCat' in l or 'longcat' in l:
out.append((i,l))
for i,l in out[:80]:
print(f'{i}:{l}')
else:
print(f'\n--- {p} ---')
data=json.loads(s)
def walk(x,path=()):
if isinstance(x,dict):
items={}
for k,v in x.items():
`#print`("ITEMS",items)
if k in {'name','models','llm','llm_name'} or isinstance(k,str) and 'model' in k.lower():
items[k]=v
if items:
print(path, items)
for k,v in x.items():
walk(v,path+(k,))
elif isinstance(x,list):
for idx,v in enumerate(x):
walk(v,path+(str(idx),))
main=find_longcat='s')
print("json")
walk(data)
PY
echo
echo '--- exact model names in conf/models and conf/llm_factories ---'
python3 - <<'PY'
import json, pathlib
for f in ["conf/models/longcat.json", "conf/llm_factories.json", "internal/llm_factories.json"]:
p=pathlib.Path(f)
if not p.exists(): continue
print(f"--- {f} ---")
data=json.loads(p.read_text())
def find_models(x, path=()):
if isinstance(x, dict):
if x.get("class") == "longcat" or x.get("name") == "LongCat" or x.get("name") == "longcat":
print(path, "MATCH", {k:x.get(k) for k in ["name","class","url","models","llm_name","llm"]})
print(data.get("name"), data.get("class"))
for k,v in x.items():
if k in ("models","llm"):
for i,item in enumerate(v):
if isinstance(item, dict):
print(k[i], item.get("name"), item.get("llm_name"))
else:
find_models(v, path+(k,))
elif isinstance(x, list):
for i,v in enumerate(x):
find_models(v, path+(str(i),))
find_models(data)
PYRepository: infiniflow/ragflow
Length of output: 23239
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- provider model lookup implementation ---'
sed -n '500,565p' internal/entity/models/model.go
echo
echo '--- LongCat model tests around model name expectations ---'
sed -n '88,170p' internal/entity/models/longcat_test.go
sed -n '440,488p' internal/entity/models/longcat_test.go
echo
echo '--- provider factory LongCat model registration ---'
sed -n '90,112p' internal/entity/models/factory.go
echo
echo '--- all model JSON LongCat factory definition ---'
python3 - <<'PY'
import json
p='conf/all_models.json'
data=json.load(open(p))
providers=data.get('providers', [])
for k,v in enumerate(providers):
if isinstance(v, dict) and 'name' in v and v['name'].lower() == 'longcat':
print('provider_index', k)
print(json.dumps(v, indent=2)[:8000])
PY
echo
echo '--- all LongCat references split by relevant patterns ---'
rg -n '"LongCat-2\.0"|"LongCat-Flash-Chat"|"LongCat-Flash-Thinking"|Name:\s*"[Ll]ongCat"|class:\s*"longcat"|name:\s*"LongCat"|class:\s*LongCat' internal conf -g '*.go' -g '*.json' -g '!conf/all_models.json'Repository: infiniflow/ragflow
Length of output: 9865
Align LongCat model metadata with the renamed identifier.
conf/models/longcat.json now declares only LongCat-2.0, but conf/llm_factories.json, conf/all_models.json, and internal/entity/models/longcat_test.go still expose or exercise LongCat-Flash-*. Either keep the LongCat-Flash-* models in the provider metadata/tests if those API models still exist, or remove them consistently when replacing LongCat with LongCat-2.0.
🤖 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/longcat.json` at line 13, Align the LongCat model identifiers
across the provider metadata and tests: update conf/llm_factories.json,
conf/all_models.json, and the LongCat tests in
internal/entity/models/longcat_test.go to consistently retain the existing
LongCat-Flash-* models or remove them alongside the LongCat-2.0 replacement.
Ensure no stale identifiers remain and the chosen model set matches the
supported API models.
| "default": "https://api.minimaxi.com/v1", | ||
| "global": "https://api.minimax.io/v1" | ||
| }, | ||
| "url_suffix": { | ||
| "chat": "v1/text/chatcompletion_v2", | ||
| "models": "v1/models", | ||
| "tts": "v1/t2a_v2", | ||
| "files": "v1/files/list" | ||
| "chat": "text/chatcompletion_v2", | ||
| "models": "models", | ||
| "tts": "t2a_v2", | ||
| "files": "files/list" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Add the missing separator between the MiniMax base URLs and suffixes.
The URL builder concatenates these strings directly, so the current values produce paths such as /v1text/chatcompletion_v2 and /v1models. All MiniMax requests will target invalid endpoints.
Proposed fix
- "default": "https://api.minimaxi.com/v1",
- "global": "https://api.minimax.io/v1"
+ "default": "https://api.minimaxi.com/v1/",
+ "global": "https://api.minimax.io/v1/"📝 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.
| "default": "https://api.minimaxi.com/v1", | |
| "global": "https://api.minimax.io/v1" | |
| }, | |
| "url_suffix": { | |
| "chat": "v1/text/chatcompletion_v2", | |
| "models": "v1/models", | |
| "tts": "v1/t2a_v2", | |
| "files": "v1/files/list" | |
| "chat": "text/chatcompletion_v2", | |
| "models": "models", | |
| "tts": "t2a_v2", | |
| "files": "files/list" | |
| "default": "https://api.minimaxi.com/v1/", | |
| "global": "https://api.minimax.io/v1/" | |
| }, | |
| "url_suffix": { | |
| "chat": "text/chatcompletion_v2", | |
| "models": "models", | |
| "tts": "t2a_v2", | |
| "files": "files/list" |
🤖 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 5 - 12, Update the MiniMax URL suffix
values under url_suffix so each begins with a slash, ensuring direct
concatenation with the default and global base URLs produces valid paths such as
/v1/text/chatcompletion_v2 and /v1/models. Apply this consistently to chat,
models, tts, and files.
| PromptTokenDetails struct { | ||
| CachedTokens int `json:"cached_tokens"` | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Missing JSON tag on PromptTokenDetails.
Every sibling field is tagged; this one falls back to case-insensitive name matching and will never bind Mistral's prompt_tokens_details. It is currently unread, so this is a latent schema bug rather than a live one. Consider dropping the field if it isn't needed.
🐛 Proposed fix
PromptTokenDetails struct {
CachedTokens int `json:"cached_tokens"`
- }
+ } `json:"prompt_tokens_details"`📝 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.
| PromptTokenDetails struct { | |
| CachedTokens int `json:"cached_tokens"` | |
| } | |
| PromptTokenDetails struct { | |
| CachedTokens int `json:"cached_tokens"` | |
| } `json:"prompt_tokens_details"` |
🤖 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/mistral.go` around lines 76 - 78, Update
PromptTokenDetails to use Mistral’s prompt_tokens_details JSON key so
unmarshalling binds the nested data correctly; if the field is not needed
anywhere, remove PromptTokenDetails instead.
|
got some problem with |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
internal/entity/models/mistral.go (3)
330-339: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueUntagged nested
PromptTokenDetailswon't bindprompt_tokens_detailshere either. Mirrors the same schema gap inMistralChatResponse.Usage; add the tag or drop the unread field.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/mistral.go` around lines 330 - 339, Update the nested PromptTokenDetails field in Usage to bind the API’s prompt_tokens_details JSON property by adding the appropriate JSON tag, or remove the field if it is not consumed; keep the surrounding token usage fields unchanged.
700-701: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStale comment: the payload is base64, not HEX. Remove or correct it.
♻️ Proposed fix
- // format HEX audioBytes, err := base64.StdEncoding.DecodeString(result.AudioData)🤖 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/mistral.go` around lines 700 - 701, Update the comment immediately above the base64.StdEncoding.DecodeString call in the audio decoding flow to describe the payload as base64, or remove the stale format comment entirely.Source: Coding guidelines
522-544: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winWhole audio file is buffered in memory.
bytes.Buffer+io.Copyholds the entire upload (plus multipart overhead) in RAM; considerio.Pipewith a goroutine writing parts so the body streams.🤖 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/mistral.go` around lines 522 - 544, Update the multipart upload flow around the audio-file handling to stream the request body instead of accumulating it in the bytes.Buffer. Use an io.Pipe with a writer goroutine that creates the multipart form part, copies audioFile into it, closes the multipart writer, and propagates write errors; pass the pipe reader to the request while preserving the existing file-opening and filename behavior.
🤖 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/mistral.json`:
- Around line 26-37: Update the Mistral model configuration by removing
voxtral-mini-transcribe-realtime-2602 from the ASR model_types list and
registering the supported batch transcription model voxtral-mini-latest instead.
Leave the voxtral-mini-tts-2603 TTS entry unchanged.
In `@internal/entity/models/mistral_test.go`:
- Around line 441-458: In the multipart request handler around MultipartReader,
NextPart, and io.ReadAll, replace each t.Fatalf error path with t.Errorf
followed immediately by return so the handler exits cleanly after reporting the
failure and does not truncate the client response.
In `@internal/entity/models/mistral.go`:
- Around line 637-650: Update the audio-generation method around the existing
audioContent validation to also reject nil or blank modelName values, matching
TranscribeAudio’s validation behavior. Before building reqBody, trim and
dereference modelName, then pass the resulting string rather than the pointer as
the "model" field.
---
Nitpick comments:
In `@internal/entity/models/mistral.go`:
- Around line 330-339: Update the nested PromptTokenDetails field in Usage to
bind the API’s prompt_tokens_details JSON property by adding the appropriate
JSON tag, or remove the field if it is not consumed; keep the surrounding token
usage fields unchanged.
- Around line 700-701: Update the comment immediately above the
base64.StdEncoding.DecodeString call in the audio decoding flow to describe the
payload as base64, or remove the stale format comment entirely.
- Around line 522-544: Update the multipart upload flow around the audio-file
handling to stream the request body instead of accumulating it in the
bytes.Buffer. Use an io.Pipe with a writer goroutine that creates the multipart
form part, copies audioFile into it, closes the multipart writer, and propagates
write errors; pass the pipe reader to the request while preserving the existing
file-opening and filename behavior.
🪄 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 Plus
Run ID: 95a6e3fb-8f6f-4d1b-9e38-c679a22edf09
📒 Files selected for processing (3)
conf/models/mistral.jsoninternal/entity/models/mistral.gointernal/entity/models/mistral_test.go
| { | ||
| "name": "voxtral-mini-tts-2603", | ||
| "model_types": [ | ||
| "tts" | ||
| ] | ||
| }, | ||
| { | ||
| "name": "voxtral-mini-transcribe-realtime-2602", | ||
| "model_types": [ | ||
| "asr" | ||
| ] | ||
| }, |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Mistral Voxtral transcription and TTS model names v1/audio/transcriptions v1/audio/speech
💡 Result:
Mistral's audio capabilities are powered by the Voxtral model family, which provides both speech-to-text (transcription) and text-to-speech (TTS) functionalities via standard API endpoints [1][2][3]. Audio Transcription Transcription services are accessed via the /v1/audio/transcriptions endpoint [4][5]. This endpoint supports various models in the Voxtral family, including: - Voxtral Mini Transcribe 2: Designed for high-accuracy batch processing with support for speaker diarization [1][6]. - Voxtral Realtime: Optimized for low-latency streaming applications, configurable down to sub-200ms delays [1]. In API requests, users typically specify these models using identifiers such as voxtral-mini-latest, voxtral-mini-2507, or voxtral-mini-2602 [5][7]. Audio Speech (TTS) Text-to-speech generation is accessed via the /v1/audio/speech endpoint [8][9]. The primary model for this service is Voxtral TTS (also identified as Voxtral-4B-TTS-2603), a 4-billion parameter model capable of multilingual voice generation and zero-shot voice cloning [10][2]. - Model ID: voxtral-mini-tts-latest is commonly used in API calls to reference the latest TTS capabilities [2][11]. - Technical Specs: The model supports inputs in 9 languages and can be used for enterprise voice agents or scalable audio generation workflows [2]. API Usage Both endpoints follow standard RESTful patterns for input submission [4][8]. - Transcription: Accepts file uploads or file URLs [4][7]. - Speech: Accepts text input along with optional parameters for voice selection (voice_id) and response format (e.g., wav, pcm, mp3) [8][12]. These models are part of the broader Voxtral ecosystem, which extends the capabilities of the Ministral/Mistral architecture to handle audio-modal inputs [3]. Documentation and SDK support are available for both Python and TypeScript via the official Mistral AI client libraries [13][7][9].
Citations:
- 1: https://mistral.ai/news/voxtral-transcribe-2/
- 2: https://mistral.ai/news/voxtral-tts/
- 3: https://huggingface.co/docs/transformers/v5.1.0/model_doc/voxtral
- 4: https://docs.mistral.ai/api/endpoint/audio/transcriptions
- 5: https://docs.mistral.ai/capabilities/audio_transcription/basic_transcription
- 6: https://mistral.ai/pricing/api/
- 7: https://github.com/mistralai/client-python/blob/main/docs/sdks/transcriptions/README.md
- 8: https://docs.mistral.ai/api/endpoint/audio/speech
- 9: https://github.com/mistralai/client-ts/blob/HEAD/docs/sdks/speech/README.md
- 10: https://huggingface.co/mistralai/Voxtral-4B-TTS-2603
- 11: https://mistral.ai/it/models/
- 12: https://github.com/mistralai/client-python/blob/37331654/src/mistralai/client/speech.py
- 13: https://github.com/mistralai/client-ts/blob/HEAD/docs/sdks/transcriptions/README.md
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== candidate files =="
fd -a 'mistral\.(json|ya?ml)$|models|mistral' . | sed 's#^\./##' | head -80
echo
echo "== conf/models/mistral.json if present =="
if [ -f conf/models/mistral.json ]; then
nl -ba conf/models/mistral.json | sed -n '1,120p'
fi
echo
echo "== references to Voxtral IDs =="
rg -n "voxtral-mini-(transcribe|tts|realtime)|v1/audio/(transcriptions|speech|realtime)|mistral" -S . --glob '!vendor/**' --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' | head -200Repository: infiniflow/ragflow
Length of output: 2230
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== conf/models/mistral.json =="
awk '{printf "%6d\t%s\n", NR, $0}' conf/models/mistral.json | sed -n '1,140p'
echo
echo "== all_models references to mistral audio models/endpoints =="
rg -n "voxtral|v1/audio/(transcriptions|speech|realtime)|transcribe-realtime|mini-tts|mini-transcribe" conf internal test web --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' || trueRepository: infiniflow/ragflow
Length of output: 6300
🌐 Web query:
Mistral API v1/audio/transcriptions supported models voxtral-mini-realtime
💡 Result:
The Mistral API v1/audio/transcriptions endpoint is designed for batch transcription and currently supports the Voxtral Mini Transcribe models (e.g., voxtral-mini-latest) [1][2][3]. It does not natively support the "voxtral-mini-realtime" model for the /v1/audio/transcriptions endpoint [3][4]. The Voxtral Realtime model (specifically identified as mistralai/Voxtral-Mini-4B-Realtime-2602) is a distinct, open-weights model built for live, low-latency streaming applications using a WebSocket-based architecture, typically served via vLLM's /v1/realtime endpoint rather than the batch audio/transcriptions API [3][5][6][7]. In summary: - /v1/audio/transcriptions: Intended for batch processing; supports models like voxtral-mini-latest [1][2]. - /v1/realtime: Intended for live streaming; utilizes Voxtral Realtime (e.g., mistralai/Voxtral-Mini-4B-Realtime-2602) [3][5][7].
Citations:
- 1: https://docs.mistral.ai/capabilities/audio_transcription/basic_transcription
- 2: https://docs.mistral.ai/studio-api/audio/speech_to_text/offline_transcription
- 3: https://docs.mistral.ai/studio-api/audio/speech_to_text
- 4: https://docs.mistral.ai/studio-api/audio/overview
- 5: https://huggingface.co/mistralai/Voxtral-Mini-4B-Realtime-2602
- 6: https://recipes.vllm.ai/mistralai/Voxtral-Mini-4B-Realtime-2602
- 7: https://docs.baseten.co/examples/models/transcription/voxtral
🌐 Web query:
Mistral API v1/audio/speech supported models Voxtral Mini TTS 2603
💡 Result:
Voxtral Mini TTS 2603 (model identifier: voxtral-mini-tts-2603) is a text-to-speech model offered by Mistral AI, accessible via the /v1/audio/speech API endpoint [1][2][3]. Key details about the model and its API integration include: Model Capabilities: Voxtral Mini TTS 2603 is a 4-billion-parameter model designed for high-quality, multilingual text-to-speech generation [4][5][6]. It supports nine languages (English, French, German, Spanish, Dutch, Portuguese, Italian, Hindi, and Arabic) and features zero-shot voice cloning, allowing users to clone a voice from a reference audio sample as short as 2–3 seconds [4][5][7]. API Endpoint: The model is used with the standard Mistral API POST /v1/audio/speech endpoint [1][8][3]. When making a request, you specify the model as voxtral-mini-tts-2603 [2][7]. Supported Parameters: - model: voxtral-mini-tts-2603 [2][3] - input: The text you wish to convert to speech [2][7]. - voice_id: The identifier for the desired voice (preset or cloned) [2][7]. - response_format: Supported formats include pcm, wav, mp3, flac, and opus [1][2][6]. Performance: The model is optimized for low-latency applications, providing a processing latency of approximately 90ms, making it suitable for real-time voice agents [5][3][9]. It is available both as a managed cloud API service and as open weights for self-deployment under the CC BY-NC 4.0 license [4][3][7].
Citations:
- 1: https://docs.mistral.ai/api/endpoint/audio/speech
- 2: https://docs.mistral.ai/studio-api/audio/text_to_speech/speech
- 3: https://docs.mistral.ai/models/model-cards/voxtral-tts-26-03
- 4: https://mistral.ai/news/voxtral-tts/
- 5: https://docs.mistral.ai/studio-api/audio/overview
- 6: https://huggingface.co/mistralai/Voxtral-4B-TTS-2603/blob/refs%2Fpr%2F3/README.md
- 7: https://www.datacamp.com/blog/voxtral-tts
- 8: https://github.com/mistralai/client-ts/blob/HEAD/docs/sdks/speech/README.md
- 9: https://docs.mistral.ai/studio-api/audio/text_to_speech
Remove the realtime transcription model from Mistral’s ASR list. voxtral-mini-tts-2603 matches the documented /v1/audio/speech TTS model, but voxtral-mini-transcribe-realtime-2602 is for realtime streaming and is not served by the batch ASR endpoint configured above. Register a supported batch transcription model such as voxtral-mini-latest instead.
🤖 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/mistral.json` around lines 26 - 37, Update the Mistral model
configuration by removing voxtral-mini-transcribe-realtime-2602 from the ASR
model_types list and registering the supported batch transcription model
voxtral-mini-latest instead. Leave the voxtral-mini-tts-2603 TTS entry
unchanged.
| reader, err := r.MultipartReader() | ||
| if err != nil { | ||
| t.Fatalf("MultipartReader: %v", err) | ||
| } | ||
| fields := make(map[string]string) | ||
| var fileName, fileBody string | ||
| for { | ||
| part, err := reader.NextPart() | ||
| if err == io.EOF { | ||
| break | ||
| } | ||
| if err != nil { | ||
| t.Fatalf("NextPart: %v", err) | ||
| } | ||
| data, err := io.ReadAll(part) | ||
| if err != nil { | ||
| t.Fatalf("ReadAll part: %v", err) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use t.Errorf + return instead of t.Fatalf inside the handler goroutine. t.Fatalf calls runtime.Goexit() on the server goroutine, which won't reliably fail the test and leaves the client hanging on a truncated response.
🐛 Proposed fix
reader, err := r.MultipartReader()
if err != nil {
- t.Fatalf("MultipartReader: %v", err)
+ t.Errorf("MultipartReader: %v", err)
+ return
}
@@
if err != nil {
- t.Fatalf("NextPart: %v", err)
+ t.Errorf("NextPart: %v", err)
+ return
}
data, err := io.ReadAll(part)
if err != nil {
- t.Fatalf("ReadAll part: %v", err)
+ t.Errorf("ReadAll part: %v", err)
+ return
}Based on learnings: in Go unit test handler goroutines, use t.Errorf instead of t.Fatalf since t.Fatalf only exits the handler goroutine.
📝 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.
| reader, err := r.MultipartReader() | |
| if err != nil { | |
| t.Fatalf("MultipartReader: %v", err) | |
| } | |
| fields := make(map[string]string) | |
| var fileName, fileBody string | |
| for { | |
| part, err := reader.NextPart() | |
| if err == io.EOF { | |
| break | |
| } | |
| if err != nil { | |
| t.Fatalf("NextPart: %v", err) | |
| } | |
| data, err := io.ReadAll(part) | |
| if err != nil { | |
| t.Fatalf("ReadAll part: %v", err) | |
| } | |
| reader, err := r.MultipartReader() | |
| if err != nil { | |
| t.Errorf("MultipartReader: %v", err) | |
| return | |
| } | |
| fields := make(map[string]string) | |
| var fileName, fileBody string | |
| for { | |
| part, err := reader.NextPart() | |
| if err == io.EOF { | |
| break | |
| } | |
| if err != nil { | |
| t.Errorf("NextPart: %v", err) | |
| return | |
| } | |
| data, err := io.ReadAll(part) | |
| if err != nil { | |
| t.Errorf("ReadAll part: %v", err) | |
| return | |
| } |
🤖 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/mistral_test.go` around lines 441 - 458, In the
multipart request handler around MultipartReader, NextPart, and io.ReadAll,
replace each t.Fatalf error path with t.Errorf followed immediately by return so
the handler exits cleanly after reporting the failure and does not truncate the
client response.
Source: Learnings
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Summary
As title, related to #17284