Skip to content

Go: add token usage for baidu, minimax, moonshot and mistral - #17413

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:master
Jul 27, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:master

Conversation

@Haruko386

@Haruko386 Haruko386 commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Summary

As title, related to #17284

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 27, 2026
@Haruko386
Haruko386 marked this pull request as draft July 27, 2026 06:20
@Haruko386
Haruko386 marked this pull request as ready for review July 27, 2026 06:20
@Haruko386 Haruko386 added the ci Continue Integration label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 88330765-0dd2-4ed1-b8fe-acf886b92a12

📥 Commits

Reviewing files that changed from the base of the PR and between 78b2f13 and 54d57f2.

📒 Files selected for processing (2)
  • internal/entity/models/baidu.go
  • internal/entity/models/mistral.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/entity/models/baidu.go
  • internal/entity/models/mistral.go

📝 Walkthrough

Walkthrough

Baidu, 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.

Changes

Provider model capabilities

Layer / File(s) Summary
Shared response contracts and request defaults
internal/entity/models/base_model.go
The shared tool-call map type now uses any, and base request construction no longer sets a default temperature.
Typed provider chat parsing
internal/entity/models/{baidu,minimax,moonshot,mistral}.go
Provider responses use typed schemas and shared parsing for content, reasoning, tool calls, errors, token fallbacks, and streamed usage.
Moonshot schema validation
internal/entity/models/moonshot_test.go
A test validates typed parsing of reasoning content, tool calls, finish reason, and token usage.
Mistral audio APIs and validation
internal/entity/models/mistral.go, internal/entity/models/mistral_test.go
Mistral adds multipart transcription and base64 speech generation, with transcription request validation and integration coverage.
Model and endpoint configuration
conf/models/mistral.json, conf/models/longcat.json
Mistral adds ASR/TTS routes and Voxtral audio models; the LongCat model list now starts with LongCat-2.0.

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
Loading

Possibly related PRs

Suggested labels: 💞 feature, ☯️ refactor

Poem

A rabbit sorts typed tokens bright,
While streaming usage hops into sight.
Mistral hears files and speaks anew,
LongCat bounds with models true.
Carrots compile beneath moonlight!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description has the required Summary section, but it is too vague and repeats the title without any background or implementation detail. Expand the Summary with the problem being solved, why these providers needed changes, and a short note on the main implementation/update.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: adding token usage support for Baidu, MiniMax, Moonshot, and Mistral.
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.

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.

@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: 4

🧹 Nitpick comments (3)
internal/entity/models/minimax.go (1)

89-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate error-extraction logic alongside extractMinimaxAPIError.

extractMinimaxAPIError (Line 120) implements the same base_resp/error.message precedence over the untyped event map. Consider having the streaming path re-marshal/decode into the typed struct (or share a small typed baseResp/error value) 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 win

Response schemas are exported but only consumed by their own package-private extractors. Each new provider schema is a type XxxChatResponse struct reachable from outside the package with no external consumer, widening the public surface for internal decoding types.

  • internal/entity/models/baidu.go#L53-L82: rename BaiduChatResponse to baiduChatResponse.
  • internal/entity/models/minimax.go#L55-L87: rename MinimaxChatResponse to minimaxChatResponse (and the *MinimaxChatResponse parameter of extractMinimaxChatResponseError).
  • internal/entity/models/mistral.go#L57-L82: rename MistralChatResponse to mistralChatResponse.
  • internal/entity/models/moonshot.go#L54-L75: rename MoonshotChatResponse to moonshotChatResponse.

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 win

Identical 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 to parseChatCompletionResponse in internal/entity/models/base_model.go as a small helper such as newTokenUsage(prompt, completion, total int) *TokenUsage.

  • internal/entity/models/baidu.go#L202-L213: replace with a call to the shared helper using result.Usage fields.
  • 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

📥 Commits

Reviewing files that changed from the base of the PR and between 58f6787 and e6d8b50.

📒 Files selected for processing (8)
  • conf/models/longcat.json
  • conf/models/minimax.json
  • internal/entity/models/baidu.go
  • internal/entity/models/base_model.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/moonshot_test.go

Comment thread conf/models/longcat.json
},
{
"name": "LongCat-2.0-Preview",
"name": "LongCat-2.0",

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.

🎯 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.json

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

Repository: 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)
PY

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

Comment thread conf/models/minimax.json Outdated
Comment on lines +5 to +12
"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"

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.

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

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

Comment thread internal/entity/models/baidu.go Resolved
Comment on lines +76 to +78
PromptTokenDetails struct {
CachedTokens int `json:"cached_tokens"`
}

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.

🗄️ 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.

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

@Haruko386

Copy link
Copy Markdown
Member Author

got some problem with Minimax, I shall fix it later

@Haruko386
Haruko386 marked this pull request as draft July 27, 2026 07:12
@Haruko386
Haruko386 marked this pull request as ready for review July 27, 2026 09:22
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 27, 2026
@Haruko386 Haruko386 removed the ci Continue Integration label Jul 27, 2026
@Haruko386
Haruko386 marked this pull request as draft July 27, 2026 09:25
@Haruko386
Haruko386 marked this pull request as ready for review July 27, 2026 09:25
@Haruko386 Haruko386 added the ci Continue Integration label Jul 27, 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: 3

🧹 Nitpick comments (3)
internal/entity/models/mistral.go (3)

330-339: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Untagged nested PromptTokenDetails won't bind prompt_tokens_details here either. Mirrors the same schema gap in MistralChatResponse.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 value

Stale 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 win

Whole audio file is buffered in memory. bytes.Buffer + io.Copy holds the entire upload (plus multipart overhead) in RAM; consider io.Pipe with 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

📥 Commits

Reviewing files that changed from the base of the PR and between e6d8b50 and 78b2f13.

📒 Files selected for processing (3)
  • conf/models/mistral.json
  • internal/entity/models/mistral.go
  • internal/entity/models/mistral_test.go

Comment thread conf/models/mistral.json
Comment on lines +26 to +37
{
"name": "voxtral-mini-tts-2603",
"model_types": [
"tts"
]
},
{
"name": "voxtral-mini-transcribe-realtime-2602",
"model_types": [
"asr"
]
},

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.

🗄️ 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:


🏁 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 -200

Repository: 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/**' || true

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


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


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.

Comment on lines +441 to +458
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)
}

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.

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

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

Comment thread internal/entity/models/mistral.go Resolved
Haruko386 and others added 2 commits July 27, 2026 17:29
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants