Skip to content

fix(upstage): extract reasoning delta from streaming responses - #14817

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
tmimmanuel:go/upstage-driver
May 21, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
tmimmanuel:go/upstage-driver

Conversation

@tmimmanuel

@tmimmanuel tmimmanuel commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added the size:L This PR changes 100-499 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

This PR extends Upstage's streaming chat handler to support reasoning tokens by detecting delta.reasoning fields in SSE events and forwarding them via the sender callback before any content. Tests validate correct extraction, intra-event ordering (reasoning before content), and regression safety for non-reasoning streams.

Changes

Reasoning-Aware Streaming Implementation

Layer / File(s) Summary
Reasoning-first SSE streaming
internal/entity/models/upstage.go
ChatStreamlyWithSender's SSE loop now detects non-empty delta.reasoning strings and emits them via sender(nil, &r) before delta.content chunks. Terminal condition handling and [DONE] marker emission remain unchanged.
Reasoning streaming test coverage
internal/entity/models/upstage_test.go
Three new tests validate: (1) reasoning chunks are extracted and accumulated alongside content, (2) reasoning callback fires before content within a single SSE delta, (3) streams without reasoning still work and don't trigger spurious reasoning callbacks.

Sequence Diagram

sequenceDiagram
  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)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#14819: Extends UpstageModel ChatStreamlyWithSender with reasoning-aware SSE handling in the same upstage.go/test files.
  • infiniflow/ragflow#14550: Implements reasoning-first SSE delta forwarding in another model driver's streaming handler.
  • infiniflow/ragflow#14605: Adds reasoning field extraction to streaming SSE parsing with reasoning before content ordering.

Suggested labels

💞 feature, ci, size:L

Suggested reviewers

  • Haruko386

Poem

🐰 A rabbit hops through Solar streams,
Finds reasoning first in delta dreams,
Before the content takes the stage,
Each chunk arrives in proper page.
Tests ensure the order's right—
Reasoning shines, then content bright! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: extracting reasoning delta from Upstage streaming responses, which is the primary focus of this PR.
Description check ✅ Passed The PR description comprehensively addresses the required template sections with detailed problem context, type classification, testing evidence, and implementation details.
Linked Issues check ✅ Passed The PR fully implements the feature requested in #14816: adds UpstageModel driver with all required methods (ChatWithMessages, ChatStreamlyWithSender, ListModels, CheckConnection, etc.) and integrates it via factory.go.
Out of Scope Changes check ✅ Passed All changes are within scope: two files modified (upstage.go and upstage_test.go) implement the reasoning delta extraction feature directly related to #14816's Upstage driver requirements, with no unrelated alterations.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.

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

📥 Commits

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

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

Comment thread internal/entity/models/upstage.go Resolved
Comment thread internal/entity/models/upstage.go Resolved
@tmimmanuel tmimmanuel mentioned this pull request May 12, 2026
1 task done
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
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.
@tmimmanuel tmimmanuel mentioned this pull request May 12, 2026
1 task done

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

30-31: ⚡ Quick win

Consider checking errors in test request handlers.

Multiple test handlers silently ignore errors from io.ReadAll and json.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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ba2303 and 3bd705b.

📒 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

JinHai-CN added a commit that referenced this pull request May 12, 2026
### 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]>
@JinHai-CN

Copy link
Copy Markdown
Member

Duplicated with #14819 . I will close it. Please feel free to re-open it, if i am wrong.

@JinHai-CN JinHai-CN closed this May 12, 2026
@JinHai-CN JinHai-CN reopened this May 12, 2026
@tmimmanuel
tmimmanuel force-pushed the go/upstage-driver branch from 3bd705b to 9ec6e3a Compare May 12, 2026 14:50
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 12, 2026
@tmimmanuel tmimmanuel changed the title Go: implement provider: Upstage fix(upstage): extract reasoning delta from streaming responses 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.

🧹 Nitpick comments (1)
internal/entity/models/upstage_test.go (1)

273-423: ⚡ Quick win

Consider adding test coverage for nil sender callback.

The PR objectives mention that a nil-sender guard was added to ChatStreamlyWithSender to 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3bd705b and 9ec6e3a.

📒 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

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

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

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

Copy link
Copy Markdown
Contributor Author

@Haruko386 thanks for pushing back on this — I went and ran live tests against api.upstage.ai to settle the question. The reasoning field does exist in responses; it's just not in the OpenAPI schema section of the doc page you linked. The relevant prose is in the same page's reasoning_effort description (search for "When reasoning is ON"):

"When reasoning is ON (`high` or `medium`) for `solar-pro3`, the response includes a `reasoning` field with the model's thought process."
— https://console.upstage.ai/api/chat (under the reasoning_effort param section)

Live evidence (api.upstage.ai)

1. solar-pro3, non-stream, reasoning_effort: "high" → reasoning is present

Request:

curl -X POST https://api.upstage.ai/v1/chat/completions \
  -H "Authorization: Bearer <KEY>" -H "Content-Type: application/json" \
  -d '{"model":"solar-pro3","messages":[{"role":"user","content":"What is 15% of 80? answer in one short sentence."}],"reasoning_effort":"high","max_tokens":2048}'

Response (pretty-printed):

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "15% of 80 equals 12.",
      "reasoning": "We need to answer: \"What is 15% of 80?\" Provide answer in one short sentence. So answer: \"15% of 80 is 12.\" That's a short sentence."
    },
    "finish_reason": "stop"
  }]
}

The message.reasoning field is 132 chars long, present, populated.

2. solar-pro3, non-stream, reasoning_effort: "minimal" → reasoning is absent (control)

{"choices":[{"message":{"role":"assistant","content":"4"},"finish_reason":"stop",...}]}

message.reasoning is correctly missing — proves the field only appears when reasoning is on.

3. solar-pro3, streaming, reasoning_effort: "high" → delta.reasoning chunks before delta.content

The exact case this PR exists to handle. First 12 deltas verbatim from the wire:

data: {"choices":[{"delta":{"role":"assistant"}, ...}]}
data: {"choices":[{"delta":{"reasoning":"The"}, ...}]}
data: {"choices":[{"delta":{"reasoning":" user"}, ...}]}
data: {"choices":[{"delta":{"reasoning":" asks"}, ...}]}
data: {"choices":[{"delta":{"reasoning":" \""}, ...}]}
data: {"choices":[{"delta":{"reasoning":"2"}, ...}]}
data: {"choices":[{"delta":{"reasoning":"+"}, ...}]}
data: {"choices":[{"delta":{"reasoning":"2"}, ...}]}
data: {"choices":[{"delta":{"reasoning":"?"}, ...}]}
data: {"choices":[{"delta":{"reasoning":" single"}, ...}]}
data: {"choices":[{"delta":{"reasoning":" number"}, ...}]}
data: {"choices":[{"delta":{"reasoning":"\"."}, ...}]}
...
data: {"choices":[{"delta":{"content":"4"}, "finish_reason":null}]}
data: {"choices":[{"delta":{}, "finish_reason":"stop"}]}
data: [DONE]

122 SSE lines total. The set of distinct delta keys observed: ['content', 'reasoning', 'role']. There is no reasoning_content — it's named reasoning (singular, no _content suffix), distinct from LongCat / DeepSeek / OpenAI-o1.

Without this PR, every one of those delta.reasoning chunks gets dropped on the floor in ChatStreamlyWithSender, and a tenant chatting with solar-pro3 sees only the final answer with no visible thinking — even though they paid the reasoning tokens.

4. solar-pro2, non-stream, reasoning_effort: "high" → reasoning is internal, not in response

{"choices":[{"message":{"role":"assistant","content":"\n\n15% of 80 is 12."},"finish_reason":"stop",...}]}

message.reasoning absent. So the docs are accurate when they scope the response field to solar-pro3 specifically — solar-pro2 with high does reason internally but doesn't surface a separate field. The driver code already handles both cases (no-op when the field is absent).

What stays

The current PR diff is doing the right thing — it adds delta.reasoning extraction to mirror the existing message.reasoning extraction on the non-stream path. Both shapes are now confirmed by the live API.

Happy to add a docstring pointer to the prose quote above if it helps future readers find the citation in the docs.

@tmimmanuel
tmimmanuel requested a review from Haruko386 May 13, 2026 04:50

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

@tmimmanuel LGTM
Thank your for your contribution

@JinHai-CN JinHai-CN added the ci Continue Integration label May 14, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 14, 2026 01:47
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 14, 2026 01:47
@codecov

codecov Bot commented May 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (5a5bbee) to head (33c7c44).

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

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

@JinHai-CN
ready to merge

@tmimmanuel
tmimmanuel force-pushed the go/upstage-driver branch from 9ec6e3a to 6a28ebc Compare May 14, 2026 17:37
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels May 14, 2026
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.
@tmimmanuel
tmimmanuel force-pushed the go/upstage-driver branch from 6a28ebc to 33c7c44 Compare May 14, 2026 18:42
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels May 14, 2026
@JinHai-CN
JinHai-CN merged commit 02a74d3 into infiniflow:main May 21, 2026
1 check passed
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)
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants