Repository navigation
[Go] Add API /api/v1/chat/recommendation and consolidate with /api/v1/searchbots/related_questions - #16500
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds a new ChangesChat Recommendation & Service Runtime
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
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…m:wangq8/ragflow into feature/go-add-api-v1-chat-recommendation
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
internal/handler/chat_recommendation.gointernal/handler/chat_test.gointernal/handler/searchbot.gointernal/router/router.go
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 Nitpick comments (3)
internal/service/related_question_test.go (2)
42-57: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAssert non-
nilempty slices here.These cases currently only prove “zero length.” Because the recommendation endpoint serializes this slice directly, a future regression from
[]string{}tonilwould silently change the response shape from[]tonullwithout these tests catching it. Addif 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 winAdd a test for the default
llm_settingbranch.This covers the populated-config path well, but it leaves the fallback contract untested:
relatedQuestionsConfigreturnsTemperature = 0.9whenllm_settingis 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 valueOptionally trim trailing whitespace/CR from parsed questions.
Lines are split on
\nonly, so CRLF responses leave a trailing\ron 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
📒 Files selected for processing (6)
internal/handler/chat_recommendation.gointernal/handler/chat_test.gointernal/handler/searchbot.gointernal/handler/searchbot_test.gointernal/service/related_question.gointernal/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
There was a problem hiding this comment.
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 winGuard
streamLLMbefore constructing the stream adapter.
NewSearchBotHandlerleavesstreamLLMunset untilSetStreamLLMis called, butAskonly checksaskSvcbefore passingh.streamLLMintoTenantStreamAdapter. MirrorSearchHandler.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 winUse
errors.Isfor context-error detection.Direct equality (
err == context.Canceled) misses wrapped errors. IfChatStreamlyWithSenderreturns a wrapped context error (e.g. viafmt.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
📒 Files selected for processing (9)
cmd/server_main.gointernal/handler/chat.gointernal/handler/chat_test.gointernal/handler/mindmap.gointernal/handler/search.gointernal/handler/searchbot.gointernal/handler/searchbot_test.gointernal/service/related_question.gointernal/service/search_runtime.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/handler/searchbot_test.go (1)
494-511: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSSE write-deadline test coverage dropped without replacement.
TestAskHandler_DisablesWriteDeadlineForSSEand itssetupAskHandlerTenantDBscaffolding 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 valueDead fallback branch.
h.sseWriteris now always populated inNewSearchHandler(line 43), so this nil-check is unreachable unlessSearchHandleris 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
📒 Files selected for processing (9)
cmd/server_main.gointernal/handler/chat.gointernal/handler/chat_test.gointernal/handler/mindmap.gointernal/handler/search.gointernal/handler/searchbot.gointernal/handler/searchbot_test.gointernal/service/model_chat.gointernal/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: |
There was a problem hiding this comment.
🎯 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/handlerRepository: 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.goRepository: 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 3Repository: infiniflow/ragflow
Length of output: 18124
🏁 Script executed:
#!/bin/bash
sed -n '1,220p' internal/service/think_tag.goRepository: 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.
Add /api/v1/chat/recommendation and consolidate with /api/v1/searchbots/related_questions


Test /api/v1/chat/recommendation
Test /api/v1/searchbots/related_questions