feat: Enhance agent tool compatibility and knowledge base filtering
- Introduced a unified capability requirements system for agent tools, ensuring consistent filtering of knowledge bases based on their capabilities. - Implemented derived `kb_filter` logic to streamline compatibility checks between agent tools and knowledge bases, reducing redundancy in configuration. - Updated frontend components to reflect new filtering logic, including improved handling of empty states and user feedback when no compatible knowledge bases are available. - Enhanced internationalization support by adding relevant messages for tool compatibility issues across multiple languages.
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
// Package tools — capability requirements for built-in agent tools.
|
||||
//
|
||||
// This file is the Go mirror of `frontend/src/utils/tool-capabilities.ts`.
|
||||
// They MUST be kept in sync: whenever you add a tool to the registry with
|
||||
// specific KB requirements, update both maps.
|
||||
//
|
||||
// Why duplicate it? The frontend uses it to gray out tools and filter KBs
|
||||
// in the agent editor and `@` mention menu; the backend uses it as the
|
||||
// authoritative last line of defense in the retrieval pipeline — a client
|
||||
// that skips the frontend filter (old tab, curl, rogue plugin) shouldn't be
|
||||
// able to hand incompatible KBs/files to a tool that would just silently
|
||||
// skip them.
|
||||
package tools
|
||||
|
||||
import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// KBCapability names the capability flags a knowledge base can expose.
|
||||
// Values mirror the keys of `types.KBCapabilities`.
|
||||
type KBCapability string
|
||||
|
||||
const (
|
||||
CapVector KBCapability = "vector"
|
||||
CapKeyword KBCapability = "keyword"
|
||||
CapWiki KBCapability = "wiki"
|
||||
CapGraph KBCapability = "graph"
|
||||
CapFAQ KBCapability = "faq"
|
||||
)
|
||||
|
||||
// ToolRequirement declares what a tool needs from the KB scope.
|
||||
//
|
||||
// - AnyOf: scope must expose at least ONE listed capability.
|
||||
// - AllOf: scope must expose ALL listed capabilities.
|
||||
// - ConsumesFiles: the tool reads user-provided file refs from
|
||||
// `knowledge_ids`; the chat input uses this to decide whether to
|
||||
// even offer the `@file` list to the user.
|
||||
//
|
||||
// A nil/zero requirement means "no KB dependency" — the tool is always
|
||||
// available and doesn't care about files.
|
||||
type ToolRequirement struct {
|
||||
AnyOf []KBCapability
|
||||
AllOf []KBCapability
|
||||
ConsumesFiles bool
|
||||
}
|
||||
|
||||
// ToolCapabilityRequirements maps tool names to their capability needs.
|
||||
// Keep this aligned with `frontend/src/utils/tool-capabilities.ts`.
|
||||
//
|
||||
// Tools absent from this map default to "no requirement" and are treated
|
||||
// as always available / file-consuming (permissive fallback: unknown MCP
|
||||
// tools shouldn't silently break).
|
||||
var ToolCapabilityRequirements = map[string]ToolRequirement{
|
||||
// ---- base / reasoning (no KB dependency, no file consumption) ----
|
||||
"thinking": {},
|
||||
"todo_write": {},
|
||||
"final_answer": {},
|
||||
|
||||
// ---- RAG / chunk retrieval (need at least one chunk-indexed KB) ----
|
||||
"knowledge_search": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
"grep_chunks": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
"list_knowledge_chunks": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
"query_knowledge_graph": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
"get_document_info": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
"database_query": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
|
||||
// ---- Wiki (operates on wiki pages; doesn't consume arbitrary file IDs) ----
|
||||
"wiki_search": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_read_page": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_read_source_doc": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_flag_issue": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_write_page": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_replace_text": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_rename_page": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_delete_page": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_read_issue": {AllOf: []KBCapability{CapWiki}},
|
||||
"wiki_update_issue": {AllOf: []KBCapability{CapWiki}},
|
||||
|
||||
// ---- Data analysis (reads table summary/column chunks from RAG ingest) ----
|
||||
"data_analysis": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
"data_schema": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
|
||||
}
|
||||
|
||||
func hasCap(caps types.KBCapabilities, c KBCapability) bool {
|
||||
switch c {
|
||||
case CapVector:
|
||||
return caps.Vector
|
||||
case CapKeyword:
|
||||
return caps.Keyword
|
||||
case CapWiki:
|
||||
return caps.Wiki
|
||||
case CapGraph:
|
||||
return caps.Graph
|
||||
case CapFAQ:
|
||||
return caps.FAQ
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// KBFilter is the derived "KB must expose at least one of these capabilities"
|
||||
// predicate for a set of allowed tools (see DeriveKBFilterFromTools).
|
||||
type KBFilter struct {
|
||||
AnyOf []KBCapability
|
||||
}
|
||||
|
||||
// IsEmpty reports whether the filter imposes no constraint
|
||||
// (either no capability accumulated, or explicit zero value).
|
||||
func (f KBFilter) IsEmpty() bool { return len(f.AnyOf) == 0 }
|
||||
|
||||
// DeriveKBFilterFromTools derives a capability filter such that a KB passes
|
||||
// iff at least ONE of the allowed tools has a requirement the KB satisfies.
|
||||
// Tools without any KB requirement don't contribute — if the allowed-tools
|
||||
// list contains only such tools, the returned filter is empty (accept all).
|
||||
func DeriveKBFilterFromTools(allowedTools []string) KBFilter {
|
||||
seen := make(map[KBCapability]struct{})
|
||||
for _, t := range allowedTools {
|
||||
req, ok := ToolCapabilityRequirements[t]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, c := range req.AnyOf {
|
||||
seen[c] = struct{}{}
|
||||
}
|
||||
for _, c := range req.AllOf {
|
||||
seen[c] = struct{}{}
|
||||
}
|
||||
}
|
||||
if len(seen) == 0 {
|
||||
return KBFilter{}
|
||||
}
|
||||
out := make([]KBCapability, 0, len(seen))
|
||||
for c := range seen {
|
||||
out = append(out, c)
|
||||
}
|
||||
return KBFilter{AnyOf: out}
|
||||
}
|
||||
|
||||
// KBSatisfiesToolRequirements reports whether a single KB is compatible
|
||||
// with the agent's tool set. "Compatible" means: the KB exposes at least
|
||||
// one capability that some tool in `allowedTools` requires. When the tool
|
||||
// set imposes no KB requirement at all, every KB is considered compatible.
|
||||
func KBSatisfiesToolRequirements(caps types.KBCapabilities, allowedTools []string) bool {
|
||||
f := DeriveKBFilterFromTools(allowedTools)
|
||||
if f.IsEmpty() {
|
||||
return true
|
||||
}
|
||||
for _, c := range f.AnyOf {
|
||||
if hasCap(caps, c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ToolsConsumeFiles reports whether any tool in the allowed-tools list can
|
||||
// use user-provided file references. Used to gate the `@file` listing in
|
||||
// the chat input (and potentially SearchKnowledge defensively on the
|
||||
// backend). An empty allowed-tools list is treated as "unknown → permissive".
|
||||
func ToolsConsumeFiles(allowedTools []string) bool {
|
||||
if len(allowedTools) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, t := range allowedTools {
|
||||
req, ok := ToolCapabilityRequirements[t]
|
||||
// Unknown tools (e.g. MCP tools, new builtin not yet registered here):
|
||||
// assume potentially file-consuming to avoid accidentally hiding the
|
||||
// file picker for users who just added a custom tool.
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if req.ConsumesFiles {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
@@ -328,6 +329,22 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
|
||||
switch customAgent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
// Authoritative capability filter for the runtime path. The frontend
|
||||
// editor and @mention dropdown apply the same filter, but we don't
|
||||
// trust the client here: a stale session payload or API caller could
|
||||
// still ask us to retrieve against an incompatible KB and we'd rather
|
||||
// just drop it (and log) than feed it to tools that would no-op.
|
||||
capFilter := tools.DeriveKBFilterFromTools(customAgent.Config.AllowedTools)
|
||||
accept := func(kb *types.KnowledgeBase) bool {
|
||||
if kb == nil {
|
||||
return false
|
||||
}
|
||||
if capFilter.IsEmpty() {
|
||||
return true
|
||||
}
|
||||
return tools.KBSatisfiesToolRequirements(kb.Capabilities(), customAgent.Config.AllowedTools)
|
||||
}
|
||||
|
||||
// Get own knowledge bases (uses ctx TenantID = agent's tenant)
|
||||
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
@@ -335,7 +352,12 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
}
|
||||
kbIDSet := make(map[string]bool)
|
||||
kbIDs := make([]string, 0, len(allKBs))
|
||||
ownSkipped := 0
|
||||
for _, kb := range allKBs {
|
||||
if !accept(kb) {
|
||||
ownSkipped++
|
||||
continue
|
||||
}
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
kbIDSet[kb.ID] = true
|
||||
}
|
||||
@@ -344,6 +366,7 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
// tenant's own KBs. Including the current user's shared KBs would leak
|
||||
// unrelated KBs from other organisations into the agent's retrieval scope.
|
||||
isSharedAgent := sessionTenantID != 0 && sessionTenantID != customAgent.TenantID
|
||||
sharedSkipped := 0
|
||||
if !isSharedAgent {
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
@@ -354,10 +377,15 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||
} else {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && !kbIDSet[info.KnowledgeBase.ID] {
|
||||
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
|
||||
kbIDSet[info.KnowledgeBase.ID] = true
|
||||
if info == nil || info.KnowledgeBase == nil || kbIDSet[info.KnowledgeBase.ID] {
|
||||
continue
|
||||
}
|
||||
if !accept(info.KnowledgeBase) {
|
||||
sharedSkipped++
|
||||
continue
|
||||
}
|
||||
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
|
||||
kbIDSet[info.KnowledgeBase.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -367,6 +395,11 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
sessionTenantID, customAgent.TenantID)
|
||||
}
|
||||
|
||||
if ownSkipped+sharedSkipped > 0 {
|
||||
logger.Infof(ctx,
|
||||
"KBSelectionMode=all: tool-capability filter removed %d own + %d shared KBs (agent=%s, tools=%v)",
|
||||
ownSkipped, sharedSkipped, customAgent.ID, customAgent.Config.AllowedTools)
|
||||
}
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases (own + shared)", len(kbIDs))
|
||||
return kbIDs
|
||||
case "selected":
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
goerrors "errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
@@ -1397,10 +1398,25 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
c.Error(errors.NewInternalServerError("Failed to list knowledge bases").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
// `all` mode: authoritative server-side capability filter. Mirrors the
|
||||
// logic in ListKnowledgeBases so @file search, KB listing, and runtime
|
||||
// all agree on what "mode=all" actually means for this agent.
|
||||
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
|
||||
removed := 0
|
||||
for _, kb := range kbs {
|
||||
if kb != nil && kb.Type == types.KnowledgeBaseTypeDocument {
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID})
|
||||
if kb == nil || kb.Type != types.KnowledgeBaseTypeDocument {
|
||||
continue
|
||||
}
|
||||
if !filter.IsEmpty() && !tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
|
||||
removed++
|
||||
continue
|
||||
}
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID})
|
||||
}
|
||||
if removed > 0 {
|
||||
logger.Infof(ctx,
|
||||
"SearchKnowledge(agent=%s, mode=all): tool-capability filter removed %d KBs",
|
||||
agentID, removed)
|
||||
}
|
||||
}
|
||||
knowledges, hasMore, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
@@ -346,6 +347,30 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
||||
}
|
||||
kbs = filtered
|
||||
}
|
||||
|
||||
// `all` mode: authoritative server-side capability filter so a client
|
||||
// that bypassed the frontend (old tab, curl, rogue plugin) can't @ a
|
||||
// KB whose capabilities don't match any allowed tool of this agent.
|
||||
// Non-`all` modes already constrain the scope explicitly.
|
||||
if mode == "all" && len(agent.Config.AllowedTools) > 0 {
|
||||
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
|
||||
if !filter.IsEmpty() {
|
||||
before := len(kbs)
|
||||
kept := make([]*types.KnowledgeBase, 0, before)
|
||||
for _, kb := range kbs {
|
||||
if tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
|
||||
kept = append(kept, kb)
|
||||
}
|
||||
}
|
||||
if removed := before - len(kept); removed > 0 {
|
||||
logger.Infof(ctx,
|
||||
"ListKnowledgeBases(agent=%s, mode=all): tool-capability filter removed %d of %d KBs",
|
||||
agentID, removed, before)
|
||||
}
|
||||
kbs = kept
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": kbs,
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
@@ -50,9 +52,24 @@ func (c *SearchCommand) Execute(ctx context.Context, cmdCtx *CommandContext, arg
|
||||
case "all":
|
||||
allKBs, err := c.kbService.ListKnowledgeBases(ctx)
|
||||
if err == nil {
|
||||
// Same tool-capability filter as the QA pipeline's
|
||||
// resolveKnowledgeBasesFromAgent (`all` branch) so `/search`
|
||||
// agrees with what the agent's tools can actually reach.
|
||||
filter := tools.DeriveKBFilterFromTools(cmdCtx.CustomAgent.Config.AllowedTools)
|
||||
skipped := 0
|
||||
for _, kb := range allKBs {
|
||||
if !filter.IsEmpty() &&
|
||||
!tools.KBSatisfiesToolRequirements(kb.Capabilities(), cmdCtx.CustomAgent.Config.AllowedTools) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
}
|
||||
if skipped > 0 {
|
||||
logger.Infof(ctx,
|
||||
"/search(agent=%s, mode=all): tool-capability filter removed %d of %d KBs",
|
||||
cmdCtx.CustomAgent.ID, skipped, len(allKBs))
|
||||
}
|
||||
}
|
||||
case "none":
|
||||
// No knowledge bases configured — will return empty results.
|
||||
|
||||
Reference in New Issue
Block a user