Skip to content

[Go] Add API /api/v1/chat/recommendation and consolidate with /api/v1/searchbots/related_questions - #16500

Merged
wangq8 merged 11 commits into
infiniflow:mainfrom
wangq8:feature/go-add-api-v1-chat-recommendation
Jul 1, 2026
Merged

wangq8 merged 11 commits into
infiniflow:mainfrom
wangq8:feature/go-add-api-v1-chat-recommendation

Conversation

@wangq8

@wangq8 wangq8 commented Jun 30, 2026 •

Copy link
Copy Markdown
Collaborator

Add /api/v1/chat/recommendation and consolidate with /api/v1/searchbots/related_questions
Test /api/v1/chat/recommendation
image
Test /api/v1/searchbots/related_questions
image

@wangq8 wangq8 added the ci Continue Integration label Jun 30, 2026
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 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 adds a new POST /api/v1/chat/recommendation endpoint that generates related questions, moving that logic into a shared service.GenerateRelatedQuestions function used by both the chat and searchbot handlers. It introduces ModelProviderService.Chat/ChatStream and TenantStreamAdapter, replacing handler-local LLM interfaces (chatLLM, ChunkRetriever, streamingLLM, ModelProviderLLM) across chat, search, and searchbot handlers and server wiring, and updates tests accordingly.

Changes

Chat Recommendation & Service Runtime

Layer / File(s) Summary
ModelProviderService chat/streaming wrappers
internal/service/model_chat.go
Adds Chat, ChatStream, chatStreamWithContext, and TenantStreamAdapter for non-streaming and tenant-aware streaming chat calls.
Related-question service logic
internal/service/related_question.go
Implements GenerateRelatedQuestions, search-config/model-ID resolution, llm_setting-to-ChatConfig conversion, and numbered-answer parsing.
Recommendation endpoint and route
internal/handler/chat_recommendation.go, internal/router/router.go
Adds ChatRecommendationRequest, (*ChatHandler).Recommendation, and registers POST /api/v1/chat/recommendation.
Chat/search/server wiring updates
internal/handler/chat.go, internal/handler/mindmap.go, internal/handler/search.go, cmd/server_main.go
Switches handler and server dependencies to *service.ModelProviderService/service.Retriever and service.TenantStreamAdapter.
Searchbot refactor
internal/handler/searchbot.go
Removes local related-question prompt/parsing and LLM adapters, delegates /related_questions to the service, and uses service.TenantStreamAdapter for Ask streaming.
Tests for service wrappers and handlers
internal/service/related_question_test.go, internal/handler/chat_test.go, internal/handler/searchbot_test.go
Adds related-question service tests, removes mindmap/parse-related-question tests, and updates searchbot tests to drop streaming-LLM wiring.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ChatHandler
  participant GenerateRelatedQuestions
  participant ModelProviderService
  Client->>ChatHandler: POST /api/v1/chat/recommendation
  ChatHandler->>GenerateRelatedQuestions: tenantID, question, search_id
  GenerateRelatedQuestions->>ModelProviderService: Chat(system + user messages)
  ModelProviderService-->>GenerateRelatedQuestions: ChatResponse
  GenerateRelatedQuestions-->>ChatHandler: []string questions
  ChatHandler-->>Client: success response
Loading
sequenceDiagram
  participant SearchBotHandler
  participant TenantStreamAdapter
  participant ModelProviderService
  participant ModelDriver
  SearchBotHandler->>TenantStreamAdapter: ChatStream(ctx, messages, config)
  TenantStreamAdapter->>ModelProviderService: ChatStream(ctx, tenantID, modelID, messages, config)
  ModelProviderService->>ModelDriver: ChatStreamlyWithSender
  ModelDriver-->>TenantStreamAdapter: streamed deltas
  TenantStreamAdapter-->>SearchBotHandler: chan string
Loading

Possibly related PRs

  • infiniflow/ragflow#16443: Both PRs modify internal/handler/searchbot.go's SearchBotHandler wiring/types for llm/chunkSvc, directly affecting the same handler and adapters.

