Repository navigation
fix(upstage): extract reasoning delta from streaming responses - #14817
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:
📝 WalkthroughWalkthroughThis PR extends Upstage's streaming chat handler to support reasoning tokens by detecting ChangesReasoning-Aware Streaming Implementation
Sequence DiagramsequenceDiagram
participant Client
participant UpstageModel
participant UpstageAPI
Client->>UpstageModel: ChatStreamlyWithSender(messages, sender)
UpstageModel->>UpstageAPI: POST stream:true
loop SSE events
UpstageAPI-->>UpstageModel: data: {delta.reasoning?, delta.content?}
alt reasoning present
UpstageModel->>Client: sender(nil, &reasoning)
end
alt content present
UpstageModel->>Client: sender(&content, nil)
end
end
UpstageAPI-->>UpstageModel: data: [DONE]
UpstageModel->>Client: sender("[DONE]", nil)
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/upstage.go`:
- Around line 102-105: Normalize the region fallback so an empty string is
treated like nil: wherever you set region (e.g., the streaming path code that
currently does var region = "default" with if apiConfig.Region != nil { region =
*apiConfig.Region }), change the check to treat both nil and "" as missing (use
if apiConfig.Region != nil && *apiConfig.Region != "" then use value else
"default"). Apply the same change in the other occurrence noted (the block used
by ChatWithMessages and ListModels) so all paths use identical empty-region
fallback behavior.
- Around line 211-212: Add a nil-guard for the sender parameter in
UpstageModel.ChatStreamlyWithSender: at the start of the function check if
sender == nil and return a clear error (e.g., fmt.Errorf or wrapped error) so
the function fails early instead of panicking when the method later invokes
sender (the call sites currently around the locations that correspond to the
sender invocations). Ensure both places where sender is invoked are covered by
this early return so no nil dereference can occur.
🪄 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: e020bc67-6d9f-442c-a993-6014743c1ff6
📒 Files selected for processing (3)
conf/models/upstage.jsoninternal/entity/models/factory.gointernal/entity/models/upstage.go
CodeRabbit review on the stacked PR infiniflow#14811 flagged that the ChatStreamlyWithSender comment promised "the client drops the connection if it stalls", which is not actually implemented in the current driver. Replace the comment with the more accurate wording used in the merged OpenAI driver (infiniflow#14605): the background context makes the request "cancellable in principle" but no hard deadline is attached because SSE streams are long-lived, and threading a real ctx through the ModelDriver interface is a wider change for a follow-up. Also add a nil-sender guard at the top of ChatStreamlyWithSender, matching the fixes applied to Mistral (infiniflow#14805) and Upstage (infiniflow#14817) on review feedback. The risk class is the same: invoking a nil callback panics the process.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/upstage_test.go (1)
30-31: ⚡ Quick winConsider checking errors in test request handlers.
Multiple test handlers silently ignore errors from
io.ReadAllandjson.Unmarshal. If the driver sends malformed JSON or the read fails, the test assertions may produce confusing failures rather than clear error messages at the point of failure.🧪 Proposed fix to improve test debugging
For example, in
TestUpstageChatPropagatesReasoningEffort(lines 30-31):- raw, _ := io.ReadAll(r.Body) - _ = json.Unmarshal(raw, &seen) + raw, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("ReadAll: %v", err) + } + if err := json.Unmarshal(raw, &seen); err != nil { + t.Errorf("Unmarshal: %v", err) + }Apply the same pattern to test handlers at lines 57-58, 81-82, and 168-169.
Also applies to: 57-58, 81-82, 168-169
🤖 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 30 - 31, The test HTTP handlers in internal/entity/models/upstage_test.go (e.g., the handler used in TestUpstageChatPropagatesReasoningEffort that reads into raw and unmarshals into seen) currently ignore errors from io.ReadAll and json.Unmarshal; update each handler to check the returned error and fail the test immediately (e.g., call t.Fatalf or panic with a clear message) when io.ReadAll or json.Unmarshal returns a non-nil error so malformed input surfaces at the read/unmarshal step; apply the same change to the other test handlers that set raw/_ and json.Unmarshal(_, &seen) at the noted spots (the handlers around lines 57-58, 81-82, and 168-169).
🤖 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 30-31: The test HTTP handlers in
internal/entity/models/upstage_test.go (e.g., the handler used in
TestUpstageChatPropagatesReasoningEffort that reads into raw and unmarshals into
seen) currently ignore errors from io.ReadAll and json.Unmarshal; update each
handler to check the returned error and fail the test immediately (e.g., call
t.Fatalf or panic with a clear message) when io.ReadAll or json.Unmarshal
returns a non-nil error so malformed input surfaces at the read/unmarshal step;
apply the same change to the other test handlers that set raw/_ and
json.Unmarshal(_, &seen) at the noted spots (the handlers around lines 57-58,
81-82, and 168-169).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 6e33363b-9584-4dbb-b48b-d1962caa46c1
📒 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
### 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 - [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 #14818 Depends on #14817 Tracking: #14736 --------- Co-authored-by: Jin Hai <[email protected]>
|
Duplicated with #14819 . I will close it. Please feel free to re-open it, if i am wrong. |
3bd705b to
9ec6e3a
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/upstage_test.go (1)
273-423: ⚡ Quick winConsider adding test coverage for nil sender callback.
The PR objectives mention that a nil-sender guard was added to
ChatStreamlyWithSenderto prevent panics, but there's no test validating this case. Adding a test would prevent regression if the guard is accidentally removed.🧪 Suggested test for nil sender guard
func TestUpstageStreamWithNilSenderDoesNotPanic(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/event-stream") _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"hi"}}]}`+"\n"+ `data: [DONE]`+"\n", ) })) defer srv.Close() u := newUpstageForTest(srv.URL) apiKey := "test-key" // Should not panic when sender is nil err := u.ChatStreamlyWithSender("solar-mini", []Message{{Role: "user", Content: "x"}}, &APIConfig{ApiKey: &apiKey}, nil, nil, // nil sender callback ) if err != nil { t.Fatalf("stream with nil sender: %v", err) } }🤖 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 273 - 423, Add a new unit test that exercises ChatStreamlyWithSender with a nil sender callback to ensure the nil-sender guard prevents panics: start an httptest.Server that streams a small SSE payload (a delta.content and [DONE]), call u.ChatStreamlyWithSender("solar-mini", ... , &APIConfig{ApiKey:&apiKey}, nil, nil) and assert the call returns no error; reference ChatStreamlyWithSender and newUpstageForTest to locate the code under test and mirror the existing SSE fixtures and err check pattern used in the other tests in upstage_test.go.
🤖 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 273-423: Add a new unit test that exercises ChatStreamlyWithSender
with a nil sender callback to ensure the nil-sender guard prevents panics: start
an httptest.Server that streams a small SSE payload (a delta.content and
[DONE]), call u.ChatStreamlyWithSender("solar-mini", ... ,
&APIConfig{ApiKey:&apiKey}, nil, nil) and assert the call returns no error;
reference ChatStreamlyWithSender and newUpstageForTest to locate the code under
test and mirror the existing SSE fixtures and err check pattern used in the
other tests in upstage_test.go.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f1cba40a-e46d-45f2-9fa5-2ebc5ebec005
📒 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
Haruko386
left a comment
There was a problem hiding this comment.
I checked the current Upstage chat response docs at Upstage Chat API Response again, and as far as I can tell there is still no documented reasoning / reasoning_content field in the response payload.
Let me know if I am wrong
|
@Haruko386 thanks for pushing back on this — I went and ran live tests against
Live evidence (api.upstage.ai)1. solar-pro3, non-stream,
|
Haruko386
left a comment
There was a problem hiding this comment.
@tmimmanuel LGTM
Thank your for your contribution
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14817 +/- ##
==========================================
- 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. 🚀 New features to boost your workflow:
|
|
@JinHai-CN |
9ec6e3a to
6a28ebc
Compare
ChatStreamlyWithSender's SSE parser only extracted delta.content. For
the solar-pro3 reasoning family (and any future Upstage model that
follows the same wire shape), the per-chunk reasoning trace is
streamed in a separate delta.reasoning field; the driver was dropping
all of it. The non-streaming code path already handles the equivalent
message.reasoning field on the response, so the two paths were
silently inconsistent for the same model.
Probed live against api.upstage.ai/v1/chat/completions with
solar-pro3 + reasoning_effort=high + stream=true:
Across 168 SSE events:
delta keys seen: [content reasoning role]
delta.content total: 121 chars (the visible answer)
delta.reasoning total: 159 chars (the chain-of-thought)
The 159 chars of reasoning were arriving and being thrown away.
Fix: in the per-event branch of the scanner loop, extract
delta.reasoning before delta.content and forward each non-empty
chunk via the sender's second arg (the existing reasonContent
channel that 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.
solar-pro2 inlines its reasoning into delta.content and never sets
delta.reasoning (verified with the same probe over 625 events), so
this is a no-op for it — the regression path is unchanged.
Three new tests in internal/entity/models/upstage_test.go:
- TestUpstageStreamExtractsReasoningDelta: reasoning + content
forwarded to the right
sender args; one-of
invariant per call
- TestUpstageStreamReasoningChunksArriveBeforeContent:
ordering pinned within
a single SSE event
- TestUpstageStreamWithoutReasoningStillWorks:
non-reasoning models
continue to work; the
reason callback never
fires
All 12 Upstage tests pass on go 1.25; build clean. Live integration
run (smoke test not committed) against solar-pro3 captured 39
reasoning chunks (90 chars) plus 50 content chunks (84 chars), where
the unfixed driver captured only the 50 content chunks.
6a28ebc to
33c7c44
Compare
### 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?
UpstageModel.ChatStreamlyWithSender(in the driver merged via #14819) only extracteddelta.contentfrom each SSE event. For thesolar-pro3reasoning family (and any future Upstage model that follows the same wire shape), the chain-of-thought is streamed in a separatedelta.reasoningfield, and the driver was silently dropping all of it.The non-streaming path already extracts
message.reasoningintoChatResponse.ReasonContent(added earlier in this PR's history), so the same model produced inconsistent behavior between streaming and non-streaming: a tenant callingsolar-pro3withreasoning_effort: highwould see the reasoning trace if they usedChatWithMessagesbut not if they usedChatStreamlyWithSender.Live evidence
Probed against
api.upstage.ai/v1/chat/completionswithsolar-pro3+reasoning_effort: high+stream: true(8000-token budget so the reasoning has room to finish):A representative event showing both fields side by side:
The 159 chars of reasoning were arriving on the wire and being thrown away.
solar-pro2was also probed (625 events); it does not emitdelta.reasoning— its reasoning is inlined intodelta.content— so this change is a no-op for it and forsolar-mini.What this PR includes
internal/entity/models/upstage.go: in the SSE scanner loop, extractdelta.reasoningbeforedelta.contentand forward each non-empty chunk via the sender's second arg (the existingreasonContentchannel 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 callTestUpstageStreamReasoningChunksArriveBeforeContent— ordering pinned within a single SSE event that carries both fieldsTestUpstageStreamWithoutReasoningStillWorks— regression net: non-reasoning models (solar-mini,solar-pro2) continue to work; the reason callback never firesNo interface change. No factory change. No config change.
How was this tested?
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/v1with the same prompt that produced the curl evidence above: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