Repository navigation
Go: implement Embed (embeddings) in Upstage driver - #14819
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds Upstage (Solar) provider support: provider config ( ChangesUpstage Provider Integration
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
conf/models/upstage.jsoninternal/entity/models/factory.gointernal/entity/models/upstage.go
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.
9e85070 to
26699a5
Compare
CodeRabbit review applied + live integration testCodeRabbit's review flagged four issues. After probing the live Upstage API and applying the legitimate ones: Fixes applied
Live integration testSame What the embed assertions verify against the real
Build: This PR remains stacked on #14817. After #14817 merges, this PR's diff will auto-reduce to the embed-only changes. |
|
@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.
26699a5 to
d9442f1
Compare
CodeRabbit review statusThe The new |
|
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/upstage_test.go (1)
25-26: ⚡ Quick winConsider 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
📒 Files selected for processing (2)
internal/entity/models/upstage.gointernal/entity/models/upstage_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/entity/models/upstage.go
3ddf03a to
31c01a7
Compare
|
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:
Both sides are now wired: Request body — both 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 Response parsing — reasonContent := ""
if r, ok := messageMap["reasoning"].(string); ok {
reasonContent = r
}Tests — six new tests in
All 9 Upstage tests pass on go 1.25. One thing I did not wire is the streaming-side |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @tmimmanuel LGTM,
Thank you for your contribution
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
conf/models/upstage.jsoninternal/entity/models/factory.gointernal/entity/models/upstage.gointernal/entity/models/upstage_test.go
✅ Files skipped from review due to trivial changes (2)
- conf/models/upstage.json
- internal/entity/models/factory.go
| 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 |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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.
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.
### 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)
### 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)
### 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]>
What problem does this PR solve?
The Upstage Go driver landed in #14817 with chat, list models, and check connection.
Embedwas 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/embeddingsvia thesolar-embedding-1-largefamily (solar-embedding-1-large-queryfor queries,solar-embedding-1-large-passagefor passages), and the Python side has hadUpstageEmbed(OpenAIEmbed)inrag/llm/embedding_model.pyfor a long time targeting this same path. The existingconf/models/upstage.jsondid 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"underurl_suffixso the driver can build the URL from config (matches theURLSuffix.Embeddingfield already used by openai, mistral, siliconflow, zhipu-ai), and addsolar-embedding-1-large-queryandsolar-embedding-1-large-passageentries undermodels.internal/entity/models/upstage.go: replace theEmbedstub with a real implementation that POSTs to/v1/solar/embeddings. Adds local response typesupstageEmbeddingDataandupstageEmbeddingResponse.No factory change. No interface change.
How the implementation works
apiConfig, the API key, and the model name. Use the existingbaseURLForRegionhelper so an unknown region fails fast with a clear error.context.WithTimeout(nonStreamCallTimeout)so the call has a clear deadline. Same pattern asChatWithMessagesandListModelsalready use in this file.inputfield as an array.data[*].embeddingand copy each slice into a[]EmbeddingDataindexed bydata[*].indexso the output order matches the input order even if the API returns items in a different order.[]EmbeddingData{}with no HTTP call.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 theEmbedchanges (one commit, ~119 line diff inupstage.goplus ~15 lines inupstage.json).Type of change
How was this tested?
go build ./internal/entity/models/...returns exit 0 on go 1.25 (thego.modminimum).UpstageModelstill matches theModelDriverinterface.internal/entity/models/mistral.go) and OpenAI Embed (internal/entity/models/openai.go) implementations.Closes #14818
Depends on #14817
Tracking: #14736