Skip to content

fix(go-agent): retrieval empty results, KB selector paging, and begin custom inputs - #17398

Closed
euvre wants to merge 2 commits into
infiniflow:mainfrom
euvre:fix/go-agent-retrieval-and-begin-inputs
Closed

euvre wants to merge 2 commits into
infiniflow:mainfrom
euvre:fix/go-agent-retrieval-and-begin-inputs

Conversation

@euvre

@euvre euvre commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Summary

Three fixes for the Go-mode agent canvas:

1. Agent retrieval returned no chunks. The NLP retrieval adapter never resolved the knowledge base's embedding model, so searches ran keyword-only and the results were filtered out by the similarity threshold — downstream Agent components concluded the knowledge base had no relevant content. The adapter now resolves the kb's embedding model (and the node's optional rerank model) through an injected RetrievalModelProvider and mounts them on the nlp request, enabling hybrid (fulltext + vector + fusion) search, matching the Python canvas. The rerank_id node param is also threaded through (previously dropped silently), and when nothing is found the node's empty_response is surfaced as formalized_content instead of an empty output map.

2. Knowledge base selector showed an empty list. Server-side pagination combined with the client-side chunk_count > 0 filter could filter out an entire page, leaving an empty, unscrollable dropdown that never triggered the next-page load. The list now auto-fetches the next page while the filtered result is empty and more pages exist. Also fixed variable option icons being rendered as image URLs, which fired bogus /sys.* img requests per option.

3. Begin custom inputs (test-run panel / chat form) were dropped. RunAgent ignored the request's inputs, so {begin@<key>} references (e.g. in a Retrieval query) never resolved in Go mode. Begin inputs are now threaded through RunAgent and seeded as the Begin component's outputs, and the Begin component applies the single-input sys.query fallback, mirroring Python's Begin._invoke.

Tests: bash build.sh --test ./internal/agent/... ./internal/service/ ./cmd/... all pass; new unit tests cover the model attachment, empty-response fill, begin input seeding, and the sys.query fallback.

… custom inputs

Three Go-mode agent canvas fixes:

1. Agent retrieval returned no chunks: the NLP retrieval adapter never
   resolved the knowledge base's embedding model, so searches ran
   keyword-only and were filtered out by the similarity threshold.
   Resolve the kb embedding model (and optional rerank model) via an
   injected RetrievalModelProvider and mount them on the nlp request
   for hybrid search, matching the Python canvas. Also surface the
   node's empty_response as formalized_content when nothing is found,
   and thread rerank_id through the tool request.

2. Knowledge base selector showed an empty list: server-side
   pagination combined with the client-side chunk_count>0 filter could
   filter out an entire page, leaving an empty, unscrollable dropdown
   that never loaded the next page. Auto-fetch the next page while the
   filtered list is empty and more pages exist. Also stop rendering
   variable icons as image URLs (bogus /sys.* img requests).

3. Begin custom inputs (test-run panel / chat form) were dropped:
   RunAgent ignored the request's inputs, so {begin@<key>} references
   never resolved. Thread begin inputs through RunAgent and seed them
   as the Begin component's outputs; add the single-input sys.query
   fallback in the Begin component, mirroring Python Begin._invoke.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 27, 2026
@euvre euvre added the ci Continue Integration label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2b02b828-bdef-469e-bfd7-552430ae28fc

📥 Commits

Reviewing files that changed from the base of the PR and between ebfd4d6 and a31988d.

📒 Files selected for processing (5)
  • internal/agent/component/begin.go
  • internal/agent/component/begin_test.go
  • internal/agent/component/retrieval_swap_test.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/tool/retrieval.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/agent/component/begin_test.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/component/begin.go
  • internal/agent/tool/retrieval.go

📝 Walkthrough

Walkthrough

The PR adds Begin input propagation and fallback behavior, retrieval embedding/rerank model resolution, empty retrieval responses, updated RunAgent call contracts, and knowledge-base selector pagination and avatar rendering changes.

Changes

Retrieval model integration

Layer / File(s) Summary
Retrieval contracts and request propagation
internal/agent/tool/retrieval_service.go, internal/agent/tool/retrieval.go
Retrieval requests accept optional rerank references, apply defaults, expose empty chunks, and use a registered model provider.
Knowledge-base model attachment
internal/agent/tool/retrieval_nlp.go, cmd/ragflow_server.go
NLP retrieval resolves knowledge bases, validates embedding references, attaches models, and receives provider wiring at startup.
Retrieval behavior validation
internal/agent/tool/retrieval_nlp_test.go
Tests cover knowledge-base resolution, model attachment, tenant fallback, mixed embeddings, and keyword-only behavior.
Empty retrieval response handling
internal/agent/component/universe_a_wrappers.go, internal/agent/component/retrieval_swap_test.go
Confirmed empty retrieval results use configured empty-response text and are tested.

Begin input propagation

Layer / File(s) Summary
RunAgent Begin input contract
internal/handler/agent.go, internal/service/bot.go, internal/service/agent.go, internal/handler/*_test.go
RunAgent accepts beginInputs, handlers forward request inputs, and wrappers and test doubles adopt the expanded signature.
Begin state seeding
internal/service/agent.go, internal/service/agent_test.go
Provided inputs are stored in the runner root and seeded into canvas Begin variables, including typed-value unwrapping.
Begin fallback compatibility
internal/agent/component/begin.go, internal/agent/component/begin_test.go
When no Begin output is seeded, one declared input can receive sys.query; seeded values take precedence.
RunAgent call-site coverage
internal/service/agent_run_e2e_test.go, internal/service/agent_test.go
Existing RunAgent tests use the expanded argument order.

Knowledge list UI updates

Layer / File(s) Summary
Knowledge selector rendering and pagination
web/src/components/knowledge-base-item.tsx, web/src/hooks/use-knowledge-request.ts
Knowledge options pass names to avatars, and filtered empty lists automatically request additional pages when available.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AgentHandler
  participant AgentService
  participant CanvasState
  participant BeginComponent
  Client->>AgentHandler: Submit query and beginInputs
  AgentHandler->>AgentService: RunAgent(beginInputs)
  AgentService->>CanvasState: Seed begin variables
  CanvasState->>BeginComponent: Provide Begin outputs
  BeginComponent-->>AgentService: Return resolved inputs
Loading

Possibly related PRs

Suggested reviewers: jinhai-cn

Poem

A rabbit hops where Begin inputs flow,
While retrieval models softly glow.
Empty chunks find words to say,
More knowledge pages load away.
“Sniff!” says Bun, “the paths are clear!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.38% 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 names the three main fixes: retrieval empty results, KB selector paging, and begin custom inputs.
Description check ✅ Passed The description includes the required Summary section and clearly explains the three fixes with background and test coverage.
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.

@euvre
euvre requested a review from wangq8 July 27, 2026 02:49

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

🧹 Nitpick comments (2)
internal/agent/tool/retrieval_nlp.go (1)

274-287: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent keyword-only fallback when tenantID resolves empty.

If req.TenantID is blank and no KB carries a tenant, both guards fail closed without a trace: the embedding model is never attached (reintroducing exactly the empty-results bug this change targets) and an explicitly configured RerankID is dropped. A debug/warn line makes that state diagnosable.

♻️ Log the degraded path
+	if tenantID == "" && (embdID != "" || req.RerankID != "") {
+		common.Warn("agent retrieval: no tenant resolved; skipping embedding/rerank model attachment (keyword-only)",
+			zap.String("embd_id", embdID),
+			zap.String("rerank_id", req.RerankID),
+		)
+	}
 	if embdID != "" && tenantID != "" {

Requires common/zap imports if not already present in this file.

🤖 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 274 - 287, Update the
embedding and rerank resolution flow around GetEmbeddingModel and GetRerankModel
to log a debug or warning message when the corresponding ID is configured but
tenantID is empty, instead of silently skipping resolution. Include enough
context to identify the degraded keyword-only path, while preserving the
existing guarded model attachment and error handling.
internal/agent/tool/retrieval_nlp_test.go (1)

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

fakeRetrievalModelProvider.err is never injected — the provider-failure path is untested.

The field exists but no test sets it, so the error wrapping at internal/agent/tool/retrieval_nlp.go lines 277 and 284 has no coverage. Either exercise it or drop the field.

♻️ Add a provider-error test
func TestAttachRetrievalModels_ProviderErrorPropagates(t *testing.T) {
	provider := &fakeRetrievalModelProvider{err: errors.New("boom")}
	SetRetrievalModelProvider(provider)
	t.Cleanup(func() { SetRetrievalModelProvider(nil) })

	nlpReq := &nlp.RetrievalRequest{}
	err := attachRetrievalModels(
		context.Background(),
		RetrievalRequest{TenantID: "tenant-a"},
		[]*entity.Knowledgebase{{ID: "kb-1", TenantID: "tenant-a", EmbdID: "emb-a"}},
		nlpReq,
	)
	if err == nil || !strings.Contains(err.Error(), "resolve embedding model") {
		t.Fatalf("err = %v, want wrapped embedding resolution failure", err)
	}
	if nlpReq.EmbeddingModel != nil {
		t.Error("EmbeddingModel should stay nil when resolution fails")
	}
}

Also applies to: 452-467

🤖 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_test.go` at line 355, Update the retrieval
NLP tests around fakeRetrievalModelProvider and attachRetrievalModels to inject
a provider error and exercise the failure path. Add coverage that verifies the
returned error includes the embedding-model resolution context and that
nlpReq.EmbeddingModel remains nil; otherwise remove the unused err field.
🤖 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/begin.go`:
- Around line 114-118: Persist fallback values in the reserved begin namespace:
in internal/agent/component/begin.go:114-118, update the fallback branch around
Invoke to call state.SetVar("begin", fallbackKey, fallbackValue) while retaining
the returned output. In internal/agent/component/begin_test.go:180-186, add an
assertion that state.GetVar("begin@color") resolves to the fallback value.

In `@internal/agent/component/universe_a_wrappers.go`:
- Around line 182-188: Restrict the empty-response fallback in the wrapper
handling around parseToolEnvelope to confirmed empty-result envelopes: validate
that parsing succeeded, inspect the parsed chunks field, and only apply
c.params.EmptyResponse when chunks are empty and formalized_content is blank. Do
not replace non-JSON {"_raw": ...} results or envelopes containing chunks.
- Around line 182-188: The fallback logic after parseToolEnvelope in
InvokableRun must apply only to supported chunk-result envelopes with zero
chunks. Validate the decoded envelope’s chunks/result shape before setting
formalized_content, excluding raw non-object wrappers and empty objects;
preserve the configured EmptyResponse behavior for genuine zero-result chunk
responses.

---

Nitpick comments:
In `@internal/agent/tool/retrieval_nlp_test.go`:
- Line 355: Update the retrieval NLP tests around fakeRetrievalModelProvider and
attachRetrievalModels to inject a provider error and exercise the failure path.
Add coverage that verifies the returned error includes the embedding-model
resolution context and that nlpReq.EmbeddingModel remains nil; otherwise remove
the unused err field.

In `@internal/agent/tool/retrieval_nlp.go`:
- Around line 274-287: Update the embedding and rerank resolution flow around
GetEmbeddingModel and GetRerankModel to log a debug or warning message when the
corresponding ID is configured but tenantID is empty, instead of silently
skipping resolution. Include enough context to identify the degraded
keyword-only path, while preserving the existing guarded model attachment and
error handling.
🪄 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 Plus

Run ID: 03bf6b9f-79d1-43a9-b3e6-916c089bf622

📥 Commits

Reviewing files that changed from the base of the PR and between 53afc32 and ebfd4d6.

📒 Files selected for processing (18)
  • cmd/ragflow_server.go
  • internal/agent/component/begin.go
  • internal/agent/component/begin_test.go
  • internal/agent/component/retrieval_swap_test.go
  • internal/agent/component/universe_a_wrappers.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/handler/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent_wait_for_user_test.go
  • internal/service/agent.go
  • internal/service/agent_run_e2e_test.go
  • internal/service/agent_test.go
  • internal/service/bot.go
  • web/src/components/knowledge-base-item.tsx
  • web/src/hooks/use-knowledge-request.ts
💤 Files with no reviewable changes (1)
  • web/src/components/knowledge-base-item.tsx

Comment thread internal/agent/component/begin.go Resolved

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Three well-scoped fixes that collectively make Go-mode agent canvas usable. Good work.

Fix 1 — Agent retrieval returned no chunks:
The root cause is clear: without resolving the KB's embedding model, the nlp request ran keyword-only and results never passed the similarity threshold. Wiring RetrievalModelProvider via injection (cleanly avoiding import cycles) and mounting embedding + rerank models on the request enables true hybrid search.

Fix 2 — KB selector empty dropdown:
The combination of server-side pagination + client-side chunk_count > 0 filter could produce an empty page that never triggers the next-page load. Auto-fetching the next page while results are empty and more pages exist is a pragmatic fix. The icon rendering fix is also correct.

Fix 3 — Begin custom inputs dropped:
Threading beginInputs through RunAgent and seeding them as Begin outputs before the first component runs correctly mirrors Python's behavior. The singleDeclaredInputKey + beginBucketEmpty guards ensure the sys.query fallback only fires when appropriate.

Minor suggestions:

  1. seedBeginInputOutputs iterates beginInputs but does not distinguish between known fields and unknown keys. Consider warning on unrecognized keys for debuggability.
  2. The EmptyResultFillsEmptyResponse test uses an empty query — consider adding a test where the query matches but the similarity threshold filters everything (more representative of the actual bug scenario).

Approved — these are solid fixes.

@wangq8
wangq8 requested a review from Haruko386 July 27, 2026 06:06

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, but would you fix the issues raised by the rabbit? @euvre

…ed empty envelope

- Begin: write the single-input sys.query fallback into the reserved
  Outputs["begin"] namespace via state.SetVar so {begin@<key>} refs
  resolve even with node ids like begin_0.
- Retrieval tool: always serialize the chunks field (no omitempty) so
  a zero-hit search yields a confirmed empty-result envelope
  ({"chunks": []}) instead of a bare {}.
- Retrieval component: apply the empty_response fallback only for a
  confirmed empty-result envelope (parsed object with an empty chunks
  array); raw non-JSON output, error stubs, envelopes with chunks but
  no rendered text, and unrelated {} shapes are left untouched.
@wangq8

wangq8 commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

@euvre resolve conflict.

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 size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants