refactor: 调整智能体配置,增强智能体选择与状态管理

This commit is contained in:
wizardchen
2025-12-26 21:31:02 +08:00
parent abfe87eaed
commit 0ca947981a
36 changed files with 2421 additions and 916 deletions
@@ -60,13 +60,8 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
{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})
}
@@ -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()
}
@@ -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()
}