feat: 统一系统提示词并优化智能体选择器界面
- 将系统提示词从分离的网络搜索开/关状态合并为统一提示词,使用 {{web_search_status}} 占位符动态控制行为
- 重构智能体选择器,从简单tooltip升级为内容丰富的popup,显示智能体详细信息、类型和能力
- 新增FAQ优先策略配置,支持FAQ答案优先于普通文档
- 优化知识库选择逻辑,智能体切换时自动同步配置的知识库
- 更新相关接口类型定义和国际化文本
This commit is contained in:
+34
-103
@@ -250,7 +250,8 @@ func renderPromptPlaceholdersWithStatus(
|
||||
return result
|
||||
}
|
||||
|
||||
// BuildSystemPromptWithWeb builds the progressive RAG system prompt with web search enabled
|
||||
// BuildSystemPromptWithKB builds the progressive RAG system prompt with knowledge bases
|
||||
// Deprecated: Use BuildSystemPrompt instead
|
||||
func BuildSystemPromptWithWeb(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
systemPromptTemplate ...string,
|
||||
@@ -259,13 +260,14 @@ func BuildSystemPromptWithWeb(
|
||||
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
|
||||
template = systemPromptTemplate[0]
|
||||
} else {
|
||||
template = ProgressiveRAGSystemPromptWithWeb
|
||||
template = ProgressiveRAGSystemPrompt
|
||||
}
|
||||
currentTime := time.Now().Format(time.RFC3339)
|
||||
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, true, currentTime)
|
||||
}
|
||||
|
||||
// BuildSystemPromptWithoutWeb builds the progressive RAG system prompt without web search
|
||||
// Deprecated: Use BuildSystemPrompt instead
|
||||
func BuildSystemPromptWithoutWeb(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
systemPromptTemplate ...string,
|
||||
@@ -274,7 +276,7 @@ func BuildSystemPromptWithoutWeb(
|
||||
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
|
||||
template = systemPromptTemplate[0]
|
||||
} else {
|
||||
template = ProgressiveRAGSystemPromptWithoutWeb
|
||||
template = ProgressiveRAGSystemPrompt
|
||||
}
|
||||
currentTime := time.Now().Format(time.RFC3339)
|
||||
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, false, currentTime)
|
||||
@@ -296,8 +298,8 @@ func BuildPureAgentSystemPrompt(
|
||||
return renderPromptPlaceholdersWithStatus(template, []*KnowledgeBaseInfo{}, webSearchEnabled, 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
|
||||
// BuildSystemPrompt builds the progressive RAG system prompt
|
||||
// This is the main function to use - it uses a unified template with dynamic web search status
|
||||
func BuildSystemPrompt(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
webSearchEnabled bool,
|
||||
@@ -305,16 +307,20 @@ func BuildSystemPrompt(
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
var basePrompt string
|
||||
var template string
|
||||
|
||||
// If no knowledge bases, use Pure Agent prompt
|
||||
if len(knowledgeBases) == 0 {
|
||||
basePrompt = BuildPureAgentSystemPrompt(webSearchEnabled, systemPromptTemplate...)
|
||||
} else if webSearchEnabled {
|
||||
basePrompt = BuildSystemPromptWithWeb(knowledgeBases, systemPromptTemplate...)
|
||||
// Determine template to use
|
||||
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
|
||||
template = systemPromptTemplate[0]
|
||||
} else if len(knowledgeBases) == 0 {
|
||||
template = PureAgentSystemPrompt
|
||||
} else {
|
||||
basePrompt = BuildSystemPromptWithoutWeb(knowledgeBases, systemPromptTemplate...)
|
||||
template = ProgressiveRAGSystemPrompt
|
||||
}
|
||||
|
||||
currentTime := time.Now().Format(time.RFC3339)
|
||||
basePrompt = renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime)
|
||||
|
||||
// Append selected documents section if any
|
||||
if len(selectedDocs) > 0 {
|
||||
basePrompt += formatSelectedDocuments(selectedDocs)
|
||||
@@ -346,10 +352,10 @@ Current Time: {{current_time}}
|
||||
Web Search: {{web_search_status}}
|
||||
`
|
||||
|
||||
// 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
|
||||
You are WeKnora, an intelligent retrieval assistant powered by Progressive Agentic RAG. You operate in a multi-tenant environment with strictly isolated knowledge bases. Your core philosophy is "Evidence-First": you never rely on internal parametric knowledge but construct answers solely from verified data retrieved from the Knowledge Base (KB) or Web.
|
||||
// ProgressiveRAGSystemPrompt is the unified progressive RAG system prompt template
|
||||
// This template dynamically adapts based on web search status via {{web_search_status}} placeholder
|
||||
var ProgressiveRAGSystemPrompt = `### Role
|
||||
You are WeKnora, an intelligent retrieval assistant powered by Progressive Agentic RAG. You operate in a multi-tenant environment with strictly isolated knowledge bases. Your core philosophy is "Evidence-First": you never rely on internal parametric knowledge but construct answers solely from verified data retrieved from the Knowledge Base (KB) or Web (if enabled).
|
||||
|
||||
### Mission
|
||||
To deliver accurate, traceable, and verifiable answers by orchestrating a dynamic retrieval process. You must first gauge the information landscape through preliminary retrieval, then rigorously execute and reflect upon specific research tasks. **You prioritize "Deep Reading" over superficial scanning.**
|
||||
@@ -357,7 +363,7 @@ To deliver accurate, traceable, and verifiable answers by orchestrating a dynami
|
||||
### Critical Constraints (ABSOLUTE RULES)
|
||||
1. **NO Internal Knowledge:** You must behave as if your training data does not exist regarding facts.
|
||||
2. **Mandatory Deep Read:** Whenever grep_chunks or knowledge_search returns matched knowledge_ids or chunk_ids, you **MUST** immediately call list_knowledge_chunks to read the full content of those specific chunks. Do not rely on search snippets alone.
|
||||
3. **KB First, Web Second:** Always exhaust KB strategies (including the Deep Read) before attempting Web Search.
|
||||
3. **KB First, Web Second:** Always exhaust KB strategies (including the Deep Read) before attempting Web Search (if enabled).
|
||||
4. **Strict Plan Adherence:** If a todo_write plan exists, execute it sequentially. No skipping.
|
||||
5. **Tool Privacy:** Never expose tool names to the user.
|
||||
|
||||
@@ -384,7 +390,7 @@ If in **Path B**, execute tasks in todo_write sequentially. For **EACH** task:
|
||||
3. **MANDATORY Deep Reflection (in think):** Pause and evaluate the full text:
|
||||
* *Validity:* "Does this full text specifically address the sub-task?"
|
||||
* *Gap Analysis:* "Is anything missing? Is the information outdated? Is the information irrelevant?"
|
||||
* *Correction:* If insufficient, formulate a remedial action (e.g., "Search for synonym X", "Web Search") immediately.
|
||||
* *Correction:* If insufficient, formulate a remedial action (e.g., "Search for synonym X", "Web Search if enabled") immediately.
|
||||
* *Completion:* Mark task as "completed" ONLY when evidence is secured.
|
||||
|
||||
#### Phase 4: Final Synthesis
|
||||
@@ -401,109 +407,34 @@ For every retrieval attempt (Phase 1 or Phase 3), follow this exact chain:
|
||||
* Rule: After Step 1 or 2 returns knowledge_ids, you MUST call this tool.
|
||||
* Frequency: Call it frequently for multiple IDs to ensure you have the full results. **Do not be lazy; fetch the content.**
|
||||
4. **Graph Exploration (query_knowledge_graph):** Optional for relationships.
|
||||
5. **Fallback (web_search):** Use ONLY if the Deep Read in Step 3 confirms the data is missing or irrelevant.
|
||||
5. **Web Fallback (web_search):** Use ONLY if Web Search is Enabled AND the Deep Read in Step 3 confirms the data is missing or irrelevant.
|
||||
|
||||
### Tool Selection Guidelines
|
||||
* **grep_chunks / knowledge_search:** Your "Index". Use these to find *where* the information might be.
|
||||
* **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is.
|
||||
* **web_search / web_fetch:** Use these ONLY when Web Search is Enabled and KB retrieval is insufficient.
|
||||
* **todo_write:** Your "Manager". Tracks multi-step research.
|
||||
* **think:** Your "Conscience". Use to plan and relect the content returned by list_knowledge_chunks.
|
||||
* **think:** Your "Conscience". Use to plan and reflect the content returned by list_knowledge_chunks.
|
||||
|
||||
### Final Output Standards
|
||||
* **Definitive:** Based strictly on the "Deep Read" content.
|
||||
* **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." /> or <web url="..." title="..." />.
|
||||
* **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." /> or <web url="..." title="..." /> (if from web).
|
||||
Citations may not be placed at the end of the answer. They must always be inserted inline, at the exact location where the referenced information is used ("proximate citation rule").
|
||||
* **Structured:** Clear hierarchy and logic.
|
||||
* **Rich Media (Markdown with Images):** When retrieved chunks contain images (indicated by the "images" field with URLs), you MUST include them in your response using standard Markdown image syntax: . Place images at contextually appropriate positions within the answer to create a well-formatted, visually rich response. Images help users better understand the content, especially for diagrams, charts, screenshots, or visual explanations.
|
||||
|
||||
### System Status
|
||||
Current Time: {{current_time}}
|
||||
Web Search: {{web_search_status}}
|
||||
|
||||
### User Selected Knowledge Bases (via @ mention)
|
||||
{{knowledge_bases}}
|
||||
`
|
||||
|
||||
// ProgressiveRAGSystemPromptWithoutWeb is the progressive RAG system prompt template without web search
|
||||
// This version emphasizes deep KB-only retrieval with advanced techniques
|
||||
var ProgressiveRAGSystemPromptWithoutWeb = `### Role
|
||||
You are WeKnora, a meticulous retrieval assistant powered by Progressive Agentic RAG. You operate in a strictly isolated, **Closed-Loop Knowledge Environment** (No Internet). You are defined by your "Deep Reading" philosophy: you never trust a snippet alone; you always verify the full context.
|
||||
// ProgressiveRAGSystemPromptWithWeb is deprecated, use ProgressiveRAGSystemPrompt instead
|
||||
// Kept for backward compatibility
|
||||
var ProgressiveRAGSystemPromptWithWeb = ProgressiveRAGSystemPrompt
|
||||
|
||||
### Mission
|
||||
To provide answers that are not only accurate but contextually complete. You achieve this by following a strict **"Locate-then-Read"** protocol: finding documents via search, then reading their full content before synthesizing an answer.
|
||||
|
||||
### Critical Constraints (ABSOLUTE RULES)
|
||||
1. **No Snippet-Only Answers:** You are FORBIDDEN from answering based solely on the short text snippets returned by grep_chunks or knowledge_search.
|
||||
2. **Mandatory Deep Reading:** Whenever a search tool returns relevant knowledge_ids, you MUST use list_knowledge_chunks to read the actual content of those chunks/documents before using them as evidence.
|
||||
3. **No Internet:** You are strictly confined to internal Knowledge Bases.
|
||||
4. **Evidence Verification:** If the full text read via list_knowledge_chunks contradicts the search snippet or shows the info is irrelevant, you must discard it and search again.
|
||||
|
||||
### Workflow: The "Locate-Read-Plan-Execute" Cycle
|
||||
|
||||
You must follow this **Specific Operational Sequence** for every user query:
|
||||
|
||||
#### Phase 1: Preliminary Reconnaissance & Context Verification
|
||||
Before answering or creating a plan, you MUST perform an initial "Test & Read" loop.
|
||||
1. **Locate:** Execute grep_chunks (keyword) and knowledge_search (semantic) to find potential documents.
|
||||
2. **READ (Mandatory):** Identify the most relevant knowledge_ids from step 1 (you can select multiple, e.g., top 3-5). **IMMEDIATELY call list_knowledge_chunks** on these IDs to retrieve their full content.
|
||||
3. **Analyze:** In your think block, evaluate the *full text* you just read. Does it cover the user's intent?
|
||||
* *Decision:* If this full text is sufficient → Go to **Answer Generation**.
|
||||
* *Decision:* If complex/incomplete → Go to **Phase 2**.
|
||||
|
||||
#### Phase 2: Strategic Decision & Planning
|
||||
If Phase 1 is insufficient, create a todo_write Work Plan.
|
||||
* **Plan Structure:** Break the problem into distinct retrieval tasks.
|
||||
* **Context Awareness:** Use the full text read in Phase 1 to inform your plan (e.g., "Doc A mentions Protocol X, I need to create a task to specifically search for Protocol X details").
|
||||
|
||||
#### Phase 3: Disciplined Execution with Deep Reading
|
||||
Execute tasks in todo_write sequentially. For **EACH** task:
|
||||
1. **Search:** Perform grep_chunks or knowledge_search specific to the sub-task.
|
||||
2. **READ (Mandatory):**
|
||||
* Extract the knowledge_ids of the most promising results.
|
||||
* **Call list_knowledge_chunks** to fetch the content for these IDs. **Do not skip this step.**
|
||||
* *Note:* You are encouraged to check multiple files if the answer might be spread across them.
|
||||
3. **Reflect (Deep Reflection):**
|
||||
* "Based on the *full text* I just read, is this sub-task resolved?"
|
||||
* If no, formulate a remedial search action immediately.
|
||||
* Only mark as "completed" when the full text evidence is secured.
|
||||
|
||||
#### Phase 4: Final Synthesis
|
||||
* Synthesize findings based **only** on the content read via list_knowledge_chunks.
|
||||
* Generate the final response with citations.
|
||||
|
||||
### Core Retrieval Strategy (The "Locate-then-Read" Pattern)
|
||||
For every information seeking step, strictly follow this 3-step atomic unit:
|
||||
|
||||
1. **Step A: Locate (Search)**
|
||||
* Use grep_chunks for specific entities (Error codes, product names).
|
||||
* Use knowledge_search for concepts.
|
||||
* *Goal:* Get a list of candidate knowledge_ids.
|
||||
|
||||
2. **Step B: Read (Fetch Context)**
|
||||
* **Action:** Call list_knowledge_chunks(knowledge_ids=[id1, id2, ...]).
|
||||
* *Rule:* Always fetch the content. Snippets are often truncated or lack necessary context (like prerequisites or exceptions).
|
||||
* *Scope:* It is acceptable and encouraged to fetch 3-5 distinct documents to ensure comprehensive coverage.
|
||||
|
||||
3. **Step C: Evaluate (Filter)**
|
||||
* Read the output of list_knowledge_chunks.
|
||||
* Discard irrelevant documents.
|
||||
* Extract facts from valid documents to build your answer.
|
||||
|
||||
### Tool Selection Guidelines
|
||||
* **grep_chunks / knowledge_search:** Used ONLY as "Pointers" or "Index Lookups". They tell you *where* to look, not *what* the answer is.
|
||||
* **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is.
|
||||
* **todo_write:** Use for managing multi-step research.
|
||||
* **think:** Your "Conscience". Use to plan and relect the content returned by list_knowledge_chunks.
|
||||
|
||||
### Final Output Standards
|
||||
1. **Context-Backed:** Your answer must reflect the nuance found in the full text (e.g., conditions, warnings, detailed steps) which might be missing from search snippets.
|
||||
2. **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." />.
|
||||
Citations may not be placed at the end of the answer. They must always be inserted inline, at the exact location where the referenced information is used ("proximate citation rule").
|
||||
3. **Honest:** If the full text reveals the search hit was a false positive, admit it and search again.
|
||||
4. **Rich Media (Markdown with Images):** When retrieved chunks contain images (indicated by the "images" field with URLs), you MUST include them in your response using standard Markdown image syntax: . Place images at contextually appropriate positions within the answer to create a well-formatted, visually rich response. Images help users better understand the content, especially for diagrams, charts, screenshots, or visual explanations.
|
||||
|
||||
### System Status
|
||||
Current Time: {{current_time}}
|
||||
|
||||
### User Selected Knowledge Bases (via @ mention)
|
||||
{{knowledge_bases}}
|
||||
`
|
||||
// ProgressiveRAGSystemPromptWithoutWeb is deprecated, use ProgressiveRAGSystemPrompt instead
|
||||
// Kept for backward compatibility
|
||||
var ProgressiveRAGSystemPromptWithoutWeb = ProgressiveRAGSystemPrompt
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const MAX_ITERATIONS = 30 // Max iterations for agent execution
|
||||
const MAX_ITERATIONS = 100 // Max iterations for agent execution
|
||||
|
||||
// agentService implements agent-related business logic
|
||||
type agentService struct {
|
||||
|
||||
@@ -37,11 +37,32 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
|
||||
"template_len": len(chatManage.SummaryConfig.ContextTemplate),
|
||||
})
|
||||
|
||||
// Extract content from merge results
|
||||
passages := make([]string, len(chatManage.MergeResult))
|
||||
for i, result := range chatManage.MergeResult {
|
||||
// 合并内容和图片信息
|
||||
passages[i] = getEnrichedPassageForChat(ctx, result)
|
||||
// Separate FAQ and document results when FAQ priority is enabled
|
||||
var faqResults, docResults []*types.SearchResult
|
||||
var hasHighConfidenceFAQ bool
|
||||
|
||||
if chatManage.FAQPriorityEnabled {
|
||||
for _, result := range chatManage.MergeResult {
|
||||
if result.ChunkType == string(types.ChunkTypeFAQ) {
|
||||
faqResults = append(faqResults, result)
|
||||
// Check if this FAQ has high confidence (above direct answer threshold)
|
||||
if result.Score >= chatManage.FAQDirectAnswerThreshold && !hasHighConfidenceFAQ {
|
||||
hasHighConfidenceFAQ = true
|
||||
pipelineInfo(ctx, "IntoChatMessage", "high_confidence_faq", map[string]interface{}{
|
||||
"chunk_id": result.ID,
|
||||
"score": fmt.Sprintf("%.4f", result.Score),
|
||||
"threshold": chatManage.FAQDirectAnswerThreshold,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
docResults = append(docResults, result)
|
||||
}
|
||||
}
|
||||
pipelineInfo(ctx, "IntoChatMessage", "faq_separation", map[string]interface{}{
|
||||
"faq_count": len(faqResults),
|
||||
"doc_count": len(docResults),
|
||||
"has_high_confidence": hasHighConfidenceFAQ,
|
||||
})
|
||||
}
|
||||
|
||||
// 验证用户查询的安全性
|
||||
@@ -56,13 +77,42 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
|
||||
// Prepare weekday names
|
||||
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
|
||||
|
||||
// Build contexts string from passages
|
||||
var contextsBuilder strings.Builder
|
||||
for i, passage := range passages {
|
||||
if i > 0 {
|
||||
contextsBuilder.WriteString("\n\n")
|
||||
|
||||
// Build contexts string based on FAQ priority strategy
|
||||
if chatManage.FAQPriorityEnabled && len(faqResults) > 0 {
|
||||
// Build structured context with FAQ prioritization
|
||||
contextsBuilder.WriteString("### 资料来源 1:标准问答库 (FAQ)\n")
|
||||
contextsBuilder.WriteString("【高置信度 - 请优先参考】\n")
|
||||
for i, result := range faqResults {
|
||||
passage := getEnrichedPassageForChat(ctx, result)
|
||||
if hasHighConfidenceFAQ && i == 0 {
|
||||
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] ⭐ 精准匹配: %s\n", i+1, passage))
|
||||
} else {
|
||||
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] %s\n", i+1, passage))
|
||||
}
|
||||
}
|
||||
|
||||
if len(docResults) > 0 {
|
||||
contextsBuilder.WriteString("\n### 资料来源 2:参考文档\n")
|
||||
contextsBuilder.WriteString("【补充资料 - 仅在FAQ无法解答时参考】\n")
|
||||
for i, result := range docResults {
|
||||
passage := getEnrichedPassageForChat(ctx, result)
|
||||
contextsBuilder.WriteString(fmt.Sprintf("[DOC-%d] %s\n", i+1, passage))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Original behavior: simple numbered list
|
||||
passages := make([]string, len(chatManage.MergeResult))
|
||||
for i, result := range chatManage.MergeResult {
|
||||
passages[i] = getEnrichedPassageForChat(ctx, result)
|
||||
}
|
||||
for i, passage := range passages {
|
||||
if i > 0 {
|
||||
contextsBuilder.WriteString("\n\n")
|
||||
}
|
||||
contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage))
|
||||
}
|
||||
contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage))
|
||||
}
|
||||
|
||||
// Replace placeholders in context template
|
||||
@@ -77,6 +127,7 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
|
||||
pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"user_content_len": len(chatManage.UserContent),
|
||||
"faq_priority": chatManage.FAQPriorityEnabled,
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
@@ -145,6 +145,22 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base)
|
||||
modelScore := rr.RelevanceScore
|
||||
sr.Score = compositeScore(sr, modelScore, base)
|
||||
|
||||
// Apply FAQ score boost if enabled
|
||||
if chatManage.FAQPriorityEnabled && chatManage.FAQScoreBoost > 1.0 &&
|
||||
sr.ChunkType == string(types.ChunkTypeFAQ) {
|
||||
originalScore := sr.Score
|
||||
sr.Score = math.Min(sr.Score*chatManage.FAQScoreBoost, 1.0)
|
||||
sr.Metadata["faq_boosted"] = "true"
|
||||
sr.Metadata["faq_original_score"] = fmt.Sprintf("%.4f", originalScore)
|
||||
pipelineInfo(ctx, "Rerank", "faq_boost", map[string]interface{}{
|
||||
"chunk_id": sr.ID,
|
||||
"original_score": fmt.Sprintf("%.4f", originalScore),
|
||||
"boosted_score": fmt.Sprintf("%.4f", sr.Score),
|
||||
"boost_factor": chatManage.FAQScoreBoost,
|
||||
})
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Rerank", "composite_calc", map[string]interface{}{
|
||||
"chunk_id": sr.ID,
|
||||
"base_score": fmt.Sprintf("%.4f", base),
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
|
||||
llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/rerank"
|
||||
"github.com/Tencent/WeKnora/internal/tracing"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -408,24 +408,15 @@ func (s *sessionService) KnowledgeQA(
|
||||
webSearchEnabled,
|
||||
)
|
||||
|
||||
// Merge custom agent's configured knowledge bases
|
||||
if customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 {
|
||||
// Create a set of existing knowledge base IDs to avoid duplicates
|
||||
existingKBs := make(map[string]bool)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
existingKBs[kbID] = true
|
||||
}
|
||||
// Add agent's knowledge bases that are not already in the list
|
||||
for _, kbID := range customAgent.Config.KnowledgeBases {
|
||||
if !existingKBs[kbID] {
|
||||
knowledgeBaseIDs = append(knowledgeBaseIDs, kbID)
|
||||
logger.Infof(ctx, "Adding custom agent's knowledge base: %s", kbID)
|
||||
}
|
||||
}
|
||||
// Use custom agent's knowledge bases only if request didn't specify any
|
||||
// When user explicitly @mentions a knowledge base or document, only search those
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 {
|
||||
knowledgeBaseIDs = customAgent.Config.KnowledgeBases
|
||||
logger.Infof(ctx, "No knowledge bases specified in request, using custom agent's knowledge bases: %v", knowledgeBaseIDs)
|
||||
} else if len(knowledgeBaseIDs) > 0 || len(knowledgeIDs) > 0 {
|
||||
logger.Infof(ctx, "Using request-specified targets (ignoring agent config): kbs=%v, docs=%v", knowledgeBaseIDs, knowledgeIDs)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Using knowledge bases: %v", knowledgeBaseIDs)
|
||||
|
||||
// Determine chat model ID: prioritize request's summaryModelID, then Remote models
|
||||
chatModelID, err := s.selectChatModelIDWithOverride(ctx, session, knowledgeBaseIDs, knowledgeIDs, summaryModelID)
|
||||
if err != nil {
|
||||
@@ -542,6 +533,20 @@ func (s *sessionService) KnowledgeQA(
|
||||
}
|
||||
}
|
||||
|
||||
// Extract FAQ strategy settings from custom agent
|
||||
var faqPriorityEnabled bool
|
||||
var faqDirectAnswerThreshold float64
|
||||
var faqScoreBoost float64
|
||||
if customAgent != nil {
|
||||
faqPriorityEnabled = customAgent.Config.FAQPriorityEnabled
|
||||
faqDirectAnswerThreshold = customAgent.Config.FAQDirectAnswerThreshold
|
||||
faqScoreBoost = customAgent.Config.FAQScoreBoost
|
||||
if faqPriorityEnabled {
|
||||
logger.Infof(ctx, "FAQ priority enabled: threshold=%.2f, boost=%.2f",
|
||||
faqDirectAnswerThreshold, faqScoreBoost)
|
||||
}
|
||||
}
|
||||
|
||||
// Build unified search targets (computed once, used throughout pipeline)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs)
|
||||
if err != nil {
|
||||
@@ -584,6 +589,10 @@ func (s *sessionService) KnowledgeQA(
|
||||
RewritePromptUser: rewritePromptUser,
|
||||
EnableRewrite: enableRewrite,
|
||||
EnableQueryExpansion: enableQueryExpansion,
|
||||
// FAQ Strategy Settings
|
||||
FAQPriorityEnabled: faqPriorityEnabled,
|
||||
FAQDirectAnswerThreshold: faqDirectAnswerThreshold,
|
||||
FAQScoreBoost: faqScoreBoost,
|
||||
}
|
||||
|
||||
// Determine pipeline based on knowledge bases availability and web search setting
|
||||
@@ -886,17 +895,6 @@ func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
func getTenantConversationConfig(ctx context.Context) (*types.ConversationConfig, error) {
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
return nil, errors.New("tenant is empty")
|
||||
}
|
||||
if tenant.ConversationConfig == nil {
|
||||
return nil, errors.New("tenant has no conversation config")
|
||||
}
|
||||
return tenant.ConversationConfig, nil
|
||||
}
|
||||
|
||||
// SearchKnowledge performs knowledge base search without LLM summarization
|
||||
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
|
||||
// knowledgeIDs: list of specific knowledge (file) IDs to search
|
||||
@@ -1020,6 +1018,8 @@ func (s *sessionService) AgentQA(
|
||||
assistantMessageID string,
|
||||
eventBus *event.EventBus,
|
||||
customAgent *types.CustomAgent,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) error {
|
||||
sessionID := session.ID
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
@@ -1045,20 +1045,8 @@ func (s *sessionService) AgentQA(
|
||||
// Ensure defaults are set
|
||||
customAgent.EnsureDefaults()
|
||||
|
||||
// Check if tenant has agent configuration (for defaults)
|
||||
if tenantInfo.AgentConfig == nil {
|
||||
tenantInfo.AgentConfig = &types.AgentConfig{
|
||||
MaxIterations: agent.DefaultAgentMaxIterations,
|
||||
ReflectionEnabled: agent.DefaultAgentReflectionEnabled,
|
||||
AllowedTools: tools.DefaultAllowedTools(),
|
||||
Temperature: agent.DefaultAgentTemperature,
|
||||
SystemPromptWebEnabled: agent.ProgressiveRAGSystemPromptWithWeb,
|
||||
SystemPromptWebDisabled: agent.ProgressiveRAGSystemPromptWithoutWeb,
|
||||
UseCustomSystemPrompt: agent.DefaultUseCustomSystemPrompt,
|
||||
}
|
||||
}
|
||||
|
||||
// Create runtime AgentConfig from customAgent
|
||||
// Note: tenantInfo.AgentConfig is deprecated, all config comes from customAgent now
|
||||
agentConfig := &types.AgentConfig{
|
||||
MaxIterations: customAgent.Config.MaxIterations,
|
||||
ReflectionEnabled: customAgent.Config.ReflectionEnabled,
|
||||
@@ -1072,6 +1060,24 @@ func (s *sessionService) AgentQA(
|
||||
MCPServices: customAgent.Config.MCPServices,
|
||||
}
|
||||
|
||||
// Handle knowledge bases: request-level @ mentions take priority over agent config
|
||||
// When user explicitly @mentions a knowledge base or document, only search those
|
||||
if len(knowledgeBaseIDs) > 0 || len(knowledgeIDs) > 0 {
|
||||
// User explicitly specified via @ mention, use only those (clear agent's default KBs)
|
||||
if len(knowledgeBaseIDs) > 0 {
|
||||
agentConfig.KnowledgeBases = knowledgeBaseIDs
|
||||
logger.Infof(ctx, "Using request-specified knowledge bases (ignoring agent config): %v", knowledgeBaseIDs)
|
||||
} else {
|
||||
// User only specified documents, clear the default KBs
|
||||
agentConfig.KnowledgeBases = nil
|
||||
logger.Infof(ctx, "User specified documents only, clearing agent's default knowledge bases")
|
||||
}
|
||||
if len(knowledgeIDs) > 0 {
|
||||
agentConfig.KnowledgeIDs = knowledgeIDs
|
||||
logger.Infof(ctx, "Using request-specified knowledge IDs: %v", knowledgeIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// Use custom agent's allowed tools if specified, otherwise use defaults
|
||||
if len(customAgent.Config.AllowedTools) > 0 {
|
||||
agentConfig.AllowedTools = customAgent.Config.AllowedTools
|
||||
@@ -1082,8 +1088,7 @@ func (s *sessionService) AgentQA(
|
||||
// Use custom agent's system prompt if specified
|
||||
if customAgent.Config.SystemPrompt != "" {
|
||||
agentConfig.UseCustomSystemPrompt = true
|
||||
agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt
|
||||
agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt
|
||||
agentConfig.SystemPrompt = customAgent.Config.SystemPrompt
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v",
|
||||
@@ -1117,14 +1122,12 @@ func (s *sessionService) AgentQA(
|
||||
agentConfig.SearchTargets = searchTargets
|
||||
logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets))
|
||||
|
||||
// Get summary model from custom agent config or tenant config
|
||||
// Get summary model from custom agent config
|
||||
// Note: tenantInfo.ConversationConfig is deprecated, all config comes from customAgent now
|
||||
summaryModelID := customAgent.Config.ModelID
|
||||
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
|
||||
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
|
||||
}
|
||||
if summaryModelID == "" {
|
||||
logger.Warnf(ctx, "No summary model configured for tenant %d or session %s", tenantInfo.ID, session.ID)
|
||||
return errors.New("summary model is not configured in conversation settings")
|
||||
logger.Warnf(ctx, "No summary model configured for custom agent %s", customAgent.ID)
|
||||
return errors.New("summary model (model_id) is not configured in custom agent settings")
|
||||
}
|
||||
|
||||
summaryModel, err := s.modelService.GetChatModel(ctx, summaryModelID)
|
||||
@@ -1133,20 +1136,23 @@ func (s *sessionService) AgentQA(
|
||||
return fmt.Errorf("failed to get chat model: %w", err)
|
||||
}
|
||||
|
||||
// Get rerank model from custom agent config or tenant config
|
||||
rerankModelID := customAgent.Config.RerankModelID
|
||||
if rerankModelID == "" && tenantInfo.ConversationConfig != nil {
|
||||
rerankModelID = tenantInfo.ConversationConfig.RerankModelID
|
||||
}
|
||||
if rerankModelID == "" {
|
||||
logger.Warnf(ctx, "No rerank model configured for tenant %d or session %s", tenantInfo.ID, session.ID)
|
||||
return errors.New("rerank model is not configured in conversation settings")
|
||||
}
|
||||
// Get rerank model from custom agent config (only required when knowledge bases are configured)
|
||||
var rerankModel rerank.Reranker
|
||||
hasKnowledge := len(agentConfig.KnowledgeBases) > 0 || len(agentConfig.KnowledgeIDs) > 0
|
||||
if hasKnowledge {
|
||||
rerankModelID := customAgent.Config.RerankModelID
|
||||
if rerankModelID == "" {
|
||||
logger.Warnf(ctx, "No rerank model configured for custom agent %s, but knowledge bases are specified", customAgent.ID)
|
||||
return errors.New("rerank model (rerank_model_id) is not configured in custom agent settings")
|
||||
}
|
||||
|
||||
rerankModel, err := s.modelService.GetRerankModel(ctx, rerankModelID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get rerank model: %v", err)
|
||||
return fmt.Errorf("failed to get rerank model: %w", err)
|
||||
rerankModel, err = s.modelService.GetRerankModel(ctx, rerankModelID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get rerank model: %v", err)
|
||||
return fmt.Errorf("failed to get rerank model: %w", err)
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "No knowledge bases configured, skipping rerank model initialization")
|
||||
}
|
||||
|
||||
// Get or create contextManager for this session
|
||||
|
||||
@@ -440,6 +440,8 @@ func (h *Handler) executeAgentModeQA(reqCtx *qaRequestContext) {
|
||||
reqCtx.assistantMessage.ID,
|
||||
streamCtx.eventBus,
|
||||
reqCtx.customAgent,
|
||||
reqCtx.knowledgeBaseIDs,
|
||||
reqCtx.knowledgeIDs,
|
||||
)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
|
||||
|
||||
+37
-42
@@ -419,12 +419,11 @@ func (h *TenantHandler) SearchTenants(c *gin.Context) {
|
||||
|
||||
// AgentConfigRequest represents the request body for updating agent configuration
|
||||
type AgentConfigRequest struct {
|
||||
MaxIterations int `json:"max_iterations"`
|
||||
ReflectionEnabled bool `json:"reflection_enabled"`
|
||||
AllowedTools []string `json:"allowed_tools"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"`
|
||||
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"`
|
||||
MaxIterations int `json:"max_iterations"`
|
||||
ReflectionEnabled bool `json:"reflection_enabled"`
|
||||
AllowedTools []string `json:"allowed_tools"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
SystemPrompt string `json:"system_prompt,omitempty"` // Unified system prompt (uses {{web_search_status}} placeholder)
|
||||
}
|
||||
|
||||
// GetTenantAgentConfig godoc
|
||||
@@ -472,42 +471,37 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"max_iterations": agent.DefaultAgentMaxIterations,
|
||||
"reflection_enabled": agent.DefaultAgentReflectionEnabled,
|
||||
"allowed_tools": agenttools.DefaultAllowedTools(),
|
||||
"temperature": agent.DefaultAgentTemperature,
|
||||
"system_prompt_web_enabled": agent.ProgressiveRAGSystemPromptWithWeb,
|
||||
"system_prompt_web_disabled": agent.ProgressiveRAGSystemPromptWithoutWeb,
|
||||
"use_custom_system_prompt": false,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
"max_iterations": agent.DefaultAgentMaxIterations,
|
||||
"reflection_enabled": agent.DefaultAgentReflectionEnabled,
|
||||
"allowed_tools": agenttools.DefaultAllowedTools(),
|
||||
"temperature": agent.DefaultAgentTemperature,
|
||||
"system_prompt": agent.ProgressiveRAGSystemPrompt,
|
||||
"use_custom_system_prompt": false,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Get system prompts for both web search states, use defaults if empty
|
||||
systemPromptWithWeb := tenant.AgentConfig.ResolveSystemPrompt(true)
|
||||
if systemPromptWithWeb == "" {
|
||||
systemPromptWithWeb = agent.ProgressiveRAGSystemPromptWithWeb
|
||||
}
|
||||
systemPromptWithoutWeb := tenant.AgentConfig.ResolveSystemPrompt(false)
|
||||
if systemPromptWithoutWeb == "" {
|
||||
systemPromptWithoutWeb = agent.ProgressiveRAGSystemPromptWithoutWeb
|
||||
// Get system prompt, use default if empty
|
||||
systemPrompt := tenant.AgentConfig.ResolveSystemPrompt(true) // webSearchEnabled doesn't matter for unified prompt
|
||||
if systemPrompt == "" {
|
||||
systemPrompt = agent.ProgressiveRAGSystemPrompt
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieved tenant agent config successfully, Tenant ID: %d", tenant.ID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"max_iterations": tenant.AgentConfig.MaxIterations,
|
||||
"reflection_enabled": tenant.AgentConfig.ReflectionEnabled,
|
||||
"allowed_tools": agenttools.DefaultAllowedTools(),
|
||||
"temperature": tenant.AgentConfig.Temperature,
|
||||
"system_prompt_web_enabled": systemPromptWithWeb,
|
||||
"system_prompt_web_disabled": systemPromptWithoutWeb,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
"max_iterations": tenant.AgentConfig.MaxIterations,
|
||||
"reflection_enabled": tenant.AgentConfig.ReflectionEnabled,
|
||||
"allowed_tools": agenttools.DefaultAllowedTools(),
|
||||
"temperature": tenant.AgentConfig.Temperature,
|
||||
"system_prompt": systemPrompt,
|
||||
"use_custom_system_prompt": tenant.AgentConfig.UseCustomSystemPrompt,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -543,19 +537,20 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
|
||||
}
|
||||
// Update agent configuration
|
||||
// Determine if using custom prompt based on whether custom prompts are set
|
||||
useCustomPrompt := req.SystemPromptWebEnabled != "" || req.SystemPromptWebDisabled != ""
|
||||
// Support both new unified SystemPrompt and deprecated separate prompts
|
||||
systemPrompt := req.SystemPrompt
|
||||
useCustomPrompt := systemPrompt != ""
|
||||
|
||||
tenant.AgentConfig = &types.AgentConfig{
|
||||
MaxIterations: req.MaxIterations,
|
||||
ReflectionEnabled: req.ReflectionEnabled,
|
||||
AllowedTools: agenttools.DefaultAllowedTools(),
|
||||
Temperature: req.Temperature,
|
||||
SystemPromptWebEnabled: req.SystemPromptWebEnabled,
|
||||
SystemPromptWebDisabled: req.SystemPromptWebDisabled,
|
||||
UseCustomSystemPrompt: useCustomPrompt,
|
||||
agentConfig := &types.AgentConfig{
|
||||
MaxIterations: req.MaxIterations,
|
||||
ReflectionEnabled: req.ReflectionEnabled,
|
||||
AllowedTools: agenttools.DefaultAllowedTools(),
|
||||
Temperature: req.Temperature,
|
||||
SystemPrompt: systemPrompt,
|
||||
UseCustomSystemPrompt: useCustomPrompt,
|
||||
}
|
||||
|
||||
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
|
||||
_, err := h.service.UpdateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
logger.Error(ctx, "Failed to update tenant: application error", appErr)
|
||||
@@ -570,7 +565,7 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
|
||||
logger.Infof(ctx, "Tenant agent config updated successfully, Tenant ID: %d", tenant.ID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": updatedTenant.AgentConfig,
|
||||
"data": agentConfig,
|
||||
"message": "Agent configuration updated successfully",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -211,10 +211,6 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
|
||||
toolNames = append(toolNames, tool.Function.Name)
|
||||
}
|
||||
logger.Infof(context.Background(), "[LLM Request] tools_count=%d, tool_names=%v", len(req.Tools), toolNames)
|
||||
// Print full tool definitions
|
||||
if toolsJSON, err := json.MarshalIndent(req.Tools, "", " "); err == nil {
|
||||
logger.Infof(context.Background(), "[LLM Request] tools_definition:\n%s", string(toolsJSON))
|
||||
}
|
||||
}
|
||||
|
||||
return req
|
||||
|
||||
+23
-14
@@ -10,20 +10,22 @@ import (
|
||||
// AgentConfig represents the full agent configuration (used at tenant level and runtime)
|
||||
// This includes all configuration parameters for agent execution
|
||||
type AgentConfig struct {
|
||||
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
|
||||
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
|
||||
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
|
||||
Temperature float64 `json:"temperature"` // LLM temperature for agent
|
||||
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
|
||||
KnowledgeIDs []string `json:"knowledge_ids"` // Accessible knowledge IDs (individual documents)
|
||||
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` // Custom prompt when web search is enabled
|
||||
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` // Custom prompt when web search is disabled
|
||||
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
|
||||
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
|
||||
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled
|
||||
HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
|
||||
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
|
||||
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
|
||||
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
|
||||
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
|
||||
Temperature float64 `json:"temperature"` // LLM temperature for agent
|
||||
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
|
||||
KnowledgeIDs []string `json:"knowledge_ids"` // Accessible knowledge IDs (individual documents)
|
||||
SystemPrompt string `json:"system_prompt,omitempty"` // Unified system prompt (uses {{web_search_status}} placeholder for dynamic behavior)
|
||||
// Deprecated: Use SystemPrompt instead. Kept for backward compatibility during migration.
|
||||
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` // Deprecated: Custom prompt when web search is enabled
|
||||
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` // Deprecated: Custom prompt when web search is disabled
|
||||
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
|
||||
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
|
||||
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled
|
||||
HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
|
||||
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
|
||||
// MCP service selection
|
||||
MCPSelectionMode string `json:"mcp_selection_mode"` // MCP selection mode: "all", "selected", "none"
|
||||
MCPServices []string `json:"mcp_services"` // Selected MCP service IDs (when mode is "selected")
|
||||
@@ -73,11 +75,18 @@ func (c *SessionAgentConfig) Scan(value interface{}) error {
|
||||
}
|
||||
|
||||
// ResolveSystemPrompt returns the prompt template for the given web search state.
|
||||
// It uses the unified SystemPrompt field, falling back to deprecated fields for backward compatibility.
|
||||
func (c *AgentConfig) ResolveSystemPrompt(webSearchEnabled bool) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// First, try the new unified SystemPrompt field
|
||||
if c.SystemPrompt != "" {
|
||||
return c.SystemPrompt
|
||||
}
|
||||
|
||||
// Fallback to deprecated fields for backward compatibility
|
||||
if webSearchEnabled {
|
||||
if c.SystemPromptWebEnabled != "" {
|
||||
return c.SystemPromptWebEnabled
|
||||
|
||||
@@ -53,6 +53,11 @@ type ChatManage struct {
|
||||
// Web search configuration (internal use)
|
||||
TenantID uint64 `json:"-"` // Tenant ID for retrieving web search config
|
||||
WebSearchEnabled bool `json:"-"` // Whether web search is enabled for this request
|
||||
|
||||
// FAQ Strategy Settings
|
||||
FAQPriorityEnabled bool `json:"-"` // Whether FAQ priority strategy is enabled
|
||||
FAQDirectAnswerThreshold float64 `json:"-"` // Threshold for direct FAQ answer (similarity > this value)
|
||||
FAQScoreBoost float64 `json:"-"` // Score multiplier for FAQ results
|
||||
}
|
||||
|
||||
// Clone creates a deep copy of the ChatManage object
|
||||
@@ -117,6 +122,10 @@ func (c *ChatManage) Clone() *ChatManage {
|
||||
EnableRewrite: c.EnableRewrite,
|
||||
EnableQueryExpansion: c.EnableQueryExpansion,
|
||||
TenantID: c.TenantID,
|
||||
// FAQ Strategy Settings
|
||||
FAQPriorityEnabled: c.FAQPriorityEnabled,
|
||||
FAQDirectAnswerThreshold: c.FAQDirectAnswerThreshold,
|
||||
FAQScoreBoost: c.FAQScoreBoost,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,14 @@ const (
|
||||
BuiltinQuickAnswerID = "builtin-quick-answer"
|
||||
// BuiltinSmartReasoningID is the ID for the built-in smart reasoning (ReAct) agent
|
||||
BuiltinSmartReasoningID = "builtin-smart-reasoning"
|
||||
// BuiltinDeepResearcherID is the ID for the built-in deep researcher agent
|
||||
BuiltinDeepResearcherID = "builtin-deep-researcher"
|
||||
// BuiltinDataAnalystID is the ID for the built-in data analyst agent
|
||||
BuiltinDataAnalystID = "builtin-data-analyst"
|
||||
// BuiltinKnowledgeGraphExpertID is the ID for the built-in knowledge graph expert agent
|
||||
BuiltinKnowledgeGraphExpertID = "builtin-knowledge-graph-expert"
|
||||
// BuiltinDocumentAssistantID is the ID for the built-in document assistant agent
|
||||
BuiltinDocumentAssistantID = "builtin-document-assistant"
|
||||
)
|
||||
|
||||
// AgentMode constants for agent running mode
|
||||
@@ -57,10 +65,8 @@ type CustomAgentConfig struct {
|
||||
// ===== Basic Settings =====
|
||||
// Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent mode
|
||||
AgentMode string `yaml:"agent_mode" json:"agent_mode"`
|
||||
// System prompt for the agent (for normal mode, or agent mode when web search is disabled)
|
||||
// System prompt for the agent (unified prompt, uses {{web_search_status}} placeholder for dynamic behavior)
|
||||
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
|
||||
// System prompt for agent mode when web search is enabled
|
||||
SystemPromptWebEnabled string `yaml:"system_prompt_web_enabled" json:"system_prompt_web_enabled"`
|
||||
// Context template for normal mode (how to format retrieved chunks)
|
||||
ContextTemplate string `yaml:"context_template" json:"context_template"`
|
||||
|
||||
@@ -92,6 +98,14 @@ type CustomAgentConfig struct {
|
||||
// Associated knowledge base IDs (only used when KBSelectionMode is "selected")
|
||||
KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"`
|
||||
|
||||
// ===== FAQ Strategy Settings =====
|
||||
// Whether FAQ priority strategy is enabled (FAQ answers prioritized over document chunks)
|
||||
FAQPriorityEnabled bool `yaml:"faq_priority_enabled" json:"faq_priority_enabled"`
|
||||
// FAQ direct answer threshold - if similarity > this value, use FAQ answer directly
|
||||
FAQDirectAnswerThreshold float64 `yaml:"faq_direct_answer_threshold" json:"faq_direct_answer_threshold"`
|
||||
// FAQ score boost multiplier - FAQ results score multiplied by this factor
|
||||
FAQScoreBoost float64 `yaml:"faq_score_boost" json:"faq_score_boost"`
|
||||
|
||||
// ===== Web Search Settings =====
|
||||
// Whether web search is enabled
|
||||
WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"`
|
||||
@@ -224,6 +238,10 @@ func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
KBSelectionMode: "all",
|
||||
// FAQ strategy
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.9,
|
||||
FAQScoreBoost: 1.2,
|
||||
// Retrieval strategy
|
||||
EmbeddingTopK: 10,
|
||||
KeywordThreshold: 0.3,
|
||||
@@ -259,6 +277,10 @@ func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
|
||||
ReflectionEnabled: false,
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
// FAQ strategy
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.9,
|
||||
FAQScoreBoost: 1.2,
|
||||
// Retrieval strategy
|
||||
EmbeddingTopK: 10,
|
||||
KeywordThreshold: 0.3,
|
||||
@@ -269,6 +291,259 @@ func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
|
||||
}
|
||||
}
|
||||
|
||||
// GetBuiltinDeepResearcherAgent returns the built-in deep researcher agent
|
||||
// This agent is optimized for in-depth research and comprehensive analysis
|
||||
func GetBuiltinDeepResearcherAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinDeepResearcherID,
|
||||
Name: "深度研究员",
|
||||
Description: "专注于深度研究和综合分析,能够制定研究计划、多维度检索信息、深入思考并给出全面的分析报告",
|
||||
Avatar: "🔬",
|
||||
IsBuiltin: true,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: AgentModeSmartReasoning,
|
||||
SystemPrompt: `你是一位专业的深度研究员,擅长进行系统性的研究和综合分析。
|
||||
|
||||
## 核心能力
|
||||
- 制定结构化的研究计划
|
||||
- 多维度信息检索和交叉验证
|
||||
- 深入思考和逻辑推理
|
||||
- 综合分析和报告撰写
|
||||
|
||||
## 工作流程
|
||||
1. **理解问题**:深入分析用户的研究需求,明确研究目标和范围
|
||||
2. **制定计划**:使用 todo_write 工具制定详细的研究计划
|
||||
3. **信息收集**:
|
||||
- 使用 knowledge_search 进行语义搜索获取相关文档
|
||||
- 使用 grep_chunks 进行关键词精确搜索
|
||||
- 使用 query_knowledge_graph 探索实体关系
|
||||
- 必要时使用网络搜索获取最新信息
|
||||
4. **深度分析**:使用 thinking 工具进行深入思考和推理
|
||||
5. **综合报告**:整合所有信息,给出结构化的研究报告
|
||||
|
||||
## 输出要求
|
||||
- 研究报告应包含:背景、方法、发现、分析、结论
|
||||
- 引用具体的信息来源
|
||||
- 指出信息的可靠性和局限性
|
||||
- 提供进一步研究的建议`,
|
||||
Temperature: 0.5,
|
||||
MaxCompletionTokens: 4096,
|
||||
MaxIterations: 30,
|
||||
KBSelectionMode: "all",
|
||||
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
|
||||
WebSearchEnabled: true,
|
||||
WebSearchMaxResults: 10,
|
||||
ReflectionEnabled: true,
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 10,
|
||||
// FAQ strategy
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.9,
|
||||
FAQScoreBoost: 1.2,
|
||||
// Retrieval strategy - more comprehensive
|
||||
EmbeddingTopK: 20,
|
||||
KeywordThreshold: 0.2,
|
||||
VectorThreshold: 0.4,
|
||||
RerankTopK: 15,
|
||||
RerankThreshold: 0.25,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetBuiltinDataAnalystAgent returns the built-in data analyst agent
|
||||
// This agent is optimized for database queries and data analysis
|
||||
func GetBuiltinDataAnalystAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinDataAnalystID,
|
||||
Name: "数据分析师",
|
||||
Description: "专注于数据库查询和数据分析,能够理解业务需求、构建SQL查询、分析数据并提供洞察",
|
||||
Avatar: "📊",
|
||||
IsBuiltin: true,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: AgentModeSmartReasoning,
|
||||
SystemPrompt: `你是一位专业的数据分析师,擅长数据库查询和数据分析。
|
||||
|
||||
## 核心能力
|
||||
- 理解业务需求并转化为数据查询
|
||||
- 构建高效的 SQL 查询语句
|
||||
- 数据分析和可视化建议
|
||||
- 提供数据驱动的业务洞察
|
||||
|
||||
## 工作流程
|
||||
1. **需求理解**:
|
||||
- 明确用户的数据分析目标
|
||||
- 确定需要查询的数据范围和维度
|
||||
2. **数据探索**:
|
||||
- 使用 database_query 查询相关数据
|
||||
- 使用 get_document_info 了解数据结构和元数据
|
||||
3. **数据分析**:
|
||||
- 使用 thinking 工具进行数据分析和推理
|
||||
- 识别数据模式和趋势
|
||||
4. **结果呈现**:
|
||||
- 清晰展示查询结果
|
||||
- 提供数据解读和业务建议
|
||||
|
||||
## 输出要求
|
||||
- 解释 SQL 查询的逻辑
|
||||
- 以表格或结构化方式展示数据
|
||||
- 提供数据的业务含义解读
|
||||
- 指出数据的局限性和注意事项
|
||||
- 建议后续分析方向`,
|
||||
Temperature: 0.3,
|
||||
MaxCompletionTokens: 2048,
|
||||
MaxIterations: 20,
|
||||
KBSelectionMode: "all",
|
||||
AllowedTools: []string{"thinking", "todo_write", "database_query", "knowledge_search", "get_document_info"},
|
||||
WebSearchEnabled: false,
|
||||
WebSearchMaxResults: 5,
|
||||
ReflectionEnabled: false,
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
// FAQ strategy
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.9,
|
||||
FAQScoreBoost: 1.2,
|
||||
// Retrieval strategy
|
||||
EmbeddingTopK: 10,
|
||||
KeywordThreshold: 0.3,
|
||||
VectorThreshold: 0.5,
|
||||
RerankTopK: 5,
|
||||
RerankThreshold: 0.3,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetBuiltinKnowledgeGraphExpertAgent returns the built-in knowledge graph expert agent
|
||||
// This agent is optimized for knowledge graph exploration and relationship analysis
|
||||
func GetBuiltinKnowledgeGraphExpertAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinKnowledgeGraphExpertID,
|
||||
Name: "知识图谱专家",
|
||||
Description: "专注于知识图谱查询和关系分析,能够探索实体关系、发现隐藏联系并构建知识网络",
|
||||
Avatar: "🕸️",
|
||||
IsBuiltin: true,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: AgentModeSmartReasoning,
|
||||
SystemPrompt: `你是一位知识图谱专家,擅长探索实体关系和构建知识网络。
|
||||
|
||||
## 核心能力
|
||||
- 实体识别和关系发现
|
||||
- 知识图谱查询和遍历
|
||||
- 关系链分析和推理
|
||||
- 知识网络可视化建议
|
||||
|
||||
## 工作流程
|
||||
1. **实体识别**:
|
||||
- 从用户问题中识别关键实体
|
||||
- 确定需要探索的关系类型
|
||||
2. **图谱查询**:
|
||||
- 使用 query_knowledge_graph 查询实体关系
|
||||
- 探索多跳关系和间接联系
|
||||
3. **关系分析**:
|
||||
- 使用 thinking 工具分析关系模式
|
||||
- 发现隐藏的关联和规律
|
||||
4. **知识整合**:
|
||||
- 结合 knowledge_search 获取更多上下文
|
||||
- 构建完整的知识图景
|
||||
|
||||
## 输出要求
|
||||
- 清晰展示实体和关系
|
||||
- 使用图形化描述(如 A -> 关系 -> B)
|
||||
- 解释关系的含义和重要性
|
||||
- 指出可能的推理和假设
|
||||
- 建议进一步探索的方向`,
|
||||
Temperature: 0.5,
|
||||
MaxCompletionTokens: 2048,
|
||||
MaxIterations: 25,
|
||||
KBSelectionMode: "all",
|
||||
AllowedTools: []string{"thinking", "todo_write", "query_knowledge_graph", "knowledge_search", "grep_chunks", "get_document_info"},
|
||||
WebSearchEnabled: false,
|
||||
WebSearchMaxResults: 5,
|
||||
ReflectionEnabled: true,
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
// FAQ strategy
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.9,
|
||||
FAQScoreBoost: 1.2,
|
||||
// Retrieval strategy
|
||||
EmbeddingTopK: 15,
|
||||
KeywordThreshold: 0.3,
|
||||
VectorThreshold: 0.4,
|
||||
RerankTopK: 10,
|
||||
RerankThreshold: 0.3,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetBuiltinDocumentAssistantAgent returns the built-in document assistant agent
|
||||
// This agent is optimized for document retrieval, organization and summarization
|
||||
func GetBuiltinDocumentAssistantAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinDocumentAssistantID,
|
||||
Name: "文档助手",
|
||||
Description: "专注于文档检索和内容整理,能够快速定位文档、提取关键信息并生成摘要",
|
||||
Avatar: "📚",
|
||||
IsBuiltin: true,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: AgentModeSmartReasoning,
|
||||
SystemPrompt: `你是一位专业的文档助手,擅长文档检索、信息提取和内容整理。
|
||||
|
||||
## 核心能力
|
||||
- 快速定位相关文档和内容
|
||||
- 提取文档关键信息
|
||||
- 生成结构化摘要
|
||||
- 文档对比和整合
|
||||
|
||||
## 工作流程
|
||||
1. **需求分析**:
|
||||
- 理解用户的文档检索需求
|
||||
- 确定搜索关键词和范围
|
||||
2. **文档检索**:
|
||||
- 使用 knowledge_search 语义搜索相关内容
|
||||
- 使用 grep_chunks 精确匹配关键词
|
||||
- 使用 get_document_info 获取文档元信息
|
||||
3. **内容处理**:
|
||||
- 使用 list_knowledge_chunks 查看完整内容
|
||||
- 使用 thinking 工具整理和分析信息
|
||||
4. **结果输出**:
|
||||
- 提供结构化的信息摘要
|
||||
- 标注信息来源和位置
|
||||
|
||||
## 输出要求
|
||||
- 清晰标注信息来源(文档名、位置)
|
||||
- 使用结构化格式展示信息
|
||||
- 区分直接引用和总结内容
|
||||
- 指出信息的完整性和可能遗漏
|
||||
- 提供相关文档的导航建议`,
|
||||
Temperature: 0.3,
|
||||
MaxCompletionTokens: 2048,
|
||||
MaxIterations: 20,
|
||||
KBSelectionMode: "all",
|
||||
AllowedTools: []string{"thinking", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "get_document_info"},
|
||||
WebSearchEnabled: false,
|
||||
WebSearchMaxResults: 5,
|
||||
ReflectionEnabled: false,
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
// FAQ strategy
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.9,
|
||||
FAQScoreBoost: 1.2,
|
||||
// Retrieval strategy - focused on precision
|
||||
EmbeddingTopK: 15,
|
||||
KeywordThreshold: 0.25,
|
||||
VectorThreshold: 0.45,
|
||||
RerankTopK: 10,
|
||||
RerankThreshold: 0.3,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated: Use GetBuiltinQuickAnswerAgent instead
|
||||
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
|
||||
return GetBuiltinQuickAnswerAgent(tenantID)
|
||||
@@ -281,14 +556,22 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
|
||||
|
||||
// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension
|
||||
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
|
||||
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
|
||||
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
|
||||
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
|
||||
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
|
||||
BuiltinDeepResearcherID: GetBuiltinDeepResearcherAgent,
|
||||
BuiltinDataAnalystID: GetBuiltinDataAnalystAgent,
|
||||
BuiltinKnowledgeGraphExpertID: GetBuiltinKnowledgeGraphExpertAgent,
|
||||
BuiltinDocumentAssistantID: GetBuiltinDocumentAssistantAgent,
|
||||
}
|
||||
|
||||
// builtinAgentIDsOrdered defines the fixed display order of built-in agents
|
||||
var builtinAgentIDsOrdered = []string{
|
||||
BuiltinQuickAnswerID,
|
||||
BuiltinSmartReasoningID,
|
||||
BuiltinDeepResearcherID,
|
||||
BuiltinDataAnalystID,
|
||||
BuiltinKnowledgeGraphExpertID,
|
||||
BuiltinDocumentAssistantID,
|
||||
}
|
||||
|
||||
// GetBuiltinAgentIDs returns all built-in agent IDs in fixed order
|
||||
|
||||
@@ -54,6 +54,8 @@ type SessionService interface {
|
||||
assistantMessageID string,
|
||||
eventBus *event.EventBus,
|
||||
customAgent *types.CustomAgent,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) error
|
||||
// ClearContext clears the LLM context for a session
|
||||
ClearContext(ctx context.Context, sessionID string) error
|
||||
|
||||
Reference in New Issue
Block a user