Skip to content

Go: implement Embed in Xinference driver - #14932

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
ai-mountain:fix/14671-aliyun-balance
May 21, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
ai-mountain:fix/14671-aliyun-balance

Conversation

@ai-mountain

@ai-mountain ai-mountain commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Replaces the "no such method" stub on XinferenceModel.Embed (internal/entity/models/xinference.go) with a real implementation against Xinference's OpenAI-compatible /v1/embeddings endpoint.
  • Adds the "embedding": "v1/embeddings" URL suffix to conf/models/xinference.json.
  • Mirrors the Python XinferenceEmbed class in rag/llm/embedding_model.py:407 for payload shape (OpenAI-compatible model + 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 existing setXinferenceAuth helper.
  • Reuses the existing normalizeXinferenceBaseURL + baseURLForRegion helpers so both http://127.0.0.1:9997 and http://127.0.0.1:9997/v1 resolve to the same /v1/embeddings target without doubled /v1.
  • 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 (placed by Index) so downstream callers can index positionally without re-sorting.
  • Forwards EmbeddingConfig.Dimension as dimensions when > 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} — clean
  • go build ./internal/entity/models/... — succeeds
  • go 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

Test Verifies
TestXinferenceEmbedHappyPathAndOmitsEmptyAuth request method/path, model + input body, out-of-order response is reordered by Index, no Authorization header when API key empty
TestXinferenceEmbedSendsAuthWhenKeyConfigured Bearer <key> sent when API key set
TestXinferenceEmbedNormalizesBaseURLWithV1Suffix tenant URL ending in /v1 doesn't double-up to /v1/v1/embeddings
TestXinferenceEmbedForwardsDimension dimensions field sent when EmbeddingConfig.Dimension > 0
TestXinferenceEmbedRejects{Duplicate,OutOfRange,Missing}Index three index-validation error paths
TestXinferenceEmbedEmptyTextsShortCircuits no HTTP call for empty input
TestXinferenceEmbedRequiresModelName nil/empty model name → clear error
TestXinferenceEmbedSurfacesHTTPError non-200 → Xinference embeddings API error
TestXinferenceEmbedRejectsMissingEmbeddingSuffix misconfigured URLSuffix.Embedding == "" → clear error

References

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

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Implements Xinference embeddings: adds url_suffix.embedding, defines the embeddings response struct, implements XinferenceModel.Embed with request construction, response parsing and strict index validation, and adds comprehensive unit tests for happy and error paths.

Changes

Xinference Embed Method

Layer / File(s) Summary
Configuration and response type definition
conf/models/xinference.json, internal/entity/models/xinference.go
Adds url_suffix.embedding: "v1/embeddings" and an internal xinferenceEmbeddingResponse struct describing per-item index and embedding fields.
Embed method implementation
internal/entity/models/xinference.go
Implements XinferenceModel.Embed with input/model validation, URL construction from region + URLSuffix, POSTing {model,input} (forwards dimensions when >0), parsing data items, enforcing index presence/range/duplicate/completeness, and returning embeddings ordered to match inputs.
Test setup and happy-path helpers
internal/entity/models/xinference_test.go
Adds v1/embeddings to test URLSuffix and an /v1/embeddings httptest helper; tests request body handling, Authorization omission/inclusion, base URL normalization, and dimension forwarding.
Validation and error tests
internal/entity/models/xinference_test.go
Adds tests for duplicate/out-of-range/missing index detection, empty-input short-circuit, missing model name, upstream HTTP 500 mapping, rejection when embedding suffix is missing, and updates to unsupported-methods test.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • Haruko386

Poem

🐰 A rabbit hops through configs so fine,
Embedding vectors in a neat line,
Tests check indices one by one,
HTTP posts and parsing done,
Xinference Embed—now finally mine!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement Embed in Xinference driver' directly and concisely describes the main change: implementing the Embed method for the Xinference driver in Go, which is the primary focus of the PR across all three modified files.
Description check ✅ Passed The PR description is comprehensive and well-structured, including a detailed summary of changes, implementation details, test coverage table, and references. However, it lacks the required 'Type of change' checkbox section from the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

@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, @RenzoMXD. I can't find Aliyun Balance API Docs
Let me know if you find it.

@JinHai-CN JinHai-CN added the invalid This doesn't seem right label May 15, 2026
@ai-mountain
ai-mountain marked this pull request as draft May 15, 2026 16:16
@ai-mountain
ai-mountain force-pushed the fix/14671-aliyun-balance branch from 72d5a80 to 9b2341b Compare May 19, 2026 12:46
@ai-mountain ai-mountain changed the title fix: implement Aliyun balance query Go: implement Embed in Xinference driver May 19, 2026
@ai-mountain

Copy link
Copy Markdown
Contributor Author

Heads-up @Haruko386 — I've repurposed this PR after our earlier exchange.

I tried to find authoritative DashScope documentation for the /api/v1/recharge/recharge-balance/query endpoint cited in #14671 and couldn't (no help.aliyun.com page describes it, no other driver in the repo calls it). Rather than ship code against an endpoint neither of us can verify, I dropped the Aliyun balance work and pivoted this branch to a fully-documented sibling gap: implementing Embed for the Xinference Go driver (#14810).

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.

@ai-mountain
ai-mountain marked this pull request as ready for review May 19, 2026 13:19

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72d5a80 and 9b2341b.

📒 Files selected for processing (3)
  • conf/models/xinference.json
  • internal/entity/models/xinference.go
  • internal/entity/models/xinference_test.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/xinference.json

Comment thread internal/entity/models/xinference.go Resolved
@ai-mountain
ai-mountain requested a review from Haruko386 May 19, 2026 13:50
@ai-mountain
ai-mountain force-pushed the fix/14671-aliyun-balance branch from 530cde6 to 7d9b976 Compare May 19, 2026 14:56
@Haruko386 Haruko386 added ci Continue Integration and removed invalid This doesn't seem right labels May 20, 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.

LGTM, thx for your contribution

@codecov

codecov Bot commented May 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (dc01e0e) to head (d15ba51).
⚠️ Report is 3 commits behind head on main.

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

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.
@ai-mountain
ai-mountain force-pushed the fix/14671-aliyun-balance branch from 05d0453 to c1a78bb Compare May 20, 2026 12:33

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

337-353: ⚡ Quick win

Assert auth/method/path inside the handler and drop shared gotAuth state.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d9b976 and c1a78bb.

📒 Files selected for processing (3)
  • conf/models/xinference.json
  • internal/entity/models/xinference.go
  • internal/entity/models/xinference_test.go

JinHai-CN pushed a commit that referenced this pull request May 21, 2026
### 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.
@JinHai-CN
JinHai-CN merged commit 394cd5d into infiniflow:main May 21, 2026
1 check passed
@ai-mountain
ai-mountain deleted the fix/14671-aliyun-balance branch May 21, 2026 13:21
@coderabbitai coderabbitai Bot mentioned this pull request Jun 3, 2026
6 tasks done
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 embeddings in the Xinference Go driver

3 participants