Suggested labels: 💞 feature, ☯️ refactor

Suggested reviewers: Haruko386

Poem

A rabbit hops through service seams,
Weaving chat streams into dreams,
No more local LLMs to bind—
One shared path for every mind. 🐇
Recommendations bloom anew,
Numbered questions, one, two, two-and-two!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.45% 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 clearly states the new recommendation API and its consolidation with related_questions.
Description check ✅ Passed The description includes a concise summary and test screenshots, with only the requested background context missing.
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.

@wangq8 wangq8 changed the title [Go] Add API /api/v1/chat/recommendation [Go] Add API /api/v1/chat/recommendation and consolidate with /api/v1/searchbots/related_questions Jun 30, 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: 1

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

Inline comments:
In `@internal/handler/chat_recommendation.go`:
- Around line 136-139: The recommendation config builder is incorrectly
inheriting the search `stream` flag, which can push `getRecommendationConfig`
into streaming mode even though `llm.Chat(...)` expects a non-streaming
response. Update the `chat_recommendation.go` config handling so the `"stream"`
case is not forwarded into the recommendation `cfg`, and keep
`getRecommendationConfig`/`generateRecommendations` on a non-streaming path that
always yields a parseable `response.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: 958b6ae3-ca80-410c-99f4-63eb8f73128d

📥 Commits

Reviewing files that changed from the base of the PR and between 3c946a7 and d178aac.

📒 Files selected for processing (4)
  • internal/handler/chat_recommendation.go
  • internal/handler/chat_test.go
  • internal/handler/searchbot.go
  • internal/router/router.go

Comment thread internal/handler/chat_recommendation.go Resolved
@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (45fc7fe) to head (226a1d9).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16500      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

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

🧹 Nitpick comments (3)
internal/service/related_question_test.go (2)

42-57: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert non-nil empty slices here.

These cases currently only prove “zero length.” Because the recommendation endpoint serializes this slice directly, a future regression from []string{} to nil would silently change the response shape from [] to null without these tests catching it. Add if got == nil { ... } alongside the length check.

🤖 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/related_question_test.go` around lines 42 - 57, The tests in
parseRelatedQuestions only assert zero length, so they can miss a regression
where the function returns a nil slice instead of an empty one. Update
TestParseRelatedQuestionsEmpty and TestParseRelatedQuestionsNoNumberedLines to
also assert that the result from parseRelatedQuestions is non-nil, while keeping
the existing length checks, so the behavior stays an empty slice rather than
null in the recommendation response.

5-20: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a test for the default llm_setting branch.

This covers the populated-config path well, but it leaves the fallback contract untested: relatedQuestionsConfig returns Temperature = 0.9 when llm_setting is absent. Since both endpoints consume that helper, I’d add one small case to pin the default behavior too.

