Skip to content

Fix chat thinking & Figure issue in GO - #16558

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
qinling0210:fix_chat_thinking
Jul 2, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
qinling0210:fix_chat_thinking

Conversation

@qinling0210

Copy link
Copy Markdown
Contributor

Summary

Fix chat thinking & Figure issue

@qinling0210 qinling0210 self-assigned this Jul 2, 2026
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bc607cb1-b0ff-415c-acca-298a03634d04

📥 Commits

Reviewing files that changed from the base of the PR and between 138bb85 and 116680c.

📒 Files selected for processing (1)
  • internal/agent/component/llm.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/agent/component/llm.go

📝 Walkthrough

Walkthrough

Updates LLM request/response handling, reasoning-state streaming, reference chunk normalization, and SSE answer chunk fields to carry start/end reasoning signals.

Changes

Think-tag cleanup and reasoning-state streaming

Layer / File(s) Summary
LLM thinking toggle and output cleaning
internal/agent/component/llm.go
Maps Thinking into provider chatCfg.Thinking and cleans formatted answer text before returning JSON or structured output.
Reasoning state tracking
internal/service/think_tag.go
Adds inReasoning state and enter/exit transitions for model-level reasoning mode.
AsyncChat reasoning/answer state streaming
internal/service/chat_pipeline.go
Replaces marker-based think handling with state-based routing in AsyncChat, including start/end reasoning events and final flush handling.
AsyncChatSolo reasoning/answer state streaming
internal/service/chat_pipeline.go
Applies the same reasoning-state routing, buffering, and end-of-thinking emission to AsyncChatSolo.
Chunk reference formatting
internal/service/chat_pipeline.go
Normalizes backend chunk maps to frontend field names and applies the formatter when building answer references.
SSE chunk schema and streaming output
internal/service/chat_session.go
Adds start_to_think and end_to_think to SSE answer chunks and updates non-legacy streaming output for final versus delta events.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Model as LLM Provider
  participant ChatPipelineService
  participant ThinkStreamState
  participant ChatSession
  participant Client

  Model->>ChatPipelineService: streamed delta
  ChatPipelineService->>ThinkStreamState: EnterReasoning() / ExitReasoning()
  ChatPipelineService->>ChatSession: StartToThink / EndToThink
  ChatPipelineService->>ChatSession: delta or final chunk
  ChatSession->>Client: SSE data event
Loading

Possibly related PRs

Suggested reviewers: Haruko386

Poem

A rabbit hopped through think and stream,
Then cleaned the fence around the dream 🐇
Start, end, and chunks all line in place,
With tidy fields and quieter pace.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description only repeats the title and lacks the requested background context in the Summary section. Expand the Summary with the problem being fixed, relevant context, and a brief note on the implemented changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main themes in the changes: chat thinking and Figure-related handling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

@qinling0210
qinling0210 marked this pull request as ready for review July 2, 2026 05:36
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 2, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/agent/component/llm.go (1)

537-550: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Parse json_output from the cleaned response.

Line 539 normalizes fenced/think-prefixed JSON into cleaned, but Line 550 still unmarshals resp.Content, so out["json"] is omitted even when "content" now contains valid JSON.

