Skip to content

Go: implement Encode (embeddings) in vLLM driver - #14688

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
pandadev66:feat/go-vllm-encode
May 11, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
pandadev66:feat/go-vllm-encode

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

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 (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) and in-flight Ollama Encode (Go: implement Encode (embeddings) in Ollama driver #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

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

How was this tested?

Closes #14687

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, or similar models on vLLM could not
run an embedding call through the Go layer.

Changes:

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

How it 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
  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 and the in-flight Ollama Encode 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.

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

Copy link
Copy Markdown
Contributor Author

Hi @Magicbook1108, gentle ping for review. Same OpenAI-compatible /embeddings shape that the merged Aliyun Encode (#14647) and the in-flight Ollama Encode (#14664) already use, scope is two files (one config, one driver), and it closes #14687. 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: 305fbcdd-e520-43fe-a000-3d53dde8c0d5

📥 Commits

Reviewing files that changed from the base of the PR and between 46d9ceb and 30609a5.

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

📝 Walkthrough

Walkthrough

Implements vLLM embeddings: adds embedding URL suffix in config, defines a response struct, imports context, and replaces the Encode stub with an HTTP POST implementation that sends inputs, applies a 30s timeout, optional Authorization, parses and validates the JSON embeddings response, and returns ordered vectors.

Changes

vLLM Embeddings API Implementation

Layer / File(s) Summary
Configuration Update
conf/models/vllm.json
Adds embedding URL suffix mapping to the embeddings endpoint path.
Context Import
internal/entity/models/vllm.go
Adds context import to enable per-request timeouts.
Response Type Definition
internal/entity/models/vllm.go
Introduces vllmEmbeddingResponse struct to model the embeddings API response with data entries (index + embedding), model, and object fields.
Encode Implementation
internal/entity/models/vllm.go
Replaces stub with full HTTP POST handler: input validation, region/base-URL selection with fallback, optional dimensions, 30s context timeout, conditional Authorization header, JSON parsing, strict count/index validation, float conversion, and assembly of [][]float64 in input order.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested labels

💞 feature, size:M

Suggested reviewers

  • Haruko386

Poem

🐰 A vLLM with wings takes flight,
Embeddings hum in soft moonlight,
No more stubs to block the way,
Vectors bloom from /v1 today —
Indexes ordered, curls of code delight.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: implementing the Encode method for embeddings in the vLLM Go driver.
Description check ✅ Passed The PR description follows the template with clear problem statement, implementation details, type selection, and testing information provided.
Linked Issues check ✅ Passed The implementation fulfills all core objectives from #14687: POST to embeddings endpoint, optional Authorization header, OpenAI-compatible format, [][]float64 output, context timeout, and config update.
Out of Scope Changes check ✅ Passed All changes are within scope: two files modified (vllm.json config and vllm.go implementation) with no factory, interface, or public API changes as required.
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.

@JinHai-CN

Copy link
Copy Markdown
Member

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

pandadev66 added 2 commits May 9, 2026 13:30
The EmbeddingConfig type added a Dimension field in infiniflow#14735 so
callers can request a specific output dimension on providers
that support it.

Pass dimensions through to the vLLM /v1/embeddings request
when embeddingConfig is non-nil and Dimension is greater than
zero, matching the pattern the merged ZhipuAI Encode now uses.
@pandadev66

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN, thanks for the heads up. Updated in 30609a5 to honor embeddingConfig.Dimension following the pattern in #14735.

@JinHai-CN

Copy link
Copy Markdown
Member

@pandadev66 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     |
+-----------+-------+

@pandadev66

pandadev66 commented May 9, 2026 •

Copy link
Copy Markdown
Contributor Author

@pandadev66 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     |
+-----------+-------+

Hi @JinHai-CN
Sharing my test output

RAGFlow(user)> embed text 'what is rag' 'who are you' with '<intfloat/e5-small-v2>@test@vllm' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 16        | 0     |
| 16        | 1     |
+-----------+-------+

@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 02:56
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 02:56
@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 (330257b) to head (30609a5).
⚠️ Report is 21 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14688   +/-   ##
=======================================
  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.

@JinHai-CN
JinHai-CN merged commit fa53b93 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
JinHai-CN pushed a commit that referenced this pull request May 15, 2026
### What problem does this PR solve?

Closes #14878.

`VllmModel.Rerank()` in
[internal/entity/models/vllm.go:551](internal/entity/models/vllm.go#L551)
is currently a stub returning `nil, fmt.Errorf("%s, Rerank not
implemented", z.Name())`, and
[conf/models/vllm.json](conf/models/vllm.json) is missing a `rerank`
entry in `url_suffix`. Chat (long-standing) and embeddings (#14688)
already work, so rerank is the last missing leg of the retrieval
pipeline for operators running everything on a single self-hosted vLLM
server — today they have to point rerank at a different provider, which
defeats the point of a fully local deployment.

Upstream vLLM has supported a Jina/Cohere-compatible `POST /v1/rerank`
endpoint since v0.7
([vllm-project/vllm#12376](vllm-project/vllm#12376)).
The request/response shape is essentially identical to the NVIDIA driver
landed in #14778, so this PR mirrors that structure with two
vLLM-specific adjustments.

This PR replaces the stub with a real implementation against vLLM's
`/v1/rerank`:

- `POST {baseURL}/rerank`
- Request body: `{"model": "<modelName>", "query": "<query>",
"documents": [...], "top_n": <int>}` — documents are a flat `[]string`,
**not** wrapped as `{text: "..."}` like NVIDIA's `/ranking`.
- Response body: `{"results": [{"index": int, "relevance_score": float},
...]}` (Jina-compatible; the optional `document` field is ignored since
callers reconstruct text via `Index`).
- `Authorization: Bearer <ApiKey>` is set **only when `APIConfig.ApiKey`
is non-empty**, matching the existing `Embed`/`ListModels` behaviour in
this file. vLLM is a local driver and can be deployed without an API
key.

The return shape matches the existing `*RerankResponse` contract used by
the NVIDIA ([nvidia.go:461](internal/entity/models/nvidia.go#L461)),
Aliyun ([aliyun.go:507](internal/entity/models/aliyun.go#L507)), and
ZhipuAI ([zhipu-ai.go:554](internal/entity/models/zhipu-ai.go#L554))
drivers, i.e. `Data []RerankResult` carrying `{Index, RelevanceScore}`
in the API's ranking order. Callers that need original-input order sort
by `Index`.

Behaviour requirements from the issue, all covered:

1. Empty `documents` → returns `&RerankResponse{}` without an HTTP call.
2. Missing `modelName` → `"model name is required"` validation error.
3. `rerankConfig.TopN` honored when `0 < TopN < len(documents)`;
otherwise `top_n` defaults to `len(documents)` so callers get a score
per input.
4. Non-200 responses return an error including upstream status and body
(`"vLLM rerank API error: <status>, body: <body>"`).
5. Response `index` values are bounds-checked against `len(documents)`.

**Scope:**

- [internal/entity/models/vllm.go](internal/entity/models/vllm.go) —
replaces the `Rerank` stub at line 551 with a real implementation; adds
`vllmRerankRequest`/`vllmRerankResponse` types for the slim subset of
the payload we need. Region/baseURL resolution, 30s context timeout,
conditional bearer header, and error wrapping all follow the existing
patterns in this file.
- [conf/models/vllm.json](conf/models/vllm.json) — adds `"rerank":
"rerank"` to `url_suffix`, joined to the operator-configured vLLM base
URL the same way the NVIDIA driver joins at
[nvidia.go:485](internal/entity/models/nvidia.go#L485).
-
[internal/entity/models/vllm_rerank_test.go](internal/entity/models/vllm_rerank_test.go)
— adds 7 `httptest`-backed tests mirroring `nvidia_rerank_test.go`:
happy path (out-of-order ranking → Index preservation), `top_n` clamp to
`RerankConfig.TopN`, empty-documents short-circuit, missing-model-name
validation, HTTP error propagation, out-of-range index rejection, and a
vLLM-specific `TestVllmRerankWithoutAPIKey` locking in the optional-auth
behaviour that distinguishes this driver from NVIDIA.

**Out of scope:** no interface change, no DDL, no frontend change. Chat,
embeddings, and balance paths are untouched. No new user-facing docs
required beyond the existing rerank model setup page — vLLM joins the
list of providers whose rerank model can be selected once `/v1/rerank`
is exposed by the server.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
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 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 vLLM Go driver

2 participants