🤖 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/related_question_test.go` around lines 5 - 20, Add a new
test case in relatedQuestionsConfig to cover the default llm_setting fallback
path when the key is absent. Use the existing
TestRelatedQuestionsConfigSkipsZeroTopP as the nearby reference, and assert that
relatedQuestionsConfig returns a non-nil config with Temperature set to 0.9 when
the input map does not contain llm_setting. Keep the existing zero top_p
coverage unchanged.
internal/service/related_question.go (1)

205-216: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Optionally trim trailing whitespace/CR from parsed questions.

Lines are split on \n only, so CRLF responses leave a trailing \r on each question, and trailing spaces are preserved. Consider trimming the result to harden against varied LLM output.

♻️ Suggested hardening
 	for _, line := range strings.Split(text, "\n") {
 		if relatedQuestionLineRe.MatchString(line) {
-			result = append(result, relatedQuestionLineRe.ReplaceAllString(line, ""))
+			result = append(result, strings.TrimSpace(relatedQuestionLineRe.ReplaceAllString(line, "")))
 		}
 	}
🤖 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/related_question.go` around lines 205 - 216,
parseRelatedQuestions currently preserves trailing spaces and CR characters when
splitting on newlines, so harden the parser by trimming each extracted question
before appending it to result. Update the parseRelatedQuestions function in
related_question.go to normalize the output from
relatedQuestionLineRe.ReplaceAllString so CRLF and extra whitespace do not leak
into returned questions. Keep the existing matching logic intact and apply the
cleanup right where the question string is collected.
🤖 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/service/related_question_test.go`:
- Around line 42-57: The tests in parseRelatedQuestions only assert zero length,
so they can miss a regression where the function returns a nil slice instead of
an empty one. Update TestParseRelatedQuestionsEmpty and
TestParseRelatedQuestionsNoNumberedLines to also assert that the result from
parseRelatedQuestions is non-nil, while keeping the existing length checks, so
the behavior stays an empty slice rather than null in the recommendation
response.
- Around line 5-20: Add a new test case in relatedQuestionsConfig to cover the
default llm_setting fallback path when the key is absent. Use the existing
TestRelatedQuestionsConfigSkipsZeroTopP as the nearby reference, and assert that
relatedQuestionsConfig returns a non-nil config with Temperature set to 0.9 when
the input map does not contain llm_setting. Keep the existing zero top_p
coverage unchanged.

In `@internal/service/related_question.go`:
- Around line 205-216: parseRelatedQuestions currently preserves trailing spaces
and CR characters when splitting on newlines, so harden the parser by trimming
each extracted question before appending it to result. Update the
parseRelatedQuestions function in related_question.go to normalize the output
from relatedQuestionLineRe.ReplaceAllString so CRLF and extra whitespace do not
leak into returned questions. Keep the existing matching logic intact and apply
the cleanup right where the question string is collected.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5acd6382-b95f-44fb-a969-ce15e736d584

📥 Commits

Reviewing files that changed from the base of the PR and between d178aac and 8a2762e.

📒 Files selected for processing (6)
  • internal/handler/chat_recommendation.go
  • internal/handler/chat_test.go
  • internal/handler/searchbot.go
  • internal/handler/searchbot_test.go
  • internal/service/related_question.go
  • internal/service/related_question_test.go
💤 Files with no reviewable changes (2)
  • internal/handler/chat_test.go
  • internal/handler/searchbot_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/handler/searchbot.go

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 30, 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.

Caution

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

⚠️ Outside diff range comments (1)
internal/handler/searchbot.go (1)

294-299: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard streamLLM before constructing the stream adapter.

NewSearchBotHandler leaves streamLLM unset until SetStreamLLM is called, but Ask only checks askSvc before passing h.streamLLM into TenantStreamAdapter. Mirror SearchHandler.Completion’s explicit "streaming LLM not configured" path to avoid nil-adapter failures.

Proposed fix
 	if h.askSvc == nil {
 		h.sseWriter.Write(c, sseError("ask service not configured"))
 		return
 	}
+	if h.streamLLM == nil {
+		h.sseWriter.Write(c, sseError("streaming LLM not configured"))
+		return
+	}
 	ctx := c.Request.Context()
 	adapter := &service.TenantStreamAdapter{LLM: h.streamLLM, TenantID: user.ID, ModelID: modelID}
🤖 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/handler/searchbot.go` around lines 294 - 299, In Ask, add an
explicit nil check for h.streamLLM before creating the TenantStreamAdapter,
similar to SearchHandler.Completion’s "streaming LLM not configured" handling.
If streamLLM is unset, write the same SSE error and return before constructing
the adapter; keep the existing askSvc guard and only build TenantStreamAdapter
after both dependencies are confirmed.
🧹 Nitpick comments (1)
internal/service/search_runtime.go (1)

151-156: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Use errors.Is for context-error detection.

Direct equality (err == context.Canceled) misses wrapped errors. If ChatStreamlyWithSender returns a wrapped context error (e.g. via fmt.Errorf("...: %w", ctx.Err())), this branch won't match and a spurious warning is logged on normal client cancellation.