Proposed fix
-		if err := json.Unmarshal([]byte(resp.Content), &parsed); err == nil {
+		if err := json.Unmarshal([]byte(cleaned), &parsed); err == nil {
🤖 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/agent/component/llm.go` around lines 537 - 550, The JSON parsing in
the response assembly is still using resp.Content instead of the normalized
cleaned value, so json_output can be dropped after formatting cleanup. Update
the p.JSONOutput branch in the llm response handling to unmarshal the cleaned
response content (the same value assigned to out["content"]) and keep the
existing fallback behavior if parsing fails. Use the cleaned variable and the
json_output logic in the llm.go response builder to locate the fix.
🤖 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/service/chat_pipeline.go`:
- Around line 1105-1117: Keep ThinkStreamState synchronized with inReasoning in
the chat pipeline: the reasoning branch currently streams deltas without
updating thinkState.fullText with the matching <think>/<think> markers, and the
stream can finish while inReasoning is still true so EndToThink is never
emitted. Add shared enter/exit helpers around the reasoning transitions in the
ChatPipeline flow (the blocks using NextThinkDelta, inReasoning, and thinkState)
to append the proper markers when reasoning starts/ends, and make sure the
post-driver final flush closes any still-open reasoning state before returning
the last result.

In `@internal/service/chat_session.go`:
- Around line 1951-1952: The think-marker flags in sseAnswerChunk are always
being serialized by sseMarshalChunk, which causes false values to appear in the
SSE payload instead of being omitted. Update the StartToThink and EndToThink
JSON tags to use omitempty so the SSE shape matches the existing async chat
fields, and verify the serialization path in sseMarshalChunk still emits only
set markers.

---

Outside diff comments:
In `@internal/agent/component/llm.go`:
- Around line 537-550: The JSON parsing in the response assembly is still using
resp.Content instead of the normalized cleaned value, so json_output can be
dropped after formatting cleanup. Update the p.JSONOutput branch in the llm
response handling to unmarshal the cleaned response content (the same value
assigned to out["content"]) and keep the existing fallback behavior if parsing
fails. Use the cleaned variable and the json_output logic in the llm.go response
builder to locate the fix.
🪄 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: a850d851-f10e-495e-a422-fc7415e047d6

📥 Commits

Reviewing files that changed from the base of the PR and between a67026f and 5f0228a.

📒 Files selected for processing (3)
  • internal/agent/component/llm.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_session.go

Comment thread internal/service/chat_pipeline.go Resolved
Comment thread internal/service/chat_session.go Resolved

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/service/chat_pipeline.go (2)

4093-4102: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Format SQL chunks after metadata enrichment.

buildSQLReference now converts backend keys like doc_id / kb_id to frontend keys before AsyncChat re-reads reference["chunks"] for metadata enrichment. That caller checks backend-shaped fields such as kb_id, so SQL references can lose metadata or multi-KB disambiguation. Return raw chunks here, then apply chunksFormat immediately before emitting the final SQL result after enrichment.

🧩 Proposed direction
-		ref["chunks"] = chunksFormat(chunks)
+		ref["chunks"] = chunks
@@
-			ref["chunks"] = chunksFormat(chunks)
+			ref["chunks"] = chunks

Then format ans["reference"]["chunks"] after the enrichment block and just before sending the SQL AsyncChatResult.

🤖 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/service/chat_pipeline.go` around lines 4093 - 4102,
`buildSQLReference` is formatting `chunks` too early, which prevents `AsyncChat`
from finding backend-shaped metadata fields like `kb_id` and `doc_id` during
enrichment. Change `buildSQLReference` to return raw chunks for SQL references,
then apply `chunksFormat` later in the `AsyncChat` flow after the metadata
enrichment block and immediately before emitting the final SQL
`AsyncChatResult`, using the existing `buildSQLReference`, `AsyncChat`, and
`chunksFormat` symbols to place the fix.

1117-1123: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not synthesize TTS for reasoning deltas.

These branches are inside model reasoning, but they produce AudioBinary from reasoning text. With TTS enabled, clients can play reasoning audio; the tool-stream path already keeps reasoning audio nil. Reserve TTS for answer deltas after EndToThink.

🔇 Proposed fix
-										AudioBinary: s.synthesizeTTS(ttsModel, d.Value),
+										AudioBinary: nil,

Apply the same change to the reasoning flushes before emitting EndToThink.

Also applies to: 1131-1139, 1434-1440, 1448-1456

🤖 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/service/chat_pipeline.go` around lines 1117 - 1123, Reasoning deltas
in the ThinkDeltaText branches are still being passed to s.synthesizeTTS and
emitted as AudioBinary. Update the reasoning paths in chat_pipeline.go,
including the flushes before EndToThink, so AsyncChatResult for reasoning text
keeps AudioBinary nil and only answer deltas after EndToThink invoke TTS. Use
the existing ThinkDeltaText and EndToThink flow to locate and mirror the
tool-stream behavior.
🤖 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.

Outside diff comments:
In `@internal/service/chat_pipeline.go`:
- Around line 4093-4102: `buildSQLReference` is formatting `chunks` too early,
which prevents `AsyncChat` from finding backend-shaped metadata fields like
`kb_id` and `doc_id` during enrichment. Change `buildSQLReference` to return raw
chunks for SQL references, then apply `chunksFormat` later in the `AsyncChat`
flow after the metadata enrichment block and immediately before emitting the
final SQL `AsyncChatResult`, using the existing `buildSQLReference`,
`AsyncChat`, and `chunksFormat` symbols to place the fix.
- Around line 1117-1123: Reasoning deltas in the ThinkDeltaText branches are
still being passed to s.synthesizeTTS and emitted as AudioBinary. Update the
reasoning paths in chat_pipeline.go, including the flushes before EndToThink, so
AsyncChatResult for reasoning text keeps AudioBinary nil and only answer deltas
after EndToThink invoke TTS. Use the existing ThinkDeltaText and EndToThink flow
to locate and mirror the tool-stream behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6a096c70-4cd9-4476-b252-691c159073b9

📥 Commits

Reviewing files that changed from the base of the PR and between 5f0228a and 138bb85.

📒 Files selected for processing (4)
  • internal/agent/component/llm.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_session.go
  • internal/service/think_tag.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/agent/component/llm.go
  • internal/service/chat_session.go

@qinling0210 qinling0210 added the ci Continue Integration label Jul 2, 2026
@qinling0210
qinling0210 marked this pull request as draft July 2, 2026 06:48
@qinling0210
qinling0210 marked this pull request as ready for review July 2, 2026 06:48
@qinling0210 qinling0210 changed the title Fix chat thinking & Figure issue Fix chat thinking & Figure issue in GO Jul 2, 2026
@coderabbitai

coderabbitai Bot commented Jul 2, 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

Updates LLM thinking config and answer cleanup, adds reasoning-state streaming signals, normalizes reference chunks, and extends SSE answer chunks with start/end reasoning flags.

Changes

Think-tag cleanup and reasoning-state streaming

Layer / File(s) Summary
LLM thinking toggle and output cleaning
internal/agent/component/llm.go
Maps Thinking into provider chatCfg.Thinking and cleans formatted answer text before returning JSON or structured output.
Reasoning state tracking
internal/service/think_tag.go
Adds inReasoning state and enter/exit transitions for model-level reasoning mode.
AsyncChat reasoning/answer state streaming
internal/service/chat_pipeline.go
Replaces marker-based think handling with state-based routing in AsyncChat, including start/end reasoning events and final flush handling.
AsyncChatSolo reasoning/answer state streaming
internal/service/chat_pipeline.go
Applies the same reasoning-state routing, buffering, and end-of-thinking emission to AsyncChatSolo.
Chunk reference formatting
internal/service/chat_pipeline.go, internal/service/chat_pipeline_test.go
Normalizes backend chunk maps to frontend field names and updates the SQL reference test to assert dataset_id.
SSE chunk schema and streaming output
internal/service/chat_session.go
Adds start_to_think and end_to_think to SSE answer chunks and updates non-legacy streaming output for final versus delta events.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ChatPipelineService
  participant ThinkStreamState
  participant ChatCompletions
  participant Client
  ChatPipelineService->>ThinkStreamState: EnterReasoning() / ExitReasoning()
  ChatPipelineService->>ChatCompletions: StartToThink / EndToThink / answer delta
  ChatCompletions->>Client: SSE data event
Loading

Possibly related PRs

Suggested labels: 🐞 bug

Suggested reviewers: Haruko386, JinHai-CN, yuzhichang

Poem

A rabbit hopped through think and stream,
Then cleaned the fence around the dream 🐇
Start, end, and chunks all line in place,
With tidy fields and quieter pace.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main theme of the changes, especially chat thinking handling, though the Figure part is less clear.
Description check ✅ Passed The description includes the required Summary section and is aligned with the PR's purpose.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

@codecov

codecov Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (c8cf0c9) to head (d9efb58).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16558   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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.

@qinling0210
qinling0210 marked this pull request as draft July 2, 2026 09:42
@qinling0210
qinling0210 marked this pull request as ready for review July 2, 2026 09:42
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 2, 2026
@JinHai-CN
JinHai-CN merged commit 24118ac into infiniflow:main Jul 2, 2026
3 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
### Summary

Fix chat thinking & Figure issue
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
### Summary

Fix chat thinking & Figure issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants