Repository navigation
feat(go-api): add RAG retrieval to chat completions - #15739
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:
📝 WalkthroughWalkthroughInjects KB/retrieval/metadata/doc-engine interfaces into ChatSessionService, threads userID through async chat, implements KB-backed retrieval (streaming and non-streaming) with metadata filtering and knowledge injection, adds NoMatchDocIDSentinel, and adds tests plus a GetRerankModel helper. ChangesKnowledge Base Retrieval in Chat Sessions
Sequence DiagramsequenceDiagram
participant Client
participant ChatSessionService
participant RetrievalService
participant KnowledgebaseStore
participant ModelProvider
participant DocEngine
Client->>ChatSessionService: Completion(userID, messages, kbIDs)
ChatSessionService->>ChatSessionService: asyncChat(userID, messages, kbIDs)
alt Has Knowledge Bases
ChatSessionService->>KnowledgebaseStore: LoadKBs(kbIDs, userID)
KnowledgebaseStore-->>ChatSessionService: KBs (tenant info, embedding model)
ChatSessionService->>RetrievalService: Retrieval(question, docIDs, embeddingModel, rerankModel)
RetrievalService-->>ChatSessionService: chunks
ChatSessionService->>DocEngine: ExpandParentChunks(chunks)
DocEngine-->>ChatSessionService: expandedChunks
ChatSessionService->>ModelProvider: Chat(messages with injected knowledge)
ModelProvider-->>ChatSessionService: response + references
else No Knowledge or Tavily-only
ChatSessionService->>ModelProvider: Chat(messages without retrieval)
ModelProvider-->>ChatSessionService: response
end
ChatSessionService-->>Client: answer + references
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ 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. Comment |
|
Hi @Haruko386 @JinHai-CN this is ready for review 👍 |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/service/chat_session.go (1)
727-731: 💤 Low valueConsider using a named constant for the empty filter sentinel.
The magic string
"-999"used as a sentinel to indicate "no documents match the filter" would benefit from being a named constant for clarity and maintainability.♻️ Suggested constant definition
+// emptyFilterSentinel is a doc ID that matches no documents, used to short-circuit +// retrieval when metadata filtering excludes all documents. +const emptyFilterSentinel = "-999" + func (s *ChatSessionService) filteredDocIDsForDialog(ctx context.Context, dialog *entity.Chat, kbIDs []string, question string, baseDocIDs []string) ([]string, error) {if empty { - return []string{"-999"}, nil + return []string{emptyFilterSentinel}, 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/service/chat_session.go` around lines 727 - 731, Replace the magic sentinel string "-999" with a named constant (e.g., EmptyFilterSentinel or NoMatchSentinel) to make intent clear: define the constant near related code or in a package-level const block, update the return in the conditional inside the function where ApplyMetaDataFilter is handled (the block that currently returns []string{"-999"}) to return []string{EmptyFilterSentinel}, and search for other places that compare to "-999" (or rely on that sentinel) and update them to use the new constant so all sentinel comparisons and returns use the named symbol.internal/service/chat_session_test.go (1)
294-294: 💤 Low valueConsider checking json.Marshal errors explicitly in test setup.
While marshaling these simple test structures will never fail in practice, explicitly checking the error (e.g.,
require.NoError(t, err)if using testify, or a simple panic) would make the test setup more robust and consistent.Also applies to: 448-448
🤖 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_session_test.go` at line 294, The test setup marshals JSON into sessionMessage without checking the returned error; update both occurrences (the sessionMessage assignment at the location creating map[string]interface{}{"messages": []interface{}{}} and the similar marshal at the other reported spot) to capture the (data, err) result and assert or fail on err (e.g., use require.NoError(t, err) or panic/ t.Fatalf) before using sessionMessage so tests fail clearly on marshal errors.
🤖 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/chat_session_test.go`:
- Line 294: The test setup marshals JSON into sessionMessage without checking
the returned error; update both occurrences (the sessionMessage assignment at
the location creating map[string]interface{}{"messages": []interface{}{}} and
the similar marshal at the other reported spot) to capture the (data, err)
result and assert or fail on err (e.g., use require.NoError(t, err) or panic/
t.Fatalf) before using sessionMessage so tests fail clearly on marshal errors.
In `@internal/service/chat_session.go`:
- Around line 727-731: Replace the magic sentinel string "-999" with a named
constant (e.g., EmptyFilterSentinel or NoMatchSentinel) to make intent clear:
define the constant near related code or in a package-level const block, update
the return in the conditional inside the function where ApplyMetaDataFilter is
handled (the block that currently returns []string{"-999"}) to return
[]string{EmptyFilterSentinel}, and search for other places that compare to
"-999" (or rely on that sentinel) and update them to use the new constant so all
sentinel comparisons and returns use the named symbol.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 7868d4d4-1593-44ea-a160-52e6bfecfdff
📒 Files selected for processing (2)
internal/service/chat_session.gointernal/service/chat_session_test.go
eb907cc to
5139748
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/service/chat_session.go (2)
1048-1051: 💤 Low valueMutation of
dialog.PromptConfigmay cause unexpected side effects.
injectKnowledgeIntoDialogPromptmutatesdialog.PromptConfigin place by replacing the "system" key. WhilecloneJSONMapcreates a shallow copy, this still modifies the dialog's state which could affect callers if the dialog object is reused elsewhere.Consider documenting this intentional mutation or ensuring callers don't rely on the original prompt config after this function is called.
🤖 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_session.go` around lines 1048 - 1051, injectKnowledgeIntoDialogPrompt is mutating dialog.PromptConfig by assigning copied["system"] and then writing copied back to dialog.PromptConfig, which can cause caller-side surprises; instead avoid mutating the dialog in place by producing a new prompt config and returning it (or rename function to indicate mutation) — use a deep copy routine (or extend cloneJSONMap to deep clone) to create newConfig, set newConfig["system"] = strings.ReplaceAll(systemPrompt, "{knowledge}", knowledge), and return the newConfig so callers explicitly assign it (or, if mutation is intentional, update function name/docs to state it mutates dialog.PromptConfig).
607-614: 💤 Low valueConsider validating embedding model consistency across KBs.
The code uses only the first KB's embedding model (line 607:
kbs[0]). If the dialog references multiple knowledge bases created with different embedding models, the retrieval may produce unexpected results due to embedding dimension mismatches.If this is intentional (e.g., dialogs are expected to only reference KBs with compatible embeddings), consider adding a validation check or comment documenting this assumption.
🤖 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_session.go` around lines 607 - 614, The code currently picks the embedding model from only kbs[0] via embeddingModelForKnowledgebase, which can cause dimension/compatibility issues if dialog.KnowledgeBases includes KBs using different embedding models; update the logic to validate that all kbs have the same embedding model (or compatible dimensions) before proceeding: iterate over kbs, resolve each with embeddingModelForKnowledgebase (or otherwise retrieve the model identifier/dimension from each KB), compare against the model for kbs[0], and return an explicit error if any mismatch is found (or document/assert the single-model assumption), referencing kbs, embeddingModelForKnowledgebase, embeddingTenantID and dialog to locate the code to change.
🤖 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/chat_session.go`:
- Around line 1048-1051: injectKnowledgeIntoDialogPrompt is mutating
dialog.PromptConfig by assigning copied["system"] and then writing copied back
to dialog.PromptConfig, which can cause caller-side surprises; instead avoid
mutating the dialog in place by producing a new prompt config and returning it
(or rename function to indicate mutation) — use a deep copy routine (or extend
cloneJSONMap to deep clone) to create newConfig, set newConfig["system"] =
strings.ReplaceAll(systemPrompt, "{knowledge}", knowledge), and return the
newConfig so callers explicitly assign it (or, if mutation is intentional,
update function name/docs to state it mutates dialog.PromptConfig).
- Around line 607-614: The code currently picks the embedding model from only
kbs[0] via embeddingModelForKnowledgebase, which can cause
dimension/compatibility issues if dialog.KnowledgeBases includes KBs using
different embedding models; update the logic to validate that all kbs have the
same embedding model (or compatible dimensions) before proceeding: iterate over
kbs, resolve each with embeddingModelForKnowledgebase (or otherwise retrieve the
model identifier/dimension from each KB), compare against the model for kbs[0],
and return an explicit error if any mismatch is found (or document/assert the
single-model assumption), referencing kbs, embeddingModelForKnowledgebase,
embeddingTenantID and dialog to locate the code to change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f26022e4-87f0-4b30-bc7e-e162367311e1
📒 Files selected for processing (6)
internal/handler/dify_retrieval_handler.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/metadata_filter.gointernal/service/metadata_filter_test.gointernal/service/model_service.go
✅ Files skipped from review due to trivial changes (1)
- internal/service/metadata_filter_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/handler/dify_retrieval_handler.go
- internal/service/chat_session_test.go
5139748 to
2f07b44
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/service/chat_session.go (2)
543-543: ⚖️ Poor tradeoffConsider propagating a cancellable context into the goroutine.
Using
context.Background()means the retrieval operation cannot be cancelled if the client disconnects. Under high load, this could result in orphaned goroutines completing work for requests that will never be consumed. If the HTTP handler provides a request context, threading it throughCompletionStream→asyncChatStream→messagesWithRetrievedKnowledgewould allow graceful cancellation.🤖 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_session.go` at line 543, The call to messagesWithRetrievedKnowledge currently uses context.Background(), preventing cancellation; update CompletionStream and asyncChatStream signatures to accept a context.Context from the HTTP request (or the caller) and pass that context into messagesWithRetrievedKnowledge instead of context.Background(), and ensure any goroutine spawned for asyncChatStream/CompletionStream uses that cancellable ctx (select on ctx.Done() where appropriate) so retrieval and downstream work can be cancelled when the request context is cancelled.
1378-1382: 💤 Low valueConsider adding a defensive type check to prevent potential panic.
The type assertion
lastMsg["content"].(string)will panic if content is nil or not a string. While the normal flow always produces string content, corrupted session data or external modifications could trigger this path with unexpected types.🛡️ Optional defensive fix
- if ans["final"] == true && ans["answer"] != nil { - lastMsg["content"] = ans["answer"] - } else { - lastMsg["content"] = (lastMsg["content"].(string)) + content - } + if ans["final"] == true && ans["answer"] != nil { + lastMsg["content"] = ans["answer"] + } else { + existing, _ := lastMsg["content"].(string) + lastMsg["content"] = existing + content + }🤖 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_session.go` around lines 1378 - 1382, Add a defensive type-check before concatenating to lastMsg["content"]: instead of using lastMsg["content"].(string) blindly (which can panic), use the comma-ok type assertion to verify it's a string and handle non-string or nil cases by either converting to an empty string or logging and skipping concatenation; update the branch where ans["final"] is false (the else block handling lastMsg and content) to safely cast lastMsg["content"] to string using the ok pattern and then set lastMsg["content"] = existing + content (or fallback to content) to avoid panics when lastMsg["content"] is nil or of an unexpected type.
🤖 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/chat_session.go`:
- Line 543: The call to messagesWithRetrievedKnowledge currently uses
context.Background(), preventing cancellation; update CompletionStream and
asyncChatStream signatures to accept a context.Context from the HTTP request (or
the caller) and pass that context into messagesWithRetrievedKnowledge instead of
context.Background(), and ensure any goroutine spawned for
asyncChatStream/CompletionStream uses that cancellable ctx (select on ctx.Done()
where appropriate) so retrieval and downstream work can be cancelled when the
request context is cancelled.
- Around line 1378-1382: Add a defensive type-check before concatenating to
lastMsg["content"]: instead of using lastMsg["content"].(string) blindly (which
can panic), use the comma-ok type assertion to verify it's a string and handle
non-string or nil cases by either converting to an empty string or logging and
skipping concatenation; update the branch where ans["final"] is false (the else
block handling lastMsg and content) to safely cast lastMsg["content"] to string
using the ok pattern and then set lastMsg["content"] = existing + content (or
fallback to content) to avoid panics when lastMsg["content"] is nil or of an
unexpected type.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 5395f435-cc3d-4b00-811a-e35f46aea4d4
📒 Files selected for processing (6)
internal/handler/dify_retrieval_handler.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/metadata_filter.gointernal/service/metadata_filter_test.gointernal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (5)
- internal/service/metadata_filter_test.go
- internal/handler/dify_retrieval_handler.go
- internal/service/metadata_filter.go
- internal/service/model_service.go
- internal/service/chat_session_test.go
2f07b44 to
e19d938
Compare
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_session.go`:
- Around line 295-298: The goroutine currently reads c.Request.Context()
directly inside go func(), which may access Gin request state concurrently;
capture the request context into a local variable (e.g., reqCtx :=
c.Request.Context()) before starting the goroutine and pass that reqCtx into
chatSessionService.CompletionStream instead of calling c.Request.Context()
inside the goroutine; update the call site where CompletionStream(userID,
req.ConversationID, ...) is invoked to include this captured context so the
worker uses the safe, pre-captured context and keeps streamChan and messageID
usage unchanged.
🪄 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: fc261014-f456-47c1-b1ff-be12c64dec62
📒 Files selected for processing (7)
internal/handler/chat_session.gointernal/handler/dify_retrieval_handler.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/metadata_filter.gointernal/service/metadata_filter_test.gointernal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (6)
- internal/service/metadata_filter.go
- internal/service/metadata_filter_test.go
- internal/handler/dify_retrieval_handler.go
- internal/service/model_service.go
- internal/service/chat_session.go
- internal/service/chat_session_test.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @oktofeesh1 The overall direction is useful: this replaces the Go chat RAG placeholder with actual KB retrieval and wires in model resolution, KB access checks, retrieval context, prompt injection, and reference construction.
However, I think this needs fixes before matching the PR description.
First, metadata filters and message-level doc_ids are currently combined as a union. ApplyMetaDataFilter initializes docIDs with baseDocIDs and then appends metadata-filter matches. That means doc_ids can bypass metadata filters, and metadata no-match will not produce the no-match sentinel when baseDocIDs is non-empty. These constraints should be intersected so retrieval only sees documents satisfying both.
Second, validateKnowledgebaseEmbeddingModels only compares Knowledgebase.EmbdID. It does not account for TenantEmbdID or the resolved composite embedding model, so mixed tenant-specific embedding configs can pass validation. Since the goal is avoiding incompatible vector dimensions, this should compare the resolved embedding model identity used for retrieval.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15739 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
Thanks, both review points were valid and are fixed now. What changed:
Validation:
Note: broader |
|
@oktofeesh1 fix the CI error |
The chat_session_test.go fake still returned []string after #15862 re-enabled the Go test step and fixed the entity/models test files, so internal/service still failed to build. Align fakeChatModelDriver with the new ModelDriver.ListModels signature. Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Haruko386 fixed. |
Summary
What changed
doc_idsbefore retrieval.Why
Validation
uvx cmake -S internal/cpp -B internal/cpp/cmake-build-releaseuvx cmake --build internal/cpp/cmake-build-release --target rag_tokenizer_c_api -j 4go test ./internal/service -run 'Test(AsyncChat|MessagesWithRetrievedKnowledge|ApplyMetaFilter|ConvertToMetaCondition|ApplySingleCondition|CompareValues)' -count=1go test ./internal/service -run '^$' -count=1go test ./internal/handler -run 'TestDifyRetrieval|Chat' -count=1go vet ./internal/service ./internal/handlergit diff --checkNotes
mainand mergeable.