♻️ Proposed fix
 			}); err != nil {
-			if err == context.Canceled || err == context.DeadlineExceeded {
+			if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
 				return
 			}
 			common.Warn("ChatStreamlyWithSender returned error", zap.Error(err))

Add "errors" to the import block.

Please confirm whether ChatStreamlyWithSender (and underlying drivers) wrap or return the raw context error.

🤖 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/search_runtime.go` around lines 151 - 156, The
context-cancellation check in the `ChatStreamlyWithSender` error handling branch
is using direct equality, which can miss wrapped context errors and trigger a
false warning. Update the `search_runtime.go` error path to use `errors.Is`
against `context.Canceled` and `context.DeadlineExceeded`, and add the `errors`
import so wrapped errors from `ChatStreamlyWithSender` and its underlying
drivers are handled correctly.
🤖 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/handler/searchbot.go`:
- Around line 294-299: In Ask, add an explicit nil check for h.streamLLM before
creating the TenantStreamAdapter, similar to SearchHandler.Completion’s
"streaming LLM not configured" handling. If streamLLM is unset, write the same
SSE error and return before constructing the adapter; keep the existing askSvc
guard and only build TenantStreamAdapter after both dependencies are confirmed.

---

Nitpick comments:
In `@internal/service/search_runtime.go`:
- Around line 151-156: The context-cancellation check in the
`ChatStreamlyWithSender` error handling branch is using direct equality, which
can miss wrapped context errors and trigger a false warning. Update the
`search_runtime.go` error path to use `errors.Is` against `context.Canceled` and
`context.DeadlineExceeded`, and add the `errors` import so wrapped errors from
`ChatStreamlyWithSender` and its underlying drivers are handled correctly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 62b0b4fd-f0ca-4802-8639-d1927d1bf027

📥 Commits

Reviewing files that changed from the base of the PR and between 8a2762e and c2c91e3.

📒 Files selected for processing (9)
  • cmd/server_main.go
  • internal/handler/chat.go
  • internal/handler/chat_test.go
  • internal/handler/mindmap.go
  • internal/handler/search.go
  • internal/handler/searchbot.go
  • internal/handler/searchbot_test.go
  • internal/service/related_question.go
  • internal/service/search_runtime.go

@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

🧹 Nitpick comments (2)
internal/handler/searchbot_test.go (1)

494-511: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

SSE write-deadline test coverage dropped without replacement.

TestAskHandler_DisablesWriteDeadlineForSSE and its setupAskHandlerTenantDB scaffolding were removed along with the GORM/SQLite-backed tenant setup, but no equivalent test verifying that SSE responses disable the write deadline was reintroduced using the new mock-based handler construction. This leaves that behavior untested going forward.

🤖 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/handler/searchbot_test.go` around lines 494 - 511, Restore test
coverage for SSE write-deadline behavior by adding a new test around
AskHandler’s SSE path that verifies the response disables the write deadline,
using the current mock-based SearchBotHandler setup instead of the removed
GORM/SQLite tenant scaffolding. Recreate the intent of
TestAskHandler_DisablesWriteDeadlineForSSE by exercising h.Ask with an SSE
request and asserting the writer/response no longer has a write deadline. Keep
the helper setup minimal and aligned with the existing fakeChunkRetriever and
cw-based test pattern so the behavior remains covered after the handler
construction changes.
internal/handler/search.go (1)

481-484: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead fallback branch.

h.sseWriter is now always populated in NewSearchHandler (line 43), so this nil-check is unreachable unless SearchHandler is constructed via a bare struct literal bypassing the constructor. Harmless, but worth trimming or documenting why it's kept as a defensive guard.

🤖 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/handler/search.go` around lines 481 - 484, The nil fallback in
SearchHandler’s SSE writer selection is dead code because NewSearchHandler now
always sets h.sseWriter; either remove the unreachable nil-check in the search
flow or add a brief comment in SearchHandler / NewSearchHandler explaining that
the guard is intentionally defensive for struct-literal construction. Keep the
logic centered around h.sseWriter and ginSSEWriter so the intent stays clear.
🤖 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/model_chat.go`:
- Line 55: The streaming path in chatStreamWithContext is forwarding driver
chunks too early, which allows a plain “[DONE]” token to be treated as answer
text by AskService/StreamThinkTagDelta. Update chatStreamWithContext to detect
and drop any terminal “[DONE]” delta before sending it on case ch <- *delta,
while still forwarding normal non-nil deltas unchanged.

---

Nitpick comments:
In `@internal/handler/search.go`:
- Around line 481-484: The nil fallback in SearchHandler’s SSE writer selection
is dead code because NewSearchHandler now always sets h.sseWriter; either remove
the unreachable nil-check in the search flow or add a brief comment in
SearchHandler / NewSearchHandler explaining that the guard is intentionally
defensive for struct-literal construction. Keep the logic centered around
h.sseWriter and ginSSEWriter so the intent stays clear.

In `@internal/handler/searchbot_test.go`:
- Around line 494-511: Restore test coverage for SSE write-deadline behavior by
adding a new test around AskHandler’s SSE path that verifies the response
disables the write deadline, using the current mock-based SearchBotHandler setup
instead of the removed GORM/SQLite tenant scaffolding. Recreate the intent of
TestAskHandler_DisablesWriteDeadlineForSSE by exercising h.Ask with an SSE
request and asserting the writer/response no longer has a write deadline. Keep
the helper setup minimal and aligned with the existing fakeChunkRetriever and
cw-based test pattern so the behavior remains covered after the handler
construction changes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b160ad65-2a45-48f6-9b8c-0be30f2a0aa3

📥 Commits

Reviewing files that changed from the base of the PR and between 226a1d9 and bbd3f65.

📒 Files selected for processing (9)
  • cmd/server_main.go
  • internal/handler/chat.go
  • internal/handler/chat_test.go
  • internal/handler/mindmap.go
  • internal/handler/search.go
  • internal/handler/searchbot.go
  • internal/handler/searchbot_test.go
  • internal/service/model_chat.go
  • internal/service/related_question.go
💤 Files with no reviewable changes (1)
  • internal/handler/chat_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/handler/searchbot.go

return nil
}
select {
case ch <- *delta:

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether service consumers filter provider "[DONE]" sentinels.
rg -n -C3 '\[DONE\]|ChatStream\(|AskDeltaAnswer|AskDeltaFinal' internal/service internal/handler

Repository: infiniflow/ragflow

Length of output: 31012


🏁 Script executed:

#!/bin/bash
sed -n '37,90p' internal/service/model_chat.go
printf '\n---\n'
sed -n '180,230p' internal/service/ask_service.go
printf '\n---\n'
sed -n '529,540p' internal/service/openai_chat.go

Repository: infiniflow/ragflow

Length of output: 3617


🏁 Script executed:

#!/bin/bash
sed -n '1,220p' internal/service/openai_chat.go
printf '\n---\n'
rg -n "StreamThinkTagDelta|isContentDelta|ThinkDeltaText|ThinkDeltaMarker" internal/service -n -C 3

Repository: infiniflow/ragflow

Length of output: 18124


🏁 Script executed:

#!/bin/bash
sed -n '1,220p' internal/service/think_tag.go

Repository: infiniflow/ragflow

Length of output: 6491


Drop [DONE] before forwarding stream chunks. chatStreamWithContext passes every non-nil delta through, and AskService/StreamThinkTagDelta treats plain strings as answer text, so a driver-emitted [DONE] can leak into the final response.

🤖 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/model_chat.go` at line 55, The streaming path in
chatStreamWithContext is forwarding driver chunks too early, which allows a
plain “[DONE]” token to be treated as answer text by
AskService/StreamThinkTagDelta. Update chatStreamWithContext to detect and drop
any terminal “[DONE]” delta before sending it on case ch <- *delta, while still
forwarding normal non-nil deltas unchanged.

@wangq8
wangq8 merged commit 8f24b30 into infiniflow:main Jul 1, 2026
1 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant