Skip to content

fix(mistral): handle structured content from magistral reasoning models - #14805

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
tmimmanuel:go/mistral-driver
May 21, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
tmimmanuel:go/mistral-driver

Conversation

@tmimmanuel

@tmimmanuel tmimmanuel commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

MistralModel.ChatWithMessages (in the driver merged via #14807) assumes that choices[0].message.content from /v1/chat/completions is always a string and falls through to return nil, fmt.Errorf("invalid content format") on anything else.

That assumption breaks for the magistral reasoning family (magistral-small-*, magistral-medium-*). When the model needs a chain-of-thought to answer, Mistral returns content as a structured array of typed parts:

"content": [
  {"type": "thinking",
   "thinking": [{"type": "text", "text": "Combined speed is 150 mph. 300 / 150 = 2 hours."}],
   "closed": true},
  {"type": "text", "text": "They will meet after **2 hours**."}
]

Concretely, this is what the live API returns today (probed against api.mistral.ai/v1):

$ curl -H "Authorization: Bearer <key>" -H "Content-Type: application/json" \
       -X POST https://api.mistral.ai/v1/chat/completions \
       -d '{"model":"magistral-medium-latest",
            "messages":[{"role":"user","content":"two trains 60mph and 90mph, 300mi apart, when do they meet? step by step."}],
            "max_tokens":1024}'
HTTP 200
{ "choices":[{"message":{
    "role":"assistant",
    "content":[
      {"type":"thinking","thinking":[{"type":"text","text":"Okay, let's see..."}],"closed":true},
      {"type":"text","text":"To determine when the two trains meet..."}
    ]}}] }

With the current driver, every call like that returns the generic "invalid content format" error. Trivial prompts that happen to fit in a string answer still succeed, so the breakage is non-deterministic from the tenant's POV: same model, same provider, sometimes works, sometimes 500s with no useful error.

A secondary issue: conf/models/mistral.json does not include any magistral model. The picker hid the broken path, which is why this wasn't caught during #14807's review.

What this PR includes

  • New helper extractMistralContent(raw interface{}) (answer, reasonContent string, err error) in internal/entity/models/mistral.go, which normalizes both shapes Mistral can return:
    • string → historical path. Answer = content, ReasonContent = "". Preserves behavior for every non-reasoning model (mistral-large-*, mistral-small-*, ministral-*, codestral-*, pixtral-*, open-mistral-nemo).
    • []interface{} → walk the parts. Concatenate every {"type":"text", "text":...} part into Answer; concatenate the inner text inside every {"type":"thinking", "thinking":[...]} part into ReasonContent.
  • ChatWithMessages now calls the helper instead of doing the raw .(string) cast.
  • Unknown part types are skipped, not failed. Mistral has been adding new content variants quickly (audio chunks, citations, etc.); this driver should not 500 every call when a new part type appears.
  • conf/models/mistral.json: add magistral-medium-latest and magistral-small-latest. Both are visible in /v1/models today.

No interface change. No factory change. No new dependencies.

How was this tested?

Unit tests — 5 new tests in internal/entity/models/mistral_test.go on top of the 27 already shipped via #14807:

  • TestMistralChatHandlesStringContent — regression net for the historical path
  • TestMistralChatExtractsReasoningFromStructuredContent — the fixture body is a trimmed copy of the actual magistral-medium-latest response captured above; asserts both Answer and ReasonContent are populated correctly
  • TestMistralChatHandlesStructuredContentWithoutThinking — magistral-* with a trivial answer returns a structured shape that has only a text part; ReasonContent must stay empty
  • TestMistralChatIgnoresUnknownContentPartTypes — audio_url and future_part_type parts are skipped, text parts still flow through
  • TestExtractMistralContent — table-driven unit coverage of the helper for string, empty string, nil, empty array, text-only, thinking+text, unsupported root type
$ go test -vet=off -run "TestMistral|TestExtractMistralContent" -count=1 -v ./internal/entity/models/...
=== RUN   TestMistralChatHandlesStringContent
--- PASS: TestMistralChatHandlesStringContent (0.00s)
=== RUN   TestMistralChatExtractsReasoningFromStructuredContent
--- PASS: TestMistralChatExtractsReasoningFromStructuredContent (0.00s)
=== RUN   TestMistralChatHandlesStructuredContentWithoutThinking
--- PASS: TestMistralChatHandlesStructuredContentWithoutThinking (0.00s)
=== RUN   TestMistralChatIgnoresUnknownContentPartTypes
--- PASS: TestMistralChatIgnoresUnknownContentPartTypes (0.00s)
=== RUN   TestExtractMistralContent
=== RUN   TestExtractMistralContent/plain_string
=== RUN   TestExtractMistralContent/empty_string
=== RUN   TestExtractMistralContent/nil
=== RUN   TestExtractMistralContent/empty_array
=== RUN   TestExtractMistralContent/text_only
=== RUN   TestExtractMistralContent/thinking_then_text
=== RUN   TestExtractMistralContent/unknown_root_type
--- PASS: TestExtractMistralContent (0.00s)
PASS
ok      ragflow/internal/entity/models  0.046s

