Skip to content

Go: implement Encode (embeddings) in OpenAI driver - #14630

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
pandadev66:feat/go-openai-encode
May 10, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
pandadev66:feat/go-openai-encode

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The OpenAI Go driver landed in #14605 with chat, list models, and check connection. Encode was left as a stub that returns `not implemented`.

`conf/models/openai.json` already lists three embedding models out of the box:

  • text-embedding-ada-002
  • text-embedding-3-small
  • text-embedding-3-large

So a tenant who picked one of these in the Go layer could not actually run an embedding call. This PR fills the gap.

What this PR includes

  • `conf/models/openai.json`: add `"embedding": "embeddings"` under `url_suffix` so the driver can build the URL from config. This matches the `URLSuffix.Embedding` field used by other drivers (siliconflow, zhipu-ai).
  • `internal/entity/models/openai.go`: replace the Encode stub with a real implementation that POSTs to `/v1/embeddings`. Adds a small local response type `openaiEmbeddingResponse`.

No factory change. No interface change.

How the implementation works

  • Validate `apiConfig` and the API key, validate 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 OpenAI API accepts the `input` field as an array.
  • Parse `data[].embedding` and copy each slice into a `[][]float64` indexed by `data[].index` so the output order matches the input order even if the API returns items in a different order.
  • Handle both `float64` and `float32` element types, the way the SiliconFlow driver does.
  • An empty input slice returns `[][]float64{}` 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 nil, return a clear error so the caller does not silently use a zero vector.

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 (the go.mod minimum) returns exit 0.
  • The full method set on `OpenAIModel` still matches the `ModelDriver` interface.
  • Pattern parity with the existing SiliconFlow Encode implementation (`internal/entity/models/siliconflow.go`).

Closes #14629

The OpenAI Go driver landed in infiniflow#14605 with chat, list models, and
check connection. Encode was left as a stub. The conf/models/openai
.json file already lists three embedding models out of the box,
so a tenant who picked text-embedding-3-small or text-embedding-3-
large or text-embedding-ada-002 in the Go layer could not actually
run an embedding call.

This commit adds the real implementation.

Changes:

- conf/models/openai.json: add "embedding": "embeddings" under
  url_suffix so the driver can build the URL from config (matches
  the URLSuffix.Embedding field already used by other drivers
  such as siliconflow and zhipu-ai).
- internal/entity/models/openai.go: replace the Encode stub with
  a real implementation that POSTs to /v1/embeddings.

How the implementation works:

- Validate apiConfig and the API key, validate 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. This is the same pattern
  ChatWithMessages and ListModels already use in this file.
- Send all input texts in one request. The OpenAI API accepts
  the input field as an array.
- Parse the response into a small local type
  (openaiEmbeddingResponse) and copy each "embedding" slice into
  a [][]float64 indexed by the response's "index" field, so the
  output order matches the input order.
- Handle both float64 and float32 element types, the way the
  siliconflow driver does, in case the JSON decoder ever returns
  float32 values.
- An empty input slice returns an empty [][]float64 with no HTTP
  call.
- Non-200 responses propagate the upstream status line and body.
- Final pass checks that every input slot got a vector. If any
  slot is still nil, return a clear error so the caller does not
  silently use a zero vector.

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

coderabbitai Bot commented May 7, 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: 42897ead-ac75-4f63-9b17-ee536cc76ea0

📥 Commits

Reviewing files that changed from the base of the PR and between 1c23940 and 7fcdc72.

📒 Files selected for processing (1)
  • internal/entity/models/factory.go

📝 Walkthrough

Walkthrough

Adds OpenAI embeddings support: updates config with an embeddings URL suffix and implements OpenAIModel.Encode to call /v1/embeddings with validation, timeout, and indexed response parsing. Critical: ChatStreamlyWithSender contains stray numeric literals causing a compilation error.

Changes

OpenAI Embeddings Support

