feat: Update agent type presets and prompt templates for improved knowledge base handling
- Changed `kb_selection_mode` in agent type presets from "selected" to "all" to allow agents to access all knowledge bases by default.
- Revised prompt templates to clarify the handling of bound knowledge bases, replacing the `{{knowledge_bases}}` placeholder with a reference to the `<bound_knowledge_bases>` block in the user message's `<runtime_context>`.
- Enhanced internal logic to ensure that only searchable knowledge bases are considered during retrieval, improving the efficiency of knowledge searches.
- Added new functions for better formatting and handling of knowledge base metadata in the runtime context.
- Updated documentation and comments for clarity on the changes made to knowledge base interactions.
This commit is contained in:
@@ -129,12 +129,14 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// Use knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
|
||||
// Use knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB).
|
||||
// Keep chunk-type filter aligned with list_knowledge_chunks so the
|
||||
// "chunk_count" reported here matches what that tool can page over.
|
||||
_, total, err := t.chunkService.GetRepository().
|
||||
ListPagedChunksByKnowledgeID(ctx, knowledge.TenantID, id, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1,
|
||||
}, []types.ChunkType{"text"}, "", "", "", "", "")
|
||||
}, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
results[id] = &docInfo{
|
||||
|
||||
@@ -471,6 +471,44 @@ func (t *KnowledgeSearchTool) concurrentSearchByTargets(
|
||||
kbList = kbs
|
||||
}
|
||||
|
||||
// Filter out non-searchable KBs (wiki-only / graph-only). knowledge_search
|
||||
// can only serve KBs with vector or keyword indexing; feeding a wiki-only
|
||||
// KB into HybridSearch causes spurious "model ID cannot be empty" errors
|
||||
// because such KBs have no EmbeddingModelID configured. Such scopes
|
||||
// should be queried via wiki_search / graph tools instead.
|
||||
//
|
||||
// KBs that we couldn't fetch from the repo (not in kbList) are kept so
|
||||
// the downstream HybridSearch path can still surface the real error.
|
||||
searchableKBs := make(map[string]bool, len(kbList))
|
||||
knownKBs := make(map[string]bool, len(kbList))
|
||||
for _, kb := range kbList {
|
||||
if kb == nil {
|
||||
continue
|
||||
}
|
||||
knownKBs[kb.ID] = true
|
||||
if kb.IsVectorEnabled() || kb.IsKeywordEnabled() {
|
||||
searchableKBs[kb.ID] = true
|
||||
}
|
||||
}
|
||||
filteredTargets := make(types.SearchTargets, 0, len(searchTargets))
|
||||
for _, st := range searchTargets {
|
||||
if searchableKBs[st.KnowledgeBaseID] {
|
||||
filteredTargets = append(filteredTargets, st)
|
||||
continue
|
||||
}
|
||||
if knownKBs[st.KnowledgeBaseID] {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Skipping non-searchable KB %s (no vector/keyword index, likely wiki/graph-only)", st.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
// KB record unavailable; keep so downstream can surface real errors.
|
||||
filteredTargets = append(filteredTargets, st)
|
||||
}
|
||||
if len(filteredTargets) == 0 {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] No searchable KBs in scope (all wiki/graph-only); skipping retrieval")
|
||||
return nil
|
||||
}
|
||||
searchTargets = filteredTargets
|
||||
|
||||
// Resolve actual model identities (name + endpoint) for cross-tenant grouping
|
||||
modelKeyMap := t.knowledgeBaseService.ResolveEmbeddingModelKeys(ctx, kbList)
|
||||
|
||||
@@ -1135,10 +1173,14 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] KB %s not found in searchTargets, skipping chunk count", result.KnowledgeBaseID)
|
||||
knowledgeTotalMap[result.KnowledgeID] = 0
|
||||
} else {
|
||||
// Use the same chunk-type filter as list_knowledge_chunks so the
|
||||
// total reported here matches what list_knowledge_chunks can page
|
||||
// over. Mismatched filters previously let LLMs compute offsets
|
||||
// against an inflated/deflated total and page past the end.
|
||||
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
effectiveTenantID, result.KnowledgeID,
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
|
||||
[]types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v", result.KnowledgeID, err)
|
||||
|
||||
@@ -27,10 +27,18 @@ var listKnowledgeChunksTool = BaseTool{
|
||||
## Parameters:
|
||||
- knowledge_id (required): Document ID
|
||||
- limit (optional): Chunks per page (default 20, max 100)
|
||||
- offset (optional): Start position (default 0)
|
||||
- offset (optional): 0-based position in the chunk list (NOT chunk_index).
|
||||
Must be < total. Use offset=0 to read from the first chunk, offset=N to
|
||||
skip the first N chunks. If offset >= total the tool returns an explicit
|
||||
out-of-range error with the valid total so you can retry.
|
||||
|
||||
## Output:
|
||||
Full chunk content with chunk_id, chunk_index, and content text.`,
|
||||
Full chunk content with chunk_id, chunk_index, and content text.
|
||||
The response attributes include:
|
||||
- total: total number of chunks in the document
|
||||
- fetched: how many chunks this page returned
|
||||
If fetched=0 with total>0, your offset is past the end — retry with a
|
||||
smaller offset (e.g. offset = max(0, total - limit)).`,
|
||||
schema: json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -161,6 +169,32 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
|
||||
totalChunks := total
|
||||
fetched := len(chunks)
|
||||
|
||||
// Explicit out-of-range guidance: when the caller paged past the end
|
||||
// (offset >= total with total > 0), silently returning fetched=0 is
|
||||
// confusing for LLMs that just saw the document in search results. Tell
|
||||
// them exactly what happened and what offset would be valid so the next
|
||||
// call lands on a real page.
|
||||
if fetched == 0 && totalChunks > 0 && int64(offset) >= totalChunks {
|
||||
suggestedOffset := totalChunks - int64(chunkLimit)
|
||||
if suggestedOffset < 0 {
|
||||
suggestedOffset = 0
|
||||
}
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf(
|
||||
"offset %d is out of range: document has only %d chunks (valid offset range: 0..%d). Retry with offset=%d (or any value < %d).",
|
||||
offset, totalChunks, totalChunks-1, suggestedOffset, totalChunks,
|
||||
),
|
||||
Data: map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
"total_chunks": totalChunks,
|
||||
"requested_offset": offset,
|
||||
"requested_limit": chunkLimit,
|
||||
"suggested_offset": suggestedOffset,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Enrich image info from child image chunks (lazy loading)
|
||||
if fetched > 0 {
|
||||
chunkIDs := make([]string, 0, fetched)
|
||||
|
||||
Reference in New Issue
Block a user