All 32 Mistral tests pass on go 1.25. go build ./internal/entity/models/... exits 0.

Live integration test — driver exercised against api.mistral.ai/v1 with the patched code:

=== RUN   TestMistralMagistralSmoke
    [OK] "magistral-small-latest" present upstream
    [OK] "magistral-medium-latest" present upstream
    [OK trivial]    Answer="7"  ReasonContent=""
    [OK reasoning]  Answer len=797   head="To determine when the two trains meet, we can follow these steps:\n\n1. **Identify..."
                    ReasonContent len=1069 head="Okay, let's see. There are two trains, one going 60 mph and the other going 90 mph. They're moving towards each other, s..."

MAGISTRAL SMOKE PASSED
--- PASS: TestMistralMagistralSmoke (18.09s)
PASS
ok      ragflow/internal/entity/models  18.112s

What the live run proves on the wire:

  • magistral-small-latest with a trivial prompt still uses the string-content shape; the regression-net path is exercised against the real server, not just the mock.
  • magistral-medium-latest with a reasoning prompt uses the structured-array shape; the new code path extracts a 1069-character reasoning trace into ChatResponse.ReasonContent and a 797-character visible answer into ChatResponse.Answer. Before this fix, the same call returned "invalid content format" and the caller saw nothing.

The smoke-test file itself is not committed (live tests live outside the PR diff, same convention used for prior provider PRs).

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 12, 2026
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5fe713db-fac9-436a-80c2-b240cc41e91e

📥 Commits

Reviewing files that changed from the base of the PR and between 5e1a80c and 1b398bc.

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

📝 Walkthrough

Walkthrough

Registers Mistral provider/models (adds two magistral chat models) and implements extractMistralContent plus tests to normalize Mistral choices[].message.content as either a plain string or a structured array (text vs thinking -> Answer vs ReasonContent).

Changes

Mistral Structured Content and Model Expansion

Layer / File(s) Summary
Mistral Provider Configuration and Model Catalog
conf/models/mistral.json
Adds Mistral provider config with base URL, chat/models/embedding suffixes, model catalog including pixtral-large-latest (vision) and mistral-embed; registers magistral-medium-latest and magistral-small-latest with max_tokens: 40000 and model_types: ["chat"].
Structured Content Parsing Implementation
internal/entity/models/mistral.go
ChatWithMessages now calls extractMistralContent(messageMap["content"]). extractMistralContent returns (answer, reasoning, err) handling nil, plain string, or array-of-parts; concatenates text parts into Answer, extracts inner thinking text into ReasonContent, and skips unknown/ill-typed parts.
Content Parsing Test Coverage
internal/entity/models/mistral_test.go
Adds integration tests for plain-string content, thinking+text structured content, text-only structured content, and unknown part types; adds unit tests for extractMistralContent covering nil/empty/array cases and invalid root type error.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14807: Implements the initial Mistral driver with core methods (ChatWithMessages, ChatStreamlyWithSender, ListModels, CheckConnection); this PR extends content parsing to handle structured responses with thinking parts.

Suggested labels

💞 feature, size:L

Suggested reviewers

  • Haruko386

Poem

🐰 I nibble logs and parse the breeze,
Magistral thoughts split into keys,
Text for the answer, thinking in tow,
Configured models ready to go —
Tests hop forward, tidy and pleased.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change—handling structured content from magistral reasoning models in the Mistral driver.
Description check ✅ Passed The description comprehensively covers the problem, solution, testing approach, and change type, meeting all template requirements with substantial detail and evidence.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.
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.

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

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

103-106: ⚡ Quick win

Harmonize region fallback logic across methods.

The three methods handle empty region strings inconsistently:

  • ChatStreamlyWithSender (line 222) checks for both nil and empty string
  • ChatWithMessages (line 104) and ListModels (line 378) only check for nil

While an empty string would eventually fail in baseURLForRegion, it's cleaner to normalize the empty-string check across all three methods.