Layer / File(s) Summary
Configuration Contract
conf/models/openai.json
URL-suffix mapping extended to include "embedding": "embeddings" alongside existing chat and models endpoints.
Factory Wiring
internal/entity/models/factory.go
CreateModelDriver registers provider "openai" and returns NewOpenAIModel(baseURL, urlSuffix).
Embeddings Implementation
internal/entity/models/openai.go
Adds /v1/embeddings response parsing and implements OpenAIModel.Encode to validate model/API key/region, POST to /v1/embeddings with nonStreamCallTimeout, parse data[] by index, convert embedding vectors to [][]float64, and error if any input position is missing.
⚠️ Critical Issue
internal/entity/models/openai.go
ChatStreamlyWithSender tail is corrupted (stray numeric literals) causing compilation failure and broken stream termination.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Encode as OpenAI.Encode
    participant HTTPClient
    participant OpenAIAPI as /v1/embeddings
    Caller->>Encode: texts, model, apiKey, region
    Encode->>Encode: validate inputs
    Encode->>Encode: build request body
    Encode->>HTTPClient: POST with timeout context
    HTTPClient->>OpenAIAPI: send request
    OpenAIAPI-->>HTTPClient: HTTP 200 + response
    HTTPClient-->>Encode: response body
    Encode->>Encode: parse by index
    Encode->>Encode: convert to []float64
    Encode-->>Caller: [][]float64, error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#14605: Introduced the OpenAI driver structure and initial config that this PR extends with embeddings support.
  • infiniflow/ragflow#14437: Standardized Encode signatures across embedding drivers; relevant to this Encode implementation.
  • infiniflow/ragflow#14652: Modifies internal/entity/models/openai.go and overlaps on chat/encoding behavior.

Suggested labels

💞 feature, size:M

Suggested reviewers

  • Haruko386

Poem

🐰 I stitched embeddings, neat and spry,
I called /v1/embeddings with a sigh,
Vectors returned in ordered rows,
But a stream broke—those stray number bows,
Fix the tail, then watch RAGFlow fly!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: implementing the Encode method (embeddings) in the OpenAI driver.
Description check ✅ Passed The description follows the template, explains the problem and solution clearly, includes what the PR does and how it was tested.
Linked Issues check ✅ Passed The PR implementation meets all coding requirements from issue #14629: POST to /v1/embeddings, accepts model and input texts, returns ordered vectors, uses shared HTTP client with timeout, updates config, and maintains the interface.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing embeddings support: config update for URL suffix, Encode implementation, and factory recognition of 'openai' provider. No extraneous modifications detected.
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.

@pandadev66

Copy link
Copy Markdown
Contributor Author

Hi @Magicbook1108, gentle ping for review. This is the follow-up to #14605 promised in that PR's review thread. Scope is two files (one config, one driver), it follows the SiliconFlow Encode pattern, and it closes #14629. Thanks!

@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/openai.go (1)

410-415: ⚡ Quick win

Decode embeddings directly into []float64 to drop unreachable float32 branch and reduce allocations.

encoding/json always unmarshals JSON numbers into float64 when the target type is interface{}, making the case float32 arm at lines 496–497 unreachable dead code. Additionally, decoding into []interface{} boxes every element, adding unnecessary allocation overhead for large vectors (1536–3072 dimensions). Changing Embedding to []float64 allows json.Unmarshal to populate the slice directly and eliminates the type-switch loop entirely.

♻️ Proposed simplification
 type openaiEmbeddingResponse struct {
 	Data []struct {
-		Index     int           `json:"index"`
-		Embedding []interface{} `json:"embedding"`
+		Index     int       `json:"index"`
+		Embedding []float64 `json:"embedding"`
 	} `json:"data"`
 }
