Skip to content

Add Replicate chat provider - #14958

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
tmimmanuel:go/replicate-chat
May 19, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
tmimmanuel:go/replicate-chat

Conversation

@tmimmanuel

Copy link
Copy Markdown
Contributor

What

  • Add Replicate as a chat provider backed by the documented predictions API
  • Register Replicate in the Go model factory and provider config
  • Support non-streaming chat through sync predictions, polling fallback, streaming through urls.stream, model listing, and connection checks

Notes

  • Uses POST /v1/predictions with Replicate model identifiers in version, which supports official and community model identifiers
  • Maps RAGFlow messages into Replicate prompt-shaped inputs (prompt, optional system_prompt) and forwards common documented LLM inputs: max_new_tokens, temperature, top_p
  • Preserves whitespace in SSE output chunks and emits RAGFlow [DONE] at stream completion

Tests

  • go test -vet=off -run TestReplicate -count=1 ./internal/entity/models
  • go test -vet=off -count=1 ./internal/entity/models

Refs #14736

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 15, 2026
@coderabbitai

coderabbitai Bot commented May 15, 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: 159fc20b-bc8d-45c8-806b-103a4150ef8c

📥 Commits

Reviewing files that changed from the base of the PR and between 54c06a7 and 77ead11.

📒 Files selected for processing (2)
  • internal/entity/models/replicate.go
  • internal/entity/models/replicate_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/entity/models/replicate_test.go
  • internal/entity/models/replicate.go

📝 Walkthrough

Walkthrough

Adds Replicate as a new model provider: config and factory wiring, a ReplicateModel driver with HTTP prediction creation, polling and SSE streaming support, model discovery and stubbed unsupported methods, plus unit tests for request, polling, and streaming flows.

Changes

Replicate Model Provider Integration

Layer / File(s) Summary
Configuration and Factory Integration
conf/models/replicate.json, internal/entity/models/factory.go
Replicate configuration defines base URL and endpoint suffixes; CreateModelDriver routes "replicate" to NewReplicateModel.
Core Driver Structure and Initialization
internal/entity/models/replicate.go (lines 1–139)
ReplicateModel struct, HTTP client tuning, NewReplicateModel/NewInstance, Name(), and prediction endpoint selection (region/version vs owner/name).
Request / Response Utilities
internal/entity/models/replicate.go (lines 140–225)
Prompt/system-prompt construction from messages, input mapping (max_new_tokens/temperature/top_p), normalization of upstream output, and createPrediction POST with bearer auth and Prefer handling.
Non-streaming Chat and Polling
internal/entity/models/replicate.go (lines 226–341)
Prediction creation, getPrediction polling, waitForPrediction loop, and ChatWithMessages orchestration returning ChatResponse on succeeded status.
Streaming Chat with SSE
internal/entity/models/replicate.go (lines 343–514)
ChatStreamlyWithSender creates streaming predictions, reads SSE with Accept: text/event-stream, dispatches output/error/done events to sender, and falls back to polling when SSE URL is absent; appends [DONE].
Model Discovery and Unsupported Operations
internal/entity/models/replicate.go (lines 516–611)
ListModels queries /v1/models and returns owner/name; CheckConnection wraps it; other capabilities return "<driver name>, no such method" errors.
Comprehensive Test Coverage
internal/entity/models/replicate_test.go
Tests for Name(), factory routing, prompt serialization, prediction endpoint logic, ChatWithMessages happy path and polling, ChatStreamlyWithSender SSE parsing and dispatch, ListModels/CheckConnection, and unsupported methods errors.

Sequence Diagram

sequenceDiagram
  participant Client
  participant ReplicateAPI
  participant SSEStream
  Client->>ReplicateAPI: POST /v1/predictions (Authorization, stream=true?)
  ReplicateAPI->>SSEStream: open SSE (Accept: text/event-stream)
  SSEStream->>Client: events (output / error / done)
  ReplicateAPI->>Client: GET /v1/predictions/<id> (polling, non-stream)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped through configs, tests, and streams,
I stitched prompts into tidy little schemes,
I listened to events that gently hum,
Appended "[DONE]" when the last bits come,
A rabbit cheers: "Replicate's begun!"

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

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.
Description check ❓ Inconclusive The PR description covers the what, implementation details, and testing approach, but lacks explicit type of change selection from the required template. Check the 'Type of change' checkboxes in the description template (e.g., mark 'New Feature' as applicable) to fully comply with the repository's template requirements.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add Replicate chat provider' is clear, concise, and directly reflects the main objective of the PR—integrating Replicate as a new chat provider.
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.

@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: 3

🤖 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/replicate_test.go`:
- Around line 62-66: The handler goroutine in replicate_test.go is using
t.Fatalf inside the http.HandlerFunc after json.Unmarshal (the block reading
raw, body and checking err); replace that t.Fatalf call with t.Errorf so
failures inside the handler are reported to the test runner rather than
terminating only the handler goroutine—update the error call where
json.Unmarshal is checked (the anonymous handler closure using t) to use
t.Errorf with the same message and error details.
- Around line 176-180: In the HTTP handler goroutine (the http.HandlerFunc that
reads r.Body into raw, unmarshals into body via json.Unmarshal), replace
t.Fatalf("body: %v", err) with t.Errorf("body: %v", err) so the test failure is
reported correctly from the goroutine; keep the rest of the error handling flow
(e.g., return from the handler after reporting the error) so the handler stops
processing when json.Unmarshal fails.
- Around line 83-85: Add an inline comment in the replicateInputFromMessages
implementation explaining why the ChatConfig.Stop field is intentionally not
forwarded to the Replicate API: mention that Stop (and similar fields) are
selectively forwarded and Stop is omitted because Replicate's upstream behavior
is undefined/unsupported; update the comment near the logic that drops Stop in
replicate.go (the block referenced in lines 151-160) and add a matching
explanatory comment above the test assertion in replicate_test.go (the assertion
checking input["stop"] is nil) so future readers understand this is intentional.
🪄 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: a85131ac-ccaa-41c3-8061-e9ab8ae91749

📥 Commits

Reviewing files that changed from the base of the PR and between 09d4504 and 2e6eaaa.

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

@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 @tmimmanuel.
Please make sure you know what you're doing.

Comment thread conf/models/replicate.json Resolved
@tmimmanuel
tmimmanuel requested a review from Haruko386 May 19, 2026 01:05

@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 @tmimmanuel, I suggest these two changes.
It will be ok to merge after these

Comment thread internal/entity/models/replicate.go Resolved
Comment thread internal/entity/models/replicate.go Resolved

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

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

codecov Bot commented May 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (09d4504) to head (77ead11).
⚠️ Report is 27 commits behind head on main.

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

@JinHai-CN
JinHai-CN merged commit 4c9529e into infiniflow:main May 19, 2026
1 check passed
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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants