feat: Enhance agent configuration and localization for web search prompts
- Updated agent configuration to support separate system prompts for web search enabled and disabled states. - Removed deprecated agent configuration parameters to streamline settings management. - Enhanced UI components in AgentSettings.vue to allow configuration of custom prompts based on web search status. - Improved localization in English, Russian, and Chinese for new prompt settings and UI elements. - Refactored related API and service logic to accommodate changes in agent configuration structure.
This commit is contained in:
@@ -23,14 +23,14 @@ const MAX_ITERATIONS = 30 // Max iterations for agent execution
|
||||
type agentService struct {
|
||||
cfg *config.Config
|
||||
modelService interfaces.ModelService
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
mcpServiceService interfaces.MCPServiceService
|
||||
mcpManager *mcp.MCPManager
|
||||
eventBus *event.EventBus
|
||||
db *gorm.DB
|
||||
webSearchService interfaces.WebSearchService
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
}
|
||||
|
||||
// NewAgentService creates a new agent service
|
||||
@@ -95,7 +95,7 @@ func (s *agentService) CreateAgentEngine(
|
||||
}
|
||||
|
||||
// Create tool registry
|
||||
toolRegistry := tools.NewToolRegistry(s.knowledgeBaseService, s.knowledgeService, s.chunkService, s.db)
|
||||
toolRegistry := tools.NewToolRegistry(s.knowledgeService, s.chunkService, s.db)
|
||||
|
||||
// Register tools
|
||||
if err := s.registerTools(ctx, toolRegistry, config, rerankModel, chatModel, sessionID, sessionService); err != nil {
|
||||
@@ -148,9 +148,9 @@ func (s *agentService) CreateAgentEngine(
|
||||
}
|
||||
}
|
||||
|
||||
systemPromptTemplate := agent.DefaultSystemPromptTemplate
|
||||
if config.UseCustomSystemPrompt && config.SystemPrompt != "" {
|
||||
systemPromptTemplate = config.SystemPrompt
|
||||
systemPromptTemplate := ""
|
||||
if config.UseCustomSystemPrompt {
|
||||
systemPromptTemplate = config.ResolveSystemPrompt(config.WebSearchEnabled)
|
||||
}
|
||||
|
||||
// Create engine with provided EventBus and contextManager
|
||||
@@ -158,7 +158,6 @@ func (s *agentService) CreateAgentEngine(
|
||||
config,
|
||||
chatModel,
|
||||
toolRegistry,
|
||||
s.knowledgeBaseService,
|
||||
eventBus,
|
||||
kbInfos,
|
||||
contextManager,
|
||||
@@ -182,10 +181,7 @@ func (s *agentService) registerTools(
|
||||
// If no specific tools allowed, register default tools
|
||||
allowedTools := config.AllowedTools
|
||||
if len(allowedTools) == 0 {
|
||||
// Register default tools from config
|
||||
if s.cfg.Agent != nil && len(s.cfg.Agent.DefaultTools) > 0 {
|
||||
allowedTools = s.cfg.Agent.DefaultTools
|
||||
}
|
||||
allowedTools = tools.DefaultAllowedTools()
|
||||
}
|
||||
// If web search is enabled, add web_search to allowedTools
|
||||
if config.WebSearchEnabled {
|
||||
@@ -216,13 +212,14 @@ func (s *agentService) registerTools(
|
||||
config.KnowledgeBases,
|
||||
rerankModel,
|
||||
chatModel,
|
||||
s.cfg,
|
||||
))
|
||||
case "get_related_chunks":
|
||||
registry.RegisterTool(tools.NewGetRelatedChunksTool(s.chunkService, s.knowledgeBaseService))
|
||||
case "list_knowledge_chunks":
|
||||
registry.RegisterTool(tools.NewListKnowledgeChunksTool(tenantID, s.knowledgeService, s.chunkService))
|
||||
case "query_knowledge_graph":
|
||||
registry.RegisterTool(tools.NewQueryKnowledgeGraphTool(s.knowledgeBaseService))
|
||||
case "get_document_info":
|
||||
registry.RegisterTool(tools.NewGetDocumentInfoTool(s.knowledgeService, s.chunkService))
|
||||
registry.RegisterTool(tools.NewGetDocumentInfoTool(tenantID, s.knowledgeService, s.chunkService))
|
||||
case "database_query":
|
||||
registry.RegisterTool(tools.NewDatabaseQueryTool(s.db, tenantID))
|
||||
case "web_search":
|
||||
|
||||
@@ -66,7 +66,7 @@ func (p *PluginChatCompletion) OnEvent(
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Completion", "output", map[string]interface{}{
|
||||
"answer_preview": truncateForLog(chatResponse.Content),
|
||||
"answer_preview": chatResponse.Content,
|
||||
"finish_reason": chatResponse.FinishReason,
|
||||
"completion_tokens": chatResponse.Usage.CompletionTokens,
|
||||
"prompt_tokens": chatResponse.Usage.PromptTokens,
|
||||
|
||||
@@ -2,87 +2,24 @@ package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const (
|
||||
logValueMaxRune = 300
|
||||
defaultStageName = "PIPELINE"
|
||||
defaultActionName = "info"
|
||||
pipelineLogPrefix = "[PIPELINE]"
|
||||
pipelineTruncateEll = "..."
|
||||
)
|
||||
|
||||
func pipelineLog(stage, action string, fields map[string]interface{}) string {
|
||||
if stage == "" {
|
||||
stage = defaultStageName
|
||||
}
|
||||
if action == "" {
|
||||
action = defaultActionName
|
||||
}
|
||||
|
||||
builder := strings.Builder{}
|
||||
builder.Grow(128)
|
||||
builder.WriteString(pipelineLogPrefix)
|
||||
builder.WriteString(" stage=")
|
||||
builder.WriteString(stage)
|
||||
builder.WriteString(" action=")
|
||||
builder.WriteString(action)
|
||||
|
||||
if len(fields) > 0 {
|
||||
keys := make([]string, 0, len(fields))
|
||||
for k := range fields {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
builder.WriteString(" ")
|
||||
builder.WriteString(key)
|
||||
builder.WriteString("=")
|
||||
builder.WriteString(formatLogValue(fields[key]))
|
||||
}
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func pipelineInfo(ctx context.Context, stage, action string, fields map[string]interface{}) {
|
||||
logger.GetLogger(ctx).Info(pipelineLog(stage, action, fields))
|
||||
common.PipelineInfo(ctx, stage, action, fields)
|
||||
}
|
||||
|
||||
func pipelineWarn(ctx context.Context, stage, action string, fields map[string]interface{}) {
|
||||
logger.GetLogger(ctx).Warn(pipelineLog(stage, action, fields))
|
||||
common.PipelineWarn(ctx, stage, action, fields)
|
||||
}
|
||||
|
||||
func pipelineError(ctx context.Context, stage, action string, fields map[string]interface{}) {
|
||||
logger.GetLogger(ctx).Error(pipelineLog(stage, action, fields))
|
||||
}
|
||||
|
||||
func formatLogValue(value interface{}) string {
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return strconv.Quote(truncateForLog(v))
|
||||
case fmt.Stringer:
|
||||
return strconv.Quote(truncateForLog(v.String()))
|
||||
default:
|
||||
return fmt.Sprintf("%v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func truncateForLog(content string) string {
|
||||
content = strings.ReplaceAll(content, "\n", "\\n")
|
||||
runes := []rune(content)
|
||||
if len(runes) <= logValueMaxRune {
|
||||
return content
|
||||
}
|
||||
return string(runes[:logValueMaxRune]) + pipelineTruncateEll
|
||||
common.PipelineError(ctx, stage, action, fields)
|
||||
}
|
||||
|
||||
// prepareChatModel shared logic to prepare chat model and options
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -139,6 +140,7 @@ func (p *PluginMerge) OnEvent(ctx context.Context,
|
||||
"merged_total": len(mergedChunks),
|
||||
})
|
||||
|
||||
mergedChunks = p.populateFAQAnswers(ctx, chatManage, mergedChunks)
|
||||
mergedChunks = p.expandShortContextWithNeighbors(ctx, chatManage, mergedChunks)
|
||||
|
||||
chatManage.MergeResult = mergedChunks
|
||||
@@ -210,6 +212,126 @@ func mergeImageInfo(ctx context.Context, target *types.SearchResult, source *typ
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PluginMerge) populateFAQAnswers(ctx context.Context, chatManage *types.ChatManage, results []*types.SearchResult) []*types.SearchResult {
|
||||
if len(results) == 0 || p.chunkRepo == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
if tenantID == 0 && chatManage != nil {
|
||||
tenantID = chatManage.TenantID
|
||||
}
|
||||
if tenantID == 0 {
|
||||
pipelineWarn(ctx, "Merge", "faq_enrich_skip", map[string]interface{}{
|
||||
"reason": "missing_tenant",
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
chunkResultMap := make(map[string][]*types.SearchResult)
|
||||
chunkIDSet := make(map[string]struct{})
|
||||
for _, r := range results {
|
||||
if r == nil || r.ID == "" {
|
||||
continue
|
||||
}
|
||||
if r.ChunkType != string(types.ChunkTypeFAQ) {
|
||||
continue
|
||||
}
|
||||
chunkResultMap[r.ID] = append(chunkResultMap[r.ID], r)
|
||||
if _, exists := chunkIDSet[r.ID]; !exists {
|
||||
chunkIDSet[r.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if len(chunkIDSet) == 0 {
|
||||
return results
|
||||
}
|
||||
|
||||
chunkIDs := make([]string, 0, len(chunkIDSet))
|
||||
for id := range chunkIDSet {
|
||||
chunkIDs = append(chunkIDs, id)
|
||||
}
|
||||
|
||||
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "faq_chunk_fetch_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
updated := 0
|
||||
for _, chunk := range chunks {
|
||||
if chunk == nil {
|
||||
continue
|
||||
}
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil || meta == nil {
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "faq_metadata_parse_failed", map[string]interface{}{
|
||||
"chunk_id": chunk.ID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := buildFAQAnswerContent(meta)
|
||||
if content == "" {
|
||||
continue
|
||||
}
|
||||
for _, r := range chunkResultMap[chunk.ID] {
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
r.Content = content
|
||||
updated++
|
||||
}
|
||||
}
|
||||
|
||||
if updated > 0 {
|
||||
pipelineInfo(ctx, "Merge", "faq_content_enriched", map[string]interface{}{
|
||||
"chunk_cnt": updated,
|
||||
})
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func buildFAQAnswerContent(meta *types.FAQChunkMetadata) string {
|
||||
if meta == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
question := strings.TrimSpace(meta.StandardQuestion)
|
||||
answers := make([]string, 0, len(meta.Answers))
|
||||
for _, ans := range meta.Answers {
|
||||
if trimmed := strings.TrimSpace(ans); trimmed != "" {
|
||||
answers = append(answers, trimmed)
|
||||
}
|
||||
}
|
||||
|
||||
if question == "" && len(answers) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
if question != "" {
|
||||
builder.WriteString("Q: ")
|
||||
builder.WriteString(question)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
if len(answers) > 0 {
|
||||
builder.WriteString("Answer:\n")
|
||||
for _, ans := range answers {
|
||||
builder.WriteString("- ")
|
||||
builder.WriteString(ans)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
return strings.TrimSpace(builder.String())
|
||||
}
|
||||
|
||||
func (p *PluginMerge) expandShortContextWithNeighbors(ctx context.Context, chatManage *types.ChatManage, results []*types.SearchResult) []*types.SearchResult {
|
||||
const (
|
||||
minLen = 350
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/yanyiwu/gojieba"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/yanyiwu/gojieba"
|
||||
)
|
||||
|
||||
// PluginPreprocess Query preprocessing plugin
|
||||
type PluginPreprocess struct {
|
||||
config *config.Config
|
||||
jieba *gojieba.Jieba
|
||||
stopwords map[string]struct{}
|
||||
modelService interfaces.ModelService
|
||||
config *config.Config
|
||||
jieba *gojieba.Jieba
|
||||
stopwords map[string]struct{}
|
||||
modelService interfaces.ModelService
|
||||
}
|
||||
|
||||
// Regular expressions for text cleaning
|
||||
@@ -35,10 +35,10 @@ const maxProcessedTokens = 12
|
||||
|
||||
// NewPluginPreprocess Creates a new query preprocessing plugin
|
||||
func NewPluginPreprocess(
|
||||
eventManager *EventManager,
|
||||
config *config.Config,
|
||||
cleaner interfaces.ResourceCleaner,
|
||||
modelService interfaces.ModelService,
|
||||
eventManager *EventManager,
|
||||
config *config.Config,
|
||||
cleaner interfaces.ResourceCleaner,
|
||||
modelService interfaces.ModelService,
|
||||
) *PluginPreprocess {
|
||||
// Use default dictionary for Jieba tokenizer
|
||||
jieba := gojieba.NewJieba()
|
||||
@@ -46,12 +46,12 @@ func NewPluginPreprocess(
|
||||
// Load stopwords from built-in stopword library
|
||||
stopwords := loadStopwords()
|
||||
|
||||
res := &PluginPreprocess{
|
||||
config: config,
|
||||
jieba: jieba,
|
||||
stopwords: stopwords,
|
||||
modelService: modelService,
|
||||
}
|
||||
res := &PluginPreprocess{
|
||||
config: config,
|
||||
jieba: jieba,
|
||||
stopwords: stopwords,
|
||||
modelService: modelService,
|
||||
}
|
||||
|
||||
// Register resource cleanup function
|
||||
if cleaner != nil {
|
||||
@@ -92,10 +92,10 @@ func (p *PluginPreprocess) ActivationEvents() []types.EventType {
|
||||
|
||||
// OnEvent Process events
|
||||
func (p *PluginPreprocess) OnEvent(ctx context.Context, eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError) *PluginError {
|
||||
rawQuery := strings.TrimSpace(chatManage.RewriteQuery)
|
||||
if rawQuery == "" {
|
||||
return next()
|
||||
}
|
||||
rawQuery := strings.TrimSpace(chatManage.RewriteQuery)
|
||||
if rawQuery == "" {
|
||||
return next()
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Preprocess", "input", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
@@ -108,12 +108,12 @@ func (p *PluginPreprocess) OnEvent(ctx context.Context, eventType types.EventTyp
|
||||
sanitized = normalized
|
||||
}
|
||||
|
||||
var (
|
||||
processed = sanitized
|
||||
strategy = "original"
|
||||
tokenPreview string
|
||||
tokenCount int
|
||||
)
|
||||
var (
|
||||
processed = sanitized
|
||||
strategy = "original"
|
||||
tokenPreview string
|
||||
tokenCount int
|
||||
)
|
||||
|
||||
switch {
|
||||
case containsChineseCharacters(sanitized):
|
||||
@@ -141,17 +141,17 @@ func (p *PluginPreprocess) OnEvent(ctx context.Context, eventType types.EventTyp
|
||||
strategy = "fallback_original"
|
||||
}
|
||||
|
||||
chatManage.ProcessedQuery = processed
|
||||
chatManage.QueryIntent = p.detectIntentLLM(ctx, chatManage, sanitized)
|
||||
chatManage.ProcessedQuery = processed
|
||||
chatManage.QueryIntent = p.detectIntentLLM(ctx, chatManage, sanitized)
|
||||
|
||||
pipelineInfo(ctx, "Preprocess", "output", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"processed_query": processed,
|
||||
"strategy": strategy,
|
||||
"token_count": tokenCount,
|
||||
"token_preview": truncateForLog(tokenPreview),
|
||||
"query_intent": chatManage.QueryIntent,
|
||||
})
|
||||
pipelineInfo(ctx, "Preprocess", "output", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"processed_query": processed,
|
||||
"strategy": strategy,
|
||||
"token_count": tokenCount,
|
||||
"token_preview": tokenPreview,
|
||||
"query_intent": chatManage.QueryIntent,
|
||||
})
|
||||
|
||||
return next()
|
||||
}
|
||||
@@ -258,63 +258,63 @@ func normalizeWhitespace(text string) string {
|
||||
}
|
||||
|
||||
func normalizeLatinQuery(text string) string {
|
||||
text = strings.ToLower(text)
|
||||
text = multiSpaceRegex.ReplaceAllString(text, " ")
|
||||
return strings.TrimSpace(text)
|
||||
text = strings.ToLower(text)
|
||||
text = multiSpaceRegex.ReplaceAllString(text, " ")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
type intentResp struct {
|
||||
Intent string `json:"intent"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Intent string `json:"intent"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
}
|
||||
|
||||
func (p *PluginPreprocess) detectIntentLLM(ctx context.Context, chatManage *types.ChatManage, text string) string {
|
||||
if p.modelService == nil || chatManage.ChatModelID == "" {
|
||||
pipelineWarn(ctx, "IntentDetect", "skip", map[string]interface{}{ "reason": "no_model", "session_id": chatManage.SessionID })
|
||||
return "general"
|
||||
}
|
||||
chatModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "IntentDetect", "get_model_failed", map[string]interface{}{ "error": err.Error(), "model_id": chatManage.ChatModelID })
|
||||
return "general"
|
||||
}
|
||||
pipelineInfo(ctx, "IntentDetect", "start", map[string]interface{}{ "session_id": chatManage.SessionID, "model_id": chatManage.ChatModelID })
|
||||
sys := "You are a query intent classifier. Classify the user's query into one of: definition, howto, compare, qa, general. Respond ONLY with a JSON object {\"intent\": \"...\", \"confidence\": 0.0 } inside a markdown fenced block."
|
||||
usr := text
|
||||
think := false
|
||||
resp, err := chatModel.Chat(ctx, []chat.Message{
|
||||
{Role: "system", Content: sys},
|
||||
{Role: "user", Content: usr},
|
||||
}, &chat.ChatOptions{Temperature: 0.0, MaxCompletionTokens: 64, Thinking: &think})
|
||||
if err != nil || resp.Content == "" {
|
||||
pipelineWarn(ctx, "IntentDetect", "model_call_failed", map[string]interface{}{ "error": err })
|
||||
return "general"
|
||||
}
|
||||
body := extractJSONBody(resp.Content)
|
||||
var ir intentResp
|
||||
if err := json.Unmarshal([]byte(body), &ir); err != nil {
|
||||
pipelineWarn(ctx, "IntentDetect", "parse_failed", map[string]interface{}{ "body": truncateForLog(body), "error": err.Error() })
|
||||
return "general"
|
||||
}
|
||||
pipelineInfo(ctx, "IntentDetect", "result", map[string]interface{}{ "intent": ir.Intent, "confidence": ir.Confidence })
|
||||
switch strings.ToLower(strings.TrimSpace(ir.Intent)) {
|
||||
case "definition", "howto", "compare", "qa", "general":
|
||||
return strings.ToLower(ir.Intent)
|
||||
default:
|
||||
return "general"
|
||||
}
|
||||
if p.modelService == nil || chatManage.ChatModelID == "" {
|
||||
pipelineWarn(ctx, "IntentDetect", "skip", map[string]interface{}{"reason": "no_model", "session_id": chatManage.SessionID})
|
||||
return "general"
|
||||
}
|
||||
chatModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "IntentDetect", "get_model_failed", map[string]interface{}{"error": err.Error(), "model_id": chatManage.ChatModelID})
|
||||
return "general"
|
||||
}
|
||||
pipelineInfo(ctx, "IntentDetect", "start", map[string]interface{}{"session_id": chatManage.SessionID, "model_id": chatManage.ChatModelID})
|
||||
sys := "You are a query intent classifier. Classify the user's query into one of: definition, howto, compare, qa, general. Respond ONLY with a JSON object {\"intent\": \"...\", \"confidence\": 0.0 } inside a markdown fenced block."
|
||||
usr := text
|
||||
think := false
|
||||
resp, err := chatModel.Chat(ctx, []chat.Message{
|
||||
{Role: "system", Content: sys},
|
||||
{Role: "user", Content: usr},
|
||||
}, &chat.ChatOptions{Temperature: 0.0, MaxCompletionTokens: 64, Thinking: &think})
|
||||
if err != nil || resp.Content == "" {
|
||||
pipelineWarn(ctx, "IntentDetect", "model_call_failed", map[string]interface{}{"error": err})
|
||||
return "general"
|
||||
}
|
||||
body := extractJSONBody(resp.Content)
|
||||
var ir intentResp
|
||||
if err := json.Unmarshal([]byte(body), &ir); err != nil {
|
||||
pipelineWarn(ctx, "IntentDetect", "parse_failed", map[string]interface{}{"body": body, "error": err.Error()})
|
||||
return "general"
|
||||
}
|
||||
pipelineInfo(ctx, "IntentDetect", "result", map[string]interface{}{"intent": ir.Intent, "confidence": ir.Confidence})
|
||||
switch strings.ToLower(strings.TrimSpace(ir.Intent)) {
|
||||
case "definition", "howto", "compare", "qa", "general":
|
||||
return strings.ToLower(ir.Intent)
|
||||
default:
|
||||
return "general"
|
||||
}
|
||||
}
|
||||
|
||||
func extractJSONBody(text string) string {
|
||||
t := strings.TrimSpace(text)
|
||||
// Try fenced block first
|
||||
if i := strings.Index(t, "{"); i >= 0 {
|
||||
j := strings.LastIndex(t, "}")
|
||||
if j > i {
|
||||
return t[i : j+1]
|
||||
}
|
||||
}
|
||||
return "{}"
|
||||
t := strings.TrimSpace(text)
|
||||
// Try fenced block first
|
||||
if i := strings.Index(t, "{"); i >= 0 {
|
||||
j := strings.LastIndex(t, "}")
|
||||
if j > i {
|
||||
return t[i : j+1]
|
||||
}
|
||||
}
|
||||
return "{}"
|
||||
}
|
||||
|
||||
// Ensure resources are properly released
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// PluginSearch implements search functionality for chat pipeline
|
||||
@@ -54,7 +55,7 @@ func (p *PluginSearch) ActivationEvents() []types.EventType {
|
||||
|
||||
// OnEvent handles search events in the chat pipeline
|
||||
func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
|
||||
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
|
||||
) *PluginError {
|
||||
// Get knowledge base IDs list
|
||||
knowledgeBaseIDs := chatManage.KnowledgeBaseIDs
|
||||
@@ -117,85 +118,85 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
wg.Wait()
|
||||
|
||||
chatManage.SearchResult = allResults
|
||||
chatManage.SearchResult = allResults
|
||||
|
||||
// If recall is low, attempt query expansion with keyword-focused search
|
||||
if len(chatManage.SearchResult) < max(1, chatManage.EmbeddingTopK/2) {
|
||||
pipelineInfo(ctx, "Search", "recall_low", map[string]interface{}{
|
||||
"current": len(chatManage.SearchResult),
|
||||
"threshold": chatManage.EmbeddingTopK / 2,
|
||||
})
|
||||
expansions := p.expandQueries(ctx, chatManage)
|
||||
if len(expansions) > 0 {
|
||||
pipelineInfo(ctx, "Search", "expansion_start", map[string]interface{}{
|
||||
"variants": len(expansions),
|
||||
})
|
||||
expTopK := max(chatManage.EmbeddingTopK*2, chatManage.RerankTopK*2)
|
||||
expKwTh := chatManage.KeywordThreshold * 0.8
|
||||
// Concurrent expansion retrieval across queries and KBs
|
||||
expResults := make([]*types.SearchResult, 0, expTopK*len(expansions))
|
||||
var muExp sync.Mutex
|
||||
var wgExp sync.WaitGroup
|
||||
jobs := len(expansions) * len(knowledgeBaseIDs)
|
||||
capSem := 16
|
||||
if jobs < capSem {
|
||||
capSem = jobs
|
||||
}
|
||||
if capSem <= 0 {
|
||||
capSem = 1
|
||||
}
|
||||
sem := make(chan struct{}, capSem)
|
||||
pipelineInfo(ctx, "Search", "expansion_concurrency", map[string]interface{}{
|
||||
"jobs": jobs,
|
||||
"cap": capSem,
|
||||
})
|
||||
for _, q := range expansions {
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wgExp.Add(1)
|
||||
go func(q string, kbID string) {
|
||||
defer wgExp.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
paramsExp := types.SearchParams{
|
||||
QueryText: q,
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: expKwTh,
|
||||
MatchCount: expTopK,
|
||||
DisableVectorMatch: true,
|
||||
DisableKeywordsMatch: false,
|
||||
}
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, kbID, paramsExp)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "expansion_error", map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
if len(res) > 0 {
|
||||
pipelineInfo(ctx, "Search", "expansion_hits", map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
"query": truncateForLog(q),
|
||||
"hits": len(res),
|
||||
})
|
||||
muExp.Lock()
|
||||
expResults = append(expResults, res...)
|
||||
muExp.Unlock()
|
||||
}
|
||||
}(q, kbID)
|
||||
}
|
||||
}
|
||||
wgExp.Wait()
|
||||
if len(expResults) > 0 {
|
||||
pipelineInfo(ctx, "Search", "expansion_done", map[string]interface{}{
|
||||
"added": len(expResults),
|
||||
})
|
||||
chatManage.SearchResult = append(chatManage.SearchResult, expResults...)
|
||||
}
|
||||
}
|
||||
}
|
||||
// If recall is low, attempt query expansion with keyword-focused search
|
||||
if len(chatManage.SearchResult) < max(1, chatManage.EmbeddingTopK/2) {
|
||||
pipelineInfo(ctx, "Search", "recall_low", map[string]interface{}{
|
||||
"current": len(chatManage.SearchResult),
|
||||
"threshold": chatManage.EmbeddingTopK / 2,
|
||||
})
|
||||
expansions := p.expandQueries(ctx, chatManage)
|
||||
if len(expansions) > 0 {
|
||||
pipelineInfo(ctx, "Search", "expansion_start", map[string]interface{}{
|
||||
"variants": len(expansions),
|
||||
})
|
||||
expTopK := max(chatManage.EmbeddingTopK*2, chatManage.RerankTopK*2)
|
||||
expKwTh := chatManage.KeywordThreshold * 0.8
|
||||
// Concurrent expansion retrieval across queries and KBs
|
||||
expResults := make([]*types.SearchResult, 0, expTopK*len(expansions))
|
||||
var muExp sync.Mutex
|
||||
var wgExp sync.WaitGroup
|
||||
jobs := len(expansions) * len(knowledgeBaseIDs)
|
||||
capSem := 16
|
||||
if jobs < capSem {
|
||||
capSem = jobs
|
||||
}
|
||||
if capSem <= 0 {
|
||||
capSem = 1
|
||||
}
|
||||
sem := make(chan struct{}, capSem)
|
||||
pipelineInfo(ctx, "Search", "expansion_concurrency", map[string]interface{}{
|
||||
"jobs": jobs,
|
||||
"cap": capSem,
|
||||
})
|
||||
for _, q := range expansions {
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
wgExp.Add(1)
|
||||
go func(q string, kbID string) {
|
||||
defer wgExp.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
paramsExp := types.SearchParams{
|
||||
QueryText: q,
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: expKwTh,
|
||||
MatchCount: expTopK,
|
||||
DisableVectorMatch: true,
|
||||
DisableKeywordsMatch: false,
|
||||
}
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, kbID, paramsExp)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "expansion_error", map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
if len(res) > 0 {
|
||||
pipelineInfo(ctx, "Search", "expansion_hits", map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
"query": q,
|
||||
"hits": len(res),
|
||||
})
|
||||
muExp.Lock()
|
||||
expResults = append(expResults, res...)
|
||||
muExp.Unlock()
|
||||
}
|
||||
}(q, kbID)
|
||||
}
|
||||
}
|
||||
wgExp.Wait()
|
||||
if len(expResults) > 0 {
|
||||
pipelineInfo(ctx, "Search", "expansion_done", map[string]interface{}{
|
||||
"added": len(expResults),
|
||||
})
|
||||
chatManage.SearchResult = append(chatManage.SearchResult, expResults...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add relevant results from chat history
|
||||
historyResult := p.getSearchResultFromHistory(chatManage)
|
||||
@@ -207,13 +208,13 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
chatManage.SearchResult = append(chatManage.SearchResult, historyResult...)
|
||||
}
|
||||
|
||||
// Remove duplicate results
|
||||
before := len(chatManage.SearchResult)
|
||||
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
|
||||
pipelineInfo(ctx, "Search", "dedup_summary", map[string]interface{}{
|
||||
"before": before,
|
||||
"after": len(chatManage.SearchResult),
|
||||
})
|
||||
// Remove duplicate results
|
||||
before := len(chatManage.SearchResult)
|
||||
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
|
||||
pipelineInfo(ctx, "Search", "dedup_summary", map[string]interface{}{
|
||||
"before": before,
|
||||
"after": len(chatManage.SearchResult),
|
||||
})
|
||||
|
||||
// Return if we have results
|
||||
if len(chatManage.SearchResult) != 0 {
|
||||
@@ -249,52 +250,52 @@ func (p *PluginSearch) getSearchResultFromHistory(chatManage *types.ChatManage)
|
||||
}
|
||||
|
||||
func removeDuplicateResults(results []*types.SearchResult) []*types.SearchResult {
|
||||
seen := make(map[string]bool)
|
||||
contentSig := make(map[string]bool)
|
||||
var uniqueResults []*types.SearchResult
|
||||
for _, r := range results {
|
||||
keys := []string{r.ID}
|
||||
if r.ParentChunkID != "" {
|
||||
keys = append(keys, "parent:"+r.ParentChunkID)
|
||||
}
|
||||
if r.KnowledgeID != "" {
|
||||
keys = append(keys, fmt.Sprintf("kb:%s#%d", r.KnowledgeID, r.ChunkIndex))
|
||||
}
|
||||
dup := false
|
||||
for _, k := range keys {
|
||||
if seen[k] {
|
||||
dup = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if dup {
|
||||
continue
|
||||
}
|
||||
sig := buildContentSignature(r.Content)
|
||||
if sig != "" {
|
||||
if contentSig[sig] {
|
||||
continue
|
||||
}
|
||||
contentSig[sig] = true
|
||||
}
|
||||
for _, k := range keys {
|
||||
seen[k] = true
|
||||
}
|
||||
uniqueResults = append(uniqueResults, r)
|
||||
}
|
||||
return uniqueResults
|
||||
seen := make(map[string]bool)
|
||||
contentSig := make(map[string]bool)
|
||||
var uniqueResults []*types.SearchResult
|
||||
for _, r := range results {
|
||||
keys := []string{r.ID}
|
||||
if r.ParentChunkID != "" {
|
||||
keys = append(keys, "parent:"+r.ParentChunkID)
|
||||
}
|
||||
if r.KnowledgeID != "" {
|
||||
keys = append(keys, fmt.Sprintf("kb:%s#%d", r.KnowledgeID, r.ChunkIndex))
|
||||
}
|
||||
dup := false
|
||||
for _, k := range keys {
|
||||
if seen[k] {
|
||||
dup = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if dup {
|
||||
continue
|
||||
}
|
||||
sig := buildContentSignature(r.Content)
|
||||
if sig != "" {
|
||||
if contentSig[sig] {
|
||||
continue
|
||||
}
|
||||
contentSig[sig] = true
|
||||
}
|
||||
for _, k := range keys {
|
||||
seen[k] = true
|
||||
}
|
||||
uniqueResults = append(uniqueResults, r)
|
||||
}
|
||||
return uniqueResults
|
||||
}
|
||||
|
||||
func buildContentSignature(content string) string {
|
||||
c := strings.ToLower(strings.TrimSpace(content))
|
||||
if c == "" {
|
||||
return ""
|
||||
}
|
||||
c = strings.Join(strings.Fields(c), " ")
|
||||
if len(c) > 128 {
|
||||
c = c[:128]
|
||||
}
|
||||
return c
|
||||
c := strings.ToLower(strings.TrimSpace(content))
|
||||
if c == "" {
|
||||
return ""
|
||||
}
|
||||
c = strings.Join(strings.Fields(c), " ")
|
||||
if len(c) > 128 {
|
||||
c = c[:128]
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// searchKnowledgeBases performs KB searches for rewrite and processed queries across KB IDs
|
||||
@@ -375,6 +376,9 @@ func (p *PluginSearch) searchKnowledgeBases(ctx context.Context, knowledgeBaseID
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// Normalize keyword retriever scores after collecting all results from multiple knowledge bases
|
||||
normalizeKeywordSearchResults(ctx, results)
|
||||
|
||||
pipelineInfo(ctx, "Search", "kb_result_summary", map[string]interface{}{
|
||||
"total_hits": len(results),
|
||||
})
|
||||
@@ -472,8 +476,8 @@ func convertWebSearchResults(webResults []*types.WebSearchResult) []*types.Searc
|
||||
ChunkIndex: 0,
|
||||
KnowledgeTitle: webResult.Title,
|
||||
StartAt: 0,
|
||||
EndAt: len(content),
|
||||
Seq: i,
|
||||
EndAt: runeLen(content),
|
||||
Seq: 1,
|
||||
Score: score,
|
||||
MatchType: types.MatchTypeWebSearch,
|
||||
SubChunkID: []string{},
|
||||
@@ -483,7 +487,7 @@ func convertWebSearchResults(webResults []*types.WebSearchResult) []*types.Searc
|
||||
"title": webResult.Title,
|
||||
"snippet": webResult.Snippet,
|
||||
},
|
||||
ChunkType: "web_search",
|
||||
ChunkType: string(types.ChunkTypeWebSearch),
|
||||
ParentChunkID: "",
|
||||
ImageInfo: "",
|
||||
KnowledgeFilename: "",
|
||||
@@ -500,79 +504,193 @@ func convertWebSearchResults(webResults []*types.WebSearchResult) []*types.Searc
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// expandQueries generates paraphrases and synonyms using chat model to improve keyword recall
|
||||
func (p *PluginSearch) expandQueries(ctx context.Context, chatManage *types.ChatManage) []string {
|
||||
if p.modelService == nil || chatManage.ChatModelID == "" {
|
||||
pipelineWarn(ctx, "Search", "expansion_skip", map[string]interface{}{
|
||||
"reason": "no_model",
|
||||
})
|
||||
return nil
|
||||
}
|
||||
model, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "expansion_get_model_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
sys := "Generate up to 5 diverse paraphrases or keyword variants for the user query to improve keyword-based search recall. Respond ONLY with a JSON array of strings inside a fenced code block."
|
||||
usr := chatManage.RewriteQuery
|
||||
think := false
|
||||
resp, err := model.Chat(ctx, []chat.Message{{Role: "system", Content: sys}, {Role: "user", Content: usr}}, &chat.ChatOptions{Temperature: 0.2, MaxCompletionTokens: 80, Thinking: &think})
|
||||
if err != nil || resp.Content == "" {
|
||||
pipelineWarn(ctx, "Search", "expansion_model_call_failed", map[string]interface{}{
|
||||
"error": err,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
body := extractJSONBlock(resp.Content)
|
||||
var arr []string
|
||||
if err := json.Unmarshal([]byte(body), &arr); err != nil || len(arr) == 0 {
|
||||
// Fallback: split lines
|
||||
lines := strings.Split(resp.Content, "\n")
|
||||
for _, l := range lines {
|
||||
l = strings.TrimSpace(l)
|
||||
if l != "" {
|
||||
arr = append(arr, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
uniq := make(map[string]struct{})
|
||||
base := []string{chatManage.Query, chatManage.RewriteQuery, chatManage.ProcessedQuery}
|
||||
for _, b := range base {
|
||||
if s := strings.TrimSpace(b); s != "" {
|
||||
uniq[strings.ToLower(s)] = struct{}{}
|
||||
}
|
||||
}
|
||||
expansions := make([]string, 0, len(arr))
|
||||
for _, a := range arr {
|
||||
s := strings.TrimSpace(a)
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(s)
|
||||
if _, ok := uniq[key]; ok {
|
||||
continue
|
||||
}
|
||||
uniq[key] = struct{}{}
|
||||
expansions = append(expansions, s)
|
||||
if len(expansions) >= 5 {
|
||||
break
|
||||
}
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "expansion_result", map[string]interface{}{
|
||||
"variants": len(expansions),
|
||||
})
|
||||
return expansions
|
||||
if p.modelService == nil || chatManage.ChatModelID == "" {
|
||||
pipelineWarn(ctx, "Search", "expansion_skip", map[string]interface{}{
|
||||
"reason": "no_model",
|
||||
})
|
||||
return nil
|
||||
}
|
||||
model, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "expansion_get_model_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
sys := "Generate up to 5 diverse paraphrases or keyword variants for the user query to improve keyword-based search recall. Respond ONLY with a JSON array of strings inside a fenced code block."
|
||||
usr := chatManage.RewriteQuery
|
||||
think := false
|
||||
resp, err := model.Chat(ctx, []chat.Message{
|
||||
{Role: "system", Content: sys},
|
||||
{Role: "user", Content: usr},
|
||||
}, &chat.ChatOptions{Temperature: 0.2, MaxCompletionTokens: 200, Thinking: &think})
|
||||
if err != nil || resp.Content == "" {
|
||||
pipelineWarn(ctx, "Search", "expansion_model_call_failed", map[string]interface{}{
|
||||
"error": err,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
body := extractJSONBlock(resp.Content)
|
||||
var arr []string
|
||||
if err := json.Unmarshal([]byte(body), &arr); err != nil || len(arr) == 0 {
|
||||
// Fallback: split lines
|
||||
lines := strings.Split(resp.Content, "\n")
|
||||
for _, l := range lines {
|
||||
l = strings.TrimSpace(l)
|
||||
if l != "" {
|
||||
arr = append(arr, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
uniq := make(map[string]struct{})
|
||||
base := []string{chatManage.Query, chatManage.RewriteQuery, chatManage.ProcessedQuery}
|
||||
for _, b := range base {
|
||||
if s := strings.TrimSpace(b); s != "" {
|
||||
uniq[strings.ToLower(s)] = struct{}{}
|
||||
}
|
||||
}
|
||||
expansions := make([]string, 0, len(arr))
|
||||
for _, a := range arr {
|
||||
s := strings.TrimSpace(a)
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(s)
|
||||
if _, ok := uniq[key]; ok {
|
||||
continue
|
||||
}
|
||||
uniq[key] = struct{}{}
|
||||
expansions = append(expansions, s)
|
||||
if len(expansions) >= 5 {
|
||||
break
|
||||
}
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "expansion_result", map[string]interface{}{
|
||||
"variants": len(expansions),
|
||||
})
|
||||
return expansions
|
||||
}
|
||||
|
||||
func extractJSONBlock(text string) string {
|
||||
t := strings.TrimSpace(text)
|
||||
if i := strings.Index(t, "["); i >= 0 {
|
||||
j := strings.LastIndex(t, "]")
|
||||
if j > i {
|
||||
return t[i : j+1]
|
||||
}
|
||||
}
|
||||
return "[]"
|
||||
t := strings.TrimSpace(text)
|
||||
if i := strings.Index(t, "["); i >= 0 {
|
||||
j := strings.LastIndex(t, "]")
|
||||
if j > i {
|
||||
return t[i : j+1]
|
||||
}
|
||||
}
|
||||
return "[]"
|
||||
}
|
||||
|
||||
// normalizeKeywordSearchResults normalizes keyword search result scores into [0,1] globally across all knowledge bases
|
||||
// Improvements:
|
||||
// 1. Uses robust normalization with percentile-based bounds to handle outliers
|
||||
// 2. Handles edge cases: single result, no variance, negative scores
|
||||
// 3. Global normalization ensures fair comparison across different knowledge bases
|
||||
func normalizeKeywordSearchResults(ctx context.Context, results []*types.SearchResult) {
|
||||
// Filter keyword match results
|
||||
keywordResults := make([]*types.SearchResult, 0)
|
||||
for _, result := range results {
|
||||
if result.MatchType == types.MatchTypeKeywords {
|
||||
keywordResults = append(keywordResults, result)
|
||||
}
|
||||
}
|
||||
|
||||
if len(keywordResults) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Single result: set to 1.0
|
||||
if len(keywordResults) == 1 {
|
||||
keywordResults[0].Score = 1.0
|
||||
return
|
||||
}
|
||||
|
||||
// Find min and max scores globally
|
||||
minS := keywordResults[0].Score
|
||||
maxS := keywordResults[0].Score
|
||||
for _, r := range keywordResults {
|
||||
if r.Score < minS {
|
||||
minS = r.Score
|
||||
}
|
||||
if r.Score > maxS {
|
||||
maxS = r.Score
|
||||
}
|
||||
}
|
||||
|
||||
// No variance: all scores are the same
|
||||
if maxS <= minS {
|
||||
for _, r := range keywordResults {
|
||||
r.Score = 1.0
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "keyword_scores_no_variance", map[string]interface{}{
|
||||
"count": len(keywordResults),
|
||||
"score": minS,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Robust normalization: use percentile-based bounds to reduce outlier impact
|
||||
// For small groups, use min/max; for larger groups, use 5th and 95th percentiles
|
||||
normalizeMin := minS
|
||||
normalizeMax := maxS
|
||||
|
||||
if len(keywordResults) >= 10 {
|
||||
// For larger groups, use percentile-based bounds to handle outliers
|
||||
// Sort scores to find percentiles
|
||||
scores := make([]float64, len(keywordResults))
|
||||
for i, r := range keywordResults {
|
||||
scores[i] = r.Score
|
||||
}
|
||||
sort.Float64s(scores)
|
||||
|
||||
// Use 5th and 95th percentiles to reduce outlier impact
|
||||
p5Idx := len(scores) * 5 / 100
|
||||
p95Idx := len(scores) * 95 / 100
|
||||
if p5Idx < len(scores) {
|
||||
normalizeMin = scores[p5Idx]
|
||||
}
|
||||
if p95Idx < len(scores) {
|
||||
normalizeMax = scores[p95Idx]
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize scores with bounds checking
|
||||
rangeSize := normalizeMax - normalizeMin
|
||||
if rangeSize > 0 {
|
||||
for _, r := range keywordResults {
|
||||
// Clamp to [normalizeMin, normalizeMax] before normalization
|
||||
clampedScore := r.Score
|
||||
if clampedScore < normalizeMin {
|
||||
clampedScore = normalizeMin
|
||||
} else if clampedScore > normalizeMax {
|
||||
clampedScore = normalizeMax
|
||||
}
|
||||
|
||||
// Normalize to [0, 1]
|
||||
ns := (clampedScore - normalizeMin) / rangeSize
|
||||
if ns < 0 {
|
||||
ns = 0
|
||||
} else if ns > 1 {
|
||||
ns = 1
|
||||
}
|
||||
r.Score = ns
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Search", "normalize_keyword_scores", map[string]interface{}{
|
||||
"count": len(keywordResults),
|
||||
"raw_min": minS,
|
||||
"raw_max": maxS,
|
||||
"normalize_min": normalizeMin,
|
||||
"normalize_max": normalizeMax,
|
||||
})
|
||||
} else {
|
||||
// Fallback: all scores are the same after percentile filtering
|
||||
for _, r := range keywordResults {
|
||||
r.Score = 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,16 @@ func NewChunkService(
|
||||
}
|
||||
}
|
||||
|
||||
// GetRepository gets the chunk repository
|
||||
// Parameters:
|
||||
// - ctx: Context with authentication and request information
|
||||
//
|
||||
// Returns:
|
||||
// - interfaces.ChunkRepository: Chunk repository
|
||||
func (s *chunkService) GetRepository() interfaces.ChunkRepository {
|
||||
return s.chunkRepository
|
||||
}
|
||||
|
||||
// CreateChunks creates multiple chunks
|
||||
// This method persists a batch of document chunks to the repository
|
||||
// Parameters:
|
||||
|
||||
@@ -106,6 +106,16 @@ func NewKnowledgeService(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetRepository gets the knowledge repository
|
||||
// Parameters:
|
||||
// - ctx: Context with authentication and request information
|
||||
//
|
||||
// Returns:
|
||||
// - interfaces.KnowledgeRepository: Knowledge repository
|
||||
func (s *knowledgeService) GetRepository() interfaces.KnowledgeRepository {
|
||||
return s.repo
|
||||
}
|
||||
|
||||
// CreateKnowledgeFromFile creates a knowledge entry from an uploaded file
|
||||
func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
kbID string, file *multipart.FileHeader, metadata map[string]string, enableMultimodel *bool,
|
||||
@@ -413,7 +423,7 @@ func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context,
|
||||
now := time.Now()
|
||||
title := safeTitle
|
||||
if title == "" {
|
||||
title = fmt.Sprintf("手工知识-%s", now.Format("20060102-150405"))
|
||||
title = fmt.Sprintf("Knowledge-%s", now.Format("20060102-150405"))
|
||||
}
|
||||
|
||||
fileName := ensureManualFileName(title)
|
||||
@@ -844,7 +854,8 @@ func (s *knowledgeService) processDocument(ctx context.Context,
|
||||
}
|
||||
|
||||
// Split file into chunks using document reader service
|
||||
span.AddEvent("start split file")
|
||||
logger.GetLogger(ctx).Infof("processDocument split file content size: %d, file name: %s, file type: %s, separators: %v, enable multimodal: %v",
|
||||
len(contentBytes), knowledge.FileName, knowledge.FileType, kb.ChunkingConfig.Separators, enableMultimodel)
|
||||
resp, err := s.docReaderClient.ReadFromFile(ctx, &proto.ReadFromFileRequest{
|
||||
FileContent: contentBytes,
|
||||
FileName: knowledge.FileName,
|
||||
@@ -3040,41 +3051,70 @@ func ensureManualFileName(title string) string {
|
||||
return trimmed + manualFileExtension
|
||||
}
|
||||
|
||||
func splitManualContent(content string) []string {
|
||||
clean := strings.TrimSpace(content)
|
||||
if clean == "" {
|
||||
return []string{}
|
||||
}
|
||||
normalized := strings.ReplaceAll(clean, "\r\n", "\n")
|
||||
segments := strings.Split(normalized, "\n\n")
|
||||
results := make([]string, 0, len(segments))
|
||||
for _, seg := range segments {
|
||||
part := strings.TrimSpace(seg)
|
||||
if part != "" {
|
||||
results = append(results, part)
|
||||
}
|
||||
}
|
||||
if len(results) == 0 {
|
||||
results = append(results, clean)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
|
||||
kb *types.KnowledgeBase, knowledge *types.Knowledge, content string, sync bool,
|
||||
) {
|
||||
passages := splitManualContent(content)
|
||||
if len(passages) == 0 {
|
||||
passages = []string{content}
|
||||
clean := strings.TrimSpace(content)
|
||||
if clean == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 docreader 按照 MD 格式处理,并使用知识库配置的分隔符
|
||||
contentBytes := []byte(clean)
|
||||
fileName := ensureManualFileName(knowledge.Title)
|
||||
fileType := "md"
|
||||
|
||||
// 检查是否需要启用多模态(对于手动内容通常不需要,但保持一致性)
|
||||
enableMultimodel := kb.ChunkingConfig.EnableMultimodal && kb.StorageConfig.Provider != ""
|
||||
|
||||
logger.GetLogger(ctx).Infof("triggerManualProcessing split manual content size: %d, file name: %s, file type: %s, separators: %v, enable multimodal: %v",
|
||||
len(contentBytes), fileName, fileType, kb.ChunkingConfig.Separators, enableMultimodel)
|
||||
|
||||
// 调用 docreader 解析 markdown 内容
|
||||
resp, err := s.docReaderClient.ReadFromFile(ctx, &proto.ReadFromFileRequest{
|
||||
FileContent: contentBytes,
|
||||
FileName: fileName,
|
||||
FileType: fileType,
|
||||
ReadConfig: &proto.ReadConfig{
|
||||
ChunkSize: int32(kb.ChunkingConfig.ChunkSize),
|
||||
ChunkOverlap: int32(kb.ChunkingConfig.ChunkOverlap),
|
||||
Separators: kb.ChunkingConfig.Separators,
|
||||
EnableMultimodal: enableMultimodel,
|
||||
StorageConfig: &proto.StorageConfig{
|
||||
Provider: proto.StorageProvider(proto.StorageProvider_value[strings.ToUpper(kb.StorageConfig.Provider)]),
|
||||
Region: kb.StorageConfig.Region,
|
||||
BucketName: kb.StorageConfig.BucketName,
|
||||
AccessKeyId: kb.StorageConfig.SecretID,
|
||||
SecretAccessKey: kb.StorageConfig.SecretKey,
|
||||
AppId: kb.StorageConfig.AppID,
|
||||
PathPrefix: kb.StorageConfig.PathPrefix,
|
||||
},
|
||||
VlmConfig: &proto.VLMConfig{
|
||||
ModelName: kb.VLMConfig.ModelName,
|
||||
BaseUrl: kb.VLMConfig.BaseURL,
|
||||
ApiKey: kb.VLMConfig.APIKey,
|
||||
InterfaceType: kb.VLMConfig.InterfaceType,
|
||||
},
|
||||
},
|
||||
RequestId: ctx.Value(types.RequestIDContextKey).(string),
|
||||
})
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).WithField("knowledge_id", knowledge.ID).
|
||||
WithField("error", err).Errorf("triggerManualProcessing read file failed")
|
||||
knowledge.ParseStatus = "failed"
|
||||
knowledge.ErrorMessage = err.Error()
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
return
|
||||
}
|
||||
|
||||
if sync {
|
||||
s.processDocumentFromPassage(ctx, kb, knowledge, passages)
|
||||
s.processChunks(ctx, kb, knowledge, resp.Chunks)
|
||||
return
|
||||
}
|
||||
|
||||
newCtx := logger.CloneContext(ctx)
|
||||
go s.processDocumentFromPassage(newCtx, kb, knowledge, passages)
|
||||
go s.processChunks(newCtx, kb, knowledge, resp.Chunks)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) cleanupKnowledgeResources(ctx context.Context, knowledge *types.Knowledge) error {
|
||||
|
||||
@@ -45,6 +45,16 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
}
|
||||
}
|
||||
|
||||
// GetRepository gets the knowledge base repository
|
||||
// Parameters:
|
||||
// - ctx: Context with authentication and request information
|
||||
//
|
||||
// Returns:
|
||||
// - interfaces.KnowledgeBaseRepository: Knowledge base repository
|
||||
func (s *knowledgeBaseService) GetRepository() interfaces.KnowledgeBaseRepository {
|
||||
return s.repo
|
||||
}
|
||||
|
||||
// CreateKnowledgeBase creates a new knowledge base
|
||||
func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
|
||||
kb *types.KnowledgeBase,
|
||||
@@ -303,18 +313,18 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
var embeddingModel embedding.Embedder
|
||||
var kb *types.KnowledgeBase
|
||||
|
||||
kb, err = s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add vector retrieval params if supported
|
||||
if retrieveEngine.SupportRetriever(types.VectorRetrieverType) && !params.DisableVectorMatch {
|
||||
logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters")
|
||||
|
||||
kb, err = s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Getting embedding model, model ID: %s", kb.EmbeddingModelID)
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err != nil {
|
||||
@@ -343,8 +353,8 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
logger.Info(ctx, "Vector retrieval parameters setup completed")
|
||||
}
|
||||
|
||||
// Add keyword retrieval params if supported
|
||||
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) && !params.DisableKeywordsMatch {
|
||||
// Add keyword retrieval params if supported and not FAQ
|
||||
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) && !params.DisableKeywordsMatch && kb.Type != types.KnowledgeBaseTypeFAQ {
|
||||
logger.Info(ctx, "Keyword retrieval supported, preparing keyword retrieval parameters")
|
||||
retrieveParams = append(retrieveParams, types.RetrieveParams{
|
||||
Query: params.QueryText,
|
||||
@@ -372,41 +382,6 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Normalize keyword retriever scores into [0,1] per-engine batch
|
||||
for i := range retrieveResults {
|
||||
rr := retrieveResults[i]
|
||||
if rr.Error != nil || rr.RetrieverType != types.KeywordsRetrieverType || len(rr.Results) == 0 {
|
||||
continue
|
||||
}
|
||||
minS := rr.Results[0].Score
|
||||
maxS := rr.Results[0].Score
|
||||
for _, r := range rr.Results {
|
||||
if r.Score < minS {
|
||||
minS = r.Score
|
||||
}
|
||||
if r.Score > maxS {
|
||||
maxS = r.Score
|
||||
}
|
||||
}
|
||||
if maxS > minS {
|
||||
for _, r := range rr.Results {
|
||||
ns := (r.Score - minS) / (maxS - minS)
|
||||
if ns < 0 {
|
||||
ns = 0
|
||||
} else if ns > 1 {
|
||||
ns = 1
|
||||
}
|
||||
r.Score = ns
|
||||
}
|
||||
logger.Infof(ctx, "Normalized keyword scores for engine %s: min=%f, max=%f", rr.RetrieverEngineType, minS, maxS)
|
||||
} else {
|
||||
for _, r := range rr.Results {
|
||||
r.Score = 1.0
|
||||
}
|
||||
logger.Infof(ctx, "Keyword scores have no variance for engine %s, set to 1.0", rr.RetrieverEngineType)
|
||||
}
|
||||
}
|
||||
|
||||
// Collect all results from different retrievers and deduplicate by chunk ID
|
||||
logger.Infof(ctx, "Processing retrieval results")
|
||||
matchResults := []*types.IndexWithScore{}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
|
||||
llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
@@ -485,8 +484,8 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
|
||||
fallbackResponse = tenantConv.FallbackResponse
|
||||
enableRewrite = tenantConv.EnableRewrite
|
||||
|
||||
if tenantConv.MaxTokens != 0 {
|
||||
summaryConfig.MaxTokens = tenantConv.MaxTokens
|
||||
if tenantConv.MaxCompletionTokens != 0 {
|
||||
summaryConfig.MaxCompletionTokens = tenantConv.MaxCompletionTokens
|
||||
}
|
||||
if tenantConv.Prompt != "" {
|
||||
summaryConfig.Prompt = tenantConv.Prompt
|
||||
@@ -882,10 +881,10 @@ func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, qu
|
||||
WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config
|
||||
}
|
||||
|
||||
if tenantInfo.AgentConfig.UseCustomSystemPrompt {
|
||||
agentConfig.SystemPrompt = tenantInfo.AgentConfig.SystemPrompt
|
||||
} else {
|
||||
agentConfig.SystemPrompt = agent.DefaultSystemPromptTemplate
|
||||
agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt
|
||||
if agentConfig.UseCustomSystemPrompt {
|
||||
agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true)
|
||||
agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false)
|
||||
}
|
||||
|
||||
// Set web search max results from tenant config (default: 5)
|
||||
|
||||
Reference in New Issue
Block a user