Skip to content

fix[go]: support retrieval kb in agent chat - #16944

Merged
yuzhichang merged 2 commits into
infiniflow:mainfrom
Haruko386:main
Jul 15, 2026
Merged

yuzhichang merged 2 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

@Haruko386 Haruko386 commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Summary

As title

  • fix tool & component Retrieval KB
  • fix agent cannot use Retrieval KB in agent chat

Main cause

Model provider do not set up:

if chatModelConfig.Tools != nil {
    reqBody["tools"] = chatModelConfig.Tools
}

Working Now

image
 ____________________________________
< This PR takes me all day to do it. >
 ------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ                                                                                                                                                                                                    

@Haruko386 Haruko386 added 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration go Pull requests that update go code labels Jul 15, 2026
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 15, 2026
@Haruko386
Haruko386 requested a review from yuzhichang July 15, 2026 08:58
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Agent and message handling

Layer / File(s) Summary
Agent inputs and message fallback
internal/agent/component/agent.go, internal/agent/component/agent_test.go, internal/agent/component/message.go, internal/agent/component/message_test.go
Agent parsing accepts tool objects and merges normalized parameters; Message derives content from formalized_content or a single eligible string input.

Retrieval pipeline

Layer / File(s) Summary
Retrieval configuration and contracts
internal/agent/tool/registry.go, internal/agent/tool/retrieval.go, internal/agent/tool/retrieval_service.go, internal/agent/component/universe_a_wrappers.go
Retrieval factories decode expanded node parameters, apply defaults, expose additional schema fields, expand request and chunk contracts, and define the query input form.
Retrieval execution and references
internal/agent/tool/retrieval.go, internal/agent/tool/retrieval_nlp.go, internal/agent/tool/*_test.go
Retrieval forwards tenant and advanced parameters, resolves dataset tenants, translates richer chunks, and records structured references in canvas state.

Model tool calling

Layer / File(s) Summary
Model tool-call transport
internal/entity/models/deepseek.go, internal/entity/models/deepseek_test.go, internal/entity/models/llm.go, internal/entity/models/llm_test.go
Eino and DeepSeek transmit tool schemas and history, parse tool calls, aggregate streaming arguments, and expose tool calls in generated messages.

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
Loading
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
Loading

Possibly related PRs

Suggested labels: 💞 feature

Suggested reviewers: yuzhichang

Poem

I’m a rabbit with tools in my tray,
Retrieval hops through fields on its way.
DeepSeek calls bloom,
References find room,
And messages know what to say!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 24.49% 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 is concise and accurately reflects the main change: enabling Retrieval KB support in agent chat.
Description check ✅ Passed The description includes the required Summary section and enough context about the bug, cause, and expected behavior.
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.

@Haruko386
Haruko386 marked this pull request as draft July 15, 2026 09:01
@Haruko386
Haruko386 marked this pull request as ready for review July 15, 2026 09:01

@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: 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 lift

Forward the retrieval knobs into the NLP request internal/agent/tool/retrieval_nlp.go:139-158 drops RerankID, TOCEnhance, and MetadataFilter before calling nlp.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 win

Extract 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 shared messageToAPIMap(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 win

Add streaming tool-call tests for ChatStreamlyWithSender.

Both tests here cover only ChatWithMessages. The new SSE tool-call accumulation logic in ChatStreamlyWithSender (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 TestDeepSeekChatStreamlyWithSenderAccumulatesToolCalls test 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4391e03 and c926c21.

📒 Files selected for processing (15)
  • internal/agent/component/agent.go
  • internal/agent/component/agent_test.go
  • internal/agent/component/message.go
  • internal/agent/component/message_test.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/tool/registry.go
  • internal/agent/tool/retrieval.go
  • internal/agent/tool/retrieval_nlp.go
  • internal/agent/tool/retrieval_nlp_test.go
  • internal/agent/tool/retrieval_service.go
  • internal/agent/tool/retrieval_test.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/deepseek_test.go
  • internal/entity/models/llm.go
  • internal/entity/models/llm_test.go

Comment thread internal/agent/component/agent.go Resolved
Comment thread internal/agent/component/agent.go Resolved
Comment thread internal/agent/component/message.go Resolved
Comment thread internal/agent/tool/registry.go Resolved
Comment thread internal/agent/tool/registry.go Resolved
Comment thread internal/agent/tool/retrieval.go Resolved
Comment thread internal/agent/tool/retrieval.go Resolved
Comment thread internal/entity/models/deepseek.go Resolved
Comment thread internal/entity/models/deepseek.go Resolved
Comment thread internal/entity/models/llm.go Resolved

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed

Image

@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/agent/tool/retrieval.go (1)

169-173: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Validate LLM-generated keywords_similarity_weight to prevent out-of-bounds errors.

While canvas configuration validates that keywords_similarity_weight is 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 bypass mergeDefaults (since the pointer is not nil) 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 value

Include similarity_threshold in debug logging.

For completeness, consider logging the similarity_threshold argument 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

📥 Commits

Reviewing files that changed from the base of the PR and between c926c21 and f2dceba.

📒 Files selected for processing (9)
  • internal/agent/component/agent.go
  • internal/agent/component/message.go
  • internal/agent/tool/registry.go
  • internal/agent/tool/retrieval.go
  • internal/agent/tool/retrieval_nlp.go
  • internal/agent/tool/retrieval_nlp_test.go
  • internal/agent/tool/retrieval_service.go
  • internal/agent/tool/retrieval_test.go
  • internal/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

@yuzhichang
yuzhichang merged commit ff3d566 into infiniflow:main Jul 15, 2026
3 checks passed
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 go Pull requests that update go code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants