Skip to content

Go: implement Embed (embeddings) in Upstage driver - #14819

Merged
JinHai-CN merged 12 commits into
infiniflow:mainfrom
tmimmanuel:go/upstage-embed
May 12, 2026
Merged

JinHai-CN merged 12 commits into
infiniflow:mainfrom
tmimmanuel:go/upstage-embed

Conversation

@tmimmanuel

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The Upstage Go driver landed in #14817 with chat, list models, and check connection. Embed was left as a stub that returns "not implemented". This PR fills the gap.

Upstage exposes an OpenAI-compatible embeddings endpoint at https://api.upstage.ai/v1/solar/embeddings via the solar-embedding-1-large family (solar-embedding-1-large-query for queries, solar-embedding-1-large-passage for passages), and the Python side has had UpstageEmbed(OpenAIEmbed) in rag/llm/embedding_model.py for a long time targeting this same path. The existing conf/models/upstage.json did not list any embedding model out of the box, so a tenant who wanted to use Upstage end to end could not run an embedding call. This PR fills the gap.

What this PR includes

  • conf/models/upstage.json: add "embedding": "embeddings" under url_suffix so the driver can build the URL from config (matches the URLSuffix.Embedding field already used by openai, mistral, siliconflow, zhipu-ai), and add solar-embedding-1-large-query and solar-embedding-1-large-passage entries under models.
  • internal/entity/models/upstage.go: replace the Embed stub with a real implementation that POSTs to /v1/solar/embeddings. Adds local response types upstageEmbeddingData and upstageEmbeddingResponse.

No factory change. No interface change.

How the implementation works

  • Validate apiConfig, the API key, and 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 Upstage API accepts the input field as an array.
  • Parse data[*].embedding and copy each slice into a []EmbeddingData indexed by data[*].index so the output order matches the input order even if the API returns items in a different order.
  • An empty input slice returns []EmbeddingData{} 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 empty, return a clear error so the caller does not silently use a zero vector.

Note on stacking

This PR builds on #14817 (the Upstage driver). Until #14817 merges, this PR's diff on GitHub will include both that PR's commits and this one. After #14817 lands on main, GitHub will auto-reduce this PR to only the Embed changes (one commit, ~119 line diff in upstage.go plus ~15 lines in upstage.json).

Type of change

  • New Feature (non-breaking change which adds functionality)

How was this tested?

  • go build ./internal/entity/models/... returns exit 0 on go 1.25 (the go.mod minimum).
  • The full method set on UpstageModel still matches the ModelDriver interface.
  • Pattern parity with the existing Mistral Embed (internal/entity/models/mistral.go) and OpenAI Embed (internal/entity/models/openai.go) implementations.

Closes #14818
Depends on #14817
Tracking: #14736

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

coderabbitai Bot commented May 12, 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

Adds Upstage (Solar) provider support: provider config (conf/models/upstage.json), factory registration for "upstage", and an UpstageModel driver implementing chat (streaming and non-streaming), embeddings, model listing, and connectivity checks, plus unit tests.

Changes

Upstage Provider Integration

Layer / File(s) Summary
Configuration and factory registration
conf/models/upstage.json, internal/entity/models/factory.go
Adds Upstage provider configuration (base URL, URL suffixes for chat/models/embedding) and registers the "upstage" provider in the factory.
UpstageModel imports and initialization
internal/entity/models/upstage.go
Adds package imports, UpstageModel type, NewUpstageModel constructor (cloned/tuned transport), NewInstance, Name, and baseURLForRegion helper.
Chat operations (non-streaming)
internal/entity/models/upstage.go (ChatWithMessages)
Implements non-streaming chat: validates API key/messages, selects region, posts stream=false, parses JSON response, extracts first choice content and optional message.reasoning into ChatResponse.ReasonContent.
Chat operations (streaming)
internal/entity/models/upstage.go (ChatStreamlyWithSender)
Implements streaming chat: posts stream=true, parses SSE data: events with enlarged scanner buffer, emits delta.content fragments via sender callback, enforces terminal signaling, and emits final "[DONE]".
Embedding implementation
internal/entity/models/upstage.go (Embed)
Adds embedding response structs and Embed: validates API key/model/texts, POSTs to embeddings endpoint, parses returned vectors, reorders by returned index, and fails on duplicate or out-of-range indices.
Model discovery and unsupported operations
internal/entity/models/upstage.go (ListModels, CheckConnection, Balance, Rerank)
Implements ListModels (GET models endpoint, extract data[].id), CheckConnection (delegates to ListModels), and stubs Balance/Rerank returning "no such method".
Unit tests: chat & embeddings
internal/entity/models/upstage_test.go
Adds test helper and tests verifying reasoning_effort propagation (stream & non-stream), reasoning extraction/absence handling, request body shape, and embedding duplicate/out-of-range/reorder behaviors.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • #14816: Implements the Go Upstage model driver including embeddings and factory/config changes — directly related to this PR's objectives.

Possibly related PRs

  • infiniflow/ragflow#14664: Adds a new model provider implementation and factory registration similar to this change.
  • infiniflow/ragflow#14605: Adds a provider driver with chat/embedding patterns and factory registration — related structure and intent.
  • infiniflow/ragflow#14630: Adds provider-specific embeddings support and related url_suffix/config changes.

Suggested reviewers

  • Haruko386

Poem

🐇 I hopped into Upstage's glow,

payloads packed in tidy row,
streams that murmur chunk by chunk,
embeddings lined and tests that thunk,
a rabbit cheers — the driver grows!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.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 accurately describes the main feature added in this PR: implementing the Embed method for embeddings in the Upstage driver.
Description check ✅ Passed The PR description comprehensively covers the problem, solution, implementation details, and testing approach, matching the required template structure with 'What problem' and 'Type of change' sections.
Linked Issues check ✅ Passed The PR fully implements all coding requirements from linked issue #14818: Embed method implementation, embeddings URL suffix in config, embedding model entries, timeout handling, and maintains interface compatibility.
Out of Scope Changes check ✅ Passed All changes are directly aligned with the linked issue #14818 objectives. The PR adds the Embed implementation, configuration updates, and supporting tests without introducing unrelated modifications.

✏️ 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: 1

🤖 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 `@conf/models/upstage.json`:
- Around line 1-49: The Upstage config has several mismatches with the official
API: update url.default from "https://api.upstage.ai/v1/solar" to
"https://api.upstage.ai/v1"; change the two embedding model entries
"solar-embedding-1-large-query" and "solar-embedding-1-large-passage" max_tokens
from 4000 to 2000; rename/adjust chat model entries so they match official names
(replace "solar-pro-2" and "solar-pro" with "solar-pro3" and "solar-pro2" and
rename "solar-mini-chat" to "solar-mini", and add a "solar-pro3" model object if
missing); and remove or disable the "models" entry in url_suffix since the
/v1/models endpoint is not documented. Locate these fields by the keys
url.default, url_suffix.models, and the models array entries (name, max_tokens)
to apply the changes.
🪄 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: de319818-a92d-440d-852c-e6032c224fe5

📥 Commits

Reviewing files that changed from the base of the PR and between 2f2d156 and 9e85070.

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

Comment thread conf/models/upstage.json Resolved
CodeRabbit review on the stacked Embed PR flagged that the config did not
match the current Upstage API. Live probing against api.upstage.ai with
the documented endpoints confirms:

- Base URL is https://api.upstage.ai/v1, not /v1/solar. Both paths still
  serve traffic but /v1/models returns the full canonical list (21 ids
  including embeddings) while /v1/solar/models returns only 11 chat ids.
- The shipped chat models solar-pro-2 / solar-pro / solar-mini-chat do
  not exist upstream. The current names are solar-pro3, solar-pro2,
  solar-pro, and solar-mini.

Update conf/models/upstage.json and the driver doc-comment accordingly.
The /v1/models endpoint is supported (one of CodeRabbit's claims was
wrong on that point), so url_suffix.models stays.
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

CodeRabbit review applied + live integration test

CodeRabbit's review flagged four issues. After probing the live Upstage API and applying the legitimate ones:

Fixes applied

Claim Verdict Where fixed
Base URL should be /v1, not /v1/solar ✅ Valid PR #14817 commit d2a865f
Chat model names (solar-pro-2, solar-pro, solar-mini-chat) wrong ✅ Valid PR #14817 commit d2a865f
Embed max_tokens 4000 → 2000 ✅ Valid (docs) This PR, commit 26699a5
Remove url_suffix.models (/v1/models "not documented") ❌ Rejected — /v1/models returned HTTP 200 with 21 entries when probed n/a

Live integration test

Same TestUpstageSmoke as PR #14817, run against go/upstage-embed head (rebased on top of the fixed PR #14817). This branch's commit ships the real Embed implementation, so the test reaches the embed assertions:

=== RUN   TestUpstageSmoke
    upstage_smoke_test.go:32: [OK] driver.Name() = "upstage"
    upstage_smoke_test.go:37: [OK] CheckConnection
    upstage_smoke_test.go:43: [OK] ListModels returned 21 ids; first 5: [solar-mini solar-mini-250422 solar-pro solar-pro-250422 solar-pro2]
    upstage_smoke_test.go:58: [OK] model "solar-pro3" present upstream
    upstage_smoke_test.go:58: [OK] model "solar-pro2" present upstream
    upstage_smoke_test.go:58: [OK] model "solar-pro" present upstream
    upstage_smoke_test.go:58: [OK] model "solar-mini" present upstream
    upstage_smoke_test.go:58: [OK] model "solar-embedding-1-large-query" present upstream
    upstage_smoke_test.go:58: [OK] model "solar-embedding-1-large-passage" present upstream
    upstage_smoke_test.go:70: [OK] ChatWithMessages answer="pong"
    upstage_smoke_test.go:84: [OK] ChatStreamlyWithSender chunks=15 joined="Hi! How can I assist you today? 😊  \n\n(And if"
    upstage_smoke_test.go:104: [OK] Embed vectors=3 dim=4096 indices=[0 1 2]
    upstage_smoke_test.go:116: [OK] Embed(query) dim=4096
    upstage_smoke_test.go:122: [OK] Balance returns no such method
    upstage_smoke_test.go:129: [OK] Rerank returns no such method
    upstage_smoke_test.go:137: [OK] Embed(empty) returned 0 vectors

ALL UPSTAGE SMOKE CHECKS PASSED
--- PASS: TestUpstageSmoke (3.92s)
PASS
ok  	ragflow/internal/entity/models	3.937s

What the embed assertions verify against the real api.upstage.ai:

  • solar-embedding-1-large-passage on 3 inputs returns 3 vectors of dimension 4096, with index field preserved as [0, 1, 2] so the order-by-index reorder logic is exercised on real data.
  • solar-embedding-1-large-query on 1 input returns 1 vector of the same 4096 dimension.
  • Empty []string input returns []EmbeddingData{} without making an HTTP call (validates the short-circuit).

