Repository navigation
fix[go]: support retrieval kb in agent chat - #16944
Conversation
📝 WalkthroughWalkthroughAgent tool configuration now accepts canvas tool objects and merges parameters. Retrieval gains richer configuration, tenant resolution, chunk metadata, and reference recording. Message fallback extraction and DeepSeek/Eino tool-calling transport are expanded with tests. ChangesAgent and message handling
Retrieval pipeline
Model tool calling
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Agent
participant RetrievalTool
participant RetrievalService
participant CanvasState
Agent->>RetrievalTool: configure tool defaults
RetrievalTool->>RetrievalService: submit enriched retrieval request
RetrievalService-->>RetrievalTool: return translated chunks
RetrievalTool->>CanvasState: record retrieval references
sequenceDiagram
participant EinoChatModel
participant DeepSeek
participant ToolRuntime
EinoChatModel->>DeepSeek: send tools and tool choice
DeepSeek-->>EinoChatModel: return tool calls
EinoChatModel->>ToolRuntime: expose translated tool calls
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 |
There was a problem hiding this comment.
Actionable comments posted: 10
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/agent/tool/retrieval_nlp.go (1)
139-158: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftForward the retrieval knobs into the NLP request
internal/agent/tool/retrieval_nlp.go:139-158dropsRerankID,TOCEnhance, andMetadataFilterbefore callingnlp.RetrievalService, so those request fields never affect retrieval. Either plumb them through the NLP path or remove them from the exposed retrieval surface.🤖 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/tool/retrieval_nlp.go` around lines 139 - 158, Update the NLP retrieval request construction in the retrieval tool to forward req.RerankID, req.TOCEnhance, and req.MetadataFilter into the corresponding nlp.RetrievalRequest fields before calling nlp.RetrievalService, preserving their values so these exposed retrieval options affect execution.
🧹 Nitpick comments (2)
internal/entity/models/deepseek.go (1)
73-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract shared helper for building
apiMsg(duplicated at line 271-281).This tool_call_id/tool_calls block is copy-pasted verbatim into
ChatStreamlyWithSender(Line 271-281). Extracting a sharedmessageToAPIMap(msg Message) map[string]interface{}helper avoids the two implementations silently diverging later.♻️ Proposed helper extraction
func messageToAPIMap(msg Message) map[string]interface{} { apiMsg := map[string]interface{}{ "role": msg.Role, "content": msg.Content, } if msg.ToolCallID != "" { apiMsg["tool_call_id"] = msg.ToolCallID } if len(msg.ToolCalls) > 0 { apiMsg["tool_calls"] = msg.ToolCalls } return apiMsg }Then both call sites reduce to
apiMessages[i] = messageToAPIMap(msg).🤖 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/entity/models/deepseek.go` around lines 73 - 83, Extract the duplicated API message construction into a shared messageToAPIMap helper in deepseek.go, preserving role, content, conditional tool_call_id, and conditional tool_calls fields. Replace the inline map-building blocks in both affected call sites, including ChatStreamlyWithSender, with calls to this helper.internal/entity/models/deepseek_test.go (1)
1-161: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd streaming tool-call tests for
ChatStreamlyWithSender.Both tests here cover only
ChatWithMessages. The new SSE tool-call accumulation logic inChatStreamlyWithSender(deepseek.go,accumulatedToolCalls/ToolCallsResult) has no direct test coverage, and this is likely why the map-ordering and finish_reason-shortcut issues flagged in that file went unnoticed. A test with two parallel tool-call deltas across multiple SSE chunks would catch both.Want me to draft a
TestDeepSeekChatStreamlyWithSenderAccumulatesToolCallstest exercising multiple parallel/chunked tool calls?🤖 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/entity/models/deepseek_test.go` around lines 1 - 161, Add a TestDeepSeekChatStreamlyWithSenderAccumulatesToolCalls test alongside the existing DeepSeek chat tests, using an httptest SSE server and ChatStreamlyWithSender. Emit multiple chunks containing interleaved deltas for at least two tool calls, including fragmented function names and arguments, then assert ToolCallsResult preserves both calls, their IDs, function names, and reconstructed arguments without relying on map iteration order. Ensure the stream includes the relevant finish event and verify the sender returns the accumulated tool calls rather than stopping prematurely.
🤖 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/agent/component/agent.go`:
- Around line 1089-1097: Update the tool-parameter construction around cloneMap
so a valid, trimmed function_name is added even when params is absent or empty.
Remove the len(toolParams) guard, and ensure toolParams is initialized before
assignment while preserving the existing return behavior.
- Around line 1121-1129: Update the override merge logic around the overrides
loop to remove all existing case-insensitive variants of each override name from
out before assigning the cloned override parameters. Then retain the normalized
lowercase assignment so lookups using either casing receive the new values,
while preserving the existing skip behavior for empty parameter maps.
In `@internal/agent/component/message.go`:
- Around line 363-371: Update isMessageInfraInput to exclude the message
configuration keys "output_format", "voice", "lang", and "auto_play" alongside
the existing infrastructure keys. Ensure these keys are treated as non-message
inputs so they do not contribute to the fallback text count.
In `@internal/agent/tool/registry.go`:
- Line 291: Update the error construction in buildRetrievalTool to use the
actual tool alias or name passed to the builder instead of hardcoding
"retrieval", so rejected node-level parameters identify search_my_dataset,
search_my_dateset, or retrieval correctly.
- Around line 281-329: The buildRetrievalTool function currently accepts several
retrieval parameters but silently discards them. Wire top_k,
keywords_similarity_weight, empty_response, retrieval_from, memory_ids, kb_vars,
and cross_languages through retrievalArgs and the downstream RetrievalRequest,
or remove them from the accepted-key switch; retain inputs, outputs, and meta as
metadata-only keys.
In `@internal/agent/tool/retrieval.go`:
- Line 230: Update referenceChunksFromRetrieval and its callers so fallback IDs
for chunks with empty c.ID include a unique identifier for the current retrieval
call, rather than only the loop index. Preserve explicit chunk IDs and ensure
separate InvokableRun calls generate distinct fallback namespaces before passing
results to CanvasState.SetRetrievalReferences.
- Around line 189-198: Thread RerankID, TOCEnhance, and MetadataFilter through
the NLP retrieval flow: add corresponding fields to
internal/service/nlp.RetrievalRequest and populate them in
NLPRetrievalAdapter.Search from the tool arguments, preserving their values
through the downstream retrieval request. Do not leave these tool-surface
arguments as no-ops.
In `@internal/entity/models/deepseek.go`:
- Around line 471-478: Update the ToolCallsResult construction in the
accumulatedToolCalls block to sort the map entries by their call index before
appending them to tcs; add the sort import as needed. Preserve the existing
behavior for empty calls and nil chatModelConfig.
- Around line 393-394: At the start of ChatStreamlyWithSender, reset
chatModelConfig.ToolCallsResult before initializing streaming state such as
sawTerminal and accumulatedToolCalls. Ensure each call begins with an empty
per-request tool-call result while preserving the existing streaming behavior.
In `@internal/entity/models/llm.go`:
- Around line 166-183: Update EinoChatModel.chatConfigForGenerate so the default
ToolChoice of "auto" is assigned only when the copied chat configuration has no
existing ToolChoice. Preserve explicitly configured choices such as "none" or a
specific tool name while still defaulting unset choices when tools are bound.
---
Outside diff comments:
In `@internal/agent/tool/retrieval_nlp.go`:
- Around line 139-158: Update the NLP retrieval request construction in the
retrieval tool to forward req.RerankID, req.TOCEnhance, and req.MetadataFilter
into the corresponding nlp.RetrievalRequest fields before calling
nlp.RetrievalService, preserving their values so these exposed retrieval options
affect execution.
---
Nitpick comments:
In `@internal/entity/models/deepseek_test.go`:
- Around line 1-161: Add a
TestDeepSeekChatStreamlyWithSenderAccumulatesToolCalls test alongside the
existing DeepSeek chat tests, using an httptest SSE server and
ChatStreamlyWithSender. Emit multiple chunks containing interleaved deltas for
at least two tool calls, including fragmented function names and arguments, then
assert ToolCallsResult preserves both calls, their IDs, function names, and
reconstructed arguments without relying on map iteration order. Ensure the
stream includes the relevant finish event and verify the sender returns the
accumulated tool calls rather than stopping prematurely.
In `@internal/entity/models/deepseek.go`:
- Around line 73-83: Extract the duplicated API message construction into a
shared messageToAPIMap helper in deepseek.go, preserving role, content,
conditional tool_call_id, and conditional tool_calls fields. Replace the inline
map-building blocks in both affected call sites, including
ChatStreamlyWithSender, with calls to this helper.
🪄 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: a57ca58f-65ac-4494-9e03-1e1230b85735
📒 Files selected for processing (15)
internal/agent/component/agent.gointernal/agent/component/agent_test.gointernal/agent/component/message.gointernal/agent/component/message_test.gointernal/agent/component/universe_a_wrappers.gointernal/agent/tool/registry.gointernal/agent/tool/retrieval.gointernal/agent/tool/retrieval_nlp.gointernal/agent/tool/retrieval_nlp_test.gointernal/agent/tool/retrieval_service.gointernal/agent/tool/retrieval_test.gointernal/entity/models/deepseek.gointernal/entity/models/deepseek_test.gointernal/entity/models/llm.gointernal/entity/models/llm_test.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/agent/tool/retrieval.go (1)
169-173: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winValidate LLM-generated
keywords_similarity_weightto prevent out-of-bounds errors.While canvas configuration validates that
keywords_similarity_weightis bounded within[0,1], the LLM-provided arguments parsed from JSON are not bounds-checked. If the model hallucinates a negative weight or a weight> 1, it will bypassmergeDefaults(since the pointer is notnil) and propagate downstream. This can cause vector-weight inversion (e.g., negative vector weight) and break the underlying retrieval queries.🛡️ Proposed fix to enforce bounds
if argumentsInJSON != "" { if err := json.Unmarshal([]byte(argumentsInJSON), &args); err != nil { return "", fmt.Errorf("retrieval: parse arguments: %w", err) } + if args.KeywordsSimilarityWeight != nil { + if *args.KeywordsSimilarityWeight < 0 || *args.KeywordsSimilarityWeight > 1 { + return "", fmt.Errorf("retrieval: keywords_similarity_weight must be in [0,1]") + } + } }🤖 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/tool/retrieval.go` around lines 169 - 173, Validate the LLM-provided keywords_similarity_weight immediately after JSON unmarshalling in the retrieval argument parsing flow, ensuring any non-nil value is within the inclusive range [0,1]. Return a descriptive validation error for out-of-range values so invalid weights cannot bypass mergeDefaults or reach downstream retrieval queries.
🧹 Nitpick comments (1)
internal/agent/tool/retrieval.go (1)
175-182: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueInclude
similarity_thresholdin debug logging.For completeness, consider logging the
similarity_thresholdargument alongside the other search controls.🛠️ Proposed fix
common.Debug("agent retrieval tool: parsed arguments", zap.String("query", args.Query), zap.Strings("dataset_ids", args.DatasetIDs), zap.Int("top_n", args.TopN), zap.Int("top_k", args.TopK), zap.Float64p("keywords_similarity_weight", args.KeywordsSimilarityWeight), + zap.Float64("similarity_threshold", args.SimilarityThreshold), zap.Bool("use_kg", args.UseKG), )🤖 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/tool/retrieval.go` around lines 175 - 182, Update the “agent retrieval tool: parsed arguments” debug log to include args.SimilarityThreshold as the similarity_threshold field, alongside the existing search-control arguments.
🤖 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/agent/tool/retrieval.go`:
- Around line 169-173: Validate the LLM-provided keywords_similarity_weight
immediately after JSON unmarshalling in the retrieval argument parsing flow,
ensuring any non-nil value is within the inclusive range [0,1]. Return a
descriptive validation error for out-of-range values so invalid weights cannot
bypass mergeDefaults or reach downstream retrieval queries.
---
Nitpick comments:
In `@internal/agent/tool/retrieval.go`:
- Around line 175-182: Update the “agent retrieval tool: parsed arguments” debug
log to include args.SimilarityThreshold as the similarity_threshold field,
alongside the existing search-control arguments.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 033b924f-1c67-4949-b36e-9df462f4a7dc
📒 Files selected for processing (9)
internal/agent/component/agent.gointernal/agent/component/message.gointernal/agent/tool/registry.gointernal/agent/tool/retrieval.gointernal/agent/tool/retrieval_nlp.gointernal/agent/tool/retrieval_nlp_test.gointernal/agent/tool/retrieval_service.gointernal/agent/tool/retrieval_test.gointernal/entity/models/deepseek.go
🚧 Files skipped from review as they are similar to previous changes (5)
- internal/agent/component/agent.go
- internal/agent/component/message.go
- internal/agent/tool/retrieval_test.go
- internal/agent/tool/retrieval_nlp.go
- internal/entity/models/deepseek.go

Summary
As title
Retrieval KBRetrieval KBin agent chatMain cause
Model provider do not set up:
Working Now