init commit

This commit is contained in:
wizardchen
2025-08-05 15:08:07 +08:00
commit 56eb2bce33
282 changed files with 49077 additions and 0 deletions
@@ -0,0 +1,60 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginChatCompletion implements chat completion functionality
// as a plugin that can be registered to EventManager
type PluginChatCompletion struct {
modelService interfaces.ModelService // Interface for model operations
}
// NewPluginChatCompletion creates a new PluginChatCompletion instance
// and registers it with the EventManager
func NewPluginChatCompletion(eventManager *EventManager, modelService interfaces.ModelService) *PluginChatCompletion {
res := &PluginChatCompletion{
modelService: modelService,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginChatCompletion) ActivationEvents() []types.EventType {
return []types.EventType{types.CHAT_COMPLETION}
}
// OnEvent handles chat completion events
// It prepares the chat model, messages, and calls the model to generate responses
func (p *PluginChatCompletion) OnEvent(
ctx context.Context, eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting chat completion")
// Prepare chat model and options
chatModel, opt, err := prepareChatModel(ctx, p.modelService, chatManage)
if err != nil {
return ErrGetChatModel.WithError(err)
}
// Prepare messages including conversation history
logger.Info(ctx, "Preparing chat messages with history")
chatMessages := prepareMessagesWithHistory(chatManage)
// Call the chat model to generate response
logger.Info(ctx, "Calling chat model")
chatResponse, err := chatModel.Chat(ctx, chatMessages, opt)
if err != nil {
logger.Errorf(ctx, "Failed to call chat model: %v", err)
return ErrModelCall.WithError(err)
}
logger.Info(ctx, "Chat completion successful")
chatManage.ChatResponse = chatResponse
return next()
}
@@ -0,0 +1,62 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginChatCompletionStream implements streaming chat completion functionality
// as a plugin that can be registered to EventManager
type PluginChatCompletionStream struct {
modelService interfaces.ModelService // Interface for model operations
}
// NewPluginChatCompletionStream creates a new PluginChatCompletionStream instance
// and registers it with the EventManager
func NewPluginChatCompletionStream(eventManager *EventManager,
modelService interfaces.ModelService,
) *PluginChatCompletionStream {
res := &PluginChatCompletionStream{
modelService: modelService,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginChatCompletionStream) ActivationEvents() []types.EventType {
return []types.EventType{types.CHAT_COMPLETION_STREAM}
}
// OnEvent handles streaming chat completion events
// It prepares the chat model, messages, and initiates streaming response
func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting chat completion stream")
// Prepare chat model and options
chatModel, opt, err := prepareChatModel(ctx, p.modelService, chatManage)
if err != nil {
return ErrGetChatModel.WithError(err)
}
// Prepare base messages without history
logger.Info(ctx, "Preparing chat messages")
chatMessages := prepareMessagesWithHistory(chatManage)
// Initiate streaming chat model call
logger.Info(ctx, "Calling chat stream model")
responseChan, err := chatModel.ChatStream(ctx, chatMessages, opt)
if err != nil {
logger.Errorf(ctx, "Failed to call chat stream model: %v", err)
return ErrModelCall.WithError(err)
}
logger.Info(ctx, "Chat stream initiated successfully")
chatManage.ResponseChan = responseChan
return next()
}
@@ -0,0 +1,161 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// Plugin defines the interface for chat pipeline plugins
// Plugins can handle specific events in the chat pipeline
type Plugin interface {
// OnEvent handles the event with given context and chat management object
OnEvent(
ctx context.Context,
eventType types.EventType,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError
// ActivationEvents returns the event types this plugin can handle
ActivationEvents() []types.EventType
}
// EventManager manages plugins and their event handling
type EventManager struct {
// Map of event types to registered plugins
listeners map[types.EventType][]Plugin
// Map of event types to handler functions
handlers map[types.EventType]func(context.Context, types.EventType, *types.ChatManage) *PluginError
}
// NewEventManager creates and initializes a new EventManager
func NewEventManager() *EventManager {
return &EventManager{
listeners: make(map[types.EventType][]Plugin),
handlers: make(map[types.EventType]func(context.Context, types.EventType, *types.ChatManage) *PluginError),
}
}
// Register adds a plugin to the EventManager and sets up its event handlers
func (e *EventManager) Register(plugin Plugin) {
if e.listeners == nil {
e.listeners = make(map[types.EventType][]Plugin)
}
if e.handlers == nil {
e.handlers = make(map[types.EventType]func(context.Context, types.EventType, *types.ChatManage) *PluginError)
}
for _, eventType := range plugin.ActivationEvents() {
e.listeners[eventType] = append(e.listeners[eventType], plugin)
e.handlers[eventType] = e.buildHandler(e.listeners[eventType])
}
}
// buildHandler constructs a handler chain for the given plugins
func (e *EventManager) buildHandler(plugins []Plugin) func(
ctx context.Context, eventType types.EventType, chatManage *types.ChatManage,
) *PluginError {
next := func(context.Context, types.EventType, *types.ChatManage) *PluginError { return nil }
for i := len(plugins) - 1; i >= 0; i-- {
current := plugins[i]
prevNext := next
next = func(ctx context.Context, eventType types.EventType, chatManage *types.ChatManage) *PluginError {
return current.OnEvent(ctx, eventType, chatManage, func() *PluginError {
return prevNext(ctx, eventType, chatManage)
})
}
}
return next
}
// Trigger invokes the handler for the specified event type
func (e *EventManager) Trigger(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage,
) *PluginError {
if handler, ok := e.handlers[eventType]; ok {
return handler(ctx, eventType, chatManage)
}
return nil
}
// PluginError represents an error in plugin execution
type PluginError struct {
Err error // Original error
Description string // Human-readable description
ErrorType string // Error type identifier
}
// Predefined plugin errors
var (
ErrSearchNothing = &PluginError{
Description: "No relevant content found",
ErrorType: "search_nothing",
}
ErrSearch = &PluginError{
Description: "Failed to search knowledge base",
ErrorType: "search_failed",
}
ErrRerank = &PluginError{
Description: "Reranking failed",
ErrorType: "rerank_failed",
}
ErrGetRerankModel = &PluginError{
Description: "Failed to get rerank model",
ErrorType: "get_rerank_model_failed",
}
ErrGetChatModel = &PluginError{
Description: "Failed to get chat model",
ErrorType: "get_chat_model_failed",
}
ErrTemplateParse = &PluginError{
Description: "Failed to parse context template",
ErrorType: "template_parse_failed",
}
ErrTemplateExecute = &PluginError{
Description: "Failed to generate search content",
ErrorType: "template_execution_failed",
}
ErrModelCall = &PluginError{
Description: "Failed to call model",
ErrorType: "model_call_failed",
}
ErrGetHistory = &PluginError{
Description: "Failed to get conversation history",
ErrorType: "get_history_failed",
}
)
// clone creates a copy of the PluginError
func (p *PluginError) clone() *PluginError {
return &PluginError{
Description: p.Description,
ErrorType: p.ErrorType,
}
}
// WithError attaches an error to the PluginError and returns a new instance
func (p *PluginError) WithError(err error) *PluginError {
pp := p.clone()
pp.Err = err
return pp
}
// NewFallbackChan creates a channel with a single fallback response
func NewFallbackChan(ctx context.Context, fallbackResponse string) <-chan types.StreamResponse {
fallabackChan := make(chan types.StreamResponse)
go func() {
fallabackChan <- NewFallback(ctx, fallbackResponse)
close(fallabackChan)
}()
return fallabackChan
}
// NewFallback creates a fallback stream response with the given content
func NewFallback(ctx context.Context, fallbackResponse string) types.StreamResponse {
requestID := ctx.Value(types.RequestIDContextKey).(string)
return types.StreamResponse{
ID: requestID,
ResponseType: types.ResponseTypeAnswer,
Content: fallbackResponse,
Done: true,
}
}
@@ -0,0 +1,125 @@
package chatpipline
import (
"context"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
// Define a test Plugin implementation
type testPlugin struct {
name string
events []types.EventType
shouldError bool
errorToReturn *PluginError
}
func (p *testPlugin) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
if p.shouldError {
return p.errorToReturn
}
fmt.Printf("Plugin %s triggered\n", p.name)
err := next()
fmt.Printf("Plugin %s finished\n", p.name)
return err
}
func (p *testPlugin) ActivationEvents() []types.EventType {
return p.events
}
func TestTrigger(t *testing.T) {
// Prepare test data
ctx := context.Background()
chatManage := &types.ChatManage{}
testEvent := types.EventType("test_event")
// Test scenario 1: No plugins registered
t.Run("NoPluginsRegistered", func(t *testing.T) {
manager := &EventManager{}
err := manager.Trigger(ctx, testEvent, chatManage)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
})
// Test scenario 2: Register a normally working plugin
t.Run("SinglePluginSuccess", func(t *testing.T) {
manager := &EventManager{}
plugin := &testPlugin{
name: "test_plugin",
events: []types.EventType{testEvent},
}
manager.Register(plugin)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
})
// Test scenario 3: Plugin chain call
t.Run("PluginChain", func(t *testing.T) {
manager := &EventManager{}
plugin1 := &testPlugin{
name: "plugin1",
events: []types.EventType{testEvent},
}
plugin2 := &testPlugin{
name: "plugin2",
events: []types.EventType{testEvent},
}
manager.Register(plugin1)
manager.Register(plugin2)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
})
// Test scenario 4: Plugin returns error
t.Run("PluginReturnsError", func(t *testing.T) {
manager := &EventManager{}
expectedErr := &PluginError{Description: "test error"}
plugin := &testPlugin{
name: "error_plugin",
events: []types.EventType{testEvent},
shouldError: true,
errorToReturn: expectedErr,
}
manager.Register(plugin)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != expectedErr {
t.Errorf("Expected error %v, got %v", expectedErr, err)
}
})
// Test scenario 5: A plugin in the chain returns error
t.Run("ErrorInPluginChain", func(t *testing.T) {
manager := &EventManager{}
expectedErr := &PluginError{Description: "test error"}
plugin1 := &testPlugin{
name: "plugin1",
events: []types.EventType{testEvent},
}
plugin2 := &testPlugin{
name: "plugin2",
events: []types.EventType{testEvent},
shouldError: true,
errorToReturn: expectedErr,
}
manager.Register(plugin1)
manager.Register(plugin2)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != expectedErr {
t.Errorf("Expected error %v, got %v", expectedErr, err)
}
})
}
@@ -0,0 +1,67 @@
package chatpipline
import (
"context"
"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"
)
// prepareChatModel shared logic to prepare chat model and options
func prepareChatModel(ctx context.Context, modelService interfaces.ModelService,
chatManage *types.ChatManage,
) (chat.Chat, *chat.ChatOptions, error) {
logger.Infof(ctx, "Getting chat model, model ID: %s", chatManage.ChatModelID)
chatModel, err := modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get chat model: %v", err)
return nil, nil, err
}
logger.Info(ctx, "Setting up chat options")
opt := &chat.ChatOptions{
Temperature: chatManage.SummaryConfig.Temperature,
TopP: chatManage.SummaryConfig.TopP,
Seed: chatManage.SummaryConfig.Seed,
MaxTokens: chatManage.SummaryConfig.MaxTokens,
MaxCompletionTokens: chatManage.SummaryConfig.MaxCompletionTokens,
FrequencyPenalty: chatManage.SummaryConfig.FrequencyPenalty,
PresencePenalty: chatManage.SummaryConfig.PresencePenalty,
}
return chatModel, opt, nil
}
// prepareBaseMessages prepare basic messages (system prompt and current user content)
func prepareBaseMessages(chatManage *types.ChatManage) []chat.Message {
var chatMessages []chat.Message
chatMessages = append(chatMessages, chat.Message{Role: "system", Content: chatManage.SummaryConfig.Prompt})
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: chatManage.UserContent})
return chatMessages
}
// prepareMessagesWithHistory prepare complete messages including history
func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
chatMessages := []chat.Message{
{Role: "system", Content: chatManage.SummaryConfig.Prompt},
}
chatHistory := chatManage.History
if len(chatHistory) > 2 {
chatHistory = chatHistory[len(chatHistory)-2:]
}
// Add conversation history
for _, history := range chatHistory {
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query})
chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer})
}
// Add current user message
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: chatManage.UserContent})
return chatMessages
}
@@ -0,0 +1,53 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginFilterTopK is a plugin that filters search results to keep only the top K items
type PluginFilterTopK struct{}
// NewPluginFilterTopK creates a new instance of PluginFilterTopK and registers it with the event manager
func NewPluginFilterTopK(eventManager *EventManager) *PluginFilterTopK {
res := &PluginFilterTopK{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types that this plugin responds to
func (p *PluginFilterTopK) ActivationEvents() []types.EventType {
return []types.EventType{types.FILTER_TOP_K}
}
// OnEvent handles the FILTER_TOP_K event by filtering results to keep only the top K items
// It can filter MergeResult, RerankResult, or SearchResult depending on which is available
func (p *PluginFilterTopK) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting filter top-K process")
logger.Infof(ctx, "Filter configuration: top-K = %d", chatManage.RerankTopK)
filterTopK := func(searchResult []*types.SearchResult, topK int) []*types.SearchResult {
if topK > 0 && len(searchResult) > topK {
logger.Infof(ctx, "Filtering results: before=%d, after=%d", len(searchResult), topK)
searchResult = searchResult[:topK]
}
return searchResult
}
if len(chatManage.MergeResult) > 0 {
chatManage.MergeResult = filterTopK(chatManage.MergeResult, chatManage.RerankTopK)
} else if len(chatManage.RerankResult) > 0 {
chatManage.RerankResult = filterTopK(chatManage.RerankResult, chatManage.RerankTopK)
} else if len(chatManage.SearchResult) > 0 {
chatManage.SearchResult = filterTopK(chatManage.SearchResult, chatManage.RerankTopK)
} else {
logger.Info(ctx, "No results to filter")
}
logger.Info(ctx, "Filter top-K process completed")
return next()
}
@@ -0,0 +1,183 @@
package chatpipline
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginIntoChatMessage handles the transformation of search results into chat messages
type PluginIntoChatMessage struct{}
// NewPluginIntoChatMessage creates and registers a new PluginIntoChatMessage instance
func NewPluginIntoChatMessage(eventManager *EventManager) *PluginIntoChatMessage {
res := &PluginIntoChatMessage{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginIntoChatMessage) ActivationEvents() []types.EventType {
return []types.EventType{types.INTO_CHAT_MESSAGE}
}
// OnEvent processes the INTO_CHAT_MESSAGE event to format chat message content
func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Extract content from merge results
passages := make([]string, len(chatManage.MergeResult))
for i, result := range chatManage.MergeResult {
// 合并内容和图片信息
passages[i] = getEnrichedPassageForChat(ctx, result)
}
// Parse the context template
tmpl, err := template.New("searchContent").Parse(chatManage.SummaryConfig.ContextTemplate)
if err != nil {
return ErrTemplateParse.WithError(err)
}
// Prepare weekday names for template
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 {
return ErrTemplateExecute.WithError(err)
}
// Set formatted content back to chat management
chatManage.UserContent = userContent.String()
return next()
}
// getEnrichedPassageForChat 合并Content和ImageInfo的文本内容,为聊天消息准备
func getEnrichedPassageForChat(ctx context.Context, result *types.SearchResult) string {
// 如果没有图片信息,直接返回内容
if result.Content == "" && result.ImageInfo == "" {
return ""
}
// 如果只有内容,没有图片信息
if result.ImageInfo == "" {
return result.Content
}
// 处理图片信息并与内容合并
return enrichContentWithImageInfo(ctx, result.Content, result.ImageInfo)
}
// 正则表达式用于匹配Markdown图片链接
var markdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
// enrichContentWithImageInfo 将图片信息与文本内容合并
func enrichContentWithImageInfo(ctx context.Context, content string, imageInfoJSON string) string {
// 解析ImageInfo
var imageInfos []types.ImageInfo
err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos)
if err != nil {
logger.Warnf(ctx, "Failed to parse ImageInfo: %v, using content only", err)
return content
}
if len(imageInfos) == 0 {
return content
}
// 创建图片URL到信息的映射
imageInfoMap := make(map[string]*types.ImageInfo)
for i := range imageInfos {
if imageInfos[i].URL != "" {
imageInfoMap[imageInfos[i].URL] = &imageInfos[i]
}
// 同时检查原始URL
if imageInfos[i].OriginalURL != "" {
imageInfoMap[imageInfos[i].OriginalURL] = &imageInfos[i]
}
}
// 查找内容中的所有Markdown图片链接
matches := markdownImageRegex.FindAllStringSubmatch(content, -1)
// 用于存储已处理的图片URL
processedURLs := make(map[string]bool)
logger.Infof(ctx, "Found %d Markdown image links in content", len(matches))
// 替换每个图片链接,添加描述和OCR文本
for _, match := range matches {
if len(match) < 3 {
continue
}
// 提取图片URL,忽略alt文本
imgURL := match[2]
// 标记该URL已处理
processedURLs[imgURL] = true
// 查找匹配的图片信息
imgInfo, found := imageInfoMap[imgURL]
// 如果找到匹配的图片信息,添加描述和OCR文本
if found && imgInfo != nil {
replacement := match[0] + "\n"
if imgInfo.Caption != "" {
replacement += fmt.Sprintf("图片描述: %s\n", imgInfo.Caption)
}
if imgInfo.OCRText != "" {
replacement += fmt.Sprintf("图片文本: %s\n", imgInfo.OCRText)
}
content = strings.Replace(content, match[0], replacement, 1)
}
}
// 处理未在内容中找到但存在于ImageInfo中的图片
var additionalImageTexts []string
for _, imgInfo := range imageInfos {
// 如果图片URL已经处理过,跳过
if processedURLs[imgInfo.URL] || processedURLs[imgInfo.OriginalURL] {
continue
}
var imgTexts []string
if imgInfo.Caption != "" {
imgTexts = append(imgTexts, fmt.Sprintf("图片 %s 的描述信息: %s", imgInfo.URL, imgInfo.Caption))
}
if imgInfo.OCRText != "" {
imgTexts = append(imgTexts, fmt.Sprintf("图片 %s 的文本: %s", imgInfo.URL, imgInfo.OCRText))
}
if len(imgTexts) > 0 {
additionalImageTexts = append(additionalImageTexts, imgTexts...)
}
}
// 如果有额外的图片信息,添加到内容末尾
if len(additionalImageTexts) > 0 {
if content != "" {
content += "\n\n"
}
content += "附加图片信息:\n" + strings.Join(additionalImageTexts, "\n")
}
logger.Debugf(ctx, "Enhanced content with image info: found %d Markdown images, added %d additional images",
len(matches), len(additionalImageTexts))
return content
}
@@ -0,0 +1,175 @@
package chatpipline
import (
"context"
"encoding/json"
"sort"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginMerge handles merging of search result chunks
type PluginMerge struct{}
// NewPluginMerge creates and registers a new PluginMerge instance
func NewPluginMerge(eventManager *EventManager) *PluginMerge {
res := &PluginMerge{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginMerge) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_MERGE}
}
// OnEvent processes the CHUNK_MERGE event to merge search result chunks
func (p *PluginMerge) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting chunk merge process")
// Use rerank results if available, fallback to search results
searchResult := chatManage.RerankResult
if len(searchResult) == 0 {
logger.Info(ctx, "No rerank results available, using search results")
searchResult = chatManage.SearchResult
}
logger.Infof(ctx, "Processing %d chunks for merging", len(searchResult))
if len(searchResult) == 0 {
logger.Info(ctx, "No chunks available for merging")
return next()
}
// Group chunks by their knowledge source ID
knowledgeGroup := make(map[string][]*types.SearchResult)
for _, chunk := range searchResult {
knowledgeGroup[chunk.KnowledgeID] = append(knowledgeGroup[chunk.KnowledgeID], chunk)
}
logger.Infof(ctx, "Grouped chunks by knowledge ID, %d knowledge sources", len(knowledgeGroup))
mergedChunks := []*types.SearchResult{}
// Process each knowledge source separately
for knowledgeID, chunks := range knowledgeGroup {
logger.Infof(ctx, "Processing knowledge ID: %s with %d chunks", knowledgeID, len(chunks))
// Sort chunks by their start position in the original document
sort.Slice(chunks, func(i, j int) bool {
if chunks[i].StartAt == chunks[j].StartAt {
return chunks[i].EndAt < chunks[j].EndAt
}
return chunks[i].StartAt < chunks[j].StartAt
})
// Merge overlapping or adjacent chunks
knowledgeMergedChunks := []*types.SearchResult{}
if chunks[0].ChunkType == types.ChunkTypeSummary {
knowledgeMergedChunks = append(knowledgeMergedChunks, chunks[0])
// skip the first chunk if it is summary chunk
// This is to avoid merging the summary chunk with the first content chunk
chunks = chunks[1:]
}
if len(chunks) > 0 {
knowledgeMergedChunks = append(knowledgeMergedChunks, chunks[0])
}
for i := 1; i < len(chunks); i++ {
lastChunk := knowledgeMergedChunks[len(knowledgeMergedChunks)-1]
// If the current chunk starts after the last chunk ends, add it to the merged chunks
if chunks[i].StartAt > lastChunk.EndAt {
knowledgeMergedChunks = append(knowledgeMergedChunks, chunks[i])
continue
}
// Merge overlapping chunks
if chunks[i].EndAt > lastChunk.EndAt {
lastChunk.Content = lastChunk.Content +
string([]rune(chunks[i].Content)[lastChunk.EndAt-chunks[i].StartAt:])
lastChunk.EndAt = chunks[i].EndAt
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
// 合并 ImageInfo
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
logger.Warnf(ctx, "Failed to merge ImageInfo: %v", err)
}
}
if chunks[i].Score > lastChunk.Score {
lastChunk.Score = chunks[i].Score
}
}
logger.Infof(ctx, "Merged %d chunks into %d chunks for knowledge ID: %s",
len(chunks), len(knowledgeMergedChunks), knowledgeID)
mergedChunks = append(mergedChunks, knowledgeMergedChunks...)
}
// Sort merged chunks by their score (highest first)
sort.Slice(mergedChunks, func(i, j int) bool {
return mergedChunks[i].Score > mergedChunks[j].Score
})
logger.Infof(ctx, "Final merged result: %d chunks, sorted by score", len(mergedChunks))
chatManage.MergeResult = mergedChunks
return next()
}
// mergeImageInfo 合并两个chunk的ImageInfo
func mergeImageInfo(ctx context.Context, target *types.SearchResult, source *types.SearchResult) error {
// 如果source没有ImageInfo,不需要合并
if source.ImageInfo == "" {
return nil
}
var sourceImageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(source.ImageInfo), &sourceImageInfos); err != nil {
logger.Warnf(ctx, "Failed to unmarshal source ImageInfo: %v", err)
return err
}
// 如果source的ImageInfo为空,不需要合并
if len(sourceImageInfos) == 0 {
return nil
}
// 处理target的ImageInfo
var targetImageInfos []types.ImageInfo
if target.ImageInfo != "" {
if err := json.Unmarshal([]byte(target.ImageInfo), &targetImageInfos); err != nil {
logger.Warnf(ctx, "Failed to unmarshal target ImageInfo: %v", err)
// 如果目标解析失败,直接使用源数据
target.ImageInfo = source.ImageInfo
return nil
}
}
// 合并ImageInfo
targetImageInfos = append(targetImageInfos, sourceImageInfos...)
// 去重
uniqueMap := make(map[string]bool)
uniqueImageInfos := make([]types.ImageInfo, 0, len(targetImageInfos))
for _, imgInfo := range targetImageInfos {
// 使用URL作为唯一标识
if imgInfo.URL != "" && !uniqueMap[imgInfo.URL] {
uniqueMap[imgInfo.URL] = true
uniqueImageInfos = append(uniqueImageInfos, imgInfo)
}
}
// 序列化合并后的ImageInfo
mergedImageInfoJSON, err := json.Marshal(uniqueImageInfos)
if err != nil {
logger.Warnf(ctx, "Failed to marshal merged ImageInfo: %v", err)
return err
}
// 更新目标chunk的ImageInfo
target.ImageInfo = string(mergedImageInfoJSON)
logger.Infof(ctx, "Successfully merged ImageInfo, total count: %d", len(uniqueImageInfos))
return nil
}
@@ -0,0 +1,180 @@
package chatpipline
import (
"context"
"regexp"
"strings"
"unicode"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"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{}
}
// Regular expressions for text cleaning
var (
multiSpaceRegex = regexp.MustCompile(`\s+`) // Multiple spaces
urlRegex = regexp.MustCompile(`https?://\S+`) // URLs
emailRegex = regexp.MustCompile(`\b[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}\b`) // Email addresses
punctRegex = regexp.MustCompile(`[^\p{L}\p{N}\s]`) // Punctuation marks
)
// NewPluginPreprocess Creates a new query preprocessing plugin
func NewPluginPreprocess(
eventManager *EventManager,
config *config.Config,
cleaner interfaces.ResourceCleaner,
) *PluginPreprocess {
// Use default dictionary for Jieba tokenizer
jieba := gojieba.NewJieba()
// Load stopwords from built-in stopword library
stopwords := loadStopwords()
res := &PluginPreprocess{
config: config,
jieba: jieba,
stopwords: stopwords,
}
// Register resource cleanup function
if cleaner != nil {
cleaner.RegisterWithName("JiebaPreprocessor", func() error {
res.Close()
return nil
})
}
eventManager.Register(res)
return res
}
// Load stopwords
func loadStopwords() map[string]struct{} {
// Directly use some common stopwords built into Jieba
commonStopwords := []string{
"的", "了", "和", "是", "在", "我", "你", "他", "她", "它",
"这", "那", "什么", "怎么", "如何", "为什么", "哪里", "什么时候",
"the", "is", "are", "am", "I", "you", "he", "she", "it", "this",
"that", "what", "how", "a", "an", "and", "or", "but", "if", "of",
"to", "in", "on", "at", "by", "for", "with", "about", "from",
"有", "无", "好", "来", "去", "说", "看", "想", "会", "可以",
"吗", "呢", "啊", "吧", "的话", "就是", "只是", "因为", "所以",
}
result := make(map[string]struct{}, len(commonStopwords))
for _, word := range commonStopwords {
result[word] = struct{}{}
}
return result
}
// ActivationEvents Register activation events
func (p *PluginPreprocess) ActivationEvents() []types.EventType {
return []types.EventType{types.PREPROCESS_QUERY}
}
// OnEvent Process events
func (p *PluginPreprocess) OnEvent(ctx context.Context, eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError) *PluginError {
if chatManage.RewriteQuery == "" {
return next()
}
logger.GetLogger(ctx).Infof("Starting query preprocessing, original query: %s", chatManage.RewriteQuery)
// 1. Basic text cleaning
processed := p.cleanText(chatManage.RewriteQuery)
// 2. Tokenization
segments := p.segmentText(processed)
// 3. Stopword filtering and reconstruction
filteredSegments := p.filterStopwords(segments)
// Update preprocessed query
chatManage.ProcessedQuery = strings.Join(filteredSegments, " ")
logger.GetLogger(ctx).Infof("Query preprocessing complete, processed query: %s", chatManage.ProcessedQuery)
return next()
}
// cleanText Basic text cleaning
func (p *PluginPreprocess) cleanText(text string) string {
// Remove URLs
text = urlRegex.ReplaceAllString(text, " ")
// Remove email addresses
text = emailRegex.ReplaceAllString(text, " ")
// Remove excessive spaces
text = multiSpaceRegex.ReplaceAllString(text, " ")
// Remove punctuation marks
text = punctRegex.ReplaceAllString(text, " ")
// Trim leading and trailing spaces
text = strings.TrimSpace(text)
return text
}
// segmentText Text tokenization
func (p *PluginPreprocess) segmentText(text string) []string {
// Use Jieba tokenizer for tokenization, using search engine mode
segments := p.jieba.CutForSearch(text, true)
return segments
}
// filterStopwords Filter stopwords
func (p *PluginPreprocess) filterStopwords(segments []string) []string {
var filtered []string
for _, word := range segments {
// If not a stopword and not blank, keep it
if _, isStopword := p.stopwords[word]; !isStopword && !isBlank(word) {
filtered = append(filtered, word)
}
}
// If filtering results in empty list, return original tokenization results
if len(filtered) == 0 {
return segments
}
return filtered
}
// isBlank Check if a string is blank
func isBlank(str string) bool {
for _, r := range str {
if !unicode.IsSpace(r) {
return false
}
}
return true
}
// Ensure resources are properly released
func (p *PluginPreprocess) Close() {
if p.jieba != nil {
p.jieba.Free()
p.jieba = nil
}
}
// ShutdownHandler Returns shutdown function
func (p *PluginPreprocess) ShutdownHandler() func() {
return func() {
p.Close()
}
}
@@ -0,0 +1,171 @@
package chatpipline
import (
"context"
"encoding/json"
"fmt"
"math"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginRerank implements reranking functionality for chat pipeline
type PluginRerank struct {
modelService interfaces.ModelService // Service to access rerank models
}
// NewPluginRerank creates a new rerank plugin instance
func NewPluginRerank(eventManager *EventManager, modelService interfaces.ModelService) *PluginRerank {
res := &PluginRerank{
modelService: modelService,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginRerank) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_RERANK}
}
// OnEvent handles reranking events in the chat pipeline
func (p *PluginRerank) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting reranking process")
logger.Infof(ctx, "Getting rerank model, model ID: %s", chatManage.RerankModelID)
if len(chatManage.SearchResult) == 0 {
logger.Infof(ctx, "No search result, skip reranking")
return next()
}
if chatManage.RerankModelID == "" {
logger.Warn(ctx, "Rerank model ID is empty, skipping reranking")
return next()
}
// Get rerank model from service
rerankModel, err := p.modelService.GetRerankModel(ctx, chatManage.RerankModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get rerank model: %v, rerank model ID: %s", err, chatManage.RerankModelID)
return ErrGetRerankModel.WithError(err)
}
// Prepare passages for reranking
logger.Infof(ctx, "Preparing passages for reranking, search result count: %d", len(chatManage.SearchResult))
var passages []string
for _, result := range chatManage.SearchResult {
// 合并Content和ImageInfo的文本内容
passage := getEnrichedPassage(ctx, result)
passages = append(passages, passage)
}
// Try reranking with different query variants in priority order
rerankResp := p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages)
if len(rerankResp) == 0 {
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.ProcessedQuery, passages)
if len(rerankResp) == 0 {
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.Query, passages)
}
}
// Update search results with reranked scores
logger.Infof(ctx, "Filtered rerank results, original: %d, filtered: %d", len(rerankResp), len(rerankResp))
result := []*types.SearchResult{}
for _, rr := range rerankResp {
chatManage.SearchResult[rr.Index].Score = rr.RelevanceScore
result = append(result, chatManage.SearchResult[rr.Index])
}
chatManage.RerankResult = result
if len(chatManage.RerankResult) == 0 {
logger.Warn(ctx, "Reranking produced no results above threshold")
return ErrSearchNothing
}
logger.Infof(ctx, "Reranking process completed successfully, result count: %d", len(chatManage.RerankResult))
return next()
}
// rerank performs the actual reranking operation with given query and passages
func (p *PluginRerank) rerank(ctx context.Context,
chatManage *types.ChatManage, rerankModel rerank.Reranker, query string, passages []string,
) []rerank.RankResult {
logger.Infof(ctx, "Executing reranking with query: %s, passage count: %d", query, len(passages))
rerankResp, err := rerankModel.Rerank(ctx, query, passages)
if err != nil {
logger.Errorf(ctx, "Reranking failed: %v", err)
return nil
}
// Log top scores for debugging
logger.Infof(ctx, "Reranking completed, filtering results with threshold: %f", chatManage.RerankThreshold)
for i := range min(3, len(rerankResp)) {
logger.Infof(ctx, "Top %d score of rerankResp: %f, passages: %s, index: %d",
i+1, rerankResp[i].RelevanceScore, rerankResp[i].Document.Text, rerankResp[i].Index,
)
}
// Filter results based on threshold with special handling for history matches
rankFilter := []rerank.RankResult{}
for _, result := range rerankResp {
th := chatManage.RerankThreshold
matchType := chatManage.SearchResult[result.Index].MatchType
if matchType == types.MatchTypeHistory {
th = math.Max(th-0.1, 0.5) // Lower threshold for history matches
}
if result.RelevanceScore > th {
rankFilter = append(rankFilter, result)
}
}
return rankFilter
}
// getEnrichedPassage 合并Content和ImageInfo的文本内容
func getEnrichedPassage(ctx context.Context, result *types.SearchResult) string {
if result.ImageInfo == "" {
return result.Content
}
// 解析ImageInfo
var imageInfos []types.ImageInfo
err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos)
if err != nil {
logger.Warnf(ctx, "Failed to parse ImageInfo: %v, using content only", err)
return result.Content
}
if len(imageInfos) == 0 {
return result.Content
}
// 提取所有图片的描述和OCR文本
var imageTexts []string
for _, img := range imageInfos {
if img.Caption != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片描述: %s", img.Caption))
}
if img.OCRText != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片文本: %s", img.OCRText))
}
}
if len(imageTexts) == 0 {
return result.Content
}
// 组合内容和图片信息
combinedText := result.Content
if combinedText != "" {
combinedText += "\n\n"
}
combinedText += strings.Join(imageTexts, "\n")
logger.Debugf(ctx, "Enhanced passage with image info: content length %d, image texts length %d",
len(result.Content), len(strings.Join(imageTexts, "\n")))
return combinedText
}
@@ -0,0 +1,174 @@
// Package chatpipline provides chat pipeline processing capabilities
// Including query rewriting, history processing, model invocation and other features
package chatpipline
import (
"bytes"
"context"
"html/template"
"regexp"
"slices"
"sort"
"time"
"github.com/Tencent/WeKnora/internal/config"
"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"
)
// PluginRewrite is a plugin for rewriting user queries
// It uses historical dialog context and large language models to optimize the user's original query
type PluginRewrite struct {
modelService interfaces.ModelService // Model service for calling large language models
messageService interfaces.MessageService // Message service for retrieving historical messages
config *config.Config // System configuration
}
// reg is a regular expression used to match and remove content between <think></think> tags
var reg = regexp.MustCompile(`(?s)<think>.*?</think>`)
// NewPluginRewrite creates a new query rewriting plugin instance
// Also registers the plugin with the event manager
func NewPluginRewrite(eventManager *EventManager,
modelService interfaces.ModelService, messageService interfaces.MessageService,
config *config.Config,
) *PluginRewrite {
res := &PluginRewrite{
modelService: modelService,
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 REWRITE_QUERY events
func (p *PluginRewrite) ActivationEvents() []types.EventType {
return []types.EventType{types.REWRITE_QUERY}
}
// OnEvent processes triggered events
// When receiving a REWRITE_QUERY event, it rewrites the user query using conversation history and the language model
func (p *PluginRewrite) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Initialize rewritten query as original query
chatManage.RewriteQuery = chatManage.Query
// Get conversation history
history, err := p.messageService.GetRecentMessagesBySession(ctx, chatManage.SessionID, 20)
if err != nil {
logger.Errorf(ctx, "Failed to get conversation history, session_id: %s, error: %v", chatManage.SessionID, err)
}
// Convert historical messages to conversation history structure
historyMap := make(map[string]*types.History)
// Process historical messages, grouped by requestID
for _, message := range history {
history, ok := historyMap[message.RequestID]
if !ok {
history = &types.History{}
}
if message.Role == "user" {
// User message as query
history.Query = message.Content
history.CreateAt = message.CreatedAt
} else {
// System message as answer, while removing thinking process
history.Answer = reg.ReplaceAllString(message.Content, "")
history.KnowledgeReferences = message.KnowledgeReferences
}
historyMap[message.RequestID] = history
}
// Convert to list and filter incomplete conversations
historyList := make([]*types.History, 0)
for _, history := range historyMap {
if history.Answer != "" && history.Query != "" {
historyList = append(historyList, history)
}
}
// 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) > p.config.Conversation.MaxRounds {
historyList = historyList[:p.config.Conversation.MaxRounds]
}
// Reverse to chronological order
slices.Reverse(historyList)
chatManage.History = historyList
userTmpl, err := template.New("rewriteContent").Parse(p.config.Conversation.RewritePromptUser)
if err != nil {
logger.Errorf(ctx, "Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
systemTmpl, err := template.New("rewriteContent").Parse(p.config.Conversation.RewritePromptSystem)
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
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 {
logger.GetLogger(ctx).Errorf("Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
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 {
logger.Errorf(ctx, "Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get model, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
// Call model to rewrite query
thinking := false
response, err := rewriteModel.Chat(ctx, []chat.Message{
{
Role: "system",
Content: systemContent.String(),
},
{
Role: "user",
Content: userContent.String(),
},
}, &chat.ChatOptions{
Temperature: 0.3,
MaxCompletionTokens: 50,
Thinking: &thinking,
})
if err != nil {
logger.Errorf(ctx, "Failed to execute model, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
// Update rewritten query
chatManage.RewriteQuery = response.Content
logger.GetLogger(ctx).Infof("Rewritten query, session_id: %s, rewrite_query: %s",
chatManage.SessionID, chatManage.RewriteQuery)
return next()
}
@@ -0,0 +1,124 @@
package chatpipline
import (
"context"
"strings"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginSearch implements search functionality for chat pipeline
type PluginSearch struct {
knowledgeBaseService interfaces.KnowledgeBaseService
modelService interfaces.ModelService
config *config.Config
}
func NewPluginSearch(eventManager *EventManager,
knowledgeBaseService interfaces.KnowledgeBaseService,
modelService interfaces.ModelService,
config *config.Config,
) *PluginSearch {
res := &PluginSearch{
knowledgeBaseService: knowledgeBaseService,
modelService: modelService,
config: config,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginSearch) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_SEARCH}
}
// OnEvent handles search events in the chat pipeline
func (p *PluginSearch) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Prepare search parameters
searchParams := types.SearchParams{
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
VectorThreshold: chatManage.VectorThreshold,
KeywordThreshold: chatManage.KeywordThreshold,
MatchCount: chatManage.EmbeddingTopK,
}
logger.Infof(ctx, "Search parameters: %v", searchParams)
// Perform initial hybrid search
searchResults, err := p.knowledgeBaseService.HybridSearch(ctx, chatManage.KnowledgeBaseID, searchParams)
logger.Infof(ctx, "Search results count: %d, error: %v", len(searchResults), err)
if err != nil {
return ErrSearch.WithError(err)
}
chatManage.SearchResult = searchResults
logger.Infof(ctx, "Search result count: %d", len(chatManage.SearchResult))
// Add relevant results from chat history
historyResult := p.getSearchResultFromHistory(chatManage)
if historyResult != nil {
logger.Infof(ctx, "Add history result, result count: %d", len(historyResult))
chatManage.SearchResult = append(chatManage.SearchResult, historyResult...)
}
// Try search with processed query if different from rewrite query
if chatManage.RewriteQuery != chatManage.ProcessedQuery {
searchParams.QueryText = strings.TrimSpace(chatManage.ProcessedQuery)
searchResults, err = p.knowledgeBaseService.HybridSearch(ctx, chatManage.KnowledgeBaseID, searchParams)
logger.Infof(ctx, "Search by processed query: %s, results count: %d, error: %v",
searchParams.QueryText, len(searchResults), err,
)
if err != nil {
return ErrSearch.WithError(err)
}
chatManage.SearchResult = append(chatManage.SearchResult, searchResults...)
}
// remove duplicate results
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
// Return if we have results
if len(chatManage.SearchResult) != 0 {
logger.Infof(
ctx,
"Get search results, count: %d, session_id: %s",
len(chatManage.SearchResult), chatManage.SessionID,
)
return next()
}
logger.Infof(ctx, "No search result, session_id: %s", chatManage.SessionID)
return ErrSearchNothing
}
// getSearchResultFromHistory retrieves relevant knowledge references from chat history
func (p *PluginSearch) getSearchResultFromHistory(chatManage *types.ChatManage) []*types.SearchResult {
if len(chatManage.History) == 0 {
return nil
}
// Search history in reverse chronological order
for i := len(chatManage.History) - 1; i >= 0; i-- {
if len(chatManage.History[i].KnowledgeReferences) > 0 {
// Mark all references as history matches
for _, reference := range chatManage.History[i].KnowledgeReferences {
reference.MatchType = types.MatchTypeHistory
}
return chatManage.History[i].KnowledgeReferences
}
}
return nil
}
func removeDuplicateResults(results []*types.SearchResult) []*types.SearchResult {
seen := make(map[string]bool)
var uniqueResults []*types.SearchResult
for _, result := range results {
if !seen[result.ID] {
seen[result.ID] = true
uniqueResults = append(uniqueResults, result)
}
}
return uniqueResults
}
@@ -0,0 +1,84 @@
package chatpipline
import (
"context"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginStreamFilter implements stream filtering functionality for chat pipeline
type PluginStreamFilter struct{}
// NewPluginStreamFilter creates a new stream filter plugin instance
func NewPluginStreamFilter(eventManager *EventManager) *PluginStreamFilter {
res := &PluginStreamFilter{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginStreamFilter) ActivationEvents() []types.EventType {
return []types.EventType{types.STREAM_FILTER}
}
// OnEvent handles stream filtering events in the chat pipeline
func (p *PluginStreamFilter) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting stream filter")
logger.Info(ctx, "Creating new stream channel")
// Create new stream channel and replace the original one
oldStream := chatManage.ResponseChan
newStream := make(chan types.StreamResponse)
chatManage.ResponseChan = newStream
// Initialize response builder and check if no-match prefix filtering is needed
responseBuilder := &strings.Builder{}
matchNoMatchBuilderPrefix := chatManage.SummaryConfig.NoMatchPrefix != ""
if matchNoMatchBuilderPrefix {
logger.Infof(ctx, "Using no match prefix filter: %s", chatManage.SummaryConfig.NoMatchPrefix)
}
// Start goroutine to filter the stream
go func() {
logger.Info(ctx, "Starting stream filter goroutine")
for resp := range oldStream {
// Accumulate answer content
if resp.ResponseType == types.ResponseTypeAnswer {
responseBuilder.WriteString(resp.Content)
}
// Skip filtering if no prefix matching is required
if !matchNoMatchBuilderPrefix {
newStream <- resp
continue
}
// Check if content matches the no-match prefix
if !strings.HasPrefix(chatManage.SummaryConfig.NoMatchPrefix, responseBuilder.String()) {
resp.Content = responseBuilder.String()
newStream <- resp
logger.Info(
ctx, "Content does not match no-match prefix, passing through, content: ",
responseBuilder.String(),
)
matchNoMatchBuilderPrefix = false
}
}
// Handle NO_MATCH case when stream ends
if matchNoMatchBuilderPrefix {
logger.Info(ctx, "Content matches no-match prefix, using fallback response")
newStream <- NewFallback(ctx, chatManage.FallbackResponse)
}
logger.Info(ctx, "Stream filter completed, closing new stream")
close(newStream)
}()
logger.Info(ctx, "Stream filter initialized")
return next()
}
@@ -0,0 +1,270 @@
package chatpipline
import (
"context"
"encoding/json"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/types"
"go.opentelemetry.io/otel/attribute"
)
// PluginTracing implements tracing functionality for chat pipeline events
type PluginTracing struct{}
// NewPluginTracing creates a new tracing plugin instance
func NewPluginTracing(eventManager *EventManager) *PluginTracing {
res := &PluginTracing{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginTracing) ActivationEvents() []types.EventType {
return []types.EventType{
types.CHUNK_SEARCH,
types.CHUNK_RERANK,
types.CHUNK_MERGE,
types.INTO_CHAT_MESSAGE,
types.CHAT_COMPLETION,
types.CHAT_COMPLETION_STREAM,
types.FILTER_TOP_K,
types.REWRITE_QUERY,
types.PREPROCESS_QUERY,
}
}
// OnEvent handles incoming events and routes them to the appropriate tracing handler based on event type.
// It acts as the central dispatcher for all tracing-related events in the chat pipeline.
//
// Parameters:
// - ctx: context.Context for request-scoped values, cancellation signals, and deadlines
// - eventType: the type of event being processed (e.g., CHUNK_SEARCH, CHAT_COMPLETION)
// - chatManage: contains all the chat-related data and state for the current request
// - next: callback function to continue processing in the pipeline
//
// Returns:
// - *PluginError: error if any occurred during processing, or nil if successful
func (p *PluginTracing) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
switch eventType {
case types.CHUNK_SEARCH:
return p.Search(ctx, eventType, chatManage, next)
case types.CHUNK_RERANK:
return p.Rerank(ctx, eventType, chatManage, next)
case types.CHUNK_MERGE:
return p.Merge(ctx, eventType, chatManage, next)
case types.INTO_CHAT_MESSAGE:
return p.IntoChatMessage(ctx, eventType, chatManage, next)
case types.CHAT_COMPLETION:
return p.ChatCompletion(ctx, eventType, chatManage, next)
case types.CHAT_COMPLETION_STREAM:
return p.ChatCompletionStream(ctx, eventType, chatManage, next)
case types.FILTER_TOP_K:
return p.FilterTopK(ctx, eventType, chatManage, next)
case types.REWRITE_QUERY:
return p.RewriteQuery(ctx, eventType, chatManage, next)
case types.PREPROCESS_QUERY:
return p.PreprocessQuery(ctx, eventType, chatManage, next)
}
return next()
}
// Search traces search operations in the chat pipeline
func (p *PluginTracing) Search(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.Search")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
attribute.Float64("vector_threshold", chatManage.VectorThreshold),
attribute.Float64("keyword_threshold", chatManage.KeywordThreshold),
attribute.Int("match_count", chatManage.EmbeddingTopK),
)
err := next()
searchResultJson, _ := json.Marshal(chatManage.SearchResult)
span.SetAttributes(
attribute.String("hybrid_search", string(searchResultJson)),
attribute.String("processed_query", chatManage.ProcessedQuery),
)
return err
}
// Rerank traces rerank operations in the chat pipeline
func (p *PluginTracing) Rerank(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.Rerank")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
attribute.Int("passages_count", len(chatManage.SearchResult)),
attribute.String("rerank_model_id", chatManage.RerankModelID),
attribute.Float64("rerank_filter_threshold", chatManage.RerankThreshold),
attribute.Int("rerank_filter_topk", chatManage.RerankTopK),
)
err := next()
resultJson, _ := json.Marshal(chatManage.RerankResult)
span.SetAttributes(
attribute.Int("rerank_resp_count", len(chatManage.RerankResult)),
attribute.String("rerank_resp_results", string(resultJson)),
)
return err
}
// Merge traces merge operations in the chat pipeline
func (p *PluginTracing) Merge(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.Merge")
defer span.End()
span.SetAttributes(
attribute.Int("search_results_count", len(chatManage.SearchResult)),
attribute.Int("rerank_results_count", len(chatManage.RerankResult)),
)
err := next()
mergeResultJson, _ := json.Marshal(chatManage.MergeResult)
span.SetAttributes(
attribute.Int("merge_results_count", len(chatManage.MergeResult)),
attribute.String("merge_results", string(mergeResultJson)),
)
return err
}
// IntoChatMessage traces message conversion operations
func (p *PluginTracing) IntoChatMessage(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.IntoChatMessage")
defer span.End()
span.SetAttributes(
attribute.Int("search_results_count", len(chatManage.SearchResult)),
attribute.Int("rerank_results_count", len(chatManage.RerankResult)),
attribute.Int("merge_results_count", len(chatManage.MergeResult)),
)
err := next()
span.SetAttributes(attribute.Int("generated_content_length", len(chatManage.UserContent)))
return err
}
// ChatCompletion traces chat completion operations
func (p *PluginTracing) ChatCompletion(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.ChatCompletion")
defer span.End()
span.SetAttributes(
attribute.String("model_id", chatManage.ChatModelID),
attribute.String("system_prompt", chatManage.SummaryConfig.Prompt),
attribute.String("user_prompt", chatManage.UserContent),
attribute.Int("total_references", len(chatManage.RerankResult)),
)
err := next()
span.SetAttributes(
attribute.String("chat_response", chatManage.ChatResponse.Content),
attribute.Int("chat_response_tokens", chatManage.ChatResponse.Usage.TotalTokens),
attribute.Int("chat_response_prompt_tokens", chatManage.ChatResponse.Usage.PromptTokens),
attribute.Int("chat_response_completion_tokens", chatManage.ChatResponse.Usage.CompletionTokens),
)
return err
}
// ChatCompletionStream traces streaming chat completion operations
func (p *PluginTracing) ChatCompletionStream(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
ctx, span := tracing.ContextWithSpan(ctx, "PluginTracing.ChatCompletionStream")
startTime := time.Now()
span.SetAttributes(
attribute.String("model_id", chatManage.ChatModelID),
attribute.String("system_prompt", chatManage.SummaryConfig.Prompt),
attribute.String("user_prompt", chatManage.UserContent),
attribute.Int("total_references", len(chatManage.RerankResult)),
)
responseBuilder := &strings.Builder{}
oldStream := chatManage.ResponseChan
newStream := make(chan types.StreamResponse)
chatManage.ResponseChan = newStream
go func(ctx context.Context) {
for resp := range oldStream {
if resp.ResponseType == types.ResponseTypeAnswer {
responseBuilder.WriteString(resp.Content)
}
newStream <- resp
}
elapsedMS := time.Since(startTime).Milliseconds()
span.SetAttributes(
attribute.Bool("chat_completion_success", true),
attribute.Int64("response_time_ms", elapsedMS),
attribute.String("chat_response", responseBuilder.String()),
attribute.Int("final_response_length", responseBuilder.Len()),
attribute.Float64("tokens_per_second", float64(responseBuilder.Len())/float64(elapsedMS)*1000),
)
span.End()
close(newStream)
}(ctx)
return next()
}
// FilterTopK traces filtering operations in the chat pipeline
func (p *PluginTracing) FilterTopK(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.FilterTopK")
defer span.End()
span.SetAttributes(
attribute.Int("before_filter_search_results_count", len(chatManage.SearchResult)),
attribute.Int("before_filter_rerank_results_count", len(chatManage.RerankResult)),
attribute.Int("before_filter_merge_results_count", len(chatManage.MergeResult)),
)
err := next()
span.SetAttributes(
attribute.Int("after_filter_search_results_count", len(chatManage.SearchResult)),
attribute.Int("after_filter_rerank_results_count", len(chatManage.RerankResult)),
attribute.Int("after_filter_merge_results_count", len(chatManage.MergeResult)),
)
return err
}
// RewriteQuery traces query rewriting operations
func (p *PluginTracing) RewriteQuery(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.RewriteQuery")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
)
err := next()
span.SetAttributes(
attribute.String("rewrite_query", chatManage.RewriteQuery),
)
return err
}
// PreprocessQuery traces query preprocessing operations
func (p *PluginTracing) PreprocessQuery(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.PreprocessQuery")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
)
err := next()
span.SetAttributes(
attribute.String("processed_query", chatManage.ProcessedQuery),
)
return err
}