Skip to content

fix: add legacy chat/completions mode - #16014

Merged
wangq8 merged 6 commits into
infiniflow:mainfrom
buua436:b076
Jun 16, 2026
Merged

wangq8 merged 6 commits into
infiniflow:mainfrom
buua436:b076

Conversation

@buua436

@buua436 buua436 commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Adds a legacy mode for /chat/completions that restores v0.23.0-style output by converting start_to_think/end_to_think back into raw markers and streaming cumulative answer text.

Type of change

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

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

session_completion in chat_api.py gains a boolean legacy request flag. When enabled, the SSE streaming loop accumulates incremental answer text and reconstructs <think>...</think> markers by reacting to start_to_think/end_to_think fields, sanitizing each emitted payload via _sanitize_json_floats. The service layer (dialog_service.py) clears the answer field from final response payloads in both async_chat and async_ask to support this streaming reconstruction.

Changes

Legacy SSE streaming mode with answer field handling

Layer / File(s) Summary
Legacy flag parsing and streaming branch
api/apps/restful_apis/chat_api.py
Parses a boolean legacy flag from the request (defaulting to False). Branches the SSE generator: legacy mode accumulates answer deltas, detects start_to_think/end_to_think chunk fields to reconstruct <think>...</think> markers, sanitizes each payload via _sanitize_json_floats, and emits a final chunk on stream completion; non-legacy mode continues emitting pre-formatted chunks directly as before.
Answer field clearing in service responses
api/db/services/dialog_service.py
Both async_chat (streaming mode) and async_ask flows now clear the answer field on their final response payloads immediately before yielding, allowing the API layer to reconstruct answer text from stream deltas in legacy mode.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 A flag called legacy hops into view,
Rebuilding old think-tags, good as new,
Service clears answers, API rebuilds the flow,
Accumulate deltas, sanitize floats, and go,
The rabbit approves — both paths run true! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: add legacy chat/completions mode' is concise and clearly identifies the main change—adding a legacy mode for the chat/completions endpoint.
Description check ✅ Passed The PR description addresses both required template sections: it explains the problem being solved (restoring v0.23.0-style output with markers and cumulative answer streaming) and identifies the change type (Bug Fix).
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.

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

@buua436 buua436 added the ci Continue Integration label Jun 15, 2026
@buua436
buua436 marked this pull request as draft June 15, 2026 05:57
@buua436
buua436 marked this pull request as ready for review June 15, 2026 05:57

@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)
api/apps/restful_apis/chat_api.py (1)

1232-1236: ⚡ Quick win

Add logging when legacy mode is activated.

Per coding guidelines, new flows should include logging. When legacy=True is requested, log this at info/debug level to aid debugging and monitoring of legacy mode usage.

         legacy = _get_bool_request_flag(
             req,
             "legacy",
             default=False,
         )