Build: go build ./internal/entity/models/... exits 0 on go 1.25.

This PR remains stacked on #14817. After #14817 merges, this PR's diff will auto-reduce to the embed-only changes.

@Haruko386

Copy link
Copy Markdown
Member

@tmimmanuel thank you for your contribution, I shall review your code later.

CodeRabbit review on this PR flagged two issues that match the ones
also addressed in the Mistral driver (infiniflow#14805) and StepFun (infiniflow#14815).

- ChatWithMessages and ListModels treated a non-nil but empty Region
  pointer as an explicit region, which then failed baseURLForRegion
  lookup despite a valid "default" entry. Match the guard already used
  in ChatStreamlyWithSender: only override "default" when the region
  string is non-empty.
- ChatStreamlyWithSender did not validate that sender was non-nil
  before invoking it inside the scan loop, which would panic on a
  nil callback. Add the guard alongside the existing messages and
  api-key checks.
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

CodeRabbit review status

The conf/models/upstage.json finding (max_tokens 4000 → 2000) was already addressed in commit 26699a5 before this round (see prior comment thread).

The new mistral.go-style findings (empty-region + nil-sender) on the driver code were applied in PR #14817 commit 2ba2303 — this branch has been rebased on top. Build still clean.

Comment thread internal/entity/models/upstage.go Resolved
Comment thread internal/entity/models/upstage.go Resolved
@Haruko386

Copy link
Copy Markdown
Member

Hi @tmimmanuel, please refer upstage chat api docs for more info

@Haruko386 pointed out that the Upstage chat API supports
reasoning_effort (https://console.upstage.ai/api/chat) and the
shipped driver did not propagate it. Per the docs at
https://console.upstage.ai/api/docs/for-agents/raw, the parameter
takes values minimal|low|medium|high (default minimal) and is
honored by solar-pro2 / solar-pro3 (ignored by solar-mini and
syn-pro). The canonical carrier already exists on the interface as
ChatConfig.Effort, so this just plumbs it through.

- ChatWithMessages: propagate Effort -> reasoning_effort in request
  body when non-empty.
- ChatStreamlyWithSender: same.
- ChatWithMessages: also extract choices[0].message.reasoning into
  ChatResponse.ReasonContent when present. Per the docs, solar-pro3
  with reasoning_effort=high|medium and solar-pro2 with
  reasoning_effort=high return the chain-of-thought there. Without
  this change the driver was discarding it and the caller had no
  way to surface reasoning to the UI even after opting in.

If Effort is unset the field is omitted from the body, which matches
the upstream default of minimal without sending an explicit value
that some proxies may treat differently from absent.

New file internal/entity/models/upstage_test.go with httptest
coverage:

- TestUpstageChatPropagatesReasoningEffort:     Effort flows into body
- TestUpstageChatOmitsReasoningEffortWhenUnset: nil Effort omits the
                                                 field
- TestUpstageStreamPropagatesReasoningEffort:   same for streaming
- TestUpstageChatExtractsReasoningField:        message.reasoning ->
                                                 ReasonContent
- TestUpstageChatHandlesAbsentReasoning:        no reasoning key ->
                                                 empty ReasonContent,
                                                 no crash
- TestUpstageRequestBodyMatchesSolarAPIShape:   end-to-end body shape
                                                 against the Solar
                                                 chat-completions API

All 6 tests pass on go 1.25.
CodeRabbit review pointed out that the documented max input length for
solar-embedding-1-large-query and solar-embedding-1-large-passage is
2000 tokens, not 4000. Update both entries.
Mirror the LocalAI fix (commit 7390d95): CodeRabbit caught that the
reorder loop in *Model.Embed would silently overwrite the earlier
vector if an upstream response repeated the same data[*].index value.
The driver would then return a length-correct []EmbeddingData where
some slots held the second vector under the index of the first, with
no signal to the caller.

Fail loudly: if filled[item.Index] is already true, return
"upstage: duplicate embedding index <n> in response".

Add internal/entity/models/upstage_test.go with three Embed-path tests:
- TestUpstageEmbedRejectsDuplicateIndex: pins the new behavior
- TestUpstageEmbedRejectsOutOfRangeIndex
- TestUpstageEmbedHappyPathReordersByIndex (covers the shuffle-then-realign path)

All 3 pass in 0.04s.

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

25-26: ⚡ Quick win

Consider validating the HTTP request path and method.

The test handlers currently accept any request without verifying the path, HTTP method, or headers. Adding basic request validation would catch URL construction bugs and ensure the implementation calls the correct endpoint.

🔍 Example: Add request validation to one test
 func TestUpstageEmbedRejectsDuplicateIndex(t *testing.T) {
 	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/embeddings" {
+			t.Errorf("unexpected path: %s", r.URL.Path)
+		}
+		if r.Method != http.MethodPost {
+			t.Errorf("unexpected method: %s", r.Method)
+		}
 		_, _ = io.WriteString(w, `{"data":[
 			{"embedding":[1],"index":0},
 			{"embedding":[2],"index":0}]}`)
 	}))

Apply similar validation to the other test handlers.

Also applies to: 42-43, 58-59

🤖 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/upstage_test.go` around lines 25 - 26, The test HTTP
handlers created with httptest.NewServer and http.HandlerFunc should validate
incoming requests' method and path to catch URL construction bugs: inside the
handler used in upstage_test.go (the function passed to httptest.NewServer),
assert r.Method == "GET" (or the expected method) and r.URL.Path (and query if
relevant) matches the expected endpoint, returning a 404/405 or failing the test
if not; do the same validation for the other test handlers referenced in the
file so each test verifies the correct HTTP method, path, and any required
headers before writing the JSON response.
🤖 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/upstage_test.go`:
- Around line 25-26: The test HTTP handlers created with httptest.NewServer and
http.HandlerFunc should validate incoming requests' method and path to catch URL
construction bugs: inside the handler used in upstage_test.go (the function
passed to httptest.NewServer), assert r.Method == "GET" (or the expected method)
and r.URL.Path (and query if relevant) matches the expected endpoint, returning
a 404/405 or failing the test if not; do the same validation for the other test
handlers referenced in the file so each test verifies the correct HTTP method,
path, and any required headers before writing the JSON response.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9d673977-2b02-4a56-bcad-29025c0a4779

📥 Commits

Reviewing files that changed from the base of the PR and between d9442f1 and 3ddf03a.

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

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

