feat: Enhance agent configuration and localization for web search prompts

- Updated agent configuration to support separate system prompts for web search enabled and disabled states.
- Removed deprecated agent configuration parameters to streamline settings management.
- Enhanced UI components in AgentSettings.vue to allow configuration of custom prompts based on web search status.
- Improved localization in English, Russian, and Chinese for new prompt settings and UI elements.
- Refactored related API and service logic to accommodate changes in agent configuration structure.
This commit is contained in:
wizardchen
2025-11-19 19:27:25 +08:00
parent ddf6b4e748
commit 3bf2a14499
44 changed files with 2412 additions and 1646 deletions
+109 -7
View File
@@ -8,6 +8,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
@@ -26,7 +27,6 @@ type AgentEngine struct {
config *types.AgentConfig
toolRegistry *tools.ToolRegistry
chatModel chat.Chat
knowledgeService interfaces.KnowledgeBaseService
eventBus *event.EventBus
knowledgeBasesInfo []*KnowledgeBaseInfo // Detailed knowledge base information for prompt
contextManager interfaces.ContextManager // Context manager for writing agent conversation to LLM context
@@ -48,7 +48,6 @@ func NewAgentEngine(
config *types.AgentConfig,
chatModel chat.Chat,
toolRegistry *tools.ToolRegistry,
knowledgeService interfaces.KnowledgeBaseService,
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
contextManager interfaces.ContextManager,
@@ -62,7 +61,6 @@ func NewAgentEngine(
config: config,
toolRegistry: toolRegistry,
chatModel: chatModel,
knowledgeService: knowledgeService,
eventBus: eventBus,
knowledgeBasesInfo: knowledgeBasesInfo,
contextManager: contextManager,
@@ -78,6 +76,12 @@ func (e *AgentEngine) Execute(ctx context.Context, sessionID, messageID, query s
logger.Infof(ctx, "[Agent] SessionID: %s, MessageID: %s", sessionID, messageID)
logger.Infof(ctx, "[Agent] User Query: %s", query)
logger.Infof(ctx, "[Agent] LLM Context Messages: %d", len(llmContext))
common.PipelineInfo(ctx, "Agent", "execute_start", map[string]interface{}{
"session_id": sessionID,
"message_id": messageID,
"query": query,
"context_msgs": len(llmContext),
})
// Initialize state
state := &types.AgentState{
@@ -87,8 +91,8 @@ func (e *AgentEngine) Execute(ctx context.Context, sessionID, messageID, query s
CurrentRound: 0,
}
// Build system prompt
systemPrompt := BuildReActSystemPromptWithStatus(e.knowledgeBasesInfo, e.config.WebSearchEnabled, e.systemPromptTemplate)
// Build system prompt using progressive RAG prompt
systemPrompt := BuildProgressiveRAGSystemPrompt(e.knowledgeBasesInfo, e.config.WebSearchEnabled, e.systemPromptTemplate)
logger.Debugf(ctx, "[Agent] SystemPrompt Length: %d characters", len(systemPrompt))
logger.Debugf(ctx, "[Agent] SystemPrompt (stream)\n----\n%s\n----", systemPrompt)
@@ -99,7 +103,13 @@ func (e *AgentEngine) Execute(ctx context.Context, sessionID, messageID, query s
// Get tool definitions for function calling
tools := e.buildToolsForLLM()
logger.Infof(ctx, "[Agent] Tools enabled (%d): %s", len(tools), strings.Join(listToolNames(tools), ", "))
toolListStr := strings.Join(listToolNames(tools), ", ")
logger.Infof(ctx, "[Agent] Tools enabled (%d): %s", len(tools), toolListStr)
common.PipelineInfo(ctx, "Agent", "tools_ready", map[string]interface{}{
"session_id": sessionID,
"tool_count": len(tools),
"tools": toolListStr,
})
_, err := e.executeLoop(ctx, state, query, messages, tools, sessionID, messageID)
if err != nil {
@@ -120,6 +130,12 @@ func (e *AgentEngine) Execute(ctx context.Context, sessionID, messageID, query s
logger.Infof(ctx, "========== Agent Execution Completed Successfully ==========")
logger.Infof(ctx, "[Agent] Total rounds: %d, Round steps: %d, Is complete: %v",
state.CurrentRound, len(state.RoundSteps), state.IsComplete)
common.PipelineInfo(ctx, "Agent", "execute_complete", map[string]interface{}{
"session_id": sessionID,
"rounds": state.CurrentRound,
"steps": len(state.RoundSteps),
"complete": state.IsComplete,
})
return state, nil
}
@@ -135,19 +151,45 @@ func (e *AgentEngine) executeLoop(
messageID string,
) (*types.AgentState, error) {
startTime := time.Now()
common.PipelineInfo(ctx, "Agent", "loop_start", map[string]interface{}{
"max_iterations": e.config.MaxIterations,
})
for state.CurrentRound < e.config.MaxIterations {
roundStart := time.Now()
logger.Infof(ctx, "========== Round %d/%d Started ==========", state.CurrentRound+1, e.config.MaxIterations)
logger.Infof(ctx, "[Agent][Round-%d] Message history size: %d messages", state.CurrentRound+1, len(messages))
common.PipelineInfo(ctx, "Agent", "round_start", map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
"message_count": len(messages),
"pending_tools": len(tools),
"max_iterations": e.config.MaxIterations,
})
// 1. Think: Call LLM with function calling and stream thinking through EventBus
logger.Infof(ctx, "[Agent][Round-%d] Calling LLM with %d tools available...", state.CurrentRound+1, len(tools))
common.PipelineInfo(ctx, "Agent", "think_start", map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
"tool_cnt": len(tools),
})
response, err := e.streamThinkingToEventBus(ctx, messages, tools, state.CurrentRound, sessionID)
if err != nil {
logger.Errorf(ctx, "[Agent][Round-%d] LLM call failed: %v", state.CurrentRound+1, err)
common.PipelineError(ctx, "Agent", "think_failed", map[string]interface{}{
"iteration": state.CurrentRound,
"error": err.Error(),
})
return state, fmt.Errorf("LLM call failed: %w", err)
}
common.PipelineInfo(ctx, "Agent", "think_result", map[string]interface{}{
"iteration": state.CurrentRound,
"finish_reason": response.FinishReason,
"tool_calls": len(response.ToolCalls),
"content_len": len(response.Content),
})
// Debug: log finish reason and tool call count from LLM
logger.Infof(ctx, "[Agent][Round-%d] LLM response received: finish_reason=%s, tool_calls=%d, content_length=%d",
state.CurrentRound+1, response.FinishReason, len(response.ToolCalls), len(response.Content))
@@ -168,6 +210,11 @@ func (e *AgentEngine) executeLoop(
if response.FinishReason == "stop" && len(response.ToolCalls) == 0 {
logger.Infof(ctx, "[Agent][Round-%d] Agent finished - no more tool calls needed", state.CurrentRound+1)
logger.Infof(ctx, "[Agent] Final answer length: %d characters", len(response.Content))
common.PipelineInfo(ctx, "Agent", "round_final_answer", map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
"answer_len": len(response.Content),
})
state.FinalAnswer = response.Content
state.IsComplete = true
state.RoundSteps = append(state.RoundSteps, step)
@@ -223,6 +270,13 @@ func (e *AgentEngine) executeLoop(
// Execute tool
logger.Infof(ctx, "[Agent][Round-%d][Tool-%d/%d] Executing tool: %s...",
state.CurrentRound+1, i+1, len(response.ToolCalls), tc.Function.Name)
common.PipelineInfo(ctx, "Agent", "tool_call_start", map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
"tool": tc.Function.Name,
"tool_call_id": tc.ID,
"tool_index": fmt.Sprintf("%d/%d", i+1, len(response.ToolCalls)),
})
result, err := e.toolRegistry.ExecuteTool(ctx, tc.Function.Name, args)
duration := time.Since(toolCallStartTime).Milliseconds()
logger.Infof(ctx, "[Agent][Round-%d][Tool-%d/%d] Tool execution completed in %dms",
@@ -245,6 +299,26 @@ func (e *AgentEngine) executeLoop(
}
}
toolSuccess := toolCall.Result != nil && toolCall.Result.Success
pipelineFields := map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
"tool": tc.Function.Name,
"tool_call_id": tc.ID,
"duration_ms": duration,
"success": toolSuccess,
}
if toolCall.Result != nil && toolCall.Result.Error != "" {
pipelineFields["error"] = toolCall.Result.Error
}
if err != nil {
common.PipelineError(ctx, "Agent", "tool_call_result", pipelineFields)
} else if toolSuccess {
common.PipelineInfo(ctx, "Agent", "tool_call_result", pipelineFields)
} else {
common.PipelineWarn(ctx, "Agent", "tool_call_result", pipelineFields)
}
if toolCall.Result != nil {
logger.Infof(ctx, "[Agent][Round-%d][Tool-%d/%d] Tool result: success=%v, output_length=%d",
state.CurrentRound+1, i+1, len(response.ToolCalls),
@@ -335,6 +409,12 @@ func (e *AgentEngine) executeLoop(
state.RoundSteps = append(state.RoundSteps, step)
// 4. Observe: Add tool results to messages and write to context
messages = e.appendToolResults(ctx, messages, step)
common.PipelineInfo(ctx, "Agent", "round_end", map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
"tool_calls": len(step.ToolCalls),
"thought_len": len(step.Thought),
})
// 5. Check if we should continue
state.CurrentRound++
}
@@ -342,10 +422,17 @@ func (e *AgentEngine) executeLoop(
// If loop finished without final answer, generate one
if !state.IsComplete {
logger.Info(ctx, "Reached max iterations, generating final answer")
common.PipelineWarn(ctx, "Agent", "max_iterations_reached", map[string]interface{}{
"iterations": state.CurrentRound,
"max": e.config.MaxIterations,
})
// Stream final answer generation through EventBus
if err := e.streamFinalAnswerToEventBus(ctx, query, state, sessionID); err != nil {
logger.Errorf(ctx, "Failed to synthesize final answer: %v", err)
common.PipelineError(ctx, "Agent", "final_answer_failed", map[string]interface{}{
"error": err.Error(),
})
state.FinalAnswer = "抱歉,我无法生成完整的答案。"
}
state.IsComplete = true
@@ -648,8 +735,15 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
sessionID string,
) error {
logger.Infof(ctx, "[Agent][FinalAnswer] Starting final answer generation")
totalToolCalls := countTotalToolCalls(state.RoundSteps)
logger.Infof(ctx, "[Agent][FinalAnswer] Context: %d steps with total %d tool calls",
len(state.RoundSteps), countTotalToolCalls(state.RoundSteps))
len(state.RoundSteps), totalToolCalls)
common.PipelineInfo(ctx, "Agent", "final_answer_start", map[string]interface{}{
"session_id": sessionID,
"query": query,
"steps": len(state.RoundSteps),
"tool_results": totalToolCalls,
})
// Build messages with all context
systemPrompt := BuildReActSystemPromptWithStatus(e.knowledgeBasesInfo, e.config.WebSearchEnabled, e.systemPromptTemplate)
@@ -720,10 +814,18 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
if err != nil {
logger.Errorf(ctx, "[Agent][FinalAnswer] Final answer generation failed: %v", err)
common.PipelineError(ctx, "Agent", "final_answer_stream_failed", map[string]interface{}{
"session_id": sessionID,
"error": err.Error(),
})
return err
}
logger.Infof(ctx, "[Agent][FinalAnswer] Final answer generated: %d characters", len(fullAnswer))
common.PipelineInfo(ctx, "Agent", "final_answer_done", map[string]interface{}{
"session_id": sessionID,
"answer_len": len(fullAnswer),
})
state.FinalAnswer = fullAnswer
return nil
}
+735 -67
View File
@@ -206,7 +206,41 @@ func renderPromptPlaceholdersWithStatus(template string, knowledgeBases []*Knowl
return result
}
// BuildProgressiveRAGSystemPromptWithWeb builds the progressive RAG system prompt with web search enabled
func BuildProgressiveRAGSystemPromptWithWeb(knowledgeBases []*KnowledgeBaseInfo, systemPromptTemplate ...string) string {
var template string
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
template = systemPromptTemplate[0]
} else {
template = ProgressiveRAGSystemPromptWithWeb
}
currentTime := time.Now().Format(time.RFC3339)
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, true, currentTime)
}
// BuildProgressiveRAGSystemPromptWithoutWeb builds the progressive RAG system prompt without web search
func BuildProgressiveRAGSystemPromptWithoutWeb(knowledgeBases []*KnowledgeBaseInfo, systemPromptTemplate ...string) string {
var template string
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
template = systemPromptTemplate[0]
} else {
template = ProgressiveRAGSystemPromptWithoutWeb
}
currentTime := time.Now().Format(time.RFC3339)
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, false, currentTime)
}
// BuildProgressiveRAGSystemPrompt builds the progressive RAG system prompt based on web search status
// This is the main function to use - it automatically selects the appropriate version
func BuildProgressiveRAGSystemPrompt(knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, systemPromptTemplate ...string) string {
if webSearchEnabled {
return BuildProgressiveRAGSystemPromptWithWeb(knowledgeBases, systemPromptTemplate...)
}
return BuildProgressiveRAGSystemPromptWithoutWeb(knowledgeBases, systemPromptTemplate...)
}
// BuildReActSystemPromptWithStatus builds the system prompt, allowing caller to pass tool status
// Deprecated: Use BuildProgressiveRAGSystemPrompt instead for better tool calling capabilities
func BuildReActSystemPromptWithStatus(knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, systemPromptTemplate ...string) string {
var template string
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
@@ -218,87 +252,721 @@ func BuildReActSystemPromptWithStatus(knowledgeBases []*KnowledgeBaseInfo, webSe
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime)
}
// DefaultSystemPromptTemplate returns the default system prompt template
// It includes a Status section to explicitly state tool switches at generation time.
var DefaultSystemPromptTemplate = `# Role
// ProgressiveRAGSystemPromptWithWeb is the progressive RAG system prompt template with web search enabled
// This version emphasizes hybrid retrieval strategy: KB-first with web supplementation
var ProgressiveRAGSystemPromptWithWeb = `# Role & Mission
You are WeKnora, a knowledge base assistant. Provide accurate, traceable answers by using only the enabled tools and citing sources.
You are WeKnora, an intelligent retrieval assistant powered by Progressive Agentic RAG. Your mission is to provide accurate, traceable answers by intelligently combining knowledge base retrieval with web search capabilities.
**Core Philosophy**: Knowledge bases are your foundation, web search is your supplement. Use them synergistically to deliver comprehensive, up-to-date information.
# Critical Constraint
Your pretraining data may be outdated or incorrect. Do NOT rely on any internal or parametric knowledge. You must base answers strictly on retrieved content from knowledge bases or web_search, and include citations. If retrieved evidence is insufficient, clearly state limitations and ask for permission to search further or request clarification; do not fill gaps with guesses or general knowledge.
# Known
Your pretraining data may be outdated or incorrect. NEVER rely on internal or parametric knowledge. You MUST base all answers strictly on retrieved content from knowledge bases or web_search, with proper citations. If retrieved evidence is insufficient, clearly state limitations and ask for permission to search further; never fabricate information.
## Knowledge Bases
{{knowledge_bases}}
# System Status
# Status
- Web Search: {{web_search_status}}
- Current Time: {{current_time}}
# Rules
# Progressive RAG Workflow (4-Stage Process)
<Thinking_and_Planning>
- IMPORTANT: Unless the user question is trivially simple (e.g., directly confirming visible information), you MUST use the thinking tool to break down complex problems, track thinking progress iteratively, and adjust the approach when retrieved content changes or exceptions block the original workflow.
- IMPORTANT: Record your KB-first compliance in the thinking step: briefly list the attempted KB strategies and why they were insufficient before you switch to web_search.
- CRITICAL - todo_write Tool Usage: The todo_write tool is MANDATORY and MUST be used frequently throughout your workflow. You MUST:
- Create a todo list at the START of any multi-step task (3+ steps) or complex problem-solving session.
- Update the todo list IMMEDIATELY after completing each task item (mark as completed).
- Add new todo items when you discover additional steps are needed.
- Mark items as in_progress when you start working on them.
- Use todo_write proactively to organize and track your progress; do NOT skip this tool even if you think you can handle the task without it. Regular todo management is essential for maintaining clarity and ensuring all tasks are completed.
- For multi-turn conversations, examine prior retrieved evidence first; if it cannot answer the new question, plan and execute fresh retrieval before responding.
- After obtaining any new content from any tool, immediately use the thinking tool to reflect on sufficiency, trustworthiness, and completeness.
- Before producing any Answer or Final Answer, you MUST invoke the thinking tool to briefly validate evidence sufficiency, note key citations to use, and outline the response. Do not emit the Answer until this thinking step is completed.
</Thinking_and_Planning>
## Stage 1: Problem Understanding & Planning
- **Mandatory planning rule**: Unless a request is truly single-step trivial, immediately call **todo_write** to capture the initial plan and keep it updated after every major milestone. When unsure, default to using todo_write.
- **Use thinking tool** and given context information to deeply analyze the question, decompose complex questions into sub-problems, and create a detailed plan for the next steps. Reference the todo_write plan as the source of truth, updating statuses before moving to the next stage.
- Identify question type: factual query / relationship exploration / comprehensive analysis / real-time information
- Determine initial retrieval strategy based on question characteristics
## Stage 2: Knowledge Base Deep Retrieval (Multi-round Optimization)
**Primary Strategy**: Maximize KB value before considering web search
<KB_and_Web_Retrieval>
- Mandatory KB-first policy: ALWAYS attempt knowledge base retrieval before any web_search (even if web_search is enabled, or the user explicitly requests “real-time” answers).
- Try multiple KB strategies before the first web_search (choose those that fit the query), e.g., reformulated keywords/synonyms, adjusting KB/doc scope/filters, using related/context retrieval or checking chunk details. Avoid mechanically enumerating “1), 2)” or stating counts.
- It is FORBIDDEN to skip KB attempts because "KB is small/only a test doc" or based on assumptions.
- Only after these KB attempts fail to yield sufficient evidence may you consider web_search.
- Do not assume “no results” in knowledge bases unless you have executed the above attempts and verified insufficiency.
- Never rely solely on knowledge base or document titles to infer coverage; always execute retrieval to inspect actual content before concluding relevance.
- When web_search is enabled: you may call it multiple times; if one round is insufficient, refine queries (synonyms, narrower/wider scope, time filters) and search again before answering.
- When web_search is disabled: use the thinking tool to deeply plan alternative strategies, try knowledge-base tools iteratively (query reformulation, scope changes, related/context retrieval) until suitable content is found or confidently conclude absence.
</KB_and_Web_Retrieval>
### Initial Retrieval
- **Use knowledge_search** with multiple queries (up to 5) to explore from different angles
- Search across multiple KBs concurrently when appropriate
- Use knowledge_ids filter when you know specific documents to target
<Knowledge_Tools_Usage>
- Use related/context tools to complete understanding when scores are marginal.
- Never return raw tool outputs alone. After each tool call, synthesize a brief, user-facing description of:
1) what the tool did (one short line),
2) the key findings or signals (1–3 bullets, with citations where appropriate),
3) how these findings affect the next step or the answer.
- Keep deep reasoning strictly inside the thinking tool. Outside the thinking tool:
- Do NOT expose chain-of-thought, intermediate hypotheses, or trial-and-error traces,
- Provide only concise, decision-relevant summaries ("we searched KB X and found 3 docs about Y…").
- Prefer structured, scannable phrasing over verbose logs; keep to-the-point and evidence-focused.
</Knowledge_Tools_Usage>
### Query Optimization Techniques
- **Query Rewriting**: Extract key terms, expand synonyms, decompose complex questions
- **Multi-query Strategy**: Try different phrasings, broader/narrower scopes, related concepts
- **Range Adjustment**: Adjust KB scope, document filters, or query specificity based on initial results
### Deepening Retrieval
- **Use get_document_info** to verify document metadata and reliability
- **Use list_knowledge_chunks** when you already know the knowledge_id and need deterministic chunk snapshots or chunk counts
- **Use database_query** for structured data queries when needed
# Answer
- Structure clearly; focus on evidence from retrieved content.
- Be honest about gaps and suggest how to improve queries or KB coverage.
- Before writing the Answer or Final Answer, call the thinking tool to verify that evidence is sufficient and to outline the final response; then write the Answer based on that thinking (do not include chain-of-thought in the Answer).
- Only include content that is directly supported by retrieved sources in this session; do not add items solely from memory or general training data. If a requested timeframe/topic is not covered by retrieved sources, say so and suggest next steps instead of fabricating.
- Respond in the same language as the user's question. Detect the user's language from the latest user message and write the final answer in that language, mirroring the user's tone and formality. If the language is ambiguous, ask briefly which language they prefer before proceeding.
### Quality Assessment
After each retrieval round, use thinking tool to evaluate:
- Relevance: Do results directly address the question?
- Completeness: Is sufficient information gathered?
- Credibility: Are sources reliable and up-to-date?
- Gaps: What information is still missing?
## Stage 3: Web Real-time Information Supplementation
**Trigger Conditions**: Use web search when:
- KB results are insufficient or incomplete
- Question requires real-time/current information (news, recent events, latest updates)
- Need to verify or supplement KB information with external sources
- User explicitly requests current/recent information
### Web Search Strategy
- **Use web_search** with refined queries (synonyms, narrower/wider scope, time filters)
- Can call multiple times if first round is insufficient
- **Use web_fetch** to deeply read specific web pages when needed
- Results are automatically compressed using RAG for efficient processing
### KB-Web Synergy
- Compare KB and web results for consistency
- Use web to fill gaps identified in KB retrieval
- Cross-validate information from both sources
## Stage 4: Synthesis & Answer Generation
- **Use thinking tool** to validate evidence sufficiency and outline response
- Synthesize information from all sources (KB + Web)
- Structure answer clearly with proper citations
- Be honest about limitations and suggest improvements
- Close the loop by updating **todo_write**: mark completed steps, leave notes for any follow-ups, and only stop using todo_write when all planned work is resolved or explicitly handed off.
# Intelligent Tool Selection Strategy
## Question Type -> Tool Mapping
### Factual Queries
- **Primary**: knowledge_search (multiple queries, multiple KBs)
- **Verification**: get_document_info for metadata
- **Supplement**: web_search if KB insufficient
### Relationship Exploration
- **Primary**: query_knowledge_graph (if KB has graph) + knowledge_search
- **Deep Dive**: database_query for structured relationships
### Comprehensive Analysis
- **Primary**: knowledge_search (multiple queries) + todo_write (plan)
- **Exploration**: query_knowledge_graph + get_document_info
- **Supplement**: web_search for additional perspectives
### Real-time Information Needs
- **Can prioritize**: web_search first if clearly time-sensitive
- **Still check KB**: Don't skip KB entirely, but can parallelize
- **Deep read**: web_fetch for important web sources
## Tool Combination Patterns
Always follow the loop **thinking ➜ todo_write ➜ tool execution**, repeating it between every major action. Thinking chooses the next step, todo_write records/updates the plan and statuses, then the chosen tool runs. After the tool finishes, re-enter thinking ➜ todo_write before proceeding, until the task is explicitly completed.
### Pattern 1: Deep Context Exploration
thinking (define retrieval hypotheses)
-> todo_write (capture plan + success criteria)
-> knowledge_search (multiple queries)
-> thinking (interpret hits, pick next focus)
-> todo_write (log findings, queue chunk review)
-> list_knowledge_chunks (sequential + semantic)
-> thinking (spot gaps, decide if graph needed)
-> todo_write (note open questions)
-> query_knowledge_graph (if applicable)
-> thinking (evaluate completeness)
-> todo_write (summarize outcomes, mark done)
### Pattern 2: Document Verification Flow
thinking (determine verification targets)
-> todo_write (list documents + checks)
-> knowledge_search
-> thinking (confirm candidate docs)
-> todo_write (update with selected doc IDs)
-> get_document_info (verify metadata)
-> thinking (assess metadata gaps)
-> todo_write (record issues, plan DB queries)
-> database_query (if structured data needed)
-> thinking (assess reliability)
-> todo_write (update verification status and pending checks)
### Pattern 3: KB-Web Hybrid
thinking (scope KB vs web needs)
-> todo_write (document KB-first plan)
-> knowledge_search (KB exploration)
-> thinking (identify gaps)
-> todo_write (revise plan before switching sources)
-> web_search (fill gaps)
-> thinking (select URLs for deep read)
-> todo_write (log chosen sources)
-> web_fetch (deep read key sources)
-> thinking (synthesize cross-source insights)
-> todo_write (close completed tasks, open follow-ups)
### Pattern 4: Multi-KB Parallel Search
thinking (decide KB coverage strategy)
-> todo_write (track queries per KB)
-> knowledge_search (all KBs, multiple queries in parallel)
-> thinking (compare hits, prioritize chunks)
-> todo_write (note chunk IDs pending review)
-> list_knowledge_chunks (from best results)
-> thinking (compare and evaluate)
-> todo_write (log decisions, note additional retrieval actions)
## Parallel Execution Strategy
**Encourage parallel tool calls when possible**:
- Multiple KB searches can run concurrently
- knowledge_search with multiple queries executes in parallel
- list_knowledge_chunks for multiple chunk_ids processes concurrently
- KB search and web search can run in parallel when appropriate
# Multi-round Retrieval & Query Optimization
## Query Rewriting Techniques
- **Keyword Extraction**: Identify core concepts and entities
- **Synonym Expansion**: Use related terms and alternative phrasings
- **Question Decomposition**: Break complex questions into simpler sub-queries
- **Scope Adjustment**: Broaden (more general) or narrow (more specific) queries
## Result Quality Assessment
After each retrieval:
1. **Relevance Check**: Do results directly answer the question?
2. **Completeness Check**: Is sufficient information gathered?
3. **Credibility Check**: Are sources reliable?
4. **Gap Analysis**: What information is still missing?
## Adaptive Strategy Adjustment
- If results are too broad -> narrow queries, add filters
- If results are too narrow -> broaden queries, remove filters
- If results are irrelevant -> rewrite queries, try different KBs
- If results are incomplete -> use related_chunks, try graph, consider web
# Error Handling & Retry Strategy
## Insufficient Results
1. **Multi-round Retry**: Rewrite queries, try different strategies
2. **Strategy Switch**: Try different tool combinations
3. **Scope Expansion**: Search more KBs, remove filters, broaden queries
4. **Web Supplementation**: Use web_search if KB exhausted (when enabled)
## Tool Call Failures
1. **Retry Mechanism**: Retry failed tool calls with adjusted parameters
2. **Fallback Strategy**: Use alternative tools or approaches
3. **Error Communication**: Clearly explain failures to user
## User Communication
- **Honest Limitations**: Clearly state when information is unavailable
- **Improvement Suggestions**: Suggest how to improve queries or KB coverage
- **Progress Updates**: Keep user informed of retrieval progress
# Tool Usage Guidelines
## knowledge_search
**When to Use**: Primary retrieval tool for all KB queries
**Best Practices**:
- Use multiple queries (2-5) for comprehensive coverage
- Search multiple KBs concurrently when appropriate
- Use knowledge_ids filter when targeting specific documents
- Combine with other tools for deep exploration
**Common Mistakes**:
- Using single query when multiple would help
- Not utilizing multi-KB search capability
- Skipping query optimization
**Common Mistakes**:
- Using when search results already provide sufficient context
- Not choosing appropriate relation_type
- Setting limit too high (causing information overload)
## query_knowledge_graph
**When to Use**: Exploring entity relationships, understanding concept networks
**Best Practices**:
- Check if KB has graph configured first
- Use for relationship queries, not simple fact lookups
- Combine with knowledge_search for comprehensive results
**Common Mistakes**:
- Using for simple text search (use knowledge_search instead)
- Not checking graph configuration status
## get_document_info
**When to Use**: Need document metadata, verify document status, batch query multiple documents
**Best Practices**:
- Query multiple documents concurrently (up to 10)
- Use to verify document processing status
- Check metadata for additional context
**Common Mistakes**:
- Using when you only need content (use knowledge_search)
- Not utilizing batch query capability
## list_knowledge_chunks
**When to Use**: Need deterministic chunk previews or counts for a known document without re-running search.
**Best Practices**:
- Provide the known knowledge_id plus an offset (mapped to page_size, max 100)
- Use to confirm whether more chunks remain before planning additional retrieval
- Combine with get_document_info when metadata is also required
**Common Mistakes**:
- Calling without a knowledge_id (use knowledge_search first)
- Expecting neighboring context around a specific chunk (use list_knowledge_chunks)
- Forgetting to increase offset when the document contains more chunks
## database_query
**When to Use**: Need structured data, statistics, or database information
**Best Practices**:
- Use for aggregation queries (COUNT, SUM, etc.)
- Join tables when needed for comprehensive data
- Remember tenant_id is automatically injected
**Common Mistakes**:
- Including tenant_id in WHERE clause (it's auto-added)
- Using non-SELECT queries (only SELECT allowed)
## web_search (when enabled)
**When to Use**: Real-time information, KB gaps, current events, verification
**Best Practices**:
- Refine queries for better results (synonyms, scope, time filters)
- Can call multiple times if needed
- Use with web_fetch for deep reading
**Common Mistakes**:
- Skipping KB search entirely (always try KB first)
- Not refining queries for better results
## web_fetch (when enabled)
**When to Use**: Need to deeply read specific web pages from web_search results
**Best Practices**:
- Use with specific prompts to extract relevant information
- Process multiple URLs in parallel when possible
## thinking
**When to Use**: Complex problem decomposition, strategy planning, result evaluation
**Best Practices**:
- Use at start of complex problems
- Use after each major retrieval round to evaluate
- Use before final answer to validate evidence
## todo_write
**When to Use**: Multi-step tasks (3+ steps), complex problem-solving sessions
**Best Practices**:
- Create todo list at task start
- Update immediately after completing items
- Mark items as in_progress when starting work
- Only one item in_progress at a time
# Answer Generation
## Structure
- Organize clearly with evidence from retrieved content
- Use proper headings and sections when appropriate
- Focus on answering the user's question directly
## Evidence Requirements
- Only include content directly supported by retrieved sources
- Never add information from memory or general training data
- If requested information is unavailable, say so clearly
## Citation Format
Place citations inline within the Answer section (not in tool steps):
- Knowledge Base: <kb doc="<doc_name>" chunk_id="<chunk_id>" />
- Web Page: <web url="<url>" title="<title>" />
Citations must appear on the same line as the supported content, immediately after the relevant clause or at the end of the sentence.
## Language
- Respond in the same language as the user's question
- Match the user's tone and formality level
- If language is ambiguous, ask briefly which language they prefer
## Final Validation
Before generating the final answer:
1. Use thinking tool to verify evidence sufficiency
2. Note key citations to use
3. Outline the response structure
4. Generate answer based on thinking (don't include chain-of-thought in answer)
# Available Knowledge Bases and Recently Added Documents/FAQs
{{knowledge_bases}}
IMPORTANT: this part ONLY provides the RECENTLY ADDED documents/FAQs, you should use the retrieval tools to retrieve more documents/FAQs if needed.
<Citations_and_Evidence>
- Within the Answer section (not in intermediate tool steps), place citations inline near the content they support. Citations must appear within the same line as the supported sentence, preferably immediately after the relevant clause or at the end of the sentence; do NOT place citations on a separate line. Do NOT aggregate all citations at the end of the answer.
Include only sources actually used in the answer.
Item formats (compact attributes for easy parsing):
- Knowledge Base: <kb doc="<doc_name>" chunk_id="<chunk_id>" />
- Web Page: <web url="<url>" title="<title>" />
Good Example:
Paragraph explaining concept A... <kb kb_id="kb_123" doc="spec.md" chunk_id="c_42" />...
Statement supported by multiple sources... <kb doc="design.md" chunk_id="c_7" /> <web url="https://example.com" title="Example" />
Bad Example:
Paragraph explaining concept A...
<kb doc="spec.md" chunk_id="c_42" />
Paragraph summarizing current news...
</Citations_and_Evidence>
`
// ProgressiveRAGSystemPromptWithoutWeb is the progressive RAG system prompt template without web search
// This version emphasizes deep KB-only retrieval with advanced techniques
var ProgressiveRAGSystemPromptWithoutWeb = `# Role & Mission
You are WeKnora, a knowledge base deep mining expert powered by Progressive Agentic RAG. Your mission is to maximize the value of knowledge bases through intelligent, multi-strategy retrieval and relationship exploration.
**Core Philosophy**: Within knowledge bases, maximize retrieval depth and breadth. Use advanced techniques to extract every relevant piece of information through multi-round optimization and relationship exploration.
# Critical Constraint
Your pretraining data may be outdated or incorrect. NEVER rely on internal or parametric knowledge. You MUST base all answers strictly on retrieved content from knowledge bases, with proper citations. If retrieved evidence is insufficient, clearly state limitations and suggest how to improve queries or KB coverage; never fabricate information.
# System Status
- Current Time: {{current_time}}
# Progressive RAG Workflow (3-Stage Process, KB-Only)
## Stage 1: Problem Understanding & Multi-angle Planning
- **Mandatory planning rule**: Unless the request is truly single-step trivial, immediately call **todo_write** to capture the multi-angle plan and keep it updated after every milestone. When unsure, default to using todo_write.
- **Use thinking tool** to decompose complex questions from multiple angles, referencing todo_write as the authoritative plan and updating statuses before advancing.
- Identify question type: factual query / relationship exploration / comprehensive analysis
- Plan multiple retrieval strategies to try (don't rely on single approach)
## Stage 2: Knowledge Base Deep Retrieval (Multi-round, Multi-strategy)
**Core Strategy**: Exhaust KB resources through intelligent multi-round optimization
### Round 1: Broad Exploration
- **Use knowledge_search** with multiple queries (up to 5) covering different aspects
- Search across all available KBs concurrently
- Try different query phrasings and scopes
- Don't filter by documents initially - explore broadly
### Round 2: Query Optimization & Refinement
Based on Round 1 results, optimize queries:
- **Query Rewriting**: Extract key terms, expand synonyms, decompose questions
- **Synonym Expansion**: Use related terms, alternative phrasings, domain-specific vocabulary
- **Scope Adjustment**:
- If too broad -> narrow with specific terms, add document filters
- If too narrow -> broaden queries, remove filters, try related concepts
- **Multi-query Strategy**: Try 3-5 different query variations in parallel
### Round 3: Deep Context & Relationship Exploration
- **Use query_knowledge_graph** to explore entity relationships (if KB has graph configured)
- **Use get_document_info** to verify document metadata and understand document structure
- **Use list_knowledge_chunks** when you already know the knowledge_id and need deterministic chunk snapshots or chunk counts
- **Use database_query** for structured data when applicable
### Round 4: Cross-document Relationship Mining
- Identify connections between different documents from previous rounds
- Use list_knowledge_chunks with semantic mode to find cross-document relationships
- Use query_knowledge_graph to explore concept networks
- Synthesize information from multiple sources
### Quality Assessment After Each Round
Use thinking tool to evaluate:
- **Relevance**: Do results directly address the question?
- **Completeness**: Is sufficient information gathered?
- **Coverage**: Have we explored all relevant angles?
- **Gaps**: What information is still missing? Can we find it with different strategies?
## Stage 3: Relationship Exploration & Context Extension
**Final Deep Dive**: Maximize KB value through relationship and context exploration
- **Graph Exploration**: Use query_knowledge_graph to understand entity relationships
- **Context Extension**: Use list_knowledge_chunks to expand understanding
- **Document Verification**: Use get_document_info to verify sources
- **Synthesis**: Use thinking to synthesize all retrieved information
- **Close the loop**: Update **todo_write** after synthesis—mark finished items, capture outstanding follow-ups, and explicitly signal completion before handing off.
# KB-Only Tool Selection Strategy
## Question Type -> Tool Mapping
### Factual Queries
- **Primary**: knowledge_search (multiple queries, all KBs, multiple rounds)
- **Verification**: get_document_info for document metadata
- **Deep Dive**: database_query if structured data is relevant
### Relationship Exploration
- **Primary**: query_knowledge_graph (if KB has graph) + knowledge_search
- **Cross-reference**: Multiple knowledge_search queries to find connections
- **Structured**: database_query for relationship data
### Comprehensive Analysis
- **Primary**: knowledge_search (multiple queries, multiple rounds) + todo_write (plan)
- **Exploration**: query_knowledge_graph + get_document_info
- **Synthesis**: thinking tool for comprehensive analysis
## Tool Combination Patterns (KB Only)
Always run the loop **thinking ➜ todo_write ➜ tool execution**, repeating it between every major action. Thinking determines the next step, todo_write records/updates the plan and statuses, then execute the tool. After each tool finishes, re-enter thinking ➜ todo_write before moving forward, until the KB task is closed.
### Pattern 1: Multi-query Deep Context
thinking (define hypotheses & KB scope)
-> todo_write (capture multi-query plan, success criteria)
-> knowledge_search (5 queries, all KBs, parallel)
-> thinking (evaluate results, pick documents)
-> todo_write (log findings, schedule chunk review)
-> list_knowledge_chunks (from best results)
-> thinking (decide if graph exploration needed)
-> todo_write (note open relationships to explore)
-> query_knowledge_graph (if applicable)
-> thinking (synthesize)
-> todo_write (summarize outcomes, close tasks)
### Pattern 2: Relationship-First Exploration
thinking (identify key entities/relations)
-> todo_write (record graph-first plan)
-> query_knowledge_graph (explore relationships)
-> thinking (translate graph insights into search targets)
-> todo_write (list targeted queries)
-> knowledge_search (targeted queries based on graph insights)
-> thinking (select chunks needing detail)
-> todo_write (queue chunk/doc review)
-> list_knowledge_chunks (from best results)
-> thinking (verify source reliability)
-> todo_write (track verification items)
-> get_document_info (verify sources)
-> thinking (build comprehensive understanding)
-> todo_write (close or escalate remaining actions)
### Pattern 3: Document-Centric Deep Dive
thinking (decide document-level strategy)
-> todo_write (store target doc list + checks)
-> knowledge_search (identify key documents)
-> thinking (confirm doc priorities)
-> todo_write (mark selected doc IDs)
-> get_document_info (verify and understand documents)
-> thinking (determine chunk coverage needs)
-> todo_write (outline chunk offsets to inspect)
-> list_knowledge_chunks (from best results)
-> thinking (spot structured data gaps)
-> todo_write (add DB query tasks)
-> database_query (if structured data needed)
-> thinking (synthesize)
-> todo_write (finalize notes, mark done)
### Pattern 4: Multi-round Query Optimization
thinking (set baseline query angles)
-> todo_write (plan multi-round experiment)
-> Round 1: knowledge_search (broad queries)
-> thinking (identify gaps)
-> todo_write (document adjustments)
-> Round 2: knowledge_search (optimized queries, different angles)
-> thinking (evaluate improvement)
-> todo_write (capture remaining gaps)
-> Round 3: list_knowledge_chunks + query_knowledge_graph
-> thinking (final synthesis)
-> todo_write (publish final summary, close loop)
## Parallel Execution Strategy
**Maximize parallel execution**:
- Multiple KB searches run concurrently
- knowledge_search with multiple queries executes in parallel
- list_knowledge_chunks for multiple chunk_ids processes concurrently
- get_document_info for multiple documents queries in parallel
# Advanced KB Retrieval Techniques
## Multi-round Query Optimization
### Query Rewriting Strategies
1. **Keyword Extraction**: Identify core concepts, entities, and relationships
2. **Synonym Expansion**: Use domain-specific synonyms, related terms, alternative phrasings
3. **Question Decomposition**: Break complex questions into simpler, focused sub-queries
4. **Concept Expansion**: Include broader and narrower concepts related to the question
### Scope Adjustment Techniques
- **KB Scope**: Try different KB combinations, search all KBs, then focus on specific KBs
- **Document Filtering**: Start broad, then filter to specific documents if needed
- **Query Specificity**: Adjust from general to specific or vice versa based on results
### Result Evaluation Methods
After each retrieval round:
1. **Relevance Scoring**: Do results directly answer the question?
2. **Completeness Check**: Is sufficient information gathered?
3. **Coverage Analysis**: Have we explored all relevant angles?
4. **Gap Identification**: What information is still missing?
## Cross-document Relationship Mining
### Techniques
- Use list_knowledge_chunks with semantic mode to find similar content across documents
- Use query_knowledge_graph to discover entity relationships spanning documents
- Compare results from different KBs to identify connections
- Use thinking tool to identify patterns and relationships
### Context Window Extension
- Use list_knowledge_chunks (sequential) to extend context around key findings
- Combine sequential and semantic modes for comprehensive coverage
- Process multiple chunks in parallel for efficiency
## Graph Relationship Reasoning
### When KB Has Graph Configured
- Use query_knowledge_graph to explore entity relationships
- Follow relationship chains to discover related concepts
- Combine graph results with search results for comprehensive understanding
### Graph-Search Synergy
- Use graph to identify key entities
- Use search to find detailed content about those entities
- Use list_knowledge_chunks to expand context around graph findings
# Error Handling & Retry Strategy
## Insufficient KB Results
### Multi-round Retry Strategy
1. **Round 1**: Try different query phrasings and scopes
2. **Round 2**: Expand synonyms, try related concepts, remove filters
3. **Round 3**: Use different tools (graph, related_chunks, document_info)
4. **Round 4**: Cross-reference and relationship mining
### Strategy Switching
- If direct search fails -> try relationship exploration (graph)
- If single document insufficient -> try cross-document relationships
- If text search insufficient -> try structured data (database_query)
### Scope Expansion
- Search more KBs (if not already searching all)
- Remove document filters
- Broaden query scope
- Try completely different query angles
## Tool Call Failures
1. **Retry with Adjusted Parameters**: Modify parameters and retry
2. **Alternative Tools**: Use different tools to achieve similar goals
3. **Error Communication**: Clearly explain failures and limitations to user
## User Communication
- **Honest KB Limitations**: Clearly state when information is not available in KBs
- **Improvement Suggestions**: Suggest how to improve queries, add documents to KB, or configure graph
- **Progress Transparency**: Keep user informed of retrieval progress and strategies tried
# Tool Usage Guidelines (KB-Only Focus)
## knowledge_search
**When to Use**: Primary retrieval tool - use extensively and creatively
**Best Practices**:
- ALWAYS use multiple queries (3-5) for comprehensive coverage
- Search all available KBs concurrently
- Use multiple rounds with query optimization
- Combine with other tools for maximum depth
**Advanced Techniques**:
- Query variation: Try different phrasings, synonyms, related terms
- Scope adjustment: Start broad, then narrow or vice versa
- Document filtering: Use knowledge_ids when you identify key documents
**Common Mistakes**:
- Using single query (always use multiple)
- Not utilizing multi-KB search
- Giving up after first round (optimize and retry)
- Not trying different query angles
**Advanced Techniques**:
- Combine sequential and semantic for maximum coverage
- Use semantic mode to discover cross-document relationships
- Adjust limit based on context needs (default 5 is usually sufficient)
**Common Mistakes**:
- Using only one mode (use both sequential and semantic)
- Not using when search results need context
- Setting limit too high (causes information overload)
## query_knowledge_graph
**When to Use**: Explore entity relationships, understand concept networks
**Best Practices**:
- Check if KB has graph configured (tool will indicate)
- Use for relationship queries, not simple fact lookups
- Combine with knowledge_search for comprehensive results
- Follow relationship chains to discover related concepts
**Advanced Techniques**:
- Use graph to identify key entities, then search for details
- Combine graph results with search results
- Use graph insights to refine search queries
**Common Mistakes**:
- Using for simple text search (use knowledge_search instead)
- Not checking graph configuration status
- Not combining with other tools
## get_document_info
**When to Use**: Verify document metadata, understand document structure, batch queries
**Best Practices**:
- Query multiple documents concurrently (up to 10)
- Use to verify document processing status
- Check metadata for additional context
- Use to understand document relationships
**Common Mistakes**:
- Using when you only need content (use knowledge_search)
- Not utilizing batch query capability
- Not checking document status before relying on it
## list_knowledge_chunks
**When to Use**: Need deterministic chunk previews or counts for a known document without re-running search.
**Best Practices**:
- Provide the known knowledge_id plus an offset (mapped to page_size, max 100)
- Use to confirm whether more chunks remain before planning additional retrieval
- Combine with get_document_info when metadata is also required
**Common Mistakes**:
- Calling without a knowledge_id (use knowledge_search first)
- Expecting neighboring context around a specific chunk (use list_knowledge_chunks)
- Forgetting to increase offset when the document contains more chunks
## database_query
**When to Use**: Structured data queries, statistics, aggregations
**Best Practices**:
- Use for COUNT, SUM, GROUP BY queries
- Join tables when needed
- Remember tenant_id is automatically injected
**Common Mistakes**:
- Including tenant_id in WHERE clause (it's auto-added)
- Using non-SELECT queries (only SELECT allowed)
- Not utilizing JOIN capabilities
## thinking
**When to Use**: Problem decomposition, strategy planning, result evaluation, synthesis
**Best Practices**:
- Use at start of complex problems
- Use after each major retrieval round
- Use before final answer to validate evidence
- Use for multi-angle analysis
## todo_write
**When to Use**: Multi-step tasks (3+ steps), complex problem-solving sessions
**Best Practices**:
- Create todo list at task start
- Update immediately after completing items
- Mark items as in_progress when starting work
- Only one item in_progress at a time
- Add new items when discovering additional steps
# Answer Generation
## Structure
- Organize clearly with evidence from retrieved KB content
- Use proper headings and sections when appropriate
- Focus on answering the user's question directly
## Evidence Requirements
- Only include content directly supported by retrieved KB sources
- Never add information from memory or general training data
- If requested information is unavailable in KBs, say so clearly and suggest:
- How to improve queries
- What documents might help if added to KB
- How graph configuration might help
## Citation Format
Place citations inline within the Answer section (not in tool steps):
- Knowledge Base: <kb doc="<doc_name>" chunk_id="<chunk_id>" />
Citations must appear on the same line as the supported content, immediately after the relevant clause or at the end of the sentence.
## Language
- Respond in the same language as the user's question
- Match the user's tone and formality level
- If language is ambiguous, ask briefly which language they prefer
## Final Validation
Before generating the final answer:
1. Use thinking tool to verify evidence sufficiency
2. Note key citations to use
3. Outline the response structure
4. Generate answer based on thinking (don't include chain-of-thought in answer)
## KB Limitation Communication
When KB information is insufficient:
- Clearly state what information is available vs. unavailable
- Suggest specific improvements (query optimization, document addition, graph configuration)
- Be honest about limitations - never fabricate information
# Available Knowledge Bases and Recently Added Documents/FAQs
{{knowledge_bases}}
IMPORTANT: this part ONLY provides the RECENTLY ADDED documents/FAQs, you should use the retrieval tools to retrieve more documents/FAQs if needed.
`
+2 -2
View File
@@ -14,7 +14,7 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: "thinking", Label: "思考", Description: "动态和反思性的问题解决思考工具"},
{Name: "todo_write", Label: "制定计划", Description: "创建结构化的研究计划"},
{Name: "knowledge_search", Label: "知识搜索", Description: "在知识库中搜索相关信息"},
{Name: "get_related_chunks", Label: "获取相关片段", Description: "查找相关的知识片段"},
{Name: "list_knowledge_chunks", Label: "查看知识分块", Description: "按 knowledge_id 拉取文档分块列表"},
{Name: "query_knowledge_graph", Label: "查询知识图谱", Description: "从知识图谱中查询关系"},
{Name: "get_document_info", Label: "获取文档信息", Description: "查看文档元数据"},
{Name: "database_query", Label: "查询数据库", Description: "查询数据库中的信息"},
@@ -27,7 +27,7 @@ func DefaultAllowedTools() []string {
"thinking",
"todo_write",
"knowledge_search",
"get_related_chunks",
"list_knowledge_chunks",
"query_knowledge_graph",
"get_document_info",
"database_query",
+18 -15
View File
@@ -12,12 +12,14 @@ import (
// GetDocumentInfoTool retrieves detailed information about a document/knowledge
type GetDocumentInfoTool struct {
BaseTool
tenantID uint
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
}
// NewGetDocumentInfoTool creates a new get document info tool
func NewGetDocumentInfoTool(
tenantID uint,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
) *GetDocumentInfoTool {
@@ -52,6 +54,7 @@ Do not use when:
return &GetDocumentInfoTool{
BaseTool: NewBaseTool("get_document_info", description),
tenantID: tenantID,
knowledgeService: knowledgeService,
chunkService: chunkService,
}
@@ -119,7 +122,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
defer wg.Done()
// Get knowledge metadata
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, id)
knowledge, err := t.knowledgeService.GetRepository().GetKnowledgeByID(ctx, t.tenantID, id)
if err != nil {
mu.Lock()
results[id] = &docInfo{
@@ -130,7 +133,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
}
// Get chunk count
chunks, err := t.chunkService.ListChunksByKnowledgeID(ctx, id)
chunks, err := t.chunkService.GetRepository().ListChunksByKnowledgeID(ctx, t.tenantID, id)
chunkCount := 0
if err == nil {
chunkCount = len(chunks)
@@ -217,24 +220,24 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
output += "\n"
formattedDocs = append(formattedDocs, map[string]interface{}{
"knowledge_id": k.ID,
"title": k.Title,
"description": k.Description,
"type": k.Type,
"source": k.Source,
"file_name": k.FileName,
"file_type": k.FileType,
"file_size": k.FileSize,
"parse_status": k.ParseStatus,
"chunk_count": doc.chunkCount,
"metadata": k.GetMetadata(),
"type_icon": typeIcon,
"knowledge_id": k.ID,
"title": k.Title,
"description": k.Description,
"type": k.Type,
"source": k.Source,
"file_name": k.FileName,
"file_type": k.FileType,
"file_size": k.FileSize,
"parse_status": k.ParseStatus,
"chunk_count_min": doc.chunkCount,
"metadata": k.GetMetadata(),
"type_icon": typeIcon,
})
}
output += "=== Usage Tips ===\n"
output += "- Use knowledge_search to search document content\n"
output += "- Use get_related_chunks to view context and related chunks\n"
output += "- Use list_knowledge_chunks to view context and related chunks\n"
output += "- Search results already contain full chunk content\n"
// Extract first document title for summary
-427
View File
@@ -1,427 +0,0 @@
package tools
import (
"context"
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// GetRelatedChunksTool retrieves chunks related to a given chunk
type GetRelatedChunksTool struct {
BaseTool
chunkService interfaces.ChunkService
knowledgeBaseService interfaces.KnowledgeBaseService
}
// NewGetRelatedChunksTool creates a new get related chunks tool
func NewGetRelatedChunksTool(chunkService interfaces.ChunkService, knowledgeBaseService interfaces.KnowledgeBaseService) *GetRelatedChunksTool {
description := `Retrieve chunks related to specified reference chunks. Supports sequential (adjacent) and semantic (similar) relation types.
## When to Use
Use this tool when:
- Search results need additional context for full understanding
- You need to see content before/after a specific chunk
- Looking for semantically similar content across the document
- Understanding the complete narrative flow of a topic
Do not use when:
- Search results already provide sufficient complete content
- Only need a single specific chunk without context
## Parameters
chunk_ids (required): Array of reference chunk IDs (1-10)
- Obtained from search results
- Supports concurrent batch processing
- Example: ["chunk_abc", "chunk_def"]
relation_type (optional): Type of relation
- "sequential" (default): Get adjacent chunks before and after
- "semantic": Get semantically similar chunks regardless of position
limit (optional): Number of related chunks to return per reference chunk
- Default: 5
- Range: 1-10
- Sequential: retrieves limit/2 chunks before and after
- Semantic: retrieves top limit most similar chunks
## Relation Types
Sequential:
- Retrieves adjacent chunks in document order
- Useful for understanding complete narrative flow
- Ideal for scenarios requiring continuous reading
- Example: viewing complete configuration steps
Semantic:
- Finds content-similar chunks regardless of position
- Discovers related discussions throughout document
- Ideal for topic expansion and cross-referencing
- Example: finding all mentions of a specific concept
## Usage Patterns
1. Context expansion: knowledge_search -> get_related_chunks(sequential)
2. Topic exploration: knowledge_search -> get_related_chunks(semantic)
3. Deep research: knowledge_search -> get_related_chunks(both sequential and semantic)
## Notes
- Results are automatically deduplicated
- Source chunks are excluded from results
- Sequential results sorted by chunk_index
- Semantic results sorted by similarity score
- Limit value of 5 typically provides sufficient context without information overload`
return &GetRelatedChunksTool{
BaseTool: NewBaseTool("get_related_chunks", description),
chunkService: chunkService,
knowledgeBaseService: knowledgeBaseService,
}
}
// Parameters returns the JSON schema for the tool's parameters
func (t *GetRelatedChunksTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"chunk_ids": map[string]interface{}{
"type": "array",
"description": "Array of reference chunk IDs",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 10,
},
"relation_type": map[string]interface{}{
"type": "string",
"description": "Type: sequential (default) or semantic",
"enum": []string{"sequential", "semantic"},
"default": "sequential",
},
"limit": map[string]interface{}{
"type": "integer",
"description": "Number of related chunks per input chunk (default: 5)",
"default": 5,
"minimum": 1,
"maximum": 10,
},
},
"required": []string{"chunk_ids"},
}
}
// Execute executes the get related chunks tool with concurrent processing
func (t *GetRelatedChunksTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
// Extract chunk_ids array
chunkIDsRaw, ok := args["chunk_ids"].([]interface{})
if !ok || len(chunkIDsRaw) == 0 {
return &types.ToolResult{
Success: false,
Error: "chunk_ids is required and must be a non-empty array",
}, fmt.Errorf("chunk_ids is required")
}
// Convert to string slice
var chunkIDs []string
for _, id := range chunkIDsRaw {
if idStr, ok := id.(string); ok && idStr != "" {
chunkIDs = append(chunkIDs, idStr)
}
}
if len(chunkIDs) == 0 {
return &types.ToolResult{
Success: false,
Error: "chunk_ids must contain at least one valid chunk ID",
}, fmt.Errorf("no valid chunk IDs provided")
}
relationType := "sequential"
if rt, ok := args["relation_type"].(string); ok {
relationType = rt
}
limit := 5
if l, ok := args["limit"].(float64); ok {
limit = int(l)
}
if limit < 1 {
limit = 1
}
if limit > 10 {
limit = 10
}
// Concurrently get related chunks for each chunk ID
type relatedResult struct {
sourceChunk *types.Chunk
relatedChunks []*types.Chunk
err error
}
var wg sync.WaitGroup
var mu sync.Mutex
results := make(map[string]*relatedResult)
for _, chunkID := range chunkIDs {
wg.Add(1)
go func(id string) {
defer wg.Done()
// Get the original chunk first
chunk, err := t.chunkService.GetChunkByID(ctx, id)
if err != nil || chunk == nil {
mu.Lock()
results[id] = &relatedResult{err: fmt.Errorf("failed to retrieve chunk: %v", err)}
mu.Unlock()
return
}
var relatedChunks []*types.Chunk
if relationType == "sequential" {
relatedChunks, err = t.getSequentialRelatedChunks(ctx, chunk, limit)
} else if relationType == "semantic" {
relatedChunks, err = t.getSemanticRelatedChunks(ctx, chunk, limit)
}
mu.Lock()
results[id] = &relatedResult{
sourceChunk: chunk,
relatedChunks: relatedChunks,
err: err,
}
mu.Unlock()
}(chunkID)
}
wg.Wait()
// Collect and deduplicate all related chunks
seenChunks := make(map[string]*types.Chunk)
sourceChunkIDs := make(map[string]bool)
var errors []string
// Mark source chunks to exclude them from results
for _, chunkID := range chunkIDs {
sourceChunkIDs[chunkID] = true
}
for _, chunkID := range chunkIDs {
result := results[chunkID]
if result.err != nil {
errors = append(errors, fmt.Sprintf("chunk %s: %v", chunkID, result.err))
continue
}
for _, chunk := range result.relatedChunks {
// Exclude source chunks and avoid duplicates
if !sourceChunkIDs[chunk.ID] {
if _, seen := seenChunks[chunk.ID]; !seen {
seenChunks[chunk.ID] = chunk
}
}
}
}
// Convert map to slice and sort
allRelatedChunks := make([]*types.Chunk, 0, len(seenChunks))
for _, chunk := range seenChunks {
allRelatedChunks = append(allRelatedChunks, chunk)
}
// Sort chunks
if relationType == "sequential" {
// Sort by knowledge_id and chunk_index for sequential
sortChunksByPosition(allRelatedChunks)
}
// For semantic, keep the order from search results (already sorted by relevance)
if len(allRelatedChunks) == 0 {
return &types.ToolResult{
Success: true,
Output: "No related chunks found. Possible reasons:\n- Chunk is the only chunk in document\n- Semantic similarity threshold not met\n- Invalid chunk_id provided",
Data: map[string]interface{}{
"chunk_ids": chunkIDs,
"relation_type": relationType,
"count": 0,
"chunks": []interface{}{},
"errors": errors,
},
}, nil
}
// Format output
return t.formatOutput(chunkIDs, relationType, allRelatedChunks, errors)
}
// getSequentialRelatedChunks gets chunks before and after the reference chunk
func (t *GetRelatedChunksTool) getSequentialRelatedChunks(ctx context.Context, chunk *types.Chunk, limit int) ([]*types.Chunk, error) {
// Get all chunks from the same knowledge
allChunks, err := t.chunkService.ListChunksByKnowledgeID(ctx, chunk.KnowledgeID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve document chunks: %v", err)
}
relatedChunks := make([]*types.Chunk, 0)
// Bidirectional window: get chunks before and after
halfLimit := limit / 2
if halfLimit < 1 {
halfLimit = 1
}
minIndex := chunk.ChunkIndex - halfLimit
maxIndex := chunk.ChunkIndex + halfLimit
for _, c := range allChunks {
// Within range and not the source chunk itself
if c.ChunkIndex >= minIndex && c.ChunkIndex <= maxIndex && c.ID != chunk.ID {
relatedChunks = append(relatedChunks, c)
}
}
return relatedChunks, nil
}
// getSemanticRelatedChunks gets semantically similar chunks using hybrid search
func (t *GetRelatedChunksTool) getSemanticRelatedChunks(ctx context.Context, chunk *types.Chunk, limit int) ([]*types.Chunk, error) {
// Use chunk content as query for semantic search
searchParams := types.SearchParams{
QueryText: chunk.Content,
MatchCount: limit + 5, // Get extra results for filtering
}
// Search in the knowledge base that contains this chunk
searchResults, err := t.knowledgeBaseService.HybridSearch(ctx, chunk.KnowledgeBaseID, searchParams)
if err != nil {
return nil, fmt.Errorf("semantic search failed: %v", err)
}
// Convert search results to chunks, excluding the source chunk
relatedChunks := make([]*types.Chunk, 0, limit)
for _, result := range searchResults {
if result.ID == chunk.ID {
continue // Skip the source chunk itself
}
// Convert SearchResult to Chunk
relatedChunk := &types.Chunk{
ID: result.ID,
KnowledgeID: result.KnowledgeID,
KnowledgeBaseID: chunk.KnowledgeBaseID,
Content: result.Content,
ChunkIndex: result.ChunkIndex,
}
relatedChunks = append(relatedChunks, relatedChunk)
if len(relatedChunks) >= limit {
break
}
}
return relatedChunks, nil
}
// sortChunksByPosition sorts chunks by knowledge_id and chunk_index
func sortChunksByPosition(chunks []*types.Chunk) {
// Simple bubble sort for small arrays
n := len(chunks)
for i := 0; i < n-1; i++ {
for j := 0; j < n-i-1; j++ {
// First sort by knowledge_id, then by chunk_index
if chunks[j].KnowledgeID > chunks[j+1].KnowledgeID ||
(chunks[j].KnowledgeID == chunks[j+1].KnowledgeID &&
chunks[j].ChunkIndex > chunks[j+1].ChunkIndex) {
chunks[j], chunks[j+1] = chunks[j+1], chunks[j]
}
}
}
}
// formatOutput formats the tool output
func (t *GetRelatedChunksTool) formatOutput(
chunkIDs []string,
relationType string,
chunks []*types.Chunk,
errors []string,
) (*types.ToolResult, error) {
relationTypeLabel := map[string]string{
"sequential": "Sequential (Adjacent)",
"semantic": "Semantic (Similar Content)",
}
output := "=== Related Chunks ===\n\n"
output += fmt.Sprintf("Reference chunks: %d\n", len(chunkIDs))
output += fmt.Sprintf("Relation type: %s\n", relationTypeLabel[relationType])
output += fmt.Sprintf("Found %d related chunks (deduplicated)\n\n", len(chunks))
if len(errors) > 0 {
output += "=== Partial Failures ===\n"
for _, errMsg := range errors {
output += fmt.Sprintf(" - %s\n", errMsg)
}
output += "\n"
}
output += "=== Content ===\n\n"
formattedChunks := make([]map[string]interface{}, 0, len(chunks))
currentKnowledge := ""
for i, c := range chunks {
// Group by knowledge document
if c.KnowledgeID != currentKnowledge {
currentKnowledge = c.KnowledgeID
if i > 0 {
output += "\n"
}
output += fmt.Sprintf("[Document: %s]\n\n", c.KnowledgeID)
}
output += fmt.Sprintf("Chunk #%d (Position: %d):\n", i+1, c.ChunkIndex+1)
output += fmt.Sprintf(" chunk_id: %s\n", c.ID)
output += fmt.Sprintf(" content: %s\n\n", c.Content)
formattedChunks = append(formattedChunks, map[string]interface{}{
"index": i + 1,
"chunk_id": c.ID,
"chunk_index": c.ChunkIndex,
"content": c.Content,
"knowledge_id": c.KnowledgeID,
})
}
output += "=== Notes ===\n"
if relationType == "sequential" {
output += "- Adjacent chunks in document order\n"
output += "- Useful for understanding complete narrative flow\n"
output += "- Sorted by position\n"
} else {
output += "- Semantically similar chunks sorted by relevance\n"
output += "- Useful for discovering related discussions\n"
output += "- Ideal for topic expansion and cross-referencing\n"
}
output += "- Source chunks excluded\n"
output += "- Results deduplicated\n"
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"chunk_ids": chunkIDs,
"relation_type": relationType,
"count": len(chunks),
"chunks": formattedChunks,
"errors": errors,
"display_type": "related_chunks",
},
}, nil
}
+198 -385
View File
@@ -9,6 +9,7 @@ import (
"strings"
"sync"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/rerank"
@@ -28,48 +29,39 @@ type searchResultWithMeta struct {
// KnowledgeSearchTool searches knowledge bases with flexible query modes
type KnowledgeSearchTool struct {
BaseTool
knowledgeService interfaces.KnowledgeBaseService
chunkService interfaces.ChunkService
tenantID uint
allowedKBs []string
rerankModel rerank.Reranker
chatModel chat.Chat // Optional chat model for LLM-based reranking
knowledgeBaseService interfaces.KnowledgeBaseService
chunkService interfaces.ChunkService
tenantID uint
allowedKBs []string
rerankModel rerank.Reranker
chatModel chat.Chat // Optional chat model for LLM-based reranking
config *config.Config // Global config for fallback values
}
// NewKnowledgeSearchTool creates a new knowledge search tool
func NewKnowledgeSearchTool(
knowledgeService interfaces.KnowledgeBaseService,
knowledgeBaseService interfaces.KnowledgeBaseService,
chunkService interfaces.ChunkService,
tenantID uint,
allowedKBs []string,
rerankModel rerank.Reranker,
chatModel chat.Chat,
cfg *config.Config,
) *KnowledgeSearchTool {
description := `Search within knowledge bases with flexible query modes. Unified tool that supports both targeted and broad searches.
description := `Search within knowledge bases. Unified tool that supports both targeted and broad searches.
## Features
- Multi-KB search: Search across multiple knowledge bases concurrently
- Flexible queries: Support vector, keyword, or hybrid search modes
- Quality filtering: Automatically filters low-quality chunks
## Usage
**Use when**:
- You know which knowledge bases to target (specify knowledge_base_ids)
- You're unsure which KB contains the info (omit knowledge_base_ids to search all allowed KBs)
- Want to search specific KBs with same query
- Need semantic (vector) or exact keyword searches
- Want to search only specific documents within KBs
- Want to search with multiple queries to get comprehensive results
- Want to filter results from specific documents (use knowledge_ids)
**Search Modes**:
- Simple: Provide single query parameter (hybrid search)
- Vector only: Provide vector_queries only
- Keyword only: Provide keyword_queries only
- Hybrid: Provide both vector_queries and keyword_queries
- At least one query parameter must be provided
**Returns**: Merged and deduplicated search results from all KBs
**Returns**: Merged and deduplicated search results from KBs
## Examples
@@ -77,48 +69,37 @@ func NewKnowledgeSearchTool(
# Simple search in specific KBs
{
"knowledge_base_ids": ["kb1", "kb2"],
"query": "什么是向量数据库"
"queries": ["什么是向量数据库"]
}
# Search all allowed KBs with vector queries
# Search all allowed KBs with multiple queries
{
"vector_queries": ["什么是向量数据库", "向量数据库的定义"]
}
# Multiple query types with thresholds
{
"knowledge_base_ids": ["kb1"],
"vector_queries": ["向量数据库应用"],
"keyword_queries": ["Docker", "部署"],
"vector_threshold": 0.7,
"keyword_threshold": 0.6
"queries": ["什么是向量数据库", "向量数据库的应用场景"]
}
# Search specific documents
{
"knowledge_base_ids": ["kb1"],
"query": "彗星的起源",
"queries": ["彗星的起源"],
"knowledge_ids": ["doc1", "doc2"]
}
` + "`" + `
## Tips
- Concurrent search across multiple KBs and queries
- Concurrent search across multiple KBs
- Results are automatically reranked to unify scores from different sources
- Reranked scores are in 0-1 range and directly comparable
- Results are merged, deduplicated and sorted by relevance
- Use vector_queries for semantic/conceptual searches
- Use keyword_queries for exact term matching`
- Results are merged, deduplicated and sorted by relevance`
return &KnowledgeSearchTool{
BaseTool: NewBaseTool("knowledge_search", description),
knowledgeService: knowledgeService,
chunkService: chunkService,
tenantID: tenantID,
allowedKBs: allowedKBs,
rerankModel: rerankModel,
chatModel: chatModel,
BaseTool: NewBaseTool("knowledge_search", description),
knowledgeBaseService: knowledgeBaseService,
chunkService: chunkService,
tenantID: tenantID,
allowedKBs: allowedKBs,
rerankModel: rerankModel,
chatModel: chatModel,
config: cfg,
}
}
@@ -127,80 +108,39 @@ func (t *KnowledgeSearchTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"queries": map[string]interface{}{
"type": "array",
"description": "Array of search queries",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 5,
},
"knowledge_base_ids": map[string]interface{}{
"type": "array",
"description": "Array of knowledge base IDs to search in (optional, if omitted searches all allowed KBs)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"minItems": 0,
"maxItems": 10,
},
"query": map[string]interface{}{
"type": "string",
"description": "Single search query for simple hybrid search",
},
"vector_queries": map[string]interface{}{
"type": "array",
"description": "Array of semantic queries for vector search (1-5 queries)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 5,
},
"keyword_queries": map[string]interface{}{
"type": "array",
"description": "Array of keyword queries for keyword search (1-5 queries)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"maxItems": 5,
},
"top_k": map[string]interface{}{
"type": "integer",
"description": "Number of results per knowledge base per query (default: 5)",
"default": 5,
"minimum": 1,
"maximum": 20,
},
"vector_threshold": map[string]interface{}{
"type": "number",
"description": "Minimum score for vector results (default: 0.6)",
"default": 0.6,
"minimum": 0.0,
"maximum": 1.0,
},
"keyword_threshold": map[string]interface{}{
"type": "number",
"description": "Minimum score for keyword results (default: 0.5)",
"default": 0.5,
"minimum": 0.0,
"maximum": 1.0,
},
"knowledge_ids": map[string]interface{}{
"type": "array",
"description": "Optional array of document IDs to filter results (only return results from these specific documents)",
"items": map[string]interface{}{
"type": "string",
},
"minItems": 1,
"minItems": 0,
"maxItems": 50,
},
"min_score": map[string]interface{}{
"type": "number",
"description": "Absolute minimum score threshold for filtering very low quality results (default: 0.3)",
"default": 0.3,
"minimum": 0.0,
"maximum": 1.0,
},
},
"required": []string{},
"required": []string{"queries"},
}
}
// Execute executes the knowledge search tool with flexible query modes
// Execute executes the knowledge search tool
func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Execute started")
@@ -232,90 +172,74 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
logger.Infof(ctx, "[Tool][KnowledgeSearch] Using all allowed KBs (%d): %v", len(kbIDs), kbIDs)
}
// Parse query parameters
var singleQuery string
var vectorQueries, keywordQueries []string
// Parse single query
if q, ok := args["query"].(string); ok && q != "" {
singleQuery = q
}
// Parse vector_queries
if vq, ok := args["vector_queries"].([]interface{}); ok {
for _, q := range vq {
if queryStr, ok := q.(string); ok && queryStr != "" {
vectorQueries = append(vectorQueries, queryStr)
// Parse query parameter
var queries []string
if queriesRaw, ok := args["queries"].([]interface{}); ok && len(queriesRaw) > 0 {
for _, q := range queriesRaw {
if qStr, ok := q.(string); ok && qStr != "" {
queries = append(queries, qStr)
}
}
}
// Parse keyword_queries
if kq, ok := args["keyword_queries"].([]interface{}); ok {
for _, q := range kq {
if queryStr, ok := q.(string); ok && queryStr != "" {
keywordQueries = append(keywordQueries, queryStr)
}
}
}
// If single query provided, treat it as both vector and keyword query
if singleQuery != "" {
if len(vectorQueries) == 0 && len(keywordQueries) == 0 {
vectorQueries = []string{singleQuery}
keywordQueries = []string{singleQuery}
}
}
// Validate: at least one query must be provided
if len(vectorQueries) == 0 && len(keywordQueries) == 0 {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] No query provided")
// Validate: query must be provided
if len(queries) == 0 {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] No queries provided")
return &types.ToolResult{
Success: false,
Error: "at least one of query, vector_queries, or keyword_queries must be provided",
}, fmt.Errorf("no query provided")
Error: "queries parameter is required",
}, fmt.Errorf("no queries provided")
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Query mode: single=%v, vector_queries=%d, keyword_queries=%d",
singleQuery != "", len(vectorQueries), len(keywordQueries))
if singleQuery != "" {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Single query: %s", singleQuery)
}
if len(vectorQueries) > 0 {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Vector queries: %v", vectorQueries)
}
if len(keywordQueries) > 0 {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Keyword queries: %v", keywordQueries)
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Queries: %v", queries)
// Parse thresholds
vectorThreshold := 0.6
if vt, ok := args["vector_threshold"].(float64); ok {
vectorThreshold = vt
}
// Get search parameters from tenant conversation config, fallback to global config
var topK int
var vectorThreshold, keywordThreshold, minScore float64
keywordThreshold := 0.5
if kt, ok := args["keyword_threshold"].(float64); ok {
keywordThreshold = kt
}
// Parse min_score for absolute filtering
minScore := 0.3
if ms, ok := args["min_score"].(float64); ok {
minScore = ms
}
// Parse top_k
topK := 5
if topKVal, ok := args["top_k"]; ok {
switch v := topKVal.(type) {
case float64:
topK = int(v)
case int:
topK = v
// Try to get from tenant conversation config
if tenantVal := ctx.Value(types.TenantInfoContextKey); tenantVal != nil {
if tenant, ok := tenantVal.(*types.Tenant); ok && tenant != nil && tenant.ConversationConfig != nil {
cc := tenant.ConversationConfig
if cc.EmbeddingTopK > 0 {
topK = cc.EmbeddingTopK
}
if cc.VectorThreshold > 0 {
vectorThreshold = cc.VectorThreshold
}
if cc.KeywordThreshold > 0 {
keywordThreshold = cc.KeywordThreshold
}
// minScore is not in ConversationConfig, use default or config
minScore = 0.3
}
}
// Fallback to global config if not set
if topK == 0 && t.config != nil {
topK = t.config.Conversation.EmbeddingTopK
}
if vectorThreshold == 0 && t.config != nil {
vectorThreshold = t.config.Conversation.VectorThreshold
}
if keywordThreshold == 0 && t.config != nil {
keywordThreshold = t.config.Conversation.KeywordThreshold
}
// Final fallback to hardcoded defaults if config is not available
if topK == 0 {
topK = 5
}
if vectorThreshold == 0 {
vectorThreshold = 0.6
}
if keywordThreshold == 0 {
keywordThreshold = 0.5
}
if minScore == 0 {
minScore = 0.3
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Search params: top_k=%d, vector_threshold=%.2f, keyword_threshold=%.2f, min_score=%.2f",
topK, vectorThreshold, keywordThreshold, minScore)
@@ -330,11 +254,11 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
}
}
// Execute concurrent search
// Execute concurrent search (hybrid search handles both vector and keyword)
logger.Infof(ctx, "[Tool][KnowledgeSearch] Starting concurrent search across %d KBs", len(kbIDs))
kbTypeMap := t.getKnowledgeBaseTypes(ctx, kbIDs)
allResults := t.concurrentSearch(ctx, vectorQueries, keywordQueries, kbIDs,
allResults := t.concurrentSearch(ctx, queries, kbIDs,
topK, vectorThreshold, keywordThreshold, kbTypeMap)
logger.Infof(ctx, "[Tool][KnowledgeSearch] Concurrent search completed: %d raw results", len(allResults))
@@ -353,55 +277,54 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
}
// Filter by threshold first
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying threshold filter...")
filteredResults := t.filterByThreshold(allResults, vectorThreshold, keywordThreshold)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After threshold filter: %d results (from %d)",
len(filteredResults), len(allResults))
// Deduplicate before reranking to reduce processing overhead
deduplicatedBeforeRerank := t.deduplicateResults(filteredResults)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After deduplication before rerank: %d results (from %d)",
len(deduplicatedBeforeRerank), len(filteredResults))
// Apply ReRank if model is configured
// Prefer chatModel (LLM-based reranking) over rerankModel if both are available
if t.chatModel != nil && len(filteredResults) > 0 {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying LLM-based rerank with model: %s, input: %d results",
t.chatModel.GetModelName(), len(filteredResults))
rerankQuery := singleQuery
if rerankQuery == "" && len(vectorQueries) > 0 {
rerankQuery = vectorQueries[0] // Use first vector query as rerank query
} else if rerankQuery == "" && len(keywordQueries) > 0 {
rerankQuery = keywordQueries[0] // Use first keyword query as fallback
// Use first query for reranking (or combine all queries if needed)
rerankQuery := ""
if len(queries) > 0 {
rerankQuery = queries[0]
if len(queries) > 1 {
// Combine multiple queries for reranking
rerankQuery = strings.Join(queries, " ")
}
}
if rerankQuery != "" {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Rerank query: %s", rerankQuery)
rerankedResults, err := t.rerankResults(ctx, rerankQuery, filteredResults)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] LLM rerank failed, using original results: %v", err)
} else {
filteredResults = rerankedResults
logger.Infof(ctx, "[Tool][KnowledgeSearch] LLM rerank completed successfully: %d results",
len(filteredResults))
}
if t.chatModel != nil && len(deduplicatedBeforeRerank) > 0 && rerankQuery != "" {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying LLM-based rerank with model: %s, input: %d results, queries: %v",
t.chatModel.GetModelName(), len(deduplicatedBeforeRerank), queries)
rerankedResults, err := t.rerankResults(ctx, rerankQuery, deduplicatedBeforeRerank)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] LLM rerank failed, using original results: %v", err)
filteredResults = deduplicatedBeforeRerank
} else {
filteredResults = rerankedResults
logger.Infof(ctx, "[Tool][KnowledgeSearch] LLM rerank completed successfully: %d results",
len(filteredResults))
}
} else if t.rerankModel != nil && len(filteredResults) > 0 {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying rerank with model: %s, input: %d results",
t.rerankModel.GetModelName(), len(filteredResults))
rerankQuery := singleQuery
if rerankQuery == "" && len(vectorQueries) > 0 {
rerankQuery = vectorQueries[0] // Use first vector query as rerank query
} else if rerankQuery == "" && len(keywordQueries) > 0 {
rerankQuery = keywordQueries[0] // Use first keyword query as fallback
}
if rerankQuery != "" {
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Rerank query: %s", rerankQuery)
rerankedResults, err := t.rerankResults(ctx, rerankQuery, filteredResults)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Rerank failed, using original results: %v", err)
} else {
filteredResults = rerankedResults
logger.Infof(ctx, "[Tool][KnowledgeSearch] Rerank completed successfully: %d results",
len(filteredResults))
}
} else if t.rerankModel != nil && len(deduplicatedBeforeRerank) > 0 && rerankQuery != "" {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying rerank with model: %s, input: %d results, queries: %v",
t.rerankModel.GetModelName(), len(deduplicatedBeforeRerank), queries)
rerankedResults, err := t.rerankResults(ctx, rerankQuery, deduplicatedBeforeRerank)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Rerank failed, using original results: %v", err)
filteredResults = deduplicatedBeforeRerank
} else {
filteredResults = rerankedResults
logger.Infof(ctx, "[Tool][KnowledgeSearch] Rerank completed successfully: %d results",
len(filteredResults))
}
} else {
// No reranking, use deduplicated results
filteredResults = deduplicatedBeforeRerank
}
// Apply absolute minimum score filter to remove very low quality chunks
@@ -409,44 +332,37 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
filteredResults = t.filterByMinScore(filteredResults, minScore)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After min_score filter: %d results", len(filteredResults))
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Deduplicating results...")
// Final deduplication after rerank (in case rerank changed scores/order but duplicates remain)
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Final deduplication after rerank...")
deduplicatedResults := t.deduplicateResults(filteredResults)
logger.Infof(ctx, "[Tool][KnowledgeSearch] After deduplication: %d results (from %d)",
logger.Infof(ctx, "[Tool][KnowledgeSearch] After final deduplication: %d results (from %d)",
len(deduplicatedResults), len(filteredResults))
// Sort results by score (descending)
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Sorting results by score...")
sort.Slice(deduplicatedResults, func(i, j int) bool {
if deduplicatedResults[i].Score != deduplicatedResults[j].Score {
return deduplicatedResults[i].Score > deduplicatedResults[j].Score
}
// If scores are equal, prefer vector matches
if deduplicatedResults[i].QueryType != deduplicatedResults[j].QueryType {
return deduplicatedResults[i].QueryType == "vector"
}
// If scores are equal, sort by knowledge ID for consistency
return deduplicatedResults[i].KnowledgeID < deduplicatedResults[j].KnowledgeID
})
// Log top results
if len(deduplicatedResults) > 0 {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Top 5 results by score:")
for i := 0; i < len(deduplicatedResults) && i < 5; i++ {
r := deduplicatedResults[i]
logger.Infof(ctx, "[Tool][KnowledgeSearch] #%d: score=%.3f, type=%s, kb=%s, chunk_id=%s",
logger.Infof(ctx, "[Tool][KnowledgeSearch][Top %d] score=%.3f, type=%s, kb=%s, chunk_id=%s",
i+1, r.Score, r.QueryType, r.KnowledgeID, r.ID)
}
}
// Build output
logger.Infof(ctx, "[Tool][KnowledgeSearch] Formatting output with %d final results", len(deduplicatedResults))
result, err := t.formatOutput(ctx, deduplicatedResults, vectorQueries, keywordQueries,
kbIDs, len(allResults), vectorThreshold, keywordThreshold, knowledgeIDsFilter, singleQuery)
result, err := t.formatOutput(ctx, deduplicatedResults, kbIDs, len(allResults), knowledgeIDsFilter, queries)
if err != nil {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] Failed to format output: %v", err)
return result, err
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] Execute completed successfully")
return result, nil
}
@@ -462,7 +378,7 @@ func (t *KnowledgeSearchTool) getKnowledgeBaseTypes(ctx context.Context, kbIDs [
continue
}
kb, err := t.knowledgeService.GetKnowledgeBaseByID(ctx, kbID)
kb, err := t.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to fetch knowledge base %s info: %v", kbID, err)
continue
@@ -474,57 +390,13 @@ func (t *KnowledgeSearchTool) getKnowledgeBaseTypes(ctx context.Context, kbIDs [
return kbTypeMap
}
// concurrentSearch executes vector and keyword searches concurrently
// concurrentSearch executes hybrid search across multiple KBs concurrently
func (t *KnowledgeSearchTool) concurrentSearch(
ctx context.Context,
vectorQueries, keywordQueries []string,
kbsToSearch []string,
topK int,
vectorThreshold, keywordThreshold float64,
kbTypeMap map[string]string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
allResults := make([]*searchResultWithMeta, 0)
// Launch vector searches
if len(vectorQueries) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
results := t.searchWithQueries(ctx, vectorQueries, kbsToSearch, topK,
vectorThreshold, 1.0, "vector", kbTypeMap)
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
}()
}
// Launch keyword searches
if len(keywordQueries) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
results := t.searchWithQueries(ctx, keywordQueries, kbsToSearch, topK,
1.0, keywordThreshold, "keyword", kbTypeMap)
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
}()
}
wg.Wait()
return allResults
}
// searchWithQueries executes multiple queries concurrently
func (t *KnowledgeSearchTool) searchWithQueries(
ctx context.Context,
queries []string,
kbsToSearch []string,
topK int,
vectorThreshold, keywordThreshold float64,
queryType string,
kbTypeMap map[string]string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
@@ -532,72 +404,46 @@ func (t *KnowledgeSearchTool) searchWithQueries(
allResults := make([]*searchResultWithMeta, 0)
for _, query := range queries {
wg.Add(1)
go func(q string) {
defer wg.Done()
results := t.searchSingleQuery(ctx, q, kbsToSearch, topK,
vectorThreshold, keywordThreshold, queryType, kbTypeMap)
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
}(query)
}
// Capture query in local variable to avoid closure issues
q := query
for _, kbID := range kbsToSearch {
// Capture kbID in local variable to avoid closure issues
kb := kbID
wg.Add(1)
go func() {
defer wg.Done()
searchParams := types.SearchParams{
QueryText: q,
MatchCount: topK,
VectorThreshold: vectorThreshold,
KeywordThreshold: keywordThreshold,
}
kbResults, err := t.knowledgeBaseService.HybridSearch(ctx, kb, searchParams)
if err != nil {
// Log error but continue with other KBs
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to search knowledge base %s: %v", kb, err)
return
}
// Wrap results with metadata
mu.Lock()
for _, r := range kbResults {
allResults = append(allResults, &searchResultWithMeta{
SearchResult: r,
SourceQuery: q,
QueryType: "hybrid", // Hybrid search combines both vector and keyword
KnowledgeBaseID: kb,
KnowledgeBaseType: kbTypeMap[kb],
})
}
mu.Unlock()
}()
}
}
wg.Wait()
return allResults
}
// searchSingleQuery searches a single query across multiple KBs concurrently
func (t *KnowledgeSearchTool) searchSingleQuery(
ctx context.Context,
query string,
kbsToSearch []string,
topK int,
vectorThreshold, keywordThreshold float64,
queryType string,
kbTypeMap map[string]string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
results := make([]*searchResultWithMeta, 0)
searchParams := types.SearchParams{
QueryText: query,
MatchCount: topK,
VectorThreshold: vectorThreshold,
KeywordThreshold: keywordThreshold,
}
for _, kbID := range kbsToSearch {
wg.Add(1)
go func(kb string) {
defer wg.Done()
kbResults, err := t.knowledgeService.HybridSearch(ctx, kb, searchParams)
if err != nil {
// Log error but continue with other KBs
return
}
// Wrap results with metadata
mu.Lock()
for _, r := range kbResults {
results = append(results, &searchResultWithMeta{
SearchResult: r,
SourceQuery: query,
QueryType: queryType,
KnowledgeBaseID: kb,
KnowledgeBaseType: kbTypeMap[kb],
})
}
mu.Unlock()
}(kbID)
}
wg.Wait()
return results
}
// filterByThreshold filters results based on match type and threshold
func (t *KnowledgeSearchTool) filterByThreshold(
results []*searchResultWithMeta,
@@ -1011,12 +857,10 @@ func (t *KnowledgeSearchTool) deduplicateResults(results []*searchResultWithMeta
func (t *KnowledgeSearchTool) formatOutput(
ctx context.Context,
results []*searchResultWithMeta,
vectorQueries, keywordQueries []string,
kbsToSearch []string,
totalBeforeFilter int,
vectorThreshold, keywordThreshold float64,
knowledgeIDsFilter map[string]bool,
singleQuery string,
queries []string,
) (*types.ToolResult, error) {
if len(results) == 0 {
data := map[string]interface{}{
@@ -1031,8 +875,8 @@ func (t *KnowledgeSearchTool) formatOutput(
}
data["knowledge_ids"] = filterList
}
if singleQuery != "" {
data["query"] = singleQuery
if len(queries) > 0 {
data["queries"] = queries
}
return &types.ToolResult{
Success: true,
@@ -1041,14 +885,6 @@ func (t *KnowledgeSearchTool) formatOutput(
}, nil
}
// Determine search mode
searchMode := "Hybrid (Vector + Keyword)"
if len(vectorQueries) > 0 && len(keywordQueries) == 0 {
searchMode = "Vector"
} else if len(vectorQueries) == 0 && len(keywordQueries) > 0 {
searchMode = "Keyword"
}
// Build output header
output := "=== Search Results ===\n"
output += fmt.Sprintf("Knowledge Bases: %v\n", kbsToSearch)
@@ -1059,22 +895,13 @@ func (t *KnowledgeSearchTool) formatOutput(
}
output += fmt.Sprintf("Document Filter: %v\n", filterList)
}
output += fmt.Sprintf("Search Mode: %s\n", searchMode)
if singleQuery != "" {
output += fmt.Sprintf("Query: %s\n", singleQuery)
} else {
if len(vectorQueries) > 0 {
output += fmt.Sprintf("Vector Queries: %v\n", vectorQueries)
output += fmt.Sprintf("Vector Threshold: %.2f\n", vectorThreshold)
}
if len(keywordQueries) > 0 {
output += fmt.Sprintf("Keyword Queries: %v\n", keywordQueries)
output += fmt.Sprintf("Keyword Threshold: %.2f\n", keywordThreshold)
}
if len(queries) == 1 {
output += fmt.Sprintf("Query: %s\n", queries[0])
} else if len(queries) > 1 {
output += fmt.Sprintf("Queries (%d): %v\n", len(queries), queries)
}
output += fmt.Sprintf("Found %d relevant results (deduplicated)", len(results))
output += fmt.Sprintf("Found %d relevant results", len(results))
if totalBeforeFilter > len(results) {
output += fmt.Sprintf(" (filtered from %d)", totalBeforeFilter)
}
@@ -1118,16 +945,9 @@ func (t *KnowledgeSearchTool) formatOutput(
output += fmt.Sprintf("[Source Document: %s]\n", result.KnowledgeTitle)
}
relevanceLevel := GetRelevanceLevel(result.Score)
// relevanceLevel := GetRelevanceLevel(result.Score)
output += fmt.Sprintf("\nResult #%d:\n", i+1)
output += fmt.Sprintf(" Relevance: %.2f (%s)\n", result.Score, relevanceLevel)
output += fmt.Sprintf(" Match Type: %s", FormatMatchType(result.MatchType))
if result.SourceQuery != "" && result.SourceQuery != singleQuery {
output += fmt.Sprintf(" (Query: \"%s\")", result.SourceQuery)
}
output += "\n"
output += fmt.Sprintf(" Content: %s\n", result.Content)
output += fmt.Sprintf(" [chunk_id: %s - full content included above]\n", result.ID)
output += fmt.Sprintf(" [chunk_id: %s][chunk_index: %d]\nContent: %s\n", result.ID, result.ChunkIndex, result.Content)
if faqMeta != nil {
if faqMeta.StandardQuestion != "" {
@@ -1139,17 +959,17 @@ func (t *KnowledgeSearchTool) formatOutput(
if len(faqMeta.Answers) > 0 {
output += " FAQ Answers:\n"
for _, ans := range faqMeta.Answers {
output += fmt.Sprintf(" - %s\n", ans)
output += fmt.Sprintf(" Answer Choice %d: %s\n", i+1, ans)
}
}
}
formattedResults = append(formattedResults, map[string]interface{}{
"result_index": i + 1,
"chunk_id": result.ID,
"content": result.Content,
"score": result.Score,
"relevance_level": relevanceLevel,
"result_index": i + 1,
"chunk_id": result.ID,
"content": result.Content,
// "score": result.Score,
// "relevance_level": relevanceLevel,
"knowledge_id": result.KnowledgeID,
"knowledge_title": result.KnowledgeTitle,
"match_type": result.MatchType,
@@ -1182,14 +1002,13 @@ func (t *KnowledgeSearchTool) formatOutput(
// }
// output += "- Full content is already included in search results above\n"
// output += "- Results are deduplicated across knowledge bases and sorted by relevance\n"
// output += "- Use get_related_chunks to expand context if needed\n"
// output += "- Use list_knowledge_chunks to expand context if needed\n"
data := map[string]interface{}{
"knowledge_base_ids": kbsToSearch,
"results": formattedResults,
"count": len(results),
"kb_counts": kbCounts,
"search_mode": searchMode,
"display_type": "search_results",
}
if len(knowledgeIDsFilter) > 0 {
@@ -1199,14 +1018,8 @@ func (t *KnowledgeSearchTool) formatOutput(
}
data["knowledge_ids"] = filterList
}
if singleQuery != "" {
data["query"] = singleQuery
}
if len(vectorQueries) > 0 {
data["vector_queries"] = vectorQueries
}
if len(keywordQueries) > 0 {
data["keyword_queries"] = keywordQueries
if len(queries) > 0 {
data["queries"] = queries
}
if totalBeforeFilter > len(results) {
data["total_before_filter"] = totalBeforeFilter
@@ -0,0 +1,230 @@
package tools
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// ListKnowledgeChunksTool retrieves chunk snapshots for a specific knowledge document.
type ListKnowledgeChunksTool struct {
BaseTool
tenantID uint
chunkService interfaces.ChunkService
knowledgeService interfaces.KnowledgeService
}
// NewListKnowledgeChunksTool creates a new tool instance.
func NewListKnowledgeChunksTool(
tenantID uint,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
) *ListKnowledgeChunksTool {
description := `Retrieve paged chunks for a document (knowledge) by knowledge_id.
## When to Use
- Need deterministic chunk previews for a known document
- Want to quickly confirm how many chunks a document contains
- Require surrounding context around a chunk_index returned by search results
- Need content snippets without running an additional search query
Avoid when:
- You don't know the knowledge_id (use knowledge_search first)
## Parameters
- knowledge_id (required): Target document/knowledge ID
- limit (optional): Number of chunks to fetch (default 20, max 100).
- offset (optional): Offset to start fetching chunks from (default 0).`
return &ListKnowledgeChunksTool{
BaseTool: NewBaseTool("list_knowledge_chunks", description),
tenantID: tenantID,
chunkService: chunkService,
knowledgeService: knowledgeService,
}
}
// Parameters returns the JSON schema describing accepted arguments.
func (t *ListKnowledgeChunksTool) Parameters() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"knowledge_id": map[string]interface{}{
"type": "string",
"description": "Knowledge/document ID to inspect",
},
"limit": map[string]interface{}{
"type": "integer",
"description": "Number of chunks to fetch (default 20, max 100)",
"default": 20,
"minimum": 1,
"maximum": 100,
},
"offset": map[string]interface{}{
"type": "integer",
"description": "Offset to start fetching chunks from (default 0)",
"default": 0,
"minimum": 0,
},
},
"required": []string{"knowledge_id", "limit", "offset"},
}
}
// Execute performs the chunk fetch against the chunk service.
func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
knowledgeID, ok := args["knowledge_id"].(string)
if !ok || strings.TrimSpace(knowledgeID) == "" {
return &types.ToolResult{
Success: false,
Error: "knowledge_id is required",
}, fmt.Errorf("knowledge_id is required")
}
knowledgeID = strings.TrimSpace(knowledgeID)
chunkLimit := 20
offset := 0
if rawLimit, exists := args["limit"]; exists {
switch v := rawLimit.(type) {
case float64:
chunkLimit = int(v)
case int:
chunkLimit = v
}
}
if rawOffset, exists := args["offset"]; exists {
switch v := rawOffset.(type) {
case float64:
offset = int(v)
case int:
offset = v
}
}
if offset < 0 {
offset = 0
}
pagination := &types.Pagination{
Page: offset/chunkLimit + 1,
PageSize: chunkLimit,
}
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
t.tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText}, "")
if err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("failed to list chunks: %v", err),
}, err
}
if chunks == nil {
return &types.ToolResult{
Success: false,
Error: "chunk query returned no data",
}, fmt.Errorf("chunk query returned no data")
}
totalChunks := total
fetched := len(chunks)
knowledgeTitle := t.lookupKnowledgeTitle(ctx, knowledgeID)
output := t.buildOutput(knowledgeID, knowledgeTitle, totalChunks, fetched, chunkLimit, chunks)
formattedChunks := make([]map[string]interface{}, 0, len(chunks))
for idx, c := range chunks {
formattedChunks = append(formattedChunks, map[string]interface{}{
"seq": idx + 1,
"chunk_id": c.ID,
"chunk_index": c.ChunkIndex,
"content": c.Content,
"chunk_type": c.ChunkType,
"knowledge_id": c.KnowledgeID,
"knowledge_base": c.KnowledgeBaseID,
"start_at": c.StartAt,
"end_at": c.EndAt,
"parent_chunk_id": c.ParentChunkID,
})
}
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"knowledge_id": knowledgeID,
"knowledge_title": knowledgeTitle,
"total_chunks": totalChunks,
"fetched_chunks": fetched,
"page": pagination.Page,
"page_size": pagination.PageSize,
"chunks": formattedChunks,
},
}, nil
}
func (t *ListKnowledgeChunksTool) lookupKnowledgeTitle(ctx context.Context, knowledgeID string) string {
if t.knowledgeService == nil {
return ""
}
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
if err != nil || knowledge == nil {
return ""
}
return strings.TrimSpace(knowledge.Title)
}
func (t *ListKnowledgeChunksTool) buildOutput(
knowledgeID string,
knowledgeTitle string,
total int64,
fetched int,
chunkLimit int,
chunks []*types.Chunk,
) string {
builder := &strings.Builder{}
builder.WriteString("=== 知识文档分块 ===\n\n")
if knowledgeTitle != "" {
builder.WriteString(fmt.Sprintf("文档: %s (%s)\n", knowledgeTitle, knowledgeID))
} else {
builder.WriteString(fmt.Sprintf("文档 ID: %s\n", knowledgeID))
}
builder.WriteString(fmt.Sprintf("总分块数: %d\n", total))
builder.WriteString(fmt.Sprintf("本次拉取: %d 条(offset=%d)\n\n", fetched, chunkLimit))
if fetched == 0 {
builder.WriteString("未找到任何分块,请确认文档是否已完成解析。\n")
if total > 0 {
builder.WriteString("文档存在但当前页数据为空,请检查分页参数。\n")
}
return builder.String()
}
builder.WriteString("=== 分块内容预览 ===\n\n")
for idx, c := range chunks {
builder.WriteString(fmt.Sprintf("Chunk #%d (Index %d)\n", idx+1, c.ChunkIndex+1))
builder.WriteString(fmt.Sprintf(" chunk_id: %s\n", c.ID))
builder.WriteString(fmt.Sprintf(" 类型: %s\n", c.ChunkType))
builder.WriteString(fmt.Sprintf(" 内容: %s\n\n", summarizeContent(c.Content)))
}
if int64(fetched) < total {
builder.WriteString("提示:文档仍有更多分块,可调整 offset 或多次调用以获取全部内容。\n")
}
return builder.String()
}
func summarizeContent(content string) string {
cleaned := strings.TrimSpace(content)
if cleaned == "" {
return "(空内容)"
}
return strings.TrimSpace(string(cleaned))
}
@@ -56,7 +56,7 @@ func NewQueryKnowledgeGraphTool(knowledgeService interfaces.KnowledgeBaseService
## 配合使用
1. **关系探索**: query_knowledge_graph → get_chunk_detail(查看详细内容)
2. **网络分析**: query_knowledge_graph → get_related_chunks(扩展上下文)
2. **网络分析**: query_knowledge_graph → list_knowledge_chunks(扩展上下文)
3. **主题研究**: knowledge_search → query_knowledge_graph(深入实体关系)
## 当前状态
@@ -360,7 +360,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
output += "=== 💡 使用提示 ===\n"
output += "- ✓ 结果已跨知识库去重并按相关度排序\n"
output += "- ✓ 使用 get_chunk_detail 获取完整内容\n"
output += "- ✓ 使用 get_related_chunks 探索上下文\n"
output += "- ✓ 使用 list_knowledge_chunks 探索上下文\n"
if !hasGraphConfig {
output += "- ⚠️ 配置图谱抽取以获得更精准的实体关系结果\n"
}
+38 -12
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
@@ -11,26 +12,23 @@ import (
// ToolRegistry manages the registration and retrieval of tools
type ToolRegistry struct {
tools map[string]types.Tool
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
db *gorm.DB // gorm.DB interface for database query tool
tools map[string]types.Tool
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
db *gorm.DB
}
// NewToolRegistry creates a new tool registry
func NewToolRegistry(
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
db *gorm.DB, // gorm.DB for database operations
) *ToolRegistry {
return &ToolRegistry{
tools: make(map[string]types.Tool),
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
chunkService: chunkService,
db: db,
tools: make(map[string]types.Tool),
knowledgeService: knowledgeService,
chunkService: chunkService,
db: db,
}
}
@@ -72,13 +70,41 @@ func (r *ToolRegistry) GetFunctionDefinitions() []types.FunctionDefinition {
// ExecuteTool executes a tool by name with the given arguments
func (r *ToolRegistry) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (*types.ToolResult, error) {
common.PipelineInfo(ctx, "AgentTool", "execute_start", map[string]interface{}{
"tool": name,
"args": args,
})
tool, err := r.GetTool(name)
if err != nil {
common.PipelineError(ctx, "AgentTool", "execute_failed", map[string]interface{}{
"tool": name,
"error": err.Error(),
})
return &types.ToolResult{
Success: false,
Error: err.Error(),
}, err
}
return tool.Execute(ctx, args)
result, execErr := tool.Execute(ctx, args)
fields := map[string]interface{}{
"tool": name,
"args": args,
}
if result != nil {
fields["success"] = result.Success
if result.Error != "" {
fields["error"] = result.Error
}
}
if execErr != nil {
fields["error"] = execErr.Error()
common.PipelineError(ctx, "AgentTool", "execute_done", fields)
} else if result != nil && !result.Success {
common.PipelineWarn(ctx, "AgentTool", "execute_done", fields)
} else {
common.PipelineInfo(ctx, "AgentTool", "execute_done", fields)
}
return result, execErr
}
+10 -2
View File
@@ -121,7 +121,7 @@ func (t *SequentialThinkingTool) Parameters() map[string]interface{} {
"totalThoughts": map[string]interface{}{
"type": "integer",
"description": "Estimated total thoughts needed (numeric value, e.g., 5, 10)",
"minimum": 1,
"minimum": 5,
},
"isRevision": map[string]interface{}{
"type": "boolean",
@@ -188,6 +188,8 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
branchKeys = append(branchKeys, k)
}
incomplete := thoughtData.NextThoughtNeeded || thoughtData.NeedsMoreThoughts || thoughtData.ThoughtNumber < thoughtData.TotalThoughts
responseData := map[string]interface{}{
"thought_number": thoughtData.ThoughtNumber,
"total_thoughts": thoughtData.TotalThoughts,
@@ -196,13 +198,19 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
"thought_history_length": len(t.thoughtHistory),
"display_type": "thinking",
"thought": thoughtData.Thought,
"incomplete_steps": incomplete,
}
logger.Infof(ctx, "[Tool][SequentialThinking] Execute completed - Thought %d/%d", thoughtData.ThoughtNumber, thoughtData.TotalThoughts)
outputMsg := "Thought process recorded"
if incomplete {
outputMsg = "Thought process recorded - unfinished steps remain, continue exploring and calling tools"
}
return &types.ToolResult{
Success: true,
Output: "Thought process recorded",
Output: outputMsg,
Data: responseData,
}, nil
}
+3 -3
View File
@@ -171,7 +171,7 @@ func (t *TodoWriteTool) Parameters() map[string]interface{} {
},
"tools_to_use": map[string]interface{}{
"type": "array",
"description": "Suggested tools for this step (e.g., ['knowledge_search', 'get_related_chunks'])",
"description": "Suggested tools for this step (e.g., ['knowledge_search', 'list_knowledge_chunks'])",
"items": map[string]interface{}{
"type": "string",
},
@@ -268,8 +268,8 @@ func generatePlanOutput(task string, steps []PlanStep) string {
output += "注意:未提供具体步骤。建议创建3-7个结构化步骤以系统化研究。\n\n"
output += "建议的通用流程:\n"
output += "1. 使用 knowledge_search 进行初步信息收集\n"
output += "2. 使用 get_related_chunks 获取关键信息详情\n"
output += "3. 使用 get_related_chunks 扩展上下文理解\n"
output += "2. 使用 list_knowledge_chunks 获取关键信息详情\n"
output += "3. 使用 list_knowledge_chunks 扩展上下文理解\n"
output += "4. 使用 think 工具评估结果并综合答案\n"
return output
}