Skip to content

Go: implement Encode (embeddings) in Ollama driver - #14664

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
davidv399:feat/go-ollama-encode
May 11, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
davidv399:feat/go-ollama-encode

Conversation

@davidv399

@davidv399 davidv399 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The Ollama Go driver shipped with a stub `Encode` method that returned `no such method`, even though Ollama is one of the most common local LLM runners and exposes an OpenAI-compatible embeddings endpoint at `/v1/embeddings`.

Ollama users routinely run local embedding models such as `nomic-embed-text`, `mxbai-embed-large`, or `bge-m3`.
Pulled with `ollama pull ` and served on the same `/v1` namespace as chat. The existing `ListModels` already
discovers them, but because `Encode` was a stub, a tenant who picked one of these models in the Go layer could not
actually run an embedding call.

What this PR includes

  • `conf/models/ollama.json`: add `"embedding": "embeddings"` under `url_suffix` so the
    driver can build the URL from config.
  • `internal/entity/models/ollama.go`: replace the `Encode` stub with a real implementation. Adds a small local response
    type that matches the OpenAI-compatible shape.

No factory change. No interface change.

How the driver works

  • Validate the model name. The API key is optional for local Ollama, so the Authorization header is only set when both
    `apiConfig` and `ApiKey` are non-nil and non-empty, the same pattern the recently merged CheckConnection PR (fix(go): wire CheckConnection to ListModels in ollama, lm-studio, and vllm #14614) uses.
  • Resolve the region with a default fallback. Return a clear "missing base URL" error when the user has not configured
    the local access address yet.
  • Use a per-call `context.WithTimeout(30s)` and `http.NewRequestWithContext`, the same pattern the merged
    Aliyun Encode (Go: implement Encode (embeddings) in Aliyun driver #14647) uses.
  • Send `{model, input: [texts]}` in one request.
  • Parse `data[].embedding` and copy each slice into a `[][]float64` indexed by `data[].index`, so the output
    order matches the input order.
  • Handle both `float64` and `float32` element types.
  • Empty input returns `[][]float64{}` with no HTTP call.
  • Length mismatch between input and result, out-of-range index, and any missing slot all return clear errors instead
    of silent zero vectors.

Type of change

  • New Feature (non-breaking change which adds functionality)

How was this tested?

  • `go build ./internal/entity/models/...` in a clean go 1.25 image returns exit 0.
  • The full method set on `OllamaModel` still matches the `ModelDriver` interface.
  • Pattern parity with the merged Aliyun Encode (Go: implement Encode (embeddings) in Aliyun driver #14647) and the existing SiliconFlow Encode.

Closes #14662

The Ollama Go driver shipped with a stub Encode method that
returned "no such method", even though Ollama is one of the
most common local LLM runners and exposes an OpenAI-compatible
embeddings endpoint at /v1/embeddings. Users who pulled local
embedding models such as nomic-embed-text or mxbai-embed-large
could not actually run an embedding call through the Go layer.

Changes:

- conf/models/ollama.json: add "embedding": "embeddings" under
  url_suffix so the driver can build the URL from config.
- internal/entity/models/ollama.go: replace the Encode stub
  with a real implementation. Adds a small local response type
  that matches the OpenAI-compatible shape.

How it works:

- Validate the model name. The API key is optional for local
  Ollama, so the Authorization header is only set when both
  apiConfig and ApiKey are non-nil and non-empty, the same
  pattern the recently merged CheckConnection PR uses.
- Resolve the region with a default fallback. Return a clear
  "missing base URL" error when the user has not configured
  the local access address yet.
- Use a per-call context.WithTimeout(30s) and
  http.NewRequestWithContext, the same pattern the recent
  Aliyun Encode uses.
- Send {model, input: [texts]} in one request.
- Parse data[*].embedding and copy each slice into a
  [][]float64 indexed by data[*].index, so the output order
  matches the input order.
- Handle both float64 and float32 element types.
- Empty input returns [][]float64{} with no HTTP call.
- Length mismatch between input and result, out-of-range
  index, and any missing slot all return clear errors instead
  of silent zero vectors.

Closes infiniflow#14662
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 8, 2026
@davidv399

Copy link
Copy Markdown
Contributor Author

Hi @Magicbook1108, gentle ping for review. Same OpenAI-compatible /embeddings shape that the merged Aliyun Encode (#14647) and SiliconFlow Encode already use, scope is two files (one config, one driver), and it closes #14662. Thanks!

@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c224c4bb-d9f6-43db-a56d-6f0c51b29eea

📥 Commits

Reviewing files that changed from the base of the PR and between ca7e034 and e846605.

📒 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 an embeddings URL suffix to Ollama config and implements OllamaModel.Encode to call /v1/embeddings with a 30s timeout, optional Authorization, JSON response parsing, index/count validation, and conversion of embeddings to [][]float64.

Changes

Ollama Embeddings Support

Layer / File(s) Summary
Configuration
conf/models/ollama.json
Adds embedding: "embeddings" to url_suffix mapping alongside existing chat and models entries.
Response Type & Dependencies
internal/entity/models/ollama.go
Imports context for timeout handling; defines ollamaEmbeddingResponse struct to unmarshal Ollama's embeddings response (data[].index, data[].embedding).
Encode Method Implementation
internal/entity/models/ollama.go
Implements OllamaModel.Encode to POST embedding requests to the configured Ollama endpoint with a 30s context timeout, set Authorization only if API key present, parse and validate response, convert numeric values to []float64, and return [][]float64 or descriptive errors.
Factory Wiring
internal/entity/models/factory.go
Adds a case "ollama" branch to CreateModelDriver to return NewOllamaModel(...) for the provider.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Encode as OllamaModel.Encode
  participant HTTP as httpClient
  participant Ollama as Ollama API
  Caller->>Encode: texts[], modelName, config
  Encode->>Encode: validate inputs
  Encode->>Encode: resolve base URL
  Encode->>Encode: create context with timeout
  Encode->>HTTP: POST /v1/embeddings
  HTTP->>Ollama: request (optional Authorization)
  Ollama-->>HTTP: embeddings response
  HTTP-->>Encode: response body
  Encode->>Encode: parse response struct
  Encode->>Encode: validate counts & indices
  Encode->>Encode: convert to [][]float64
  Encode-->>Caller: embeddings or error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #14646: Both implement the model driver Encode (embeddings) path and add embedding-related config entries.
  • #14629: Both add an "embeddings" url_suffix and implement Encode in a model driver.

Possibly related PRs

Suggested labels

size:M

Poem

🐰 Hopping through vectors, soft and neat,
Ollama hums where local models meet,
Context set, timeouts keep the pace,
Float64 dons its math-space lace,
A rabbit cheers your embeddings' feat!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: implementing the Encode (embeddings) method in the Ollama driver.
Description check ✅ Passed The description covers required sections (problem, type of change) and provides comprehensive implementation details, usage patterns, and testing approach.
Linked Issues check ✅ Passed The PR implementation fully addresses all coding requirements from issue #14662: POST to embeddings endpoint, optional Authorization header, OpenAI-compatible request/response, per-call timeout, url_suffix config update, and order preservation via index.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing Encode in Ollama driver: config update (ollama.json), method implementation (ollama.go), and factory registration (factory.go). No unrelated modifications present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

🧹 Nitpick comments (2)
internal/entity/models/ollama.go (2)

363-368: ⚡ Quick win

float32 type-switch branch is unreachable.

Go's encoding/json always unmarshals JSON numbers into float64 when the target is interface{}; a float32 value can never appear here. The case float32 branch at line 451 is dead code and may mislead future maintainers.

🔧 Proposed fix
 type ollamaEmbeddingResponse struct {
 	Data []struct {
 		Index     int           `json:"index"`
-		Embedding []interface{} `json:"embedding"`
+		Embedding []float64     `json:"embedding"`
 	} `json:"data"`
 }

With a concrete []float64 element type, the type switch in Encode is no longer needed and the loop simplifies to:

 vec := make([]float64, len(item.Embedding))
-for j, v := range item.Embedding {
-    switch val := v.(type) {
-    case float64:
-        vec[j] = val
-    case float32:
-        vec[j] = float64(val)
-    default:
-        return nil, fmt.Errorf("unexpected embedding value type at item %d index %d", item.Index, j)
-    }
-}
+copy(vec, item.Embedding)
🤖 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/ollama.go` around lines 363 - 368, The
ollamaEmbeddingResponse struct's Embedding field is declared as []interface{}
which causes unreachable float32 type-switch branches; change Embedding to
[]float64 in type ollamaEmbeddingResponse (and any other uses), then update the
Encode function (the loop handling Data[i].Embedding) to treat each embedding
element as float64 directly—remove the float32 case and either cast float64 ->
float32 only where you actually need float32 (e.g., building []float32 output)
or keep []float64 throughout; ensure all references to Data[].Embedding and the
Encode conversion logic (function Encode) are adjusted to the concrete []float64
type.

404-407: 💤 Low value

context.Background() ignores caller cancellation; embeddingConfig is silently ignored.

Two concerns here:

  1. Context not threaded through: context.WithTimeout(context.Background(), 30*time.Second) creates a fresh root context, so if the caller's context is already cancelled or has a shorter deadline, the HTTP call will not respect it. The method signature does not accept a context.Context, but at minimum the 30 s cap should be documented given that large batches may legitimately exceed it.

  2. embeddingConfig is unused: the parameter is accepted for interface compliance but no field (e.g. dimensions, encoding format) is ever read. This is fine for now but worth a // embeddingConfig is reserved for future use comment to prevent silent data loss if a caller sets options expecting them to take effect.

🤖 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/ollama.go` around lines 404 - 407, The code creates a
fresh root context via context.WithTimeout(context.Background(), 30*time.Second)
which ignores caller cancellation and also silently ignores the embeddingConfig
parameter; fix by (preferably) changing the method signature to accept a caller
context (ctx context.Context) and use context.WithTimeout(ctx, 30*time.Second)
so the http.NewRequestWithContext call respects caller cancellation, or if you
cannot change the signature, add a clear comment/docstring stating the hard 30s
timeout is enforced and may block long batches; additionally add an explicit
comment like "// embeddingConfig is reserved for future use" and reference the
embeddingConfig symbol so callers know their options are not currently applied.
🤖 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/ollama.go`:
- Around line 363-368: The ollamaEmbeddingResponse struct's Embedding field is
declared as []interface{} which causes unreachable float32 type-switch branches;
change Embedding to []float64 in type ollamaEmbeddingResponse (and any other
uses), then update the Encode function (the loop handling Data[i].Embedding) to
treat each embedding element as float64 directly—remove the float32 case and
either cast float64 -> float32 only where you actually need float32 (e.g.,
building []float32 output) or keep []float64 throughout; ensure all references
to Data[].Embedding and the Encode conversion logic (function Encode) are
adjusted to the concrete []float64 type.
- Around line 404-407: The code creates a fresh root context via
context.WithTimeout(context.Background(), 30*time.Second) which ignores caller
cancellation and also silently ignores the embeddingConfig parameter; fix by
(preferably) changing the method signature to accept a caller context (ctx
context.Context) and use context.WithTimeout(ctx, 30*time.Second) so the
http.NewRequestWithContext call respects caller cancellation, or if you cannot
change the signature, add a clear comment/docstring stating the hard 30s timeout
is enforced and may block long batches; additionally add an explicit comment
like "// embeddingConfig is reserved for future use" and reference the
embeddingConfig symbol so callers know their options are not currently applied.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 04ed333e-5034-4f77-9ca4-5792f14d65f0

📥 Commits

Reviewing files that changed from the base of the PR and between a82ae4a and 8069b04.

📒 Files selected for processing (2)
  • conf/models/ollama.json
  • internal/entity/models/ollama.go

ivannnnnik pushed a commit to ivannnnnik/ragflow that referenced this pull request May 8, 2026
Wires the existing stub to the DeepSeek OpenAI-compatible /embeddings
endpoint and adds the embedding URL suffix and text-embedding-v3 model
entry to conf/models/deepseek.json.

The implementation mirrors the recently merged Aliyun Encode and the
in-flight OpenAI (infiniflow#14682) and Ollama (infiniflow#14664) PRs:

- POST to ${BaseURL}/${URLSuffix.Embedding}
- Authorization: Bearer <api_key>
- OpenAI-compatible request body {"model", "input"}
- Per-call context.WithTimeout(nonStreamCallTimeout) so a slow upstream
  cannot block forever
- [][]float64 returned in the original input order, sorted by the
  response `index` field, with explicit checks for out-of-range,
  duplicate, and missing indices

Adds internal/entity/models/deepseek_test.go covering the happy path,
empty-input short-circuit, missing api key / model name, non-OK
upstream status, and out-of-range / missing-index responses.

Closes infiniflow#14680

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ivannnnnik pushed a commit to ivannnnnik/ragflow that referenced this pull request May 8, 2026
Wires the existing stub to the DeepSeek OpenAI-compatible /embeddings
endpoint and adds the embedding URL suffix and text-embedding-v3 model
entry to conf/models/deepseek.json.

The implementation mirrors the recently merged Aliyun Encode and the
in-flight OpenAI (infiniflow#14682) and Ollama (infiniflow#14664) PRs:

- POST to ${BaseURL}/${URLSuffix.Embedding}
- Authorization: Bearer <api_key>
- OpenAI-compatible request body {"model", "input"}
- Per-call context.WithTimeout(nonStreamCallTimeout) so a slow upstream
  cannot block forever
- [][]float64 returned in the original input order, sorted by the
  response `index` field, with explicit checks for out-of-range,
  duplicate, and missing indices

Adds internal/entity/models/deepseek_test.go covering the happy path,
empty-input short-circuit, missing api key / model name, non-OK
upstream status, and out-of-range / missing-index responses.

Closes infiniflow#14680
ivannnnnik added a commit to ivannnnnik/ragflow that referenced this pull request May 8, 2026
Wires the existing stub to the DeepSeek OpenAI-compatible /embeddings
endpoint and adds the embedding URL suffix and text-embedding-v3 model
entry to conf/models/deepseek.json.

The implementation mirrors the recently merged Aliyun Encode and the
in-flight OpenAI (infiniflow#14682) and Ollama (infiniflow#14664) PRs:

- POST to ${BaseURL}/${URLSuffix.Embedding}
- Authorization: Bearer <api_key>
- OpenAI-compatible request body {"model", "input"}
- Per-call context.WithTimeout(nonStreamCallTimeout) so a slow upstream
  cannot block forever
- [][]float64 returned in the original input order, sorted by the
  response `index` field, with explicit checks for out-of-range,
  duplicate, and missing indices

Adds internal/entity/models/deepseek_test.go covering the happy path,
empty-input short-circuit, missing api key / model name, non-OK
upstream status, and out-of-range / missing-index responses.

Closes infiniflow#14680
@JinHai-CN

Copy link
Copy Markdown
Member

@jack-stormentswe Encode interface is updated, would you please update your implementation accordingly? please refer to #14735

@davidv399

davidv399 commented May 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN, how are you?
Done! ❤️ thanks for your kind message.

@JinHai-CN

Copy link
Copy Markdown
Member

@jack-stormentswe Refer to the CLI usage in #14736, would you please provide the CLI embedding test result as below?

RAGFlow(user)> embed text 'what is rag' 'who are you' with 'embedding-3@test@zhipu-ai' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 16        | 0     |
| 16        | 1     |
+-----------+-------+

@davidv399

davidv399 commented May 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN, here is the CLI test output on Ollama with the latest commit:

RAGFlow(user)> embed text 'what is rag' 'who are you' with 'nomic-embed-text:latest@test@ollama' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 16        | 0     |
| 16        | 1     |
+-----------+-------+

embeddingConfig.Dimension is honored as expected.

@JinHai-CN JinHai-CN added the ci Continue Integration label May 11, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 11, 2026 03:25
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 03:25
@codecov

codecov Bot commented May 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (6bfe0f9) to head (e846605).
⚠️ Report is 15 commits behind head on main.

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

JinHai-CN pushed a commit that referenced this pull request May 11, 2026
### What problem does this PR solve?

The vLLM Go driver shipped with a stub \`Encode\` method that returned
\`not implemented\`, even though vLLM is one of the most common
production-grade self-hosted inference servers and exposes an
OpenAI-compatible embeddings endpoint at \`/v1/embeddings\`.

Users who self-host \`BAAI/bge-m3\`, \`Qwen3-Embedding-*\`,
\`NV-Embed-v2\`, or similar models on vLLM could not run an embedding
call through the Go layer. The existing \`ListModels\` already discovers
the loaded models, but the embedding path failed because \`Encode\` was
a stub.

### What this PR includes

- \`conf/models/vllm.json\`: add \`\"embedding\": \"embeddings\"\` under
\`url_suffix\` so the driver can build the URL from config.
- \`internal/entity/models/vllm.go\`: replace the \`Encode\` stub with a
real implementation. Adds a small local response
  type that matches the OpenAI-compatible shape.

No factory change. No interface change.

### How the driver works

- Validate the model name. The API key is optional for self-hosted vLLM,
so the Authorization header is only set when both \`apiConfig\` and
\`ApiKey\` are non-nil and non-empty, the same pattern the recently
merged CheckConnection PR (#14614) uses.
- Resolve the region with a default fallback. Return a clear "missing
base URL" error when the user has not configured
  the local access address yet.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, the same pattern the merged
  Aliyun Encode (#14647) and in-flight Ollama Encode (#14664) use.
- Send \`{model, input: [texts]}\` in one request.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\`, so the output
  order matches the input order.
- Handle both \`float64\` and \`float32\` element types.
- Empty input returns \`[][]float64{}\` with no HTTP call.
- Length mismatch between input and result, out-of-range index, and any
missing slot all return clear errors instead
  of silent zero vectors.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`VllmModel\` still matches the \`ModelDriver\`
interface.
- Pattern parity with the merged Aliyun Encode (#14647), the in-flight
Ollama Encode (#14664), and the existing
  SiliconFlow Encode.

Closes #14687
@JinHai-CN
JinHai-CN merged commit 8ff623f into infiniflow:main May 11, 2026
2 checks passed
JinHai-CN pushed a commit that referenced this pull request May 11, 2026
### What problem does this PR solve?

The LM Studio Go driver shipped with a stub \`Encode\` method that
returned \`no such method\`, even though LM Studio is one of the most
common local LLM runners on macOS and Windows and exposes an
OpenAI-compatible embeddings endpoint at \`/v1/embeddings\`.

LM Studio users routinely load local embedding models such as
\`nomic-ai/nomic-embed-text-v1.5\`,
\`mixedbread-ai/mxbai-embed-large-v1\`, or \`BAAI/bge-m3\`. They run on
the same \`/v1\` namespace as chat. The existing \`ListModels\` already
discovers them, but because \`Encode\` was a stub, a tenant who picked
one of these models in the Go layer could not actually run an embedding
call.

This finishes the local-LLM trio: Ollama Encode (#14664) and vLLM Encode
(#14688) are already in flight, both using the
same OpenAI-compatible \`/embeddings\` shape.

### What this PR includes

- \`conf/models/lmstudio.json\`: add \`\"embedding\": \"embeddings\"\`
under \`url_suffix\` so the driver can build the URL from config.
- \`internal/entity/models/lmstudio.go\`: replace the \`Encode\` stub
with a real implementation. Adds a small local response type that
matches the OpenAI-compatible shape.

No factory change. No interface change.

### How the driver works

- Validate the model name. The API key is optional for local LM Studio,
so the Authorization header is only set when both \`apiConfig\` and
\`ApiKey\` are non-nil and non-empty, the same pattern the recently
merged CheckConnection PR (#14614) uses.
- Resolve the region with a default fallback. Return a clear "missing
base URL" error when the user has not configured
  the local access address yet.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, the same pattern the merged
Aliyun Encode (#14647) and the in-flight Ollama Encode (#14664) and vLLM
Encode (#14688) use.
- Send \`{model, input: [texts]}\` in one request.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\`, so the output
  order matches the input order.
- Handle both \`float64\` and \`float32\` element types.
- Empty input returns \`[][]float64{}\` with no HTTP call.
- Length mismatch between input and result, out-of-range index, and any
missing slot all return clear errors instead
  of silent zero vectors.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`LmStudioModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the merged Aliyun Encode (#14647), the in-flight
Ollama Encode (#14664) and vLLM Encode (#14688), and the existing
SiliconFlow Encode.

Closes #14693
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 vLLM Go driver shipped with a stub \`Encode\` method that returned
\`not implemented\`, even though vLLM is one of the most common
production-grade self-hosted inference servers and exposes an
OpenAI-compatible embeddings endpoint at \`/v1/embeddings\`.

Users who self-host \`BAAI/bge-m3\`, \`Qwen3-Embedding-*\`,
\`NV-Embed-v2\`, or similar models on vLLM could not run an embedding
call through the Go layer. The existing \`ListModels\` already discovers
the loaded models, but the embedding path failed because \`Encode\` was
a stub.

### What this PR includes

- \`conf/models/vllm.json\`: add \`\"embedding\": \"embeddings\"\` under
\`url_suffix\` so the driver can build the URL from config.
- \`internal/entity/models/vllm.go\`: replace the \`Encode\` stub with a
real implementation. Adds a small local response
  type that matches the OpenAI-compatible shape.

No factory change. No interface change.

### How the driver works

- Validate the model name. The API key is optional for self-hosted vLLM,
so the Authorization header is only set when both \`apiConfig\` and
\`ApiKey\` are non-nil and non-empty, the same pattern the recently
merged CheckConnection PR (infiniflow#14614) uses.
- Resolve the region with a default fallback. Return a clear "missing
base URL" error when the user has not configured
  the local access address yet.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, the same pattern the merged
  Aliyun Encode (infiniflow#14647) and in-flight Ollama Encode (infiniflow#14664) use.
- Send \`{model, input: [texts]}\` in one request.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\`, so the output
  order matches the input order.
- Handle both \`float64\` and \`float32\` element types.
- Empty input returns \`[][]float64{}\` with no HTTP call.
- Length mismatch between input and result, out-of-range index, and any
missing slot all return clear errors instead
  of silent zero vectors.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`VllmModel\` still matches the \`ModelDriver\`
interface.
- Pattern parity with the merged Aliyun Encode (infiniflow#14647), the in-flight
Ollama Encode (infiniflow#14664), and the existing
  SiliconFlow Encode.

Closes infiniflow#14687
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 Ollama Go driver shipped with a stub \`Encode\` method that returned
\`no such method\`, even though Ollama is one of the most common local
LLM runners and exposes an OpenAI-compatible embeddings endpoint at
\`/v1/embeddings\`.

Ollama users routinely run local embedding models such as
\`nomic-embed-text\`, \`mxbai-embed-large\`, or \`bge-m3\`.
Pulled with \`ollama pull <model>\` and served on the same \`/v1\`
namespace as chat. The existing \`ListModels\` already
discovers them, but because \`Encode\` was a stub, a tenant who picked
one of these models in the Go layer could not
actually run an embedding call.

### What this PR includes

- \`conf/models/ollama.json\`: add \`\"embedding\": \"embeddings\"\`
under \`url_suffix\` so the
  driver can build the URL from config.
- \`internal/entity/models/ollama.go\`: replace the \`Encode\` stub with
a real implementation. Adds a small local response
  type that matches the OpenAI-compatible shape.

No factory change. No interface change.

### How the driver works

- Validate the model name. The API key is optional for local Ollama, so
the Authorization header is only set when both
\`apiConfig\` and \`ApiKey\` are non-nil and non-empty, the same pattern
the recently merged CheckConnection PR (infiniflow#14614) uses.
- Resolve the region with a default fallback. Return a clear "missing
base URL" error when the user has not configured
  the local access address yet.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, the same pattern the merged
  Aliyun Encode (infiniflow#14647) uses.
- Send \`{model, input: [texts]}\` in one request.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\`, so the output
  order matches the input order.
- Handle both \`float64\` and \`float32\` element types.
- Empty input returns \`[][]float64{}\` with no HTTP call.
- Length mismatch between input and result, out-of-range index, and any
missing slot all return clear errors instead
  of silent zero vectors.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`OllamaModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the merged Aliyun Encode (infiniflow#14647) and the existing
SiliconFlow Encode.

Closes infiniflow#14662
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 LM Studio Go driver shipped with a stub \`Encode\` method that
returned \`no such method\`, even though LM Studio is one of the most
common local LLM runners on macOS and Windows and exposes an
OpenAI-compatible embeddings endpoint at \`/v1/embeddings\`.

LM Studio users routinely load local embedding models such as
\`nomic-ai/nomic-embed-text-v1.5\`,
\`mixedbread-ai/mxbai-embed-large-v1\`, or \`BAAI/bge-m3\`. They run on
the same \`/v1\` namespace as chat. The existing \`ListModels\` already
discovers them, but because \`Encode\` was a stub, a tenant who picked
one of these models in the Go layer could not actually run an embedding
call.

This finishes the local-LLM trio: Ollama Encode (infiniflow#14664) and vLLM Encode
(infiniflow#14688) are already in flight, both using the
same OpenAI-compatible \`/embeddings\` shape.

### What this PR includes

- \`conf/models/lmstudio.json\`: add \`\"embedding\": \"embeddings\"\`
under \`url_suffix\` so the driver can build the URL from config.
- \`internal/entity/models/lmstudio.go\`: replace the \`Encode\` stub
with a real implementation. Adds a small local response type that
matches the OpenAI-compatible shape.

No factory change. No interface change.

### How the driver works

- Validate the model name. The API key is optional for local LM Studio,
so the Authorization header is only set when both \`apiConfig\` and
\`ApiKey\` are non-nil and non-empty, the same pattern the recently
merged CheckConnection PR (infiniflow#14614) uses.
- Resolve the region with a default fallback. Return a clear "missing
base URL" error when the user has not configured
  the local access address yet.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, the same pattern the merged
Aliyun Encode (infiniflow#14647) and the in-flight Ollama Encode (infiniflow#14664) and vLLM
Encode (infiniflow#14688) use.
- Send \`{model, input: [texts]}\` in one request.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\`, so the output
  order matches the input order.
- Handle both \`float64\` and \`float32\` element types.
- Empty input returns \`[][]float64{}\` with no HTTP call.
- Length mismatch between input and result, out-of-range index, and any
missing slot all return clear errors instead
  of silent zero vectors.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`LmStudioModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the merged Aliyun Encode (infiniflow#14647), the in-flight
Ollama Encode (infiniflow#14664) and vLLM Encode (infiniflow#14688), and the existing
SiliconFlow Encode.

Closes infiniflow#14693
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement Encode (embeddings) in the Ollama Go driver

2 participants