Merge branch 'custom_agent'
This commit is contained in:
+48
-119
@@ -4,6 +4,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// formatFileSize formats file size in human-readable format
|
||||
@@ -78,6 +80,7 @@ type KnowledgeBaseInfo struct {
|
||||
}
|
||||
|
||||
// PlaceholderDefinition defines a placeholder exposed to UI/configuration
|
||||
// Deprecated: Use types.PromptPlaceholder instead
|
||||
type PlaceholderDefinition struct {
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label"`
|
||||
@@ -85,24 +88,19 @@ type PlaceholderDefinition struct {
|
||||
}
|
||||
|
||||
// AvailablePlaceholders lists all supported prompt placeholders for UI hints
|
||||
// This returns agent mode specific placeholders
|
||||
func AvailablePlaceholders() []PlaceholderDefinition {
|
||||
return []PlaceholderDefinition{
|
||||
{
|
||||
Name: "knowledge_bases",
|
||||
Label: "知识库列表",
|
||||
Description: "自动格式化为表格形式的知识库列表,包含知识库名称、描述、文档数量、最近添加的文档等信息",
|
||||
},
|
||||
{
|
||||
Name: "web_search_status",
|
||||
Label: "网络检索模式开关状态",
|
||||
Description: "网络检索(web_search)工具是否启用的状态说明,值为 Enabled 或 Disabled",
|
||||
},
|
||||
{
|
||||
Name: "current_time",
|
||||
Label: "当前系统时间",
|
||||
Description: "格式为 RFC3339 的当前系统时间,用于帮助模型感知实时性",
|
||||
},
|
||||
// Use centralized placeholder definitions from types package
|
||||
placeholders := types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt)
|
||||
result := make([]PlaceholderDefinition, len(placeholders))
|
||||
for i, p := range placeholders {
|
||||
result[i] = PlaceholderDefinition{
|
||||
Name: p.Name,
|
||||
Label: p.Label,
|
||||
Description: p.Description,
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// formatKnowledgeBaseList formats knowledge base information for the prompt
|
||||
@@ -252,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,
|
||||
@@ -261,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,
|
||||
@@ -276,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)
|
||||
@@ -298,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,
|
||||
@@ -307,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)
|
||||
@@ -348,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.**
|
||||
@@ -359,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.
|
||||
|
||||
@@ -386,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
|
||||
@@ -403,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
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ErrCustomAgentNotFound is returned when a custom agent is not found
|
||||
var ErrCustomAgentNotFound = errors.New("custom agent not found")
|
||||
|
||||
// customAgentRepository implements the CustomAgentRepository interface
|
||||
type customAgentRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewCustomAgentRepository creates a new custom agent repository
|
||||
func NewCustomAgentRepository(db *gorm.DB) interfaces.CustomAgentRepository {
|
||||
return &customAgentRepository{db: db}
|
||||
}
|
||||
|
||||
// CreateAgent creates a new custom agent
|
||||
func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.CustomAgent) error {
|
||||
return r.db.WithContext(ctx).Create(agent).Error
|
||||
}
|
||||
|
||||
// GetAgentByID gets an agent by id and tenant
|
||||
func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) {
|
||||
var agent types.CustomAgent
|
||||
if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&agent).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrCustomAgentNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &agent, nil
|
||||
}
|
||||
|
||||
// ListAgentsByTenantID lists all agents for a specific tenant
|
||||
func (r *customAgentRepository) ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error) {
|
||||
var agents []*types.CustomAgent
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("created_at DESC").
|
||||
Find(&agents).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return agents, nil
|
||||
}
|
||||
|
||||
// UpdateAgent updates an agent
|
||||
func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.CustomAgent) error {
|
||||
return r.db.WithContext(ctx).Save(agent).Error
|
||||
}
|
||||
|
||||
// DeleteAgent deletes an agent (soft delete)
|
||||
func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string, tenantID uint64) error {
|
||||
return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.CustomAgent{}).Error
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -83,9 +83,8 @@ func (s *agentService) CreateAgentEngine(
|
||||
return nil, fmt.Errorf("chat model is nil after initialization")
|
||||
}
|
||||
|
||||
if rerankModel == nil {
|
||||
return nil, fmt.Errorf("rerank model is nil after initialization")
|
||||
}
|
||||
// Note: rerankModel can be nil when no knowledge bases are configured
|
||||
// The registerTools function will filter out knowledge-related tools in this case
|
||||
|
||||
// Create tool registry
|
||||
toolRegistry := tools.NewToolRegistry(s.knowledgeService, s.chunkService, s.db)
|
||||
@@ -101,25 +100,51 @@ func (s *agentService) CreateAgentEngine(
|
||||
tenantID = tid
|
||||
}
|
||||
if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil {
|
||||
// Get enabled MCP services for this tenant
|
||||
mcpServices, err := s.mcpServiceService.ListMCPServices(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
|
||||
// Check MCP selection mode from agent config
|
||||
mcpMode := config.MCPSelectionMode
|
||||
if mcpMode == "" {
|
||||
mcpMode = "all" // Default to all enabled MCP services
|
||||
}
|
||||
|
||||
// Skip MCP registration if mode is "none"
|
||||
if mcpMode == "none" {
|
||||
logger.Infof(ctx, "MCP services disabled by agent config (mode: none)")
|
||||
} else {
|
||||
// Filter enabled services
|
||||
enabledServices := make([]*types.MCPService, 0)
|
||||
for _, svc := range mcpServices {
|
||||
if svc != nil && svc.Enabled {
|
||||
enabledServices = append(enabledServices, svc)
|
||||
var mcpServices []*types.MCPService
|
||||
var err error
|
||||
|
||||
if mcpMode == "selected" && len(config.MCPServices) > 0 {
|
||||
// Get only selected MCP services
|
||||
mcpServices, err = s.mcpServiceService.ListMCPServicesByIDs(ctx, tenantID, config.MCPServices)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list selected MCP services: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Using %d selected MCP services from agent config", len(mcpServices))
|
||||
}
|
||||
} else {
|
||||
// Get all MCP services for this tenant
|
||||
mcpServices, err = s.mcpServiceService.ListMCPServices(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Register MCP tools
|
||||
if len(enabledServices) > 0 {
|
||||
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
|
||||
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
|
||||
if err == nil && len(mcpServices) > 0 {
|
||||
// Filter enabled services
|
||||
enabledServices := make([]*types.MCPService, 0)
|
||||
for _, svc := range mcpServices {
|
||||
if svc != nil && svc.Enabled {
|
||||
enabledServices = append(enabledServices, svc)
|
||||
}
|
||||
}
|
||||
|
||||
// Register MCP tools
|
||||
if len(enabledServices) > 0 {
|
||||
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
|
||||
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,8 +204,16 @@ func (s *agentService) registerTools(
|
||||
sessionID string,
|
||||
sessionService interfaces.SessionService,
|
||||
) error {
|
||||
// If no specific tools allowed, register default tools
|
||||
allowedTools := tools.DefaultAllowedTools()
|
||||
// Use config's allowed tools if specified, otherwise use defaults
|
||||
var allowedTools []string
|
||||
if len(config.AllowedTools) > 0 {
|
||||
allowedTools = make([]string, len(config.AllowedTools))
|
||||
copy(allowedTools, config.AllowedTools)
|
||||
logger.Infof(ctx, "Using custom allowed tools from config: %v", allowedTools)
|
||||
} else {
|
||||
allowedTools = tools.DefaultAllowedTools()
|
||||
logger.Infof(ctx, "Using default allowed tools: %v", allowedTools)
|
||||
}
|
||||
|
||||
// Filter out knowledge base tools if no knowledge bases or knowledge IDs are configured
|
||||
hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0
|
||||
@@ -206,7 +239,7 @@ func (s *agentService) registerTools(
|
||||
}
|
||||
}
|
||||
allowedTools = filteredTools
|
||||
logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools disabled due to empty configuration")
|
||||
logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools filtered out, remaining: %v", allowedTools)
|
||||
}
|
||||
|
||||
// If web search is enabled, add web_search to allowedTools
|
||||
|
||||
@@ -2,6 +2,8 @@ package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
@@ -51,17 +53,15 @@ func prepareChatModel(ctx context.Context, modelService interfaces.ModelService,
|
||||
|
||||
// prepareMessagesWithHistory prepare complete messages including history
|
||||
func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
|
||||
// Replace placeholders in system prompt
|
||||
systemPrompt := renderSystemPromptPlaceholders(chatManage.SummaryConfig.Prompt)
|
||||
|
||||
chatMessages := []chat.Message{
|
||||
{Role: "system", Content: chatManage.SummaryConfig.Prompt},
|
||||
{Role: "system", Content: systemPrompt},
|
||||
}
|
||||
|
||||
chatHistory := chatManage.History
|
||||
if len(chatHistory) > 2 {
|
||||
chatHistory = chatHistory[len(chatHistory)-2:]
|
||||
}
|
||||
|
||||
// Add conversation history
|
||||
for _, history := range chatHistory {
|
||||
// Add conversation history (already limited by maxRounds in load_history/rewrite plugins)
|
||||
for _, history := range chatManage.History {
|
||||
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query})
|
||||
chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer})
|
||||
}
|
||||
@@ -71,3 +71,18 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
|
||||
|
||||
return chatMessages
|
||||
}
|
||||
|
||||
// renderSystemPromptPlaceholders replaces placeholders in system prompt
|
||||
// Supported placeholders:
|
||||
// - {{current_time}} -> current time in RFC3339 format
|
||||
func renderSystemPromptPlaceholders(prompt string) string {
|
||||
result := prompt
|
||||
|
||||
// Replace {{current_time}} placeholder
|
||||
if strings.Contains(result, "{{current_time}}") {
|
||||
currentTime := time.Now().Format(time.RFC3339)
|
||||
result = strings.ReplaceAll(result, "{{current_time}}", currentTime)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// PluginIntoChatMessage handles the transformation of search results into chat messages
|
||||
@@ -38,47 +37,97 @@ 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
|
||||
|
||||
// Parse the context template
|
||||
tmpl, err := template.New("searchContent").Parse(chatManage.SummaryConfig.ContextTemplate)
|
||||
if err != nil {
|
||||
pipelineError(ctx, "IntoChatMessage", "parse_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
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,
|
||||
})
|
||||
return ErrTemplateParse.WithError(err)
|
||||
}
|
||||
|
||||
// Prepare weekday names for template
|
||||
// 验证用户查询的安全性
|
||||
safeQuery, isValid := utils.ValidateInput(chatManage.Query)
|
||||
if !isValid {
|
||||
pipelineWarn(ctx, "IntoChatMessage", "invalid_query", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
})
|
||||
return ErrTemplateExecute.WithError(fmt.Errorf("用户查询包含非法内容"))
|
||||
}
|
||||
|
||||
// Prepare weekday names
|
||||
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
|
||||
var userContent bytes.Buffer
|
||||
|
||||
// Execute template with context data
|
||||
err = tmpl.Execute(&userContent, map[string]interface{}{
|
||||
"Query": chatManage.Query, // User's original query
|
||||
"Contexts": passages, // Extracted passages from search results
|
||||
"CurrentTime": time.Now().Format("2006-01-02 15:04:05"), // Formatted current time
|
||||
"CurrentWeek": weekdayName[time.Now().Weekday()], // Current weekday in Chinese
|
||||
})
|
||||
if err != nil {
|
||||
pipelineError(ctx, "IntoChatMessage", "render_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return ErrTemplateExecute.WithError(err)
|
||||
var contextsBuilder strings.Builder
|
||||
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
|
||||
// Replace placeholders in context template
|
||||
userContent := chatManage.SummaryConfig.ContextTemplate
|
||||
userContent = strings.ReplaceAll(userContent, "{{query}}", safeQuery)
|
||||
userContent = strings.ReplaceAll(userContent, "{{contexts}}", contextsBuilder.String())
|
||||
userContent = strings.ReplaceAll(userContent, "{{current_time}}", time.Now().Format("2006-01-02 15:04:05"))
|
||||
userContent = strings.ReplaceAll(userContent, "{{current_week}}", weekdayName[time.Now().Weekday()])
|
||||
|
||||
// Set formatted content back to chat management
|
||||
chatManage.UserContent = userContent.String()
|
||||
chatManage.UserContent = userContent
|
||||
pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"user_content_len": len(chatManage.UserContent),
|
||||
"faq_priority": chatManage.FAQPriorityEnabled,
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// Package chatpipline provides chat pipeline processing capabilities
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// PluginLoadHistory is a plugin for loading conversation history without query rewriting
|
||||
// It loads historical dialog context for multi-turn conversations
|
||||
type PluginLoadHistory struct {
|
||||
messageService interfaces.MessageService // Message service for retrieving historical messages
|
||||
config *config.Config // System configuration
|
||||
}
|
||||
|
||||
// regThink is a regular expression used to match and remove content between <think></think> tags
|
||||
var regThink = regexp.MustCompile(`(?s)<think>.*?</think>`)
|
||||
|
||||
// NewPluginLoadHistory creates a new history loading plugin instance
|
||||
// Also registers the plugin with the event manager
|
||||
func NewPluginLoadHistory(eventManager *EventManager,
|
||||
messageService interfaces.MessageService,
|
||||
config *config.Config,
|
||||
) *PluginLoadHistory {
|
||||
res := &PluginLoadHistory{
|
||||
messageService: messageService,
|
||||
config: config,
|
||||
}
|
||||
eventManager.Register(res)
|
||||
return res
|
||||
}
|
||||
|
||||
// ActivationEvents returns the list of event types this plugin responds to
|
||||
// This plugin only responds to LOAD_HISTORY events
|
||||
func (p *PluginLoadHistory) ActivationEvents() []types.EventType {
|
||||
return []types.EventType{types.LOAD_HISTORY}
|
||||
}
|
||||
|
||||
// OnEvent processes triggered events
|
||||
// When receiving a LOAD_HISTORY event, it loads conversation history without rewriting the query
|
||||
func (p *PluginLoadHistory) OnEvent(ctx context.Context,
|
||||
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
|
||||
) *PluginError {
|
||||
// Determine max rounds from config or request
|
||||
maxRounds := p.config.Conversation.MaxRounds
|
||||
if chatManage.MaxRounds > 0 {
|
||||
maxRounds = chatManage.MaxRounds
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "LoadHistory", "input", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"max_rounds": maxRounds,
|
||||
})
|
||||
|
||||
// Get conversation history (fetch more to account for incomplete pairs)
|
||||
history, err := p.messageService.GetRecentMessagesBySession(ctx, chatManage.SessionID, maxRounds*2+10)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "LoadHistory", "history_fetch", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "LoadHistory", "fetched", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"message_count": len(history),
|
||||
})
|
||||
|
||||
// Convert historical messages to conversation history structure
|
||||
historyMap := make(map[string]*types.History)
|
||||
|
||||
// Process historical messages, grouped by requestID
|
||||
for _, message := range history {
|
||||
h, ok := historyMap[message.RequestID]
|
||||
if !ok {
|
||||
h = &types.History{}
|
||||
}
|
||||
if message.Role == "user" {
|
||||
// User message as query
|
||||
h.Query = message.Content
|
||||
h.CreateAt = message.CreatedAt
|
||||
} else {
|
||||
// System message as answer, while removing thinking process
|
||||
h.Answer = regThink.ReplaceAllString(message.Content, "")
|
||||
h.KnowledgeReferences = message.KnowledgeReferences
|
||||
}
|
||||
historyMap[message.RequestID] = h
|
||||
}
|
||||
|
||||
// Convert to list and filter incomplete conversations
|
||||
historyList := make([]*types.History, 0)
|
||||
for _, h := range historyMap {
|
||||
if h.Answer != "" && h.Query != "" {
|
||||
historyList = append(historyList, h)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by time, keep the most recent conversations
|
||||
sort.Slice(historyList, func(i, j int) bool {
|
||||
return historyList[i].CreateAt.After(historyList[j].CreateAt)
|
||||
})
|
||||
|
||||
// Limit the number of historical records
|
||||
if len(historyList) > maxRounds {
|
||||
historyList = historyList[:maxRounds]
|
||||
}
|
||||
|
||||
// Reverse to chronological order
|
||||
slices.Reverse(historyList)
|
||||
chatManage.History = historyList
|
||||
|
||||
pipelineInfo(ctx, "LoadHistory", "output", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"history_rounds": len(historyList),
|
||||
"max_rounds": maxRounds,
|
||||
})
|
||||
|
||||
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),
|
||||
|
||||
@@ -3,12 +3,11 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"html/template"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
@@ -144,54 +143,27 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
|
||||
if chatManage.RewritePromptUser != "" {
|
||||
userPrompt = chatManage.RewritePromptUser
|
||||
}
|
||||
userTmpl, err := template.New("rewriteContent").Parse(userPrompt)
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "parse_user_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
systemPrompt := p.config.Conversation.RewritePromptSystem
|
||||
if chatManage.RewritePromptSystem != "" {
|
||||
systemPrompt = chatManage.RewritePromptSystem
|
||||
}
|
||||
systemTmpl, err := template.New("rewriteContent").Parse(systemPrompt)
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "parse_system_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
// Format conversation history for template
|
||||
conversationText := formatConversationHistory(historyList)
|
||||
currentTime := time.Now().Format("2006-01-02 15:04:05")
|
||||
var userContent, systemContent bytes.Buffer
|
||||
err = userTmpl.Execute(&userContent, map[string]interface{}{
|
||||
"Query": chatManage.Query,
|
||||
"CurrentTime": currentTime,
|
||||
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
|
||||
"Conversation": historyList,
|
||||
})
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "render_user_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
err = systemTmpl.Execute(&systemContent, map[string]interface{}{
|
||||
"Query": chatManage.Query,
|
||||
"CurrentTime": currentTime,
|
||||
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
|
||||
"Conversation": historyList,
|
||||
})
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "render_system_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
|
||||
|
||||
// Replace placeholders in prompts
|
||||
userContent := strings.ReplaceAll(userPrompt, "{{conversation}}", conversationText)
|
||||
userContent = strings.ReplaceAll(userContent, "{{query}}", chatManage.Query)
|
||||
userContent = strings.ReplaceAll(userContent, "{{current_time}}", currentTime)
|
||||
userContent = strings.ReplaceAll(userContent, "{{yesterday}}", yesterday)
|
||||
|
||||
systemContent := strings.ReplaceAll(systemPrompt, "{{conversation}}", conversationText)
|
||||
systemContent = strings.ReplaceAll(systemContent, "{{query}}", chatManage.Query)
|
||||
systemContent = strings.ReplaceAll(systemContent, "{{current_time}}", currentTime)
|
||||
systemContent = strings.ReplaceAll(systemContent, "{{yesterday}}", yesterday)
|
||||
|
||||
rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "get_model", map[string]interface{}{
|
||||
@@ -207,11 +179,11 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
|
||||
response, err := rewriteModel.Chat(ctx, []chat.Message{
|
||||
{
|
||||
Role: "system",
|
||||
Content: systemContent.String(),
|
||||
Content: systemContent,
|
||||
},
|
||||
{
|
||||
Role: "user",
|
||||
Content: userContent.String(),
|
||||
Content: userContent,
|
||||
},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
@@ -236,3 +208,21 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
// formatConversationHistory formats conversation history for prompt template
|
||||
func formatConversationHistory(historyList []*types.History) string {
|
||||
if len(historyList) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
for _, h := range historyList {
|
||||
builder.WriteString("------BEGIN------\n")
|
||||
builder.WriteString("用户的问题是:")
|
||||
builder.WriteString(h.Query)
|
||||
builder.WriteString("\n助手的回答是:")
|
||||
builder.WriteString(h.Answer)
|
||||
builder.WriteString("\n------END------\n")
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Custom agent related errors
|
||||
var (
|
||||
ErrAgentNotFound = errors.New("agent not found")
|
||||
ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent basic info")
|
||||
ErrCannotDeleteBuiltin = errors.New("cannot delete built-in agent")
|
||||
ErrAgentNameRequired = errors.New("agent name is required")
|
||||
)
|
||||
|
||||
// customAgentService implements the CustomAgentService interface
|
||||
type customAgentService struct {
|
||||
repo interfaces.CustomAgentRepository
|
||||
}
|
||||
|
||||
// NewCustomAgentService creates a new custom agent service
|
||||
func NewCustomAgentService(repo interfaces.CustomAgentRepository) interfaces.CustomAgentService {
|
||||
return &customAgentService{
|
||||
repo: repo,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateAgent creates a new custom agent
|
||||
func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
|
||||
// Validate required fields
|
||||
if strings.TrimSpace(agent.Name) == "" {
|
||||
return nil, ErrAgentNameRequired
|
||||
}
|
||||
|
||||
// Generate UUID and set creation timestamps
|
||||
if agent.ID == "" {
|
||||
agent.ID = uuid.New().String()
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
agent.TenantID = tenantID
|
||||
|
||||
// Set timestamps
|
||||
agent.CreatedAt = time.Now()
|
||||
agent.UpdatedAt = time.Now()
|
||||
|
||||
// Ensure agent mode is set for user-created agents
|
||||
if agent.Config.AgentMode == "" {
|
||||
agent.Config.AgentMode = types.AgentModeQuickAnswer
|
||||
}
|
||||
|
||||
// Cannot create built-in agents
|
||||
agent.IsBuiltin = false
|
||||
|
||||
// Set defaults
|
||||
agent.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s",
|
||||
agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode)
|
||||
|
||||
if err := s.repo.CreateAgent(ctx, agent); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agent.ID,
|
||||
"tenant_id": agent.TenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s", agent.ID, agent.Name)
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
// GetAgentByID retrieves an agent by its ID (including built-in agents)
|
||||
func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) {
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
return nil, errors.New("agent ID cannot be empty")
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Check if it's a built-in agent using the registry
|
||||
if types.IsBuiltinAgentID(id) {
|
||||
// Try to get from database first (for customized config)
|
||||
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
|
||||
if err == nil {
|
||||
// Found in database, return with customized config
|
||||
return agent, nil
|
||||
}
|
||||
// Not in database, return default built-in agent from registry
|
||||
if builtinAgent := types.GetBuiltinAgent(id, tenantID); builtinAgent != nil {
|
||||
return builtinAgent, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Query from database
|
||||
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrCustomAgentNotFound) {
|
||||
return nil, ErrAgentNotFound
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
// ListAgents lists all agents for the current tenant (including built-in agents)
|
||||
func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAgent, error) {
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Get all agents from database (including built-in agents with customized config)
|
||||
allAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Track which built-in agents exist in database
|
||||
builtinInDB := make(map[string]bool)
|
||||
for _, agent := range allAgents {
|
||||
if types.IsBuiltinAgentID(agent.ID) {
|
||||
builtinInDB[agent.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Build result: built-in agents first, then custom agents
|
||||
builtinIDs := types.GetBuiltinAgentIDs()
|
||||
result := make([]*types.CustomAgent, 0, len(allAgents)+len(builtinIDs))
|
||||
|
||||
// Add built-in agents in order
|
||||
for _, builtinID := range builtinIDs {
|
||||
if builtinInDB[builtinID] {
|
||||
// Use customized config from database
|
||||
for _, agent := range allAgents {
|
||||
if agent.ID == builtinID {
|
||||
result = append(result, agent)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Use default built-in agent
|
||||
if agent := types.GetBuiltinAgent(builtinID, tenantID); agent != nil {
|
||||
result = append(result, agent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add custom agents
|
||||
for _, agent := range allAgents {
|
||||
if !types.IsBuiltinAgentID(agent.ID) {
|
||||
result = append(result, agent)
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// UpdateAgent updates an agent's information
|
||||
func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
|
||||
if agent.ID == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
return nil, errors.New("agent ID cannot be empty")
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Handle built-in agents specially using registry
|
||||
if types.IsBuiltinAgentID(agent.ID) {
|
||||
return s.updateBuiltinAgent(ctx, agent, tenantID)
|
||||
}
|
||||
|
||||
// Get existing agent
|
||||
existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrCustomAgentNotFound) {
|
||||
return nil, ErrAgentNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Cannot modify built-in status
|
||||
if existingAgent.IsBuiltin {
|
||||
return nil, ErrCannotModifyBuiltin
|
||||
}
|
||||
|
||||
// Validate name
|
||||
if strings.TrimSpace(agent.Name) == "" {
|
||||
return nil, ErrAgentNameRequired
|
||||
}
|
||||
|
||||
// Update fields
|
||||
existingAgent.Name = agent.Name
|
||||
existingAgent.Description = agent.Description
|
||||
existingAgent.Avatar = agent.Avatar
|
||||
existingAgent.Config = agent.Config
|
||||
existingAgent.UpdatedAt = time.Now()
|
||||
|
||||
// Ensure defaults
|
||||
existingAgent.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s", agent.ID, agent.Name)
|
||||
|
||||
if err := s.repo.UpdateAgent(ctx, existingAgent); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agent.ID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent updated successfully, ID: %s", agent.ID)
|
||||
return existingAgent, nil
|
||||
}
|
||||
|
||||
// updateBuiltinAgent updates a built-in agent's configuration (but not basic info)
|
||||
func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) {
|
||||
// Get the default built-in agent from registry
|
||||
defaultAgent := types.GetBuiltinAgent(agent.ID, tenantID)
|
||||
if defaultAgent == nil {
|
||||
return nil, ErrAgentNotFound
|
||||
}
|
||||
|
||||
// Try to get existing customized config from database
|
||||
existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID)
|
||||
if err != nil && !errors.Is(err, repository.ErrCustomAgentNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if existingAgent != nil {
|
||||
// Update existing record - only update config, keep basic info unchanged
|
||||
existingAgent.Config = agent.Config
|
||||
existingAgent.UpdatedAt = time.Now()
|
||||
existingAgent.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Updating built-in agent config, ID: %s", agent.ID)
|
||||
|
||||
if err := s.repo.UpdateAgent(ctx, existingAgent); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agent.ID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Built-in agent config updated successfully, ID: %s", agent.ID)
|
||||
return existingAgent, nil
|
||||
}
|
||||
|
||||
// Create new record for built-in agent with customized config
|
||||
newAgent := &types.CustomAgent{
|
||||
ID: defaultAgent.ID,
|
||||
Name: defaultAgent.Name,
|
||||
Description: defaultAgent.Description,
|
||||
Avatar: defaultAgent.Avatar,
|
||||
IsBuiltin: true,
|
||||
TenantID: tenantID,
|
||||
Config: agent.Config,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
newAgent.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Creating built-in agent config record, ID: %s, tenant ID: %d", agent.ID, tenantID)
|
||||
|
||||
if err := s.repo.CreateAgent(ctx, newAgent); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agent.ID,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Built-in agent config record created successfully, ID: %s", agent.ID)
|
||||
return newAgent, nil
|
||||
}
|
||||
|
||||
// DeleteAgent deletes an agent
|
||||
func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
return errors.New("agent ID cannot be empty")
|
||||
}
|
||||
|
||||
// Cannot delete built-in agents using registry check
|
||||
if types.IsBuiltinAgentID(id) {
|
||||
return ErrCannotDeleteBuiltin
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Get existing agent to verify ownership
|
||||
existingAgent, err := s.repo.GetAgentByID(ctx, id, tenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrCustomAgentNotFound) {
|
||||
return ErrAgentNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Cannot delete built-in agents
|
||||
if existingAgent.IsBuiltin {
|
||||
return ErrCannotDeleteBuiltin
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Deleting custom agent, ID: %s", id)
|
||||
|
||||
if err := s.repo.DeleteAgent(ctx, id, tenantID); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyAgent creates a copy of an existing agent
|
||||
func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error) {
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
return nil, errors.New("agent ID cannot be empty")
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Get the source agent
|
||||
sourceAgent, err := s.GetAgentByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create a new agent with copied data
|
||||
newAgent := &types.CustomAgent{
|
||||
ID: uuid.New().String(),
|
||||
Name: sourceAgent.Name + " (副本)",
|
||||
Description: sourceAgent.Description,
|
||||
Avatar: sourceAgent.Avatar,
|
||||
IsBuiltin: false, // Copied agents are never built-in
|
||||
TenantID: tenantID,
|
||||
Config: sourceAgent.Config,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Ensure defaults
|
||||
newAgent.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Copying agent, source ID: %s, new ID: %s", id, newAgent.ID)
|
||||
|
||||
if err := s.repo.CreateAgent(ctx, newAgent); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"source_agent_id": id,
|
||||
"new_agent_id": newAgent.ID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Agent copied successfully, source ID: %s, new ID: %s", id, newAgent.ID)
|
||||
return newAgent, nil
|
||||
}
|
||||
@@ -1956,10 +1956,10 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
|
||||
}
|
||||
|
||||
// Replace placeholders
|
||||
prompt = strings.ReplaceAll(prompt, "{{.QuestionCount}}", fmt.Sprintf("%d", questionCount))
|
||||
prompt = strings.ReplaceAll(prompt, "{{.Content}}", content)
|
||||
prompt = strings.ReplaceAll(prompt, "{{.Context}}", contextSection)
|
||||
prompt = strings.ReplaceAll(prompt, "{{.DocName}}", docName)
|
||||
prompt = strings.ReplaceAll(prompt, "{{question_count}}", fmt.Sprintf("%d", questionCount))
|
||||
prompt = strings.ReplaceAll(prompt, "{{content}}", content)
|
||||
prompt = strings.ReplaceAll(prompt, "{{context}}", contextSection)
|
||||
prompt = strings.ReplaceAll(prompt, "{{doc_name}}", docName)
|
||||
|
||||
thinking := false
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
@@ -2000,11 +2000,11 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
|
||||
// Default prompt for question generation with context support
|
||||
const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
|
||||
|
||||
{{.Context}}
|
||||
{{context}}
|
||||
## 主要内容(请基于此内容生成问题)
|
||||
文档名称:{{.DocName}}
|
||||
文档名称:{{doc_name}}
|
||||
文档内容:
|
||||
{{.Content}}
|
||||
{{content}}
|
||||
|
||||
## 核心要求
|
||||
- 生成的问题必须与【主要内容】直接相关
|
||||
@@ -2013,7 +2013,7 @@ const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手
|
||||
- 问题应该是用户在实际场景中可能会提出的自然问题
|
||||
- 问题应该多样化,覆盖内容的不同方面
|
||||
- 每个问题应该简洁明了,长度控制在30字以内
|
||||
- 生成的问题数量为 {{.QuestionCount}} 个
|
||||
- 生成的问题数量为 {{question_count}} 个
|
||||
|
||||
## 问题类型建议
|
||||
- 定义类:什么是...?...是什么?
|
||||
@@ -5860,4 +5860,3 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string,
|
||||
}
|
||||
return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit)
|
||||
}
|
||||
|
||||
|
||||
@@ -166,3 +166,42 @@ func (cm *contextManager) GetContextStats(ctx context.Context, sessionID string)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// SetSystemPrompt sets or updates the system prompt for a session
|
||||
// If a system message exists, it will be replaced; otherwise, a new one will be added at the beginning
|
||||
func (cm *contextManager) SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error {
|
||||
logger.Infof(ctx, "[ContextManager][Session-%s] Setting system prompt, length=%d", sessionID, len(systemPrompt))
|
||||
|
||||
// Load existing messages from storage
|
||||
messages, err := cm.storage.Load(ctx, sessionID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to load context: %v", sessionID, err)
|
||||
return fmt.Errorf("failed to load context: %w", err)
|
||||
}
|
||||
|
||||
// Create new system message
|
||||
systemMessage := chat.Message{
|
||||
Role: "system",
|
||||
Content: systemPrompt,
|
||||
}
|
||||
|
||||
// Check if first message is a system message
|
||||
if len(messages) > 0 && messages[0].Role == "system" {
|
||||
// Replace existing system message
|
||||
logger.Debugf(ctx, "[ContextManager][Session-%s] Replacing existing system prompt", sessionID)
|
||||
messages[0] = systemMessage
|
||||
} else {
|
||||
// Insert system message at the beginning
|
||||
logger.Debugf(ctx, "[ContextManager][Session-%s] Inserting new system prompt at beginning", sessionID)
|
||||
messages = append([]chat.Message{systemMessage}, messages...)
|
||||
}
|
||||
|
||||
// Save updated messages to storage
|
||||
if err := cm.storage.Save(ctx, sessionID, messages); err != nil {
|
||||
logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to save context: %v", sessionID, err)
|
||||
return fmt.Errorf("failed to save context: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[ContextManager][Session-%s] System prompt set successfully", sessionID)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"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"
|
||||
@@ -17,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"
|
||||
@@ -87,8 +85,7 @@ func (s *sessionService) CreateSession(ctx context.Context, session *types.Sessi
|
||||
return nil, errors.New("tenant ID is required")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating session, tenant ID: %d, model ID: %s, knowledge base ID: %s",
|
||||
session.TenantID, session.SummaryModelID, session.KnowledgeBaseID)
|
||||
logger.Infof(ctx, "Creating session, tenant ID: %d", session.TenantID)
|
||||
|
||||
// Create session in repository
|
||||
createdSession, err := s.sessionRepo.Create(ctx, session)
|
||||
@@ -221,8 +218,9 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
|
||||
}
|
||||
|
||||
// GenerateTitle generates a title for the current conversation content
|
||||
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
|
||||
func (s *sessionService) GenerateTitle(ctx context.Context,
|
||||
session *types.Session, messages []types.Message,
|
||||
session *types.Session, messages []types.Message, modelID string,
|
||||
) (string, error) {
|
||||
if session == nil {
|
||||
logger.Error(ctx, "Failed to generate title: session cannot be empty")
|
||||
@@ -259,23 +257,20 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
|
||||
return "", errors.New("no user message found")
|
||||
}
|
||||
|
||||
// Get chat model, use default if SummaryModelID is empty
|
||||
modelID := session.SummaryModelID
|
||||
// Use provided modelID, or fallback to first available KnowledgeQA model
|
||||
if modelID == "" {
|
||||
// Try to get an available KnowledgeQA model
|
||||
models, err := s.modelService.ListModels(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return "", fmt.Errorf("failed to list models: %w", err)
|
||||
}
|
||||
// Find first available KnowledgeQA model
|
||||
for _, model := range models {
|
||||
if model == nil {
|
||||
continue
|
||||
}
|
||||
if model.Type == types.ModelTypeKnowledgeQA {
|
||||
modelID = model.ID
|
||||
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID)
|
||||
logger.Infof(ctx, "Using first available KnowledgeQA model for title: %s", modelID)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -283,6 +278,8 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
|
||||
logger.Error(ctx, "No KnowledgeQA model found")
|
||||
return "", errors.New("no KnowledgeQA model available for title generation")
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "Using specified model for title generation: %s", modelID)
|
||||
}
|
||||
|
||||
chatModel, err := s.modelService.GetChatModel(ctx, modelID)
|
||||
@@ -329,10 +326,12 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
|
||||
// GenerateTitleAsync generates a title for the session asynchronously
|
||||
// This method clones the session and generates the title in a goroutine
|
||||
// It emits an event when the title is generated
|
||||
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
|
||||
func (s *sessionService) GenerateTitleAsync(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
userQuery string,
|
||||
modelID string,
|
||||
eventBus *event.EventBus,
|
||||
) {
|
||||
// Extract values from context before cloning
|
||||
@@ -361,7 +360,7 @@ func (s *sessionService) GenerateTitleAsync(
|
||||
},
|
||||
}
|
||||
|
||||
title, err := s.GenerateTitle(bgCtx, session, messages)
|
||||
title, err := s.GenerateTitle(bgCtx, session, messages, modelID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(bgCtx, err, map[string]interface{}{
|
||||
"session_id": session.ID,
|
||||
@@ -392,6 +391,7 @@ func (s *sessionService) GenerateTitleAsync(
|
||||
|
||||
// KnowledgeQA performs knowledge base question answering with LLM summarization
|
||||
// Events are emitted through eventBus (references, answer chunks, completion)
|
||||
// customAgent is optional - if provided, uses custom agent configuration for multiTurnEnabled and historyTurns
|
||||
func (s *sessionService) KnowledgeQA(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
@@ -402,6 +402,7 @@ func (s *sessionService) KnowledgeQA(
|
||||
summaryModelID string,
|
||||
webSearchEnabled bool,
|
||||
eventBus *event.EventBus,
|
||||
customAgent *types.CustomAgent,
|
||||
) error {
|
||||
logger.Infof(
|
||||
ctx,
|
||||
@@ -411,101 +412,42 @@ func (s *sessionService) KnowledgeQA(
|
||||
webSearchEnabled,
|
||||
)
|
||||
|
||||
// If no knowledge base IDs provided, fall back to session's default
|
||||
if len(knowledgeBaseIDs) == 0 {
|
||||
if session.KnowledgeBaseID != "" {
|
||||
knowledgeBaseIDs = []string{session.KnowledgeBaseID}
|
||||
logger.Infof(ctx, "No knowledge base IDs provided, using session default: %s", session.KnowledgeBaseID)
|
||||
} else {
|
||||
logger.Warnf(ctx, "Session has no associated knowledge base, session ID: %s", session.ID)
|
||||
}
|
||||
// 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 {
|
||||
knowledgeBaseIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent)
|
||||
} else {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
|
||||
// Initialize default values from config.yaml
|
||||
rewritePromptSystem := s.cfg.Conversation.RewritePromptSystem
|
||||
rewritePromptUser := s.cfg.Conversation.RewritePromptUser
|
||||
var tenantConv *types.ConversationConfig
|
||||
if tc, err := getTenantConversationConfig(ctx); err == nil {
|
||||
tenantConv = tc
|
||||
} else {
|
||||
logger.Warnf(ctx, "Failed to load tenant conversation config, tenant ID: %d, error: %v", session.TenantID, err)
|
||||
}
|
||||
vectorThreshold := s.cfg.Conversation.VectorThreshold
|
||||
keywordThreshold := s.cfg.Conversation.KeywordThreshold
|
||||
embeddingTopK := s.cfg.Conversation.EmbeddingTopK
|
||||
rerankTopK := s.cfg.Conversation.RerankTopK
|
||||
rerankThreshold := s.cfg.Conversation.RerankThreshold
|
||||
maxRounds := s.cfg.Conversation.MaxRounds
|
||||
fallbackStrategy := types.FallbackStrategy(s.cfg.Conversation.FallbackStrategy)
|
||||
fallbackResponse := s.cfg.Conversation.FallbackResponse
|
||||
fallbackPrompt := s.cfg.Conversation.FallbackPrompt
|
||||
enableRewrite := s.cfg.Conversation.EnableRewrite
|
||||
enableQueryExpansion := s.cfg.Conversation.EnableQueryExpansion
|
||||
rerankModelID := ""
|
||||
|
||||
vectorThreshold := session.VectorThreshold
|
||||
keywordThreshold := session.KeywordThreshold
|
||||
embeddingTopK := session.EmbeddingTopK
|
||||
rerankModelID := session.RerankModelID
|
||||
rerankTopK := session.RerankTopK
|
||||
rerankThreshold := session.RerankThreshold
|
||||
maxRounds := session.MaxRounds
|
||||
fallbackStrategy := session.FallbackStrategy
|
||||
fallbackResponse := session.FallbackResponse
|
||||
fallbackPrompt := ""
|
||||
enableRewrite := session.EnableRewrite
|
||||
enableQueryExpansion := true
|
||||
|
||||
summaryParams := session.SummaryParameters
|
||||
if summaryParams == nil {
|
||||
summaryParams = &types.SummaryConfig{}
|
||||
}
|
||||
summaryConfig := types.SummaryConfig{
|
||||
MaxTokens: summaryParams.MaxTokens,
|
||||
RepeatPenalty: summaryParams.RepeatPenalty,
|
||||
TopK: summaryParams.TopK,
|
||||
TopP: summaryParams.TopP,
|
||||
FrequencyPenalty: summaryParams.FrequencyPenalty,
|
||||
PresencePenalty: summaryParams.PresencePenalty,
|
||||
Prompt: summaryParams.Prompt,
|
||||
ContextTemplate: summaryParams.ContextTemplate,
|
||||
Temperature: summaryParams.Temperature,
|
||||
Seed: summaryParams.Seed,
|
||||
NoMatchPrefix: summaryParams.NoMatchPrefix,
|
||||
MaxCompletionTokens: summaryParams.MaxCompletionTokens,
|
||||
}
|
||||
|
||||
if tenantConv != nil {
|
||||
vectorThreshold = tenantConv.VectorThreshold
|
||||
keywordThreshold = tenantConv.KeywordThreshold
|
||||
embeddingTopK = tenantConv.EmbeddingTopK
|
||||
rerankModelID = tenantConv.RerankModelID
|
||||
rerankTopK = tenantConv.RerankTopK
|
||||
rerankThreshold = tenantConv.RerankThreshold
|
||||
maxRounds = tenantConv.MaxRounds
|
||||
if tenantConv.FallbackStrategy != "" {
|
||||
fallbackStrategy = types.FallbackStrategy(tenantConv.FallbackStrategy)
|
||||
}
|
||||
fallbackResponse = tenantConv.FallbackResponse
|
||||
if tenantConv.FallbackPrompt != "" {
|
||||
fallbackPrompt = tenantConv.FallbackPrompt
|
||||
}
|
||||
enableRewrite = tenantConv.EnableRewrite
|
||||
enableQueryExpansion = tenantConv.EnableQueryExpansion
|
||||
|
||||
if tenantConv.MaxCompletionTokens != 0 {
|
||||
summaryConfig.MaxCompletionTokens = tenantConv.MaxCompletionTokens
|
||||
}
|
||||
if tenantConv.Prompt != "" {
|
||||
summaryConfig.Prompt = tenantConv.Prompt
|
||||
}
|
||||
if tenantConv.ContextTemplate != "" {
|
||||
summaryConfig.ContextTemplate = tenantConv.ContextTemplate
|
||||
}
|
||||
if tenantConv.Temperature != 0 {
|
||||
summaryConfig.Temperature = tenantConv.Temperature
|
||||
}
|
||||
if tenantConv.RewritePromptSystem != "" {
|
||||
rewritePromptSystem = tenantConv.RewritePromptSystem
|
||||
}
|
||||
if tenantConv.RewritePromptUser != "" {
|
||||
rewritePromptUser = tenantConv.RewritePromptUser
|
||||
}
|
||||
Prompt: s.cfg.Conversation.Summary.Prompt,
|
||||
ContextTemplate: s.cfg.Conversation.Summary.ContextTemplate,
|
||||
Temperature: s.cfg.Conversation.Summary.Temperature,
|
||||
NoMatchPrefix: s.cfg.Conversation.Summary.NoMatchPrefix,
|
||||
MaxCompletionTokens: s.cfg.Conversation.Summary.MaxCompletionTokens,
|
||||
}
|
||||
|
||||
// Set default fallback strategy if not set
|
||||
@@ -514,6 +456,100 @@ func (s *sessionService) KnowledgeQA(
|
||||
logger.Infof(ctx, "Fallback strategy not set, using default: %v", fallbackStrategy)
|
||||
}
|
||||
|
||||
// Apply custom agent configuration if provided
|
||||
if customAgent != nil {
|
||||
// Ensure defaults are set
|
||||
customAgent.EnsureDefaults()
|
||||
|
||||
// Override model ID
|
||||
if customAgent.Config.ModelID != "" {
|
||||
chatModelID = customAgent.Config.ModelID
|
||||
logger.Infof(ctx, "Using custom agent's model_id: %s", chatModelID)
|
||||
}
|
||||
// Override system prompt
|
||||
if customAgent.Config.SystemPrompt != "" {
|
||||
summaryConfig.Prompt = customAgent.Config.SystemPrompt
|
||||
logger.Infof(ctx, "Using custom agent's system_prompt")
|
||||
}
|
||||
// Override context template
|
||||
if customAgent.Config.ContextTemplate != "" {
|
||||
summaryConfig.ContextTemplate = customAgent.Config.ContextTemplate
|
||||
logger.Infof(ctx, "Using custom agent's context_template")
|
||||
}
|
||||
// Override temperature
|
||||
if customAgent.Config.Temperature > 0 {
|
||||
summaryConfig.Temperature = customAgent.Config.Temperature
|
||||
logger.Infof(ctx, "Using custom agent's temperature: %f", customAgent.Config.Temperature)
|
||||
}
|
||||
// Override max completion tokens
|
||||
if customAgent.Config.MaxCompletionTokens > 0 {
|
||||
summaryConfig.MaxCompletionTokens = customAgent.Config.MaxCompletionTokens
|
||||
logger.Infof(ctx, "Using custom agent's max_completion_tokens: %d", customAgent.Config.MaxCompletionTokens)
|
||||
}
|
||||
// Override retrieval strategy settings
|
||||
if customAgent.Config.EmbeddingTopK > 0 {
|
||||
embeddingTopK = customAgent.Config.EmbeddingTopK
|
||||
}
|
||||
if customAgent.Config.KeywordThreshold > 0 {
|
||||
keywordThreshold = customAgent.Config.KeywordThreshold
|
||||
}
|
||||
if customAgent.Config.VectorThreshold > 0 {
|
||||
vectorThreshold = customAgent.Config.VectorThreshold
|
||||
}
|
||||
if customAgent.Config.RerankTopK > 0 {
|
||||
rerankTopK = customAgent.Config.RerankTopK
|
||||
}
|
||||
if customAgent.Config.RerankThreshold > 0 {
|
||||
rerankThreshold = customAgent.Config.RerankThreshold
|
||||
}
|
||||
if customAgent.Config.RerankModelID != "" {
|
||||
rerankModelID = customAgent.Config.RerankModelID
|
||||
}
|
||||
// Override rewrite settings
|
||||
enableRewrite = customAgent.Config.EnableRewrite
|
||||
enableQueryExpansion = customAgent.Config.EnableQueryExpansion
|
||||
if customAgent.Config.RewritePromptSystem != "" {
|
||||
rewritePromptSystem = customAgent.Config.RewritePromptSystem
|
||||
}
|
||||
if customAgent.Config.RewritePromptUser != "" {
|
||||
rewritePromptUser = customAgent.Config.RewritePromptUser
|
||||
}
|
||||
// Override fallback settings
|
||||
if customAgent.Config.FallbackStrategy != "" {
|
||||
fallbackStrategy = types.FallbackStrategy(customAgent.Config.FallbackStrategy)
|
||||
}
|
||||
if customAgent.Config.FallbackResponse != "" {
|
||||
fallbackResponse = customAgent.Config.FallbackResponse
|
||||
}
|
||||
if customAgent.Config.FallbackPrompt != "" {
|
||||
fallbackPrompt = customAgent.Config.FallbackPrompt
|
||||
}
|
||||
// Override history turns
|
||||
if customAgent.Config.HistoryTurns > 0 {
|
||||
maxRounds = customAgent.Config.HistoryTurns
|
||||
logger.Infof(ctx, "Using custom agent's history_turns: %d", maxRounds)
|
||||
}
|
||||
// Check if multi-turn is disabled
|
||||
if !customAgent.Config.MultiTurnEnabled {
|
||||
maxRounds = 0 // Disable history
|
||||
logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history")
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -556,6 +592,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
|
||||
@@ -563,10 +603,18 @@ func (s *sessionService) KnowledgeQA(
|
||||
// Otherwise use rag_stream pipeline (which handles both KB search and web search)
|
||||
var pipeline []types.EventType
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && !webSearchEnabled {
|
||||
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat_stream pipeline")
|
||||
pipeline = types.Pipline["chat_stream"]
|
||||
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat pipeline")
|
||||
// For pure chat, UserContent is the Query (since INTO_CHAT_MESSAGE is skipped)
|
||||
chatManage.UserContent = query
|
||||
|
||||
// Use chat_history_stream if multi-turn is enabled, otherwise use chat_stream
|
||||
if maxRounds > 0 {
|
||||
logger.Infof(ctx, "Multi-turn enabled with maxRounds=%d, using chat_history_stream pipeline", maxRounds)
|
||||
pipeline = types.Pipline["chat_history_stream"]
|
||||
} else {
|
||||
logger.Info(ctx, "Multi-turn disabled, using chat_stream pipeline")
|
||||
pipeline = types.Pipline["chat_stream"]
|
||||
}
|
||||
} else {
|
||||
if webSearchEnabled && len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
logger.Info(ctx, "Web search enabled without knowledge bases, using rag_stream pipeline for web search only")
|
||||
@@ -581,8 +629,7 @@ func (s *sessionService) KnowledgeQA(
|
||||
err = s.KnowledgeQAByEvent(ctx, chatManage, pipeline)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"session_id": session.ID,
|
||||
"knowledge_base_id": session.KnowledgeBaseID,
|
||||
"session_id": session.ID,
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -659,10 +706,6 @@ func (s *sessionService) selectChatModelID(
|
||||
knowledgeIDs []string,
|
||||
) (string, error) {
|
||||
|
||||
// First, check if session has a SummaryModelID and if it's a Remote model
|
||||
if session.SummaryModelID != "" {
|
||||
return session.SummaryModelID, nil
|
||||
}
|
||||
// If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) > 0 {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
@@ -684,7 +727,7 @@ func (s *sessionService) selectChatModelID(
|
||||
len(knowledgeBaseIDs), len(knowledgeIDs))
|
||||
}
|
||||
}
|
||||
// If no Remote model found from session, check knowledge bases for Remote models
|
||||
// Check knowledge bases for models
|
||||
if len(knowledgeBaseIDs) > 0 {
|
||||
// Try to find a knowledge base with Remote model
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
@@ -702,13 +745,7 @@ func (s *sessionService) selectChatModelID(
|
||||
}
|
||||
}
|
||||
|
||||
// If still no Remote model found, use session's SummaryModelID if available
|
||||
if session.SummaryModelID != "" {
|
||||
logger.Infof(ctx, "No Remote model found, using session's summary model: %s", session.SummaryModelID)
|
||||
return session.SummaryModelID, nil
|
||||
}
|
||||
|
||||
// If still empty, use first knowledge base's model
|
||||
// If no Remote model found, use first knowledge base's model
|
||||
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, knowledgeBaseIDs[0])
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge base for model ID: %v", err)
|
||||
@@ -722,22 +759,66 @@ func (s *sessionService) selectChatModelID(
|
||||
kb.SummaryModelID,
|
||||
)
|
||||
return kb.SummaryModelID, nil
|
||||
} else {
|
||||
logger.Errorf(ctx, "Knowledge base %s has no summary model ID", knowledgeBaseIDs[0])
|
||||
return "", fmt.Errorf("knowledge base %s has no summary model configured", knowledgeBaseIDs[0])
|
||||
}
|
||||
}
|
||||
|
||||
// No knowledge bases - use session's SummaryModelID if available
|
||||
if session.SummaryModelID != "" {
|
||||
logger.Infof(ctx, "No knowledge bases, using session's summary model: %s", session.SummaryModelID)
|
||||
return session.SummaryModelID, nil
|
||||
// No knowledge bases - try to find any available chat model
|
||||
models, err := s.modelService.ListModels(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to list models: %v", err)
|
||||
return "", fmt.Errorf("failed to list models: %w", err)
|
||||
}
|
||||
for _, model := range models {
|
||||
if model != nil && model.Type == types.ModelTypeKnowledgeQA {
|
||||
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", model.ID)
|
||||
return model.ID, nil
|
||||
}
|
||||
}
|
||||
|
||||
logger.Error(ctx, "No chat model ID available")
|
||||
return "", errors.New(
|
||||
"no chat model ID available: session has no SummaryModelID and no knowledge bases configured",
|
||||
)
|
||||
return "", errors.New("no chat model ID available: no knowledge bases configured and no available models")
|
||||
}
|
||||
|
||||
// resolveKnowledgeBasesFromAgent resolves knowledge base IDs based on agent's KBSelectionMode
|
||||
// Returns the resolved knowledge base IDs based on the selection mode:
|
||||
// - "all": fetches all knowledge bases for the tenant
|
||||
// - "selected": uses the explicitly configured knowledge bases
|
||||
// - "none": returns empty slice
|
||||
// - default: falls back to configured knowledge bases for backward compatibility
|
||||
func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
ctx context.Context,
|
||||
customAgent *types.CustomAgent,
|
||||
) []string {
|
||||
if customAgent == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch customAgent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list all knowledge bases: %v", err)
|
||||
return nil
|
||||
}
|
||||
kbIDs := make([]string, 0, len(allKBs))
|
||||
for _, kb := range allKBs {
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
}
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases", len(kbIDs))
|
||||
return kbIDs
|
||||
case "selected":
|
||||
logger.Infof(ctx, "KBSelectionMode=selected: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
|
||||
return customAgent.Config.KnowledgeBases
|
||||
case "none":
|
||||
logger.Infof(ctx, "KBSelectionMode=none: no knowledge bases configured")
|
||||
return nil
|
||||
default:
|
||||
// Default to "selected" behavior for backward compatibility
|
||||
if len(customAgent.Config.KnowledgeBases) > 0 {
|
||||
logger.Infof(ctx, "KBSelectionMode not set: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
|
||||
}
|
||||
return customAgent.Config.KnowledgeBases
|
||||
}
|
||||
}
|
||||
|
||||
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
|
||||
@@ -859,17 +940,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
|
||||
@@ -985,12 +1055,16 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
|
||||
}
|
||||
|
||||
// AgentQA performs agent-based question answering with conversation history and streaming support
|
||||
// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults
|
||||
func (s *sessionService) AgentQA(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
query string,
|
||||
assistantMessageID string,
|
||||
eventBus *event.EventBus,
|
||||
customAgent *types.CustomAgent,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) error {
|
||||
sessionID := session.ID
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
@@ -1003,82 +1077,82 @@ func (s *sessionService) AgentQA(
|
||||
sessionID, tenantID, query, string(sessionJSON))
|
||||
|
||||
// Build effective agent configuration by merging session and tenant configs
|
||||
// Session-level config: Enabled, KnowledgeBases (stored in session.AgentConfig)
|
||||
// Tenant-level config: MaxIterations, Temperature, Models, Tools, etc. (from tenant.AgentConfig)
|
||||
// All config now comes from customAgent parameter
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
|
||||
// Check if agent is enabled at session level
|
||||
if session.AgentConfig == nil {
|
||||
logger.Warnf(ctx, "Agent config not found for session: %s", sessionID)
|
||||
return errors.New("agent config not found for session")
|
||||
// customAgent is required for AgentQA
|
||||
if customAgent == nil {
|
||||
logger.Warnf(ctx, "Custom agent not provided for session: %s", sessionID)
|
||||
return errors.New("custom agent configuration is required for agent QA")
|
||||
}
|
||||
|
||||
// Check if tenant has agent configuration
|
||||
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,
|
||||
}
|
||||
}
|
||||
// Ensure defaults are set
|
||||
customAgent.EnsureDefaults()
|
||||
|
||||
// Create runtime AgentConfig by merging session and tenant configs
|
||||
// Tenant config provides the runtime parameters (MaxIterations, Temperature, Tools, Models)
|
||||
// Session config provides KnowledgeBases and KnowledgeIDs
|
||||
// Create runtime AgentConfig from customAgent
|
||||
// Note: tenantInfo.AgentConfig is deprecated, all config comes from customAgent now
|
||||
agentConfig := &types.AgentConfig{
|
||||
MaxIterations: tenantInfo.AgentConfig.MaxIterations,
|
||||
ReflectionEnabled: tenantInfo.AgentConfig.ReflectionEnabled,
|
||||
AllowedTools: tools.DefaultAllowedTools(),
|
||||
Temperature: tenantInfo.AgentConfig.Temperature,
|
||||
KnowledgeBases: session.AgentConfig.KnowledgeBases, // Use session's knowledge bases
|
||||
KnowledgeIDs: session.AgentConfig.KnowledgeIDs, // Use session's knowledge IDs (individual documents)
|
||||
WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config
|
||||
MaxIterations: customAgent.Config.MaxIterations,
|
||||
ReflectionEnabled: customAgent.Config.ReflectionEnabled,
|
||||
Temperature: customAgent.Config.Temperature,
|
||||
WebSearchEnabled: customAgent.Config.WebSearchEnabled,
|
||||
WebSearchMaxResults: customAgent.Config.WebSearchMaxResults,
|
||||
MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,
|
||||
HistoryTurns: customAgent.Config.HistoryTurns,
|
||||
MCPSelectionMode: customAgent.Config.MCPSelectionMode,
|
||||
MCPServices: customAgent.Config.MCPServices,
|
||||
}
|
||||
|
||||
agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt
|
||||
if agentConfig.UseCustomSystemPrompt {
|
||||
agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true)
|
||||
agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false)
|
||||
// Resolve knowledge bases: request-level @ mentions take priority over agent config
|
||||
if len(knowledgeBaseIDs) > 0 || len(knowledgeIDs) > 0 {
|
||||
// User explicitly specified via @ mention
|
||||
if len(knowledgeBaseIDs) > 0 {
|
||||
agentConfig.KnowledgeBases = knowledgeBaseIDs
|
||||
logger.Infof(ctx, "Using request-specified knowledge bases: %v", knowledgeBaseIDs)
|
||||
}
|
||||
if len(knowledgeIDs) > 0 {
|
||||
agentConfig.KnowledgeIDs = knowledgeIDs
|
||||
logger.Infof(ctx, "Using request-specified knowledge IDs: %v", knowledgeIDs)
|
||||
}
|
||||
} else {
|
||||
// Use agent's configured knowledge bases based on KBSelectionMode
|
||||
agentConfig.KnowledgeBases = s.resolveKnowledgeBasesFromAgent(ctx, customAgent)
|
||||
}
|
||||
|
||||
// Set web search max results from tenant config (default: 5)
|
||||
agentConfig.WebSearchMaxResults = 5
|
||||
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
|
||||
agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults
|
||||
// Use custom agent's allowed tools if specified, otherwise use defaults
|
||||
if len(customAgent.Config.AllowedTools) > 0 {
|
||||
agentConfig.AllowedTools = customAgent.Config.AllowedTools
|
||||
} else {
|
||||
agentConfig.AllowedTools = tools.DefaultAllowedTools()
|
||||
}
|
||||
|
||||
// Use custom agent's system prompt if specified
|
||||
if customAgent.Config.SystemPrompt != "" {
|
||||
agentConfig.UseCustomSystemPrompt = true
|
||||
agentConfig.SystemPrompt = customAgent.Config.SystemPrompt
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v",
|
||||
agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled)
|
||||
|
||||
// Set web search max results from tenant config if not set (default: 5)
|
||||
if agentConfig.WebSearchMaxResults == 0 {
|
||||
agentConfig.WebSearchMaxResults = 5
|
||||
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
|
||||
agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, sessionID)
|
||||
|
||||
// Log knowledge IDs if present
|
||||
if len(agentConfig.KnowledgeIDs) > 0 {
|
||||
logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s): %v",
|
||||
len(agentConfig.KnowledgeIDs), agentConfig.KnowledgeIDs)
|
||||
}
|
||||
|
||||
// Determine knowledge bases for agent
|
||||
// Priority: Session.AgentConfig.KnowledgeBases > Session.KnowledgeBaseID > All tenant knowledge bases
|
||||
// Exception: If KnowledgeIDs are specified, don't auto-add all KBs (let buildSearchTargets handle it)
|
||||
if len(agentConfig.KnowledgeBases) == 0 && len(agentConfig.KnowledgeIDs) == 0 {
|
||||
if session.KnowledgeBaseID != "" {
|
||||
// Use session's knowledge base as fallback
|
||||
agentConfig.KnowledgeBases = []string{session.KnowledgeBaseID}
|
||||
logger.Infof(ctx, "Using session's knowledge base for agent: %s", session.KnowledgeBaseID)
|
||||
} else {
|
||||
// Allow running without knowledge bases (Pure Agent mode)
|
||||
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
|
||||
}
|
||||
} else if len(agentConfig.KnowledgeIDs) > 0 && len(agentConfig.KnowledgeBases) == 0 {
|
||||
// User specified individual files but no KBs - don't auto-add all KBs
|
||||
logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s), no KB auto-expansion",
|
||||
len(agentConfig.KnowledgeIDs))
|
||||
} else {
|
||||
// Log knowledge bases if present
|
||||
if len(agentConfig.KnowledgeBases) > 0 {
|
||||
logger.Infof(ctx, "Agent configured with %d knowledge base(s): %v",
|
||||
len(agentConfig.KnowledgeBases), agentConfig.KnowledgeBases)
|
||||
} else {
|
||||
// Allow running without knowledge bases (Pure Agent mode)
|
||||
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
|
||||
}
|
||||
|
||||
// Build search targets for agent (pre-compute once to avoid repeated queries)
|
||||
@@ -1090,13 +1164,12 @@ func (s *sessionService) AgentQA(
|
||||
agentConfig.SearchTargets = searchTargets
|
||||
logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets))
|
||||
|
||||
summaryModelID := session.SummaryModelID
|
||||
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
|
||||
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
|
||||
}
|
||||
// Get summary model from custom agent config
|
||||
// Note: tenantInfo.ConversationConfig is deprecated, all config comes from customAgent now
|
||||
summaryModelID := customAgent.Config.ModelID
|
||||
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)
|
||||
@@ -1105,23 +1178,39 @@ func (s *sessionService) AgentQA(
|
||||
return fmt.Errorf("failed to get chat model: %w", err)
|
||||
}
|
||||
|
||||
rerankModelID := session.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
|
||||
contextManager := s.getContextManagerForSession(ctx, session, summaryModel)
|
||||
|
||||
// Set system prompt for the current agent in context manager
|
||||
// This ensures the context uses the correct system prompt when switching agents
|
||||
systemPrompt := agentConfig.ResolveSystemPrompt(agentConfig.WebSearchEnabled)
|
||||
if systemPrompt != "" {
|
||||
if err := contextManager.SetSystemPrompt(ctx, sessionID, systemPrompt); err != nil {
|
||||
logger.Warnf(ctx, "Failed to set system prompt in context manager: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "System prompt updated in context manager for agent")
|
||||
}
|
||||
}
|
||||
|
||||
// Get LLM context from context manager
|
||||
llmContext, err := s.getContextForSession(ctx, contextManager, sessionID)
|
||||
if err != nil {
|
||||
@@ -1130,6 +1219,15 @@ func (s *sessionService) AgentQA(
|
||||
}
|
||||
logger.Infof(ctx, "Loaded %d messages from LLM context manager", len(llmContext))
|
||||
|
||||
// Apply multi-turn configuration for Agent mode
|
||||
// Note: In Agent mode, context is managed by contextManager with compression strategies,
|
||||
// so we don't apply HistoryTurns limit here. HistoryTurns is used in normal (KnowledgeQA) mode.
|
||||
if !agentConfig.MultiTurnEnabled {
|
||||
// Multi-turn disabled, clear history
|
||||
logger.Infof(ctx, "Multi-turn disabled for this agent, clearing history context")
|
||||
llmContext = []chat.Message{}
|
||||
}
|
||||
|
||||
// Create agent engine with EventBus and ContextManager
|
||||
logger.Info(ctx, "Creating agent engine")
|
||||
engine, err := s.agentService.CreateAgentEngine(
|
||||
@@ -1176,13 +1274,9 @@ func (s *sessionService) getContextManagerForSession(
|
||||
) interfaces.ContextManager {
|
||||
// Get tenant to access global context configuration
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
// Determine which context config to use: session-specific or tenant-level
|
||||
// Determine which context config to use: tenant-level or default
|
||||
var contextConfig *types.ContextConfig
|
||||
if session.ContextConfig != nil {
|
||||
// Use session-specific configuration
|
||||
contextConfig = session.ContextConfig
|
||||
logger.Infof(ctx, "Using session-specific context config for session %s", session.ID)
|
||||
} else if tenant.ContextConfig != nil {
|
||||
if tenant != nil && tenant.ContextConfig != nil {
|
||||
// Use tenant-level configuration
|
||||
contextConfig = tenant.ContextConfig
|
||||
logger.Infof(ctx, "Using tenant-level context config for session %s", session.ID)
|
||||
@@ -1409,20 +1503,9 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty
|
||||
|
||||
// renderFallbackPrompt renders the fallback prompt template with Query variable
|
||||
func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *types.ChatManage) (string, error) {
|
||||
tmpl, err := template.New("fallbackPrompt").Parse(chatManage.FallbackPrompt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse template: %w", err)
|
||||
}
|
||||
|
||||
var promptContent bytes.Buffer
|
||||
err = tmpl.Execute(&promptContent, map[string]interface{}{
|
||||
"Query": chatManage.Query,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to execute template: %w", err)
|
||||
}
|
||||
|
||||
return promptContent.String(), nil
|
||||
// Use simple string replacement instead of Go template
|
||||
result := strings.ReplaceAll(chatManage.FallbackPrompt, "{{query}}", chatManage.Query)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// consumeFallbackStream consumes the streaming response and emits events
|
||||
|
||||
+91
-10
@@ -3,6 +3,7 @@ package config
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -10,20 +11,22 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
"github.com/spf13/viper"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Config 应用程序总配置
|
||||
type Config struct {
|
||||
Conversation *ConversationConfig `yaml:"conversation" json:"conversation"`
|
||||
Server *ServerConfig `yaml:"server" json:"server"`
|
||||
KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"`
|
||||
Tenant *TenantConfig `yaml:"tenant" json:"tenant"`
|
||||
Models []ModelConfig `yaml:"models" json:"models"`
|
||||
VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"`
|
||||
DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"`
|
||||
StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"`
|
||||
ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"`
|
||||
WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"`
|
||||
Conversation *ConversationConfig `yaml:"conversation" json:"conversation"`
|
||||
Server *ServerConfig `yaml:"server" json:"server"`
|
||||
KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"`
|
||||
Tenant *TenantConfig `yaml:"tenant" json:"tenant"`
|
||||
Models []ModelConfig `yaml:"models" json:"models"`
|
||||
VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"`
|
||||
DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"`
|
||||
StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"`
|
||||
ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"`
|
||||
WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"`
|
||||
PromptTemplates *PromptTemplatesConfig `yaml:"prompt_templates" json:"prompt_templates"`
|
||||
}
|
||||
|
||||
type DocReaderConfig struct {
|
||||
@@ -108,6 +111,25 @@ type TenantConfig struct {
|
||||
EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"`
|
||||
}
|
||||
|
||||
// PromptTemplate 提示词模板
|
||||
type PromptTemplate struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Description string `yaml:"description" json:"description"`
|
||||
Content string `yaml:"content" json:"content"`
|
||||
HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"`
|
||||
HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"`
|
||||
}
|
||||
|
||||
// PromptTemplatesConfig 提示词模板配置
|
||||
type PromptTemplatesConfig struct {
|
||||
SystemPrompt []PromptTemplate `yaml:"system_prompt" json:"system_prompt"`
|
||||
ContextTemplate []PromptTemplate `yaml:"context_template" json:"context_template"`
|
||||
RewriteSystem []PromptTemplate `yaml:"rewrite_system" json:"rewrite_system"`
|
||||
RewriteUser []PromptTemplate `yaml:"rewrite_user" json:"rewrite_user"`
|
||||
Fallback []PromptTemplate `yaml:"fallback" json:"fallback"`
|
||||
}
|
||||
|
||||
// ModelConfig 模型配置
|
||||
type ModelConfig struct {
|
||||
Type string `yaml:"type" json:"type"`
|
||||
@@ -192,9 +214,68 @@ func LoadConfig() (*Config, error) {
|
||||
return nil, fmt.Errorf("unable to decode config into struct: %w", err)
|
||||
}
|
||||
fmt.Printf("Using configuration file: %s\n", viper.ConfigFileUsed())
|
||||
|
||||
// 加载提示词模板(从目录或配置文件)
|
||||
configDir := filepath.Dir(viper.ConfigFileUsed())
|
||||
promptTemplates, err := loadPromptTemplates(configDir)
|
||||
if err != nil {
|
||||
fmt.Printf("Warning: failed to load prompt templates from directory: %v\n", err)
|
||||
// 如果目录加载失败,使用配置文件中的模板(如果有)
|
||||
} else if promptTemplates != nil {
|
||||
cfg.PromptTemplates = promptTemplates
|
||||
}
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// promptTemplateFile 用于解析模板文件
|
||||
type promptTemplateFile struct {
|
||||
Templates []PromptTemplate `yaml:"templates"`
|
||||
}
|
||||
|
||||
// loadPromptTemplates 从目录加载提示词模板
|
||||
func loadPromptTemplates(configDir string) (*PromptTemplatesConfig, error) {
|
||||
templatesDir := filepath.Join(configDir, "prompt_templates")
|
||||
|
||||
// 检查目录是否存在
|
||||
if _, err := os.Stat(templatesDir); os.IsNotExist(err) {
|
||||
return nil, nil // 目录不存在,返回nil让调用者使用配置文件中的模板
|
||||
}
|
||||
|
||||
config := &PromptTemplatesConfig{}
|
||||
|
||||
// 定义模板文件映射
|
||||
templateFiles := map[string]*[]PromptTemplate{
|
||||
"system_prompt.yaml": &config.SystemPrompt,
|
||||
"context_template.yaml": &config.ContextTemplate,
|
||||
"rewrite_system.yaml": &config.RewriteSystem,
|
||||
"rewrite_user.yaml": &config.RewriteUser,
|
||||
"fallback.yaml": &config.Fallback,
|
||||
}
|
||||
|
||||
// 加载每个模板文件
|
||||
for filename, target := range templateFiles {
|
||||
filePath := filepath.Join(templatesDir, filename)
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
continue // 文件不存在,跳过
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read %s: %w", filename, err)
|
||||
}
|
||||
|
||||
var file promptTemplateFile
|
||||
if err := yaml.Unmarshal(data, &file); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse %s: %w", filename, err)
|
||||
}
|
||||
|
||||
*target = file.Templates
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// WebSearchConfig represents the web search configuration
|
||||
type WebSearchConfig struct {
|
||||
Providers []WebSearchProviderConfig `yaml:"providers" json:"providers"`
|
||||
|
||||
@@ -97,6 +97,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(repository.NewAuthTokenRepository))
|
||||
must(container.Provide(neo4jRepo.NewNeo4jRepository))
|
||||
must(container.Provide(repository.NewMCPServiceRepository))
|
||||
must(container.Provide(repository.NewCustomAgentRepository))
|
||||
|
||||
// MCP manager for managing MCP client connections
|
||||
must(container.Provide(mcp.NewMCPManager))
|
||||
@@ -115,6 +116,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewChunkExtractService))
|
||||
must(container.Provide(service.NewMessageService))
|
||||
must(container.Provide(service.NewMCPServiceService))
|
||||
must(container.Provide(service.NewCustomAgentService))
|
||||
|
||||
// Web search service (needed by AgentService)
|
||||
must(container.Provide(service.NewWebSearchService))
|
||||
@@ -143,6 +145,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Invoke(chatpipline.NewPluginStreamFilter))
|
||||
must(container.Invoke(chatpipline.NewPluginFilterTopK))
|
||||
must(container.Invoke(chatpipline.NewPluginRewrite))
|
||||
must(container.Invoke(chatpipline.NewPluginLoadHistory))
|
||||
must(container.Invoke(chatpipline.NewPluginExtractEntity))
|
||||
must(container.Invoke(chatpipline.NewPluginSearchEntity))
|
||||
must(container.Invoke(chatpipline.NewPluginSearchParallel))
|
||||
@@ -163,6 +166,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(handler.NewSystemHandler))
|
||||
must(container.Provide(handler.NewMCPServiceHandler))
|
||||
must(container.Provide(handler.NewWebSearchHandler))
|
||||
must(container.Provide(handler.NewCustomAgentHandler))
|
||||
|
||||
// Router configuration
|
||||
must(container.Provide(router.NewRouter))
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CustomAgentHandler defines the HTTP handler for custom agent operations
|
||||
type CustomAgentHandler struct {
|
||||
service interfaces.CustomAgentService
|
||||
}
|
||||
|
||||
// NewCustomAgentHandler creates a new custom agent handler instance
|
||||
func NewCustomAgentHandler(service interfaces.CustomAgentService) *CustomAgentHandler {
|
||||
return &CustomAgentHandler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateAgentRequest defines the request body for creating an agent
|
||||
type CreateAgentRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Config types.CustomAgentConfig `json:"config"`
|
||||
}
|
||||
|
||||
// UpdateAgentRequest defines the request body for updating an agent
|
||||
type UpdateAgentRequest struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Config types.CustomAgentConfig `json:"config"`
|
||||
}
|
||||
|
||||
// CreateAgent godoc
|
||||
// @Summary 创建智能体
|
||||
// @Description 创建新的自定义智能体
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body CreateAgentRequest true "智能体信息"
|
||||
// @Success 201 {object} map[string]interface{} "创建的智能体"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents [post]
|
||||
func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start creating custom agent")
|
||||
|
||||
// Parse request body
|
||||
var req CreateAgentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Build agent object
|
||||
agent := &types.CustomAgent{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Avatar: req.Avatar,
|
||||
Config: req.Config,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating custom agent, name: %s, agent_mode: %s",
|
||||
secutils.SanitizeForLog(req.Name), req.Config.AgentMode)
|
||||
|
||||
// Create agent using the service
|
||||
createdAgent, err := h.service.CreateAgent(ctx, agent)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
if err == service.ErrAgentNameRequired {
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s",
|
||||
secutils.SanitizeForLog(createdAgent.ID), secutils.SanitizeForLog(createdAgent.Name))
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"success": true,
|
||||
"data": createdAgent,
|
||||
})
|
||||
}
|
||||
|
||||
// GetAgent godoc
|
||||
// @Summary 获取智能体详情
|
||||
// @Description 根据ID获取智能体详情
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Success 200 {object} map[string]interface{} "智能体详情"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "智能体不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id} [get]
|
||||
func (h *CustomAgentHandler) GetAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
agent, err := h.service.GetAgentByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
if err == service.ErrAgentNotFound {
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
return
|
||||
}
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": agent,
|
||||
})
|
||||
}
|
||||
|
||||
// ListAgents godoc
|
||||
// @Summary 获取智能体列表
|
||||
// @Description 获取当前租户的所有智能体(包括内置智能体)
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "智能体列表"
|
||||
// @Failure 500 {object} errors.AppError "服务器错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents [get]
|
||||
func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get all agents for this tenant
|
||||
agents, err := h.service.ListAgents(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": agents,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateAgent godoc
|
||||
// @Summary 更新智能体
|
||||
// @Description 更新智能体的名称、描述和配置
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Param request body UpdateAgentRequest true "更新请求"
|
||||
// @Success 200 {object} map[string]interface{} "更新后的智能体"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "无法修改内置智能体"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id} [put]
|
||||
func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start updating custom agent")
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var req UpdateAgentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Build agent object
|
||||
agent := &types.CustomAgent{
|
||||
ID: id,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Avatar: req.Avatar,
|
||||
Config: req.Config,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.Name))
|
||||
|
||||
// Update the agent
|
||||
updatedAgent, err := h.service.UpdateAgent(ctx, agent)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
switch err {
|
||||
case service.ErrAgentNotFound:
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
case service.ErrCannotModifyBuiltin:
|
||||
c.Error(errors.NewForbiddenError("Cannot modify built-in agent"))
|
||||
case service.ErrAgentNameRequired:
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
default:
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent updated successfully, ID: %s", secutils.SanitizeForLog(id))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": updatedAgent,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteAgent godoc
|
||||
// @Summary 删除智能体
|
||||
// @Description 删除指定的智能体
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Success 200 {object} map[string]interface{} "删除成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "无法删除内置智能体"
|
||||
// @Failure 404 {object} errors.AppError "智能体不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id} [delete]
|
||||
func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start deleting custom agent")
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Deleting custom agent, ID: %s", secutils.SanitizeForLog(id))
|
||||
|
||||
// Delete the agent
|
||||
err := h.service.DeleteAgent(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
switch err {
|
||||
case service.ErrAgentNotFound:
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
case service.ErrCannotDeleteBuiltin:
|
||||
c.Error(errors.NewForbiddenError("Cannot delete built-in agent"))
|
||||
default:
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", secutils.SanitizeForLog(id))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Agent deleted successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// CopyAgent godoc
|
||||
// @Summary 复制智能体
|
||||
// @Description 复制指定的智能体
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Success 201 {object} map[string]interface{} "复制成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "智能体不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id}/copy [post]
|
||||
func (h *CustomAgentHandler) CopyAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start copying custom agent")
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Copying custom agent, ID: %s", secutils.SanitizeForLog(id))
|
||||
|
||||
// Copy the agent
|
||||
copiedAgent, err := h.service.CopyAgent(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
switch err {
|
||||
case service.ErrAgentNotFound:
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
default:
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent copied successfully, source ID: %s, new ID: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(copiedAgent.ID))
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"success": true,
|
||||
"data": copiedAgent,
|
||||
})
|
||||
}
|
||||
|
||||
// GetPlaceholders godoc
|
||||
// @Summary 获取占位符定义
|
||||
// @Description 获取所有可用的提示词占位符定义,按字段类型分组
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "占位符定义"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/placeholders [get]
|
||||
func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
|
||||
// Return all placeholder definitions grouped by field type
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"all": types.AllPlaceholders(),
|
||||
"system_prompt": types.PlaceholdersByField(types.PromptFieldSystemPrompt),
|
||||
"agent_system_prompt": types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt),
|
||||
"context_template": types.PlaceholdersByField(types.PromptFieldContextTemplate),
|
||||
"rewrite_system_prompt": types.PlaceholdersByField(types.PromptFieldRewriteSystemPrompt),
|
||||
"rewrite_prompt": types.PlaceholdersByField(types.PromptFieldRewritePrompt),
|
||||
"fallback_prompt": types.PlaceholdersByField(types.PromptFieldFallbackPrompt),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
@@ -20,6 +19,7 @@ type Handler struct {
|
||||
streamManager interfaces.StreamManager // Manager for handling streaming responses
|
||||
config *config.Config // Application configuration
|
||||
knowledgebaseService interfaces.KnowledgeBaseService // Service for managing knowledge bases
|
||||
customAgentService interfaces.CustomAgentService // Service for managing custom agents
|
||||
}
|
||||
|
||||
// NewHandler creates a new instance of Handler with all necessary dependencies
|
||||
@@ -29,6 +29,7 @@ func NewHandler(
|
||||
streamManager interfaces.StreamManager,
|
||||
config *config.Config,
|
||||
knowledgebaseService interfaces.KnowledgeBaseService,
|
||||
customAgentService interfaces.CustomAgentService,
|
||||
) *Handler {
|
||||
return &Handler{
|
||||
sessionService: sessionService,
|
||||
@@ -36,6 +37,7 @@ func NewHandler(
|
||||
streamManager: streamManager,
|
||||
config: config,
|
||||
knowledgebaseService: knowledgebaseService,
|
||||
customAgentService: customAgentService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,75 +73,17 @@ func (h *Handler) CreateSession(c *gin.Context) {
|
||||
|
||||
// Validate session creation request
|
||||
// Sessions are now knowledge-base-independent:
|
||||
// - KnowledgeBaseID is optional during session creation
|
||||
// - Knowledge base can be specified in each query request (AgentQA/KnowledgeQA)
|
||||
// - Agent mode can access multiple knowledge bases via AgentConfig.KnowledgeBases
|
||||
// - Knowledge base can be switched during conversation
|
||||
isAgentMode := request.AgentConfig != nil && request.AgentConfig.AgentModeEnabled
|
||||
hasAgentKnowledgeBases := request.AgentConfig != nil && len(request.AgentConfig.KnowledgeBases) > 0
|
||||
|
||||
// - All configuration comes from custom agent at query time
|
||||
// - Session only stores basic info (tenant ID, title, etc.)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Processing session creation request, tenant ID: %d, knowledge base ID: %s, agent mode: %v, agent KBs: %v",
|
||||
"Processing session creation request, tenant ID: %d",
|
||||
tenantID,
|
||||
request.KnowledgeBaseID,
|
||||
isAgentMode,
|
||||
hasAgentKnowledgeBases,
|
||||
)
|
||||
|
||||
// Create session object with base properties
|
||||
createdSession := &types.Session{
|
||||
TenantID: tenantID.(uint64),
|
||||
KnowledgeBaseID: request.KnowledgeBaseID,
|
||||
AgentConfig: request.AgentConfig, // Set agent config if provided
|
||||
}
|
||||
|
||||
// If summary model parameters are empty, set defaults
|
||||
if request.SessionStrategy != nil {
|
||||
createdSession.RerankModelID = request.SessionStrategy.RerankModelID
|
||||
createdSession.SummaryModelID = request.SessionStrategy.SummaryModelID
|
||||
createdSession.MaxRounds = request.SessionStrategy.MaxRounds
|
||||
createdSession.EnableRewrite = request.SessionStrategy.EnableRewrite
|
||||
createdSession.FallbackStrategy = request.SessionStrategy.FallbackStrategy
|
||||
createdSession.FallbackResponse = request.SessionStrategy.FallbackResponse
|
||||
createdSession.EmbeddingTopK = request.SessionStrategy.EmbeddingTopK
|
||||
createdSession.KeywordThreshold = request.SessionStrategy.KeywordThreshold
|
||||
createdSession.VectorThreshold = request.SessionStrategy.VectorThreshold
|
||||
createdSession.RerankTopK = request.SessionStrategy.RerankTopK
|
||||
createdSession.RerankThreshold = request.SessionStrategy.RerankThreshold
|
||||
if request.SessionStrategy.SummaryParameters != nil {
|
||||
createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters
|
||||
} else {
|
||||
createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx)
|
||||
}
|
||||
h.fillSummaryConfigDefaults(ctx, createdSession.SummaryParameters)
|
||||
|
||||
logger.Debug(ctx, "Custom session strategy set")
|
||||
} else {
|
||||
tenantInfo, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
h.applyConversationDefaults(ctx, createdSession, tenantInfo)
|
||||
logger.Debug(ctx, "Using default session strategy")
|
||||
}
|
||||
|
||||
// Fetch knowledge base if KnowledgeBaseID is provided to inherit its model configurations
|
||||
// If no KB is provided, models will be determined at query time or use tenant/system defaults
|
||||
if request.KnowledgeBaseID != "" {
|
||||
kb, err := h.knowledgebaseService.GetKnowledgeBaseByID(ctx, request.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to get knowledge base", err)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Use knowledge base's summary model if session doesn't specify it
|
||||
if createdSession.SummaryModelID == "" {
|
||||
createdSession.SummaryModelID = kb.SummaryModelID
|
||||
}
|
||||
|
||||
logger.Debugf(ctx, "Knowledge base fetched: %s, summary model: %s",
|
||||
kb.ID, kb.SummaryModelID)
|
||||
} else {
|
||||
logger.Debug(ctx, "No knowledge base ID provided, models will use session strategy or be determined at query time")
|
||||
TenantID: tenantID.(uint64),
|
||||
}
|
||||
|
||||
// Call service to create session
|
||||
@@ -159,45 +103,6 @@ func (h *Handler) CreateSession(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) applyConversationDefaults(ctx context.Context, session *types.Session, tenant *types.Tenant) {
|
||||
session.MaxRounds = h.config.Conversation.MaxRounds
|
||||
session.EnableRewrite = h.config.Conversation.EnableRewrite
|
||||
session.FallbackStrategy = types.FallbackStrategy(h.config.Conversation.FallbackStrategy)
|
||||
session.FallbackResponse = h.config.Conversation.FallbackResponse
|
||||
session.EmbeddingTopK = h.config.Conversation.EmbeddingTopK
|
||||
session.KeywordThreshold = h.config.Conversation.KeywordThreshold
|
||||
session.VectorThreshold = h.config.Conversation.VectorThreshold
|
||||
session.RerankThreshold = h.config.Conversation.RerankThreshold
|
||||
session.RerankTopK = h.config.Conversation.RerankTopK
|
||||
session.RerankModelID = ""
|
||||
session.SummaryModelID = ""
|
||||
|
||||
if tenant != nil && tenant.ConversationConfig != nil {
|
||||
tc := tenant.ConversationConfig
|
||||
session.MaxRounds = tc.MaxRounds
|
||||
session.EnableRewrite = tc.EnableRewrite
|
||||
if tc.FallbackStrategy != "" {
|
||||
session.FallbackStrategy = types.FallbackStrategy(tc.FallbackStrategy)
|
||||
}
|
||||
if tc.FallbackResponse != "" {
|
||||
session.FallbackResponse = tc.FallbackResponse
|
||||
}
|
||||
session.EmbeddingTopK = tc.EmbeddingTopK
|
||||
session.KeywordThreshold = tc.KeywordThreshold
|
||||
session.VectorThreshold = tc.VectorThreshold
|
||||
session.RerankThreshold = tc.RerankThreshold
|
||||
session.RerankTopK = tc.RerankTopK
|
||||
if tc.RerankModelID != "" {
|
||||
session.RerankModelID = tc.RerankModelID
|
||||
}
|
||||
if tc.SummaryModelID != "" {
|
||||
session.SummaryModelID = tc.SummaryModelID
|
||||
}
|
||||
}
|
||||
|
||||
session.SummaryParameters = h.createDefaultSummaryConfig(ctx)
|
||||
}
|
||||
|
||||
// GetSession godoc
|
||||
// @Summary 获取会话详情
|
||||
// @Description 根据ID获取会话详情
|
||||
|
||||
@@ -203,20 +203,13 @@ func (h *Handler) createDefaultSummaryConfig(ctx context.Context) *types.Summary
|
||||
|
||||
// Override with tenant-level conversation config if available
|
||||
if tenant != nil && tenant.ConversationConfig != nil {
|
||||
useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt
|
||||
if !useSystemPrompt && tenant.ConversationConfig.Prompt != "" {
|
||||
// Backward compatibility: treat legacy configs without flag as custom
|
||||
useSystemPrompt = true
|
||||
}
|
||||
if useSystemPrompt && tenant.ConversationConfig.Prompt != "" {
|
||||
// Use custom prompt if provided
|
||||
if tenant.ConversationConfig.Prompt != "" {
|
||||
cfg.Prompt = tenant.ConversationConfig.Prompt
|
||||
}
|
||||
|
||||
useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate
|
||||
if !useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" {
|
||||
useContextTemplate = true
|
||||
}
|
||||
if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" {
|
||||
// Use custom context template if provided
|
||||
if tenant.ConversationConfig.ContextTemplate != "" {
|
||||
cfg.ContextTemplate = tenant.ConversationConfig.ContextTemplate
|
||||
}
|
||||
if tenant.ConversationConfig.Temperature > 0 {
|
||||
@@ -242,13 +235,13 @@ func (h *Handler) fillSummaryConfigDefaults(ctx context.Context, config *types.S
|
||||
var defaultMaxCompletionTokens int
|
||||
|
||||
if tenant != nil && tenant.ConversationConfig != nil {
|
||||
useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt
|
||||
if useSystemPrompt && tenant.ConversationConfig.Prompt != "" {
|
||||
// Use custom prompt if provided
|
||||
if tenant.ConversationConfig.Prompt != "" {
|
||||
defaultPrompt = tenant.ConversationConfig.Prompt
|
||||
}
|
||||
|
||||
useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate
|
||||
if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" {
|
||||
// Use custom context template if provided
|
||||
if tenant.ConversationConfig.ContextTemplate != "" {
|
||||
defaultContextTemplate = tenant.ConversationConfig.ContextTemplate
|
||||
}
|
||||
defaultTemperature = tenant.ConversationConfig.Temperature
|
||||
|
||||
+289
-452
@@ -16,6 +16,149 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// qaRequestContext holds all the common data needed for QA requests
|
||||
type qaRequestContext struct {
|
||||
ctx context.Context
|
||||
c *gin.Context
|
||||
sessionID string
|
||||
requestID string
|
||||
query string
|
||||
session *types.Session
|
||||
customAgent *types.CustomAgent
|
||||
assistantMessage *types.Message
|
||||
knowledgeBaseIDs []string
|
||||
knowledgeIDs []string
|
||||
summaryModelID string
|
||||
webSearchEnabled bool
|
||||
mentionedItems types.MentionedItems
|
||||
}
|
||||
|
||||
// parseQARequest parses and validates a QA request, returns the request context
|
||||
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
logger.Infof(ctx, "[%s] Start processing request", logPrefix)
|
||||
|
||||
// Get session ID from URL parameter
|
||||
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
||||
if sessionID == "" {
|
||||
logger.Error(ctx, "Session ID is empty")
|
||||
return nil, nil, errors.NewBadRequestError(errors.ErrInvalidSessionID.Error())
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var request CreateKnowledgeQARequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request data", err)
|
||||
return nil, nil, errors.NewBadRequestError(err.Error())
|
||||
}
|
||||
|
||||
// Validate query content
|
||||
if request.Query == "" {
|
||||
logger.Error(ctx, "Query content is empty")
|
||||
return nil, nil, errors.NewBadRequestError("Query content cannot be empty")
|
||||
}
|
||||
|
||||
// Log request details
|
||||
if requestJSON, err := json.Marshal(request); err == nil {
|
||||
logger.Infof(ctx, "[%s] Request: session_id=%s, request=%s",
|
||||
logPrefix, sessionID, secutils.SanitizeForLog(string(requestJSON)))
|
||||
}
|
||||
|
||||
// Get session
|
||||
session, err := h.sessionService.GetSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
|
||||
return nil, nil, errors.NewNotFoundError("Session not found")
|
||||
}
|
||||
|
||||
// Get custom agent if agent_id is provided
|
||||
var customAgent *types.CustomAgent
|
||||
if request.AgentID != "" {
|
||||
logger.Infof(ctx, "Fetching custom agent, agent ID: %s", secutils.SanitizeForLog(request.AgentID))
|
||||
agent, err := h.customAgentService.GetAgentByID(ctx, request.AgentID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
|
||||
secutils.SanitizeForLog(request.AgentID), err)
|
||||
} else {
|
||||
customAgent = agent
|
||||
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s",
|
||||
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode)
|
||||
}
|
||||
}
|
||||
|
||||
// Build request context
|
||||
reqCtx := &qaRequestContext{
|
||||
ctx: ctx,
|
||||
c: c,
|
||||
sessionID: sessionID,
|
||||
requestID: secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String())),
|
||||
query: secutils.SanitizeForLog(request.Query),
|
||||
session: session,
|
||||
customAgent: customAgent,
|
||||
assistantMessage: &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
},
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(request.KnowledgeBaseIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(request.KnowledgeIds),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
mentionedItems: convertMentionedItems(request.MentionedItems),
|
||||
}
|
||||
|
||||
return reqCtx, &request, nil
|
||||
}
|
||||
|
||||
// sseStreamContext holds the context for SSE streaming
|
||||
type sseStreamContext struct {
|
||||
eventBus *event.EventBus
|
||||
asyncCtx context.Context
|
||||
cancel context.CancelFunc
|
||||
assistantMessage *types.Message
|
||||
}
|
||||
|
||||
// setupSSEStream sets up the SSE streaming context
|
||||
func (h *Handler) setupSSEStream(reqCtx *qaRequestContext) *sseStreamContext {
|
||||
// Set SSE headers
|
||||
setSSEHeaders(reqCtx.c)
|
||||
|
||||
// Write initial agent_query event
|
||||
h.writeAgentQueryEvent(reqCtx.ctx, reqCtx.sessionID, reqCtx.assistantMessage.ID)
|
||||
|
||||
// Create EventBus and cancellable context
|
||||
eventBus := event.NewEventBus()
|
||||
asyncCtx, cancel := context.WithCancel(logger.CloneContext(reqCtx.ctx))
|
||||
|
||||
streamCtx := &sseStreamContext{
|
||||
eventBus: eventBus,
|
||||
asyncCtx: asyncCtx,
|
||||
cancel: cancel,
|
||||
assistantMessage: reqCtx.assistantMessage,
|
||||
}
|
||||
|
||||
// Setup stop event handler
|
||||
h.setupStopEventHandler(eventBus, reqCtx.sessionID, reqCtx.assistantMessage, cancel)
|
||||
|
||||
// Setup stream handler
|
||||
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
|
||||
reqCtx.requestID, reqCtx.assistantMessage, eventBus)
|
||||
|
||||
// Generate title if needed
|
||||
if reqCtx.session.Title == "" {
|
||||
// Use the same model as the conversation for title generation
|
||||
modelID := ""
|
||||
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ModelID != "" {
|
||||
modelID = reqCtx.customAgent.Config.ModelID
|
||||
}
|
||||
logger.Infof(reqCtx.ctx, "Session has no title, starting async title generation, session ID: %s, model: %s", reqCtx.sessionID, modelID)
|
||||
h.sessionService.GenerateTitleAsync(asyncCtx, reqCtx.session, reqCtx.query, modelID, eventBus)
|
||||
}
|
||||
|
||||
return streamCtx
|
||||
}
|
||||
|
||||
// SearchKnowledge godoc
|
||||
// @Summary 知识搜索
|
||||
// @Description 在知识库中搜索(不使用LLM总结)
|
||||
@@ -30,7 +173,6 @@ import (
|
||||
// @Router /sessions/search [post]
|
||||
func (h *Handler) SearchKnowledge(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
logger.Info(ctx, "Start processing knowledge search request")
|
||||
|
||||
// Parse request body
|
||||
@@ -87,8 +229,6 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge search completed, found %d results", len(searchResults))
|
||||
|
||||
// Return search results
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": searchResults,
|
||||
@@ -109,73 +249,15 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{session_id}/knowledge-qa [post]
|
||||
func (h *Handler) KnowledgeQA(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
logger.Info(ctx, "Start processing knowledge QA request")
|
||||
|
||||
// Get session ID from URL parameter
|
||||
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
||||
if sessionID == "" {
|
||||
logger.Error(ctx, "Session ID is empty")
|
||||
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var request CreateKnowledgeQARequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request data", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message
|
||||
assistantMessage := &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
}
|
||||
|
||||
// Validate query content
|
||||
if request.Query == "" {
|
||||
logger.Error(ctx, "Query content is empty")
|
||||
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge QA request, session ID: %s, query: %s",
|
||||
sessionID,
|
||||
secutils.SanitizeForLog(request.Query),
|
||||
)
|
||||
|
||||
// Get session to prepare knowledge base IDs
|
||||
session, err := h.sessionService.GetSession(ctx, sessionID)
|
||||
// Parse and validate request
|
||||
reqCtx, _, err := h.parseQARequest(c, "KnowledgeQA")
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Prepare knowledge base IDs
|
||||
knowledgeBaseIDs := request.KnowledgeBaseIDs
|
||||
// if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" {
|
||||
// knowledgeBaseIDs = []string{session.KnowledgeBaseID}
|
||||
// logger.Infof(
|
||||
// ctx,
|
||||
// "No knowledge base IDs in request, using session default: %s",
|
||||
// secutils.SanitizeForLog(session.KnowledgeBaseID),
|
||||
// )
|
||||
// }
|
||||
|
||||
// Use shared function to handle KnowledgeQA request
|
||||
h.handleKnowledgeQARequest(ctx, c, session, secutils.SanitizeForLog(request.Query),
|
||||
secutils.SanitizeForLogArray(knowledgeBaseIDs),
|
||||
secutils.SanitizeForLogArray(request.KnowledgeIds),
|
||||
assistantMessage, true, secutils.SanitizeForLog(request.SummaryModelID), request.WebSearchEnabled,
|
||||
convertMentionedItems(request.MentionedItems))
|
||||
// Execute normal mode QA
|
||||
h.executeNormalModeQA(reqCtx, true)
|
||||
}
|
||||
|
||||
// AgentQA godoc
|
||||
@@ -192,427 +274,100 @@ func (h *Handler) KnowledgeQA(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{session_id}/agent-qa [post]
|
||||
func (h *Handler) AgentQA(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
logger.Info(ctx, "Start processing agent QA request")
|
||||
|
||||
// Get session ID from URL parameter
|
||||
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
||||
if sessionID == "" {
|
||||
logger.Error(ctx, "Session ID is empty")
|
||||
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
|
||||
// Parse and validate request
|
||||
reqCtx, request, err := h.parseQARequest(c, "AgentQA")
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var request CreateKnowledgeQARequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request data", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
// Determine if agent mode should be enabled
|
||||
// Priority: customAgent.IsAgentMode() > request.AgentEnabled
|
||||
agentModeEnabled := request.AgentEnabled
|
||||
if reqCtx.customAgent != nil {
|
||||
agentModeEnabled = reqCtx.customAgent.IsAgentMode()
|
||||
logger.Infof(reqCtx.ctx, "Agent mode determined by custom agent: %v (config.agent_mode=%s)",
|
||||
agentModeEnabled, reqCtx.customAgent.Config.AgentMode)
|
||||
}
|
||||
if requestJSON, err := json.Marshal(request); err == nil {
|
||||
logger.Infof(ctx, "Agent QA request, request: %s", secutils.SanitizeForLog(string(requestJSON)))
|
||||
|
||||
// Route to appropriate handler based on agent mode
|
||||
if agentModeEnabled {
|
||||
h.executeAgentModeQA(reqCtx)
|
||||
} else {
|
||||
logger.Warnf(ctx, "failed to marshal for logging: %s", secutils.SanitizeForLog(err.Error()))
|
||||
logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID)
|
||||
// Knowledge bases should be specified in request or from custom agent
|
||||
h.executeNormalModeQA(reqCtx, false)
|
||||
}
|
||||
|
||||
// Validate query content
|
||||
if request.Query == "" {
|
||||
logger.Error(ctx, "Query content is empty")
|
||||
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
|
||||
// Get session information first
|
||||
session, err := h.sessionService.GetSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
|
||||
c.Error(errors.NewNotFoundError("Session not found"))
|
||||
return
|
||||
}
|
||||
sessionJSON, err := json.Marshal(session)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Before AgentQA, Session: %s", secutils.SanitizeForLog(string(sessionJSON)))
|
||||
|
||||
// Create assistant message
|
||||
assistantMessage := &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
}
|
||||
|
||||
// Initialize AgentConfig if it doesn't exist
|
||||
if session.AgentConfig == nil {
|
||||
session.AgentConfig = &types.SessionAgentConfig{}
|
||||
}
|
||||
|
||||
// Detect if knowledge bases or agent mode has changed
|
||||
knowledgeBasesChanged := false
|
||||
knowledgeIdsChanged := false
|
||||
configChanged := false
|
||||
|
||||
// Check if knowledge bases array has changed
|
||||
if len(request.KnowledgeBaseIDs) > 0 || len(session.AgentConfig.KnowledgeBases) > 0 {
|
||||
// Compare arrays to detect changes
|
||||
currentKBs := session.AgentConfig.KnowledgeBases
|
||||
if len(currentKBs) != len(request.KnowledgeBaseIDs) {
|
||||
knowledgeBasesChanged = true
|
||||
configChanged = true
|
||||
} else {
|
||||
// Check if contents are different
|
||||
kbMap := make(map[string]bool)
|
||||
for _, kb := range currentKBs {
|
||||
kbMap[kb] = true
|
||||
}
|
||||
for _, kb := range request.KnowledgeBaseIDs {
|
||||
if !kbMap[kb] {
|
||||
knowledgeBasesChanged = true
|
||||
configChanged = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if knowledgeBasesChanged {
|
||||
logger.Infof(ctx, "Knowledge bases changed from %s to %s",
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeBases)),
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeBaseIDs)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if knowledge IDs array has changed
|
||||
if len(request.KnowledgeIds) > 0 || len(session.AgentConfig.KnowledgeIDs) > 0 {
|
||||
// Compare arrays to detect changes
|
||||
currentKIDs := session.AgentConfig.KnowledgeIDs
|
||||
if len(currentKIDs) != len(request.KnowledgeIds) {
|
||||
knowledgeIdsChanged = true
|
||||
configChanged = true
|
||||
} else {
|
||||
// Check if contents are different
|
||||
kidMap := make(map[string]bool)
|
||||
for _, kid := range currentKIDs {
|
||||
kidMap[kid] = true
|
||||
}
|
||||
for _, kid := range request.KnowledgeIds {
|
||||
if !kidMap[kid] {
|
||||
knowledgeIdsChanged = true
|
||||
configChanged = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if knowledgeIdsChanged {
|
||||
logger.Infof(ctx, "Knowledge IDs changed from %s to %s",
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeIDs)),
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeIds)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if agent mode has changed
|
||||
currentAgentEnabled := session.AgentConfig.AgentModeEnabled
|
||||
if request.AgentEnabled != currentAgentEnabled {
|
||||
logger.Infof(ctx, "Agent mode changed from %v to %v", currentAgentEnabled, request.AgentEnabled)
|
||||
configChanged = true
|
||||
}
|
||||
currentWebSearchEnabled := session.AgentConfig.WebSearchEnabled
|
||||
if request.WebSearchEnabled != currentWebSearchEnabled {
|
||||
logger.Infof(ctx, "Web search mode changed from %v to %v", currentWebSearchEnabled, request.WebSearchEnabled)
|
||||
configChanged = true
|
||||
}
|
||||
summaryModelID := secutils.SanitizeForLog(request.SummaryModelID)
|
||||
if summaryModelID == "" {
|
||||
summaryModelID = session.SummaryModelID
|
||||
}
|
||||
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
|
||||
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
|
||||
}
|
||||
if summaryModelID != session.SummaryModelID {
|
||||
configChanged = true
|
||||
session.SummaryModelID = summaryModelID
|
||||
}
|
||||
|
||||
// If configuration changed, clear context and update session
|
||||
if configChanged {
|
||||
logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID)
|
||||
// Clear the LLM context to prevent contamination
|
||||
if err := h.sessionService.ClearContext(ctx, sessionID); err != nil {
|
||||
logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err)
|
||||
// Continue anyway - this is not a fatal error
|
||||
}
|
||||
if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil {
|
||||
logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err)
|
||||
// Continue anyway - this is not a fatal error
|
||||
}
|
||||
session.AgentConfig.KnowledgeBases = secutils.SanitizeForLogArray(request.KnowledgeBaseIDs)
|
||||
session.AgentConfig.KnowledgeIDs = secutils.SanitizeForLogArray(request.KnowledgeIds)
|
||||
session.AgentConfig.AgentModeEnabled = request.AgentEnabled
|
||||
session.AgentConfig.WebSearchEnabled = request.WebSearchEnabled
|
||||
session.SummaryModelID = secutils.SanitizeForLog(summaryModelID)
|
||||
// Persist the session changes
|
||||
if err := h.sessionService.UpdateSession(ctx, session); err != nil {
|
||||
logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err)
|
||||
c.Error(errors.NewInternalServerError("Failed to update session configuration"))
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID)
|
||||
}
|
||||
|
||||
// If Agent mode is disabled, delegate to KnowledgeQA
|
||||
if !request.AgentEnabled {
|
||||
logger.Infof(ctx, "Agent mode disabled, delegating to KnowledgeQA for session: %s", sessionID)
|
||||
|
||||
// Use knowledge bases from request or session config
|
||||
knowledgeBaseIDs := secutils.SanitizeForLogArray(request.KnowledgeBaseIDs)
|
||||
if len(knowledgeBaseIDs) == 0 {
|
||||
knowledgeBaseIDs = session.AgentConfig.KnowledgeBases
|
||||
}
|
||||
|
||||
// If still empty, use session default knowledge base
|
||||
if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" {
|
||||
knowledgeBaseIDs = []string{session.KnowledgeBaseID}
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Using session default knowledge base: %s",
|
||||
secutils.SanitizeForLog(session.KnowledgeBaseID),
|
||||
)
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Delegating to KnowledgeQA with knowledge bases: %s",
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs)),
|
||||
)
|
||||
|
||||
// Use shared function to handle KnowledgeQA request (no title generation for AgentQA fallback)
|
||||
h.handleKnowledgeQARequest(
|
||||
ctx,
|
||||
c,
|
||||
session,
|
||||
secutils.SanitizeForLog(request.Query),
|
||||
secutils.SanitizeForLogArray(
|
||||
knowledgeBaseIDs,
|
||||
),
|
||||
secutils.SanitizeForLogArray(
|
||||
request.KnowledgeIds,
|
||||
),
|
||||
assistantMessage,
|
||||
false,
|
||||
secutils.SanitizeForLog(request.SummaryModelID),
|
||||
request.WebSearchEnabled,
|
||||
convertMentionedItems(request.MentionedItems),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Emit agent query event to create user message
|
||||
requestID := secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String()))
|
||||
if err := event.Emit(ctx, event.Event{
|
||||
Type: event.EventAgentQuery,
|
||||
SessionID: sessionID,
|
||||
RequestID: requestID,
|
||||
Data: event.AgentQueryData{
|
||||
SessionID: sessionID,
|
||||
Query: secutils.SanitizeForLog(request.Query),
|
||||
RequestID: requestID,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Set headers for SSE immediately
|
||||
setSSEHeaders(c)
|
||||
|
||||
// Create user message
|
||||
if err := h.createUserMessage(ctx, sessionID, secutils.SanitizeForLog(request.Query), requestID, convertMentionedItems(request.MentionedItems)); err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message (response)
|
||||
assistantMessagePtr, err := h.createAssistantMessage(ctx, assistantMessage)
|
||||
if err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
assistantMessage = assistantMessagePtr
|
||||
|
||||
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
|
||||
|
||||
// Write initial agent_query event to StreamManager
|
||||
h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID)
|
||||
|
||||
eventBus := event.NewEventBus()
|
||||
// Create cancellable context for async operations
|
||||
asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx))
|
||||
// Create and subscribe stream handler
|
||||
h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus)
|
||||
|
||||
// Start async title generation if session has no title
|
||||
if session.Title == "" {
|
||||
logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID)
|
||||
h.sessionService.GenerateTitleAsync(asyncCtx, session, secutils.SanitizeForLog(request.Query), eventBus)
|
||||
}
|
||||
|
||||
// Register stop event handler to cancel the context
|
||||
h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel)
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 1024)
|
||||
runtime.Stack(buf, true)
|
||||
logger.ErrorWithFields(asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))),
|
||||
map[string]interface{}{
|
||||
"session_id": sessionID,
|
||||
})
|
||||
}
|
||||
h.completeAssistantMessage(asyncCtx, assistantMessage)
|
||||
logger.Infof(asyncCtx, "Agent QA service completed for session: %s", sessionID)
|
||||
}()
|
||||
err := h.sessionService.AgentQA(
|
||||
asyncCtx,
|
||||
session,
|
||||
secutils.SanitizeForLog(request.Query),
|
||||
assistantMessage.ID,
|
||||
eventBus,
|
||||
)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(asyncCtx, err, nil)
|
||||
// Emit error event to dedicated EventBus
|
||||
eventBus.Emit(asyncCtx, event.Event{
|
||||
Type: event.EventError,
|
||||
SessionID: sessionID,
|
||||
Data: event.ErrorData{
|
||||
Error: err.Error(),
|
||||
Stage: "agent_execution",
|
||||
SessionID: sessionID,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle events for SSE (blocking until connection is done)
|
||||
// Wait for title only if session has no title (first message in session)
|
||||
h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "")
|
||||
}
|
||||
|
||||
// handleKnowledgeQARequest handles a KnowledgeQA request with the given parameters
|
||||
// This is a shared function used by both KnowledgeQA endpoint and AgentQA fallback
|
||||
func (h *Handler) handleKnowledgeQARequest(
|
||||
ctx context.Context,
|
||||
c *gin.Context,
|
||||
session *types.Session,
|
||||
query string,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
assistantMessage *types.Message,
|
||||
generateTitle bool, // Whether to generate title if session has no title
|
||||
summaryModelID string, // Optional summary model ID (overrides session default)
|
||||
webSearchEnabled bool, // Whether web search is enabled
|
||||
mentionedItems types.MentionedItems, // @mentioned knowledge bases and files
|
||||
) {
|
||||
sessionID := session.ID
|
||||
requestID := getRequestID(c)
|
||||
// executeNormalModeQA executes the normal (KnowledgeQA) mode
|
||||
func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle bool) {
|
||||
ctx := reqCtx.ctx
|
||||
sessionID := reqCtx.sessionID
|
||||
|
||||
// Create user message
|
||||
if err := h.createUserMessage(ctx, sessionID, query, requestID, mentionedItems); err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message (response)
|
||||
if _, err := h.createAssistantMessage(ctx, assistantMessage); err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
// Create assistant message
|
||||
if _, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage); err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Using knowledge bases: %s", secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs)))
|
||||
logger.Infof(ctx, "Using knowledge bases: %v", reqCtx.knowledgeBaseIDs)
|
||||
|
||||
// Set headers for SSE
|
||||
setSSEHeaders(c)
|
||||
// Setup SSE stream
|
||||
streamCtx := h.setupSSEStream(reqCtx)
|
||||
|
||||
// Write initial agent_query event to StreamManager
|
||||
h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID)
|
||||
|
||||
// Create dedicated EventBus for this request
|
||||
eventBus := event.NewEventBus()
|
||||
// Create cancellable context for async operations
|
||||
asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx))
|
||||
|
||||
// Register stop event handler and setup stream handler
|
||||
h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel)
|
||||
h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus)
|
||||
|
||||
// Generate title if needed
|
||||
if generateTitle && session.Title == "" {
|
||||
logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID)
|
||||
h.sessionService.GenerateTitleAsync(asyncCtx, session, query, eventBus)
|
||||
}
|
||||
|
||||
eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
|
||||
// Setup completion handler for normal mode
|
||||
streamCtx.eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.AgentFinalAnswerData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
assistantMessage.Content += data.Content
|
||||
streamCtx.assistantMessage.Content += data.Content
|
||||
if data.Done {
|
||||
logger.Infof(asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
|
||||
h.completeAssistantMessage(asyncCtx, assistantMessage)
|
||||
// Emit completion event when stream finishes
|
||||
if err := eventBus.Emit(asyncCtx, event.Event{
|
||||
logger.Infof(streamCtx.asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
|
||||
h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage)
|
||||
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
||||
Type: event.EventAgentComplete,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentCompleteData{
|
||||
FinalAnswer: assistantMessage.Content,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(asyncCtx, "Failed to emit completion event: %v", err)
|
||||
}
|
||||
cancel() // Clean up context
|
||||
return nil
|
||||
Data: event.AgentCompleteData{FinalAnswer: streamCtx.assistantMessage.Content},
|
||||
})
|
||||
streamCtx.cancel()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// Call service to perform knowledge QA (async, emits events)
|
||||
// Execute KnowledgeQA asynchronously
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 10240)
|
||||
runtime.Stack(buf, true)
|
||||
logger.ErrorWithFields(
|
||||
asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))),
|
||||
nil,
|
||||
)
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))), nil)
|
||||
}
|
||||
}()
|
||||
|
||||
err := h.sessionService.KnowledgeQA(
|
||||
asyncCtx,
|
||||
session,
|
||||
query,
|
||||
knowledgeBaseIDs,
|
||||
knowledgeIDs,
|
||||
assistantMessage.ID,
|
||||
summaryModelID,
|
||||
webSearchEnabled,
|
||||
eventBus,
|
||||
streamCtx.asyncCtx,
|
||||
reqCtx.session,
|
||||
reqCtx.query,
|
||||
reqCtx.knowledgeBaseIDs,
|
||||
reqCtx.knowledgeIDs,
|
||||
reqCtx.assistantMessage.ID,
|
||||
reqCtx.summaryModelID,
|
||||
reqCtx.webSearchEnabled,
|
||||
streamCtx.eventBus,
|
||||
reqCtx.customAgent,
|
||||
)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(asyncCtx, err, nil)
|
||||
// Emit error event to dedicated EventBus
|
||||
eventBus.Emit(asyncCtx, event.Event{
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
|
||||
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
||||
Type: event.EventError,
|
||||
SessionID: sessionID,
|
||||
Data: event.ErrorData{
|
||||
@@ -621,13 +376,95 @@ func (h *Handler) handleKnowledgeQARequest(
|
||||
SessionID: sessionID,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle events for SSE (blocking until connection is done)
|
||||
// Wait for title only if session has no title (first message in session)
|
||||
h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "")
|
||||
// Handle SSE events (blocking)
|
||||
shouldWaitForTitle := generateTitle && reqCtx.session.Title == ""
|
||||
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
|
||||
reqCtx.requestID, streamCtx.eventBus, shouldWaitForTitle)
|
||||
}
|
||||
|
||||
// executeAgentModeQA executes the agent mode
|
||||
func (h *Handler) executeAgentModeQA(reqCtx *qaRequestContext) {
|
||||
ctx := reqCtx.ctx
|
||||
sessionID := reqCtx.sessionID
|
||||
|
||||
// Emit agent query event
|
||||
if err := event.Emit(ctx, event.Event{
|
||||
Type: event.EventAgentQuery,
|
||||
SessionID: sessionID,
|
||||
RequestID: reqCtx.requestID,
|
||||
Data: event.AgentQueryData{
|
||||
SessionID: sessionID,
|
||||
Query: reqCtx.query,
|
||||
RequestID: reqCtx.requestID,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Create user message
|
||||
if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message
|
||||
assistantMessagePtr, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage)
|
||||
if err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
reqCtx.assistantMessage = assistantMessagePtr
|
||||
|
||||
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
|
||||
|
||||
// Setup SSE stream
|
||||
streamCtx := h.setupSSEStream(reqCtx)
|
||||
|
||||
// Execute AgentQA asynchronously
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 1024)
|
||||
runtime.Stack(buf, true)
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))),
|
||||
map[string]interface{}{"session_id": sessionID})
|
||||
}
|
||||
h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage)
|
||||
logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)
|
||||
}()
|
||||
|
||||
err := h.sessionService.AgentQA(
|
||||
streamCtx.asyncCtx,
|
||||
reqCtx.session,
|
||||
reqCtx.query,
|
||||
reqCtx.assistantMessage.ID,
|
||||
streamCtx.eventBus,
|
||||
reqCtx.customAgent,
|
||||
reqCtx.knowledgeBaseIDs,
|
||||
reqCtx.knowledgeIDs,
|
||||
)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
|
||||
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
||||
Type: event.EventError,
|
||||
SessionID: sessionID,
|
||||
Data: event.ErrorData{
|
||||
Error: err.Error(),
|
||||
Stage: "agent_execution",
|
||||
SessionID: sessionID,
|
||||
},
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle SSE events (blocking)
|
||||
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
|
||||
reqCtx.requestID, streamCtx.eventBus, reqCtx.session.Title == "")
|
||||
}
|
||||
|
||||
// completeAssistantMessage marks an assistant message as complete and updates it
|
||||
|
||||
@@ -52,7 +52,7 @@ func (h *Handler) GenerateTitle(c *gin.Context) {
|
||||
|
||||
// Call service to generate title
|
||||
logger.Infof(ctx, "Generating session title, session ID: %s, message count: %d", sessionID, len(request.Messages))
|
||||
title, err := h.sessionService.GenerateTitle(ctx, session, request.Messages)
|
||||
title, err := h.sessionService.GenerateTitle(ctx, session, request.Messages, "")
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
|
||||
@@ -65,6 +65,7 @@ type CreateKnowledgeQARequest struct {
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
|
||||
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
|
||||
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
|
||||
AgentID string `json:"agent_id"` // Selected custom agent ID for this request
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
|
||||
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
|
||||
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
|
||||
|
||||
+85
-157
@@ -419,13 +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"`
|
||||
UseCustomPrompt *bool `json:"use_custom_system_prompt"`
|
||||
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
|
||||
@@ -473,45 +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
|
||||
// Get system prompt, use default if empty
|
||||
systemPrompt := tenant.AgentConfig.ResolveSystemPrompt(true) // webSearchEnabled doesn't matter for unified prompt
|
||||
if systemPrompt == "" {
|
||||
systemPrompt = agent.ProgressiveRAGSystemPrompt
|
||||
}
|
||||
systemPromptWithoutWeb := tenant.AgentConfig.ResolveSystemPrompt(false)
|
||||
if systemPromptWithoutWeb == "" {
|
||||
systemPromptWithoutWeb = agent.ProgressiveRAGSystemPromptWithoutWeb
|
||||
}
|
||||
|
||||
useCustomPrompt := tenant.AgentConfig.UseCustomSystemPrompt
|
||||
|
||||
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,
|
||||
"use_custom_system_prompt": useCustomPrompt,
|
||||
"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,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -546,25 +536,21 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
// Update agent configuration
|
||||
useCustomPrompt := false
|
||||
if tenant.AgentConfig != nil {
|
||||
useCustomPrompt = tenant.AgentConfig.UseCustomSystemPrompt
|
||||
}
|
||||
if req.UseCustomPrompt != nil {
|
||||
useCustomPrompt = *req.UseCustomPrompt
|
||||
// Determine if using custom prompt based on whether custom prompts are set
|
||||
// Support both new unified SystemPrompt and deprecated separate prompts
|
||||
systemPrompt := req.SystemPrompt
|
||||
useCustomPrompt := systemPrompt != ""
|
||||
|
||||
agentConfig := &types.AgentConfig{
|
||||
MaxIterations: req.MaxIterations,
|
||||
ReflectionEnabled: req.ReflectionEnabled,
|
||||
AllowedTools: agenttools.DefaultAllowedTools(),
|
||||
Temperature: req.Temperature,
|
||||
SystemPrompt: systemPrompt,
|
||||
UseCustomSystemPrompt: useCustomPrompt,
|
||||
}
|
||||
|
||||
tenant.AgentConfig = &types.AgentConfig{
|
||||
MaxIterations: req.MaxIterations,
|
||||
ReflectionEnabled: req.ReflectionEnabled,
|
||||
AllowedTools: agenttools.DefaultAllowedTools(),
|
||||
Temperature: req.Temperature,
|
||||
SystemPromptWebEnabled: req.SystemPromptWebEnabled,
|
||||
SystemPromptWebDisabled: req.SystemPromptWebDisabled,
|
||||
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)
|
||||
@@ -579,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",
|
||||
})
|
||||
}
|
||||
@@ -610,6 +596,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
|
||||
case "conversation-config":
|
||||
h.GetTenantConversationConfig(c)
|
||||
return
|
||||
case "prompt-templates":
|
||||
h.GetPromptTemplates(c)
|
||||
return
|
||||
default:
|
||||
logger.Info(ctx, "KV key not supported", "key", key)
|
||||
c.Error(errors.NewBadRequestError("unsupported key"))
|
||||
@@ -726,25 +715,23 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
|
||||
|
||||
func (h *TenantHandler) buildDefaultConversationConfig() *types.ConversationConfig {
|
||||
return &types.ConversationConfig{
|
||||
Prompt: h.config.Conversation.Summary.Prompt,
|
||||
ContextTemplate: h.config.Conversation.Summary.ContextTemplate,
|
||||
UseCustomContextTemplate: true,
|
||||
UseCustomSystemPrompt: true,
|
||||
Temperature: h.config.Conversation.Summary.Temperature,
|
||||
MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens,
|
||||
MaxRounds: h.config.Conversation.MaxRounds,
|
||||
EmbeddingTopK: h.config.Conversation.EmbeddingTopK,
|
||||
KeywordThreshold: h.config.Conversation.KeywordThreshold,
|
||||
VectorThreshold: h.config.Conversation.VectorThreshold,
|
||||
RerankTopK: h.config.Conversation.RerankTopK,
|
||||
RerankThreshold: h.config.Conversation.RerankThreshold,
|
||||
EnableRewrite: h.config.Conversation.EnableRewrite,
|
||||
EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion,
|
||||
FallbackStrategy: h.config.Conversation.FallbackStrategy,
|
||||
FallbackResponse: h.config.Conversation.FallbackResponse,
|
||||
FallbackPrompt: h.config.Conversation.FallbackPrompt,
|
||||
RewritePromptUser: h.config.Conversation.RewritePromptUser,
|
||||
RewritePromptSystem: h.config.Conversation.RewritePromptSystem,
|
||||
Prompt: h.config.Conversation.Summary.Prompt,
|
||||
ContextTemplate: h.config.Conversation.Summary.ContextTemplate,
|
||||
Temperature: h.config.Conversation.Summary.Temperature,
|
||||
MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens,
|
||||
MaxRounds: h.config.Conversation.MaxRounds,
|
||||
EmbeddingTopK: h.config.Conversation.EmbeddingTopK,
|
||||
KeywordThreshold: h.config.Conversation.KeywordThreshold,
|
||||
VectorThreshold: h.config.Conversation.VectorThreshold,
|
||||
RerankTopK: h.config.Conversation.RerankTopK,
|
||||
RerankThreshold: h.config.Conversation.RerankThreshold,
|
||||
EnableRewrite: h.config.Conversation.EnableRewrite,
|
||||
EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion,
|
||||
FallbackStrategy: h.config.Conversation.FallbackStrategy,
|
||||
FallbackResponse: h.config.Conversation.FallbackResponse,
|
||||
FallbackPrompt: h.config.Conversation.FallbackPrompt,
|
||||
RewritePromptUser: h.config.Conversation.RewritePromptUser,
|
||||
RewritePromptSystem: h.config.Conversation.RewritePromptSystem,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -803,91 +790,8 @@ func (h *TenantHandler) GetTenantConversationConfig(c *gin.Context) {
|
||||
|
||||
// If tenant has no conversation config, return defaults from config.yaml
|
||||
var response *types.ConversationConfig
|
||||
if tc := tenant.ConversationConfig; tc == nil {
|
||||
logger.Info(ctx, "Tenant has no conversation config, returning defaults")
|
||||
response = h.buildDefaultConversationConfig()
|
||||
} else {
|
||||
logger.Infof(ctx, "Tenant has conversation config, merging with defaults, Tenant ID: %d", tenant.ID)
|
||||
// Merge tenant config with defaults, so that newly added fields always have valid values
|
||||
defaultCfg := h.buildDefaultConversationConfig()
|
||||
// Prompt related
|
||||
defaultCfg.UseCustomSystemPrompt = tc.UseCustomSystemPrompt
|
||||
if !defaultCfg.UseCustomSystemPrompt && tc.Prompt != "" {
|
||||
// Legacy configs without explicit flag
|
||||
defaultCfg.UseCustomSystemPrompt = true
|
||||
}
|
||||
defaultCfg.UseCustomContextTemplate = tc.UseCustomContextTemplate
|
||||
if !defaultCfg.UseCustomContextTemplate && tc.ContextTemplate != "" {
|
||||
defaultCfg.UseCustomContextTemplate = true
|
||||
}
|
||||
if tc.Prompt != "" {
|
||||
defaultCfg.Prompt = tc.Prompt
|
||||
}
|
||||
if tc.ContextTemplate != "" {
|
||||
defaultCfg.ContextTemplate = tc.ContextTemplate
|
||||
}
|
||||
if tc.Temperature > 0 {
|
||||
defaultCfg.Temperature = tc.Temperature
|
||||
}
|
||||
if tc.MaxCompletionTokens > 0 {
|
||||
defaultCfg.MaxCompletionTokens = tc.MaxCompletionTokens
|
||||
}
|
||||
|
||||
// Retrieval parameters
|
||||
if tc.MaxRounds > 0 {
|
||||
defaultCfg.MaxRounds = tc.MaxRounds
|
||||
}
|
||||
if tc.EmbeddingTopK > 0 {
|
||||
defaultCfg.EmbeddingTopK = tc.EmbeddingTopK
|
||||
}
|
||||
if tc.KeywordThreshold > 0 {
|
||||
defaultCfg.KeywordThreshold = tc.KeywordThreshold
|
||||
}
|
||||
if tc.VectorThreshold > 0 {
|
||||
defaultCfg.VectorThreshold = tc.VectorThreshold
|
||||
}
|
||||
if tc.RerankTopK > 0 {
|
||||
defaultCfg.RerankTopK = tc.RerankTopK
|
||||
}
|
||||
if tc.RerankThreshold > 0 {
|
||||
defaultCfg.RerankThreshold = tc.RerankThreshold
|
||||
}
|
||||
// EnableRewrite 需要允许显式关闭,因此直接覆盖
|
||||
defaultCfg.EnableRewrite = tc.EnableRewrite
|
||||
|
||||
// Query expansion toggle
|
||||
defaultCfg.EnableQueryExpansion = tc.EnableQueryExpansion
|
||||
|
||||
// Model IDs
|
||||
if tc.SummaryModelID != "" {
|
||||
defaultCfg.SummaryModelID = tc.SummaryModelID
|
||||
}
|
||||
if tc.RerankModelID != "" {
|
||||
defaultCfg.RerankModelID = tc.RerankModelID
|
||||
}
|
||||
|
||||
// Fallback settings
|
||||
if tc.FallbackStrategy != "" {
|
||||
defaultCfg.FallbackStrategy = tc.FallbackStrategy
|
||||
}
|
||||
if tc.FallbackResponse != "" {
|
||||
defaultCfg.FallbackResponse = tc.FallbackResponse
|
||||
}
|
||||
if tc.FallbackPrompt != "" {
|
||||
defaultCfg.FallbackPrompt = tc.FallbackPrompt
|
||||
}
|
||||
|
||||
// Rewrite prompts
|
||||
if tc.RewritePromptSystem != "" {
|
||||
defaultCfg.RewritePromptSystem = tc.RewritePromptSystem
|
||||
}
|
||||
if tc.RewritePromptUser != "" {
|
||||
defaultCfg.RewritePromptUser = tc.RewritePromptUser
|
||||
}
|
||||
|
||||
response = defaultCfg
|
||||
}
|
||||
|
||||
logger.Info(ctx, "Tenant has no conversation config, returning defaults")
|
||||
response = h.buildDefaultConversationConfig()
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": response,
|
||||
@@ -943,3 +847,27 @@ func (h *TenantHandler) updateTenantConversationInternal(c *gin.Context) {
|
||||
"message": "Conversation configuration updated successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// GetPromptTemplates godoc
|
||||
// @Summary 获取提示词模板
|
||||
// @Description 获取系统配置的提示词模板列表
|
||||
// @Tags 租户管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "提示词模板配置"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /tenants/kv/prompt-templates [get]
|
||||
func (h *TenantHandler) GetPromptTemplates(c *gin.Context) {
|
||||
// Return prompt templates from config.yaml
|
||||
templates := h.config.PromptTemplates
|
||||
if templates == nil {
|
||||
templates = &config.PromptTemplatesConfig{}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": templates,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -208,12 +208,19 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
|
||||
"enable_thinking": thinking,
|
||||
}
|
||||
|
||||
// print req
|
||||
// jsonData, err := json.Marshal(req)
|
||||
// if err != nil {
|
||||
// logger.Error(context.Background(), "marshal request: %w", err)
|
||||
// }
|
||||
// logger.Infof(context.Background(), "llm request: %s", string(jsonData))
|
||||
// Log LLM request for debugging
|
||||
if jsonData, err := json.MarshalIndent(req, "", " "); err == nil {
|
||||
logger.Infof(context.Background(), "[LLM Request] model=%s, stream=%v, request:\n%s", c.modelName, isStream, string(jsonData))
|
||||
}
|
||||
|
||||
// Log tools/functions separately for clarity
|
||||
if len(req.Tools) > 0 {
|
||||
toolNames := make([]string, 0, len(req.Tools))
|
||||
for _, tool := range req.Tools {
|
||||
toolNames = append(toolNames, tool.Function.Name)
|
||||
}
|
||||
logger.Infof(context.Background(), "[LLM Request] tools_count=%d, tool_names=%v", len(req.Tools), toolNames)
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ type RouterParams struct {
|
||||
WebSearchHandler *handler.WebSearchHandler
|
||||
FAQHandler *handler.FAQHandler
|
||||
TagHandler *handler.TagHandler
|
||||
CustomAgentHandler *handler.CustomAgentHandler
|
||||
}
|
||||
|
||||
// NewRouter 创建新的路由
|
||||
@@ -110,6 +111,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterSystemRoutes(v1, params.SystemHandler)
|
||||
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler)
|
||||
RegisterWebSearchRoutes(v1, params.WebSearchHandler)
|
||||
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler)
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -412,3 +414,24 @@ func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSe
|
||||
webSearch.GET("/providers", webSearchHandler.GetProviders)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterCustomAgentRoutes registers custom agent routes
|
||||
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) {
|
||||
agents := r.Group("/agents")
|
||||
{
|
||||
// Get placeholder definitions (must be before /:id to avoid conflict)
|
||||
agents.GET("/placeholders", agentHandler.GetPlaceholders)
|
||||
// Create custom agent
|
||||
agents.POST("", agentHandler.CreateAgent)
|
||||
// List all agents (including built-in)
|
||||
agents.GET("", agentHandler.ListAgents)
|
||||
// Get agent by ID
|
||||
agents.GET("/:id", agentHandler.GetAgent)
|
||||
// Update agent
|
||||
agents.PUT("/:id", agentHandler.UpdateAgent)
|
||||
// Delete agent
|
||||
agents.DELETE("/:id", agentHandler.DeleteAgent)
|
||||
// Copy agent
|
||||
agents.POST("/:id/copy", agentHandler.CopyAgent)
|
||||
}
|
||||
}
|
||||
|
||||
+26
-12
@@ -10,18 +10,25 @@ 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)
|
||||
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")
|
||||
}
|
||||
|
||||
// SessionAgentConfig represents session-level agent configuration
|
||||
@@ -68,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +133,7 @@ func (c *ChatManage) Clone() *ChatManage {
|
||||
type EventType string
|
||||
|
||||
const (
|
||||
LOAD_HISTORY EventType = "load_history" // Load conversation history without rewriting
|
||||
REWRITE_QUERY EventType = "rewrite_query" // Query rewriting for better retrieval
|
||||
CHUNK_SEARCH EventType = "chunk_search" // Search for relevant chunks
|
||||
CHUNK_SEARCH_PARALLEL EventType = "chunk_search_parallel" // Parallel search: chunks + entities
|
||||
@@ -142,7 +152,12 @@ var Pipline = map[string][]EventType{
|
||||
"chat": { // Simple chat without retrieval
|
||||
CHAT_COMPLETION,
|
||||
},
|
||||
"chat_stream": { // Streaming chat without retrieval
|
||||
"chat_stream": { // Streaming chat without retrieval (no history)
|
||||
CHAT_COMPLETION_STREAM,
|
||||
STREAM_FILTER,
|
||||
},
|
||||
"chat_history_stream": { // Streaming chat with conversation history
|
||||
LOAD_HISTORY,
|
||||
CHAT_COMPLETION_STREAM,
|
||||
STREAM_FILTER,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,594 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// BuiltinAgentID constants for built-in agents
|
||||
const (
|
||||
// BuiltinQuickAnswerID is the ID for the built-in quick answer (RAG) agent
|
||||
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
|
||||
const (
|
||||
// AgentModeQuickAnswer is the RAG mode for quick Q&A
|
||||
AgentModeQuickAnswer = "quick-answer"
|
||||
// AgentModeSmartReasoning is the ReAct mode for multi-step reasoning
|
||||
AgentModeSmartReasoning = "smart-reasoning"
|
||||
)
|
||||
|
||||
// CustomAgent represents a configurable AI agent (similar to GPTs)
|
||||
type CustomAgent struct {
|
||||
// Unique identifier of the agent (composite primary key with TenantID)
|
||||
// For built-in agents, this is 'builtin-quick-answer' or 'builtin-smart-reasoning'
|
||||
// For custom agents, this is a UUID
|
||||
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Name of the agent
|
||||
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
|
||||
// Description of the agent
|
||||
Description string `yaml:"description" json:"description" gorm:"type:text"`
|
||||
// Avatar/Icon of the agent (emoji or icon name)
|
||||
Avatar string `yaml:"avatar" json:"avatar" gorm:"type:varchar(64)"`
|
||||
// Whether this is a built-in agent (normal mode / agent mode)
|
||||
IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"`
|
||||
// Tenant ID (composite primary key with ID)
|
||||
TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"primaryKey"`
|
||||
// Created by user ID
|
||||
CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"`
|
||||
|
||||
// Agent configuration
|
||||
Config CustomAgentConfig `yaml:"config" json:"config" gorm:"type:json"`
|
||||
|
||||
// Timestamps
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
|
||||
}
|
||||
|
||||
// CustomAgentConfig represents the configuration of a custom agent
|
||||
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 (unified prompt, uses {{web_search_status}} placeholder for dynamic behavior)
|
||||
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
|
||||
// Context template for normal mode (how to format retrieved chunks)
|
||||
ContextTemplate string `yaml:"context_template" json:"context_template"`
|
||||
|
||||
// ===== Model Settings =====
|
||||
// Model ID to use for conversations
|
||||
ModelID string `yaml:"model_id" json:"model_id"`
|
||||
// ReRank model ID for retrieval
|
||||
RerankModelID string `yaml:"rerank_model_id" json:"rerank_model_id"`
|
||||
// Temperature for LLM (0-1)
|
||||
Temperature float64 `yaml:"temperature" json:"temperature"`
|
||||
// Maximum completion tokens (only for normal mode)
|
||||
MaxCompletionTokens int `yaml:"max_completion_tokens" json:"max_completion_tokens"`
|
||||
|
||||
// ===== Agent Mode Settings =====
|
||||
// Maximum iterations for ReAct loop (only for agent type)
|
||||
MaxIterations int `yaml:"max_iterations" json:"max_iterations"`
|
||||
// Allowed tools (only for agent type)
|
||||
AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"`
|
||||
// Whether reflection is enabled (only for agent type)
|
||||
ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`
|
||||
// MCP service selection mode: "all" = all enabled MCP services, "selected" = specific services, "none" = no MCP
|
||||
MCPSelectionMode string `yaml:"mcp_selection_mode" json:"mcp_selection_mode"`
|
||||
// Selected MCP service IDs (only used when MCPSelectionMode is "selected")
|
||||
MCPServices []string `yaml:"mcp_services" json:"mcp_services"`
|
||||
|
||||
// ===== Knowledge Base Settings =====
|
||||
// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB
|
||||
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`
|
||||
// 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"`
|
||||
// Maximum web search results
|
||||
WebSearchMaxResults int `yaml:"web_search_max_results" json:"web_search_max_results"`
|
||||
|
||||
// ===== Multi-turn Conversation Settings =====
|
||||
// Whether multi-turn conversation is enabled
|
||||
MultiTurnEnabled bool `yaml:"multi_turn_enabled" json:"multi_turn_enabled"`
|
||||
// Number of history turns to keep in context
|
||||
HistoryTurns int `yaml:"history_turns" json:"history_turns"`
|
||||
|
||||
// ===== Retrieval Strategy Settings (for both modes) =====
|
||||
// Embedding/Vector retrieval top K
|
||||
EmbeddingTopK int `yaml:"embedding_top_k" json:"embedding_top_k"`
|
||||
// Keyword retrieval threshold
|
||||
KeywordThreshold float64 `yaml:"keyword_threshold" json:"keyword_threshold"`
|
||||
// Vector retrieval threshold
|
||||
VectorThreshold float64 `yaml:"vector_threshold" json:"vector_threshold"`
|
||||
// Rerank top K
|
||||
RerankTopK int `yaml:"rerank_top_k" json:"rerank_top_k"`
|
||||
// Rerank threshold
|
||||
RerankThreshold float64 `yaml:"rerank_threshold" json:"rerank_threshold"`
|
||||
|
||||
// ===== Advanced Settings (mainly for normal mode) =====
|
||||
// Whether to enable query expansion
|
||||
EnableQueryExpansion bool `yaml:"enable_query_expansion" json:"enable_query_expansion"`
|
||||
// Whether to enable query rewrite for multi-turn conversations
|
||||
EnableRewrite bool `yaml:"enable_rewrite" json:"enable_rewrite"`
|
||||
// Rewrite prompt system message
|
||||
RewritePromptSystem string `yaml:"rewrite_prompt_system" json:"rewrite_prompt_system"`
|
||||
// Rewrite prompt user message template
|
||||
RewritePromptUser string `yaml:"rewrite_prompt_user" json:"rewrite_prompt_user"`
|
||||
// Fallback strategy: "fixed" for fixed response, "model" for model generation
|
||||
FallbackStrategy string `yaml:"fallback_strategy" json:"fallback_strategy"`
|
||||
// Fixed fallback response (when FallbackStrategy is "fixed")
|
||||
FallbackResponse string `yaml:"fallback_response" json:"fallback_response"`
|
||||
// Fallback prompt (when FallbackStrategy is "model")
|
||||
FallbackPrompt string `yaml:"fallback_prompt" json:"fallback_prompt"`
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for CustomAgentConfig
|
||||
func (c CustomAgentConfig) Value() (driver.Value, error) {
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements sql.Scanner interface for CustomAgentConfig
|
||||
func (c *CustomAgentConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// TableName returns the table name for CustomAgent
|
||||
func (CustomAgent) TableName() string {
|
||||
return "custom_agents"
|
||||
}
|
||||
|
||||
// EnsureDefaults sets default values for the agent
|
||||
func (a *CustomAgent) EnsureDefaults() {
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
if a.Config.Temperature == 0 {
|
||||
a.Config.Temperature = 0.7
|
||||
}
|
||||
if a.Config.MaxIterations == 0 {
|
||||
a.Config.MaxIterations = 10
|
||||
}
|
||||
if a.Config.WebSearchMaxResults == 0 {
|
||||
a.Config.WebSearchMaxResults = 5
|
||||
}
|
||||
if a.Config.HistoryTurns == 0 {
|
||||
a.Config.HistoryTurns = 5
|
||||
}
|
||||
// Retrieval strategy defaults
|
||||
if a.Config.EmbeddingTopK == 0 {
|
||||
a.Config.EmbeddingTopK = 10
|
||||
}
|
||||
if a.Config.KeywordThreshold == 0 {
|
||||
a.Config.KeywordThreshold = 0.3
|
||||
}
|
||||
if a.Config.VectorThreshold == 0 {
|
||||
a.Config.VectorThreshold = 0.5
|
||||
}
|
||||
if a.Config.RerankTopK == 0 {
|
||||
a.Config.RerankTopK = 5
|
||||
}
|
||||
if a.Config.RerankThreshold == 0 {
|
||||
a.Config.RerankThreshold = 0.5
|
||||
}
|
||||
// Advanced settings defaults
|
||||
if a.Config.FallbackStrategy == "" {
|
||||
a.Config.FallbackStrategy = "model"
|
||||
}
|
||||
if a.Config.MaxCompletionTokens == 0 {
|
||||
a.Config.MaxCompletionTokens = 2048
|
||||
}
|
||||
// Agent mode should always enable multi-turn conversation
|
||||
if a.Config.AgentMode == AgentModeSmartReasoning {
|
||||
a.Config.MultiTurnEnabled = true
|
||||
}
|
||||
}
|
||||
|
||||
// IsAgentMode returns true if this agent uses ReAct agent mode
|
||||
func (a *CustomAgent) IsAgentMode() bool {
|
||||
return a.Config.AgentMode == AgentModeSmartReasoning
|
||||
}
|
||||
|
||||
// GetBuiltinQuickAnswerAgent returns the built-in quick answer (RAG) mode agent
|
||||
func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinQuickAnswerID,
|
||||
Name: "快速问答",
|
||||
Description: "基于知识库的 RAG 问答,快速准确地回答问题",
|
||||
IsBuiltin: true,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: AgentModeQuickAnswer,
|
||||
SystemPrompt: "",
|
||||
Temperature: 0.7,
|
||||
MaxCompletionTokens: 2048,
|
||||
WebSearchEnabled: true,
|
||||
WebSearchMaxResults: 5,
|
||||
MultiTurnEnabled: true,
|
||||
HistoryTurns: 5,
|
||||
KBSelectionMode: "all",
|
||||
// FAQ strategy
|
||||
FAQPriorityEnabled: true,
|
||||
FAQDirectAnswerThreshold: 0.9,
|
||||
FAQScoreBoost: 1.2,
|
||||
// Retrieval strategy
|
||||
EmbeddingTopK: 10,
|
||||
KeywordThreshold: 0.3,
|
||||
VectorThreshold: 0.5,
|
||||
RerankTopK: 10,
|
||||
RerankThreshold: 0.3,
|
||||
// Advanced settings
|
||||
EnableQueryExpansion: true,
|
||||
EnableRewrite: true,
|
||||
FallbackStrategy: "model",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetBuiltinSmartReasoningAgent returns the built-in smart reasoning (ReAct) mode agent
|
||||
func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinSmartReasoningID,
|
||||
Name: "智能推理",
|
||||
Description: "ReAct 推理框架,支持多步思考和工具调用",
|
||||
IsBuiltin: true,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: AgentModeSmartReasoning,
|
||||
SystemPrompt: "",
|
||||
Temperature: 0.7,
|
||||
MaxCompletionTokens: 2048,
|
||||
MaxIterations: 50,
|
||||
KBSelectionMode: "all",
|
||||
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
|
||||
WebSearchEnabled: true,
|
||||
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: 10,
|
||||
RerankThreshold: 0.3,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetBuiltinSmartReasoningAgent instead
|
||||
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
|
||||
return GetBuiltinSmartReasoningAgent(tenantID)
|
||||
}
|
||||
|
||||
// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension
|
||||
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
|
||||
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
|
||||
func GetBuiltinAgentIDs() []string {
|
||||
return builtinAgentIDsOrdered
|
||||
}
|
||||
|
||||
// IsBuiltinAgentID checks if the given ID is a built-in agent ID
|
||||
func IsBuiltinAgentID(id string) bool {
|
||||
_, exists := BuiltinAgentRegistry[id]
|
||||
return exists
|
||||
}
|
||||
|
||||
// GetBuiltinAgent returns a built-in agent by ID, or nil if not found
|
||||
func GetBuiltinAgent(id string, tenantID uint64) *CustomAgent {
|
||||
if factory, exists := BuiltinAgentRegistry[id]; exists {
|
||||
return factory(tenantID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -24,6 +24,10 @@ type ContextManager interface {
|
||||
|
||||
// GetContextStats returns statistics about the context
|
||||
GetContextStats(ctx context.Context, sessionID string) (*ContextStats, error)
|
||||
|
||||
// SetSystemPrompt sets or updates the system prompt for a session
|
||||
// If a system message exists, it will be replaced; otherwise, a new one will be added at the beginning
|
||||
SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error
|
||||
}
|
||||
|
||||
// ContextStats contains statistics about session context
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// Package interfaces defines the interface contracts for custom agent management
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// CustomAgentService defines the custom agent service interface
|
||||
// Provides high-level operations for agent creation, querying, updating, and deletion
|
||||
type CustomAgentService interface {
|
||||
// CreateAgent creates a new custom agent
|
||||
// Parameters:
|
||||
// - ctx: Context information, carrying request tracking, user identity, etc.
|
||||
// - agent: Agent object containing basic information and configuration
|
||||
// Returns:
|
||||
// - Created agent object (including automatically generated ID)
|
||||
// - Possible errors such as insufficient permissions, validation errors, etc.
|
||||
CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error)
|
||||
|
||||
// GetAgentByID retrieves agent information by ID
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Unique identifier of the agent
|
||||
// Returns:
|
||||
// - Agent object, if found (including built-in agents)
|
||||
// - Possible errors such as not existing, insufficient permissions, etc.
|
||||
GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error)
|
||||
|
||||
// ListAgents lists all agents under the current tenant (including built-in agents)
|
||||
// Parameters:
|
||||
// - ctx: Context information, containing tenant information
|
||||
// Returns:
|
||||
// - List of agent objects (built-in agents first, then custom agents sorted by creation time)
|
||||
// - Possible errors such as insufficient permissions, etc.
|
||||
ListAgents(ctx context.Context) ([]*types.CustomAgent, error)
|
||||
|
||||
// UpdateAgent updates agent information
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - agent: Agent object containing update information
|
||||
// Returns:
|
||||
// - Updated agent object
|
||||
// - Possible errors such as not existing, insufficient permissions, cannot modify built-in, etc.
|
||||
UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error)
|
||||
|
||||
// DeleteAgent deletes an agent
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Unique identifier of the agent
|
||||
// Returns:
|
||||
// - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc.
|
||||
DeleteAgent(ctx context.Context, id string) error
|
||||
|
||||
// CopyAgent creates a copy of an existing agent
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Unique identifier of the agent to copy
|
||||
// Returns:
|
||||
// - The newly created agent copy
|
||||
// - Possible errors such as not existing, insufficient permissions, etc.
|
||||
CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error)
|
||||
}
|
||||
|
||||
// CustomAgentRepository defines the custom agent repository interface
|
||||
// Responsible for agent data persistence and retrieval
|
||||
type CustomAgentRepository interface {
|
||||
// CreateAgent creates an agent record
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - agent: Agent object
|
||||
// Returns:
|
||||
// - Possible errors such as database connection failure, unique constraint conflicts, etc.
|
||||
CreateAgent(ctx context.Context, agent *types.CustomAgent) error
|
||||
|
||||
// GetAgentByID queries an agent by ID and tenant
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Agent ID
|
||||
// - tenantID: Tenant ID for isolation
|
||||
// Returns:
|
||||
// - Agent object, if found
|
||||
// - Possible errors such as record not existing, database errors, etc.
|
||||
GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error)
|
||||
|
||||
// ListAgentsByTenantID lists all agents for a specific tenant
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - tenantID: Tenant ID
|
||||
// Returns:
|
||||
// - List of agent objects
|
||||
// - Possible errors such as database errors, etc.
|
||||
ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error)
|
||||
|
||||
// UpdateAgent updates an agent record
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - agent: Agent object containing update information
|
||||
// Returns:
|
||||
// - Possible errors such as record not existing, database errors, etc.
|
||||
UpdateAgent(ctx context.Context, agent *types.CustomAgent) error
|
||||
|
||||
// DeleteAgent deletes an agent record
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Agent ID
|
||||
// - tenantID: Tenant ID for isolation (required for composite primary key)
|
||||
// Returns:
|
||||
// - Possible errors such as record not existing, database errors, etc.
|
||||
DeleteAgent(ctx context.Context, id string, tenantID uint64) error
|
||||
}
|
||||
@@ -22,19 +22,23 @@ type SessionService interface {
|
||||
// DeleteSession deletes a session
|
||||
DeleteSession(ctx context.Context, id string) error
|
||||
// GenerateTitle generates a title for the current conversation
|
||||
GenerateTitle(ctx context.Context, session *types.Session, messages []types.Message) (string, error)
|
||||
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
|
||||
GenerateTitle(ctx context.Context, session *types.Session, messages []types.Message, modelID string) (string, error)
|
||||
// GenerateTitleAsync generates a title for the session asynchronously
|
||||
// It emits an event when the title is generated
|
||||
GenerateTitleAsync(ctx context.Context, session *types.Session, userQuery string, eventBus *event.EventBus)
|
||||
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
|
||||
GenerateTitleAsync(ctx context.Context, session *types.Session, userQuery string, modelID string, eventBus *event.EventBus)
|
||||
// KnowledgeQA performs knowledge-based question answering
|
||||
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
|
||||
// knowledgeIDs: list of specific knowledge (file) IDs to search
|
||||
// summaryModelID: optional summary model ID override (if empty, uses session/KB default)
|
||||
// webSearchEnabled: whether to enable web search to supplement knowledge base results
|
||||
// customAgent: optional custom agent for config override (multiTurnEnabled, historyTurns)
|
||||
// Events are emitted through eventBus (references, answer chunks, completion)
|
||||
KnowledgeQA(ctx context.Context,
|
||||
session *types.Session, query string, knowledgeBaseIDs []string, knowledgeIDs []string,
|
||||
assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus,
|
||||
customAgent *types.CustomAgent,
|
||||
) error
|
||||
// KnowledgeQAByEvent performs knowledge-based question answering by event
|
||||
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
|
||||
@@ -44,12 +48,16 @@ type SessionService interface {
|
||||
SearchKnowledge(ctx context.Context, knowledgeBaseIDs []string, knowledgeIDs []string, query string) ([]*types.SearchResult, error)
|
||||
// AgentQA performs agent-based question answering with conversation history and streaming support
|
||||
// eventBus is optional - if nil, uses service's default EventBus
|
||||
// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults
|
||||
AgentQA(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
query string,
|
||||
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
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package types
|
||||
|
||||
// PromptPlaceholder represents a placeholder that can be used in prompt templates
|
||||
type PromptPlaceholder struct {
|
||||
// Name is the placeholder name (without braces), e.g., "query"
|
||||
Name string `json:"name"`
|
||||
// Label is a short label for the placeholder
|
||||
Label string `json:"label"`
|
||||
// Description explains what this placeholder represents
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// PromptFieldType represents the type of prompt field
|
||||
type PromptFieldType string
|
||||
|
||||
const (
|
||||
// PromptFieldSystemPrompt is for system prompts (normal mode)
|
||||
PromptFieldSystemPrompt PromptFieldType = "system_prompt"
|
||||
// PromptFieldAgentSystemPrompt is for agent mode system prompts
|
||||
PromptFieldAgentSystemPrompt PromptFieldType = "agent_system_prompt"
|
||||
// PromptFieldContextTemplate is for context templates
|
||||
PromptFieldContextTemplate PromptFieldType = "context_template"
|
||||
// PromptFieldRewriteSystemPrompt is for rewrite system prompts
|
||||
PromptFieldRewriteSystemPrompt PromptFieldType = "rewrite_system_prompt"
|
||||
// PromptFieldRewritePrompt is for rewrite user prompts
|
||||
PromptFieldRewritePrompt PromptFieldType = "rewrite_prompt"
|
||||
// PromptFieldFallbackPrompt is for fallback prompts
|
||||
PromptFieldFallbackPrompt PromptFieldType = "fallback_prompt"
|
||||
)
|
||||
|
||||
// All available placeholders in the system
|
||||
var (
|
||||
// Common placeholders
|
||||
PlaceholderQuery = PromptPlaceholder{
|
||||
Name: "query",
|
||||
Label: "用户问题",
|
||||
Description: "用户当前的问题或查询内容",
|
||||
}
|
||||
|
||||
PlaceholderContexts = PromptPlaceholder{
|
||||
Name: "contexts",
|
||||
Label: "检索内容",
|
||||
Description: "从知识库检索到的相关内容列表",
|
||||
}
|
||||
|
||||
PlaceholderCurrentTime = PromptPlaceholder{
|
||||
Name: "current_time",
|
||||
Label: "当前时间",
|
||||
Description: "当前系统时间(格式:2006-01-02 15:04:05)",
|
||||
}
|
||||
|
||||
PlaceholderCurrentWeek = PromptPlaceholder{
|
||||
Name: "current_week",
|
||||
Label: "当前星期",
|
||||
Description: "当前星期几(如:星期一、Monday)",
|
||||
}
|
||||
|
||||
// Rewrite prompt placeholders
|
||||
PlaceholderConversation = PromptPlaceholder{
|
||||
Name: "conversation",
|
||||
Label: "历史对话",
|
||||
Description: "格式化的历史对话内容,用于多轮对话改写",
|
||||
}
|
||||
|
||||
PlaceholderYesterday = PromptPlaceholder{
|
||||
Name: "yesterday",
|
||||
Label: "昨天日期",
|
||||
Description: "昨天的日期(格式:2006-01-02)",
|
||||
}
|
||||
|
||||
PlaceholderAnswer = PromptPlaceholder{
|
||||
Name: "answer",
|
||||
Label: "助手回答",
|
||||
Description: "助手的回答内容(用于对话历史格式化)",
|
||||
}
|
||||
|
||||
// Agent mode specific placeholders
|
||||
PlaceholderKnowledgeBases = PromptPlaceholder{
|
||||
Name: "knowledge_bases",
|
||||
Label: "知识库列表",
|
||||
Description: "自动格式化的知识库列表,包含名称、描述、文档数量等信息",
|
||||
}
|
||||
|
||||
PlaceholderWebSearchStatus = PromptPlaceholder{
|
||||
Name: "web_search_status",
|
||||
Label: "网络搜索状态",
|
||||
Description: "网络搜索工具是否启用的状态(Enabled 或 Disabled)",
|
||||
}
|
||||
)
|
||||
|
||||
// PlaceholdersByField returns the available placeholders for a specific prompt field type
|
||||
func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
|
||||
switch fieldType {
|
||||
case PromptFieldSystemPrompt:
|
||||
// Normal mode system prompt
|
||||
return []PromptPlaceholder{
|
||||
PlaceholderQuery,
|
||||
PlaceholderContexts,
|
||||
PlaceholderCurrentTime,
|
||||
PlaceholderCurrentWeek,
|
||||
}
|
||||
case PromptFieldAgentSystemPrompt:
|
||||
// Agent mode system prompt
|
||||
return []PromptPlaceholder{
|
||||
PlaceholderKnowledgeBases,
|
||||
PlaceholderWebSearchStatus,
|
||||
PlaceholderCurrentTime,
|
||||
}
|
||||
case PromptFieldContextTemplate:
|
||||
return []PromptPlaceholder{
|
||||
PlaceholderQuery,
|
||||
PlaceholderContexts,
|
||||
PlaceholderCurrentTime,
|
||||
PlaceholderCurrentWeek,
|
||||
}
|
||||
case PromptFieldRewriteSystemPrompt:
|
||||
// Rewrite system prompt supports same placeholders as rewrite user prompt
|
||||
return []PromptPlaceholder{
|
||||
PlaceholderQuery,
|
||||
PlaceholderConversation,
|
||||
PlaceholderCurrentTime,
|
||||
PlaceholderYesterday,
|
||||
}
|
||||
case PromptFieldRewritePrompt:
|
||||
return []PromptPlaceholder{
|
||||
PlaceholderQuery,
|
||||
PlaceholderConversation,
|
||||
PlaceholderCurrentTime,
|
||||
PlaceholderYesterday,
|
||||
}
|
||||
case PromptFieldFallbackPrompt:
|
||||
return []PromptPlaceholder{
|
||||
PlaceholderQuery,
|
||||
}
|
||||
default:
|
||||
return []PromptPlaceholder{}
|
||||
}
|
||||
}
|
||||
|
||||
// AllPlaceholders returns all available placeholders in the system
|
||||
func AllPlaceholders() []PromptPlaceholder {
|
||||
return []PromptPlaceholder{
|
||||
PlaceholderQuery,
|
||||
PlaceholderContexts,
|
||||
PlaceholderCurrentTime,
|
||||
PlaceholderCurrentWeek,
|
||||
PlaceholderConversation,
|
||||
PlaceholderYesterday,
|
||||
PlaceholderAnswer,
|
||||
PlaceholderKnowledgeBases,
|
||||
PlaceholderWebSearchStatus,
|
||||
}
|
||||
}
|
||||
|
||||
// PlaceholderMap returns a map of field types to their available placeholders
|
||||
func PlaceholderMap() map[PromptFieldType][]PromptPlaceholder {
|
||||
return map[PromptFieldType][]PromptPlaceholder{
|
||||
PromptFieldSystemPrompt: PlaceholdersByField(PromptFieldSystemPrompt),
|
||||
PromptFieldAgentSystemPrompt: PlaceholdersByField(PromptFieldAgentSystemPrompt),
|
||||
PromptFieldContextTemplate: PlaceholdersByField(PromptFieldContextTemplate),
|
||||
PromptFieldRewriteSystemPrompt: PlaceholdersByField(PromptFieldRewriteSystemPrompt),
|
||||
PromptFieldRewritePrompt: PlaceholdersByField(PromptFieldRewritePrompt),
|
||||
PromptFieldFallbackPrompt: PlaceholdersByField(PromptFieldFallbackPrompt),
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -80,22 +80,22 @@ type Session struct {
|
||||
// Tenant ID
|
||||
TenantID uint64 `json:"tenant_id" gorm:"index"`
|
||||
|
||||
// Strategy configuration
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
|
||||
MaxRounds int `json:"max_rounds"` // 多轮保持轮数
|
||||
EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关
|
||||
FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略
|
||||
FallbackResponse string `json:"fallback_response"` // 固定回复内容
|
||||
EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK
|
||||
KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值
|
||||
VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值
|
||||
RerankModelID string `json:"rerank_model_id"` // 排序模型ID
|
||||
RerankTopK int `json:"rerank_top_k"` // 排序TopK
|
||||
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
|
||||
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
|
||||
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
|
||||
AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)
|
||||
ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选)
|
||||
// // Strategy configuration
|
||||
// KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
|
||||
// MaxRounds int `json:"max_rounds"` // 多轮保持轮数
|
||||
// EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关
|
||||
// FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略
|
||||
// FallbackResponse string `json:"fallback_response"` // 固定回复内容
|
||||
// EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK
|
||||
// KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值
|
||||
// VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值
|
||||
// RerankModelID string `json:"rerank_model_id"` // 排序模型ID
|
||||
// RerankTopK int `json:"rerank_top_k"` // 排序TopK
|
||||
// RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
|
||||
// SummaryModelID string `json:"summary_model_id"` // 总结模型ID
|
||||
// SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
|
||||
// AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)
|
||||
// ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选)
|
||||
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
@@ -69,13 +69,15 @@ type Tenant struct {
|
||||
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
|
||||
// Storage used (Bytes)
|
||||
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
|
||||
// Global Agent configuration for this tenant (default for all sessions)
|
||||
// Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.
|
||||
// This field is kept for backward compatibility and will be removed in future versions.
|
||||
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`
|
||||
// Global Context configuration for this tenant (default for all sessions)
|
||||
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
|
||||
// Global WebSearch configuration for this tenant
|
||||
WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`
|
||||
// Global Conversation configuration for this tenant (default for normal mode sessions)
|
||||
// Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.
|
||||
// This field is kept for backward compatibility and will be removed in future versions.
|
||||
ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
@@ -126,9 +128,7 @@ func (c *RetrieverEngines) Scan(value interface{}) error {
|
||||
// ConversationConfig represents the conversation configuration for normal mode
|
||||
type ConversationConfig struct {
|
||||
// Prompt is the system prompt for normal mode
|
||||
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"`
|
||||
Prompt string `json:"prompt"`
|
||||
UseCustomContextTemplate bool `json:"use_custom_context_template"`
|
||||
Prompt string `json:"prompt"`
|
||||
// ContextTemplate is the prompt template for summarizing retrieval results
|
||||
ContextTemplate string `json:"context_template"`
|
||||
// Temperature controls the randomness of the model output
|
||||
|
||||
Reference in New Issue
Block a user