♻️ Proposed fix for consistency
 func (m *MistralModel) ChatWithMessages(...) (*ChatResponse, error) {
   ...
   var region = "default"
-  if apiConfig.Region != nil {
+  if apiConfig.Region != nil && *apiConfig.Region != "" {
     region = *apiConfig.Region
   }
   ...
 }

 func (m *MistralModel) ListModels(apiConfig *APIConfig) ([]string, error) {
   ...
   var region = "default"
-  if apiConfig.Region != nil {
+  if apiConfig.Region != nil && *apiConfig.Region != "" {
     region = *apiConfig.Region
   }
   ...
 }

Also applies to: 221-224, 377-380

🤖 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 103 - 106, Harmonize the
region fallback by treating nil and empty string the same: in ChatWithMessages,
ChatStreamlyWithSender, and ListModels replace the current region initialization
so it checks both apiConfig.Region == nil and *apiConfig.Region == "" (e.g., if
apiConfig.Region == nil || *apiConfig.Region == "" then region = "default" else
region = *apiConfig.Region) so baseURLForRegion always receives a normalized
non-empty region; you can also extract this into a small helper (e.g.,
normalizeRegion(apiConfig)) and call it from the three methods to avoid
duplication.
🤖 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.

Nitpick comments:
In `@internal/entity/models/mistral.go`:
- Around line 103-106: Harmonize the region fallback by treating nil and empty
string the same: in ChatWithMessages, ChatStreamlyWithSender, and ListModels
replace the current region initialization so it checks both apiConfig.Region ==
nil and *apiConfig.Region == "" (e.g., if apiConfig.Region == nil ||
*apiConfig.Region == "" then region = "default" else region = *apiConfig.Region)
so baseURLForRegion always receives a normalized non-empty region; you can also
extract this into a small helper (e.g., normalizeRegion(apiConfig)) and call it
from the three methods to avoid duplication.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 338becc5-89c3-4e1f-9d4e-5e36e2bd8b65

📥 Commits

Reviewing files that changed from the base of the PR and between 2f2d156 and 0af7e24.

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

@Haruko386 Haruko386 added the ci Continue Integration label May 12, 2026
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
Replace the stub-pinning TestMistralEmbedReturnsNotImplemented from
PR infiniflow#14805 with a full suite covering the real Embed implementation:

- TestMistralEmbedHappyPath:           three vectors back in order
- TestMistralEmbedReordersByIndex:     upstream returns out-of-order,
                                       driver realigns by index field
- TestMistralEmbedEmptyInputShortCircuits: empty []string makes zero
                                       HTTP calls (test fails the
                                       request, not the assertion,
                                       if that contract breaks)
- TestMistralEmbedRequiresAPIKey:      nil/empty key rejected
- TestMistralEmbedRequiresModelName:   nil and empty modelName both
                                       rejected
- TestMistralEmbedRejectsOutOfRangeIndex: upstream index 7 with 2
                                       inputs => clear error, no
                                       silent slice grow
- TestMistralEmbedRejectsMissingSlot:  upstream returns only 1 of 2
                                       requested embeddings => clear
                                       error for the missing slot
- TestMistralEmbedRejectsHTTPError:    upstream 401 propagated

All 23 Mistral tests pass (15 driver + 8 embed) under
go test -vet=off -run TestMistral on go 1.25.

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

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

31-35: 💤 Low value

Consider checking errors in test setup for better diagnostics.

While ignoring errors in test helpers is common practice, checking and failing early with t.Fatalf would make test failures clearer if the request body is malformed.

Minor improvement for error handling
 		raw, err := io.ReadAll(r.Body)
 		if err != nil {
-			t.Errorf("failed to read body: %v", err)
-			return
+			t.Fatalf("failed to read body: %v", err)
 		}
 		var body map[string]interface{}
 		if err := json.Unmarshal(raw, &body); err != nil {
-			t.Errorf("invalid JSON body: %v\n%s", err, string(raw))
-			return
+			t.Fatalf("invalid JSON body: %v\n%s", err, string(raw))
 		}
🤖 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 31 - 35, In the test
helper where you call io.ReadAll(r.Body) and currently handle errors with
t.Errorf("failed to read body: %v", err) and return, change this to fail the
test immediately using t.Fatalf with the error (e.g., t.Fatalf("failed to read
body: %v", err)) so malformed request bodies produce a clear, immediate test
failure; update the code in the block around raw, err := io.ReadAll(r.Body) and
the subsequent error handling accordingly.

340-340: 💤 Low value

Use descriptive variable name for model parameter.

The variable q (suggesting "query") is used for the model name. Consider model for clarity.

Suggested naming improvement
-	q := "mistral-large-latest"
-	_, err := m.Rerank(&q, "what is rag?", []string{"a", "b"}, &APIConfig{}, &RerankConfig{TopN: 2})
+	model := "mistral-large-latest"
+	_, err := m.Rerank(&model, "what is rag?", []string{"a", "b"}, &APIConfig{}, &RerankConfig{TopN: 2})
🤖 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` at line 340, The variable name `q`
used to hold the model name in the test should be renamed to a descriptive
identifier (e.g., `model`) to improve clarity: locate the declaration `q :=
"mistral-large-latest"` in the Mistral test (mistral_test.go) and rename the
variable to `model`, then update every usage of `q` in that test (and any helper
calls or assertions that reference it) to `model`; ensure you run the tests to
confirm no reference is missed and that there are no naming collisions.

99-101: 💤 Low value

Clarify ReasonContent nil vs empty string contract.

The test asserts that ReasonContent must be non-nil and equal to empty string when there's no reason content. Consider whether returning nil would be simpler than a pointer to an empty string, as it would avoid the need to dereference and reduces API surface complexity.

🤖 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 99 - 101, The test
currently expects resp.ReasonContent to be a non-nil pointer to an empty string;
change the contract to use nil to represent "no reason" and update both the
implementation that builds the response and this test accordingly: ensure code
paths that set ReasonContent (the factory/serializer that produces
resp.ReasonContent) return nil when there is no content, and modify the test in
mistral_test.go to assert resp.ReasonContent == nil instead of dereferencing and
comparing to ""; keep the ReasonContent type as-is but standardize on nil for
absent content.
🤖 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.

Nitpick comments:
In `@internal/entity/models/mistral_test.go`:
- Around line 31-35: In the test helper where you call io.ReadAll(r.Body) and
currently handle errors with t.Errorf("failed to read body: %v", err) and
return, change this to fail the test immediately using t.Fatalf with the error
(e.g., t.Fatalf("failed to read body: %v", err)) so malformed request bodies
produce a clear, immediate test failure; update the code in the block around
raw, err := io.ReadAll(r.Body) and the subsequent error handling accordingly.
- Line 340: The variable name `q` used to hold the model name in the test should
be renamed to a descriptive identifier (e.g., `model`) to improve clarity:
locate the declaration `q := "mistral-large-latest"` in the Mistral test
(mistral_test.go) and rename the variable to `model`, then update every usage of
`q` in that test (and any helper calls or assertions that reference it) to
`model`; ensure you run the tests to confirm no reference is missed and that
there are no naming collisions.
- Around line 99-101: The test currently expects resp.ReasonContent to be a
non-nil pointer to an empty string; change the contract to use nil to represent
"no reason" and update both the implementation that builds the response and this
test accordingly: ensure code paths that set ReasonContent (the
factory/serializer that produces resp.ReasonContent) return nil when there is no
content, and modify the test in mistral_test.go to assert resp.ReasonContent ==
nil instead of dereferencing and comparing to ""; keep the ReasonContent type
as-is but standardize on nil for absent content.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 02798806-22cf-4518-87aa-ed8b73f1d16e

📥 Commits

Reviewing files that changed from the base of the PR and between 0af7e24 and b2e08cd.

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

tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
Replace the stub-pinning TestMistralEmbedReturnsNotImplemented from
PR infiniflow#14805 with a full suite covering the real Embed implementation:

- TestMistralEmbedHappyPath:           three vectors back in order
- TestMistralEmbedReordersByIndex:     upstream returns out-of-order,
                                       driver realigns by index field
- TestMistralEmbedEmptyInputShortCircuits: empty []string makes zero
                                       HTTP calls (test fails the
                                       request, not the assertion,
                                       if that contract breaks)
- TestMistralEmbedRequiresAPIKey:      nil/empty key rejected
- TestMistralEmbedRequiresModelName:   nil and empty modelName both
                                       rejected
- TestMistralEmbedRejectsOutOfRangeIndex: upstream index 7 with 2
                                       inputs => clear error, no
                                       silent slice grow
- TestMistralEmbedRejectsMissingSlot:  upstream returns only 1 of 2
                                       requested embeddings => clear
                                       error for the missing slot
- TestMistralEmbedRejectsHTTPError:    upstream 401 propagated

All 23 Mistral tests pass (15 driver + 8 embed) under
go test -vet=off -run TestMistral on go 1.25.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
CodeRabbit review on this PR flagged two issues that match the ones
also addressed in the Mistral driver (infiniflow#14805) and StepFun (infiniflow#14815).

- ChatWithMessages and ListModels treated a non-nil but empty Region
  pointer as an explicit region, which then failed baseURLForRegion
  lookup despite a valid "default" entry. Match the guard already used
  in ChatStreamlyWithSender: only override "default" when the region
  string is non-empty.
- ChatStreamlyWithSender did not validate that sender was non-nil
  before invoking it inside the scan loop, which would panic on a
  nil callback. Add the guard alongside the existing messages and
  api-key checks.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
CodeRabbit review on the stacked PR infiniflow#14811 flagged that the
ChatStreamlyWithSender comment promised "the client drops the
connection if it stalls", which is not actually implemented in the
current driver. Replace the comment with the more accurate wording
used in the merged OpenAI driver (infiniflow#14605): the background context
makes the request "cancellable in principle" but no hard deadline is
attached because SSE streams are long-lived, and threading a real
ctx through the ModelDriver interface is a wider change for a
follow-up.

Also add a nil-sender guard at the top of ChatStreamlyWithSender,
matching the fixes applied to Mistral (infiniflow#14805) and Upstage (infiniflow#14817)
on review feedback. The risk class is the same: invoking a nil
callback panics the process.

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

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

342-342: 💤 Low value

Consider checking all model IDs for completeness.

The assertion verifies ids[0] and ids[2] but skips ids[1]. While this sufficiently proves parsing works, checking all three IDs (or just the full slice equality) would be more thorough and guard against potential ordering bugs.

📝 Optional enhancement
-	if len(ids) != 3 || ids[0] != "mistral-large-latest" || ids[2] != "mistral-embed" {
+	want := []string{"mistral-large-latest", "mistral-small-latest", "mistral-embed"}
+	if len(ids) != len(want) {
+		t.Errorf("ids length=%d, want %d", len(ids), len(want))
+	}
+	for i, id := range ids {
+		if id != want[i] {
+			t.Errorf("ids[%d]=%q, want %q", i, id, want[i])
+		}
+	}

Alternatively, use a simple slice comparison if available in your test utilities.

🤖 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` at line 342, The test currently
checks ids[0] and ids[2] but omits ids[1]; update the assertion in
mistral_test.go to verify all elements of the ids slice (either by asserting
ids[1] equals the expected value or by asserting full slice equality against an
expected []string) so the test validates the complete ordering and contents of
ids.
🤖 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.

Nitpick comments:
In `@internal/entity/models/mistral_test.go`:
- Line 342: The test currently checks ids[0] and ids[2] but omits ids[1]; update
the assertion in mistral_test.go to verify all elements of the ids slice (either
by asserting ids[1] equals the expected value or by asserting full slice
equality against an expected []string) so the test validates the complete
ordering and contents of ids.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a7309f6a-020e-487b-a562-672af5a0fa0a

📥 Commits

Reviewing files that changed from the base of the PR and between b2e08cd and ee08b64.

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

@codecov

codecov Bot commented May 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (5a5bbee) to head (1b398bc).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14805      +/-   ##
==========================================
- Coverage   95.59%   94.16%   -1.43%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          672      662      -10     
- Misses         21       25       +4     
- Partials       10       16       +6     

☔ 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

Copy link
Copy Markdown
Member

Duplicated with #14807. I will close it. Please feel free to re-open it, if i am wrong.

@JinHai-CN JinHai-CN closed this May 12, 2026
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
PR infiniflow#14805 was closed as a perceived duplicate of infiniflow#14807. Pushing an
empty commit to nudge the head SHA so the PR can be reopened via the
GitHub API, since the closed-then-reopen path requires a state
change to validate.
JinHai-CN added a commit that referenced this pull request May 12, 2026
### What problem does this PR solve?

The Mistral Go driver landed in #14805 with chat, list models, and check
connection. `Embed` was left as a stub that returns `"not implemented"`.
This PR fills the gap.

`conf/models/mistral.json` did not list any embedding model out of the
box, so a tenant who wanted to use Mistral end to end (chat +
embeddings) could not run an embedding call. This PR adds
`mistral-embed` to the config and a real `/v1/embeddings`
implementation.

### What this PR includes

- `conf/models/mistral.json`: add `"embedding": "embeddings"` under
`url_suffix` so the driver can build the URL from config (matches the
`URLSuffix.Embedding` field already used by openai, siliconflow,
zhipu-ai), and add a `mistral-embed` entry under `models`
(1024-dimensional vectors, 8192 max input tokens).
- `internal/entity/models/mistral.go`: replace the `Embed` stub with a
real implementation that POSTs to `/v1/embeddings`. Adds local response
types `mistralEmbeddingData` and `mistralEmbeddingResponse`.

No factory change. No interface change.

### How the implementation works

- Validate `apiConfig`, the API key, and the model name. Use the
existing `baseURLForRegion` helper so an unknown region fails fast with
a clear error.
- Wrap the request with `context.WithTimeout(nonStreamCallTimeout)` so
the call has a clear deadline. Same pattern as `ChatWithMessages` and
`ListModels` already use in this file.
- Send all input texts in one request. The Mistral API accepts the
`input` field as an array.
- Parse `data[*].embedding` and copy each slice into a `[]EmbeddingData`
indexed by `data[*].index` so the output order matches the input order
even if the API returns items in a different order.
- An empty input slice returns `[]EmbeddingData{}` with no HTTP call.
- Non-200 responses propagate the upstream status line and body.
- A final pass checks that every input slot got a vector. If any slot is
still empty, return a clear error so the caller does not silently use a
zero vector.

### Note on stacking

This PR builds on #14805 (the Mistral driver). Until #14805 merges, this
PR's diff on GitHub will include both that PR's commits and this one.
After #14805 lands on `main`, GitHub will auto-reduce this PR to only
the `Embed` changes (one commit, ~111 line diff in `mistral.go` plus 8
lines in `mistral.json`).

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- `go build ./internal/entity/models/...` returns exit 0 on go 1.25 (the
`go.mod` minimum).
- The full method set on `MistralModel` still matches the `ModelDriver`
interface.
- Pattern parity with the existing OpenAI Embed implementation
(`internal/entity/models/openai.go`).

Closes #14806
Depends on #14805
Tracking: #14736

---------

Co-authored-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN reopened this May 12, 2026
@tmimmanuel
tmimmanuel force-pushed the go/mistral-driver branch from ee08b64 to 5e1a80c Compare May 12, 2026 14:29
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 12, 2026
@tmimmanuel tmimmanuel changed the title Go: implement provider: Mistral fix(mistral): handle structured content from magistral reasoning models May 12, 2026
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

@Haruko386 please review.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
Replace the stub-pinning TestMistralEmbedReturnsNotImplemented from
PR infiniflow#14805 with a full suite covering the real Embed implementation:

- TestMistralEmbedHappyPath:           three vectors back in order
- TestMistralEmbedReordersByIndex:     upstream returns out-of-order,
                                       driver realigns by index field
- TestMistralEmbedEmptyInputShortCircuits: empty []string makes zero
                                       HTTP calls (test fails the
                                       request, not the assertion,
                                       if that contract breaks)
- TestMistralEmbedRequiresAPIKey:      nil/empty key rejected
- TestMistralEmbedRequiresModelName:   nil and empty modelName both
                                       rejected
- TestMistralEmbedRejectsOutOfRangeIndex: upstream index 7 with 2
                                       inputs => clear error, no
                                       silent slice grow
- TestMistralEmbedRejectsMissingSlot:  upstream returns only 1 of 2
                                       requested embeddings => clear
                                       error for the missing slot
- TestMistralEmbedRejectsHTTPError:    upstream 401 propagated

All 23 Mistral tests pass (15 driver + 8 embed) under
go test -vet=off -run TestMistral on go 1.25.
@tmimmanuel
tmimmanuel force-pushed the go/mistral-driver branch from 5e1a80c to 940e10d Compare May 14, 2026 17:37
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
CodeRabbit review on this PR flagged two issues that match the ones
also addressed in the Mistral driver (infiniflow#14805) and StepFun (infiniflow#14815).

- ChatWithMessages and ListModels treated a non-nil but empty Region
  pointer as an explicit region, which then failed baseURLForRegion
  lookup despite a valid "default" entry. Match the guard already used
  in ChatStreamlyWithSender: only override "default" when the region
  string is non-empty.
- ChatStreamlyWithSender did not validate that sender was non-nil
  before invoking it inside the scan loop, which would panic on a
  nil callback. Add the guard alongside the existing messages and
  api-key checks.
@dosubot dosubot Bot removed the size:M This PR changes 30-99 lines, ignoring generated files. label May 14, 2026
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label May 14, 2026
ChatWithMessages assumed choices[0].message.content is always a string
and bailed out with "invalid content format" on anything else. The
magistral reasoning family (magistral-small-*, magistral-medium-*)
breaks that assumption: when the model needs a chain-of-thought to
answer, it returns content as a structured array of typed parts:

  "content": [
    {"type": "thinking", "thinking": [{"type": "text", "text": "..."}]},
    {"type": "text", "text": "The answer is ..."}
  ]

The driver then errored every call to magistral that triggered
reasoning, and worked only for trivial prompts that fit in a string
answer. The breakage was non-deterministic from the tenant's POV.

This change introduces extractMistralContent, which accepts both:

- the historical string shape (preserved for every non-reasoning
  model: mistral-large, mistral-small, ministral-*, codestral-*,
  pixtral-*, open-mistral-nemo, etc.) -> Answer = content, no reason
- the structured array shape -> walk the parts, concatenate "text"
  parts into Answer, concatenate inner thinking text into
  ReasonContent

Unknown part types are skipped instead of failing the call, so a new
Mistral content variant (audio_url, citation, future_part_type) will
just be ignored by this driver rather than 500'ing every chat.

Also add magistral-small-latest and magistral-medium-latest to
conf/models/mistral.json. They're visible in /v1/models for accounts
that exist today, and without them the model picker had nothing that
could trigger the bug to begin with (the picker hid the broken path).

Tests:
- TestMistralChatHandlesStringContent (regression net)
- TestMistralChatExtractsReasoningFromStructuredContent
- TestMistralChatHandlesStructuredContentWithoutThinking
- TestMistralChatIgnoresUnknownContentPartTypes
- TestExtractMistralContent (table-driven unit coverage of the helper:
  string, empty string, nil, empty array, text-only, thinking+text,
  unsupported root type)

All 32 Mistral tests pass; build clean on go 1.25. Verified live
against api.mistral.ai/v1 with magistral-small-latest (trivial prompt
-> string shape) and magistral-medium-latest (reasoning prompt ->
structured shape, 1069-char reasoning trace successfully extracted
into ChatResponse.ReasonContent and 797-char visible answer into
ChatResponse.Answer).
@tmimmanuel
tmimmanuel force-pushed the go/mistral-driver branch from 940e10d to 1b398bc Compare May 14, 2026 18:42
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels May 14, 2026
@JinHai-CN
JinHai-CN merged commit 00665ea into infiniflow:main May 21, 2026
1 check passed
JinHai-CN pushed a commit that referenced this pull request May 21, 2026
…ls (#14805)

### What problem does this PR solve?

`MistralModel.ChatWithMessages` (in the driver merged via #14807)
assumes that `choices[0].message.content` from `/v1/chat/completions` is
always a string and falls through to `return nil, fmt.Errorf("invalid
content format")` on anything else.

That assumption breaks for the **magistral reasoning family**
(`magistral-small-*`, `magistral-medium-*`). When the model needs a
chain-of-thought to answer, Mistral returns `content` as a **structured
array of typed parts**:

```json
"content": [
  {"type": "thinking",
   "thinking": [{"type": "text", "text": "Combined speed is 150 mph. 300 / 150 = 2 hours."}],
   "closed": true},
  {"type": "text", "text": "They will meet after **2 hours**."}
]
```

Concretely, this is what the live API returns today (probed against
`api.mistral.ai/v1`):

```
$ curl -H "Authorization: Bearer <key>" -H "Content-Type: application/json" \
       -X POST https://api.mistral.ai/v1/chat/completions \
       -d '{"model":"magistral-medium-latest",
            "messages":[{"role":"user","content":"two trains 60mph and 90mph, 300mi apart, when do they meet? step by step."}],
            "max_tokens":1024}'
HTTP 200
{ "choices":[{"message":{
    "role":"assistant",
    "content":[
      {"type":"thinking","thinking":[{"type":"text","text":"Okay, let's see..."}],"closed":true},
      {"type":"text","text":"To determine when the two trains meet..."}
    ]}}] }
```

With the current driver, every call like that returns the generic
`"invalid content format"` error. Trivial prompts that happen to fit in
a string answer still succeed, so the breakage is **non-deterministic
from the tenant's POV**: same model, same provider, sometimes works,
sometimes 500s with no useful error.

A secondary issue: `conf/models/mistral.json` does not include any
magistral model. The picker hid the broken path, which is why this
wasn't caught during #14807's review.

### What this PR includes

- New helper `extractMistralContent(raw interface{}) (answer,
reasonContent string, err error)` in
`internal/entity/models/mistral.go`, which normalizes both shapes
Mistral can return:
- `string` → historical path. `Answer = content`, `ReasonContent = ""`.
Preserves behavior for every non-reasoning model (`mistral-large-*`,
`mistral-small-*`, `ministral-*`, `codestral-*`, `pixtral-*`,
`open-mistral-nemo`).
- `[]interface{}` → walk the parts. Concatenate every `{"type":"text",
"text":...}` part into `Answer`; concatenate the inner text inside every
`{"type":"thinking", "thinking":[...]}` part into `ReasonContent`.
- `ChatWithMessages` now calls the helper instead of doing the raw
`.(string)` cast.
- Unknown part types are **skipped, not failed**. Mistral has been
adding new content variants quickly (audio chunks, citations, etc.);
this driver should not 500 every call when a new part type appears.
- `conf/models/mistral.json`: add `magistral-medium-latest` and
`magistral-small-latest`. Both are visible in `/v1/models` today.

No interface change. No factory change. No new dependencies.

### How was this tested?

**Unit tests** — 5 new tests in `internal/entity/models/mistral_test.go`
on top of the 27 already shipped via #14807:

- `TestMistralChatHandlesStringContent` — regression net for the
historical path
- `TestMistralChatExtractsReasoningFromStructuredContent` — the fixture
body is a trimmed copy of the actual `magistral-medium-latest` response
captured above; asserts both `Answer` and `ReasonContent` are populated
correctly
- `TestMistralChatHandlesStructuredContentWithoutThinking` —
`magistral-*` with a trivial answer returns a structured shape that has
only a `text` part; `ReasonContent` must stay empty
- `TestMistralChatIgnoresUnknownContentPartTypes` — `audio_url` and
`future_part_type` parts are skipped, `text` parts still flow through
- `TestExtractMistralContent` — table-driven unit coverage of the helper
for string, empty string, nil, empty array, text-only, thinking+text,
unsupported root type

```
$ go test -vet=off -run "TestMistral|TestExtractMistralContent" -count=1 -v ./internal/entity/models/...
=== RUN   TestMistralChatHandlesStringContent
--- PASS: TestMistralChatHandlesStringContent (0.00s)
=== RUN   TestMistralChatExtractsReasoningFromStructuredContent
--- PASS: TestMistralChatExtractsReasoningFromStructuredContent (0.00s)
=== RUN   TestMistralChatHandlesStructuredContentWithoutThinking
--- PASS: TestMistralChatHandlesStructuredContentWithoutThinking (0.00s)
=== RUN   TestMistralChatIgnoresUnknownContentPartTypes
--- PASS: TestMistralChatIgnoresUnknownContentPartTypes (0.00s)
=== RUN   TestExtractMistralContent
=== RUN   TestExtractMistralContent/plain_string
=== RUN   TestExtractMistralContent/empty_string
=== RUN   TestExtractMistralContent/nil
=== RUN   TestExtractMistralContent/empty_array
=== RUN   TestExtractMistralContent/text_only
=== RUN   TestExtractMistralContent/thinking_then_text
=== RUN   TestExtractMistralContent/unknown_root_type
--- PASS: TestExtractMistralContent (0.00s)
PASS
ok      ragflow/internal/entity/models  0.046s
```

All 32 Mistral tests pass on go 1.25. `go build
./internal/entity/models/...` exits 0.

**Live integration test** — driver exercised against `api.mistral.ai/v1`
with the patched code:

```
=== RUN   TestMistralMagistralSmoke
    [OK] "magistral-small-latest" present upstream
    [OK] "magistral-medium-latest" present upstream
    [OK trivial]    Answer="7"  ReasonContent=""
    [OK reasoning]  Answer len=797   head="To determine when the two trains meet, we can follow these steps:\n\n1. **Identify..."
                    ReasonContent len=1069 head="Okay, let's see. There are two trains, one going 60 mph and the other going 90 mph. They're moving towards each other, s..."

MAGISTRAL SMOKE PASSED
--- PASS: TestMistralMagistralSmoke (18.09s)
PASS
ok      ragflow/internal/entity/models  18.112s
```

What the live run proves on the wire:

- `magistral-small-latest` with a trivial prompt still uses the
string-content shape; the regression-net path is exercised against the
real server, not just the mock.
- `magistral-medium-latest` with a reasoning prompt uses the
structured-array shape; the new code path extracts a 1069-character
reasoning trace into `ChatResponse.ReasonContent` and a 797-character
visible answer into `ChatResponse.Answer`. Before this fix, the same
call returned `"invalid content format"` and the caller saw nothing.

The smoke-test file itself is not committed (live tests live outside the
PR diff, same convention used for prior provider PRs).

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

The Mistral Go driver landed in infiniflow#14805 with chat, list models, and check
connection. `Embed` was left as a stub that returns `"not implemented"`.
This PR fills the gap.

`conf/models/mistral.json` did not list any embedding model out of the
box, so a tenant who wanted to use Mistral end to end (chat +
embeddings) could not run an embedding call. This PR adds
`mistral-embed` to the config and a real `/v1/embeddings`
implementation.

### What this PR includes

- `conf/models/mistral.json`: add `"embedding": "embeddings"` under
`url_suffix` so the driver can build the URL from config (matches the
`URLSuffix.Embedding` field already used by openai, siliconflow,
zhipu-ai), and add a `mistral-embed` entry under `models`
(1024-dimensional vectors, 8192 max input tokens).
- `internal/entity/models/mistral.go`: replace the `Embed` stub with a
real implementation that POSTs to `/v1/embeddings`. Adds local response
types `mistralEmbeddingData` and `mistralEmbeddingResponse`.

No factory change. No interface change.

### How the implementation works

- Validate `apiConfig`, the API key, and the model name. Use the
existing `baseURLForRegion` helper so an unknown region fails fast with
a clear error.
- Wrap the request with `context.WithTimeout(nonStreamCallTimeout)` so
the call has a clear deadline. Same pattern as `ChatWithMessages` and
`ListModels` already use in this file.
- Send all input texts in one request. The Mistral API accepts the
`input` field as an array.
- Parse `data[*].embedding` and copy each slice into a `[]EmbeddingData`
indexed by `data[*].index` so the output order matches the input order
even if the API returns items in a different order.
- An empty input slice returns `[]EmbeddingData{}` with no HTTP call.
- Non-200 responses propagate the upstream status line and body.
- A final pass checks that every input slot got a vector. If any slot is
still empty, return a clear error so the caller does not silently use a
zero vector.

### Note on stacking

This PR builds on infiniflow#14805 (the Mistral driver). Until infiniflow#14805 merges, this
PR's diff on GitHub will include both that PR's commits and this one.
After infiniflow#14805 lands on `main`, GitHub will auto-reduce this PR to only
the `Embed` changes (one commit, ~111 line diff in `mistral.go` plus 8
lines in `mistral.json`).

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- `go build ./internal/entity/models/...` returns exit 0 on go 1.25 (the
`go.mod` minimum).
- The full method set on `MistralModel` still matches the `ModelDriver`
interface.
- Pattern parity with the existing OpenAI Embed implementation
(`internal/entity/models/openai.go`).

Closes infiniflow#14806
Depends on infiniflow#14805
Tracking: infiniflow#14736

---------

Co-authored-by: Jin Hai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants