Merge branch 'custom_agent'
This commit is contained in:
@@ -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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user