Repository navigation
fix(mistral): handle structured content from magistral reasoning models - #14805
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughRegisters 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). ChangesMistral Structured Content and Model Expansion
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/mistral.go (1)
103-106: ⚡ Quick winHarmonize region fallback logic across methods.
The three methods handle empty region strings inconsistently:
ChatStreamlyWithSender(line 222) checks for both nil and empty stringChatWithMessages(line 104) andListModels(line 378) only check for nilWhile 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
📒 Files selected for processing (3)
conf/models/mistral.jsoninternal/entity/models/factory.gointernal/entity/models/mistral.go
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.
There was a problem hiding this comment.
🧹 Nitpick comments (3)
internal/entity/models/mistral_test.go (3)
31-35: 💤 Low valueConsider checking errors in test setup for better diagnostics.
While ignoring errors in test helpers is common practice, checking and failing early with
t.Fatalfwould 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 valueUse descriptive variable name for model parameter.
The variable
q(suggesting "query") is used for the model name. Considermodelfor 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 valueClarify ReasonContent nil vs empty string contract.
The test asserts that
ReasonContentmust be non-nil and equal to empty string when there's no reason content. Consider whether returningnilwould 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
📒 Files selected for processing (1)
internal/entity/models/mistral_test.go
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.
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.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/mistral_test.go (1)
342-342: 💤 Low valueConsider checking all model IDs for completeness.
The assertion verifies
ids[0]andids[2]but skipsids[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
📒 Files selected for processing (2)
internal/entity/models/mistral.gointernal/entity/models/mistral_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/entity/models/mistral.go
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Duplicated with #14807. I will close it. Please feel free to re-open it, if i am wrong. |
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.
### 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]>
ee08b64 to
5e1a80c
Compare
|
@Haruko386 please review. |
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.
5e1a80c to
940e10d
Compare
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.
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).
940e10d to
1b398bc
Compare
…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)
### 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]>
What problem does this PR solve?
MistralModel.ChatWithMessages(in the driver merged via #14807) assumes thatchoices[0].message.contentfrom/v1/chat/completionsis always a string and falls through toreturn 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 returnscontentas a structured array of typed parts:Concretely, this is what the live API returns today (probed against
api.mistral.ai/v1):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.jsondoes 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
extractMistralContent(raw interface{}) (answer, reasonContent string, err error)ininternal/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 intoAnswer; concatenate the inner text inside every{"type":"thinking", "thinking":[...]}part intoReasonContent.ChatWithMessagesnow calls the helper instead of doing the raw.(string)cast.conf/models/mistral.json: addmagistral-medium-latestandmagistral-small-latest. Both are visible in/v1/modelstoday.No interface change. No factory change. No new dependencies.
How was this tested?
Unit tests — 5 new tests in
internal/entity/models/mistral_test.goon top of the 27 already shipped via #14807:TestMistralChatHandlesStringContent— regression net for the historical pathTestMistralChatExtractsReasoningFromStructuredContent— the fixture body is a trimmed copy of the actualmagistral-medium-latestresponse captured above; asserts bothAnswerandReasonContentare populated correctlyTestMistralChatHandlesStructuredContentWithoutThinking—magistral-*with a trivial answer returns a structured shape that has only atextpart;ReasonContentmust stay emptyTestMistralChatIgnoresUnknownContentPartTypes—audio_urlandfuture_part_typeparts are skipped,textparts still flow throughTestExtractMistralContent— table-driven unit coverage of the helper for string, empty string, nil, empty array, text-only, thinking+text, unsupported root typeAll 32 Mistral tests pass on go 1.25.
go build ./internal/entity/models/...exits 0.Live integration test — driver exercised against
api.mistral.ai/v1with the patched code:What the live run proves on the wire:
magistral-small-latestwith 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-latestwith a reasoning prompt uses the structured-array shape; the new code path extracts a 1069-character reasoning trace intoChatResponse.ReasonContentand a 797-character visible answer intoChatResponse.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