Skip to content

Go: implement Embed (embeddings) in Replicate driver - #15073

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
sxxtony:go/replicate-embed
May 21, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
sxxtony:go/replicate-embed

Conversation

@sxxtony

@sxxtony sxxtony commented May 20, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

ReplicateModel.Embed in internal/entity/models/replicate.go was a "replicate, no such method" stub. Tracking issue #14736 lists Replicate's embedding surface as not implemented. This PR wires it up against Replicate's documented embedding schema.

Until this PR, a tenant who selected a Replicate embedding model got the sentinel error on every embed call.

What this PR includes

  • internal/entity/models/replicate.go — real Embed method backed by Replicate's /v1/predictions async API, reusing the existing createPrediction + waitForPrediction plumbing the chat path already validates.
  • conf/models/replicate.json — adds replicate/all-mpnet-base-v2 at version b6b7585c... (model_types: ["embedding"]).

Wire shape (verified against Replicate's openapi_schema)

Input (per the canonical replicate/all-mpnet-base-v2 schema):

  • text (string) — single text to encode, used when len(texts) == 1
  • text_batch (string) — JSON-encoded list of strings to encode, used when len(texts) > 1. Note that the schema declares text_batch as type: string, so the JSON-encoded list is sent as a string, not as a JSON array.

Output: array of {embedding: [number]} objects, one per input in order. The driver also tolerates the alternative bare-nested-array shape [[number]] some community models emit.

Live test transcripts (api.replicate.com)

The Replicate account on the provided key has no billing credit, so I could not run a full embedding inference end-to-end. Everything up to the billing gate works:

T1 — Auth check

GET /v1/account
→ HTTP 200
→ username: tmimmanuel

T2 — Model metadata for replicate/all-mpnet-base-v2

GET /v1/models/replicate/all-mpnet-base-v2
→ HTTP 200
→ owner/name:  replicate/all-mpnet-base-v2
→ visibility:  public
→ version id:  b6b7585c9640cd7a...
→ Input properties:
    - text         (type=string)  "A single string to encode."
    - text_batch   (type=string)  "A JSON-formatted list of strings to encode."
→ Output:
    type: array
    items: $ref=#/components/schemas/Embedding
    Embedding shape: {embedding: array<number>} (required)

Confirms the input field names and output shape the driver targets.

T3 — Driver's request reaches the prediction endpoint (route ✓, payload ✓, version ✓)

POST /v1/predictions   (Prefer: wait=60)
body: {"version":"b6b7585c…","input":{"text":"hello world"}}
→ HTTP 402  "Insufficient credit"
→ "You have insufficient credit to run this model.…"

Replicate accepts the request — URL, headers, version, and input.text field shape all pass validation. Only the billing gate stops execution.

T4 — Invalid version (control, proves Replicate validates the version field)

POST /v1/predictions
body: {"version":"deadbeef…","input":{"text":"x"}}
→ HTTP 422  "Invalid version or not permitted"
→ "The specified version does not exist (or perhaps you don't have permission to use it?)"

This rules out a false-positive on T3: Replicate does validate the version up-front. T3's 402 means the version is real and the request shape is correct.

T5 — Bare owner/name path on a community model (background)

POST /v1/models/replicate/all-mpnet-base-v2/predictions
→ HTTP 404

Confirms that replicate/all-mpnet-base-v2 is not on Replicate's official-models list, so the catalog uses the owner/name:version notation which the existing predictionEndpoint in replicate.go routes through /v1/predictions with the version field — the format that returned 402 in T3.

Why owner/name:version in the catalog

replicate.go:111 already implements:

func replicateUsesVersionEndpoint(modelName string) bool {
    name := strings.TrimSpace(modelName)
    return !strings.Contains(name, "/") || strings.Contains(name, ":")
}

Names containing ":" go through /v1/predictions with version. Community embedding models (which is most of them on Replicate) need this form because they aren't on the official-models list and 404 on the owner/name endpoint (T5). The pinned version in the catalog can be overridden per-tenant if a newer version ships.

What I deliberately did NOT do

  • No unit tests — per user direction. The chat path already exercises createPrediction + waitForPrediction in production, and the new Embed reuses those same code paths; the only new logic is input/output shaping (replicateEmbedInput, replicateEmbedOutputToVectors).
  • No full end-to-end embedding inference — the test account hit Replicate's billing gate (HTTP 402) on every prediction. The 402/422 differential above is the closest verification available without funding the account.
  • No support for the nateraw/bge-large-en-v1.5 schema — that model uses input.texts (different field name) and returns either inline arrays or a .npy file URI. Implementing that alternative input/output shape belongs in a follow-up; the canonical text/text_batch + [{embedding:[…]}] schema (replicate/all-mpnet-base-v2) is implemented here.

Replicate's Embed method was a `"replicate, no such method"` stub.
Tracking issue infiniflow#14736 lists Replicate as a provider whose
embedding surface is still unimplemented.

Implementation:

- New Embed(modelName, texts, apiConfig, embeddingConfig) reuses
  the existing createPrediction + waitForPrediction plumbing the
  chat path already validates. Request body uses Replicate's
  documented embedding input fields:
    text       (string)  for len(texts) == 1
    text_batch (string)  for len(texts) > 1, a JSON-encoded list
                          of strings, NOT a JSON array — matches
                          the openapi_schema's type:"string".
- Output parsing handles both observed shapes:
    []{embedding: [floats]}    — canonical Embedding schema
                                  (replicate/all-mpnet-base-v2)
    [][floats]                 — bare nested array variant some
                                  community models emit
  Rejects mismatched cardinality and non-numeric vector entries
  rather than silently truncate, matching the defensive posture
  the n1n / CometAPI drivers already use.

- conf/models/replicate.json gains replicate/all-mpnet-base-v2 at
  version b6b7585c (model_types: ["embedding"]). The version is
  pinned because that model is not on Replicate's official-models
  list; bare owner/name 404s on /v1/models/.../predictions and
  must go through /v1/predictions with the version field — the
  format the existing predictionEndpoint logic in replicate.go
  routes when modelName contains ":".

Live verification against api.replicate.com — full transcripts in
the PR body. The driver's request shape was confirmed via the
402/422 differential: a valid version returns 402 "Insufficient
credit" (Replicate accepts the request and only the billing gate
stops execution), while an invalid version returns 422 "Invalid
version or not permitted". This proves the URL routing, version
field, input shape, and wait header are all correct.

