feat: Remove outdated analysis and documentation files
- Deleted `AGENT_WIKI_ANALYSIS.md`, `ANALYSIS_SUMMARY.md`, `COMPLETION_REPORT.md`, `DEPLOYMENT_CHECKLIST.md`, `DOCUMENTATION_INDEX.md`, `EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md`, and `EXECUTIVE_SUMMARY.md` as they are no longer relevant to the current project scope. - This cleanup helps streamline the repository and reduces clutter, ensuring that only up-to-date and necessary documentation remains accessible.
This commit is contained in:
@@ -1,619 +0,0 @@
|
||||
# Agent/KB Integration - Implementation Patterns
|
||||
|
||||
This document provides practical implementation patterns and code walkthroughs for working with the agent/KB system.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Creating a Custom Agent](#creating-a-custom-agent)
|
||||
2. [Configuring Agent Knowledge Bases](#configuring-agent-knowledge-bases)
|
||||
3. [Common Configuration Scenarios](#common-configuration-scenarios)
|
||||
4. [Retrieving Search Results](#retrieving-search-results)
|
||||
5. [Debugging Configuration Issues](#debugging-configuration-issues)
|
||||
|
||||
---
|
||||
|
||||
## Creating a Custom Agent
|
||||
|
||||
### Agent Creation Flow
|
||||
|
||||
```go
|
||||
// From handler layer (e.g., HTTP POST /agents)
|
||||
customAgent := &types.CustomAgent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
Name: "Research Assistant",
|
||||
Config: types.CustomAgentConfig{
|
||||
// KB Configuration
|
||||
KBSelectionMode: "selected",
|
||||
KnowledgeBases: []string{"kb-001", "kb-002"},
|
||||
|
||||
// Model Configuration
|
||||
ModelID: "model-gpt4",
|
||||
RerankModelID: "model-rerank",
|
||||
|
||||
// Agent Mode Configuration
|
||||
AgentMode: types.AgentModeSmartReasoning,
|
||||
MaxIterations: 15,
|
||||
Temperature: 0.7,
|
||||
|
||||
// Tool Configuration
|
||||
AllowedTools: []string{
|
||||
tools.ToolKnowledgeSearch,
|
||||
tools.ToolGrepChunks,
|
||||
tools.ToolWebSearch,
|
||||
tools.ToolFinalAnswer,
|
||||
},
|
||||
|
||||
// Retrieval Strategy
|
||||
EmbeddingTopK: 20,
|
||||
VectorThreshold: 0.4,
|
||||
KeywordThreshold: 0.5,
|
||||
RerankTopK: 10,
|
||||
|
||||
// Multi-turn
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
|
||||
// Web Search
|
||||
WebSearchEnabled: true,
|
||||
WebSearchMaxResults: 8,
|
||||
},
|
||||
}
|
||||
|
||||
// Save to database
|
||||
err := s.customAgentRepo.Create(ctx, customAgent)
|
||||
```
|
||||
|
||||
### Agent Defaults
|
||||
|
||||
The system automatically sets defaults for omitted fields:
|
||||
|
||||
```go
|
||||
// From types.CustomAgent.EnsureDefaults()
|
||||
func (a *CustomAgent) EnsureDefaults() {
|
||||
if a.Config.Temperature < 0 {
|
||||
a.Config.Temperature = 0.7
|
||||
}
|
||||
if a.Config.MaxIterations == 0 {
|
||||
a.Config.MaxIterations = 10
|
||||
}
|
||||
if a.Config.WebSearchMaxResults == 0 {
|
||||
a.Config.WebSearchMaxResults = 5
|
||||
}
|
||||
if a.Config.HistoryTurns == 0 {
|
||||
a.Config.HistoryTurns = 5
|
||||
}
|
||||
if a.Config.EmbeddingTopK == 0 {
|
||||
a.Config.EmbeddingTopK = 10
|
||||
}
|
||||
// ... more defaults
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuring Agent Knowledge Bases
|
||||
|
||||
### Pattern 1: "selected" Mode - Specific KBs
|
||||
|
||||
For agents with curated knowledge bases:
|
||||
|
||||
```go
|
||||
customAgent.Config.KBSelectionMode = "selected"
|
||||
customAgent.Config.KnowledgeBases = []string{
|
||||
"sales-kb",
|
||||
"product-docs-kb",
|
||||
"faq-kb",
|
||||
}
|
||||
```
|
||||
|
||||
When a request is made:
|
||||
1. `resolveKnowledgeBases()` detects mode="selected"
|
||||
2. Returns `["sales-kb", "product-docs-kb", "faq-kb"]`
|
||||
3. `buildSearchTargets()` creates 3 SearchTargets (KNOWLEDGE_BASE type)
|
||||
4. Tool receives SearchTargets restricted to these 3 KBs
|
||||
5. Agent cannot access other KBs even if @mentioned
|
||||
|
||||
### Pattern 2: "all" Mode - Dynamic KB Access
|
||||
|
||||
For research agents with broad KB access:
|
||||
|
||||
```go
|
||||
customAgent.Config.KBSelectionMode = "all"
|
||||
customAgent.Config.KnowledgeBases = []string{} // Ignored when mode="all"
|
||||
```
|
||||
|
||||
When a request is made:
|
||||
1. `resolveKnowledgeBases()` calls `ListKnowledgeBases()`
|
||||
2. For non-shared agents: also includes user's shared KBs
|
||||
3. Returns ALL accessible KB IDs at request time
|
||||
4. `buildSearchTargets()` creates SearchTarget for each KB
|
||||
5. Agent can search any accessible KB without reconfiguration
|
||||
|
||||
### Pattern 3: "none" Mode - No KB Access
|
||||
|
||||
For agents that don't use knowledge bases:
|
||||
|
||||
```go
|
||||
customAgent.Config.KBSelectionMode = "none"
|
||||
customAgent.Config.KnowledgeBases = []string{}
|
||||
|
||||
// Knowledge base tools are automatically filtered out
|
||||
// Only web search and other tools available
|
||||
```
|
||||
|
||||
### Pattern 4: RetrieveKBOnlyWhenMentioned - Explicit Selection
|
||||
|
||||
For agents where KB usage is optional:
|
||||
|
||||
```go
|
||||
customAgent.Config.KBSelectionMode = "selected"
|
||||
customAgent.Config.KnowledgeBases = []string{"kb-001", "kb-002"}
|
||||
customAgent.Config.RetrieveKBOnlyWhenMentioned = true
|
||||
```
|
||||
|
||||
Behavior:
|
||||
- Agent has access to kb-001 and kb-002
|
||||
- KB search only occurs if user explicitly @mentions a KB
|
||||
- Without @mention: KB tools won't be called by LLM
|
||||
|
||||
Example query behaviors:
|
||||
```
|
||||
Query: "What is this?"
|
||||
→ No KB search (no @mention)
|
||||
→ May use web search if enabled
|
||||
|
||||
Query: "What is this? @kb-001"
|
||||
→ KB search in kb-001 only
|
||||
→ Respects RetrieveKBOnlyWhenMentioned setting
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Configuration Scenarios
|
||||
|
||||
### Scenario 1: Specialized Domain Expert
|
||||
|
||||
Use case: Agent focused on specific domain (e.g., finance)
|
||||
|
||||
```go
|
||||
customAgent.Config = types.CustomAgentConfig{
|
||||
AgentMode: "smart-reasoning",
|
||||
KBSelectionMode: "selected",
|
||||
KnowledgeBases: []string{"finance-kb", "compliance-kb"},
|
||||
|
||||
AllowedTools: []string{
|
||||
tools.ToolKnowledgeSearch,
|
||||
tools.ToolDatabaseQuery,
|
||||
tools.ToolFinalAnswer,
|
||||
},
|
||||
|
||||
MaxIterations: 20,
|
||||
Temperature: 0.5, // Conservative
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 10,
|
||||
|
||||
EmbeddingTopK: 25,
|
||||
VectorThreshold: 0.6, // High threshold = precise matches
|
||||
|
||||
WebSearchEnabled: false, // Rely on internal KB only
|
||||
}
|
||||
```
|
||||
|
||||
### Scenario 2: General-Purpose Research Assistant
|
||||
|
||||
Use case: Broad access, flexible retrieval
|
||||
|
||||
```go
|
||||
customAgent.Config = types.CustomAgentConfig{
|
||||
AgentMode: "smart-reasoning",
|
||||
KBSelectionMode: "all", // All accessible KBs
|
||||
|
||||
AllowedTools: []string{
|
||||
tools.ToolKnowledgeSearch,
|
||||
tools.ToolGrepChunks,
|
||||
tools.ToolWebSearch,
|
||||
tools.ToolTodoWrite,
|
||||
tools.ToolFinalAnswer,
|
||||
},
|
||||
|
||||
MaxIterations: 15,
|
||||
Temperature: 0.7, // Balanced
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
|
||||
EmbeddingTopK: 10,
|
||||
VectorThreshold: 0.3, // Lower = broader matches
|
||||
|
||||
WebSearchEnabled: true,
|
||||
WebSearchMaxResults: 10,
|
||||
}
|
||||
```
|
||||
|
||||
### Scenario 3: FAQ-Focused Quick Responder
|
||||
|
||||
Use case: Fast answers from FAQ KB only
|
||||
|
||||
```go
|
||||
customAgent.Config = types.CustomAgentConfig{
|
||||
AgentMode: "quick-answer", // RAG mode, not agent mode
|
||||
KBSelectionMode: "selected",
|
||||
KnowledgeBases: []string{"faq-kb"},
|
||||
|
||||
AllowedTools: []string{
|
||||
tools.ToolKnowledgeSearch,
|
||||
tools.ToolFinalAnswer,
|
||||
},
|
||||
|
||||
MaxIterations: 1, // Quick, single shot
|
||||
Temperature: 0.3, // Deterministic
|
||||
MultiTurnEnabled: false,
|
||||
|
||||
EmbeddingTopK: 5,
|
||||
VectorThreshold: 0.7, // Very high = exact matches
|
||||
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.8,
|
||||
FAQScoreBoost: 2.0,
|
||||
}
|
||||
```
|
||||
|
||||
### Scenario 4: Cross-Tenant Shared Agent
|
||||
|
||||
Use case: Agent shared across organizations
|
||||
|
||||
```go
|
||||
// Organization A's agent (owner)
|
||||
sharedAgent := &types.CustomAgent{
|
||||
ID: "shared-research-agent",
|
||||
TenantID: orgAID, // ← Owner is Org A
|
||||
Config: types.CustomAgentConfig{
|
||||
KBSelectionMode: "selected",
|
||||
KnowledgeBases: []string{"orgA-kb-1", "orgA-kb-2"},
|
||||
// ... other config
|
||||
},
|
||||
}
|
||||
|
||||
// When Organization B uses this agent:
|
||||
req := &types.QARequest{
|
||||
CustomAgent: sharedAgent,
|
||||
Session: &types.Session{
|
||||
TenantID: orgBID, // ← User is from Org B
|
||||
},
|
||||
Query: "What is...",
|
||||
}
|
||||
|
||||
// During buildAgentConfig():
|
||||
agentTenantID := sharedAgent.TenantID // orgAID
|
||||
sessionTenantID := req.Session.TenantID // orgBID
|
||||
|
||||
isSharedAgent := sessionTenantID != agentTenantID // TRUE
|
||||
|
||||
// Key behavior:
|
||||
// - Only Org A's KBs (orgA-kb-1, orgA-kb-2) are searched
|
||||
// - Org B user CANNOT add their own KBs via @mention
|
||||
// - This prevents data leak across organizations
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Retrieving Search Results
|
||||
|
||||
### Pattern 1: Direct Tool Usage in Agent
|
||||
|
||||
When agent calls knowledge_search tool:
|
||||
|
||||
```go
|
||||
// In LLM response, agent generates:
|
||||
{
|
||||
"tool_name": "knowledge_search",
|
||||
"arguments": {
|
||||
"queries": [
|
||||
"What are the key features of our product?",
|
||||
"How does the pricing model work?"
|
||||
],
|
||||
"knowledge_base_ids": [] // Optional: empty = search all allowed KBs
|
||||
}
|
||||
}
|
||||
|
||||
// Tool execution (knowledge_search.go:155)
|
||||
func (t *KnowledgeSearchTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
|
||||
var input KnowledgeSearchInput
|
||||
json.Unmarshal(args, &input)
|
||||
|
||||
// t.searchTargets = pre-computed targets from config
|
||||
searchTargets := t.searchTargets
|
||||
|
||||
// If user specifies KBs, filter further
|
||||
if len(input.KnowledgeBaseIDs) > 0 {
|
||||
filtered := filterTargets(searchTargets, input.KnowledgeBaseIDs)
|
||||
searchTargets = filtered
|
||||
}
|
||||
|
||||
// Execute search using all targets
|
||||
results := t.concurrentSearchByTargets(
|
||||
ctx, input.Queries, searchTargets, ...)
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: formatResults(results),
|
||||
Data: resultsAsJSON(results),
|
||||
}, nil
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 2: Non-Agent KB Search (Chat Pipeline)
|
||||
|
||||
```go
|
||||
// Via chat pipeline for non-agent mode
|
||||
chatManage := &types.ChatManage{
|
||||
Query: "Summarize Q3 results",
|
||||
SearchTargets: /* pre-computed */,
|
||||
VectorThreshold: 0.3,
|
||||
KeywordThreshold: 0.5,
|
||||
EmbeddingTopK: 10,
|
||||
}
|
||||
|
||||
// Pipeline plugin executes
|
||||
plugin.OnEvent(ctx, types.CHUNK_SEARCH, chatManage, next)
|
||||
↓
|
||||
plugin.searchByTargets(ctx, chatManage)
|
||||
├─ Groups targets by embedding model
|
||||
├─ For full KBs: HybridSearch(all full KB IDs)
|
||||
├─ For specific files: Per-target search
|
||||
└─ Returns merged SearchResults
|
||||
```
|
||||
|
||||
### Pattern 3: Accessing Single SearchTarget
|
||||
|
||||
```go
|
||||
// When processing specific knowledge files
|
||||
target := &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledge,
|
||||
KnowledgeBaseID: "kb-001",
|
||||
TenantID: tenantID,
|
||||
KnowledgeIDs: []string{"file-1", "file-2"},
|
||||
}
|
||||
|
||||
// In searchSingleTarget (search.go:460)
|
||||
params := types.SearchParams{
|
||||
QueryText: query,
|
||||
QueryEmbedding: embedding,
|
||||
KnowledgeBaseIDs: []string{target.KnowledgeBaseID},
|
||||
KnowledgeIDs: target.KnowledgeIDs, // ← Restricts to these files
|
||||
VectorThreshold: 0.3,
|
||||
KeywordThreshold: 0.5,
|
||||
MatchCount: 10,
|
||||
}
|
||||
|
||||
results, _ := knowledgeBaseService.HybridSearch(ctx, target.KnowledgeBaseID, params)
|
||||
// Returns chunks from kb-001 that are in file-1 or file-2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Debugging Configuration Issues
|
||||
|
||||
### Issue 1: "No Search Targets Available"
|
||||
|
||||
**Error**: Tool returns error "no knowledge bases specified and no search targets configured"
|
||||
|
||||
**Diagnosis**:
|
||||
```go
|
||||
// In knowledge_search.go:196
|
||||
if len(searchTargets) == 0 {
|
||||
logger.Errorf(ctx, "[Tool][KnowledgeSearch] No search targets available")
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "no knowledge bases specified and no search targets configured",
|
||||
}, err
|
||||
}
|
||||
```
|
||||
|
||||
**Causes**:
|
||||
1. Agent configured with KBSelectionMode="none"
|
||||
2. Request has no @mentions and RetrieveKBOnlyWhenMentioned=true
|
||||
3. Agent has no allowed KBs for shared agent scenario
|
||||
|
||||
**Fix**:
|
||||
```go
|
||||
// Check agent config
|
||||
if customAgent.Config.KBSelectionMode == "none" {
|
||||
// Need to enable KB mode
|
||||
customAgent.Config.KBSelectionMode = "selected"
|
||||
customAgent.Config.KnowledgeBases = []string{"kb-id"}
|
||||
}
|
||||
|
||||
// Or check @mention requirement
|
||||
if customAgent.Config.RetrieveKBOnlyWhenMentioned && len(req.KnowledgeBaseIDs) == 0 {
|
||||
// Requires @mention
|
||||
req.KnowledgeBaseIDs = []string{"kb-id"} // User needs to mention
|
||||
}
|
||||
```
|
||||
|
||||
### Issue 2: "Shared Agent Blocked All @Mentions"
|
||||
|
||||
**Error**: @mention filtered out with warning "Blocking @mentioned KB: not in shared agent's allowed scope"
|
||||
|
||||
**Diagnosis**:
|
||||
```go
|
||||
// In session_qa_helpers.go:231
|
||||
if !allowedSet[id] {
|
||||
logger.Warnf(ctx, "Blocking @mentioned KB %s: not in shared agent's allowed scope", id)
|
||||
}
|
||||
```
|
||||
|
||||
**Cause**: Using shared agent from different organization, @mentioning KB outside agent's scope
|
||||
|
||||
**Fix**:
|
||||
```go
|
||||
// Check agent's allowed KBs
|
||||
allowedKBs := customAgent.Config.KnowledgeBases
|
||||
userMentionedKBs := req.KnowledgeBaseIDs
|
||||
|
||||
// Only use KBs that are in both lists
|
||||
validKBs := make([]string, 0)
|
||||
for _, kb := range userMentionedKBs {
|
||||
for _, allowed := range allowedKBs {
|
||||
if kb == allowed {
|
||||
validKBs = append(validKBs, kb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Or: configure agent with mode="all" to allow any KB
|
||||
customAgent.Config.KBSelectionMode = "all"
|
||||
```
|
||||
|
||||
### Issue 3: "Failed to Get Chat Model"
|
||||
|
||||
**Error**: "Failed to get chat model: model not found"
|
||||
|
||||
**Diagnosis**:
|
||||
```go
|
||||
// In session_agent_qa.go:88
|
||||
summaryModel, err := s.modelService.GetChatModel(ctx, effectiveModelID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get chat model: %v", err)
|
||||
return fmt.Errorf("failed to get chat model: %w", err)
|
||||
}
|
||||
```
|
||||
|
||||
**Causes**:
|
||||
1. CustomAgent.Config.ModelID doesn't exist
|
||||
2. No model configured at any level
|
||||
3. Model is disabled/deleted
|
||||
|
||||
**Debug**:
|
||||
```go
|
||||
// Check model resolution priority
|
||||
effectiveModelID := ""
|
||||
|
||||
// Priority 1: Request override
|
||||
if req.SummaryModelID != "" {
|
||||
effectiveModelID = req.SummaryModelID
|
||||
}
|
||||
|
||||
// Priority 2: Agent config
|
||||
if effectiveModelID == "" && customAgent.Config.ModelID != "" {
|
||||
effectiveModelID = customAgent.Config.ModelID
|
||||
}
|
||||
|
||||
// Priority 3: KB default
|
||||
if effectiveModelID == "" {
|
||||
effectiveModelID = s.selectChatModelID(ctx, req.Session, kbs, knowledgeIDs)
|
||||
}
|
||||
|
||||
// Verify model exists
|
||||
model, err := s.modelService.GetChatModel(ctx, effectiveModelID)
|
||||
if err != nil {
|
||||
logger.Infof(ctx, "Model %s not found: %v", effectiveModelID, err)
|
||||
}
|
||||
```
|
||||
|
||||
### Issue 4: Knowledge Base Tools Filtered Out
|
||||
|
||||
**Error**: Agent calls knowledge_search but tool not available
|
||||
|
||||
**Diagnosis**:
|
||||
```go
|
||||
// In agent_service.go:338
|
||||
hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0
|
||||
if !hasKnowledge {
|
||||
// Remove all KB-related tools
|
||||
filteredTools = filterOut(allowedTools, [
|
||||
ToolKnowledgeSearch,
|
||||
ToolGrepChunks,
|
||||
ToolListKnowledgeChunks,
|
||||
// etc
|
||||
])
|
||||
}
|
||||
```
|
||||
|
||||
**Cause**: Agent has no KBs configured
|
||||
|
||||
**Fix**:
|
||||
```go
|
||||
// Ensure at least one KB is configured
|
||||
customAgent.Config.KBSelectionMode = "selected"
|
||||
customAgent.Config.KnowledgeBases = []string{"kb-id"}
|
||||
|
||||
// Or use "all" mode
|
||||
customAgent.Config.KBSelectionMode = "all"
|
||||
```
|
||||
|
||||
### Issue 5: Low Recall (Few Results)
|
||||
|
||||
**Diagnosis**:
|
||||
```
|
||||
Query results: 2 chunks
|
||||
Expected: 10+ chunks
|
||||
```
|
||||
|
||||
**Causes**:
|
||||
1. VectorThreshold too high
|
||||
2. EmbeddingTopK too low
|
||||
3. KB doesn't contain relevant content
|
||||
|
||||
**Tune Parameters**:
|
||||
```go
|
||||
// Lower VectorThreshold for broader matches
|
||||
customAgent.Config.VectorThreshold = 0.3 // Was 0.7
|
||||
|
||||
// Increase TopK to retrieve more candidates
|
||||
customAgent.Config.EmbeddingTopK = 50 // Was 10
|
||||
|
||||
// Or relax keyword matching
|
||||
customAgent.Config.KeywordThreshold = 0.2 // Was 0.5
|
||||
```
|
||||
|
||||
### Issue 6: Rerank Model Missing
|
||||
|
||||
**Error**: "Rerank model not configured for custom agent, but knowledge_search tool is enabled"
|
||||
|
||||
**Diagnosis**:
|
||||
```go
|
||||
// In session_agent_qa.go:104
|
||||
hasKnowledgeSearchTool := false
|
||||
for _, tool := range agentConfig.AllowedTools {
|
||||
if tool == tools.ToolKnowledgeSearch {
|
||||
hasKnowledgeSearchTool = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if hasKnowledgeSearchTool {
|
||||
rerankModelID := req.CustomAgent.Config.RerankModelID
|
||||
if rerankModelID == "" {
|
||||
return errors.New("rerank model is not configured")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Cause**: Using knowledge_search but no rerank model specified
|
||||
|
||||
**Fix**:
|
||||
```go
|
||||
customAgent.Config.RerankModelID = "model-rerank-id"
|
||||
|
||||
// Or disable knowledge_search if rerank unavailable
|
||||
customAgent.Config.AllowedTools = []string{
|
||||
tools.ToolGrepChunks, // Keyword search doesn't need rerank
|
||||
tools.ToolFinalAnswer,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Key patterns to remember:
|
||||
|
||||
1. **Always set KBSelectionMode** - Defaults to "selected" which requires explicit KnowledgeBases
|
||||
2. **SearchTargets computed once** - Set before creating agent engine
|
||||
3. **Tools constrained by SearchTargets** - Cannot search outside pre-computed scope
|
||||
4. **Shared agents cannot leak KBs** - isSharedAgent detection prevents cross-org data access
|
||||
5. **Configuration precedence matters** - Request > Agent > Tenant > System defaults
|
||||
6. **Rerank model required for knowledge_search** - Or use grep_chunks instead
|
||||
7. **Use mode="all" for flexible KB access** - Resolves at request time
|
||||
8. **Use RetrieveKBOnlyWhenMentioned for optional KB** - KB search only on @mention
|
||||
@@ -1,286 +0,0 @@
|
||||
# Agent & Knowledge Base Integration - Quick Reference
|
||||
|
||||
## Core Data Structures
|
||||
|
||||
### Agent Models
|
||||
|
||||
```
|
||||
CustomAgent (persisted)
|
||||
├── ID: agent-uuid or builtin-quick-answer
|
||||
├── TenantID: owner tenant
|
||||
├── Config: CustomAgentConfig
|
||||
│ ├── AvailableKnowledgeBases: []string # Which KBs agent can access
|
||||
│ ├── AvailableKnowledgeIDs: []string # Which documents it can access
|
||||
│ ├── AllowedTools: []string # Tool whitelist
|
||||
│ ├── RerankModelID: string # For search result ranking
|
||||
│ ├── WebSearchEnabled: bool
|
||||
│ ├── MultiTurnEnabled: bool
|
||||
│ ├── RetrieveKBOnlyWhenMentioned: bool
|
||||
│ └── [... more settings ...]
|
||||
└── IsBuiltin: bool
|
||||
|
||||
↓ (Runtime resolution)
|
||||
|
||||
AgentConfig (runtime only)
|
||||
├── KnowledgeBases: []string # Resolved KB IDs
|
||||
├── KnowledgeIDs: []string # Resolved document IDs
|
||||
├── SearchTargets: []*SearchTarget # ← UNIFIED search scope
|
||||
├── AllowedTools: []string
|
||||
├── RetrievalConfig params
|
||||
└── [... execution config ...]
|
||||
```
|
||||
|
||||
### Knowledge Base Model
|
||||
|
||||
```
|
||||
KnowledgeBase
|
||||
├── ID: kb-uuid
|
||||
├── Type: "document" | "faq" | "wiki" # KB type
|
||||
├── TenantID: owner tenant
|
||||
├── EmbeddingModelID: model-id # For vector search
|
||||
├── FAQConfig: FAQConfig (if Type == "faq") # FAQ indexing strategy
|
||||
├── WikiConfig: WikiConfig (if Type == "wiki") # Wiki-specific config
|
||||
└── ChunkingConfig: ChunkingConfig # How documents split
|
||||
```
|
||||
|
||||
### Retrieval Configuration (Tenant-level)
|
||||
|
||||
```
|
||||
RetrievalConfig (at Tenant)
|
||||
├── EmbeddingTopK: int # Vector search: max candidates (default: 50)
|
||||
├── VectorThreshold: float64 # Min similarity 0-1 (default: 0.15)
|
||||
├── KeywordThreshold: float64 # Min keyword match 0-1 (default: 0.3)
|
||||
├── RerankTopK: int # Final results count (default: 10)
|
||||
├── RerankThreshold: float64 # Min rerank score (default: 0.2)
|
||||
└── RerankModelID: string # Which reranker to use
|
||||
|
||||
Tenant.EffectiveEngines: []RetrieverEngineParams
|
||||
├── RetrieverEngineType: "elasticsearch" | "postgres" | "qdrant" | ...
|
||||
└── RetrieverType: "vector" | "keywords" | "websearch"
|
||||
```
|
||||
|
||||
## How Agents Access KBs: Step-by-Step
|
||||
|
||||
### 1. Request Arrives
|
||||
```
|
||||
QARequest {
|
||||
Query: "user question",
|
||||
Agent: CustomAgent (with Config.AvailableKnowledgeBases),
|
||||
SessionAgentConfig: {KnowledgeBases: override} // optional override
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Resolve Runtime Configuration
|
||||
```
|
||||
buildAgentConfig() {
|
||||
// Merge CustomAgent + SessionAgentConfig
|
||||
agentConfig.KnowledgeBases = resolveKnowledgeBases(customAgent, sessionConfig)
|
||||
agentConfig.KnowledgeIDs = resolveKnowledgeIDs(...)
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Convert to Unified Search Targets
|
||||
```
|
||||
buildSearchTargets(knowledgeBaseIDs, knowledgeIDs) {
|
||||
// For each KB:
|
||||
targets.append(SearchTarget{
|
||||
Type: "knowledge_base", // Search entire KB
|
||||
KnowledgeBaseID: id,
|
||||
TenantID: resolved_tenant,
|
||||
KnowledgeIDs: [] // Empty = whole KB
|
||||
})
|
||||
|
||||
// For specific documents:
|
||||
targets.append(SearchTarget{
|
||||
Type: "knowledge", // Search specific files
|
||||
KnowledgeBaseID: parent_kb,
|
||||
TenantID: resolved_tenant,
|
||||
KnowledgeIDs: [doc1, doc2, ...] // Only these
|
||||
})
|
||||
}
|
||||
// Result stored in: AgentConfig.SearchTargets
|
||||
```
|
||||
|
||||
### 4. Agent Calls Retrieval Tool
|
||||
```
|
||||
Agent's thought: "I need to search knowledge..."
|
||||
Agent.ExecuteTool("knowledge_search", {
|
||||
queries: ["What is RAG?"],
|
||||
knowledge_base_ids: [] // if empty, uses SearchTargets
|
||||
})
|
||||
```
|
||||
|
||||
### 5. Tool Performs Hybrid Search
|
||||
```
|
||||
Tool.Execute() {
|
||||
// Get query embedding
|
||||
queryEmbedding = getEmbedding(query) // from KB's EmbeddingModelID
|
||||
|
||||
// Call HybridSearch
|
||||
results = HybridSearch(kb_id, {
|
||||
QueryText: query,
|
||||
Embedding: queryEmbedding,
|
||||
KnowledgeIDs: target.KnowledgeIDs, // Scoped if present
|
||||
VectorThreshold: retrieval_config.threshold,
|
||||
KeywordThreshold: retrieval_config.threshold,
|
||||
MatchCount: retrieval_config.top_k,
|
||||
RetrieverType: "vector" // for vector search
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Hybrid Search Orchestrates Retrieval
|
||||
```
|
||||
HybridSearch(kb_id, params) {
|
||||
// 1. Create composite engine from tenant's configured backends
|
||||
engine = CompositeRetrieveEngine(tenant.EffectiveEngines)
|
||||
|
||||
// 2. Execute parallel retrieval
|
||||
vectorResults = engine.Retrieve(RetrieveParams{
|
||||
RetrieverType: "vector",
|
||||
KnowledgeBaseIDs: [kb_id],
|
||||
Embedding: query_embedding,
|
||||
Threshold: vector_threshold,
|
||||
TopK: 5x over_retrieval
|
||||
})
|
||||
|
||||
keywordResults = engine.Retrieve(RetrieveParams{
|
||||
RetrieverType: "keywords",
|
||||
KnowledgeBaseIDs: [kb_id],
|
||||
Query: query_text,
|
||||
Threshold: keyword_threshold,
|
||||
TopK: 5x over_retrieval
|
||||
})
|
||||
|
||||
// 3. Merge with RRF (Reciprocal Rank Fusion)
|
||||
merged = RRF(vectorResults, keywordResults)
|
||||
|
||||
// 4. Rerank
|
||||
final = Rerank(merged, rerank_model, top_k=10)
|
||||
|
||||
return final
|
||||
}
|
||||
```
|
||||
|
||||
### 7. CompositeRetrieveEngine Routes to Backend
|
||||
```
|
||||
CompositeRetrieveEngine.Retrieve(params) {
|
||||
// params.RetrieverType = "vector" or "keywords"
|
||||
|
||||
// Find engine that supports this type
|
||||
for engineInfo in this.engineInfos {
|
||||
if engineInfo.supports(params.RetrieverType) {
|
||||
return engineInfo.engine.Retrieve(params) // Delegate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Backends that might handle it:
|
||||
// - "vector" type → Elasticsearch, Qdrant, Milvus, etc.
|
||||
// - "keywords" type → Elasticsearch, PostgreSQL, etc.
|
||||
```
|
||||
|
||||
## Enumeration Reference
|
||||
|
||||
### RetrieverType (what to search)
|
||||
- `"vector"` - Semantic/embedding search
|
||||
- `"keywords"` - Exact keyword/full-text search
|
||||
- `"websearch"` - External web search
|
||||
|
||||
### RetrieverEngineType (where to search)
|
||||
- `"elasticsearch"` - ES backend (supports both vector & keywords)
|
||||
- `"postgres"` - PostgreSQL (keywords)
|
||||
- `"qdrant"` - Qdrant vector DB
|
||||
- `"infinity"` - Infinity vector DB
|
||||
- `"milvus"` - Milvus vector DB
|
||||
- `"weaviate"` - Weaviate vector DB
|
||||
- `"elasticfaiss"` - FAISS indices
|
||||
- `"sqlite"` - SQLite (keywords)
|
||||
|
||||
### SearchTargetType
|
||||
- `"knowledge_base"` - Search entire KB
|
||||
- `"knowledge"` - Search specific files/documents only
|
||||
|
||||
### KnowledgeBase Type
|
||||
- `"document"` - Standard documents
|
||||
- `"faq"` - FAQ pairs
|
||||
- `"wiki"` - Wiki pages
|
||||
|
||||
## Tool Choices
|
||||
|
||||
### Available Tools (Agents can use)
|
||||
- `"knowledge_search"` → VectorRetrieverType (semantic)
|
||||
- `"grep_chunks"` → KeywordsRetrieverType (exact match)
|
||||
- `"list_knowledge_chunks"` → Direct doc access
|
||||
- `"query_knowledge_graph"` → Graph search
|
||||
- `"web_search"` → WebSearchRetrieverType
|
||||
- `"wiki_search"` → Wiki search
|
||||
- [... and more]
|
||||
|
||||
**Agent decides which tool → System routes to right backend**
|
||||
|
||||
## Configuration Precedence (lowest to highest)
|
||||
|
||||
1. **System default** (hardcoded)
|
||||
- `EmbeddingTopK = 50`
|
||||
- `VectorThreshold = 0.15`
|
||||
|
||||
2. **Knowledge Base config**
|
||||
- `KB.EmbeddingModelID` (which embedding model)
|
||||
- `KB.FAQConfig` (FAQ indexing strategy)
|
||||
|
||||
3. **Tenant-level RetrievalConfig**
|
||||
- `RetrievalConfig.EmbeddingTopK`
|
||||
- `RetrievalConfig.VectorThreshold`
|
||||
- `Tenant.EffectiveEngines` (which backends)
|
||||
|
||||
4. **Agent-level config**
|
||||
- `CustomAgentConfig.AllowedTools`
|
||||
- `CustomAgentConfig.RerankModelID`
|
||||
|
||||
5. **Session-level override**
|
||||
- `SessionAgentConfig.KnowledgeBases` (restrict KBs)
|
||||
|
||||
6. **Request-level**
|
||||
- Tool parameters (e.g., explicit `knowledge_base_ids`)
|
||||
|
||||
## Key Files
|
||||
|
||||
| Layer | File | Key Classes |
|
||||
|-------|------|-------------|
|
||||
| **Model** | `internal/types/agent.go` | `AgentConfig`, `SessionAgentConfig` |
|
||||
| **Model** | `internal/types/custom_agent.go` | `CustomAgent`, `CustomAgentConfig` |
|
||||
| **Model** | `internal/types/knowledgebase.go` | `KnowledgeBase` |
|
||||
| **Model** | `internal/types/retrieval_config.go` | `RetrievalConfig` |
|
||||
| **Model** | `internal/types/retriever.go` | `RetrieverType`, `RetrieverEngineType` |
|
||||
| **Model** | `internal/types/search.go` | `SearchTarget`, `SearchTargets` |
|
||||
| **Service** | `internal/application/service/session_agent_qa.go` | `buildAgentConfig`, `buildSearchTargets` |
|
||||
| **Service** | `internal/application/service/knowledgebase_search.go` | `HybridSearch` |
|
||||
| **Service** | `internal/application/service/retriever/composite.go` | `CompositeRetrieveEngine` |
|
||||
| **Tool** | `internal/agent/tools/knowledge_search.go` | Knowledge search tool impl |
|
||||
| **Tool** | `internal/agent/tools/definitions.go` | Tool registry, tool names |
|
||||
| **Pipeline** | `internal/application/service/chat_pipeline/search.go` | `PluginSearch` (chat pipeline) |
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Q: How does an agent know which KBs to search?
|
||||
**A:** `AgentConfig.SearchTargets` - pre-computed at request entry point, contains all KBs the agent has access to (after resolving CustomAgent + SessionAgentConfig + permissions)
|
||||
|
||||
### Q: Can an agent search multiple KBs with one query?
|
||||
**A:** Yes! If they share the same embedding model:
|
||||
- `HybridSearch(kb1_id, params{KnowledgeBaseIDs: [kb1, kb2, kb3]})`
|
||||
- Results are merged and reranked together
|
||||
|
||||
### Q: How are vector vs keyword results combined?
|
||||
**A:** RRF (Reciprocal Rank Fusion) - mathematical fusion of ranks, then reranked
|
||||
|
||||
### Q: What decides: Elasticsearch vs Qdrant?
|
||||
**A:** `Tenant.EffectiveEngines` - configured at tenant level, tells system which backend handles which retriever type
|
||||
|
||||
### Q: Can an agent override its KB list?
|
||||
**A:** Partially - `SessionAgentConfig.KnowledgeBases` can restrict (not expand) at session level
|
||||
|
||||
### Q: Where is reranking configured?
|
||||
**A:**
|
||||
- Agent level: `CustomAgentConfig.RerankModelID` (which model)
|
||||
- Tenant level: `RetrievalConfig.RerankTopK`, `RerankThreshold` (result quality thresholds)
|
||||
@@ -1,581 +0,0 @@
|
||||
# Agent/Bot Knowledge Base Integration Architecture
|
||||
|
||||
## Overview
|
||||
This document maps how agents/bots in WeKnora use knowledge bases, reference datasets, configure retrieval strategies, and execute the retrieval pipeline.
|
||||
|
||||
---
|
||||
|
||||
## 1. AGENT/BOT MODEL DEFINITIONS
|
||||
|
||||
### Primary Models
|
||||
|
||||
#### `CustomAgent` (`internal/types/custom_agent.go`)
|
||||
- **Role**: User-configurable AI agent (similar to GPTs)
|
||||
- **Key Fields**:
|
||||
- `ID`: Agent identifier (UUID for custom, or `builtin-*` prefix for built-in)
|
||||
- `TenantID`: Owner tenant (composite primary key with ID)
|
||||
- `Config`: `CustomAgentConfig` struct containing full configuration
|
||||
- `IsBuiltin`: Boolean flag (built-in vs. custom)
|
||||
|
||||
**Built-in Agent IDs**:
|
||||
- `builtin-quick-answer`: RAG mode for Q&A
|
||||
- `builtin-smart-reasoning`: ReAct mode for multi-step reasoning
|
||||
- `builtin-deep-researcher`, `builtin-data-analyst`, etc.
|
||||
|
||||
#### `AgentConfig` (`internal/types/agent.go`)
|
||||
- **Role**: Runtime agent configuration (resolved from CustomAgent + Tenant config)
|
||||
- **Key Fields**:
|
||||
```go
|
||||
KnowledgeBases []string // Accessible KB IDs
|
||||
KnowledgeIDs []string // Individual document IDs (within KBs)
|
||||
SearchTargets SearchTargets // Pre-computed unified search targets (runtime only)
|
||||
AllowedTools []string // List of tool names agent can use
|
||||
WebSearchEnabled bool // Whether web search is available
|
||||
MultiTurnEnabled bool // Multi-turn conversation support
|
||||
RetrieveKBOnlyWhenMentioned bool // Only retrieve KB when explicitly mentioned with @
|
||||
Thinking *bool // Extended thinking mode support
|
||||
LLMCallTimeout int // Single LLM call timeout in seconds
|
||||
```
|
||||
|
||||
#### `SessionAgentConfig` (`internal/types/agent.go`)
|
||||
- **Role**: Session-level agent override
|
||||
- **Immutable fields only**: `AgentModeEnabled`, `WebSearchEnabled`, `KnowledgeBases`, `KnowledgeIDs`
|
||||
- Other configs read from Tenant at runtime
|
||||
|
||||
---
|
||||
|
||||
## 2. KNOWLEDGE BASE BINDING
|
||||
|
||||
### How Agents Reference Knowledge Bases
|
||||
|
||||
**Path**: `internal/types/agent.go` → `AgentConfig.KnowledgeBases[]`
|
||||
|
||||
1. **Agent Config Level**:
|
||||
- `CustomAgentConfig.AvailableKnowledgeBases` contains KB IDs agent can access
|
||||
- These are stored in the agent definition
|
||||
|
||||
2. **Session Override Level**:
|
||||
- `SessionAgentConfig.KnowledgeBases` can override/restrict agent's KB access
|
||||
- Resolved at request entry point
|
||||
|
||||
3. **Runtime Resolution** (`session_agent_qa.go:242`):
|
||||
```go
|
||||
agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs =
|
||||
s.resolveKnowledgeBases(ctx, req)
|
||||
```
|
||||
|
||||
### Knowledge Base Model (`internal/types/knowledgebase.go`)
|
||||
|
||||
```go
|
||||
type KnowledgeBase struct {
|
||||
ID string // Unique identifier
|
||||
Type string // "document", "faq", "wiki"
|
||||
TenantID uint64 // Owner tenant
|
||||
EmbeddingModelID string // Embedding model for vectors
|
||||
ChunkingConfig ChunkingConfig // Document splitting strategy
|
||||
FAQConfig *FAQConfig // FAQ-specific indexing options
|
||||
WikiConfig *WikiConfig // Wiki-specific configuration
|
||||
VLMConfig VLMConfig // Vision model for image processing
|
||||
QuestionGenerationConfig *QuestionGenerationConfig // Auto-generate questions
|
||||
// ... other metadata
|
||||
}
|
||||
```
|
||||
|
||||
**Knowledge Base Types**:
|
||||
- `"document"`: Standard document-based KB
|
||||
- `"faq"`: FAQ pairs (question-answer)
|
||||
- `"wiki"`: Wiki pages with structured content
|
||||
|
||||
---
|
||||
|
||||
## 3. RETRIEVAL STRATEGY CONFIGURATION
|
||||
|
||||
### Global Retrieval Configuration (`internal/types/retrieval_config.go`)
|
||||
|
||||
**Stored at**: Tenant level (JSONB column in `tenants` table)
|
||||
**Managed via**: Settings UI at `/tenants/kv/retrieval-config`
|
||||
|
||||
```go
|
||||
type RetrievalConfig struct {
|
||||
EmbeddingTopK int // Vector search result limit (default: 50)
|
||||
VectorThreshold float64 // Min similarity score 0-1 (default: 0.15)
|
||||
KeywordThreshold float64 // Min keyword match score 0-1 (default: 0.3)
|
||||
RerankTopK int // Results after reranking (default: 10)
|
||||
RerankThreshold float64 // Min rerank score (default: 0.2)
|
||||
RerankModelID string // Rerank model to use
|
||||
}
|
||||
```
|
||||
|
||||
**Application**: Used by all chat/search operations in the tenant
|
||||
|
||||
### Retriever Types (`internal/types/retriever.go`)
|
||||
|
||||
```go
|
||||
type RetrieverType string
|
||||
|
||||
const (
|
||||
KeywordsRetrieverType RetrieverType = "keywords" // Exact/keyword matching
|
||||
VectorRetrieverType RetrieverType = "vector" // Semantic/embedding search
|
||||
WebSearchRetrieverType RetrieverType = "websearch" // Web search
|
||||
)
|
||||
```
|
||||
|
||||
### Retriever Engine Types (`internal/types/retriever.go`)
|
||||
|
||||
```go
|
||||
type RetrieverEngineType string
|
||||
|
||||
const (
|
||||
PostgresRetrieverEngineType RetrieverEngineType = "postgres" // Native SQL
|
||||
ElasticsearchRetrieverEngineType RetrieverEngineType = "elasticsearch" // ES
|
||||
InfinityRetrieverEngineType RetrieverEngineType = "infinity" // Vector DB
|
||||
ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss" // FAISS
|
||||
QdrantRetrieverEngineType RetrieverEngineType = "qdrant" // Qdrant
|
||||
MilvusRetrieverEngineType RetrieverEngineType = "milvus" // Milvus
|
||||
WeaviateRetrieverEngineType RetrieverEngineType = "weaviate" // Weaviate
|
||||
SQLiteRetrieverEngineType RetrieverEngineType = "sqlite" // SQLite
|
||||
)
|
||||
```
|
||||
|
||||
### Retriever Engine Configuration (Tenant-level)
|
||||
|
||||
**Field**: `Tenant.EffectiveEngines` → `[]RetrieverEngineParams`
|
||||
|
||||
```go
|
||||
type RetrieverEngineParams struct {
|
||||
RetrieverEngineType RetrieverEngineType // e.g., "elasticsearch"
|
||||
RetrieverType RetrieverType // e.g., "vector" or "keywords"
|
||||
}
|
||||
```
|
||||
|
||||
**Determines**: Which physical backend (ES, Postgres, etc.) handles which retrieval type
|
||||
|
||||
---
|
||||
|
||||
## 4. THE RETRIEVAL PIPELINE
|
||||
|
||||
### Entry Point: Agent Execution
|
||||
|
||||
**File**: `internal/application/service/session_agent_qa.go`
|
||||
|
||||
**Flow**:
|
||||
1. **Request arrives** with `QARequest` containing user query and agent ID
|
||||
2. **Resolve Tenant**: Determine retrieval tenant (own tenant or shared agent tenant)
|
||||
3. **Build AgentConfig** (line 210-298):
|
||||
```go
|
||||
func (s *sessionService) buildAgentConfig(ctx context.Context, ...) {
|
||||
// ... resolve KnowledgeBases and KnowledgeIDs
|
||||
agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs =
|
||||
s.resolveKnowledgeBases(ctx, req)
|
||||
|
||||
// Build SearchTargets (next step)
|
||||
searchTargets, _ := s.buildSearchTargets(ctx, agentTenantID,
|
||||
agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
|
||||
agentConfig.SearchTargets = searchTargets
|
||||
}
|
||||
```
|
||||
|
||||
### Stage 1: Build Search Targets (`session_knowledge_qa.go:393-486`)
|
||||
|
||||
**Function**: `buildSearchTargets(ctx, tenantID, knowledgeBaseIDs, knowledgeIDs)`
|
||||
|
||||
**Purpose**: Convert KnowledgeBase IDs and Knowledge IDs into unified SearchTargets
|
||||
|
||||
**Output**: `SearchTargets` = `[]*SearchTarget`
|
||||
|
||||
```go
|
||||
type SearchTarget struct {
|
||||
Type SearchTargetType // "knowledge_base" or "knowledge"
|
||||
KnowledgeBaseID string // KB to search
|
||||
TenantID uint64 // KB's tenant (for cross-tenant shared KBs)
|
||||
KnowledgeIDs []string // Specific file IDs (only for "knowledge" type)
|
||||
}
|
||||
```
|
||||
|
||||
**Logic**:
|
||||
```
|
||||
For each KnowledgeBaseID:
|
||||
→ Create SearchTarget(Type=knowledge_base, KnowledgeBaseID=id, TenantID=resolved)
|
||||
|
||||
For each KnowledgeID:
|
||||
→ Find its parent KnowledgeBase
|
||||
→ If KB not already fully searched, create SearchTarget(Type=knowledge,
|
||||
KnowledgeBaseID=parent, KnowledgeIDs=[kid1, kid2, ...])
|
||||
```
|
||||
|
||||
**Stored in**: `AgentConfig.SearchTargets` (runtime only, not persisted)
|
||||
|
||||
### Stage 2: Agent Initialization
|
||||
|
||||
**File**: `internal/application/service/agent_service.go:81-179`
|
||||
|
||||
**Creates**: `AgentEngine` with:
|
||||
- `AgentConfig` (with SearchTargets)
|
||||
- Chat model
|
||||
- Rerank model
|
||||
- Event bus
|
||||
- Context manager
|
||||
|
||||
### Stage 3: Tool Execution - Knowledge Search
|
||||
|
||||
**File**: `internal/agent/tools/knowledge_search.go`
|
||||
|
||||
**Tool Definition**:
|
||||
- **Name**: `"knowledge_search"`
|
||||
- **Type**: `BaseTool`
|
||||
- **Description**: Semantic/vector search for retrieving knowledge by meaning
|
||||
- **Input**: 1-5 semantic queries (not raw text)
|
||||
- **Retrieval Strategy**: Uses vector/semantic matching
|
||||
|
||||
**Execution Flow** (Execute method):
|
||||
1. Parse input queries
|
||||
2. Get embedding model from KB
|
||||
3. Compute query embeddings
|
||||
4. Call HybridSearch with SearchTargets
|
||||
5. Return ranked results
|
||||
|
||||
### Stage 4: Hybrid Search (`knowledgebase_search.go:77-120`)
|
||||
|
||||
**Function**: `HybridSearch(ctx, kbID, params)`
|
||||
|
||||
**Parameters**:
|
||||
- `kbID`: Primary KB (or first of multiple)
|
||||
- `params.KnowledgeBaseIDs`: Override IDs (for multi-KB search with same embedding model)
|
||||
- `params.QueryText`: Query string
|
||||
- `params.VectorThreshold`: Min vector similarity
|
||||
- `params.KeywordThreshold`: Min keyword score
|
||||
- `params.MatchCount`: Desired results
|
||||
- `params.DisableVectorMatch / DisableKeywordsMatch`: Optional disable flags
|
||||
|
||||
**Process**:
|
||||
```
|
||||
1. Determine search KBs (use params.KnowledgeBaseIDs if provided, else [kbID])
|
||||
2. Create CompositeRetrieveEngine with tenant's configured engines
|
||||
3. For each KB:
|
||||
a. Get embedding model
|
||||
b. Compute query embedding (if vector search enabled)
|
||||
c. Create vector + keyword retrieve jobs
|
||||
4. Execute parallel retrieval across all engines
|
||||
5. Deduplicate and merge results
|
||||
6. Apply RRF (Reciprocal Rank Fusion) fusion
|
||||
7. Rerank using rerank model
|
||||
8. Return top results
|
||||
```
|
||||
|
||||
### Stage 5: Composite Retrieval Engine (`internal/application/service/retriever/composite.go`)
|
||||
|
||||
**Role**: Routes retrieval requests to correct backend based on RetrieverType
|
||||
|
||||
**Structure**:
|
||||
```go
|
||||
type CompositeRetrieveEngine struct {
|
||||
engineInfos []*engineInfo // Each maps RetrieverType to backend engine
|
||||
}
|
||||
|
||||
type engineInfo struct {
|
||||
retrieveEngine interfaces.RetrieveEngineService
|
||||
retrieverType []types.RetrieverType // "vector", "keywords", etc.
|
||||
}
|
||||
```
|
||||
|
||||
**Dispatch Logic** (`Retrieve` method):
|
||||
```go
|
||||
For each RetrieveParams:
|
||||
Find first engineInfo that supports params.RetrieverType
|
||||
Delegate to that engine's Retrieve method
|
||||
```
|
||||
|
||||
**Created from Tenant config**:
|
||||
```go
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
registry,
|
||||
tenantInfo.GetEffectiveEngines() // []RetrieverEngineParams
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. SEARCH/RETRIEVAL TARGETS AT REQUEST LEVEL
|
||||
|
||||
### ChatManage (Pipeline State)
|
||||
|
||||
**File**: `internal/types/chat_manage.go`
|
||||
|
||||
```go
|
||||
type ChatManage struct {
|
||||
// Immutable config (set at entry point)
|
||||
PipelineRequest struct {
|
||||
KnowledgeBaseIDs []string // User-selected KBs
|
||||
KnowledgeIDs []string // User-selected specific files
|
||||
SearchTargets SearchTargets // Pre-computed unified targets
|
||||
VectorThreshold float64 // From tenant RetrievalConfig
|
||||
KeywordThreshold float64 // From tenant RetrievalConfig
|
||||
EmbeddingTopK int // From tenant RetrievalConfig
|
||||
VectorDatabase string // Primary vector DB selection
|
||||
}
|
||||
// Mutable state
|
||||
PipelineState struct {
|
||||
SearchResult []*SearchResult // Raw search results
|
||||
RerankResult []*SearchResult // After reranking
|
||||
MergeResult []*SearchResult // After context merging
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### SearchTargets Usage
|
||||
|
||||
**Used by**: Chat pipeline plugins
|
||||
|
||||
**File**: `internal/application/service/chat_pipeline/search.go`
|
||||
|
||||
```go
|
||||
func (p *PluginSearch) OnEvent(ctx, event, chatManage, next) error {
|
||||
// Check if targets exist
|
||||
if len(chatManage.SearchTargets) == 0 {
|
||||
// No targets, skip KB search (unless web search enabled)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Execute KB search using SearchTargets
|
||||
kbResults := p.searchByTargets(ctx, chatManage)
|
||||
|
||||
// searchByTargets iterates SearchTargets and queries each
|
||||
for _, target := range chatManage.SearchTargets {
|
||||
// Determine which index to query based on target
|
||||
results := p.knowledgeBaseService.HybridSearch(
|
||||
ctx, target.KnowledgeBaseID,
|
||||
types.SearchParams{
|
||||
KnowledgeBaseIDs: []string{target.KnowledgeBaseID},
|
||||
KnowledgeIDs: target.KnowledgeIDs, // Scoped if present
|
||||
QueryText: chatManage.RewriteQuery,
|
||||
// ... thresholds, top K from RetrievalConfig
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. AGENT-LEVEL RETRIEVAL PREFERENCES
|
||||
|
||||
### AgentConfig: Retrieval Preferences
|
||||
|
||||
**Stored in CustomAgentConfig**:
|
||||
|
||||
```go
|
||||
type CustomAgentConfig struct {
|
||||
// Tool selection
|
||||
AllowedTools []string // e.g., ["knowledge_search", "web_search", ...]
|
||||
|
||||
// Retrieval triggers
|
||||
RetrieveKBOnlyWhenMentioned bool // @mention required for KB search
|
||||
|
||||
// Search strategy
|
||||
WebSearchEnabled bool // Enable web search tool
|
||||
WebSearchMaxResults int // Max web results to return
|
||||
WebSearchProviderID string // Which web search provider
|
||||
|
||||
// Model selection for retrieval
|
||||
RerankModelID string // Rerank model for search results
|
||||
|
||||
// History management
|
||||
MultiTurnEnabled bool // Use conversation history
|
||||
HistoryTurns int // How many previous turns to keep
|
||||
|
||||
// Context management
|
||||
RetainRetrievalHistory bool // Keep wiki_read_page results across turns
|
||||
}
|
||||
```
|
||||
|
||||
### Agent Tool Definitions
|
||||
|
||||
**File**: `internal/agent/tools/definitions.go`
|
||||
|
||||
**Key Tools for Knowledge Retrieval**:
|
||||
|
||||
1. **`knowledge_search`** (Semantic Search)
|
||||
- Purpose: Vector/embedding-based semantic search
|
||||
- Input: 1-5 semantic queries (not raw text)
|
||||
- Backends: Vector retrieval engines
|
||||
- RetrievalType: `VectorRetrieverType`
|
||||
|
||||
2. **`grep_chunks`** (Keyword Search)
|
||||
- Purpose: Exact keyword/literal matching
|
||||
- Input: Keywords to find
|
||||
- Backends: Keyword retrieval engines (ES, SQL)
|
||||
- RetrievalType: `KeywordsRetrieverType`
|
||||
|
||||
3. **`list_knowledge_chunks`** (List Chunks)
|
||||
- Purpose: Browse document chunks
|
||||
- Input: KB ID, document ID
|
||||
- Backends: Direct document lookup
|
||||
|
||||
4. **`wiki_search`** (Wiki Search)
|
||||
- Purpose: Search within wiki pages
|
||||
- Input: Query
|
||||
- Backends: Wiki-specific retrieval
|
||||
|
||||
5. **`web_search`** (Web Search)
|
||||
- Purpose: Search the internet
|
||||
- Input: Query
|
||||
- Backends: External web search provider
|
||||
- RetrievalType: `WebSearchRetrieverType`
|
||||
|
||||
**Default Allowed Tools**:
|
||||
```go
|
||||
[]string{
|
||||
ToolThinking,
|
||||
ToolTodoWrite,
|
||||
ToolKnowledgeSearch, // Vector search
|
||||
ToolGrepChunks, // Keyword search
|
||||
ToolListKnowledgeChunks,
|
||||
ToolWebSearch,
|
||||
ToolWebFetch,
|
||||
ToolFinalAnswer,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. KEY DECISION FLOWS
|
||||
|
||||
### Decision 1: Which KB to Search?
|
||||
1. Agent has `AgentConfig.SearchTargets`
|
||||
2. When agent calls tool, it optionally specifies `knowledge_base_ids`
|
||||
3. If not specified, uses all SearchTargets
|
||||
4. Explicit KB param overrides agent defaults
|
||||
|
||||
### Decision 2: Which Retrieval Strategy?
|
||||
1. Agent decides: calls `knowledge_search` (vector) or `grep_chunks` (keyword)
|
||||
2. Or both sequentially with different queries
|
||||
3. Or combines with `query_knowledge_graph` (graph search)
|
||||
4. Tool makes the strategic choice, not the system
|
||||
|
||||
### Decision 3: Which Backend?
|
||||
1. `RetrieveParams.RetrieverType` set by tool
|
||||
2. CompositeRetrieveEngine looks up configured engines
|
||||
3. Finds engine that supports that RetrieverType
|
||||
4. Delegates to that backend
|
||||
|
||||
### Decision 4: Result Quality (Reranking)?
|
||||
1. `RetrievalConfig.RerankModelID` specifies reranker
|
||||
2. HybridSearch uses it to rerank combined results
|
||||
3. Threshold applied: `RetrievalConfig.RerankThreshold`
|
||||
4. Top-K applied: `RetrievalConfig.RerankTopK`
|
||||
|
||||
---
|
||||
|
||||
## 8. DATA FLOW DIAGRAM
|
||||
|
||||
```
|
||||
Request
|
||||
↓
|
||||
QARequest (agent ID, query, KB IDs)
|
||||
↓
|
||||
BuildAgentConfig
|
||||
├→ Resolve KnowledgeBases from agent + session override
|
||||
├→ Resolve KnowledgeIDs (individual documents)
|
||||
├→ BuildSearchTargets (converts KB IDs → SearchTargets)
|
||||
└→ AgentConfig.SearchTargets = [SearchTarget{...}, ...]
|
||||
↓
|
||||
CreateAgentEngine(AgentConfig, ChatModel, RerankModel)
|
||||
├→ Register tools (knowledge_search, grep_chunks, web_search, ...)
|
||||
└→ Tool registry has access to SearchTargets
|
||||
↓
|
||||
Agent Execution Loop (ReAct)
|
||||
↓
|
||||
Agent calls tool (e.g., knowledge_search)
|
||||
├→ Tool receives SearchTargets from AgentConfig
|
||||
├→ Optionally filters by knowledge_base_ids param
|
||||
└→ Computes query embedding
|
||||
↓
|
||||
HybridSearch(kb_id, params)
|
||||
├→ Create CompositeRetrieveEngine with tenant engines
|
||||
├→ Parallel: Vector search + Keyword search
|
||||
├→ Both call Retrieve() which dispatches to backends
|
||||
└→ Merge + Rerank + Return
|
||||
↓
|
||||
Backend (ES, Postgres, Qdrant, etc.)
|
||||
├→ Vector search via embedding DB
|
||||
├→ Keyword search via ES/SQL
|
||||
└→ Return scored results
|
||||
↓
|
||||
RRF Fusion (combine vector + keyword)
|
||||
↓
|
||||
Reranker (optional)
|
||||
↓
|
||||
Top-K Results
|
||||
↓
|
||||
Tool Result → Agent Thought/Action Loop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. CONFIGURATION PRECEDENCE
|
||||
|
||||
For any retrieval operation:
|
||||
|
||||
1. **Agent-level**:
|
||||
- `CustomAgentConfig.AllowedTools` (which tools available)
|
||||
- `CustomAgentConfig.RetrieveKBOnlyWhenMentioned` (when to retrieve)
|
||||
- `CustomAgentConfig.KnowledgeBases` (which KBs)
|
||||
|
||||
2. **Session-level override**:
|
||||
- `SessionAgentConfig.KnowledgeBases` (restrict agent's KBs)
|
||||
|
||||
3. **Request-level**:
|
||||
- Query string, optional KB filter, images, etc.
|
||||
|
||||
4. **Tenant-level**:
|
||||
- `RetrievalConfig` (thresholds, top-K, reranker)
|
||||
- `Tenant.EffectiveEngines` (which backends for vector/keyword)
|
||||
|
||||
5. **Knowledge Base-level**:
|
||||
- `KnowledgeBase.EmbeddingModelID` (which embedding model)
|
||||
- `KnowledgeBase.Type` (document vs FAQ vs wiki)
|
||||
- `KnowledgeBase.FAQConfig`, `WikiConfig` (type-specific config)
|
||||
|
||||
---
|
||||
|
||||
## 10. KEY FILES SUMMARY
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `internal/types/agent.go` | `AgentConfig`, `SessionAgentConfig` |
|
||||
| `internal/types/custom_agent.go` | `CustomAgent`, `CustomAgentConfig` |
|
||||
| `internal/types/knowledgebase.go` | `KnowledgeBase`, KB types (document/faq/wiki) |
|
||||
| `internal/types/retrieval_config.go` | `RetrievalConfig` (tenant-level thresholds) |
|
||||
| `internal/types/retriever.go` | `RetrieverType`, `RetrieverEngineType` enums |
|
||||
| `internal/types/search.go` | `SearchTarget`, `SearchTargets`, `SearchResult` |
|
||||
| `internal/application/service/session_agent_qa.go` | Agent QA entry point, `buildAgentConfig`, `buildSearchTargets` |
|
||||
| `internal/application/service/knowledgebase_search.go` | `HybridSearch` orchestration |
|
||||
| `internal/application/service/retriever/composite.go` | `CompositeRetrieveEngine` (backend dispatch) |
|
||||
| `internal/agent/tools/knowledge_search.go` | Knowledge search tool definition |
|
||||
| `internal/agent/tools/definitions.go` | Tool names and available tools list |
|
||||
| `internal/application/service/chat_pipeline/search.go` | Chat pipeline search plugin |
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
**Agents bind to KBs via**:
|
||||
- `CustomAgent.Config.AvailableKnowledgeBases` + `CustomAgent.Config.AvailableKnowledgeIDs`
|
||||
- Resolved to `AgentConfig.KnowledgeBases` + `AgentConfig.KnowledgeIDs` at runtime
|
||||
- Converted to `AgentConfig.SearchTargets` for unified multi-KB querying
|
||||
|
||||
**Retrieval strategy is determined by**:
|
||||
- **Tool choice**: Agent decides to call `knowledge_search` (vector) vs `grep_chunks` (keyword)
|
||||
- **Tenant config**: `RetrievalConfig` sets thresholds, top-K, and rerank model
|
||||
- **Tenant engines**: `Tenant.EffectiveEngines` specifies which backends handle which retriever types
|
||||
- **KB model**: `KnowledgeBase.EmbeddingModelID`, type, and type-specific configs
|
||||
|
||||
**Retrieval pipeline**:
|
||||
1. Agent executes and calls a retrieval tool
|
||||
2. Tool computes embedding or keywords
|
||||
3. Tool calls `HybridSearch` with SearchTargets
|
||||
4. `HybridSearch` creates `CompositeRetrieveEngine` from tenant engines
|
||||
5. `CompositeRetrieveEngine` dispatches to appropriate backend based on RetrieverType
|
||||
6. Results are fused (RRF), reranked, and returned
|
||||
7. Agent uses results in reasoning loop
|
||||
|
||||
@@ -1,910 +0,0 @@
|
||||
# Agent/KB Retrieval Flow - Deep Dive Analysis
|
||||
|
||||
## Overview
|
||||
|
||||
This document provides a technical deep-dive into how WeKnora agents use knowledge bases for information retrieval. It traces the complete flow from agent configuration through retrieval execution, showing exactly how agents dynamically select which knowledge bases to search and how retrieval strategies are applied.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Configuration Hierarchy](#configuration-hierarchy)
|
||||
2. [Request Entry Point](#request-entry-point)
|
||||
3. [Search Target Resolution](#search-target-resolution)
|
||||
4. [Runtime Agent Configuration](#runtime-agent-configuration)
|
||||
5. [Tool Registration with SearchTargets](#tool-registration-with-searchtargets)
|
||||
6. [Retrieval Pipeline Execution](#retrieval-pipeline-execution)
|
||||
7. [Cross-Tenant KB Sharing](#cross-tenant-kb-sharing)
|
||||
8. [Configuration Precedence](#configuration-precedence)
|
||||
9. [Key Decision Points](#key-decision-points)
|
||||
|
||||
---
|
||||
|
||||
## Configuration Hierarchy
|
||||
|
||||
### Three-Level Configuration System
|
||||
|
||||
WeKnora uses a three-tier configuration system that resolves from most specific to most general:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ 1. Request-Level Override (Most Specific) │
|
||||
│ - SummaryModelID, KnowledgeBaseIDs, etc. │
|
||||
│ - Session-level web search enabled flag │
|
||||
└─────────────────────────────────────────────┘
|
||||
↓ (if not provided)
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ 2. Agent-Level Configuration (CustomAgent) │
|
||||
│ - CustomAgent.Config.ModelID │
|
||||
│ - CustomAgent.Config.KBSelectionMode │
|
||||
│ - CustomAgent.Config.AllowedTools │
|
||||
│ - CustomAgent.Config.Temperature, etc. │
|
||||
└─────────────────────────────────────────────┘
|
||||
↓ (if not provided)
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ 3. Tenant-Level Defaults (Most General) │
|
||||
│ - RetrievalConfig thresholds │
|
||||
│ - Tenant default models │
|
||||
│ - WebSearchConfig │
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Configuration Objects
|
||||
|
||||
#### CustomAgent (Persistent, DB-Stored)
|
||||
Located: `internal/types/custom_agent.go`
|
||||
|
||||
```go
|
||||
type CustomAgent struct {
|
||||
ID string // UUID or builtin-* ID
|
||||
Name string
|
||||
TenantID uint64 // Agent owner (composite key)
|
||||
Config CustomAgentConfig // JSONB configuration
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type CustomAgentConfig struct {
|
||||
// KB Selection
|
||||
KBSelectionMode string // "all", "selected", or "none"
|
||||
KnowledgeBases []string // IDs when mode="selected"
|
||||
|
||||
// Retrieval
|
||||
ModelID string
|
||||
RerankModelID string
|
||||
AllowedTools []string // Which tools can be called
|
||||
|
||||
// Strategy
|
||||
EmbeddingTopK int
|
||||
VectorThreshold float64
|
||||
KeywordThreshold float64
|
||||
RerankTopK int
|
||||
RerankThreshold float64
|
||||
|
||||
// Agent Mode
|
||||
MaxIterations int
|
||||
Temperature float64
|
||||
MultiTurnEnabled bool
|
||||
HistoryTurns int
|
||||
|
||||
// Advanced
|
||||
RetrieveKBOnlyWhenMentioned bool // Only search KB if @mentioned
|
||||
WebSearchEnabled bool
|
||||
WebSearchMaxResults int
|
||||
}
|
||||
```
|
||||
|
||||
#### AgentConfig (Runtime Resolution)
|
||||
Located: `internal/types/agent.go`
|
||||
|
||||
This is built at request time from CustomAgent + TenantInfo:
|
||||
|
||||
```go
|
||||
type AgentConfig struct {
|
||||
MaxIterations int
|
||||
AllowedTools []string
|
||||
Temperature float64
|
||||
KnowledgeBases []string // Resolved KB IDs
|
||||
KnowledgeIDs []string // Resolved file IDs
|
||||
SystemPrompt string
|
||||
WebSearchEnabled bool
|
||||
WebSearchMaxResults int
|
||||
MultiTurnEnabled bool
|
||||
HistoryTurns int
|
||||
SearchTargets SearchTargets // ← Pre-computed HERE
|
||||
RetrieveKBOnlyWhenMentioned bool
|
||||
// ... more fields
|
||||
}
|
||||
```
|
||||
|
||||
#### RetrievalConfig (Tenant-Level)
|
||||
Located: `internal/types/retrieval_config.go`
|
||||
|
||||
Stored as JSONB on tenants table:
|
||||
|
||||
```go
|
||||
type RetrievalConfig struct {
|
||||
EmbeddingTopK int // default: 50
|
||||
VectorThreshold float64 // default: 0.15
|
||||
KeywordThreshold float64 // default: 0.3
|
||||
RerankTopK int // default: 10
|
||||
RerankThreshold float64 // default: 0.2
|
||||
RerankModelID string
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Request Entry Point
|
||||
|
||||
### AgentQA Handler Flow
|
||||
|
||||
Located: `internal/application/service/session_agent_qa.go`
|
||||
|
||||
**Key Function**: `func (s *sessionService) AgentQA(ctx context.Context, req *types.QARequest, eventBus *event.EventBus) error`
|
||||
|
||||
Entry point receives:
|
||||
- `req.CustomAgent` - The agent being used (required for AgentQA)
|
||||
- `req.Query` - User question
|
||||
- `req.KnowledgeBaseIDs` - Optional @mentions (overrides agent config)
|
||||
- `req.KnowledgeIDs` - Specific file @mentions
|
||||
- `req.Session.TenantID` - Session owner tenant
|
||||
- `req.WebSearchEnabled` - Session-level web search override
|
||||
|
||||
### Sequence of Operations
|
||||
|
||||
```
|
||||
1. Validate customAgent is provided (line 36)
|
||||
↓
|
||||
2. Resolve retrieval tenant ID (line 42)
|
||||
- Returns agent's tenant if agent is from different org
|
||||
- Otherwise returns session tenant
|
||||
↓
|
||||
3. Load tenant info (lines 51-62)
|
||||
- May fetch agent's tenant if different from session tenant
|
||||
↓
|
||||
4. Build runtime AgentConfig (line 68)
|
||||
- This is where SearchTargets are computed
|
||||
↓
|
||||
5. Resolve effective model ID (line 79)
|
||||
↓
|
||||
6. Create agent engine (line 153)
|
||||
- Passes AgentConfig with SearchTargets
|
||||
↓
|
||||
7. Execute agent (line 191)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Search Target Resolution
|
||||
|
||||
### What are SearchTargets?
|
||||
|
||||
Located: `internal/types/search.go`
|
||||
|
||||
```go
|
||||
type SearchTarget struct {
|
||||
Type SearchTargetType // "knowledge_base" or "knowledge"
|
||||
KnowledgeBaseID string // KB to search
|
||||
TenantID uint64 // Which tenant owns this KB
|
||||
KnowledgeIDs []string // Specific files (only for "knowledge" type)
|
||||
}
|
||||
|
||||
type SearchTargets []*SearchTarget
|
||||
```
|
||||
|
||||
**Two Target Types**:
|
||||
- `SearchTargetTypeKnowledgeBase` ("knowledge_base"): Search entire KB
|
||||
- `SearchTargetTypeKnowledge` ("knowledge"): Search specific files
|
||||
|
||||
### buildSearchTargets Function
|
||||
|
||||
Located: `internal/application/service/session_knowledge_qa.go:393`
|
||||
|
||||
This function is **critical** - it's called once at request entry and pre-computes all search targets.
|
||||
|
||||
**Inputs**:
|
||||
- `knowledgeBaseIDs` - Full KB IDs to search
|
||||
- `knowledgeIDs` - Specific file IDs to search
|
||||
|
||||
**Logic**:
|
||||
|
||||
```
|
||||
PASS 1: Full Knowledge Bases
|
||||
├─ Batch-fetch KB records
|
||||
├─ For each KB:
|
||||
│ ├─ Resolve actual TenantID (own, shared, or agent's)
|
||||
│ ├─ Check user has permission (for shared KBs)
|
||||
│ └─ Create SearchTarget with Type=KNOWLEDGE_BASE
|
||||
└─ Track which KBs are fully covered
|
||||
|
||||
PASS 2: Specific Files (KnowledgeIDs)
|
||||
├─ Batch-fetch Knowledge records
|
||||
├─ For each Knowledge:
|
||||
│ ├─ Find its parent KnowledgeBaseID
|
||||
│ ├─ Skip if parent KB already fully covered
|
||||
│ ├─ Group by KnowledgeBaseID
|
||||
│ └─ Create SearchTarget with Type=KNOWLEDGE + KnowledgeIDs list
|
||||
└─ Result: One SearchTarget per unique KB, with specific file lists
|
||||
```
|
||||
|
||||
**Key Algorithm Detail**:
|
||||
|
||||
If user passes:
|
||||
```
|
||||
KnowledgeBaseIDs: ["kb-1", "kb-2"]
|
||||
KnowledgeIDs: ["file-3", "file-4", "file-5"]
|
||||
```
|
||||
|
||||
Where file-3 and file-4 are in kb-1, and file-5 is in kb-3:
|
||||
|
||||
Result SearchTargets:
|
||||
```
|
||||
[
|
||||
{Type: KNOWLEDGE_BASE, KnowledgeBaseID: "kb-1"}, // Entire kb-1
|
||||
{Type: KNOWLEDGE_BASE, KnowledgeBaseID: "kb-2"}, // Entire kb-2
|
||||
{Type: KNOWLEDGE, KnowledgeBaseID: "kb-3", KnowledgeIDs: ["file-5"]}
|
||||
]
|
||||
```
|
||||
|
||||
Note: file-3 and file-4 are NOT created as separate targets because kb-1 is already being fully searched.
|
||||
|
||||
---
|
||||
|
||||
## Runtime Agent Configuration
|
||||
|
||||
### buildAgentConfig Function
|
||||
|
||||
Located: `internal/application/service/session_agent_qa.go:210`
|
||||
|
||||
**Input**: `CustomAgent` + `TenantInfo` + `QARequest`
|
||||
|
||||
**Output**: Runtime `AgentConfig` with pre-computed SearchTargets
|
||||
|
||||
**Steps**:
|
||||
|
||||
```go
|
||||
1. Create base AgentConfig from CustomAgent.Config
|
||||
- Copy: MaxIterations, Temperature, WebSearchEnabled, etc.
|
||||
- Copy AllowedTools (or use defaults if empty)
|
||||
|
||||
2. Call EnsureDefaults() (line 65)
|
||||
- Sets missing values to hardcoded defaults
|
||||
|
||||
3. Resolve knowledge base IDs (line 242)
|
||||
agentConfig.KnowledgeBases = s.resolveKnowledgeBases(ctx, req)
|
||||
|
||||
This function (session_qa_helpers.go:19) implements KB resolution priority:
|
||||
|
||||
Priority 1: Explicit @mentions in request
|
||||
if req.KnowledgeBaseIDs or req.KnowledgeIDs provided
|
||||
└─ Use those (but validate against agent scope for shared agents)
|
||||
|
||||
Priority 2: RetrieveKBOnlyWhenMentioned override
|
||||
if customAgent.Config.RetrieveKBOnlyWhenMentioned && no @mention
|
||||
└─ Clear the KB list (KB disabled for this request)
|
||||
|
||||
Priority 3: Agent's configured KBs
|
||||
else
|
||||
└─ Resolve based on KBSelectionMode:
|
||||
├─ "all": List all KBs (own + shared for non-shared agents)
|
||||
├─ "selected": Use customAgent.Config.KnowledgeBases
|
||||
├─ "none": Return empty
|
||||
└─ default: Fallback to KnowledgeBases for backward compat
|
||||
|
||||
4. Merge with tenant config (lines 260-273)
|
||||
- Set WebSearchMaxResults from tenant if not set
|
||||
- Resolve web search provider ID
|
||||
|
||||
5. Build SearchTargets (line 286)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, agentTenantID,
|
||||
agentConfig.KnowledgeBases,
|
||||
agentConfig.KnowledgeIDs)
|
||||
agentConfig.SearchTargets = searchTargets
|
||||
```
|
||||
|
||||
### resolveKnowledgeBasesFromAgent Function
|
||||
|
||||
Located: `internal/application/service/session_knowledge_qa.go:320`
|
||||
|
||||
This function implements the KB selection mode logic:
|
||||
|
||||
```go
|
||||
func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
ctx context.Context,
|
||||
customAgent *types.CustomAgent,
|
||||
sessionTenantID uint64,
|
||||
) []string {
|
||||
switch customAgent.Config.KBSelectionMode {
|
||||
|
||||
case "all":
|
||||
// Fetch all KBs from agent's tenant
|
||||
allKBs, _ := s.knowledgeBaseService.ListKnowledgeBases(ctx)
|
||||
|
||||
// For non-shared agents: also include user's shared KBs
|
||||
isSharedAgent := sessionTenantID != 0 &&
|
||||
sessionTenantID != customAgent.TenantID
|
||||
if !isSharedAgent {
|
||||
sharedList, _ := s.kbShareService.ListSharedKnowledgeBases(
|
||||
ctx, userID, tenantID)
|
||||
// Merge shared KBs into allKBs
|
||||
}
|
||||
return allKBIDs
|
||||
|
||||
case "selected":
|
||||
// Use explicitly configured list
|
||||
return customAgent.Config.KnowledgeBases
|
||||
|
||||
case "none":
|
||||
return nil
|
||||
|
||||
default:
|
||||
// Backward compat: use configured KBs
|
||||
return customAgent.Config.KnowledgeBases
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Critical Detail**: Shared agent detection (line 346)
|
||||
```go
|
||||
isSharedAgent := sessionTenantID != 0 &&
|
||||
sessionTenantID != customAgent.TenantID
|
||||
```
|
||||
|
||||
When `isSharedAgent` is true:
|
||||
- ONLY use agent's tenant KBs
|
||||
- DO NOT include user's shared KBs (security)
|
||||
- This prevents data leak across organizations
|
||||
|
||||
---
|
||||
|
||||
## Tool Registration with SearchTargets
|
||||
|
||||
### Where SearchTargets Flow
|
||||
|
||||
The pre-computed SearchTargets from AgentConfig are passed to EVERY tool that needs to search:
|
||||
|
||||
Located: `internal/application/service/agent_service.go:318`
|
||||
|
||||
**Tool Registration**:
|
||||
|
||||
```go
|
||||
func (s *agentService) registerTools(ctx context.Context,
|
||||
registry *tools.ToolRegistry,
|
||||
config *types.AgentConfig, // ← Contains SearchTargets
|
||||
rerankModel rerank.Reranker,
|
||||
chatModel chat.Chat,
|
||||
sessionID string) error {
|
||||
|
||||
// ... determine allowedTools ...
|
||||
|
||||
for _, toolName := range allowedTools {
|
||||
switch toolName {
|
||||
|
||||
case tools.ToolKnowledgeSearch:
|
||||
// SearchTargets passed directly to tool
|
||||
toolToRegister = tools.NewKnowledgeSearchTool(
|
||||
s.knowledgeBaseService,
|
||||
s.knowledgeService,
|
||||
s.chunkService,
|
||||
config.SearchTargets, // ← HERE
|
||||
rerankModel,
|
||||
chatModel,
|
||||
s.cfg,
|
||||
)
|
||||
|
||||
case tools.ToolGrepChunks:
|
||||
toolToRegister = tools.NewGrepChunksTool(
|
||||
s.db,
|
||||
config.SearchTargets, // ← HERE
|
||||
)
|
||||
|
||||
case tools.ToolListKnowledgeChunks:
|
||||
toolToRegister = tools.NewListKnowledgeChunksTool(
|
||||
s.knowledgeService,
|
||||
s.chunkService,
|
||||
config.SearchTargets, // ← HERE
|
||||
)
|
||||
|
||||
// ... similar for other KB tools ...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### KnowledgeSearchTool Initialization
|
||||
|
||||
Located: `internal/agent/tools/knowledge_search.go:133`
|
||||
|
||||
```go
|
||||
type KnowledgeSearchTool struct {
|
||||
BaseTool
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
searchTargets types.SearchTargets // ← Stored here
|
||||
rerankModel rerank.Reranker
|
||||
chatModel chat.Chat
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
func NewKnowledgeSearchTool(..., searchTargets types.SearchTargets, ...) {
|
||||
return &KnowledgeSearchTool{
|
||||
// ...
|
||||
searchTargets: searchTargets, // ← Captured at creation
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Tool Execution Uses SearchTargets
|
||||
|
||||
When agent calls knowledge_search tool at runtime:
|
||||
|
||||
Located: `internal/agent/tools/knowledge_search.go:155`
|
||||
|
||||
```go
|
||||
func (t *KnowledgeSearchTool) Execute(
|
||||
ctx context.Context,
|
||||
args json.RawMessage) (*types.ToolResult, error) {
|
||||
|
||||
// Parse input
|
||||
var input KnowledgeSearchInput
|
||||
json.Unmarshal(args, &input)
|
||||
|
||||
// Use pre-computed search targets
|
||||
searchTargets := t.searchTargets // ← Line 180
|
||||
|
||||
// Allow user to optionally filter to specific KBs
|
||||
if len(input.KnowledgeBaseIDs) > 0 {
|
||||
// Filter searchTargets to only include user-specified KBs
|
||||
userKBSet := make(map[string]bool)
|
||||
for _, kbID := range input.KnowledgeBaseIDs {
|
||||
userKBSet[kbID] = true
|
||||
}
|
||||
var filteredTargets types.SearchTargets
|
||||
for _, target := range t.searchTargets {
|
||||
if userKBSet[target.KnowledgeBaseID] {
|
||||
filteredTargets = append(filteredTargets, target)
|
||||
}
|
||||
}
|
||||
searchTargets = filteredTargets
|
||||
}
|
||||
|
||||
// Get all KB IDs from targets
|
||||
kbIDs := searchTargets.GetAllKnowledgeBaseIDs() // Line 205
|
||||
|
||||
// Execute concurrent search using targets
|
||||
allResults := t.concurrentSearchByTargets(
|
||||
ctx,
|
||||
input.Queries,
|
||||
searchTargets, // ← Passed to search executor
|
||||
topK,
|
||||
vectorThreshold,
|
||||
keywordThreshold,
|
||||
kbTypeMap)
|
||||
|
||||
// ... reranking, MMR, dedup ...
|
||||
|
||||
return toolResult, nil
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Retrieval Pipeline Execution
|
||||
|
||||
### Two Parallel Search Paths
|
||||
|
||||
In the chat pipeline (non-agent mode):
|
||||
|
||||
Located: `internal/application/service/chat_pipeline/search.go:61`
|
||||
|
||||
```go
|
||||
func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
eventType types.EventType,
|
||||
chatManage *types.ChatManage,
|
||||
next func() *PluginError) *PluginError {
|
||||
|
||||
// Run KB search and web search CONCURRENTLY
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Goroutine 1: Knowledge Base Search
|
||||
go func() {
|
||||
kbResults := p.searchByTargets(ctx, chatManage)
|
||||
}()
|
||||
|
||||
// Goroutine 2: Web Search
|
||||
go func() {
|
||||
webResults := p.searchWebIfEnabled(ctx, chatManage)
|
||||
}()
|
||||
}
|
||||
```
|
||||
|
||||
### SearchByTargets Execution
|
||||
|
||||
Located: `internal/application/service/chat_pipeline/search.go:312`
|
||||
|
||||
This function orchestrates KB retrieval using SearchTargets:
|
||||
|
||||
```go
|
||||
func (p *PluginSearch) searchByTargets(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage) []*types.SearchResult {
|
||||
|
||||
// Step 1: Group targets by embedding model (optimization)
|
||||
// Targets with same embedding model share one embedding computation
|
||||
groups := groupTargetsByEmbeddingModel(
|
||||
ctx,
|
||||
chatManage.SearchTargets,
|
||||
p.knowledgeBaseService)
|
||||
|
||||
// Step 2: For each model group, execute search
|
||||
for modelKey, targets := range groups {
|
||||
// Compute embedding once for all targets in group
|
||||
queryEmbedding, _ := p.knowledgeBaseService.GetQueryEmbedding(
|
||||
ctx, targets[0].KnowledgeBaseID, queryText)
|
||||
|
||||
// Separate full-KB from specific-knowledge targets
|
||||
var fullKBIDs []string
|
||||
var knowledgeTargets []*types.SearchTarget
|
||||
for _, t := range targets {
|
||||
if t.Type == types.SearchTargetTypeKnowledgeBase {
|
||||
fullKBIDs = append(fullKBIDs, t.KnowledgeBaseID)
|
||||
} else {
|
||||
knowledgeTargets = append(knowledgeTargets, t)
|
||||
}
|
||||
}
|
||||
|
||||
// Execute combined search for full KBs (all in one call)
|
||||
if len(fullKBIDs) > 0 {
|
||||
params := types.SearchParams{
|
||||
QueryText: queryText,
|
||||
QueryEmbedding: queryEmbedding,
|
||||
KnowledgeBaseIDs: fullKBIDs, // ← Multiple KBs combined
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: chatManage.KeywordThreshold,
|
||||
MatchCount: chatManage.EmbeddingTopK,
|
||||
}
|
||||
res, _ := p.knowledgeBaseService.HybridSearch(
|
||||
ctx, fullKBIDs[0], params)
|
||||
// ← HybridSearch with multiple KBs returns unified results
|
||||
}
|
||||
|
||||
// Execute individual search for specific-knowledge targets
|
||||
for _, target := range knowledgeTargets {
|
||||
p.searchSingleTarget(ctx, chatManage, target,
|
||||
queryText, queryEmbedding, ...)
|
||||
}
|
||||
}
|
||||
|
||||
return allResults
|
||||
}
|
||||
```
|
||||
|
||||
### HybridSearch with Multiple KBs
|
||||
|
||||
Located: `internal/application/service/knowledgebase_search.go`
|
||||
|
||||
The HybridSearch function orchestrates parallel vector + keyword retrieval:
|
||||
|
||||
```go
|
||||
func (s *Service) HybridSearch(
|
||||
ctx context.Context,
|
||||
mainKBID string,
|
||||
params types.SearchParams) ([]*types.SearchResult, error) {
|
||||
|
||||
// params.KnowledgeBaseIDs can contain MULTIPLE KB IDs
|
||||
searchKBIDs := params.KnowledgeBaseIDs
|
||||
if len(searchKBIDs) == 0 {
|
||||
searchKBIDs = []string{mainKBID}
|
||||
}
|
||||
|
||||
// Create CompositeRetrieveEngine for all KBs
|
||||
engine := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieverRegistry,
|
||||
s.getTenantRetrieverEngines(ctx))
|
||||
|
||||
// Execute PARALLEL vector + keyword search
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Vector search
|
||||
go func() {
|
||||
vectorResults, _ := engine.Retrieve(ctx,
|
||||
types.RetrieveParams{
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
KnowledgeBaseIDs: searchKBIDs, // All KBs
|
||||
EmbeddingTopK: params.MatchCount * 5, // Over-retrieve
|
||||
QueryEmbedding: params.QueryEmbedding,
|
||||
VectorThreshold: params.VectorThreshold,
|
||||
})
|
||||
}()
|
||||
|
||||
// Keyword search
|
||||
go func() {
|
||||
keywordResults, _ := engine.Retrieve(ctx,
|
||||
types.RetrieveParams{
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
KnowledgeBaseIDs: searchKBIDs, // All KBs
|
||||
EmbeddingTopK: params.MatchCount * 5,
|
||||
QueryText: params.QueryText,
|
||||
KeywordThreshold: params.KeywordThreshold,
|
||||
})
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Merge using RRF (Reciprocal Rank Fusion)
|
||||
mergedResults := rrf(vectorResults, keywordResults)
|
||||
|
||||
// Rerank
|
||||
if rerankModel != nil {
|
||||
rerankedResults := rerank(mergedResults,
|
||||
params.QueryText,
|
||||
rerankModel)
|
||||
}
|
||||
|
||||
return rerankedResults, nil
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cross-Tenant KB Sharing
|
||||
|
||||
### Shared Agent Scenario
|
||||
|
||||
When `sessionTenantID != customAgent.TenantID`:
|
||||
|
||||
Located: `internal/application/service/session_qa_helpers.go:37`
|
||||
|
||||
```go
|
||||
// When using a shared agent, restrict @mentions to the agent's allowed KB scope
|
||||
// to prevent users from injecting KB/knowledge IDs outside the agent's configured range.
|
||||
if customAgent != nil &&
|
||||
req.Session != nil &&
|
||||
req.Session.TenantID != customAgent.TenantID {
|
||||
kbIDs, knowledgeIDs = s.restrictMentionsToAgentScope(
|
||||
ctx, customAgent, req.Session.TenantID, kbIDs, knowledgeIDs)
|
||||
}
|
||||
```
|
||||
|
||||
### Permission Validation
|
||||
|
||||
Located: `internal/application/service/session_knowledge_qa.go:393`
|
||||
|
||||
In buildSearchTargets:
|
||||
|
||||
```go
|
||||
// For each KB in the request
|
||||
kb := kbByID[kbID]
|
||||
if kb == nil {
|
||||
// Not found, default to session tenant
|
||||
kbTenantMap[kbID] = tenantID
|
||||
} else if kb.TenantID == tenantID {
|
||||
// Own KB
|
||||
kbTenantMap[kbID] = tenantID
|
||||
} else if s.kbShareService != nil && userID != "" {
|
||||
// Cross-tenant shared KB - check permission
|
||||
hasAccess, _ := s.kbShareService.HasKBPermission(
|
||||
ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if hasAccess {
|
||||
kbTenantMap[kbID] = kb.TenantID // Use original owner
|
||||
} else {
|
||||
kbTenantMap[kbID] = tenantID // Fallback
|
||||
}
|
||||
} else {
|
||||
kbTenantMap[kbID] = tenantID
|
||||
}
|
||||
```
|
||||
|
||||
### SearchTarget Tenant Tracking
|
||||
|
||||
Each SearchTarget includes TenantID:
|
||||
|
||||
```go
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: kbID,
|
||||
TenantID: kbTenantMap[kbID], // ← Track owner
|
||||
})
|
||||
```
|
||||
|
||||
The retrieval system uses this to scope searches correctly.
|
||||
|
||||
---
|
||||
|
||||
## Configuration Precedence
|
||||
|
||||
### Complete Priority Chain
|
||||
|
||||
```
|
||||
Request Layer
|
||||
└─ req.SummaryModelID (overrides agent model)
|
||||
└─ req.KnowledgeBaseIDs (overrides agent KB config)
|
||||
└─ req.KnowledgeIDs (specific files)
|
||||
└─ req.WebSearchEnabled (request-level override)
|
||||
|
||||
↓ (if not provided)
|
||||
|
||||
Agent Layer (CustomAgent.Config)
|
||||
└─ ModelID (chat model for agent)
|
||||
└─ RerankModelID (rerank model)
|
||||
└─ AllowedTools (which tools available)
|
||||
└─ KBSelectionMode + KnowledgeBases
|
||||
└─ Temperature, MaxIterations
|
||||
└─ EmbeddingTopK, VectorThreshold, KeywordThreshold
|
||||
└─ WebSearchEnabled, WebSearchMaxResults
|
||||
└─ RetrieveKBOnlyWhenMentioned
|
||||
└─ SystemPrompt, MultiTurnEnabled
|
||||
|
||||
↓ (if not provided)
|
||||
|
||||
Tenant Layer (Tenant.RetrievalConfig)
|
||||
└─ EmbeddingTopK (default: 50)
|
||||
└─ VectorThreshold (default: 0.15)
|
||||
└─ KeywordThreshold (default: 0.3)
|
||||
└─ RerankTopK (default: 10)
|
||||
└─ RerankThreshold (default: 0.2)
|
||||
└─ RerankModelID
|
||||
|
||||
↓ (if not provided)
|
||||
|
||||
System Defaults
|
||||
└─ EmbeddingTopK: 50
|
||||
└─ VectorThreshold: 0.15
|
||||
└─ KeywordThreshold: 0.3
|
||||
└─ RerankTopK: 10
|
||||
└─ Temperature: 0.7
|
||||
└─ MaxIterations: 10
|
||||
```
|
||||
|
||||
### Example: KBSelectionMode Resolution
|
||||
|
||||
```go
|
||||
// resolveKnowledgeBases (session_qa_helpers.go:19)
|
||||
|
||||
hasExplicitMention := len(kbIDs) > 0 || len(knowledgeIDs) > 0
|
||||
|
||||
if hasExplicitMention {
|
||||
// Priority 1: Use request-specified targets
|
||||
kbIDs, knowledgeIDs = req.KnowledgeBaseIDs, req.KnowledgeIDs
|
||||
} else if customAgent.Config.RetrieveKBOnlyWhenMentioned {
|
||||
// Priority 2: Mode flag disables KB for this request
|
||||
kbIDs, knowledgeIDs = nil, nil
|
||||
} else {
|
||||
// Priority 3: Use agent's configured KBs based on mode
|
||||
kbIDs = resolveKnowledgeBasesFromAgent(customAgent, sessionTenantID)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Decision Points
|
||||
|
||||
### 1. When is SearchTargets Computed?
|
||||
|
||||
**Answer**: Once at request entry, in `buildAgentConfig()` (line 286)
|
||||
|
||||
**Why**: Avoids recomputation on every tool call
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
AgentQA() → buildAgentConfig() → buildSearchTargets() → agentConfig.SearchTargets
|
||||
↓
|
||||
CreateAgentEngine() → registerTools() →
|
||||
All tools capture SearchTargets at init
|
||||
```
|
||||
|
||||
### 2. How Does Agent Choose Which Tool to Call?
|
||||
|
||||
**Answer**: The LLM decides which tool, but only allowed ones are available
|
||||
|
||||
```
|
||||
// agent_service.go:328-334
|
||||
var allowedTools []string
|
||||
if len(config.AllowedTools) > 0 {
|
||||
allowedTools = config.AllowedTools // ← Agent specifies
|
||||
} else {
|
||||
allowedTools = tools.DefaultAllowedTools()
|
||||
}
|
||||
|
||||
// ← These are the ONLY tools available to LLM
|
||||
```
|
||||
|
||||
The agent.AllowedTools directly constrains what the LLM can call.
|
||||
|
||||
### 3. Can Agent Override Knowledge Bases?
|
||||
|
||||
**Partially - Depends on Configuration**:
|
||||
|
||||
```
|
||||
If RetrieveKBOnlyWhenMentioned == true:
|
||||
└─ KB searches ONLY work if user explicitly mentions KB with @
|
||||
└─ No automatic KB retrieval
|
||||
|
||||
If KBSelectionMode == "selected":
|
||||
└─ Agent is LOCKED to configured KnowledgeBases
|
||||
└─ @mentions outside this set are rejected
|
||||
└─ Exception: Within search tool, user can filter to subset
|
||||
|
||||
If KBSelectionMode == "all":
|
||||
└─ Agent CAN search any KB user has access to
|
||||
└─ But searchTargets still pre-computed from "all"
|
||||
```
|
||||
|
||||
### 4. What if CustomAgent.Config.AllowedTools is empty?
|
||||
|
||||
**Answer**: Use defaults (line 333)
|
||||
|
||||
```go
|
||||
if len(config.AllowedTools) > 0 {
|
||||
allowedTools = config.AllowedTools
|
||||
} else {
|
||||
allowedTools = tools.DefaultAllowedTools() // ← USES DEFAULTS
|
||||
}
|
||||
```
|
||||
|
||||
Default allowed tools: `ToolThinking, ToolTodoWrite, ToolKnowledgeSearch, ToolGrepChunks, ToolListKnowledgeChunks, ToolQueryKnowledgeGraph, ToolGetDocumentInfo, ToolDatabaseQuery, ToolDataAnalysis, ToolDataSchema, ToolFinalAnswer`
|
||||
|
||||
### 5. How are Multiple KBs Searched Efficiently?
|
||||
|
||||
**Answer**: Group by embedding model, batch the search
|
||||
|
||||
Located: `search.go:312`
|
||||
|
||||
```
|
||||
1. Group SearchTargets by embedding model identity
|
||||
└─ Targets with same model = one embedding computation
|
||||
|
||||
2. For each group:
|
||||
a. Compute query embedding ONCE
|
||||
b. Separate full-KB targets from specific-knowledge targets
|
||||
c. Combined search: HybridSearch(allFullKBIDs)
|
||||
└─ Searches ALL KBs in ONE retrieval call
|
||||
└─ Returns merged results from all KBs
|
||||
d. Individual search: One HybridSearch per specific-knowledge target
|
||||
```
|
||||
|
||||
**Result**: If 5 KBs use same embedding model:
|
||||
- Traditional: 5 embedding computations, 5 retrieval calls
|
||||
- Optimized: 1 embedding computation, 2 retrieval calls (combined full + individuals)
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
### Configuration Resolution Flow
|
||||
|
||||
```
|
||||
QARequest
|
||||
↓
|
||||
resolveKnowledgeBases()
|
||||
├─ Check: explicit @mention? → YES: use request KBs
|
||||
├─ Check: RetrieveKBOnlyWhenMentioned? → YES: clear KBs
|
||||
└─ Otherwise: resolveKnowledgeBasesFromAgent()
|
||||
├─ KBSelectionMode="all" → List all (own + shared)
|
||||
├─ KBSelectionMode="selected" → Use CustomAgent.Config.KnowledgeBases
|
||||
└─ KBSelectionMode="none" → Empty list
|
||||
↓
|
||||
buildSearchTargets(ctx, tenantID, kbIDs, knowledgeIDs)
|
||||
├─ PASS 1: Full KB → SearchTarget(KNOWLEDGE_BASE, kbID)
|
||||
├─ PASS 2: Specific files → SearchTarget(KNOWLEDGE, kbID, [fileIDs])
|
||||
└─ Track TenantID per target (for cross-tenant sharing)
|
||||
↓
|
||||
agentConfig.SearchTargets = results
|
||||
↓
|
||||
registerTools(..., agentConfig)
|
||||
└─ Each tool receives: agentConfig.SearchTargets
|
||||
↓
|
||||
At runtime, when agent calls tool:
|
||||
└─ Tool uses pre-computed SearchTargets
|
||||
└─ Tool can filter by user-specified KB subset
|
||||
└─ Executes HybridSearch with targets
|
||||
```
|
||||
|
||||
### Key Invariants
|
||||
|
||||
1. **SearchTargets computed once**: At `buildAgentConfig()` entry
|
||||
2. **All KB tools constrained by SearchTargets**: Via constructor injection
|
||||
3. **Permission checked at build time**: Not at retrieval time
|
||||
4. **Cross-tenant sharing validated**: In `buildSearchTargets()`
|
||||
5. **Shared agents cannot leak KBs**: `isSharedAgent` detection
|
||||
6. **Configuration is immutable after engine creation**: No runtime config changes
|
||||
@@ -1,256 +0,0 @@
|
||||
# Agent & Knowledge Base Integration Documentation
|
||||
|
||||
This directory contains comprehensive documentation on how agents/bots use knowledge bases in WeKnora, including model definitions, retrieval configuration, and the complete retrieval pipeline.
|
||||
|
||||
## Documents
|
||||
|
||||
### 1. [AGENT_KB_RETRIEVAL_ARCHITECTURE.md](./AGENT_KB_RETRIEVAL_ARCHITECTURE.md) - **Deep Dive (581 lines)**
|
||||
The comprehensive reference guide covering:
|
||||
- Agent/Bot model definitions (CustomAgent, AgentConfig, SessionAgentConfig)
|
||||
- Knowledge base binding mechanisms
|
||||
- Retrieval strategy configuration (RetrievalConfig, RetrieverType, RetrieverEngineType)
|
||||
- Complete retrieval pipeline stages (1-7)
|
||||
- SearchTargets computation and usage
|
||||
- Agent-level retrieval preferences
|
||||
- Key decision flows
|
||||
- Data flow diagram
|
||||
- Configuration precedence
|
||||
- Complete file manifest
|
||||
|
||||
**Best for**: Understanding the complete architecture, implementation details, and data flows.
|
||||
|
||||
### 2. [AGENT_KB_QUICK_REFERENCE.md](./AGENT_KB_QUICK_REFERENCE.md) - **Quick Guide (286 lines)**
|
||||
A practical, scenario-focused guide including:
|
||||
- Core data structures with tree diagrams
|
||||
- Step-by-step KB access flow
|
||||
- Enumeration reference (RetrieverType, RetrieverEngineType, etc.)
|
||||
- Tool choices and routing
|
||||
- Configuration precedence summary
|
||||
- Key files lookup table
|
||||
- Common Q&A scenarios
|
||||
|
||||
**Best for**: Quick lookups, implementation decisions, and troubleshooting.
|
||||
|
||||
---
|
||||
|
||||
## Key Concepts at a Glance
|
||||
|
||||
### The Agent-KB Link
|
||||
|
||||
**Agents reference KBs through**:
|
||||
```
|
||||
CustomAgent.Config.AvailableKnowledgeBases[]
|
||||
↓
|
||||
buildAgentConfig() resolves to
|
||||
↓
|
||||
AgentConfig.KnowledgeBases[]
|
||||
↓
|
||||
buildSearchTargets() converts to
|
||||
↓
|
||||
AgentConfig.SearchTargets[] (unified search scope)
|
||||
↓
|
||||
Used by retrieval tools at execution time
|
||||
```
|
||||
|
||||
### Retrieval Strategy Decision Path
|
||||
|
||||
1. **Which KBs?** → `AgentConfig.SearchTargets` (pre-computed)
|
||||
2. **Which retrieval type?** → Agent decides (tool choice: knowledge_search vs grep_chunks)
|
||||
3. **Which backend?** → `Tenant.EffectiveEngines` routes RetrieverType to engine
|
||||
4. **Result quality?** → `RetrievalConfig` (thresholds, reranking)
|
||||
|
||||
### Search Pipeline Overview
|
||||
|
||||
```
|
||||
Agent Tool Call
|
||||
↓
|
||||
HybridSearch (orchestration)
|
||||
├→ Vector search (via embedding model)
|
||||
├→ Keyword search (via full-text index)
|
||||
├→ RRF fusion
|
||||
└→ Reranking
|
||||
↓
|
||||
CompositeRetrieveEngine (backend dispatch)
|
||||
├→ "vector" type → Qdrant/Milvus/Weaviate/Elasticsearch
|
||||
├→ "keywords" type → Elasticsearch/PostgreSQL/SQLite
|
||||
└→ "websearch" type → External provider
|
||||
↓
|
||||
Backend-specific retrieval
|
||||
↓
|
||||
Results merged, fused, reranked
|
||||
↓
|
||||
Agent uses in reasoning loop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## File Organization
|
||||
|
||||
### Core Model Files
|
||||
|
||||
| Path | Purpose | Key Classes |
|
||||
|------|---------|-------------|
|
||||
| `internal/types/agent.go` | Agent runtime config | `AgentConfig`, `SessionAgentConfig` |
|
||||
| `internal/types/custom_agent.go` | Agent definition | `CustomAgent`, `CustomAgentConfig` |
|
||||
| `internal/types/knowledgebase.go` | KB model & types | `KnowledgeBase` (document/faq/wiki) |
|
||||
| `internal/types/retrieval_config.go` | Tenant retrieval settings | `RetrievalConfig` |
|
||||
| `internal/types/retriever.go` | Retriever type enums | `RetrieverType`, `RetrieverEngineType` |
|
||||
| `internal/types/search.go` | Search models | `SearchTarget`, `SearchTargets`, `SearchResult` |
|
||||
|
||||
### Service/Pipeline Files
|
||||
|
||||
| Path | Purpose | Key Functions |
|
||||
|------|---------|----------------|
|
||||
| `internal/application/service/session_agent_qa.go` | Agent QA entry point | `buildAgentConfig()`, `buildSearchTargets()` |
|
||||
| `internal/application/service/knowledgebase_search.go` | Search orchestration | `HybridSearch()` |
|
||||
| `internal/application/service/retriever/composite.go` | Backend dispatcher | `CompositeRetrieveEngine` |
|
||||
| `internal/agent/tools/knowledge_search.go` | Vector search tool | Knowledge search implementation |
|
||||
| `internal/agent/tools/definitions.go` | Tool registry | Tool names and availability |
|
||||
| `internal/application/service/chat_pipeline/search.go` | Chat pipeline search | `PluginSearch` |
|
||||
|
||||
---
|
||||
|
||||
## Enumerations Quick Ref
|
||||
|
||||
### RetrieverType (What)
|
||||
- `"vector"` - Semantic/embedding search
|
||||
- `"keywords"` - Exact keyword/full-text search
|
||||
- `"websearch"` - External web search
|
||||
|
||||
### RetrieverEngineType (Where)
|
||||
- `"elasticsearch"` - Elasticsearch backend
|
||||
- `"postgres"` - PostgreSQL backend
|
||||
- `"qdrant"` - Qdrant vector DB
|
||||
- `"milvus"` - Milvus vector DB
|
||||
- `"weaviate"` - Weaviate vector DB
|
||||
- `"infinity"` - Infinity vector DB
|
||||
- `"elasticfaiss"` - FAISS backend
|
||||
- `"sqlite"` - SQLite backend
|
||||
|
||||
### SearchTargetType
|
||||
- `"knowledge_base"` - Search entire KB
|
||||
- `"knowledge"` - Search specific files within KB
|
||||
|
||||
### KnowledgeBase.Type
|
||||
- `"document"` - Standard document-based
|
||||
- `"faq"` - Question-answer pairs
|
||||
- `"wiki"` - Wiki pages
|
||||
|
||||
---
|
||||
|
||||
## Configuration Hierarchy
|
||||
|
||||
From lowest to highest priority:
|
||||
|
||||
1. **System defaults** (hardcoded in code)
|
||||
2. **Knowledge Base config** (EmbeddingModelID, FAQConfig, etc.)
|
||||
3. **Tenant-level RetrievalConfig** (thresholds, top-K, reranker)
|
||||
4. **Agent-level config** (AllowedTools, RerankModelID)
|
||||
5. **Session-level override** (KnowledgeBases restriction)
|
||||
6. **Request/Tool-level** (explicit parameters)
|
||||
|
||||
---
|
||||
|
||||
## Common Implementation Patterns
|
||||
|
||||
### Pattern 1: Agent Access to Multiple KBs
|
||||
```go
|
||||
// If KBs share embedding model:
|
||||
HybridSearch(kb1_id, params{
|
||||
KnowledgeBaseIDs: [kb1, kb2, kb3], // Search all 3
|
||||
QueryText: query,
|
||||
// ... results merged and reranked together
|
||||
})
|
||||
```
|
||||
|
||||
### Pattern 2: Scoped Document Search
|
||||
```go
|
||||
// Search only specific documents within a KB:
|
||||
SearchTarget{
|
||||
Type: "knowledge",
|
||||
KnowledgeBaseID: kb_id,
|
||||
KnowledgeIDs: [doc1, doc2], // Only these files
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 3: Backend Selection
|
||||
```go
|
||||
// CompositeRetrieveEngine routes automatically:
|
||||
// RetrrieverType="vector" → Qdrant (if configured)
|
||||
// RetrieverType="keywords" → Elasticsearch (if configured)
|
||||
```
|
||||
|
||||
### Pattern 4: Result Fusion
|
||||
```go
|
||||
// Vector + Keyword results merged via RRF:
|
||||
vectorScores = [query1: 0.9, query2: 0.8]
|
||||
keywordScores = [query2: 0.85, query3: 0.7]
|
||||
fusedScores = RRF(vectorScores, keywordScores)
|
||||
// Then reranked
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- **Agent Architecture**: See `docs/AGENT_ARCHITECTURE.md` (if exists)
|
||||
- **Chat Pipeline**: See `docs/CHAT_PIPELINE.md` (if exists)
|
||||
- **Knowledge Base Management**: See `docs/KNOWLEDGE_BASE.md` (if exists)
|
||||
- **API Documentation**: See `docs/api/` directory
|
||||
|
||||
---
|
||||
|
||||
## Quick Start: Adding a New Retrieval Strategy
|
||||
|
||||
1. **Create retriever type**: Add constant to `RetrieverType` enum in `internal/types/retriever.go`
|
||||
2. **Register backend**: Implement `RetrieveEngineService` interface
|
||||
3. **Configure at tenant level**: Update `Tenant.EffectiveEngines` to include new type
|
||||
4. **Agent tool**: Create tool that sets `params.RetrieverType` to new type
|
||||
5. **CompositeRetrieveEngine**: Automatically routes based on type
|
||||
|
||||
---
|
||||
|
||||
## FAQ
|
||||
|
||||
**Q: Where is KB access control enforced?**
|
||||
A: Multiple places:
|
||||
- `buildSearchTargets()` checks permissions via `kbShareService`
|
||||
- Session initialization validates agent access
|
||||
- Request handler validates user/session authorization
|
||||
|
||||
**Q: How are cross-tenant shared KBs handled?**
|
||||
A:
|
||||
- `SearchTarget.TenantID` tracks which tenant owns each KB
|
||||
- HybridSearch handles tenant isolation
|
||||
- Permissions resolved at buildSearchTargets time
|
||||
|
||||
**Q: Can I change retrieval strategy per-agent?**
|
||||
A: Indirectly - via `AllowedTools` (which tools agent can use) and tool implementation
|
||||
|
||||
**Q: How does reranking work?**
|
||||
A:
|
||||
- Tenant specifies `RetrievalConfig.RerankModelID`
|
||||
- HybridSearch applies after RRF fusion
|
||||
- Results filtered by `RerankThreshold`
|
||||
- Limited to `RerankTopK` results
|
||||
|
||||
**Q: What's the difference between vector and keyword search?**
|
||||
A:
|
||||
- **Vector**: Semantic/conceptual similarity (embeddings)
|
||||
- **Keyword**: Exact text matching/full-text search (BM25, ES)
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
When modifying agent or KB integration:
|
||||
1. Update relevant section in both documents
|
||||
2. Keep Quick Reference as 1-page reference, Architecture as comprehensive guide
|
||||
3. Update files list if adding new source files
|
||||
4. Document new enumerations/types
|
||||
5. Test configuration precedence scenarios
|
||||
|
||||
---
|
||||
|
||||
Generated: 2026-04-20
|
||||
Last Updated: See git history
|
||||
Reference in New Issue
Block a user