Thanks for the pointer to the docs @Haruko386. Applied in driver-branch commit 3bd705b (this PR is stacked on #14817; rebased here as 31c01a7).

Read https://console.upstage.ai/api/docs/for-agents/raw and confirmed:

  • Request: reasoning_effort accepts minimal | low | medium | high. Default minimal. Honored by solar-pro2 / solar-pro3, ignored by solar-mini and syn-pro.
  • Response: when reasoning is enabled, choices[0].message.reasoning carries the chain-of-thought.

Both sides are now wired:

Request body — both ChatWithMessages and ChatStreamlyWithSender propagate ChatConfig.Effort (the canonical Go-side carrier) to reasoning_effort in the request body when non-empty:

if chatModelConfig.Effort != nil && *chatModelConfig.Effort != "" {
    reqBody["reasoning_effort"] = *chatModelConfig.Effort
}

When the caller does not opt in, the field is omitted rather than sent as "minimal" — that way any proxies that distinguish present-vs-absent see the same shape as the upstream default.

Response parsing — ChatWithMessages now extracts choices[0].message.reasoning into ChatResponse.ReasonContent. Absent or non-string reasoning leaves it empty, so non-reasoning models (solar-mini, syn-pro) and low-effort requests still parse cleanly.

reasonContent := ""
if r, ok := messageMap["reasoning"].(string); ok {
    reasonContent = r
}

Tests — six new tests in internal/entity/models/upstage_test.go covering:

  • TestUpstageChatPropagatesReasoningEffort — Effort: "high" → body reasoning_effort: "high"
  • TestUpstageChatOmitsReasoningEffortWhenUnset — nil Effort → no reasoning_effort key in body
  • TestUpstageStreamPropagatesReasoningEffort — same for the streaming path
  • TestUpstageChatExtractsReasoningField — feeds the exact 15% of 80 example from the docs, asserts the reasoning trace surfaces on ChatResponse.ReasonContent
  • TestUpstageChatHandlesAbsentReasoning — solar-mini response with no reasoning field → empty ReasonContent, no crash
  • TestUpstageRequestBodyMatchesSolarAPIShape — end-to-end body shape pinned against the Solar chat-completions schema (model, stream, max_tokens, temperature, top_p, stop, reasoning_effort, messages)

All 9 Upstage tests pass on go 1.25.

$ go test -vet=off -run TestUpstage -v ./internal/entity/models/...
=== RUN   TestUpstageChatPropagatesReasoningEffort
--- PASS: TestUpstageChatPropagatesReasoningEffort (0.00s)
=== RUN   TestUpstageChatOmitsReasoningEffortWhenUnset
--- PASS: TestUpstageChatOmitsReasoningEffortWhenUnset (0.00s)
=== RUN   TestUpstageStreamPropagatesReasoningEffort
--- PASS: TestUpstageStreamPropagatesReasoningEffort (0.00s)
=== RUN   TestUpstageChatExtractsReasoningField
--- PASS: TestUpstageChatExtractsReasoningField (0.00s)
=== RUN   TestUpstageChatHandlesAbsentReasoning
--- PASS: TestUpstageChatHandlesAbsentReasoning (0.00s)
=== RUN   TestUpstageRequestBodyMatchesSolarAPIShape
--- PASS: TestUpstageRequestBodyMatchesSolarAPIShape (0.00s)
=== RUN   TestUpstageEmbedRejectsDuplicateIndex
--- PASS: TestUpstageEmbedRejectsDuplicateIndex (0.00s)
=== RUN   TestUpstageEmbedRejectsOutOfRangeIndex
--- PASS: TestUpstageEmbedRejectsOutOfRangeIndex (0.00s)
=== RUN   TestUpstageEmbedHappyPathReordersByIndex
--- PASS: TestUpstageEmbedHappyPathReordersByIndex (0.00s)
PASS
ok      ragflow/internal/entity/models  0.024s

One thing I did not wire is the streaming-side reasoning delta. The for-agents raw doc shows the non-streaming message.reasoning shape and the request-side reasoning_effort parameter, but I didn't find an explicit example of how reasoning appears inside delta chunks for SSE streaming. Happy to add SSE-side parsing once we have a documented wire shape (or a sample response I can verify). Let me know if you want me to file that as a separate follow-up.

@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 LGTM,
Thank you for your contribution

@Haruko386 Haruko386 added the ci Continue Integration label May 12, 2026

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

🤖 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/upstage.go`:
- Around line 475-489: In the loop over parsed.Data in upstage.go, validate that
item.Embedding is non-nil and non-empty before populating embeddings[item.Index]
and setting filled[item.Index]; if len(item.Embedding) == 0 return an error
(e.g., "upstage: empty embedding for index %d") so we don't mark a slot filled
with an empty slice. Update the code paths that construct EmbeddingData (and the
error messages around duplicate/out-of-range checks) accordingly and add a
regression test that sends a payload like {"index":0} and asserts the function
returns an error instead of producing a zero-length embedding.
🪄 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: 576d079c-0609-4254-8af3-f4ad2f633576

📥 Commits

Reviewing files that changed from the base of the PR and between 3ddf03a and b884268.

📒 Files selected for processing (4)
  • conf/models/upstage.json
  • internal/entity/models/factory.go
  • internal/entity/models/upstage.go
  • internal/entity/models/upstage_test.go
✅ Files skipped from review due to trivial changes (2)
  • conf/models/upstage.json
  • internal/entity/models/factory.go

Comment on lines +475 to +489
for _, item := range parsed.Data {
if item.Index < 0 || item.Index >= len(texts) {
return nil, fmt.Errorf("upstage: response index %d out of range for %d inputs", item.Index, len(texts))
}
if filled[item.Index] {
// A malformed response that repeats the same index would
// silently overwrite the earlier vector. Fail loudly so
// the caller never uses ambiguous output.
return nil, fmt.Errorf("upstage: duplicate embedding index %d in response", item.Index)
}
embeddings[item.Index] = EmbeddingData{
Embedding: item.Embedding,
Index: item.Index,
}
filled[item.Index] = true

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject empty embedding payloads before marking a slot as filled.

json.Unmarshal leaves item.Embedding nil when the field is missing, and [] also passes here. This loop still flips filled[item.Index], so a malformed upstream payload like {"index":0} returns a zero-length embedding instead of failing fast. Please guard len(item.Embedding) == 0 before storing it, and add a regression test for that case.

Suggested fix
 	for _, item := range parsed.Data {
 		if item.Index < 0 || item.Index >= len(texts) {
 			return nil, fmt.Errorf("upstage: response index %d out of range for %d inputs", item.Index, len(texts))
 		}
 		if filled[item.Index] {
 			// A malformed response that repeats the same index would
 			// silently overwrite the earlier vector. Fail loudly so
 			// the caller never uses ambiguous output.
 			return nil, fmt.Errorf("upstage: duplicate embedding index %d in response", item.Index)
 		}
+		if len(item.Embedding) == 0 {
+			return nil, fmt.Errorf("upstage: empty embedding for input index %d", item.Index)
+		}
 		embeddings[item.Index] = EmbeddingData{
 			Embedding: item.Embedding,
 			Index:     item.Index,
 		}
 		filled[item.Index] = true
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for _, item := range parsed.Data {
if item.Index < 0 || item.Index >= len(texts) {
return nil, fmt.Errorf("upstage: response index %d out of range for %d inputs", item.Index, len(texts))
}
if filled[item.Index] {
// A malformed response that repeats the same index would
// silently overwrite the earlier vector. Fail loudly so
// the caller never uses ambiguous output.
return nil, fmt.Errorf("upstage: duplicate embedding index %d in response", item.Index)
}
embeddings[item.Index] = EmbeddingData{
Embedding: item.Embedding,
Index: item.Index,
}
filled[item.Index] = true
for _, item := range parsed.Data {
if item.Index < 0 || item.Index >= len(texts) {
return nil, fmt.Errorf("upstage: response index %d out of range for %d inputs", item.Index, len(texts))
}
if filled[item.Index] {
// A malformed response that repeats the same index would
// silently overwrite the earlier vector. Fail loudly so
// the caller never uses ambiguous output.
return nil, fmt.Errorf("upstage: duplicate embedding index %d in response", item.Index)
}
if len(item.Embedding) == 0 {
return nil, fmt.Errorf("upstage: empty embedding for input index %d", item.Index)
}
embeddings[item.Index] = EmbeddingData{
Embedding: item.Embedding,
Index: item.Index,
}
filled[item.Index] = true
}
🤖 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/upstage.go` around lines 475 - 489, In the loop over
parsed.Data in upstage.go, validate that item.Embedding is non-nil and non-empty
before populating embeddings[item.Index] and setting filled[item.Index]; if
len(item.Embedding) == 0 return an error (e.g., "upstage: empty embedding for
index %d") so we don't mark a slot filled with an empty slice. Update the code
paths that construct EmbeddingData (and the error messages around
duplicate/out-of-range checks) accordingly and add a regression test that sends
a payload like {"index":0} and asserts the function returns an error instead of
producing a zero-length embedding.

@codecov

codecov Bot commented May 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (128a64e) to head (b884268).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14819   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ 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 eaa2e46 into infiniflow:main May 12, 2026
1 check passed
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
LongCat (Meituan, https://longcat.chat) is one of the unchecked
providers on the umbrella tracking issue infiniflow#14736. Its API is
OpenAI-compatible at https://api.longcat.chat/openai/v1 with three
public chat models: LongCat-Flash-Chat, LongCat-Flash-Lite, and
LongCat-Flash-Thinking (a reasoning model).

What this PR includes:

- internal/entity/models/longcat.go: full driver implementing the
  ModelDriver interface
- conf/models/longcat.json: base URL + url_suffix + the 3 public
  models
- factory.go: route "longcat" provider name to NewLongCatModel
- internal/entity/models/longcat_test.go: 21 unit tests

Methods:

- ChatWithMessages         non-stream chat
- ChatStreamlyWithSender   SSE streaming chat
- ListModels / CheckConnection
- reasoning_content extraction on both stream and non-stream paths
  (LongCat-Flash-Thinking returns the chain-of-thought in
  message.reasoning_content / delta.reasoning_content, OpenAI
  o-series shape; live-probed before writing tests)
- reasoning_effort propagation from ChatConfig.Effort
- Embed / Rerank / Balance / TranscribeAudio / AudioSpeech / OCRFile
  return the "no such method" sentinel (LongCat does not expose any
  of these surfaces)

Pattern parity with the merged Mistral (infiniflow#14807), Upstage (infiniflow#14819),
and StepFun (infiniflow#14815) drivers. No interface change.

Verified live against api.longcat.chat:
- ListModels: 5 ids (Flash-Lite, Flash-Chat, Flash-Thinking-2601,
  Flash-Omni-2603, 2.0-Preview)
- Chat (Flash-Chat) non-stream: "Got it! Let me know if you..."
- Chat (Flash-Thinking) non-stream: 443-char answer + 557-char
  reasoning trace extracted into ChatResponse.ReasonContent
- Stream (Flash-Thinking): 78 content chunks (351 chars) + 107
  reasoning chunks (537 chars) — the delta.reasoning_content
  extraction works end to end against real wire data
- Sentinels all return "no such method"

21 unit tests pass on go 1.25; build clean.

Note on PR history: this branch was previously named for LocalAI
work which has since been consolidated into PR infiniflow#14813. The branch
was reset to upstream/main and rebuilt for LongCat — diff is a
clean +1052 lines on top of current main.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
LongCat (Meituan, https://longcat.chat) is one of the unchecked
providers on the umbrella tracking issue infiniflow#14736. Its API is
OpenAI-compatible at https://api.longcat.chat/openai/v1 with three
public chat models: LongCat-Flash-Chat, LongCat-Flash-Lite, and
LongCat-Flash-Thinking (a reasoning model).

What this PR includes:

- internal/entity/models/longcat.go: full driver implementing the
  ModelDriver interface
- conf/models/longcat.json: base URL + url_suffix + the 3 public
  models
- factory.go: route "longcat" provider name to NewLongCatModel
- internal/entity/models/longcat_test.go: 21 unit tests

Methods:

- ChatWithMessages         non-stream chat
- ChatStreamlyWithSender   SSE streaming chat
- ListModels / CheckConnection
- reasoning_content extraction on both stream and non-stream paths
  (LongCat-Flash-Thinking returns the chain-of-thought in
  message.reasoning_content / delta.reasoning_content, OpenAI
  o-series shape; live-probed before writing tests)
- reasoning_effort propagation from ChatConfig.Effort
- Embed / Rerank / Balance / TranscribeAudio / AudioSpeech / OCRFile
  return the "no such method" sentinel (LongCat does not expose any
  of these surfaces)

Pattern parity with the merged Mistral (infiniflow#14807), Upstage (infiniflow#14819),
and StepFun (infiniflow#14815) drivers. No interface change.

Verified live against api.longcat.chat:
- ListModels: 5 ids (Flash-Lite, Flash-Chat, Flash-Thinking-2601,
  Flash-Omni-2603, 2.0-Preview)
- Chat (Flash-Chat) non-stream: "Got it! Let me know if you..."
- Chat (Flash-Thinking) non-stream: 443-char answer + 557-char
  reasoning trace extracted into ChatResponse.ReasonContent
- Stream (Flash-Thinking): 78 content chunks (351 chars) + 107
  reasoning chunks (537 chars) — the delta.reasoning_content
  extraction works end to end against real wire data
- Sentinels all return "no such method"

21 unit tests pass on go 1.25; build clean.

Note on PR history: this branch was previously named for LocalAI
work which has since been consolidated into PR infiniflow#14813. The branch
was reset to upstream/main and rebuilt for LongCat — diff is a
clean +1052 lines on top of current main.
JinHai-CN pushed a commit that referenced this pull request May 21, 2026
### What problem does this PR solve?

`UpstageModel.ChatStreamlyWithSender` (in the driver merged via #14819)
only extracted `delta.content` from each SSE event. For the `solar-pro3`
reasoning family (and any future Upstage model that follows the same
wire shape), the chain-of-thought is streamed in a **separate
`delta.reasoning` field**, and the driver was silently dropping all of
it.

The non-streaming path already extracts `message.reasoning` into
`ChatResponse.ReasonContent` (added earlier in this PR's history), so
the same model produced **inconsistent behavior** between streaming and
non-streaming: a tenant calling `solar-pro3` with `reasoning_effort:
high` would see the reasoning trace if they used `ChatWithMessages` but
not if they used `ChatStreamlyWithSender`.

### Live evidence

Probed against `api.upstage.ai/v1/chat/completions` with `solar-pro3` +
`reasoning_effort: high` + `stream: true` (8000-token budget so the
reasoning has room to finish):

```
$ curl -sN -H "Authorization: Bearer <key>" -H "Content-Type: application/json" \
       -X POST https://api.upstage.ai/v1/chat/completions \
       -d '{"model":"solar-pro3","messages":[{"role":"user","content":"Compute 15% of 80."}],
            "max_tokens":8000,"stream":true,"reasoning_effort":"high"}'

# across 168 SSE events:
#   delta keys seen: [content reasoning role]
#   delta.content total len:   121 chars   (the visible answer)
#   delta.reasoning total len: 159 chars   (the chain-of-thought) <- driver dropped this
```

A representative event showing both fields side by side:

```json
data: {"choices":[{"index":0,"delta":{"reasoning":"15% = 0.15."}}]}
data: {"choices":[{"index":0,"delta":{"content":"15% of 80 is "}}]}
```

The 159 chars of reasoning were arriving on the wire and being thrown
away. `solar-pro2` was also probed (625 events); it does **not** emit
`delta.reasoning` — its reasoning is inlined into `delta.content` — so
this change is a no-op for it and for `solar-mini`.

### What this PR includes

- `internal/entity/models/upstage.go`: in the SSE scanner loop, extract
`delta.reasoning` before `delta.content` and forward each non-empty
chunk via the sender's second arg (the existing `reasonContent` channel
the non-stream path already populates).

The ordering contract is documented inline: reasoning chunks within a
single SSE event are emitted before content chunks, so a UI that pipes
both sees the chain-of-thought start before the answer for that token,
matching the wire order Upstage emits.

- `internal/entity/models/upstage_test.go`: three new tests pinning the
new behavior:
- `TestUpstageStreamExtractsReasoningDelta` — reasoning + content
forwarded to the right sender args; one-of invariant per call
- `TestUpstageStreamReasoningChunksArriveBeforeContent` — ordering
pinned within a single SSE event that carries both fields
- `TestUpstageStreamWithoutReasoningStillWorks` — regression net:
non-reasoning models (`solar-mini`, `solar-pro2`) continue to work; the
reason callback never fires

No interface change. No factory change. No config change.

### How was this tested?

```
$ go test -vet=off -run TestUpstage -count=1 -v ./internal/entity/models/...
... (existing tests 1..9 still pass) ...
=== RUN   TestUpstageStreamExtractsReasoningDelta
--- PASS: TestUpstageStreamExtractsReasoningDelta (0.01s)
=== RUN   TestUpstageStreamReasoningChunksArriveBeforeContent
--- PASS: TestUpstageStreamReasoningChunksArriveBeforeContent (0.01s)
=== RUN   TestUpstageStreamWithoutReasoningStillWorks
--- PASS: TestUpstageStreamWithoutReasoningStillWorks (0.00s)
PASS
ok      ragflow/internal/entity/models  0.034s
```

12/12 Upstage tests pass on go 1.25. `go build
./internal/entity/models/...` exits 0.

**Live integration test** (smoke test not committed) — the patched
driver was run directly against `api.upstage.ai/v1` with the same prompt
that produced the curl evidence above:

```
=== RUN   TestUpstageStreamReasoningLiveSmoke
    [OK] visible content: 50 chunks, 84 chars
    [OK] reasoning:       39 chunks, 90 chars
    content head 200:   "\\(15\\% = \\frac{15}{100}=0.15\\).\n\n\\[\n0.15 \\times 80 = 12.\n\\]\n\n**15 % of 80 is 12.**"
    reasoning head 200: "We need to compute 15% of 80. That's 0.15 * 80 = 12. So answer is 12. Provide explanation."

UPSTAGE STREAM REASONING SMOKE PASSED
--- PASS: TestUpstageStreamReasoningLiveSmoke (1.97s)
```

Before this fix, the same call would have produced **0 reasoning
chunks**. The 90 chars of reasoning that the patched driver now surfaces
are the chain-of-thought solar-pro3 emits when reasoning_effort is high.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
JinHai-CN pushed a commit that referenced this pull request May 21, 2026
### What problem does this PR solve?

`UpstageModel.ChatStreamlyWithSender` (in the driver merged via #14819)
only extracted `delta.content` from each SSE event. For the `solar-pro3`
reasoning family (and any future Upstage model that follows the same
wire shape), the chain-of-thought is streamed in a **separate
`delta.reasoning` field**, and the driver was silently dropping all of
it.

The non-streaming path already extracts `message.reasoning` into
`ChatResponse.ReasonContent` (added earlier in this PR's history), so
the same model produced **inconsistent behavior** between streaming and
non-streaming: a tenant calling `solar-pro3` with `reasoning_effort:
high` would see the reasoning trace if they used `ChatWithMessages` but
not if they used `ChatStreamlyWithSender`.

### Live evidence

Probed against `api.upstage.ai/v1/chat/completions` with `solar-pro3` +
`reasoning_effort: high` + `stream: true` (8000-token budget so the
reasoning has room to finish):

```
$ curl -sN -H "Authorization: Bearer <key>" -H "Content-Type: application/json" \
       -X POST https://api.upstage.ai/v1/chat/completions \
       -d '{"model":"solar-pro3","messages":[{"role":"user","content":"Compute 15% of 80."}],
            "max_tokens":8000,"stream":true,"reasoning_effort":"high"}'

# across 168 SSE events:
#   delta keys seen: [content reasoning role]
#   delta.content total len:   121 chars   (the visible answer)
#   delta.reasoning total len: 159 chars   (the chain-of-thought) <- driver dropped this
```

A representative event showing both fields side by side:

```json
data: {"choices":[{"index":0,"delta":{"reasoning":"15% = 0.15."}}]}
data: {"choices":[{"index":0,"delta":{"content":"15% of 80 is "}}]}
```

The 159 chars of reasoning were arriving on the wire and being thrown
away. `solar-pro2` was also probed (625 events); it does **not** emit
`delta.reasoning` — its reasoning is inlined into `delta.content` — so
this change is a no-op for it and for `solar-mini`.

### What this PR includes

- `internal/entity/models/upstage.go`: in the SSE scanner loop, extract
`delta.reasoning` before `delta.content` and forward each non-empty
chunk via the sender's second arg (the existing `reasonContent` channel
the non-stream path already populates).

The ordering contract is documented inline: reasoning chunks within a
single SSE event are emitted before content chunks, so a UI that pipes
both sees the chain-of-thought start before the answer for that token,
matching the wire order Upstage emits.

- `internal/entity/models/upstage_test.go`: three new tests pinning the
new behavior:
- `TestUpstageStreamExtractsReasoningDelta` — reasoning + content
forwarded to the right sender args; one-of invariant per call
- `TestUpstageStreamReasoningChunksArriveBeforeContent` — ordering
pinned within a single SSE event that carries both fields
- `TestUpstageStreamWithoutReasoningStillWorks` — regression net:
non-reasoning models (`solar-mini`, `solar-pro2`) continue to work; the
reason callback never fires

No interface change. No factory change. No config change.

### How was this tested?

```
$ go test -vet=off -run TestUpstage -count=1 -v ./internal/entity/models/...
... (existing tests 1..9 still pass) ...
=== RUN   TestUpstageStreamExtractsReasoningDelta
--- PASS: TestUpstageStreamExtractsReasoningDelta (0.01s)
=== RUN   TestUpstageStreamReasoningChunksArriveBeforeContent
--- PASS: TestUpstageStreamReasoningChunksArriveBeforeContent (0.01s)
=== RUN   TestUpstageStreamWithoutReasoningStillWorks
--- PASS: TestUpstageStreamWithoutReasoningStillWorks (0.00s)
PASS
ok      ragflow/internal/entity/models  0.034s
```

12/12 Upstage tests pass on go 1.25. `go build
./internal/entity/models/...` exits 0.

**Live integration test** (smoke test not committed) — the patched
driver was run directly against `api.upstage.ai/v1` with the same prompt
that produced the curl evidence above:

```
=== RUN   TestUpstageStreamReasoningLiveSmoke
    [OK] visible content: 50 chunks, 84 chars
    [OK] reasoning:       39 chunks, 90 chars
    content head 200:   "\\(15\\% = \\frac{15}{100}=0.15\\).\n\n\\[\n0.15 \\times 80 = 12.\n\\]\n\n**15 % of 80 is 12.**"
    reasoning head 200: "We need to compute 15% of 80. That's 0.15 * 80 = 12. So answer is 12. Provide explanation."

UPSTAGE STREAM REASONING SMOKE PASSED
--- PASS: TestUpstageStreamReasoningLiveSmoke (1.97s)
```

Before this fix, the same call would have produced **0 reasoning
chunks**. The 90 chars of reasoning that the patched driver now surfaces
are the chain-of-thought solar-pro3 emits when reasoning_effort is high.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
@coderabbitai coderabbitai Bot mentioned this pull request May 25, 2026
2 tasks done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

The Upstage Go driver landed in infiniflow#14817 with chat, list models, and check
connection. `Embed` was left as a stub that returns `"not implemented"`.
This PR fills the gap.

Upstage exposes an OpenAI-compatible embeddings endpoint at
`https://api.upstage.ai/v1/solar/embeddings` via the
`solar-embedding-1-large` family (`solar-embedding-1-large-query` for
queries, `solar-embedding-1-large-passage` for passages), and the Python
side has had `UpstageEmbed(OpenAIEmbed)` in `rag/llm/embedding_model.py`
for a long time targeting this same path. The existing
`conf/models/upstage.json` did not list any embedding model out of the
box, so a tenant who wanted to use Upstage end to end could not run an
embedding call. This PR fills the gap.

### What this PR includes

- `conf/models/upstage.json`: add `"embedding": "embeddings"` under
`url_suffix` so the driver can build the URL from config (matches the
`URLSuffix.Embedding` field already used by openai, mistral,
siliconflow, zhipu-ai), and add `solar-embedding-1-large-query` and
`solar-embedding-1-large-passage` entries under `models`.
- `internal/entity/models/upstage.go`: replace the `Embed` stub with a
real implementation that POSTs to `/v1/solar/embeddings`. Adds local
response types `upstageEmbeddingData` and `upstageEmbeddingResponse`.

No factory change. No interface change.

### How the implementation works

- Validate `apiConfig`, the API key, and 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 Upstage API accepts the
`input` field as an array.
- Parse `data[*].embedding` and copy each slice into a `[]EmbeddingData`
indexed by `data[*].index` so the output order matches the input order
even if the API returns items in a different order.
- An empty input slice returns `[]EmbeddingData{}` 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 empty, return a clear error so the caller does not silently use a
zero vector.

### Note on stacking

This PR builds on infiniflow#14817 (the Upstage driver). Until infiniflow#14817 merges, this
PR's diff on GitHub will include both that PR's commits and this one.
After infiniflow#14817 lands on `main`, GitHub will auto-reduce this PR to only
the `Embed` changes (one commit, ~119 line diff in `upstage.go` plus ~15
lines in `upstage.json`).

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- `go build ./internal/entity/models/...` returns exit 0 on go 1.25 (the
`go.mod` minimum).
- The full method set on `UpstageModel` still matches the `ModelDriver`
interface.
- Pattern parity with the existing Mistral Embed
(`internal/entity/models/mistral.go`) and OpenAI Embed
(`internal/entity/models/openai.go`) implementations.

Closes infiniflow#14818
Depends on infiniflow#14817
Tracking: infiniflow#14736

---------

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.

[Feature Request]: Implement Embed (embeddings) in the Upstage Go driver

3 participants