+        if legacy:
+            logging.debug("Legacy streaming mode enabled for chat completion")
         stream_mode = req.pop("stream", 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 `@api/apps/restful_apis/chat_api.py` around lines 1232 - 1236, After the legacy
variable is assigned by the _get_bool_request_flag call, add a logging statement
that checks if legacy is True and logs an info or debug level message indicating
that legacy mode has been activated. This will provide visibility into when
legacy mode is being used for debugging and monitoring purposes.

Source: Coding guidelines

🤖 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 `@api/apps/restful_apis/chat_api.py`:
- Around line 1232-1236: After the legacy variable is assigned by the
_get_bool_request_flag call, add a logging statement that checks if legacy is
True and logs an info or debug level message indicating that legacy mode has
been activated. This will provide visibility into when legacy mode is being used
for debugging and monitoring purposes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fcc376f6-684c-41a5-b709-ac0b0abea57c

📥 Commits

Reviewing files that changed from the base of the PR and between 400dfd5 and 839d53e.

📒 Files selected for processing (1)
  • api/apps/restful_apis/chat_api.py

@codecov

codecov Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16014   +/-   ##
=======================================
  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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/db/services/dialog_service.py`:
- Line 903: The clearing of the answer field (setting `final["answer"] = ""`) in
the shared service layer of `async_ask` in dialog_service.py affects all
streaming consumers, not just the legacy endpoint, causing non-legacy clients to
receive empty answers. Remove the `final["answer"] = ""` assignment from the
shared service layer in dialog_service.py at line 903, and also at line 1719
where it similarly applies. Then move this clearing/fallback logic into the
legacy endpoint branch in the restful API layer (the
`/chat/completions?legacy=true` endpoint), and have that legacy branch
explicitly emit `legacy_answer` for its final chunk instead of depending on the
shared service to blank the answer.
🪄 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: c3c5b0ae-f96c-4ed5-8ff0-64edab27312e

📥 Commits

Reviewing files that changed from the base of the PR and between 839d53e and a471417.

📒 Files selected for processing (1)
  • api/db/services/dialog_service.py

final = await decorate_answer(_extract_visible_answer(thought + full_answer))
final["final"] = True
final["audio_binary"] = None
final["answer"] = ""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep legacy response shaping out of the shared service layer.

Both changes discard the fully decorated final answer for every streaming consumer, not just /chat/completions?legacy=true. async_ask is forwarded directly by api/apps/restful_apis/bot_api.py and api/apps/restful_apis/search_api.py, and non-legacy session_completion also streams formatted chunks unchanged, so clients that rely on the final event now receive answer: "".

Move the clearing/fallback behavior into the legacy endpoint branch instead, and keep these service payloads complete.

Suggested service-side rollback
 final = await decorate_answer(_extract_visible_answer(thought + full_answer))
 final["final"] = True
 final["audio_binary"] = None
-final["answer"] = ""
 yield final
 final = await decorate_answer(_extract_visible_answer(full_answer))
 final["final"] = True
-final["answer"] = ""
 yield final

Then have the legacy /chat/completions branch emit legacy_answer explicitly for its final chunk rather than depending on shared services to blank the answer.

Also applies to: 1719-1719

🤖 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 `@api/db/services/dialog_service.py` at line 903, The clearing of the answer
field (setting `final["answer"] = ""`) in the shared service layer of
`async_ask` in dialog_service.py affects all streaming consumers, not just the
legacy endpoint, causing non-legacy clients to receive empty answers. Remove the
`final["answer"] = ""` assignment from the shared service layer in
dialog_service.py at line 903, and also at line 1719 where it similarly applies.
Then move this clearing/fallback logic into the legacy endpoint branch in the
restful API layer (the `/chat/completions?legacy=true` endpoint), and have that
legacy branch explicitly emit `legacy_answer` for its final chunk instead of
depending on the shared service to blank the answer.

@buua436
buua436 marked this pull request as draft June 15, 2026 09:24
@buua436
buua436 marked this pull request as ready for review June 15, 2026 09:24
@buua436
buua436 marked this pull request as draft June 15, 2026 09:34
@buua436
buua436 marked this pull request as ready for review June 15, 2026 09:34
@buua436
buua436 marked this pull request as draft June 15, 2026 11:20
@buua436
buua436 marked this pull request as ready for review June 15, 2026 11:20
@wangq8
wangq8 merged commit 8e235b7 into infiniflow:main Jun 16, 2026
1 of 4 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 16, 2026
1 task done
Harry-Hz-Zhang pushed a commit to Harry-Hz-Zhang/ragflow that referenced this pull request Jun 17, 2026
### What problem does this PR solve?
Adds a legacy mode for /chat/completions that restores v0.23.0-style
output by converting start_to_think/end_to_think back into raw
<think></think> markers and streaming cumulative answer text.

### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
This was referenced Jul 13, 2026
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 🌈 python Pull requests that update Python code size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants