Skip to content

Go: implement Embed (embeddings) in Mistral driver - #14807

Merged
JinHai-CN merged 11 commits into
infiniflow:mainfrom
tmimmanuel:go/mistral-embed
May 12, 2026
Merged

JinHai-CN merged 11 commits into
infiniflow:mainfrom
tmimmanuel:go/mistral-embed

Conversation

@tmimmanuel

Copy link
Copy Markdown
Contributor

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

  • 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

@dosubot dosubot Bot added the size:XL This PR changes 500-999 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: a4aafcca-481b-4b90-8b10-c8675a6e1962

📥 Commits

Reviewing files that changed from the base of the PR and between 893f640 and c6d4706.

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

📝 Walkthrough

Walkthrough

Adds Mistral provider: config, factory registration, MistralModel driver (chat non-stream + SSE, embeddings, list models, connection check, unsupported stubs), and comprehensive unit tests.

Changes

Mistral Provider Integration

Layer / File(s) Summary
Provider Configuration
conf/models/mistral.json
Defines base URLs, url_suffix for chat, models, embedding, and lists Mistral model IDs with max_tokens and model_types.
Factory Registration
internal/entity/models/factory.go
Adds "mistral" case to CreateModelDriver to return NewMistralModel(baseURL, urlSuffix).
Type Definition & HTTP Transport
internal/entity/models/mistral.go
Adds MistralModel type and constructor, clones http.DefaultTransport, and configures pooled transport and timeouts.
Initialization & region lookup
internal/entity/models/mistral.go
Implements NewInstance, Name, and base-URL region lookup with error on missing region.
Chat (non-stream)
internal/entity/models/mistral.go
Implements ChatWithMessages (validates API key/messages, posts JSON, enforces timeout, parses choices[0].message.content).
Chat (SSE streaming)
internal/entity/models/mistral.go
Implements ChatStreamlyWithSender (SSE POST with stream:true, scans data: events, forwards delta.content via sender, terminal handling and final [DONE]).
Embeddings Support
internal/entity/models/mistral.go
Implements Embed: empty-input short-circuit, validates API key/model, POSTs to embeddings endpoint, parses embeddings and reorders by returned index to match input order; errors on duplicates/out-of-range/missing indices.
Model Listing & Connection Validation
internal/entity/models/mistral.go
Implements ListModels (GET /models -> parse data[].id) and CheckConnection delegating to ListModels.
Unsupported Method Stubs
internal/entity/models/mistral.go
Implements Balance and Rerank returning "no such method" errors.
Tests & Helpers
internal/entity/models/mistral_test.go
Adds httptest server helper, Mistral test constructor, and extensive unit tests covering chat, streaming, embeddings, listing, connection check, and unsupported stubs.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

"🐰 I hopped through configs, code, and test today,
Mistral now chats, streams, and embeds away.
Chunks and vectors neatly keep their place,
Region-aware, polite, and full of grace—
Hooray for models, in rabbit-feet array!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'Go: implement Embed (embeddings) in Mistral driver' clearly describes the main change: adding embeddings support to the Mistral driver.
Description check ✅ Passed The description includes both required sections (What problem does this PR solve and Type of change) with substantial detail about the implementation, testing, and dependencies.
Linked Issues check ✅ Passed The PR fully implements the requirements from issue #14806: Embed method POSTs to /v1/embeddings [#14806], config updated with embedding URL suffix and mistral-embed model [#14806], validates API key and model name, uses context timeout, reorders by index, and includes comprehensive unit tests.
Out of Scope Changes check ✅ Passed All changes are within scope of issue #14806 and PR objectives: config updates, Embed implementation, and related unit tests. No unrelated or extraneous changes detected.

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

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

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

📥 Commits

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

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

Comment thread internal/entity/models/mistral.go Resolved
Comment thread internal/entity/models/mistral.go Resolved
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.
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

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 TestMistralEmbedReturnsNotImplemented — which only pinned the stub — with eight tests covering the real /v1/embeddings implementation.

Coverage

Test What it pins
TestMistralEmbedHappyPath POST /embeddings, model name + input-array shape, vectors back in order
TestMistralEmbedReordersByIndex upstream returns [index 2, index 0, index 1] — driver realigns by index field so vecs[i].Index == i
TestMistralEmbedEmptyInputShortCircuits Embed(..., []string{}, ...) makes zero HTTP calls. The mock server fails the test if it's hit.
TestMistralEmbedRequiresAPIKey nil and empty-string key both rejected
TestMistralEmbedRequiresModelName nil *modelName and &"" both rejected
TestMistralEmbedRejectsOutOfRangeIndex upstream index: 7 with 2 inputs → clear error instead of silent panic on slice growth
TestMistralEmbedRejectsMissingSlot upstream returns only 1 of 2 requested embeddings → clear error for the missing slot
TestMistralEmbedRejectsHTTPError upstream 401 propagated, not swallowed

Results

$ go test -vet=off -run TestMistral -v ./internal/entity/models/...
=== RUN   TestMistralName
--- PASS: TestMistralName (0.00s)
=== RUN   TestMistralChatHappyPath
--- PASS: TestMistralChatHappyPath (0.00s)
=== RUN   TestMistralChatPropagatesConfig
--- PASS: TestMistralChatPropagatesConfig (0.00s)
=== RUN   TestMistralChatRequiresAPIKey
--- PASS: TestMistralChatRequiresAPIKey (0.00s)
=== RUN   TestMistralChatRequiresMessages
--- PASS: TestMistralChatRequiresMessages (0.00s)
=== RUN   TestMistralChatRejectsHTTPError
--- PASS: TestMistralChatRejectsHTTPError (0.02s)
=== RUN   TestMistralChatRejectsUnknownRegion
--- PASS: TestMistralChatRejectsUnknownRegion (0.00s)
=== RUN   TestMistralStreamHappyPath
--- PASS: TestMistralStreamHappyPath (0.00s)
=== RUN   TestMistralStreamRejectsExplicitFalse
--- PASS: TestMistralStreamRejectsExplicitFalse (0.00s)
=== RUN   TestMistralStreamFailsWithoutTerminal
--- PASS: TestMistralStreamFailsWithoutTerminal (0.00s)
=== RUN   TestMistralListModelsHappyPath
--- PASS: TestMistralListModelsHappyPath (0.00s)
=== RUN   TestMistralListModelsRequiresAPIKey
--- PASS: TestMistralListModelsRequiresAPIKey (0.00s)
=== RUN   TestMistralCheckConnectionDelegatesToListModels
--- PASS: TestMistralCheckConnectionDelegatesToListModels (0.00s)
=== RUN   TestMistralBalanceReturnsNoSuchMethod
--- PASS: TestMistralBalanceReturnsNoSuchMethod (0.00s)
=== RUN   TestMistralRerankReturnsNoSuchMethod
--- PASS: TestMistralRerankReturnsNoSuchMethod (0.00s)
=== RUN   TestMistralEmbedHappyPath
--- PASS: TestMistralEmbedHappyPath (0.00s)
=== RUN   TestMistralEmbedReordersByIndex
--- PASS: TestMistralEmbedReordersByIndex (0.00s)
=== RUN   TestMistralEmbedEmptyInputShortCircuits
--- PASS: TestMistralEmbedEmptyInputShortCircuits (0.00s)
=== RUN   TestMistralEmbedRequiresAPIKey
--- PASS: TestMistralEmbedRequiresAPIKey (0.00s)
=== RUN   TestMistralEmbedRequiresModelName
--- PASS: TestMistralEmbedRequiresModelName (0.00s)
=== RUN   TestMistralEmbedRejectsOutOfRangeIndex
--- PASS: TestMistralEmbedRejectsOutOfRangeIndex (0.00s)
=== RUN   TestMistralEmbedRejectsMissingSlot
--- PASS: TestMistralEmbedRejectsMissingSlot (0.00s)
=== RUN   TestMistralEmbedRejectsHTTPError
--- PASS: TestMistralEmbedRejectsHTTPError (0.00s)
PASS
ok  	ragflow/internal/entity/models	0.049s

23/23 pass on go 1.25 (15 from PR #14805 plus 8 new in this PR). -vet=off only because of pre-existing format-string issues in other drivers (baidu/cohere/fishaudio/openrouter) untouched by this PR.

This PR remains stacked on #14805 — after that lands, the diff here reduces to the Embed implementation in mistral.go, the mistral.json updates, and the 8-test addition to mistral_test.go.

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.

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

27-29: ⚡ Quick win

Make Content-Type assertion 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

📥 Commits

Reviewing files that changed from the base of the PR and between 848cdbe and 354231c.

📒 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 (2)
  • conf/models/mistral.json
  • internal/entity/models/mistral.go

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

CodeRabbit review applied (rebased on top of #14805 fixes)

The two findings CodeRabbit posted here (mistral.go:106 empty-region, mistral.go:219 nil-sender) live on the driver code that this PR depends on. They were fixed in PR #14805 commit ee08b64 and this branch was rebased on top — see my comment there for the diff.

This PR's own delta is unchanged: Embed implementation + mistral.json updates + 8 Embed tests.

go test -vet=off -run TestMistral ./internal/entity/models/... → 26/26 pass on the rebased branch (19 from #14805 + 7 Embed tests; one driver-branch test was replaced).

@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, LGTM!
thank you for your contribution.

@Haruko386 Haruko386 added the ci Continue Integration label May 12, 2026
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

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 (eaa2e46) to head (c6d4706).
⚠️ Report is 1 commits behind head on main.

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

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

The ragflow_tests failure here is unrelated to this PR's diff — it's a flake in the Python SDK suite. The failing test in this run was:

ERROR test/testcases/test_sdk_api/test_chunk_management_within_dataset/test_delete_chunks.py
::TestChunksDeletion::test_basic_scenarios[<lambda>--1] - AssertionError: Document parsing timeout

(PR #14815 saw the same family of error in its run — Document parsing timeout — but on a different test in the same Python SDK suite, so this is a CI-side timing issue rather than a regression from this branch.)

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:

  • The document-parsing pipeline
  • The Python SDK
  • Anything outside internal/entity/models/mistral.go + conf/models/mistral.json + the Go unit tests

Could a maintainer re-run the failed job? I tried gh run rerun --failed from my side but the API rejected it ("cannot be rerun"), which is expected since the run is on the upstream repo where I don't have rerun rights.

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
JinHai-CN merged commit 7d38369 into infiniflow:main May 12, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 12, 2026
1 task done
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
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.
@coderabbitai coderabbitai Bot mentioned this pull request May 12, 2026
1 task done
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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.
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)
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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement Embed (embeddings) in the Mistral Go driver

3 participants