@@
 	embeddings := make([][]float64, len(texts))
 	for _, item := range parsed.Data {
 		if item.Index < 0 || item.Index >= len(texts) {
 			continue
 		}
-		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)
-			}
-		}
-		embeddings[item.Index] = vec
+		embeddings[item.Index] = 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/openai.go` around lines 410 - 415, The struct
openaiEmbeddingResponse should decode embedding values directly as []float64 to
avoid boxing and unreachable float32 handling: change the Embedding field type
from []interface{} to []float64 in openaiEmbeddingResponse and update any code
that iterates/assigns embedding values (the converter that previously
type-switched on interface{} and float32/float64) to treat elements as float64
directly, removing the float32 branch and the interface{} type assertions so
json.Unmarshal fills the slice without extra allocations.
🤖 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/openai.go`:
- Around line 410-415: The struct openaiEmbeddingResponse should decode
embedding values directly as []float64 to avoid boxing and unreachable float32
handling: change the Embedding field type from []interface{} to []float64 in
openaiEmbeddingResponse and update any code that iterates/assigns embedding
values (the converter that previously type-switched on interface{} and
float32/float64) to treat elements as float64 directly, removing the float32
branch and the interface{} type assertions so json.Unmarshal fills the slice
without extra allocations.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 30fe7ac9-8c91-4ef5-bece-f525ee29323e

📥 Commits

Reviewing files that changed from the base of the PR and between 0501134 and c6fa061.

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

@Haruko386 Haruko386 added the ci Continue Integration label May 8, 2026

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

Hi @pandadev66 , LGTM

I have reviewed the code changes, and there are no apparent issues with the code, thank you for you contribution.

However, to ensure everything works flawlessly in practice, could you please provide a snippet of your local test results in your future PR description or comments?

@codecov

codecov Bot commented May 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (048ec2f) to head (7fcdc72).

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

@pandadev66

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN
How are you? ❤️ This PR could be merged unless there is any other problem or improvement.
Appreciate

@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:08
The EmbeddingConfig type added a Dimension field in infiniflow#14735 so
callers can request a specific output dimension on providers
that support it (OpenAI text-embedding-3-* among them).

Pass dimensions through to the OpenAI /v1/embeddings request
when embeddingConfig is non-nil and Dimension is greater than
zero, matching the pattern the merged ZhipuAI Encode now uses.
@pandadev66
pandadev66 force-pushed the feat/go-openai-encode branch from 4109aba to 1c23940 Compare May 9, 2026 11:29
@pandadev66

Copy link
Copy Markdown
Contributor Author

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

Hi @JinHai-CN sharing output ❤️

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

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 OpenAI Go driver landed in infiniflow#14605 with chat, list models, and check
connection. Encode was left as a stub that returns \`not implemented\`.

\`conf/models/openai.json\` already lists three embedding models out of
the box:

- text-embedding-ada-002
- text-embedding-3-small
- text-embedding-3-large

So a tenant who picked one of these in the Go layer could not actually
run an embedding call. This PR fills the gap.

### What this PR includes

- \`conf/models/openai.json\`: add \`\"embedding\": \"embeddings\"\`
under \`url_suffix\` so the driver can build the URL from config. This
matches the \`URLSuffix.Embedding\` field used by other drivers
(siliconflow, zhipu-ai).
- \`internal/entity/models/openai.go\`: replace the Encode stub with a
real implementation that POSTs to \`/v1/embeddings\`. Adds a small local
response type \`openaiEmbeddingResponse\`.

No factory change. No interface change.

### How the implementation works

- Validate \`apiConfig\` and the API key, validate 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 OpenAI API accepts the
\`input\` field as an array.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\` so the output order matches the input order
even if the API returns items in a different order.
- Handle both \`float64\` and \`float32\` element types, the way the
SiliconFlow driver does.
- An empty input slice returns \`[][]float64{}\` 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 nil, return a clear error so the caller does not silently use a
zero vector.

### 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
(the go.mod minimum) returns exit 0.
- The full method set on \`OpenAIModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing SiliconFlow Encode implementation
(\`internal/entity/models/siliconflow.go\`).

Closes infiniflow#14629

---------

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: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 OpenAI Go driver

3 participants