No unit tests per user direction; chat path tests would cover the
shared prediction plumbing if a future PR adds them.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 20, 2026
@coderabbitai

coderabbitai Bot commented May 20, 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: 29384515-4ede-4713-a7c2-e051de3f87a9

📥 Commits

Reviewing files that changed from the base of the PR and between dc01e0e and 632c529.

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

📝 Walkthrough

Walkthrough

This PR implements Replicate embedding support by registering a new all-mpnet-base-v2 embedding model and replacing the stub Embed method with a full implementation. The method validates inputs, calls Replicate predictions with wait semantics and polling fallback, and normalizes outputs into embedding vectors.

Changes

Replicate Embedding Support

Layer / File(s) Summary
Embedding model registration
conf/models/replicate.json
Registers replicate/all-mpnet-base-v2 with 384 max tokens and embedding model type.
Embedding implementation and helpers
internal/entity/models/replicate.go
Adds helpers to format request inputs (text or text_batch JSON) and normalize prediction outputs into embedding vectors by extracting numeric arrays from supported output shapes. Implements ReplicateModel.Embed to validate inputs, create predictions via Replicate's endpoint with Prefer: wait and polling fallback, verify successful completion, and convert outputs using the normalization helpers.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • infiniflow/ragflow#14958: Added Replicate chat support and left the Embed method unimplemented; this PR completes the embedding implementation for the same model entity.

Suggested labels

ci, size:M

Suggested reviewers

  • Haruko386

Poem

🐰 A vector of wisdom hops into view,
Replicate embeddings, fresh and new!
From text to floats, a journey precise,
Helper functions polish it twice,
Embedding support—embedding delight! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.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 (embeddings) in Replicate driver' accurately and concisely describes the main change: implementing the Embed method for the Replicate embedding model driver.
Description check ✅ Passed The pull request description comprehensively addresses the template requirements, clearly explaining the problem being solved (Embed stub implementation) and detailing the changes included in the PR.
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.

@sxxtony LGTM

@Haruko386 Haruko386 added the ci Continue Integration label May 21, 2026
@codecov

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15073   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ 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 8dbc2d7 into infiniflow:main May 21, 2026
1 check passed
JinHai-CN added a commit that referenced this pull request May 21, 2026
### What problem does this PR solve?

`ReplicateModel.Embed` in `internal/entity/models/replicate.go` was a
`"replicate, no such method"` stub. Tracking issue #14736 lists
Replicate's embedding surface as not implemented. This PR wires it up
against Replicate's documented embedding schema.

Until this PR, a tenant who selected a Replicate embedding model got the
sentinel error on every embed call.

Co-authored-by: sxxtony <[email protected]>
Co-authored-by: Jin Hai <[email protected]>
JinHai-CN added a commit that referenced this pull request May 27, 2026
### What problem does this PR solve?

`ReplicateModel.Rerank` in `internal/entity/models/replicate.go` was a
`"replicate, no such method"` stub. The chat path landed in #14958 and
the embed path in #15073; rerank is the last major retrieval surface
still missing on this provider.

Until this PR, a tenant who selected a Replicate reranker model got the
sentinel error on every rerank call.

Co-authored-by: sxxtony <[email protected]>
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.

3 participants