Repository navigation
Go: implement Embed in Xinference driver - #14932
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughImplements Xinference embeddings: adds ChangesXinference Embed Method
Sequence Diagram(s)sequenceDiagram
participant Caller
participant EmbedMethod as XinferenceModel.Embed
participant HTTPClient
participant XinferenceAPI as Xinference /v1/embeddings
participant Parser as Response parser
Caller->>EmbedMethod: Call Embed(modelName, texts, apiConfig, embeddingConfig)
EmbedMethod->>EmbedMethod: Validate inputs and modelName
EmbedMethod->>HTTPClient: POST /v1/embeddings {model, input, dimensions?}
HTTPClient->>XinferenceAPI: Forward request (Authorization? Bearer <key>)
XinferenceAPI-->>HTTPClient: JSON {data:[{index, embedding},...]}
HTTPClient->>Parser: Return JSON payload
Parser->>Parser: Validate indices (present, in-range, unique, complete)
Parser-->>EmbedMethod: []EmbeddingData ordered by index
EmbedMethod-->>Caller: Return embeddings or error
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
Haruko386
left a comment
There was a problem hiding this comment.
Hi, @RenzoMXD. I can't find Aliyun Balance API Docs
Let me know if you find it.
72d5a80 to
9b2341b
Compare
|
Heads-up @Haruko386 — I've repurposed this PR after our earlier exchange. I tried to find authoritative DashScope documentation for the The new scope:
Title, body, and diff are all updated. When you have a moment, would you mind taking a fresh look? Your prior CHANGES_REQUESTED was on the now-removed Aliyun code path and is no longer applicable. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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.
Inline comments:
In `@internal/entity/models/xinference_test.go`:
- Around line 301-313: The test TestXinferenceEmbedHappyPathAndOmitsEmptyAuth
currently never checks the HTTP request headers; update the server handler
created by newXinferenceEmbedServer in that test to assert the Authorization
header is absent/empty (e.g., inspect the incoming *http.Request r inside the
handler and verify r.Header.Get("Authorization") == "" or that
r.Header["Authorization"] is nil/empty) before writing the mock response; keep
all other assertions (model, input, response ordering) intact.
In `@internal/entity/models/xinference.go`:
- Around line 387-390: The Data item struct currently allows missing fields to
silently decode (Index becomes 0 and Embedding can be nil); change the Data
element types to use pointers for presence detection (e.g., Index *int and
Embedding *[]float64) and after unmarshalling iterate over the slice and return
a validation error if any item has Index == nil or Embedding == nil or
len(*Embedding) == 0; apply the same change/validation to the other identical
Data slice definition referenced around lines 469-477 so missing index/embedding
are caught explicitly rather than treated as defaults.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 62f6df98-90ed-42a7-98b7-89e818eadf81
📒 Files selected for processing (3)
conf/models/xinference.jsoninternal/entity/models/xinference.gointernal/entity/models/xinference_test.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/xinference.json
530cde6 to
7d9b976
Compare
Haruko386
left a comment
There was a problem hiding this comment.
LGTM, thx for your contribution
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14932 +/- ##
==========================================
- Coverage 94.53% 93.12% -1.41%
==========================================
Files 10 10
Lines 713 713
Branches 116 116
==========================================
- Hits 674 664 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Replaces the "no such method" stub on XinferenceModel.Embed with a real implementation against Xinference's OpenAI-compatible /v1/embeddings endpoint, and adds the embedding URL suffix to conf/models/xinference.json. The driver: - Reuses normalizeXinferenceBaseURL + baseURLForRegion so both http://127.0.0.1:9997 and http://127.0.0.1:9997/v1 resolve to the same /v1/embeddings target. - Reuses setXinferenceAuth so no-auth deployments don't send an Authorization header while auth-enabled deployments still receive Bearer <api_key>, matching the Xinference chat path. - Sends the OpenAI-compatible request body (model + input), forwards EmbeddingConfig.Dimension as "dimensions" when > 0 for models that support truncated output vectors. - Mirrors the Python XinferenceEmbed class at rag/llm/embedding_model.py for payload shape (data[*].index + data[*].embedding). - Validates response indices: duplicate, missing, or out-of-range data[*].index values fail with a clear error rather than silently producing misaligned vectors. - Returns []EmbeddingData in original input order (sorted by Index) rather than API arrival order, so downstream callers can index positionally without re-sorting. Tests added (httptest): happy path with out-of-order response, optional auth handling (no header when key empty, Bearer when set), base URL normalization with /v1 suffix, dimension forwarding, all three index error paths (duplicate, out-of-range, missing), empty-input short circuit, missing model name, missing embedding suffix, and HTTP error surfacing. All 22 Xinference tests pass.
05d0453 to
c1a78bb
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/xinference_test.go (1)
337-353: ⚡ Quick winAssert auth/method/path inside the handler and drop shared
gotAuthstate.At Line 338 and Line 351, this test relies on cross-goroutine shared state (
gotAuth). It’s cleaner and more robust to assert directly inside the handler (like the other embed tests), and validate method/path in the same place.Proposed change
func TestXinferenceEmbedSendsAuthWhenKeyConfigured(t *testing.T) { - gotAuth := "" srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotAuth = r.Header.Get("Authorization") + if r.Method != http.MethodPost { + t.Errorf("method=%s, want POST", r.Method) + } + if r.URL.Path != "/v1/embeddings" { + t.Errorf("path=%s, want /v1/embeddings", r.URL.Path) + } + if got := r.Header.Get("Authorization"); got != "Bearer sk-test" { + t.Errorf("Authorization=%q, want Bearer sk-test", got) + } _, _ = io.WriteString(w, `{"data":[{"index":0,"embedding":[0.1]}]}`) })) defer srv.Close() @@ if _, err := x.Embed(&model, []string{"x"}, &APIConfig{ApiKey: &key}, nil); err != nil { t.Fatalf("Embed: %v", err) } - if gotAuth != "Bearer sk-test" { - t.Errorf("Authorization=%q, want Bearer sk-test", gotAuth) - } }🤖 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/xinference_test.go` around lines 337 - 353, The test TestXinferenceEmbedSendsAuthWhenKeyConfigured currently uses shared gotAuth state across goroutines; modify the httptest server handler (the http.HandlerFunc passed to httptest.NewServer) to perform inline assertions: check r.Method and r.URL.Path are the expected values and assert r.Header.Get("Authorization") == "Bearer sk-test" directly inside the handler, remove the gotAuth variable and the external post-call assertion, and keep the rest of the test flow (calling x.Embed with APIConfig{ApiKey: &key}) unchanged so the handler owns all validation.
🤖 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/xinference_test.go`:
- Around line 337-353: The test TestXinferenceEmbedSendsAuthWhenKeyConfigured
currently uses shared gotAuth state across goroutines; modify the httptest
server handler (the http.HandlerFunc passed to httptest.NewServer) to perform
inline assertions: check r.Method and r.URL.Path are the expected values and
assert r.Header.Get("Authorization") == "Bearer sk-test" directly inside the
handler, remove the gotAuth variable and the external post-call assertion, and
keep the rest of the test flow (calling x.Embed with APIConfig{ApiKey: &key})
unchanged so the handler owns all validation.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c3cb7a17-29d2-44a1-ba82-e5a170bd4d82
📒 Files selected for processing (3)
conf/models/xinference.jsoninternal/entity/models/xinference.gointernal/entity/models/xinference_test.go
### What problem does this PR solve? Fixes #14816 The Xinference Go driver landed chat in #14938 and Embed is in review in #14932, but `Rerank` shipped as a stub that returns `"xinference, no such method"`. Tenants who launch a rerank model with `--model-type rerank` on their Xinference instance cannot route it through the Go API server. This PR fills the gap. Xinference exposes an OpenAI-compatible REST API. The rerank endpoint is at `POST <base>/v1/rerank` and accepts the Cohere-shaped body `{model, query, documents, top_n}`, returning `{results: [{index, relevance_score}]}` — the same wire shape used by the merged NVIDIA (#14778), Aliyun (#14676), Gitee (#14656), ZhipuAI (#14608), Novita (#15014), and LocalAI (#14813) Rerank implementations. Documented in [Xinference rerank docs](https://inference.readthedocs.io/en/v1.6.1/models/model_abilities/rerank.html); the [builtin rerank model catalog](https://inference.readthedocs.io/en/stable/models/builtin/rerank/) lists `bge-reranker-base`, `bge-reranker-large`, `bge-reranker-v2-m3`, and others.
Summary
"no such method"stub onXinferenceModel.Embed(internal/entity/models/xinference.go) with a real implementation against Xinference's OpenAI-compatible/v1/embeddingsendpoint."embedding": "v1/embeddings"URL suffix toconf/models/xinference.json.XinferenceEmbedclass inrag/llm/embedding_model.py:407for payload shape (OpenAI-compatiblemodel + input→data[*].index + data[*].embedding) and tolerates the same no-auth default Xinference deployments use. Authorization is only sent when a non-empty API key is configured, via the existingsetXinferenceAuthhelper.normalizeXinferenceBaseURL+baseURLForRegionhelpers so bothhttp://127.0.0.1:9997andhttp://127.0.0.1:9997/v1resolve to the same/v1/embeddingstarget without doubled/v1.data[*].indexvalues fail with a clear error rather than silently producing misaligned vectors.[]EmbeddingDatain original input order (placed byIndex) so downstream callers can index positionally without re-sorting.EmbeddingConfig.Dimensionasdimensionswhen> 0, matching the OpenAI cluster pattern.Closes #14810
Note on scope
This PR's branch previously contained an Aliyun balance attempt for #14671. After investigation (and a CHANGES_REQUESTED review from @Haruko386 asking for documentation we couldn't locate), I concluded the DashScope balance endpoint in that issue isn't publicly documented and pivoted the branch to a fully-documented sibling gap on the Xinference Go driver. The Aliyun work has been dropped — happy to revisit if upstream docs surface later.
Test plan
gofmt -l internal/entity/models/xinference{.go,_test.go}— cleango build ./internal/entity/models/...— succeedsgo test -vet=off -run TestXinference -v ./internal/entity/models/...— 22/22 pass (11 new Embed tests + 11 existing chat/list/factory tests)New tests cover
TestXinferenceEmbedHappyPathAndOmitsEmptyAuthIndex, noAuthorizationheader when API key emptyTestXinferenceEmbedSendsAuthWhenKeyConfiguredBearer <key>sent when API key setTestXinferenceEmbedNormalizesBaseURLWithV1Suffix/v1doesn't double-up to/v1/v1/embeddingsTestXinferenceEmbedForwardsDimensiondimensionsfield sent whenEmbeddingConfig.Dimension > 0TestXinferenceEmbedRejects{Duplicate,OutOfRange,Missing}IndexTestXinferenceEmbedEmptyTextsShortCircuitsTestXinferenceEmbedRequiresModelNameTestXinferenceEmbedSurfacesHTTPErrorXinference embeddings API errorTestXinferenceEmbedRejectsMissingEmbeddingSuffixURLSuffix.Embedding == ""→ clear errorReferences
rag/llm/embedding_model.py:407 (XinferenceEmbed)