Repository navigation
Go: implement Encode (embeddings) in OpenAI driver - #14630
Conversation
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
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds 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. ChangesOpenAI Embeddings Support
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ 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. Comment |
|
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! |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/openai.go (1)
410-415: ⚡ Quick winDecode embeddings directly into
[]float64to drop unreachable float32 branch and reduce allocations.
encoding/jsonalways unmarshals JSON numbers intofloat64when the target type isinterface{}, making thecase float32arm at lines 496–497 unreachable dead code. Additionally, decoding into[]interface{}boxes every element, adding unnecessary allocation overhead for large vectors (1536–3072 dimensions). ChangingEmbeddingto[]float64allowsjson.Unmarshalto 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
📒 Files selected for processing (2)
conf/models/openai.jsoninternal/entity/models/openai.go
Haruko386
left a comment
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Hi @JinHai-CN |
|
@pandadev66 Encode interface is updated, would you please update your implementation accordingly? please refer to #14735 |
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.
4109aba to
1c23940
Compare
|
Hi @JinHai-CN, thanks for the heads up. Updated in 1c23940 to honor embeddingConfig.Dimension following the pattern in #14735. |
|
@pandadev66 Refer to the CLI usage in #14736, would you please provide the CLI embedding test result as below? |
|
Hi @JinHai-CN sharing output ❤️ |
### 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]>
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:
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
No factory change. No interface change.
How the implementation works
Type of change
How was this tested?
Closes #14629