Skip to content

Go: implement Encode (embeddings) in LM Studio driver - #14694

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

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

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

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

Type of change

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

How was this tested?

Closes #14693

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.
Users who loaded local embedding models such as
nomic-embed-text-v1.5 or mxbai-embed-large-v1 in LM Studio
could not run an embedding call through the Go layer.

Changes:

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

How it 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 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 and vLLM 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#14693
@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), in-flight Ollama Encode (#14664), and in-flight vLLM Encode (#14688) all use, scope is two files (one config, one driver), and it closes #14693. 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: 7ecd64fb-2672-4dce-a227-95298e00abef

📥 Commits

Reviewing files that changed from the base of the PR and between c458bc9 and 2fc7dbd.

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

📝 Walkthrough

Walkthrough

Adds an embedding URL suffix to LM Studio config and implements (*LmStudioModel).Encode to POST to the embeddings endpoint with a 30s context timeout, optional bearer auth, response unmarshalling, strict index/type validation, and conversion to [][]float64.

Changes

LM Studio Embeddings Implementation

Layer / File(s) Summary
Configuration
conf/models/lmstudio.json
Adds url_suffix.embedding with value embeddings for the LM Studio embeddings endpoint.
Context Import
internal/entity/models/lmstudio.go
Adds context import to support per-call timeouts for Encode.
Response Types
internal/entity/models/lmstudio.go
Defines lmstudioEmbeddingResponse struct with data entries (index, embedding) to unmarshal the OpenAI-compatible embeddings response.
Encode — Request Build
internal/entity/models/lmstudio.go
Implements input validation, region/base-URL resolution with default fallback, constructs embeddings URL and request body (includes optional dimensions).
Encode — Request Execution
internal/entity/models/lmstudio.go
Creates a 30s context.WithTimeout, builds HTTP POST with Content-Type, conditionally sets Authorization: Bearer <key> only when API key is non-empty; sends request and reads response.
Parse, Validate & Convert
internal/entity/models/lmstudio.go
Unmarshals into lmstudioEmbeddingResponse, checks HTTP status and returned count, validates indices/types, converts values (float32/float64) into [][]float64, and returns the matrix.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Possibly related issues

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped to the code with nimble paws,
Replaced the stub with POSTs and timeout laws,
Optional bearer, indices aligned,
Vectors returned in order — neatly signed,
Now LM Studio hums and the embeddings applause.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: implementing the Encode method for embeddings in the LM Studio driver.
Description check ✅ Passed The description comprehensively covers the problem, implementation details, testing, and follows the template structure with all required sections completed.
Linked Issues check ✅ Passed The implementation addresses all requirements from #14693: Encode method now handles OpenAI-compatible embeddings endpoint, validates inputs, supports optional API keys, uses context timeout, and config includes embedding url_suffix.
Out of Scope Changes check ✅ Passed Changes are limited to the two intended files (lmstudio.json and lmstudio.go) and directly address the linked issue without introducing unrelated modifications.
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

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN, thanks for the heads up. Updated in 2fc7dbd 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 result

RAGFlow(user)> embed text 'what is rag' 'who are you' with '<text-embedding-bge-small-en-v1.5>@test@lmstudio' 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:57
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 02:57
@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 (2fc7dbd).
⚠️ Report is 26 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14694   +/-   ##
=======================================
  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 530edba into infiniflow:main May 11, 2026
2 of 3 checks passed
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 LM Studio Go driver

2 participants