Repository navigation
Go: implement Embed (embeddings) in Mistral driver - #14807
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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds Mistral provider: config, factory registration, MistralModel driver (chat non-stream + SSE, embeddings, list models, connection check, unsupported stubs), and comprehensive unit tests. ChangesMistral Provider Integration
Sequence Diagram (high-level request flow) sequenceDiagram
participant Client
participant ModelFactory
participant MistralModel
participant MistralAPI
Client->>ModelFactory: request provider "mistral"
ModelFactory->>MistralModel: instantiate with base URLs & suffixes
Client->>MistralModel: Chat/Embed/ListModels call (with API key)
MistralModel->>MistralAPI: HTTP POST/GET to resolved endpoint
MistralAPI-->>MistralModel: HTTP response (JSON or SSE)
MistralModel-->>Client: parsed result or streamed chunks
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/mistral.go`:
- Around line 212-219: The function MistralModel.ChatStreamlyWithSender should
validate the sender callback before use: add a nil check for the sender
parameter at the start of ChatStreamlyWithSender and return a descriptive error
(e.g., "sender callback is required") if sender == nil so subsequent calls to
sender (the invocations currently made inside ChatStreamlyWithSender) cannot
panic at runtime; ensure this same nil-guard covers every code path that calls
sender within the method.
- Around line 104-106: The code assigns region = *apiConfig.Region without
handling empty strings, causing baseURLForRegion("") to fail; update the region
normalization where apiConfig.Region is read (the block that currently does
region = *apiConfig.Region) to set region to "default" when apiConfig.Region is
non-nil but the dereferenced value is empty (i.e., if apiConfig.Region != nil {
if *apiConfig.Region == "" { region = "default" } else { region =
*apiConfig.Region } }), and apply the same normalization in the other place that
reads apiConfig.Region (the similar assignment used before calling
baseURLForRegion and in functions referenced like Embed and
ChatStreamlyWithSender) so baseURLForRegion always receives a non-empty region.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ff37e9b0-d331-454e-8539-132d6c26c85b
📒 Files selected for processing (3)
conf/models/mistral.jsoninternal/entity/models/factory.gointernal/entity/models/mistral.go
Add httptest-based unit tests for the Mistral driver, matching the pattern in internal/entity/models/nvidia_rerank_test.go. Covered on this branch (driver-only PR): - Name() returns "mistral" - ChatWithMessages happy path, config propagation (max_tokens, temperature, top_p, stop), missing API key, empty messages, upstream HTTP error, unknown region - ChatStreamlyWithSender SSE parsing (multiple data: lines, final [DONE] sender call), stream=false rejection, stream truncation detection (no [DONE] / finish_reason) - ListModels happy path and missing-API-key guard - CheckConnection delegates to ListModels - Balance and Rerank return the "no such method" sentinel - Embed returns "not implemented" on this branch (the stub will be replaced by a real implementation in PR infiniflow#14807) All 16 tests pass with go test -vet=off -run TestMistral on go 1.25.
f365831 to
848cdbe
Compare
Added unit tests for Embed (commit 848cdbe)This branch was rebased onto the updated PR #14805 (which added the driver-test suite). On top, this commit replaces Coverage
Results23/23 pass on go 1.25 (15 from PR #14805 plus 8 new in this PR). This PR remains stacked on #14805 — after that lands, the diff here reduces to the Embed implementation in |
CodeRabbit review on the stacked PR infiniflow#14807 flagged two issues in the driver. Both apply to this branch since the driver code lives here. - 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. Add three tests pinning the new behaviors: - TestMistralChatFallsBackToDefaultOnEmptyRegion - TestMistralListModelsFallsBackToDefaultOnEmptyRegion - TestMistralStreamRequiresSender All 19 Mistral tests pass on go 1.25.
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.
848cdbe to
354231c
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/mistral_test.go (1)
27-29: ⚡ Quick winMake
Content-Typeassertion tolerant to valid parameters.Exact match on
"application/json"is brittle; valid values like"application/json; charset=utf-8"will fail this helper and create false negatives.♻️ Suggested change
import ( "encoding/json" "io" + "mime" "net/http" "net/http/httptest" "strings" "sync/atomic" "testing" ) @@ if r.Method == http.MethodPost { - if got := r.Header.Get("Content-Type"); got != "application/json" { + ct, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) + if ct != "application/json" { t.Errorf("expected Content-Type=application/json, got %q", got) 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 27 - 29, The test's Content-Type assertion uses an exact equality on r.Header.Get("Content-Type") which fails for valid values like "application/json; charset=utf-8"; update the check around that header retrieval to parse/tolerate parameters—e.g., call mime.ParseMediaType or normalize the header by trimming, lowercasing and splitting at ';' and then assert the media type equals "application/json" (replace the current exact-match branch that uses r.Header.Get("Content-Type") and t.Errorf).
🤖 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 27-29: The test's Content-Type assertion uses an exact equality on
r.Header.Get("Content-Type") which fails for valid values like
"application/json; charset=utf-8"; update the check around that header retrieval
to parse/tolerate parameters—e.g., call mime.ParseMediaType or normalize the
header by trimming, lowercasing and splitting at ';' and then assert the media
type equals "application/json" (replace the current exact-match branch that uses
r.Header.Get("Content-Type") and t.Errorf).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2c237f5f-612c-4703-82ec-fbbe48f837ef
📒 Files selected for processing (3)
conf/models/mistral.jsoninternal/entity/models/mistral.gointernal/entity/models/mistral_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- conf/models/mistral.json
- internal/entity/models/mistral.go
CodeRabbit review applied (rebased on top of #14805 fixes)The two findings CodeRabbit posted here ( This PR's own delta is unchanged: Embed implementation +
|
Haruko386
left a comment
There was a problem hiding this comment.
@tmimmanuel, LGTM!
thank you for your contribution.
Mirror the LocalAI fix (commit 7390d95): CodeRabbit caught that the reorder loop in *Model.Embed would silently overwrite the earlier vector if an upstream response repeated the same data[*].index value. The driver would then return a length-correct []EmbeddingData where some slots held the second vector under the index of the first, with no signal to the caller. Fail loudly: if filled[item.Index] is already true, return "mistral: duplicate embedding index <n> in response". Add TestMistralEmbedRejectsDuplicateIndex pinning the new behavior. All 27 Mistral tests pass.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14807 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
The (PR #14815 saw the same family of error in its run — The failing test waits for the document-parsing pipeline (OCR + chunker) to finish before it can delete the resulting chunks. When the CI runner is under load the parser overruns the wait window and the test fails with the generic "Document parsing timeout" assertion. Nothing in this PR touches:
Could a maintainer re-run the failed job? I tried |
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.
LongCat (Meituan, https://longcat.chat) is one of the unchecked providers on the umbrella tracking issue infiniflow#14736. Its API is OpenAI-compatible at https://api.longcat.chat/openai/v1 with three public chat models: LongCat-Flash-Chat, LongCat-Flash-Lite, and LongCat-Flash-Thinking (a reasoning model). What this PR includes: - internal/entity/models/longcat.go: full driver implementing the ModelDriver interface - conf/models/longcat.json: base URL + url_suffix + the 3 public models - factory.go: route "longcat" provider name to NewLongCatModel - internal/entity/models/longcat_test.go: 21 unit tests Methods: - ChatWithMessages non-stream chat - ChatStreamlyWithSender SSE streaming chat - ListModels / CheckConnection - reasoning_content extraction on both stream and non-stream paths (LongCat-Flash-Thinking returns the chain-of-thought in message.reasoning_content / delta.reasoning_content, OpenAI o-series shape; live-probed before writing tests) - reasoning_effort propagation from ChatConfig.Effort - Embed / Rerank / Balance / TranscribeAudio / AudioSpeech / OCRFile return the "no such method" sentinel (LongCat does not expose any of these surfaces) Pattern parity with the merged Mistral (infiniflow#14807), Upstage (infiniflow#14819), and StepFun (infiniflow#14815) drivers. No interface change. Verified live against api.longcat.chat: - ListModels: 5 ids (Flash-Lite, Flash-Chat, Flash-Thinking-2601, Flash-Omni-2603, 2.0-Preview) - Chat (Flash-Chat) non-stream: "Got it! Let me know if you..." - Chat (Flash-Thinking) non-stream: 443-char answer + 557-char reasoning trace extracted into ChatResponse.ReasonContent - Stream (Flash-Thinking): 78 content chunks (351 chars) + 107 reasoning chunks (537 chars) — the delta.reasoning_content extraction works end to end against real wire data - Sentinels all return "no such method" 21 unit tests pass on go 1.25; build clean. Note on PR history: this branch was previously named for LocalAI work which has since been consolidated into PR infiniflow#14813. The branch was reset to upstream/main and rebuilt for LongCat — diff is a clean +1052 lines on top of current main.
Add httptest-based unit tests for the Mistral driver, matching the pattern in internal/entity/models/nvidia_rerank_test.go. Covered on this branch (driver-only PR): - Name() returns "mistral" - ChatWithMessages happy path, config propagation (max_tokens, temperature, top_p, stop), missing API key, empty messages, upstream HTTP error, unknown region - ChatStreamlyWithSender SSE parsing (multiple data: lines, final [DONE] sender call), stream=false rejection, stream truncation detection (no [DONE] / finish_reason) - ListModels happy path and missing-API-key guard - CheckConnection delegates to ListModels - Balance and Rerank return the "no such method" sentinel - Embed returns "not implemented" on this branch (the stub will be replaced by a real implementation in PR infiniflow#14807) All 16 tests pass with go test -vet=off -run TestMistral on go 1.25.
CodeRabbit review on the stacked PR infiniflow#14807 flagged two issues in the driver. Both apply to this branch since the driver code lives here. - 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. Add three tests pinning the new behaviors: - TestMistralChatFallsBackToDefaultOnEmptyRegion - TestMistralListModelsFallsBackToDefaultOnEmptyRegion - TestMistralStreamRequiresSender All 19 Mistral tests pass on go 1.25.
LongCat (Meituan, https://longcat.chat) is one of the unchecked providers on the umbrella tracking issue infiniflow#14736. Its API is OpenAI-compatible at https://api.longcat.chat/openai/v1 with three public chat models: LongCat-Flash-Chat, LongCat-Flash-Lite, and LongCat-Flash-Thinking (a reasoning model). What this PR includes: - internal/entity/models/longcat.go: full driver implementing the ModelDriver interface - conf/models/longcat.json: base URL + url_suffix + the 3 public models - factory.go: route "longcat" provider name to NewLongCatModel - internal/entity/models/longcat_test.go: 21 unit tests Methods: - ChatWithMessages non-stream chat - ChatStreamlyWithSender SSE streaming chat - ListModels / CheckConnection - reasoning_content extraction on both stream and non-stream paths (LongCat-Flash-Thinking returns the chain-of-thought in message.reasoning_content / delta.reasoning_content, OpenAI o-series shape; live-probed before writing tests) - reasoning_effort propagation from ChatConfig.Effort - Embed / Rerank / Balance / TranscribeAudio / AudioSpeech / OCRFile return the "no such method" sentinel (LongCat does not expose any of these surfaces) Pattern parity with the merged Mistral (infiniflow#14807), Upstage (infiniflow#14819), and StepFun (infiniflow#14815) drivers. No interface change. Verified live against api.longcat.chat: - ListModels: 5 ids (Flash-Lite, Flash-Chat, Flash-Thinking-2601, Flash-Omni-2603, 2.0-Preview) - Chat (Flash-Chat) non-stream: "Got it! Let me know if you..." - Chat (Flash-Thinking) non-stream: 443-char answer + 557-char reasoning trace extracted into ChatResponse.ReasonContent - Stream (Flash-Thinking): 78 content chunks (351 chars) + 107 reasoning chunks (537 chars) — the delta.reasoning_content extraction works end to end against real wire data - Sentinels all return "no such method" 21 unit tests pass on go 1.25; build clean. Note on PR history: this branch was previously named for LocalAI work which has since been consolidated into PR infiniflow#14813. The branch was reset to upstream/main and rebuilt for LongCat — diff is a clean +1052 lines on top of current main.
…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)
…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?
The Mistral Go driver landed in #14805 with chat, list models, and check connection.
Embedwas left as a stub that returns"not implemented". This PR fills the gap.conf/models/mistral.jsondid 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 addsmistral-embedto the config and a real/v1/embeddingsimplementation.What this PR includes
conf/models/mistral.json: add"embedding": "embeddings"underurl_suffixso the driver can build the URL from config (matches theURLSuffix.Embeddingfield already used by openai, siliconflow, zhipu-ai), and add amistral-embedentry undermodels(1024-dimensional vectors, 8192 max input tokens).internal/entity/models/mistral.go: replace theEmbedstub with a real implementation that POSTs to/v1/embeddings. Adds local response typesmistralEmbeddingDataandmistralEmbeddingResponse.No factory change. No interface change.
How the implementation works
apiConfig, the API key, and the model name. Use the existingbaseURLForRegionhelper so an unknown region fails fast with a clear error.context.WithTimeout(nonStreamCallTimeout)so the call has a clear deadline. Same pattern asChatWithMessagesandListModelsalready use in this file.inputfield as an array.data[*].embeddingand copy each slice into a[]EmbeddingDataindexed bydata[*].indexso the output order matches the input order even if the API returns items in a different order.[]EmbeddingData{}with no HTTP call.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 theEmbedchanges (one commit, ~111 line diff inmistral.goplus 8 lines inmistral.json).Type of change
How was this tested?
go build ./internal/entity/models/...returns exit 0 on go 1.25 (thego.modminimum).MistralModelstill matches theModelDriverinterface.internal/entity/models/openai.go).Closes #14806
Depends on #14805
Tracking: #14736