feat(prompts): update assistant descriptions and add intent-specific templates

- Updated the assistant descriptions in various prompt templates to specify that they are developed by Tencent.
- Added new intent-specific system prompt templates for greeting, chitchat, follow-up, image analysis, summarization, and web search unavailability scenarios.
- Enhanced citation rules in the system prompts to ensure proper inline citation formatting.
- Refactored the rewrite prompt to classify user intent more accurately and output structured JSON responses.
This commit is contained in:
wizardchen
2026-03-23 01:57:06 +08:00
committed by lyingbug
parent 109393dd16
commit 052be53c42
44 changed files with 1272 additions and 1323 deletions
@@ -0,0 +1,76 @@
package chatpipeline
import (
"context"
"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 {
pipelineInfo(ctx, "Completion", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_question": chatManage.UserContent,
"history_rounds": len(chatManage.History),
"chat_model": chatManage.ChatModelID,
})
// 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
pipelineInfo(ctx, "Completion", "messages_ready", map[string]interface{}{
"message_count": len(chatManage.History) + 2,
})
chatMessages := prepareMessagesWithHistory(chatManage)
// Call the chat model to generate response
pipelineInfo(ctx, "Completion", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
})
chatResponse, err := chatModel.Chat(ctx, chatMessages, opt)
if err != nil {
pipelineError(ctx, "Completion", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
"error": err.Error(),
})
return ErrModelCall.WithError(err)
}
pipelineInfo(ctx, "Completion", "output", map[string]interface{}{
"answer_preview": chatResponse.Content,
"finish_reason": chatResponse.FinishReason,
"completion_tokens": chatResponse.Usage.CompletionTokens,
"prompt_tokens": chatResponse.Usage.PromptTokens,
})
chatManage.ChatResponse = chatResponse
return next()
}
@@ -0,0 +1,222 @@
package chatpipeline
import (
"context"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// 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 {
pipelineInfo(ctx, "Stream", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_question": chatManage.UserContent,
"history_rounds": len(chatManage.History),
"chat_model": chatManage.ChatModelID,
})
// 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
chatMessages := prepareMessagesWithHistory(chatManage)
pipelineInfo(ctx, "Stream", "messages_ready", map[string]interface{}{
"message_count": len(chatMessages),
"system_prompt": chatMessages[0].Content,
})
pipelineInfo(ctx, "Stream", "user_message", map[string]interface{}{
"content": chatMessages[len(chatMessages)-1].Content,
})
// EventBus is required for event-driven streaming
if chatManage.EventBus == nil {
pipelineError(ctx, "Stream", "eventbus_missing", map[string]interface{}{
"session_id": chatManage.SessionID,
})
return ErrModelCall.WithError(errors.New("EventBus is required for streaming"))
}
eventBus := chatManage.EventBus
pipelineInfo(ctx, "Stream", "eventbus_ready", map[string]interface{}{
"session_id": chatManage.SessionID,
})
// Initiate streaming chat model call with independent context
pipelineInfo(ctx, "Stream", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
})
responseChan, err := chatModel.ChatStream(ctx, chatMessages, opt)
if err != nil {
pipelineError(ctx, "Stream", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
"error": err.Error(),
})
return ErrModelCall.WithError(err)
}
if responseChan == nil {
pipelineError(ctx, "Stream", "model_call", map[string]interface{}{
"chat_model": chatManage.ChatModelID,
"error": "nil_channel",
})
return ErrModelCall.WithError(errors.New("chat stream returned nil channel"))
}
pipelineInfo(ctx, "Stream", "model_started", map[string]interface{}{
"session_id": chatManage.SessionID,
})
// Start goroutine to consume channel and emit events directly.
// For non-agent mode, thinking content is embedded in answer stream with <think> tags.
// The goroutine monitors ctx.Done() to avoid leaking when the context is cancelled
// and the upstream channel is not closed promptly.
go func() {
answerID := fmt.Sprintf("%s-answer", uuid.New().String()[:8])
var finalContent string
var thinkingStarted bool
var thinkingEnded bool
for {
select {
case <-ctx.Done():
if thinkingStarted && !thinkingEnded {
eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: "</think>",
Done: true,
},
})
}
pipelineInfo(ctx, "Stream", "context_cancelled", map[string]interface{}{
"session_id": chatManage.SessionID,
})
return
case response, ok := <-responseChan:
if !ok {
if thinkingStarted && !thinkingEnded {
finalContent += "</think>"
eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: "</think>",
Done: true,
},
})
}
pipelineInfo(ctx, "Stream", "channel_close", map[string]interface{}{
"session_id": chatManage.SessionID,
})
return
}
if response.ResponseType == types.ResponseTypeError {
pipelineError(ctx, "Stream", "stream_error", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": response.Content,
})
eventBus.Emit(ctx, types.Event{
ID: fmt.Sprintf("%s-error", uuid.New().String()[:8]),
Type: types.EventType(event.EventError),
SessionID: chatManage.SessionID,
Data: event.ErrorData{
Error: response.Content,
Stage: "chat_completion_stream",
SessionID: chatManage.SessionID,
},
})
continue
}
if response.ResponseType == types.ResponseTypeThinking {
content := response.Content
if !thinkingStarted {
content = "<think>" + content
thinkingStarted = true
}
if response.Done && !thinkingEnded {
content = content + "</think>"
thinkingEnded = true
}
finalContent += content
eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: content,
Done: false,
},
})
continue
}
if response.ResponseType == types.ResponseTypeAnswer {
if thinkingStarted && !thinkingEnded {
thinkingEnded = true
finalContent += "</think>"
eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: "</think>",
Done: false,
},
})
}
finalContent += response.Content
eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: response.Content,
Done: response.Done,
},
})
}
}
}
}()
return next()
}
@@ -0,0 +1,140 @@
package chatpipeline
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
}
@@ -0,0 +1,125 @@
package chatpipeline
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,228 @@
package chatpipeline
import (
"context"
"regexp"
"slices"
"sort"
"strings"
"sync"
"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"
)
var regThinkTags = regexp.MustCompile(`(?s)<think>.*?</think>`)
// pipelineInfo logs pipeline info level entries.
func pipelineInfo(ctx context.Context, stage, action string, fields map[string]interface{}) {
common.PipelineInfo(ctx, stage, action, fields)
}
// pipelineWarn logs pipeline warning level entries.
func pipelineWarn(ctx context.Context, stage, action string, fields map[string]interface{}) {
common.PipelineWarn(ctx, stage, action, fields)
}
// pipelineError logs pipeline error level entries.
func pipelineError(ctx context.Context, stage, action string, fields map[string]interface{}) {
common.PipelineError(ctx, stage, action, fields)
}
// prepareChatModel shared logic to prepare chat model and options
// it gets the chat model and sets up the chat options based on the chat manage.
func prepareChatModel(ctx context.Context, modelService interfaces.ModelService,
chatManage *types.ChatManage,
) (chat.Chat, *chat.ChatOptions, error) {
chatModel, err := modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get chat model: %v", err)
return nil, nil, err
}
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,
Thinking: chatManage.SummaryConfig.Thinking,
}
return chatModel, opt, nil
}
// prepareMessagesWithHistory prepare complete messages including history.
// When SystemPromptOverride is set (e.g. by intent-specific prompt logic),
// it takes precedence over the default SummaryConfig.Prompt.
func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
base := chatManage.SummaryConfig.Prompt
if chatManage.SystemPromptOverride != "" {
base = chatManage.SystemPromptOverride
}
systemPrompt := renderSystemPromptPlaceholders(base, chatManage.Language)
chatMessages := []chat.Message{
{Role: "system", Content: systemPrompt},
}
// 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})
}
// Add current user message. Only include images when the chat model supports
// vision; non-vision models rely on the text description in UserContent.
userMsg := chat.Message{Role: "user", Content: chatManage.UserContent}
if chatManage.ChatModelSupportsVision && len(chatManage.Images) > 0 {
userMsg.Images = chatManage.Images
}
chatMessages = append(chatMessages, userMsg)
return chatMessages
}
// loadAndProcessHistory fetches recent messages, groups them into Q&A pairs,
// strips <think> tags from assistant answers, sorts by recency, and limits to maxRounds.
// fetchCount controls how many raw messages to fetch (typically maxRounds*2+10).
func loadAndProcessHistory(
ctx context.Context,
messageService interfaces.MessageService,
sessionID string,
maxRounds int,
fetchCount int,
) ([]*types.History, error) {
history, err := messageService.GetRecentMessagesBySession(ctx, sessionID, fetchCount)
if err != nil {
return nil, err
}
historyMap := make(map[string]*types.History)
for _, message := range history {
h, ok := historyMap[message.RequestID]
if !ok {
h = &types.History{}
}
if message.Role == "user" {
h.Query = message.Content
h.CreateAt = message.CreatedAt
if desc := extractImageCaptions(message.Images); desc != "" {
h.Query += "\n\n[用户上传图片内容]\n" + desc
}
} else {
h.Answer = regThinkTags.ReplaceAllString(message.Content, "")
h.KnowledgeReferences = message.KnowledgeReferences
}
historyMap[message.RequestID] = h
}
historyList := make([]*types.History, 0, len(historyMap))
for _, h := range historyMap {
if h.Answer != "" && h.Query != "" {
historyList = append(historyList, h)
}
}
sort.Slice(historyList, func(i, j int) bool {
return historyList[i].CreateAt.After(historyList[j].CreateAt)
})
if len(historyList) > maxRounds {
historyList = historyList[:maxRounds]
}
slices.Reverse(historyList)
return historyList, nil
}
// extractImageCaptions concatenates non-empty Caption fields from stored
// message images. Used when loading history so that previous turns' image
// descriptions are visible to the model.
func extractImageCaptions(images types.MessageImages) string {
var parts []string
for _, img := range images {
if img.Caption != "" {
parts = append(parts, img.Caption)
}
}
return strings.Join(parts, "\n")
}
// renderSystemPromptPlaceholders replaces placeholders in system prompt
// Supported placeholders:
// - {{current_time}} -> current time in RFC3339 format
// - {{language}} -> user language name (replaced if present; empty string if not set in ChatManage)
func renderSystemPromptPlaceholders(prompt string, language ...string) string {
vals := types.PlaceholderValues{}
if len(language) > 0 {
vals["language"] = language[0]
}
return types.RenderPromptPlaceholders(prompt, vals)
}
// ---------------------------------------------------------------------------
// Concurrency utilities
// ---------------------------------------------------------------------------
// ParallelTask represents a named unit of concurrent work.
type ParallelTask struct {
Name string
Run func() *PluginError
}
// RunParallel executes tasks concurrently.
// Returns a map of task name → error for tasks that returned non-nil errors.
func RunParallel(tasks ...ParallelTask) map[string]*PluginError {
errs := make(map[string]*PluginError)
var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(len(tasks))
for _, task := range tasks {
go func(t ParallelTask) {
defer wg.Done()
if err := t.Run(); err != nil {
mu.Lock()
errs[t.Name] = err
mu.Unlock()
}
}(task)
}
wg.Wait()
return errs
}
// ParallelMap applies fn to each element of items concurrently (up to
// maxWorkers goroutines) and returns results in the same order as items.
// If maxWorkers <= 0, concurrency is unbounded (one goroutine per item).
func ParallelMap[T, R any](items []T, maxWorkers int, fn func(int, T) R) []R {
n := len(items)
if n == 0 {
return nil
}
results := make([]R, n)
if maxWorkers <= 0 || maxWorkers > n {
maxWorkers = n
}
var wg sync.WaitGroup
sem := make(chan struct{}, maxWorkers)
for i, item := range items {
wg.Add(1)
sem <- struct{}{}
go func(idx int, it T) {
defer func() { <-sem; wg.Done() }()
results[idx] = fn(idx, it)
}(i, item)
}
wg.Wait()
return results
}
@@ -0,0 +1,169 @@
package chatpipeline
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"slices"
"strings"
"github.com/Tencent/WeKnora/internal/agent/tools"
"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"
"github.com/Tencent/WeKnora/internal/utils"
)
type PluginDataAnalysis struct {
modelService interfaces.ModelService
knowledgeService interfaces.KnowledgeService
fileService interfaces.FileService
chunkRepo interfaces.ChunkRepository
db *sql.DB
}
func NewPluginDataAnalysis(
eventManager *EventManager,
modelService interfaces.ModelService,
knowledgeService interfaces.KnowledgeService,
fileService interfaces.FileService,
chunkRepo interfaces.ChunkRepository,
db *sql.DB,
) *PluginDataAnalysis {
p := &PluginDataAnalysis{
modelService: modelService,
knowledgeService: knowledgeService,
fileService: fileService,
chunkRepo: chunkRepo,
db: db,
}
eventManager.Register(p)
return p
}
func (p *PluginDataAnalysis) ActivationEvents() []types.EventType {
return []types.EventType{types.DATA_ANALYSIS}
}
func (p *PluginDataAnalysis) OnEvent(
ctx context.Context,
eventType types.EventType,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
if !chatManage.NeedsRetrieval() {
return next()
}
// 1. Check if there are any CSV/Excel files in MergeResult
var dataFiles []*types.SearchResult
for _, result := range chatManage.MergeResult {
if isDataFile(result.KnowledgeFilename) {
dataFiles = append(dataFiles, result)
}
}
// Filter out table column and table summary chunks from MergeResult
chatManage.MergeResult = filterOutTableChunks(chatManage.MergeResult)
if len(dataFiles) == 0 {
return next()
}
// 2. Ask LLM if data analysis is needed
// We only process the first data file for now to avoid complexity
targetFile := dataFiles[0]
// Get Knowledge details to get file path
knowledge, err := p.knowledgeService.GetKnowledgeByID(ctx, targetFile.KnowledgeID)
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge %s: %v", targetFile.KnowledgeID, err)
return next()
}
// Initialize DataAnalysisTool
tool := tools.NewDataAnalysisTool(p.knowledgeService, p.fileService, p.db, chatManage.SessionID)
defer tool.Cleanup(ctx)
// Load data into DuckDB
schema, err := tool.LoadFromKnowledge(ctx, knowledge)
if err != nil {
logger.Errorf(ctx, "Failed to get data schema: %v", err)
return next()
}
// Ask LLM to generate SQL for data analysis
chatModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
return ErrGetChatModel.WithError(err)
}
// Use utils.GenerateSchema to generate format schema for DataAnalysisInput
formatSchema := utils.GenerateSchema[tools.DataAnalysisInput]()
analysisPrompt := fmt.Sprintf(`
User Question: %s
Knowledge ID: %s
Table Schema: %s
Determine if the user's question requires data analysis (e.g., statistics, aggregation, filtering) on this table.
If YES, generate a DuckDB SQL query to answer the user's question and fill in the knowledge_id and sql fields.
If NO, leave the sql field empty.
Return your response in the specified JSON format.`, chatManage.Query, knowledge.ID, schema.Description())
response, err := chatModel.Chat(ctx, []chat.Message{
{Role: "user", Content: analysisPrompt},
}, &chat.ChatOptions{
Temperature: 0.1,
Format: formatSchema,
})
if err != nil {
logger.Errorf(ctx, "Failed to generate analysis response: %v", err)
return next()
}
// logger.Debugf(ctx, "Data analysis LLM response: %s", response.Content)
// Execute SQL using the tool
// Initialize DataAnalysisTool
toolResult, err := tool.Execute(ctx, json.RawMessage(response.Content))
if err != nil {
logger.Errorf(ctx, "Failed to execute SQL: %v", err)
return next()
}
// 5. Store result
// Create a new SearchResult for the analysis output
analysisResult := &types.SearchResult{
ID: "analysis_" + knowledge.ID,
Content: toolResult.Output,
Score: 1.0,
MatchType: types.MatchTypeDataAnalysis,
KnowledgeID: knowledge.ID,
KnowledgeTitle: knowledge.Title,
KnowledgeFilename: knowledge.FileName,
}
chatManage.MergeResult = append(chatManage.MergeResult, analysisResult)
return next()
}
func isDataFile(filename string) bool {
lower := strings.ToLower(filename)
return strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".xlsx") || strings.HasSuffix(lower, ".xls")
}
// filterOutTableChunks filters out table column and table summary chunks from search results
func filterOutTableChunks(results []*types.SearchResult) []*types.SearchResult {
filtered := make([]*types.SearchResult, 0, len(results))
filterList := []string{string(types.ChunkTypeTableColumn), string(types.ChunkTypeTableSummary)}
for _, result := range results {
if slices.Contains(filterList, result.ChunkType) {
continue
}
filtered = append(filtered, result)
}
return filtered
}
@@ -0,0 +1,569 @@
package chatpipeline
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"strings"
"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"
)
// PluginExtractEntity is a plugin for extracting entities from user queries
// It uses historical dialog context and large language models to identify key entities in the user's original query
type PluginExtractEntity struct {
modelService interfaces.ModelService // Model service for calling large language models
template *types.PromptTemplateStructured // Template for generating prompts
knowledgeBaseRepo interfaces.KnowledgeBaseRepository
knowledgeService interfaces.KnowledgeService // For shared KB document resolution
knowledgeRepo interfaces.KnowledgeRepository
}
// NewPluginExtractEntity creates a new extract-entity plugin instance
// Also registers the plugin with the event manager
func NewPluginExtractEntity(
eventManager *EventManager,
modelService interfaces.ModelService,
knowledgeBaseRepo interfaces.KnowledgeBaseRepository,
knowledgeService interfaces.KnowledgeService,
knowledgeRepo interfaces.KnowledgeRepository,
config *config.Config,
) *PluginExtractEntity {
res := &PluginExtractEntity{
modelService: modelService,
template: config.ExtractManager.ExtractEntity,
knowledgeBaseRepo: knowledgeBaseRepo,
knowledgeService: knowledgeService,
knowledgeRepo: knowledgeRepo,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the list of event types this plugin responds to.
func (p *PluginExtractEntity) ActivationEvents() []types.EventType {
return []types.EventType{types.QUERY_UNDERSTAND}
}
// OnEvent processes triggered events
// When receiving a QUERY_UNDERSTAND event, it extracts entities from the query
func (p *PluginExtractEntity) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
if strings.ToLower(os.Getenv("NEO4J_ENABLE")) != "true" {
logger.Debugf(ctx, "skipping extract entity, neo4j is disabled")
return next()
}
query := chatManage.Query
model, 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()
}
// Collect all knowledge base IDs to query
kbIDSet := make(map[string]struct{})
for _, id := range chatManage.KnowledgeBaseIDs {
kbIDSet[id] = struct{}{}
}
// If KnowledgeIDs is specified, retrieve them and collect their knowledge base IDs (include shared KB docs)
// Also build a mapping from KnowledgeID to KnowledgeBaseID
knowledgeToKBMap := make(map[string]string)
if len(chatManage.KnowledgeIDs) > 0 {
knowledges, err := p.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, chatManage.TenantID, chatManage.KnowledgeIDs)
if err != nil {
logger.Errorf(ctx, "failed to get knowledges: %v", err)
return next()
}
for _, k := range knowledges {
kbIDSet[k.KnowledgeBaseID] = struct{}{}
knowledgeToKBMap[k.ID] = k.KnowledgeBaseID
}
}
// Convert set to slice
allKBIDs := make([]string, 0, len(kbIDSet))
for id := range kbIDSet {
allKBIDs = append(allKBIDs, id)
}
// Batch retrieve all knowledge bases
kbs, err := p.knowledgeBaseRepo.GetKnowledgeBaseByIDs(ctx, allKBIDs)
if err != nil {
logger.Errorf(ctx, "failed to get knowledge bases: %v", err)
return next()
}
// Check if any knowledge base has ExtractConfig enabled and collect their IDs
enabledKBSet := make(map[string]struct{})
for _, kb := range kbs {
if kb.ExtractConfig != nil && kb.ExtractConfig.Enabled {
enabledKBSet[kb.ID] = struct{}{}
}
}
if len(enabledKBSet) == 0 {
logger.Debugf(ctx, "no knowledge base has extract config enabled")
return next()
}
// Save enabled knowledge base IDs for later use in search_entity
enabledKBIDs := make([]string, 0, len(enabledKBSet))
for id := range enabledKBSet {
enabledKBIDs = append(enabledKBIDs, id)
}
chatManage.EntityKBIDs = enabledKBIDs
// Filter knowledgeToKBMap to only include files from enabled knowledge bases
entityKnowledge := make(map[string]string)
for knowledgeID, kbID := range knowledgeToKBMap {
if _, ok := enabledKBSet[kbID]; ok {
entityKnowledge[knowledgeID] = kbID
}
}
chatManage.EntityKnowledge = entityKnowledge
template := &types.PromptTemplateStructured{
Description: p.template.Description,
Examples: p.template.Examples,
}
extractor := NewExtractor(model, template)
graph, err := extractor.Extract(ctx, query)
if err != nil {
logger.Errorf(ctx, "Failed to extract entities, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
nodes := []string{}
for _, node := range graph.Node {
nodes = append(nodes, node.Name)
}
logger.Debugf(ctx, "extracted node: %v", nodes)
chatManage.Entity = nodes
return next()
}
// Extractor is a struct for extracting entities
type Extractor struct {
chat chat.Chat
formater *Formater
template *types.PromptTemplateStructured
chatOpt *chat.ChatOptions
}
// NewExtractor creates a new extractor
func NewExtractor(
chatModel chat.Chat,
template *types.PromptTemplateStructured,
) Extractor {
think := false
return Extractor{
chat: chatModel,
formater: NewFormater(),
template: template,
chatOpt: &chat.ChatOptions{
Temperature: 0.3,
MaxTokens: 4096,
Thinking: &think,
},
}
}
// Extract extracts entities from content
func (e *Extractor) Extract(ctx context.Context, content string) (*types.GraphData, error) {
generator := NewQAPromptGenerator(e.formater, e.template)
// logger.Debugf(ctx, "chat system: %s", generator.System(ctx))
// logger.Debugf(ctx, "chat user: %s", generator.User(ctx, content))
chatResponse, err := e.chat.Chat(ctx, generator.Render(ctx, content), e.chatOpt)
if err != nil {
logger.Errorf(ctx, "failed to chat: %v", err)
return nil, err
}
graph, err := e.formater.ParseGraph(ctx, chatResponse.Content)
if err != nil {
logger.Errorf(ctx, "failed to parse graph: %v", err)
return nil, err
}
// e.RemoveUnknownRelation(ctx, graph)
return graph, nil
}
// RemoveUnknownRelation removes unknown relations from graph
func (e *Extractor) RemoveUnknownRelation(ctx context.Context, graph *types.GraphData) {
relationType := make(map[string]bool)
for _, tag := range e.template.Tags {
relationType[tag] = true
}
relationNew := make([]*types.GraphRelation, 0)
for _, relation := range graph.Relation {
if _, ok := relationType[relation.Type]; ok {
relationNew = append(relationNew, relation)
} else {
logger.Infof(ctx, "Unknown relation type %s with %v, ignore it", relation.Type, e.template.Tags)
}
}
graph.Relation = relationNew
}
// QAPromptGenerator is a struct for generating QA prompts
type QAPromptGenerator struct {
Formater *Formater
Template *types.PromptTemplateStructured
ExamplesHeading string
QuestionHeading string
QuestionPrefix string
AnswerPrefix string
}
// NewQAPromptGenerator creates a new QA prompt generator
func NewQAPromptGenerator(formater *Formater, template *types.PromptTemplateStructured) *QAPromptGenerator {
return &QAPromptGenerator{
Formater: formater,
Template: template,
ExamplesHeading: "# Examples",
QuestionHeading: "# Question",
QuestionPrefix: "Q: ",
AnswerPrefix: "A: ",
}
}
// System generates a system prompt
func (qa *QAPromptGenerator) System(ctx context.Context) string {
promptLines := []string{}
if len(qa.Template.Tags) == 0 {
promptLines = append(promptLines, qa.Template.Description)
} else {
tags, _ := json.Marshal(qa.Template.Tags)
promptLines = append(promptLines, fmt.Sprintf(qa.Template.Description, string(tags)))
}
if len(qa.Template.Examples) > 0 {
promptLines = append(promptLines, qa.ExamplesHeading)
for _, example := range qa.Template.Examples {
// Question
promptLines = append(promptLines, fmt.Sprintf("%s%s", qa.QuestionPrefix, strings.TrimSpace(example.Text)))
// Answer
answer, err := qa.Formater.formatExtraction(example.Node, example.Relation)
if err != nil {
return ""
}
promptLines = append(promptLines, fmt.Sprintf("%s%s", qa.AnswerPrefix, answer))
// new line
promptLines = append(promptLines, "")
}
}
return strings.Join(promptLines, "\n")
}
// User generates a user prompt
func (qa *QAPromptGenerator) User(ctx context.Context, question string) string {
promptLines := []string{}
promptLines = append(promptLines, qa.QuestionHeading)
promptLines = append(promptLines, fmt.Sprintf("%s%s", qa.QuestionPrefix, question))
promptLines = append(promptLines, qa.AnswerPrefix)
return strings.Join(promptLines, "\n")
}
// Render renders a prompt
func (qa *QAPromptGenerator) Render(ctx context.Context, question string) []chat.Message {
return []chat.Message{
{
Role: "system",
Content: qa.System(ctx),
},
{
Role: "user",
Content: qa.User(ctx, question),
},
}
}
// FormatType is a type for format types
type FormatType string
const (
// FormatTypeJSON is a format type for JSON
FormatTypeJSON FormatType = "json"
// FormatTypeYAML is a format type for YAML
FormatTypeYAML FormatType = "yaml"
)
const (
_FENCE_START = "```"
_LANGUAGE_TAG = `(?P<lang>[A-Za-z0-9_+-]+)?`
_FENCE_NEWLINE = `(?:\s*\n)?`
_FENCE_BODY = `(?P<body>[\s\S]*?)`
_FENCE_END = "```"
)
var _FENCE_RE = regexp.MustCompile(
_FENCE_START + _LANGUAGE_TAG + _FENCE_NEWLINE + _FENCE_BODY + _FENCE_END,
)
// Formater is a struct for formatting entities
type Formater struct {
attributeSuffix string
formatType FormatType
useFences bool
nodePrefix string
relationSource string
relationTarget string
relationPrefix string
}
// NewFormater creates a new formater
func NewFormater() *Formater {
return &Formater{
attributeSuffix: "_attributes",
formatType: FormatTypeJSON,
useFences: true,
nodePrefix: "entity",
relationSource: "entity1",
relationTarget: "entity2",
relationPrefix: "relation",
}
}
// formatExtraction formats extraction
func (f *Formater) formatExtraction(nodes []*types.GraphNode, relations []*types.GraphRelation) (string, error) {
items := make([]map[string]interface{}, 0)
for _, node := range nodes {
item := map[string]interface{}{
f.nodePrefix: node.Name,
}
if len(node.Attributes) > 0 {
item[fmt.Sprintf("%s%s", f.nodePrefix, f.attributeSuffix)] = node.Attributes
}
items = append(items, item)
}
for _, relation := range relations {
item := map[string]interface{}{
f.relationSource: relation.Node1,
f.relationTarget: relation.Node2,
f.relationPrefix: relation.Type,
}
items = append(items, item)
}
formatted := ""
switch f.formatType {
default:
formattedBytes, err := json.MarshalIndent(items, "", " ")
if err != nil {
return "", err
}
formatted = string(formattedBytes)
}
if f.useFences {
formatted = f.addFences(formatted)
}
return formatted, nil
}
func (f *Formater) parseOutput(ctx context.Context, text string) ([]map[string]interface{}, error) {
if text == "" {
return nil, errors.New("empty or invalid input string")
}
content := f.extractContent(ctx, text)
// logger.Debugf(ctx, "Extracted content: %s", content)
if content == "" {
return nil, errors.New("empty or invalid input string")
}
var parsed interface{}
var err error
if f.formatType == FormatTypeJSON {
err = json.Unmarshal([]byte(content), &parsed)
}
if err != nil {
return nil, fmt.Errorf("failed to parse %s content: %s", strings.ToUpper(string(f.formatType)), err.Error())
}
if parsed == nil {
return nil, fmt.Errorf("content must be a list of extractions or a dict")
}
var items []interface{}
if parsedMap, ok := parsed.(map[string]interface{}); ok {
items = []interface{}{parsedMap}
} else if parsedList, ok := parsed.([]interface{}); ok {
items = parsedList
} else {
return nil, fmt.Errorf("expected list or dict, got %T", parsed)
}
itemsList := make([]map[string]interface{}, 0)
for _, item := range items {
if itemMap, ok := item.(map[string]interface{}); ok {
itemsList = append(itemsList, itemMap)
} else {
return nil, fmt.Errorf("each item in the sequence must be a mapping.")
}
}
return itemsList, nil
}
func (f *Formater) ParseGraph(ctx context.Context, text string) (*types.GraphData, error) {
matchData, err := f.parseOutput(ctx, text)
if err != nil {
return nil, err
}
if len(matchData) == 0 {
logger.Debugf(ctx, "received empty extraction data.")
return &types.GraphData{}, nil
}
// mm, _ := json.Marshal(matchData)
// logger.Debugf(ctx, "Parsed graph data: %s", string(mm))
var nodes []*types.GraphNode
var relations []*types.GraphRelation
for _, group := range matchData {
switch {
case group[f.nodePrefix] != nil:
attributes := make([]string, 0)
attributesKey := f.nodePrefix + f.attributeSuffix
if attr, ok := group[attributesKey].([]interface{}); ok {
for _, v := range attr {
attributes = append(attributes, fmt.Sprintf("%v", v))
}
}
nodes = append(nodes, &types.GraphNode{
Name: fmt.Sprintf("%v", group[f.nodePrefix]),
Attributes: attributes,
})
case group[f.relationSource] != nil && group[f.relationTarget] != nil:
relations = append(relations, &types.GraphRelation{
Node1: fmt.Sprintf("%v", group[f.relationSource]),
Node2: fmt.Sprintf("%v", group[f.relationTarget]),
Type: fmt.Sprintf("%v", group[f.relationPrefix]),
})
default:
logger.Warnf(ctx, "Unsupported graph group: %v", group)
continue
}
}
graph := &types.GraphData{
Node: nodes,
Relation: relations,
}
f.rebuildGraph(ctx, graph)
return graph, nil
}
func (f *Formater) rebuildGraph(ctx context.Context, graph *types.GraphData) {
nodeMap := make(map[string]*types.GraphNode)
nodes := make([]*types.GraphNode, 0, len(graph.Node))
for _, node := range graph.Node {
if prenode, ok := nodeMap[node.Name]; ok {
logger.Infof(ctx, "Duplicate node ID: %s, merge attribute", node.Name)
// 修复panic:检查Attributes是否为nil
if node.Attributes == nil {
node.Attributes = make([]string, 0)
}
if prenode.Attributes != nil {
node.Attributes = append(node.Attributes, prenode.Attributes...)
}
continue
}
nodeMap[node.Name] = node
nodes = append(nodes, node)
}
relations := make([]*types.GraphRelation, 0, len(graph.Relation))
for _, relation := range graph.Relation {
if relation.Node1 == relation.Node2 {
logger.Infof(ctx, "Duplicate relation, ignore it")
continue
}
if _, ok := nodeMap[relation.Node1]; !ok {
node := &types.GraphNode{Name: relation.Node1}
nodes = append(nodes, node)
nodeMap[relation.Node1] = node
logger.Infof(ctx, "Add unknown source node ID: %s", relation.Node1)
}
if _, ok := nodeMap[relation.Node2]; !ok {
node := &types.GraphNode{Name: relation.Node2}
nodes = append(nodes, node)
nodeMap[relation.Node2] = node
logger.Infof(ctx, "Add unknown target node ID: %s", relation.Node2)
}
relations = append(relations, relation)
}
*graph = types.GraphData{
Node: nodes,
Relation: relations,
}
}
func (f *Formater) extractContent(ctx context.Context, text string) string {
if !f.useFences {
return strings.TrimSpace(text)
}
validTags := map[FormatType]map[string]struct{}{
FormatTypeYAML: {"yaml": {}, "yml": {}},
FormatTypeJSON: {"json": {}},
}
matches := _FENCE_RE.FindAllStringSubmatch(text, -1)
var candidates []string
for _, match := range matches {
lang := match[1]
body := match[2]
if f.isValidLanguageTag(lang, validTags) {
candidates = append(candidates, body)
}
}
switch {
case len(candidates) == 1:
return strings.TrimSpace(candidates[0])
case len(candidates) > 1:
logger.Warnf(ctx, "multiple candidates found: %d", len(candidates))
return strings.TrimSpace(candidates[0])
case len(matches) == 1:
logger.Debugf(ctx, "no candidate found, use first match without language tag: %s", matches[0][1])
return strings.TrimSpace(matches[0][2])
case len(matches) > 1:
logger.Warnf(ctx, "multiple matches found: %d", len(matches))
return strings.TrimSpace(matches[0][2])
default:
logger.Warnf(ctx, "no match found")
return strings.TrimSpace(text)
}
}
func (f *Formater) addFences(content string) string {
content = strings.TrimSpace(content)
return fmt.Sprintf("```%s\n%s\n```", f.formatType, content)
}
func (f *Formater) isValidLanguageTag(lang string, validTags map[FormatType]map[string]struct{}) bool {
if lang == "" {
return true
}
tag := strings.TrimSpace(strings.ToLower(lang))
validSet, ok := validTags[f.formatType]
if !ok {
return false
}
_, exists := validSet[tag]
return exists
}
@@ -0,0 +1,69 @@
package chatpipeline
import (
"context"
"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 {
if !chatManage.NeedsRetrieval() {
return next()
}
pipelineInfo(ctx, "FilterTopK", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"top_k": chatManage.RerankTopK,
"merge_cnt": len(chatManage.MergeResult),
"rerank_cnt": len(chatManage.RerankResult),
"search_cnt": len(chatManage.SearchResult),
})
filterTopK := func(searchResult []*types.SearchResult, topK int) []*types.SearchResult {
if topK > 0 && len(searchResult) > topK {
pipelineInfo(ctx, "FilterTopK", "filter", map[string]interface{}{
"before": len(searchResult),
"after": 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 {
pipelineWarn(ctx, "FilterTopK", "skip", map[string]interface{}{
"reason": "no_results",
})
}
pipelineInfo(ctx, "FilterTopK", "output", map[string]interface{}{
"merge_cnt": len(chatManage.MergeResult),
"rerank_cnt": len(chatManage.RerankResult),
"search_cnt": len(chatManage.SearchResult),
})
return next()
}
@@ -0,0 +1,284 @@
package chatpipeline
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// 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 {
pipelineInfo(ctx, "IntoChatMessage", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"merge_result_cnt": len(chatManage.MergeResult),
"template_len": len(chatManage.SummaryConfig.ContextTemplate),
})
// Separate FAQ and document results when FAQ priority is enabled
var faqResults, docResults []*types.SearchResult
var hasHighConfidenceFAQ bool
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,
})
}
// 验证用户查询的安全性
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("user query contains invalid content"))
}
// Intent-based no-search path: bypass "reference materials" template entirely.
if !chatManage.NeedsRetrieval() {
// Prefer rewritten query in no-search mode; fallback to original query.
userContent := safeQuery
if rewrite := strings.TrimSpace(chatManage.RewriteQuery); rewrite != "" {
if safeRewrite, ok := utils.ValidateInput(rewrite); ok {
userContent = safeRewrite
} else {
pipelineWarn(ctx, "IntoChatMessage", "invalid_rewrite_query_fallback", map[string]interface{}{
"session_id": chatManage.SessionID,
})
}
}
if chatManage.ImageDescription != "" && !chatManage.ChatModelSupportsVision {
userContent += "\n\n[用户上传图片内容]\n" + chatManage.ImageDescription
}
chatManage.UserContent = userContent
pipelineInfo(ctx, "IntoChatMessage", "skip_template_no_search", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_content_len": len(chatManage.UserContent),
})
return next()
}
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("### Source 1: FAQ Knowledge Base\n")
contextsBuilder.WriteString("[High Confidence - Prioritize these results]\n")
for i, result := range faqResults {
passage := getEnrichedPassageForChat(ctx, result)
if hasHighConfidenceFAQ && i == 0 {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] Exact Match: %s\n", i+1, passage))
} else {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] %s\n", i+1, passage))
}
}
if len(docResults) > 0 {
contextsBuilder.WriteString("\n### Source 2: Reference Documents\n")
contextsBuilder.WriteString("[Supplementary - Use only when FAQ cannot answer the question]\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 := types.RenderPromptPlaceholders(chatManage.SummaryConfig.ContextTemplate, types.PlaceholderValues{
"query": safeQuery,
"contexts": contextsBuilder.String(),
"language": chatManage.Language,
})
// Append image description as text fallback only when the chat model cannot
// process images directly. Vision-capable models see images via MultiContent.
if chatManage.ImageDescription != "" && !chatManage.ChatModelSupportsVision {
userContent += "\n\n[用户上传图片内容]\n" + chatManage.ImageDescription
}
// Set formatted content back to chat management
chatManage.UserContent = userContent
pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_content_len": len(chatManage.UserContent),
"faq_priority": chatManage.FAQPriorityEnabled,
"intent": chatManage.Intent,
"image_description": chatManage.ImageDescription,
"chat_model_supports_vision": chatManage.ChatModelSupportsVision,
})
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 {
pipelineWarn(ctx, "IntoChatMessage", "image_parse_error", map[string]interface{}{
"error": err.Error(),
})
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)
pipelineInfo(ctx, "IntoChatMessage", "image_markdown_links", map[string]interface{}{
"match_count": 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("Image Caption: %s\n", imgInfo.Caption)
}
if imgInfo.OCRText != "" {
replacement += fmt.Sprintf("Image Text: %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("Image %s caption: %s", imgInfo.URL, imgInfo.Caption))
}
if imgInfo.OCRText != "" {
imgTexts = append(imgTexts, fmt.Sprintf("Image %s text: %s", imgInfo.URL, imgInfo.OCRText))
}
if len(imgTexts) > 0 {
additionalImageTexts = append(additionalImageTexts, imgTexts...)
}
}
// 如果有额外的图片信息,添加到内容末尾
if len(additionalImageTexts) > 0 {
if content != "" {
content += "\n\n"
}
content += "Additional Image Info:\n" + strings.Join(additionalImageTexts, "\n")
}
pipelineInfo(ctx, "IntoChatMessage", "image_enrich_summary", map[string]interface{}{
"markdown_images": len(matches),
"additional_imgs": len(additionalImageTexts),
})
return content
}
@@ -0,0 +1,63 @@
package chatpipeline
import (
"context"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type PluginLoadHistory struct {
messageService interfaces.MessageService
config *config.Config
}
func NewPluginLoadHistory(eventManager *EventManager,
messageService interfaces.MessageService,
config *config.Config,
) *PluginLoadHistory {
res := &PluginLoadHistory{
messageService: messageService,
config: config,
}
eventManager.Register(res)
return res
}
func (p *PluginLoadHistory) ActivationEvents() []types.EventType {
return []types.EventType{types.LOAD_HISTORY}
}
func (p *PluginLoadHistory) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
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,
})
historyList, err := loadAndProcessHistory(ctx, p.messageService, chatManage.SessionID, maxRounds, maxRounds*2+10)
if err != nil {
pipelineWarn(ctx, "LoadHistory", "history_fetch", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
chatManage.History = historyList
pipelineInfo(ctx, "LoadHistory", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"history_rounds": len(historyList),
"max_rounds": maxRounds,
})
return next()
}
@@ -0,0 +1,148 @@
package chatpipeline
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type MemoryPlugin struct {
memoryService interfaces.MemoryService
}
func NewMemoryPlugin(eventManager *EventManager, memoryService interfaces.MemoryService) *MemoryPlugin {
res := &MemoryPlugin{
memoryService: memoryService,
}
eventManager.Register(res)
return res
}
func (p *MemoryPlugin) ActivationEvents() []types.EventType {
return []types.EventType{
types.MEMORY_RETRIEVAL,
types.MEMORY_STORAGE,
}
}
func (p *MemoryPlugin) OnEvent(
ctx context.Context,
eventType types.EventType,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
switch eventType {
case types.MEMORY_RETRIEVAL:
return p.handleRetrieval(ctx, chatManage, next)
case types.MEMORY_STORAGE:
return p.handleStorage(ctx, chatManage, next)
default:
return next()
}
}
func (p *MemoryPlugin) handleRetrieval(
ctx context.Context,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
// Check if memory is enabled
if !chatManage.EnableMemory {
return next()
}
logger.Info(ctx, "Start to retrieve memory")
// Retrieve memory context
query := chatManage.RewriteQuery
if query == "" {
query = chatManage.Query
}
memoryContext, err := p.memoryService.RetrieveMemory(ctx, chatManage.UserID, query)
if err != nil {
logger.Errorf(ctx, "failed to retrieve memory: %v", err)
// Don't block the pipeline if memory retrieval fails
return next()
}
// Add memory context to chatManage
if len(memoryContext.RelatedEpisodes) > 0 {
memoryStr := "\n\nRelevant Memory:\n"
for _, ep := range memoryContext.RelatedEpisodes {
memoryStr += fmt.Sprintf("- %s (Summary: %s)\n", ep.CreatedAt.Format("2006-01-02"), ep.Summary)
}
chatManage.UserContent += memoryStr
logger.Infof(ctx, "Retrieved memory: %s", memoryStr)
}
logger.Info(ctx, "End to retrieve memory")
return next()
}
func (p *MemoryPlugin) handleStorage(
ctx context.Context,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
if err := next(); err != nil {
return err
}
// Check if memory is enabled
if !chatManage.EnableMemory {
return nil
}
logger.Info(ctx, "Start to store memory")
// If ChatResponse is already available (non-streaming), store it directly
if chatManage.ChatResponse != nil {
messages := []types.Message{
{Role: "user", Content: chatManage.Query},
{Role: "assistant", Content: chatManage.ChatResponse.Content},
}
userID := chatManage.UserID
sessionID := chatManage.SessionID
bgCtx := context.WithoutCancel(ctx)
go func() {
if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil {
logger.Errorf(bgCtx, "failed to add episode: %v", err)
}
}()
return nil
}
// If streaming, subscribe to events
if chatManage.EventBus != nil {
var fullResponse string
userID := chatManage.UserID
sessionID := chatManage.SessionID
bgCtx := context.WithoutCancel(ctx)
chatManage.EventBus.On(types.EventType(event.EventAgentFinalAnswer), func(_ context.Context, evt types.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if !ok {
return nil
}
fullResponse += data.Content
if data.Done {
messages := []types.Message{
{Role: "user", Content: chatManage.Query},
{Role: "assistant", Content: fullResponse},
}
go func() {
if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil {
logger.Errorf(bgCtx, "failed to add episode: %v", err)
}
}()
}
return nil
})
}
logger.Info(ctx, "End to store memory")
return nil
}
@@ -0,0 +1,374 @@
package chatpipeline
import (
"context"
"encoding/json"
"sort"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginMerge handles merging of search result chunks
type PluginMerge struct {
chunkRepo interfaces.ChunkRepository
chunkService interfaces.ChunkService // for parent chunk resolution
}
// NewPluginMerge creates and registers a new PluginMerge instance
func NewPluginMerge(eventManager *EventManager, chunkRepo interfaces.ChunkRepository, chunkService interfaces.ChunkService) *PluginMerge {
res := &PluginMerge{
chunkRepo: chunkRepo,
chunkService: chunkService,
}
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.
// The merge pipeline is:
// 1. Select input (rerank or search fallback)
// 2. Deduplicate by ID and content signature
// 3. Inject relevant history references
// 4. Resolve parent chunks (child → parent content)
// 5. Group by knowledge source + chunk type, merge overlapping ranges
// 6. Populate FAQ answers
// 7. Expand short contexts with neighboring chunks
// 8. Final deduplication (catches duplicates introduced by steps 4-7)
func (p *PluginMerge) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
if !chatManage.NeedsRetrieval() {
return next()
}
pipelineInfo(ctx, "Merge", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"candidate_cnt": len(chatManage.RerankResult),
})
// Step 1: Select input
searchResult := p.selectInputResults(ctx, chatManage)
// Step 2: Initial dedup
searchResult = p.dedup(ctx, "dedup_summary", searchResult)
// Step 3: Inject history references
searchResult = p.injectHistoryResults(ctx, chatManage, searchResult)
pipelineInfo(ctx, "Merge", "candidate_ready", map[string]interface{}{
"chunk_cnt": len(searchResult),
})
if len(searchResult) == 0 {
pipelineWarn(ctx, "Merge", "output", map[string]interface{}{
"chunk_cnt": 0,
"reason": "no_candidates",
})
return next()
}
// Step 4: Resolve parent chunks
searchResult = p.resolveParentChunks(ctx, chatManage, searchResult)
// Step 5: Group by knowledge/chunkType and merge overlapping ranges
mergedChunks := p.groupAndMergeOverlapping(ctx, searchResult)
// Step 6: Populate FAQ answers
mergedChunks = p.populateFAQAnswers(ctx, chatManage, mergedChunks)
// Step 7: Expand short contexts
mergedChunks = p.expandShortContextWithNeighbors(ctx, chatManage, mergedChunks)
// Step 8: Final dedup (catches duplicates from parent resolution / expansion)
mergedChunks = p.dedup(ctx, "final_dedup", mergedChunks)
chatManage.MergeResult = mergedChunks
return next()
}
// selectInputResults picks rerank results if available, falling back to search
// results sorted by score descending.
func (p *PluginMerge) selectInputResults(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult {
if len(chatManage.RerankResult) > 0 {
return chatManage.RerankResult
}
pipelineWarn(ctx, "Merge", "fallback", map[string]interface{}{
"reason": "empty_rerank_result",
})
result := chatManage.SearchResult
sort.Slice(result, func(i, j int) bool {
return result[i].Score > result[j].Score
})
return result
}
// dedup wraps removeDuplicateResults with before/after logging.
func (p *PluginMerge) dedup(ctx context.Context, label string, results []*types.SearchResult) []*types.SearchResult {
before := len(results)
out := removeDuplicateResults(results)
if len(out) < before {
pipelineInfo(ctx, "Merge", label, map[string]interface{}{
"before": before,
"after": len(out),
})
}
return out
}
// injectHistoryResults appends relevant history references to the current results
// and deduplicates the combined set.
func (p *PluginMerge) injectHistoryResults(
ctx context.Context,
chatManage *types.ChatManage,
current []*types.SearchResult,
) []*types.SearchResult {
historyResults := filterHistoryResults(ctx, chatManage, current)
if len(historyResults) == 0 {
return current
}
pipelineInfo(ctx, "Merge", "history_inject", map[string]interface{}{
"session_id": chatManage.SessionID,
"history_hits": len(historyResults),
})
combined := append(current, historyResults...)
return removeDuplicateResults(combined)
}
// groupAndMergeOverlapping groups chunks by KnowledgeID + ChunkType, then merges
// overlapping ranges within each group using mergeOverlappingChunks.
func (p *PluginMerge) groupAndMergeOverlapping(ctx context.Context, results []*types.SearchResult) []*types.SearchResult {
// Group by KnowledgeID → ChunkType
knowledgeGroup := make(map[string]map[string][]*types.SearchResult)
for _, chunk := range results {
if _, ok := knowledgeGroup[chunk.KnowledgeID]; !ok {
knowledgeGroup[chunk.KnowledgeID] = make(map[string][]*types.SearchResult)
}
knowledgeGroup[chunk.KnowledgeID][chunk.ChunkType] = append(
knowledgeGroup[chunk.KnowledgeID][chunk.ChunkType], chunk,
)
}
pipelineInfo(ctx, "Merge", "group_summary", map[string]interface{}{
"knowledge_cnt": len(knowledgeGroup),
})
// Flatten into independent (knowledgeID, chunks) work units for parallel merge.
type mergeUnit struct {
knowledgeID string
chunks []*types.SearchResult
}
var units []mergeUnit
for knowledgeID, chunkGroup := range knowledgeGroup {
for _, chunks := range chunkGroup {
units = append(units, mergeUnit{knowledgeID: knowledgeID, chunks: chunks})
}
}
groupResults := ParallelMap(units, 0, func(_ int, u mergeUnit) []*types.SearchResult {
pipelineInfo(ctx, "Merge", "group_process", map[string]interface{}{
"knowledge_id": u.knowledgeID,
"chunk_cnt": len(u.chunks),
})
sort.Slice(u.chunks, func(i, j int) bool {
if u.chunks[i].StartAt == u.chunks[j].StartAt {
return u.chunks[i].EndAt < u.chunks[j].EndAt
}
return u.chunks[i].StartAt < u.chunks[j].StartAt
})
grouped := p.mergeOverlappingChunks(ctx, u.knowledgeID, u.chunks)
pipelineInfo(ctx, "Merge", "group_output", map[string]interface{}{
"knowledge_id": u.knowledgeID,
"merged_chunks": len(grouped),
})
return grouped
})
var mergedChunks []*types.SearchResult
for _, g := range groupResults {
mergedChunks = append(mergedChunks, g...)
}
pipelineInfo(ctx, "Merge", "output", map[string]interface{}{
"merged_total": len(mergedChunks),
})
return mergedChunks
}
// resolveParentChunks replaces child chunk content with parent chunk content
// for results that have ParentChunkID set. This provides fuller context
// for small child chunks used in parent-child chunking strategy.
func (p *PluginMerge) resolveParentChunks(
ctx context.Context,
chatManage *types.ChatManage,
results []*types.SearchResult,
) []*types.SearchResult {
if len(results) == 0 || p.chunkRepo == nil {
return results
}
tenantID, _ := types.TenantIDFromContext(ctx)
if tenantID == 0 && chatManage != nil {
tenantID = chatManage.TenantID
}
if tenantID == 0 {
pipelineWarn(ctx, "Merge", "parent_resolve_skip", map[string]interface{}{
"reason": "missing_tenant",
})
return results
}
// Collect unique parent chunk IDs
parentIDs := make(map[string]struct{})
for _, r := range results {
if r.ParentChunkID != "" {
parentIDs[r.ParentChunkID] = struct{}{}
}
}
if len(parentIDs) == 0 {
return results
}
// Batch fetch parent chunks
ids := make([]string, 0, len(parentIDs))
for id := range parentIDs {
ids = append(ids, id)
}
parentChunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, ids)
if err != nil {
pipelineWarn(ctx, "Merge", "parent_resolve_failed", map[string]interface{}{
"error": err.Error(),
})
return results
}
parentMap := make(map[string]*types.Chunk, len(parentChunks))
for _, c := range parentChunks {
parentMap[c.ID] = c
}
// Collect merged ImageInfo for each parent by fetching ALL sibling
// child chunks. Individual child chunks only carry ImageInfo for images
// within their own range, but the parent content spans all children.
parentImageInfoMap := p.collectParentImageInfo(ctx, tenantID, ids)
// Replace child content with parent content
for _, r := range results {
if r.ParentChunkID == "" {
continue
}
parent, ok := parentMap[r.ParentChunkID]
if !ok || parent.Content == "" {
continue
}
pipelineInfo(ctx, "Merge", "parent_resolve", map[string]interface{}{
"child_id": r.ID,
"parent_id": r.ParentChunkID,
"child_len": runeLen(r.Content),
"parent_len": runeLen(parent.Content),
})
r.Content = parent.Content
r.StartAt = parent.StartAt
r.EndAt = parent.EndAt
if mergedImageInfo, ok := parentImageInfoMap[r.ParentChunkID]; ok && mergedImageInfo != "" {
r.ImageInfo = mergedImageInfo
}
// Track the original child as a sub-chunk
if !containsID(r.SubChunkID, r.ID) {
r.SubChunkID = append(r.SubChunkID, r.ID)
}
}
return results
}
// collectParentImageInfo batch-fetches all child chunks for the given parents
// and merges their ImageInfo into a single JSON string per parent. This ensures
// that when child content is replaced with parent content, the complete set of
// image descriptions across all sibling chunks is preserved.
func (p *PluginMerge) collectParentImageInfo(
ctx context.Context,
tenantID uint64,
parentIDs []string,
) map[string]string {
result := make(map[string]string, len(parentIDs))
allChildren, err := p.chunkRepo.ListChunksByParentIDs(ctx, tenantID, parentIDs)
if err != nil {
pipelineWarn(ctx, "Merge", "parent_imageinfo_fetch_failed", map[string]interface{}{
"parent_cnt": len(parentIDs),
"error": err.Error(),
})
return result
}
// Group children by parent chunk ID, collecting unique ImageInfo entries
type parentAgg struct {
imageInfos []types.ImageInfo
uniqueURLs map[string]bool
siblingCnt int
}
aggMap := make(map[string]*parentAgg, len(parentIDs))
for _, child := range allChildren {
agg, ok := aggMap[child.ParentChunkID]
if !ok {
agg = &parentAgg{uniqueURLs: make(map[string]bool)}
aggMap[child.ParentChunkID] = agg
}
agg.siblingCnt++
if child.ImageInfo == "" {
continue
}
var infos []types.ImageInfo
if err := json.Unmarshal([]byte(child.ImageInfo), &infos); err != nil {
pipelineWarn(ctx, "Merge", "parent_imageinfo_parse", map[string]interface{}{
"chunk_id": child.ID,
"error": err.Error(),
})
continue
}
for _, info := range infos {
key := info.URL
if key == "" {
key = info.OriginalURL
}
if key != "" && !agg.uniqueURLs[key] {
agg.uniqueURLs[key] = true
agg.imageInfos = append(agg.imageInfos, info)
}
}
}
for parentID, agg := range aggMap {
if len(agg.imageInfos) == 0 {
continue
}
merged, err := json.Marshal(agg.imageInfos)
if err != nil {
pipelineWarn(ctx, "Merge", "parent_imageinfo_marshal", map[string]interface{}{
"parent_id": parentID,
"error": err.Error(),
})
continue
}
result[parentID] = string(merged)
pipelineInfo(ctx, "Merge", "parent_imageinfo_collected", map[string]interface{}{
"parent_id": parentID,
"sibling_cnt": agg.siblingCnt,
"image_cnt": len(agg.imageInfos),
})
}
return result
}
@@ -0,0 +1,349 @@
package chatpipeline
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// expandShortContextWithNeighbors expands the short context with neighbors
func (p *PluginMerge) expandShortContextWithNeighbors(
ctx context.Context,
chatManage *types.ChatManage,
results []*types.SearchResult,
) []*types.SearchResult {
const (
minLen = 350
maxLen = 850
)
if len(results) == 0 || p.chunkRepo == nil {
return results
}
tenantID, _ := types.TenantIDFromContext(ctx)
if tenantID == 0 && chatManage != nil {
tenantID = chatManage.TenantID
}
if tenantID == 0 {
pipelineWarn(ctx, "Merge", "expand_skip", map[string]interface{}{
"reason": "missing_tenant",
})
return results
}
type targetInfo struct {
result *types.SearchResult
}
targets := make([]targetInfo, 0)
baseIDsSet := make(map[string]struct{})
for _, r := range results {
if r == nil || r.ID == "" || r.Content == "" {
continue
}
if r.ChunkType != string(types.ChunkTypeText) {
continue
}
if runeLen(r.Content) >= minLen {
continue
}
targets = append(targets, targetInfo{result: r})
baseIDsSet[r.ID] = struct{}{}
pipelineInfo(ctx, "Merge", "need_expand", map[string]interface{}{
"chunk_id": r.ID,
"content": r.Content,
"chunk_type": r.ChunkType,
"len": runeLen(r.Content),
})
}
if len(targets) == 0 {
return results
}
baseIDs := make([]string, 0, len(baseIDsSet))
for id := range baseIDsSet {
baseIDs = append(baseIDs, id)
}
chunkMap := make(map[string]*types.Chunk, len(baseIDs))
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, baseIDs)
if err != nil {
pipelineWarn(ctx, "Merge", "expand_list_base_failed", map[string]interface{}{
"error": err.Error(),
})
return results
}
for _, chunk := range chunks {
chunkMap[chunk.ID] = chunk
}
neighborIDsSet := make(map[string]struct{})
for _, chunk := range chunkMap {
if chunk == nil {
continue
}
if chunk.PreChunkID != "" {
if _, exists := chunkMap[chunk.PreChunkID]; !exists {
neighborIDsSet[chunk.PreChunkID] = struct{}{}
}
}
if chunk.NextChunkID != "" {
if _, exists := chunkMap[chunk.NextChunkID]; !exists {
neighborIDsSet[chunk.NextChunkID] = struct{}{}
}
}
}
if len(neighborIDsSet) > 0 {
neighborIDs := make([]string, 0, len(neighborIDsSet))
for id := range neighborIDsSet {
neighborIDs = append(neighborIDs, id)
}
neighbors, err := p.chunkRepo.ListChunksByID(ctx, tenantID, neighborIDs)
if err != nil {
pipelineWarn(ctx, "Merge", "expand_list_neighbor_failed", map[string]interface{}{
"error": err.Error(),
})
} else {
for _, chunk := range neighbors {
chunkMap[chunk.ID] = chunk
pipelineInfo(ctx, "Merge", "expand_list_neighbor_success", map[string]interface{}{
"neighbor_chunk_id": chunk.ID,
"neighbor_content": chunk.Content,
"neighbor_chunk_type": chunk.ChunkType,
"neighbor_len": runeLen(chunk.Content),
})
}
}
}
for _, target := range targets {
res := target.result
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, res.ID)
baseChunk := chunkMap[res.ID]
if baseChunk == nil || baseChunk.Content == "" || baseChunk.ChunkType != types.ChunkTypeText {
continue
}
prevContent := ""
nextContent := ""
prevIDs := []string{}
nextIDs := []string{}
prevCursor := baseChunk.PreChunkID
nextCursor := baseChunk.NextChunkID
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor, nextCursor)
if prevCursor != "" {
if prevChunk := chunkMap[prevCursor]; prevChunk != nil && prevChunk.KnowledgeID == baseChunk.KnowledgeID {
prevContent = prevChunk.Content
prevIDs = append(prevIDs, prevChunk.ID)
prevCursor = prevChunk.PreChunkID
} else {
prevCursor = ""
}
}
if nextCursor != "" {
if nextChunk := chunkMap[nextCursor]; nextChunk != nil && nextChunk.KnowledgeID == baseChunk.KnowledgeID {
nextContent = nextChunk.Content
nextIDs = append(nextIDs, nextChunk.ID)
nextCursor = nextChunk.NextChunkID
} else {
nextCursor = ""
}
}
var merged string
for {
merged = mergeOrderedContent(prevContent, baseChunk.Content, nextContent, maxLen)
if merged == "" {
break
}
if runeLen(merged) >= minLen {
break
}
if prevCursor == "" && nextCursor == "" {
break
}
expanded := false
if prevCursor != "" {
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor)
if prevChunk := chunkMap[prevCursor]; prevChunk != nil &&
prevChunk.KnowledgeID == baseChunk.KnowledgeID {
prevContent = concatNoOverlap(prevChunk.Content, prevContent)
prevIDs = append([]string{prevChunk.ID}, prevIDs...)
prevCursor = prevChunk.PreChunkID
expanded = true
} else {
prevCursor = ""
}
}
merged = mergeOrderedContent(prevContent, baseChunk.Content, nextContent, maxLen)
if runeLen(merged) >= minLen {
break
}
if nextCursor != "" {
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, nextCursor)
if nextChunk := chunkMap[nextCursor]; nextChunk != nil &&
nextChunk.KnowledgeID == baseChunk.KnowledgeID {
nextContent = concatNoOverlap(nextContent, nextChunk.Content)
nextIDs = append(nextIDs, nextChunk.ID)
nextCursor = nextChunk.NextChunkID
expanded = true
} else {
nextCursor = ""
}
}
if !expanded {
break
}
}
if merged == "" {
continue
}
beforeLen := runeLen(res.Content)
res.Content = merged
for _, id := range prevIDs {
if id != "" && !containsID(res.SubChunkID, id) {
res.SubChunkID = append(res.SubChunkID, id)
}
}
for _, id := range nextIDs {
if id != "" && !containsID(res.SubChunkID, id) {
res.SubChunkID = append(res.SubChunkID, id)
}
}
if prevContent != "" {
res.StartAt = baseChunk.StartAt - runeLen(prevContent)
if res.StartAt < 0 {
res.StartAt = 0
}
}
res.EndAt = res.StartAt + runeLen(res.Content)
pipelineInfo(ctx, "Merge", "expand_short_chunk", map[string]interface{}{
"chunk_id": res.ID,
"prev_ids": prevIDs,
"next_ids": nextIDs,
"before_len": beforeLen,
"after_len": runeLen(res.Content),
"base_content": baseChunk.Content,
"after_content": res.Content,
"chunk_type": res.ChunkType,
"remaining_prev": prevCursor,
"remaining_next": nextCursor,
})
}
return results
}
// runeLen returns the length of a string in runes
func runeLen(s string) int {
return len([]rune(s))
}
// mergeOrderedContent merges ordered content
func mergeOrderedContent(prev, base, next string, maxLen int) string {
content := base
if prev != "" {
content = concatNoOverlap(prev, content)
}
if next != "" {
content = concatNoOverlap(content, next)
}
runes := []rune(content)
if len(runes) > maxLen {
return string(runes[:maxLen])
}
return content
}
// concatNoOverlap concatenates two strings, removing potential overlapping prefix/suffix
func concatNoOverlap(a, b string) string {
if a == "" {
return b
}
if b == "" {
return a
}
ar := []rune(a)
br := []rune(b)
maxOverlap := minInt(len(ar), len(br))
for k := maxOverlap; k > 0; k-- {
if string(ar[len(ar)-k:]) == string(br[:k]) {
return string(ar) + string(br[k:])
}
}
return string(ar) + string(br)
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
func containsID(ids []string, target string) bool {
for _, id := range ids {
if id == target {
return true
}
}
return false
}
func (p *PluginMerge) fetchChunksIfMissing(
ctx context.Context,
tenantID uint64,
chunkMap map[string]*types.Chunk,
chunkIDs ...string,
) {
missing := make([]string, 0, len(chunkIDs))
for _, id := range chunkIDs {
if id == "" {
continue
}
if _, exists := chunkMap[id]; !exists {
missing = append(missing, id)
}
}
if len(missing) == 0 {
return
}
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, missing)
if err != nil {
pipelineWarn(ctx, "Merge", "expand_fetch_missing_failed", map[string]interface{}{
"missing_cnt": len(missing),
"error": err.Error(),
})
}
found := make(map[string]struct{}, len(chunks))
for _, chunk := range chunks {
chunkMap[chunk.ID] = chunk
found[chunk.ID] = struct{}{}
}
for _, id := range missing {
if _, ok := found[id]; !ok {
chunkMap[id] = nil
}
}
}
@@ -0,0 +1,134 @@
package chatpipeline
import (
"context"
"strings"
"github.com/Tencent/WeKnora/internal/types"
)
// populateFAQAnswers populates FAQ answers for the search results
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, _ := types.TenantIDFromContext(ctx)
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
}
// buildFAQAnswerContent builds the content of a FAQ answer
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())
}
@@ -0,0 +1,85 @@
package chatpipeline
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
)
// filterHistoryResults retrieves history references and filters them by
// textual similarity to the current query. Only references that are above
// a Jaccard similarity threshold are kept, and their scores are discounted
// to reflect that they were not directly retrieved for the current query.
// Results already present in currentResults (by chunk ID) are excluded.
func filterHistoryResults(
ctx context.Context,
chatManage *types.ChatManage,
currentResults []*types.SearchResult,
) []*types.SearchResult {
const (
// minSimilarity is the minimum Jaccard similarity between the current
// query and a history chunk's content for it to be injected.
minSimilarity = 0.15
// historyScoreDiscount reduces the original score of history results
// to rank them below freshly-retrieved results of similar relevance.
historyScoreDiscount = 0.6
// maxHistoryResults caps the number of history results injected to
// avoid overwhelming the context with stale references.
maxHistoryResults = 3
)
raw := getSearchResultFromHistory(chatManage)
if len(raw) == 0 {
return nil
}
// Build a set of chunk IDs already in current results for fast dedup
existingIDs := make(map[string]struct{}, len(currentResults))
for _, r := range currentResults {
existingIDs[r.ID] = struct{}{}
}
// Use RewriteQuery if available (it's the cleaned-up retrieval query),
// otherwise fall back to the original query.
query := chatManage.RewriteQuery
if query == "" {
query = chatManage.Query
}
queryTokens := searchutil.TokenizeSimple(query)
var filtered []*types.SearchResult
for _, r := range raw {
if _, exists := existingIDs[r.ID]; exists {
continue
}
contentTokens := searchutil.TokenizeSimple(r.Content)
sim := searchutil.Jaccard(queryTokens, contentTokens)
if sim < minSimilarity {
pipelineInfo(ctx, "Merge", "history_filter_drop", map[string]interface{}{
"chunk_id": r.ID,
"similarity": sim,
})
continue
}
r.MatchType = types.MatchTypeHistory
r.Score = r.Score * historyScoreDiscount
r.Metadata = ensureMetadata(r.Metadata)
r.Metadata["history_similarity"] = strings.TrimRight(strings.TrimRight(
fmt.Sprintf("%.4f", sim), "0"), ".")
filtered = append(filtered, r)
pipelineInfo(ctx, "Merge", "history_filter_keep", map[string]interface{}{
"chunk_id": r.ID,
"similarity": sim,
"new_score": r.Score,
})
if len(filtered) >= maxHistoryResults {
break
}
}
return filtered
}
@@ -0,0 +1,128 @@
package chatpipeline
import (
"context"
"encoding/json"
"sort"
"github.com/Tencent/WeKnora/internal/types"
)
// mergeOverlappingChunks merges chunks with overlapping or adjacent StartAt/EndAt
// ranges within a single knowledge source group. Chunks MUST be pre-sorted by
// StartAt ascending, EndAt ascending. The highest score among merged chunks is kept.
func (p *PluginMerge) mergeOverlappingChunks(
ctx context.Context,
knowledgeID string,
chunks []*types.SearchResult,
) []*types.SearchResult {
if len(chunks) == 0 {
return nil
}
merged := []*types.SearchResult{chunks[0]}
for i := 1; i < len(chunks); i++ {
lastChunk := merged[len(merged)-1]
// Non-overlapping: add as a new entry
if chunks[i].StartAt > lastChunk.EndAt {
merged = append(merged, chunks[i])
continue
}
// Partial overlap: append the non-overlapping suffix
if chunks[i].EndAt > lastChunk.EndAt {
contentRunes := []rune(chunks[i].Content)
offset := len(contentRunes) - (chunks[i].EndAt - lastChunk.EndAt)
lastChunk.Content = lastChunk.Content + string(contentRunes[offset:])
lastChunk.EndAt = chunks[i].EndAt
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
pipelineWarn(ctx, "Merge", "image_merge", map[string]interface{}{
"knowledge_id": knowledgeID,
"error": err.Error(),
})
}
} else {
// Fully contained: track the subsumed chunk and merge its ImageInfo
if !containsID(lastChunk.SubChunkID, chunks[i].ID) {
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
}
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
pipelineWarn(ctx, "Merge", "image_merge_contained", map[string]interface{}{
"knowledge_id": knowledgeID,
"error": err.Error(),
})
}
}
// Keep the higher score
if chunks[i].Score > lastChunk.Score {
lastChunk.Score = chunks[i].Score
}
}
// Sort merged chunks by score (highest first)
sort.Slice(merged, func(i, j int) bool {
return merged[i].Score > merged[j].Score
})
return merged
}
// mergeImageInfo merges ImageInfo from source into target, deduplicating by URL.
func mergeImageInfo(ctx context.Context, target *types.SearchResult, source *types.SearchResult) error {
if source.ImageInfo == "" {
return nil
}
var sourceImageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(source.ImageInfo), &sourceImageInfos); err != nil {
pipelineWarn(ctx, "Merge", "image_unmarshal_source", map[string]interface{}{
"error": err.Error(),
})
return err
}
if len(sourceImageInfos) == 0 {
return nil
}
var targetImageInfos []types.ImageInfo
if target.ImageInfo != "" {
if err := json.Unmarshal([]byte(target.ImageInfo), &targetImageInfos); err != nil {
pipelineWarn(ctx, "Merge", "image_unmarshal_target", map[string]interface{}{
"error": err.Error(),
})
target.ImageInfo = source.ImageInfo
return nil
}
}
targetImageInfos = append(targetImageInfos, sourceImageInfos...)
uniqueMap := make(map[string]bool)
uniqueImageInfos := make([]types.ImageInfo, 0, len(targetImageInfos))
for _, imgInfo := range targetImageInfos {
if imgInfo.URL != "" && !uniqueMap[imgInfo.URL] {
uniqueMap[imgInfo.URL] = true
uniqueImageInfos = append(uniqueImageInfos, imgInfo)
}
}
mergedImageInfoJSON, err := json.Marshal(uniqueImageInfos)
if err != nil {
pipelineWarn(ctx, "Merge", "image_marshal", map[string]interface{}{
"error": err.Error(),
})
return err
}
target.ImageInfo = string(mergedImageInfoJSON)
pipelineInfo(ctx, "Merge", "image_merged", map[string]interface{}{
"image_refs": len(uniqueImageInfos),
})
return nil
}
@@ -0,0 +1,147 @@
package chatpipeline
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
// --- IntoChatMessage tests ---
func TestIntoChatMessage_NoKBRetrieval(t *testing.T) {
cm := &types.ChatManage{
PipelineRequest: types.PipelineRequest{
Query: "hello world",
},
PipelineState: types.PipelineState{
Intent: types.IntentChitchat,
},
}
plugin := &PluginIntoChatMessage{}
nextCalled := false
err := plugin.OnEvent(context.Background(), types.INTO_CHAT_MESSAGE, cm, func() *PluginError {
nextCalled = true
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !nextCalled {
t.Fatal("next() was not called")
}
if cm.UserContent != "hello world" {
t.Errorf("UserContent: got %q, want %q", cm.UserContent, "hello world")
}
}
func TestIntoChatMessage_WithMergeResults(t *testing.T) {
cm := &types.ChatManage{
PipelineRequest: types.PipelineRequest{
Query: "test query",
SummaryConfig: types.SummaryConfig{
ContextTemplate: "Question: {{query}}\n\nReferences:\n{{contexts}}",
},
},
PipelineState: types.PipelineState{
MergeResult: []*types.SearchResult{
{Content: "chunk A content"},
{Content: "chunk B content"},
},
},
}
plugin := &PluginIntoChatMessage{}
nextCalled := false
err := plugin.OnEvent(context.Background(), types.INTO_CHAT_MESSAGE, cm, func() *PluginError {
nextCalled = true
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !nextCalled {
t.Fatal("next() was not called")
}
if cm.UserContent == "" {
t.Fatal("expected UserContent to be populated")
}
if !contains(cm.UserContent, "test query") {
t.Errorf("UserContent should contain query, got: %s", cm.UserContent)
}
if !contains(cm.UserContent, "chunk A content") {
t.Errorf("UserContent should contain chunk A, got: %s", cm.UserContent)
}
}
func TestIntoChatMessage_ImageDescriptionAppended(t *testing.T) {
cm := &types.ChatManage{
PipelineRequest: types.PipelineRequest{
Query: "what is this?",
ChatModelSupportsVision: false,
},
PipelineState: types.PipelineState{
Intent: types.IntentChitchat,
ImageDescription: "a cat sitting on a mat",
},
}
plugin := &PluginIntoChatMessage{}
_ = plugin.OnEvent(context.Background(), types.INTO_CHAT_MESSAGE, cm, func() *PluginError {
return nil
})
if !contains(cm.UserContent, "a cat sitting on a mat") {
t.Errorf("UserContent should contain image description, got: %s", cm.UserContent)
}
}
// --- PipelineBuilder tests ---
func TestPipelineBuilder_Basic(t *testing.T) {
pipeline := types.NewPipelineBuilder().
Add(types.LOAD_HISTORY).
Add(types.CHAT_COMPLETION_STREAM).
Build()
if len(pipeline) != 2 {
t.Fatalf("expected 2 stages, got %d", len(pipeline))
}
if pipeline[0] != types.LOAD_HISTORY {
t.Errorf("stage 0: got %v, want %v", pipeline[0], types.LOAD_HISTORY)
}
}
func TestPipelineBuilder_AddIf(t *testing.T) {
pipeline := types.NewPipelineBuilder().
Add(types.LOAD_HISTORY).
AddIf(false, types.QUERY_UNDERSTAND).
AddIf(true, types.CHAT_COMPLETION_STREAM).
Build()
if len(pipeline) != 2 {
t.Fatalf("expected 2 stages (QUERY_UNDERSTAND skipped), got %d", len(pipeline))
}
if pipeline[1] != types.CHAT_COMPLETION_STREAM {
t.Errorf("stage 1: got %v, want %v", pipeline[1], types.CHAT_COMPLETION_STREAM)
}
}
func TestPipelineBuilder_Empty(t *testing.T) {
pipeline := types.NewPipelineBuilder().Build()
if len(pipeline) != 0 {
t.Fatalf("expected 0 stages, got %d", len(pipeline))
}
}
// --- helpers ---
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsString(s, substr))
}
func containsString(s, sub string) bool {
for i := 0; i <= len(s)-len(sub); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}
@@ -0,0 +1,253 @@
package chatpipeline
import (
"context"
"regexp"
"strings"
"sync"
"unicode"
"github.com/Tencent/WeKnora/internal/types"
)
// runQueryExpansion performs query expansion when initial recall is low.
// It generates query variants and runs concurrent retrieval across search targets.
func (p *PluginSearch) runQueryExpansion(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult {
pipelineInfo(ctx, "Search", "recall_low", map[string]interface{}{
"current": len(chatManage.SearchResult),
"threshold": chatManage.EmbeddingTopK,
})
expansions := p.expandQueries(ctx, chatManage)
if len(expansions) == 0 {
return nil
}
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 search targets
expResults := make([]*types.SearchResult, 0, expTopK*len(expansions))
var muExp sync.Mutex
var wgExp sync.WaitGroup
jobs := len(expansions) * len(chatManage.SearchTargets)
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 _, target := range chatManage.SearchTargets {
wgExp.Add(1)
go func(q string, t *types.SearchTarget) {
defer wgExp.Done()
sem <- struct{}{}
defer func() { <-sem }()
paramsExp := types.SearchParams{
QueryText: q,
VectorThreshold: chatManage.VectorThreshold,
KeywordThreshold: expKwTh,
MatchCount: expTopK,
DisableVectorMatch: false,
DisableKeywordsMatch: false,
SkipContextEnrichment: true, // Pipeline handles context assembly in merge stage
}
// Apply knowledge ID filter if this is a partial KB search
if t.Type == types.SearchTargetTypeKnowledge {
paramsExp.KnowledgeIDs = t.KnowledgeIDs
}
res, err := p.knowledgeBaseService.HybridSearch(ctx, t.KnowledgeBaseID, paramsExp)
if err != nil {
pipelineWarn(ctx, "Search", "expansion_error", map[string]interface{}{
"kb_id": t.KnowledgeBaseID,
"error": err.Error(),
})
return
}
if len(res) > 0 {
for _, r := range res {
r.KnowledgeBaseID = t.KnowledgeBaseID
}
pipelineInfo(ctx, "Search", "expansion_hits", map[string]interface{}{
"kb_id": t.KnowledgeBaseID,
"query": q,
"hits": len(res),
})
muExp.Lock()
expResults = append(expResults, res...)
muExp.Unlock()
}
}(q, target)
}
}
wgExp.Wait()
if len(expResults) > 0 {
pipelineInfo(ctx, "Search", "expansion_done", map[string]interface{}{
"added": len(expResults),
})
}
return expResults
}
// expandQueries generates query variants locally without LLM to improve keyword recall.
// Uses simple techniques: word reordering, stopword removal, key phrase extraction.
func (p *PluginSearch) expandQueries(ctx context.Context, chatManage *types.ChatManage) []string {
query := strings.TrimSpace(chatManage.RewriteQuery)
if query == "" {
return nil
}
expansions := make([]string, 0, 5)
seen := make(map[string]struct{})
seen[strings.ToLower(query)] = struct{}{}
if q := strings.ToLower(chatManage.Query); q != "" {
seen[q] = struct{}{}
}
addIfNew := func(s string) {
s = strings.TrimSpace(s)
if s == "" || len(s) < 3 {
return
}
key := strings.ToLower(s)
if _, ok := seen[key]; ok {
return
}
seen[key] = struct{}{}
expansions = append(expansions, s)
}
// 1. Remove common stopwords and create keyword-only variant
keywords := extractKeywords(query)
if len(keywords) >= 2 {
addIfNew(strings.Join(keywords, " "))
}
// 2. Extract quoted phrases or key segments
phrases := extractPhrases(query)
for _, phrase := range phrases {
addIfNew(phrase)
}
// 3. Split by common delimiters and use longest segment
segments := splitByDelimiters(query)
for _, seg := range segments {
if len(seg) > 5 {
addIfNew(seg)
}
}
// 4. Remove question words (什么/如何/怎么/为什么/哪个 etc.)
cleaned := removeQuestionWords(query)
if cleaned != query {
addIfNew(cleaned)
}
// Limit to 5 expansions
if len(expansions) > 5 {
expansions = expansions[:5]
}
pipelineInfo(ctx, "Search", "local_expansion_result", map[string]interface{}{
"variants": len(expansions),
})
return expansions
}
// Common Chinese and English stopwords
var stopwords = map[string]struct{}{
"的": {}, "是": {}, "在": {}, "了": {}, "和": {}, "与": {}, "或": {},
"a": {}, "an": {}, "the": {}, "is": {}, "are": {}, "was": {}, "were": {},
"be": {}, "been": {}, "being": {}, "have": {}, "has": {}, "had": {},
"do": {}, "does": {}, "did": {}, "will": {}, "would": {}, "could": {},
"should": {}, "may": {}, "might": {}, "must": {}, "can": {},
"to": {}, "of": {}, "in": {}, "for": {}, "on": {}, "with": {}, "at": {},
"by": {}, "from": {}, "as": {}, "into": {}, "through": {}, "about": {},
"what": {}, "how": {}, "why": {}, "when": {}, "where": {}, "which": {},
"who": {}, "whom": {}, "whose": {},
}
// Question words in Chinese
var questionWords = regexp.MustCompile(`^(什么是|什么|如何|怎么|怎样|为什么|为何|哪个|哪些|谁|何时|何地|请问|请告诉我|帮我|我想知道|我想了解)`)
func extractKeywords(text string) []string {
words := tokenize(text)
keywords := make([]string, 0, len(words))
for _, w := range words {
lower := strings.ToLower(w)
if _, isStop := stopwords[lower]; !isStop && len(w) > 1 {
keywords = append(keywords, w)
}
}
return keywords
}
func extractPhrases(text string) []string {
// Extract quoted content
var phrases []string
re := regexp.MustCompile(`["'"'「」『』]([^"'"'「」『』]+)["'"'「」『』]`)
matches := re.FindAllStringSubmatch(text, -1)
for _, m := range matches {
if len(m) > 1 && len(m[1]) > 2 {
phrases = append(phrases, m[1])
}
}
return phrases
}
func splitByDelimiters(text string) []string {
// Split by common delimiters
re := regexp.MustCompile(`[,,;;、。!?!?\s]+`)
parts := re.Split(text, -1)
var result []string
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
result = append(result, p)
}
}
return result
}
func removeQuestionWords(text string) string {
return strings.TrimSpace(questionWords.ReplaceAllString(text, ""))
}
func tokenize(text string) []string {
var tokens []string
var current strings.Builder
for _, r := range text {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
current.WriteRune(r)
} else if unicode.Is(unicode.Han, r) {
// Flush current token
if current.Len() > 0 {
tokens = append(tokens, current.String())
current.Reset()
}
// Chinese character as single token
tokens = append(tokens, string(r))
} else {
// Delimiter
if current.Len() > 0 {
tokens = append(tokens, current.String())
current.Reset()
}
}
}
if current.Len() > 0 {
tokens = append(tokens, current.String())
}
return tokens
}
@@ -0,0 +1,454 @@
package chatpipeline
import (
"context"
"encoding/json"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// PluginQueryUnderstand performs query rewriting and intent classification.
// It uses conversation history and an LLM to optimise the user's original query
// and determine the downstream pipeline behaviour.
type PluginQueryUnderstand struct {
modelService interfaces.ModelService
messageService interfaces.MessageService
config *config.Config
}
var rewriteImageSepPattern = regexp.MustCompile(`(?s)^(.*?)\s*\n?---\n(.*)$`)
type queryUnderstandOutput struct {
RewriteQuery string `json:"rewrite_query"`
Intent types.QueryIntent `json:"intent"`
ImageDescription string `json:"image_description"`
}
// NewPluginQueryUnderstand creates a new query-understanding plugin instance
// and registers it with the event manager.
func NewPluginQueryUnderstand(eventManager *EventManager,
modelService interfaces.ModelService, messageService interfaces.MessageService,
config *config.Config,
) *PluginQueryUnderstand {
res := &PluginQueryUnderstand{
modelService: modelService,
messageService: messageService,
config: config,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the list of event types this plugin responds to.
func (p *PluginQueryUnderstand) ActivationEvents() []types.EventType {
return []types.EventType{types.QUERY_UNDERSTAND}
}
// OnEvent processes triggered events.
// Handles three input combinations:
// - Text only: standard rewrite + intent classification (uses chat model)
// - Text + images: multimodal rewrite + intent + image description (uses VLM/vision model)
// - Images only: multimodal analysis + intent + image description (uses VLM/vision model)
func (p *PluginQueryUnderstand) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
chatManage.RewriteQuery = chatManage.Query
hasImages := len(chatManage.Images) > 0
needRewrite := chatManage.EnableRewrite
if !needRewrite && !hasImages {
pipelineInfo(ctx, "QueryUnderstand", "skip", map[string]interface{}{
"session_id": chatManage.SessionID,
"reason": "rewrite_disabled_no_images",
})
return next()
}
pipelineInfo(ctx, "QueryUnderstand", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"tenant_id": chatManage.TenantID,
"user_query": chatManage.Query,
"has_images": hasImages,
"enable_rewrite": chatManage.EnableRewrite,
})
// --- Load and prepare conversation history ---
var historyList []*types.History
if len(chatManage.History) > 0 {
historyList = chatManage.History
pipelineInfo(ctx, "QueryUnderstand", "history_reused", map[string]interface{}{
"session_id": chatManage.SessionID,
"rounds": len(historyList),
})
} else {
historyList = p.loadHistory(ctx, chatManage)
}
// --- Select the appropriate model ---
rewriteModel, useImages := p.selectModel(ctx, chatManage, hasImages)
if rewriteModel == nil {
pipelineError(ctx, "QueryUnderstand", "get_model", map[string]interface{}{
"session_id": chatManage.SessionID,
})
return next()
}
// --- Build prompts ---
systemContent, userContent := p.buildPrompts(chatManage, historyList)
userMsg := chat.Message{Role: "user", Content: userContent}
if useImages {
userMsg.Images = chatManage.Images
}
maxTokens := 60
if useImages {
maxTokens = 500
}
// --- Emit progress event for image analysis ---
var toolCallID string
if useImages && chatManage.EventBus != nil {
toolCallID = uuid.New().String()
chatManage.EventBus.Emit(ctx, types.Event{
Type: types.EventType(event.EventAgentToolCall),
SessionID: chatManage.SessionID,
Data: event.AgentToolCallData{
ToolCallID: toolCallID,
ToolName: "image_analysis",
},
})
}
// --- Call model ---
thinking := false
vlmStart := time.Now()
response, err := rewriteModel.Chat(ctx, []chat.Message{
{Role: "system", Content: systemContent},
userMsg,
}, &chat.ChatOptions{
Temperature: 0.3,
MaxCompletionTokens: maxTokens,
Thinking: &thinking,
})
if err != nil {
if toolCallID != "" && chatManage.EventBus != nil {
chatManage.EventBus.Emit(ctx, types.Event{
Type: types.EventType(event.EventAgentToolResult),
SessionID: chatManage.SessionID,
Data: event.AgentToolResultData{
ToolCallID: toolCallID,
ToolName: "image_analysis",
Output: "图片分析失败",
Success: false,
Duration: time.Since(vlmStart).Milliseconds(),
},
})
}
pipelineError(ctx, "QueryUnderstand", "model_call", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
// --- Emit completion event for image analysis ---
if toolCallID != "" && chatManage.EventBus != nil {
chatManage.EventBus.Emit(ctx, types.Event{
Type: types.EventType(event.EventAgentToolResult),
SessionID: chatManage.SessionID,
Data: event.AgentToolResultData{
ToolCallID: toolCallID,
ToolName: "image_analysis",
Output: "已分析图片内容",
Success: true,
Duration: time.Since(vlmStart).Milliseconds(),
},
})
}
// --- Parse structured output ---
p.parseOutput(chatManage, response.Content)
// Persist image description asynchronously — this DB write does not affect
// the current pipeline result, so it can run in the background.
if chatManage.ImageDescription != "" && chatManage.UserMessageID != "" {
go p.updateUserMessageImageCaption(context.WithoutCancel(ctx), chatManage)
}
// --- Apply intent-specific system prompt override ---
if !chatManage.NeedsRetrieval() {
if prompt, ok := p.config.Conversation.IntentSystemPrompts[string(chatManage.Intent)]; ok {
chatManage.SystemPromptOverride = prompt
pipelineInfo(ctx, "QueryUnderstand", "prompt_override", map[string]interface{}{
"session_id": chatManage.SessionID,
"intent": chatManage.Intent,
})
}
}
pipelineInfo(ctx, "QueryUnderstand", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"rewrite_query": chatManage.RewriteQuery,
"intent": chatManage.Intent,
"has_image_desc": chatManage.ImageDescription != "",
"has_prompt_override": chatManage.SystemPromptOverride != "",
"original_output": response.Content,
})
return next()
}
// updateUserMessageImageCaption writes the generated ImageDescription back to
// the stored user message so that subsequent turns can see it in history.
func (p *PluginQueryUnderstand) updateUserMessageImageCaption(ctx context.Context, chatManage *types.ChatManage) {
msg, err := p.messageService.GetMessage(ctx, chatManage.SessionID, chatManage.UserMessageID)
if err != nil {
pipelineWarn(ctx, "QueryUnderstand", "get_user_message", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_message_id": chatManage.UserMessageID,
"error": err.Error(),
})
return
}
if len(msg.Images) == 0 {
return
}
msg.Images[0].Caption = chatManage.ImageDescription
if err := p.messageService.UpdateMessageImages(ctx, chatManage.SessionID, chatManage.UserMessageID, msg.Images); err != nil {
pipelineWarn(ctx, "QueryUnderstand", "update_image_caption", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_message_id": chatManage.UserMessageID,
"error": err.Error(),
})
}
}
// loadHistory fetches and processes conversation history for rewrite context.
func (p *PluginQueryUnderstand) loadHistory(ctx context.Context, chatManage *types.ChatManage) []*types.History {
maxRounds := p.config.Conversation.MaxRounds
if chatManage.MaxRounds > 0 {
maxRounds = chatManage.MaxRounds
}
historyList, err := loadAndProcessHistory(ctx, p.messageService, chatManage.SessionID, maxRounds, 20)
if err != nil {
pipelineWarn(ctx, "QueryUnderstand", "history_fetch", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return nil
}
chatManage.History = historyList
if len(historyList) > 0 {
pipelineInfo(ctx, "QueryUnderstand", "history_ready", map[string]interface{}{
"session_id": chatManage.SessionID,
"history_rounds": len(historyList),
})
}
return historyList
}
// selectModel picks the model for query understanding. When images are present
// it prefers a vision-capable model. Returns (model, useImages).
func (p *PluginQueryUnderstand) selectModel(ctx context.Context, chatManage *types.ChatManage, hasImages bool) (chat.Chat, bool) {
if hasImages {
if chatManage.ChatModelSupportsVision {
m, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err == nil {
return m, true
}
pipelineWarn(ctx, "QueryUnderstand", "vision_model_fallback", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
}
if chatManage.VLMModelID != "" {
m, err := p.modelService.GetChatModel(ctx, chatManage.VLMModelID)
if err == nil {
return m, true
}
pipelineWarn(ctx, "QueryUnderstand", "vlm_model_fallback", map[string]interface{}{
"session_id": chatManage.SessionID,
"vlm_model_id": chatManage.VLMModelID,
"error": err.Error(),
})
}
pipelineWarn(ctx, "QueryUnderstand", "no_vision_model", map[string]interface{}{
"session_id": chatManage.SessionID,
})
}
m, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
pipelineError(ctx, "QueryUnderstand", "get_model", map[string]interface{}{
"session_id": chatManage.SessionID,
"chat_model_id": chatManage.ChatModelID,
"error": err.Error(),
})
return nil, false
}
return m, false
}
// buildPrompts constructs system and user prompts with placeholder replacement.
func (p *PluginQueryUnderstand) buildPrompts(chatManage *types.ChatManage, historyList []*types.History) (string, string) {
userPrompt := p.config.Conversation.RewritePromptUser
if chatManage.RewritePromptUser != "" {
userPrompt = chatManage.RewritePromptUser
}
systemPrompt := p.config.Conversation.RewritePromptSystem
if chatManage.RewritePromptSystem != "" {
systemPrompt = chatManage.RewritePromptSystem
}
conversationText := formatConversationHistory(historyList)
vals := types.PlaceholderValues{
"conversation": conversationText,
"query": chatManage.Query,
"language": chatManage.Language,
}
return types.RenderPromptPlaceholders(systemPrompt, vals),
types.RenderPromptPlaceholders(userPrompt, vals)
}
// parseOutput extracts the rewritten query, intent classification, and optional
// image description from the model's structured JSON output.
//
// Expected format: {"rewrite_query":"...","intent":"kb_search","image_description":"..."}
func (p *PluginQueryUnderstand) parseOutput(chatManage *types.ChatManage, raw string) {
content := strings.TrimSpace(raw)
if content == "" {
return
}
if output, ok := parseStructuredQueryOutput(content); ok {
if rewrite := strings.TrimSpace(output.RewriteQuery); rewrite != "" {
chatManage.RewriteQuery = rewrite
}
chatManage.Intent = output.Intent
chatManage.ImageDescription = strings.TrimSpace(output.ImageDescription)
return
}
// If JSON parsing failed entirely, treat the raw text as the rewritten query
// and default to IntentKBSearch for safety.
if content != "" {
chatManage.RewriteQuery = content
}
}
func parseStructuredQueryOutput(raw string) (queryUnderstandOutput, bool) {
content := strings.TrimSpace(raw)
if content == "" {
return queryUnderstandOutput{}, false
}
if parsed, ok := parseStructuredQueryOutputJSON(content); ok {
return parsed, true
}
// Be tolerant to occasional markdown wrappers or extra prose.
start := strings.Index(content, "{")
end := strings.LastIndex(content, "}")
if start < 0 || end <= start {
return queryUnderstandOutput{}, false
}
candidate := content[start : end+1]
if parsed, ok := parseStructuredQueryOutputJSON(candidate); ok {
return parsed, true
}
return queryUnderstandOutput{}, false
}
func parseStructuredQueryOutputJSON(content string) (queryUnderstandOutput, bool) {
var obj map[string]json.RawMessage
if err := json.Unmarshal([]byte(content), &obj); err != nil {
return queryUnderstandOutput{}, false
}
out := queryUnderstandOutput{
RewriteQuery: strings.TrimSpace(firstStringField(obj,
"rewrite_query", "rewritten_query", "query", "question")),
}
intentStr := strings.TrimSpace(firstStringField(obj, "intent"))
if intentStr != "" {
out.Intent = types.QueryIntent(intentStr)
}
desc := strings.TrimSpace(firstStringField(obj,
"image_description", "image_desc", "image_text", "image_ocr_text", "description"))
ocr := strings.TrimSpace(firstStringField(obj,
"ocr_text", "ocr", "full_ocr", "image_ocr", "ocr_content"))
combined, set := mergeImageDescAndOCR(desc, ocr)
if set {
out.ImageDescription = combined
}
return out, true
}
func firstStringField(obj map[string]json.RawMessage, keys ...string) string {
for _, key := range keys {
raw, ok := obj[key]
if !ok || len(raw) == 0 {
continue
}
var s string
if err := json.Unmarshal(raw, &s); err == nil {
return s
}
}
return ""
}
func mergeImageDescAndOCR(desc, ocr string) (string, bool) {
if desc == "" && ocr == "" {
return "", false
}
if desc == "" {
return ocr, true
}
if ocr == "" {
return desc, true
}
if strings.Contains(desc, ocr) {
return desc, true
}
return desc + "\n\n[OCR]\n" + ocr, true
}
// 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("User question: ")
builder.WriteString(h.Query)
builder.WriteString("\nAssistant answer: ")
builder.WriteString(h.Answer)
builder.WriteString("\n------END------\n")
}
return builder.String()
}
@@ -0,0 +1,601 @@
package chatpipeline
import (
"context"
"encoding/json"
"fmt"
"math"
"regexp"
"strings"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/searchutil"
"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 {
if !chatManage.NeedsRetrieval() {
return next()
}
pipelineInfo(ctx, "Rerank", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"candidate_cnt": len(chatManage.SearchResult),
"rerank_model": chatManage.RerankModelID,
"rerank_thresh": chatManage.RerankThreshold,
"rewrite_query": chatManage.RewriteQuery,
})
if len(chatManage.SearchResult) == 0 {
pipelineInfo(ctx, "Rerank", "skip", map[string]interface{}{
"reason": "empty_search_result",
})
return next()
}
if chatManage.RerankModelID == "" {
pipelineWarn(ctx, "Rerank", "skip", map[string]interface{}{
"reason": "empty_model_id",
})
return next()
}
// Get rerank model from service
rerankModel, err := p.modelService.GetRerankModel(ctx, chatManage.RerankModelID)
if err != nil {
pipelineError(ctx, "Rerank", "get_model", map[string]interface{}{
"model_id": chatManage.RerankModelID,
"error": err.Error(),
})
return ErrGetRerankModel.WithError(err)
}
// Prepare passages for reranking (excluding DirectLoad results)
var passages []string
var candidatesToRerank []*types.SearchResult
var directLoadResults []*types.SearchResult
for _, result := range chatManage.SearchResult {
if result.MatchType == types.MatchTypeDirectLoad {
directLoadResults = append(directLoadResults, result)
pipelineInfo(ctx, "Rerank", "direct_load_skip", map[string]interface{}{
"chunk_id": result.ID,
})
continue
}
// 合并Content和ImageInfo的文本内容
passage := getEnrichedPassage(ctx, result)
// Skip passages that become empty after cleaning
if strings.TrimSpace(passage) == "" {
pipelineInfo(ctx, "Rerank", "empty_passage_skip", map[string]interface{}{
"chunk_id": result.ID,
})
continue
}
passages = append(passages, passage)
candidatesToRerank = append(candidatesToRerank, result)
}
pipelineInfo(ctx, "Rerank", "build_passages", map[string]interface{}{
"total_cnt": len(chatManage.SearchResult),
"candidate_cnt": len(candidatesToRerank),
"direct_cnt": len(directLoadResults),
})
var rerankResp []rerank.RankResult
// Only call rerank model if there are candidates
if len(candidatesToRerank) > 0 {
// Single rerank call with RewriteQuery, use threshold degradation if no results
originalThreshold := chatManage.RerankThreshold
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages, candidatesToRerank)
// If no results and threshold is high enough, try with lower threshold
if len(rerankResp) == 0 && originalThreshold > 0.3 {
degradedThreshold := originalThreshold * 0.7
if degradedThreshold < 0.3 {
degradedThreshold = 0.3
}
pipelineWarn(ctx, "Rerank", "threshold_degrade", map[string]interface{}{
"original": originalThreshold,
"degraded": degradedThreshold,
"candidate_cnt": len(candidatesToRerank),
"reason": "no results above original threshold, retrying with lower threshold",
})
chatManage.RerankThreshold = degradedThreshold
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages, candidatesToRerank)
// Restore original threshold
chatManage.RerankThreshold = originalThreshold
}
}
pipelineInfo(ctx, "Rerank", "model_response", map[string]interface{}{
"result_cnt": len(rerankResp),
})
logRerankInputScoreSample(ctx, chatManage.SearchResult)
for i := range chatManage.SearchResult {
chatManage.SearchResult[i].Metadata = ensureMetadata(chatManage.SearchResult[i].Metadata)
}
reranked := make([]*types.SearchResult, 0, len(rerankResp)+len(directLoadResults))
// Process reranked results
for _, rr := range rerankResp {
if rr.Index >= len(candidatesToRerank) {
continue
}
sr := candidatesToRerank[rr.Index]
base := sr.Score
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,
})
}
reranked = append(reranked, sr)
}
// Process direct load results (bypass rerank model, assume high relevance)
for _, sr := range directLoadResults {
base := sr.Score
sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base)
// Assign high model score for direct load items
modelScore := 1.0
sr.Score = compositeScore(sr, modelScore, base)
reranked = append(reranked, sr)
}
final := applyMMR(ctx, reranked, chatManage, min(len(reranked), max(1, chatManage.RerankTopK)), 0.7)
chatManage.RerankResult = final
// Log composite top scores and MMR selection summary
topN := min(3, len(reranked))
for i := 0; i < topN; i++ {
pipelineInfo(ctx, "Rerank", "composite_top", map[string]interface{}{
"rank": i + 1,
"chunk_id": reranked[i].ID,
"base_score": reranked[i].Metadata["base_score"],
"final_score": fmt.Sprintf("%.4f", reranked[i].Score),
})
}
if len(chatManage.RerankResult) == 0 {
pipelineWarn(ctx, "Rerank", "output", map[string]interface{}{
"filtered_cnt": 0,
})
return ErrSearchNothing
}
pipelineInfo(ctx, "Rerank", "output", map[string]interface{}{
"filtered_cnt": 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,
candidates []*types.SearchResult,
) []rerank.RankResult {
pipelineInfo(ctx, "Rerank", "model_call", map[string]interface{}{
"query_variant": query,
"passages": len(passages),
})
// Filter out empty or whitespace-only passages before sending to the API
var cleanPassages []string
var cleanCandidates []*types.SearchResult
for i, p := range passages {
if strings.TrimSpace(p) != "" {
cleanPassages = append(cleanPassages, p)
if i < len(candidates) {
cleanCandidates = append(cleanCandidates, candidates[i])
}
}
}
if len(cleanPassages) == 0 {
pipelineInfo(ctx, "Rerank", "model_call_skip", map[string]interface{}{
"reason": "all_passages_empty",
})
return nil
}
passages = cleanPassages
candidates = cleanCandidates
rerankResp, err := rerankModel.Rerank(ctx, query, passages)
if err != nil {
pipelineError(ctx, "Rerank", "model_call", map[string]interface{}{
"query_variant": query,
"error": err.Error(),
})
return nil
}
// Log top scores for debugging
pipelineInfo(ctx, "Rerank", "threshold", map[string]interface{}{
"threshold": chatManage.RerankThreshold,
})
logged := min(5, len(rerankResp))
for i := range logged {
if rerankResp[i].Index < len(candidates) {
pipelineInfo(ctx, "Rerank", "top_score", map[string]interface{}{
"rank": i + 1,
"score": rerankResp[i].RelevanceScore,
"chunk_id": candidates[rerankResp[i].Index].ID,
"match_type": candidates[rerankResp[i].Index].MatchType,
"chunk_type": candidates[rerankResp[i].Index].ChunkType,
"content_len": len(candidates[rerankResp[i].Index].Content),
})
}
}
if len(rerankResp) > logged {
pipelineInfo(ctx, "Rerank", "top_score_summary", map[string]interface{}{
"total": len(rerankResp),
"logged": logged,
"truncated": len(rerankResp) - logged,
})
}
// Filter results based on threshold
rankFilter := []rerank.RankResult{}
for _, result := range rerankResp {
if result.Index >= len(candidates) {
continue
}
if result.RelevanceScore >= chatManage.RerankThreshold {
rankFilter = append(rankFilter, result)
}
}
// Fallback: if threshold filtering removed all results but the top candidate
// still has a reasonable score, keep it as a safety net. Skip fallback entirely
// when the best score is too low — forcing irrelevant results is worse than
// returning nothing and letting the caller handle the empty-result case.
const fallbackMinScore = 0.15
if len(rankFilter) == 0 && len(rerankResp) > 0 && rerankResp[0].RelevanceScore >= fallbackMinScore {
rankFilter = rerankResp[:1]
pipelineInfo(ctx, "Rerank", "fallback_top1", map[string]interface{}{
"reason": "all_below_threshold",
"threshold": chatManage.RerankThreshold,
"top_score": rerankResp[0].RelevanceScore,
})
} else if len(rankFilter) == 0 {
pipelineInfo(ctx, "Rerank", "fallback_skip", map[string]interface{}{
"reason": "top_score_too_low",
"threshold": chatManage.RerankThreshold,
"top_score": safeTopScore(rerankResp),
})
}
return rankFilter
}
// ensureMetadata ensures the metadata is not nil
func ensureMetadata(m map[string]string) map[string]string {
if m == nil {
return make(map[string]string)
}
return m
}
func safeTopScore(results []rerank.RankResult) float64 {
if len(results) == 0 {
return 0
}
return results[0].RelevanceScore
}
// compositeScore calculates the composite score for a search result
func compositeScore(sr *types.SearchResult, modelScore, baseScore float64) float64 {
sourceWeight := 1.0
switch strings.ToLower(sr.KnowledgeSource) {
case "web_search":
sourceWeight = 0.95
default:
sourceWeight = 1.0
}
positionPrior := 1.0
if sr.StartAt >= 0 {
positionPrior += searchutil.ClampFloat(1.0-float64(sr.StartAt)/float64(sr.EndAt+1), -0.05, 0.05)
}
composite := 0.6*modelScore + 0.3*baseScore + 0.1*sourceWeight
composite *= positionPrior
if composite < 0 {
composite = 0
}
if composite > 1 {
composite = 1
}
return composite
}
// applyMMR applies the MMR algorithm to the search results with pre-computed token sets
func applyMMR(
ctx context.Context,
results []*types.SearchResult,
chatManage *types.ChatManage,
k int,
lambda float64,
) []*types.SearchResult {
if k <= 0 || len(results) == 0 {
return nil
}
pipelineInfo(ctx, "Rerank", "mmr_start", map[string]interface{}{
"lambda": lambda,
"k": k,
"candidates": len(results),
})
// Pre-compute all token sets concurrently (CPU-bound tokenization)
allTokenSets := ParallelMap(results, 0, func(i int, r *types.SearchResult) map[string]struct{} {
return searchutil.TokenizeSimple(getEnrichedPassage(ctx, r))
})
selected := make([]*types.SearchResult, 0, k)
selectedTokenSets := make([]map[string]struct{}, 0, k)
selectedIndices := make(map[int]struct{})
for len(selected) < k && len(selectedIndices) < len(results) {
bestIdx := -1
bestScore := -1.0
for i, r := range results {
if _, isSelected := selectedIndices[i]; isSelected {
continue
}
relevance := r.Score
redundancy := 0.0
// Use pre-computed token sets for redundancy calculation
for _, selTokens := range selectedTokenSets {
sim := searchutil.Jaccard(allTokenSets[i], selTokens)
if sim > redundancy {
redundancy = sim
}
}
mmr := lambda*relevance - (1.0-lambda)*redundancy
if mmr > bestScore {
bestScore = mmr
bestIdx = i
}
}
if bestIdx < 0 {
break
}
selected = append(selected, results[bestIdx])
selectedTokenSets = append(selectedTokenSets, allTokenSets[bestIdx])
selectedIndices[bestIdx] = struct{}{}
}
// Compute average redundancy among selected using pre-computed token sets
avgRed := 0.0
if len(selected) > 1 {
pairs := 0
for i := 0; i < len(selectedTokenSets); i++ {
for j := i + 1; j < len(selectedTokenSets); j++ {
avgRed += searchutil.Jaccard(selectedTokenSets[i], selectedTokenSets[j])
pairs++
}
}
if pairs > 0 {
avgRed /= float64(pairs)
}
}
pipelineInfo(ctx, "Rerank", "mmr_done", map[string]interface{}{
"selected": len(selected),
"avg_redundancy": fmt.Sprintf("%.4f", avgRed),
})
return selected
}
// --- Passage cleaning for rerank ---
//
// Rerank models work on semantic text similarity. Markdown formatting, raw URLs,
// image references, table separators, and other structural syntax are noise that
// can dilute the semantic signal. The functions below strip this noise before
// passages are sent to the rerank model.
var (
// reMarkdownImage matches ![alt](url) — the entire construct is noise.
// URL group supports one level of balanced parentheses.
reMarkdownImage = regexp.MustCompile(`!\[[^\]]*\]\([^()\s]*(?:\([^)]*\)[^()\s]*)*\)`)
// reLinkedImage matches [![alt](img_url)](link_url) — unwrap to ![alt](img_url)
// so that the subsequent reMarkdownImage pass can remove the image.
reLinkedImage = regexp.MustCompile(
`\[!\[([^\]]*)\]\(([^()\s]*(?:\([^)]*\)[^()\s]*)*)\)\]` +
`\([^()\s]*(?:\([^)]*\)[^()\s]*)*\)`,
)
// reMarkdownLink matches [text](url) — we keep the text, drop the URL.
// URL group supports one level of balanced parentheses.
reMarkdownLink = regexp.MustCompile(`\[([^\]]+)\]\([^()\s]*(?:\([^)]*\)[^()\s]*)*\)`)
// reRawURL matches standalone http(s) URLs.
reRawURL = regexp.MustCompile(`https?://[^\s)\]>]+`)
// reCodeBlock matches fenced code blocks (```...```).
reCodeBlock = regexp.MustCompile("(?s)```(?:\\w*)\n?.*?```")
// reLatexBlock matches block-level LaTeX ($$...$$).
reLatexBlock = regexp.MustCompile(`(?s)\$\$.*?\$\$`)
// reTableSep matches table separator rows like |---|---|.
reTableSep = regexp.MustCompile(`(?m)^\s*\|[\s:|-]+\|\s*$`)
// reTableRow matches markdown table data rows like | col1 | col2 |.
reTableRow = regexp.MustCompile(`(?m)^\s*\|(.+?)\|\s*$`)
// reHeadingPrefix matches leading # markers in headings.
reHeadingPrefix = regexp.MustCompile(`(?m)^#{1,6}\s+`)
// reBlockquote matches leading > markers.
reBlockquote = regexp.MustCompile(`(?m)^>\s?`)
// reBoldItalic3 matches ***text*** wrappers (must come before 2 and 1).
reBoldItalic3 = regexp.MustCompile(`\*{3}(.+?)\*{3}`)
// reBoldItalic2 matches **text** wrappers.
reBoldItalic2 = regexp.MustCompile(`\*{2}(.+?)\*{2}`)
// reBoldItalic1 matches *text* wrappers.
reBoldItalic1 = regexp.MustCompile(`\*(.+?)\*`)
// reExcessiveNewlines collapses 3+ consecutive newlines into 2.
reExcessiveNewlines = regexp.MustCompile(`\n{3,}`)
// reListMarker matches unordered (- , * ) and ordered (1. ) list prefixes.
reListMarker = regexp.MustCompile(`(?m)^[\t ]*(?:[-*+]|\d+\.)\s+`)
// reHTMLTag matches HTML tags like <br>, <div class="...">, etc.
reHTMLTag = regexp.MustCompile(`</?[a-zA-Z][^>]*>`)
)
// cleanPassageForRerank strips markdown/structural noise from text to produce
// a clean semantic passage for the rerank model. The cleaning is designed to
// preserve all meaningful natural-language content while removing formatting
// that would confuse text-similarity scoring.
func cleanPassageForRerank(text string) string {
// 1. Remove code blocks (before other patterns to avoid partial matches)
text = reCodeBlock.ReplaceAllString(text, "")
// 2. Remove LaTeX block math
text = reLatexBlock.ReplaceAllString(text, "")
// 3. Remove HTML tags
text = reHTMLTag.ReplaceAllString(text, "")
// 3.5. Unwrap nested [![alt](img_url)](link_url) → ![alt](img_url)
// so that the next step removes the full construct cleanly.
text = reLinkedImage.ReplaceAllString(text, "![$1]($2)")
// 4. Remove markdown image references entirely
text = reMarkdownImage.ReplaceAllString(text, "")
// 5. Convert markdown links to just their display text
text = reMarkdownLink.ReplaceAllString(text, "$1")
// 6. Remove standalone raw URLs
text = reRawURL.ReplaceAllString(text, "")
// 7. Remove table separator rows
text = reTableSep.ReplaceAllString(text, "")
// 7.5. Convert table data rows to plain text (strip | delimiters)
text = reTableRow.ReplaceAllStringFunc(text, func(match string) string {
inner := reTableRow.FindStringSubmatch(match)
if len(inner) < 2 {
return match
}
cells := strings.Split(inner[1], "|")
var parts []string
for _, cell := range cells {
cell = strings.TrimSpace(cell)
if cell != "" {
parts = append(parts, cell)
}
}
return strings.Join(parts, ", ")
})
// 8. Strip heading markers but keep heading text
text = reHeadingPrefix.ReplaceAllString(text, "")
// 9. Strip blockquote markers
text = reBlockquote.ReplaceAllString(text, "")
// 10. Unwrap bold/italic markers, keeping inner text (order: *** before ** before *)
text = reBoldItalic3.ReplaceAllString(text, "$1")
text = reBoldItalic2.ReplaceAllString(text, "$1")
text = reBoldItalic1.ReplaceAllString(text, "$1")
// 11. Strip list markers
text = reListMarker.ReplaceAllString(text, "")
// 12. Collapse excessive newlines
text = reExcessiveNewlines.ReplaceAllString(text, "\n\n")
return strings.TrimSpace(text)
}
// getEnrichedPassage 合并Content、ImageInfo和GeneratedQuestions的文本内容
func getEnrichedPassage(ctx context.Context, result *types.SearchResult) string {
combinedText := cleanPassageForRerank(result.Content)
var enrichments []string
// 解析ImageInfo
if result.ImageInfo != "" {
var imageInfos []types.ImageInfo
err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos)
if err != nil {
pipelineWarn(ctx, "Rerank", "image_info_parse", map[string]interface{}{
"error": err.Error(),
})
} else {
// 提取所有图片的描述和OCR文本
for _, img := range imageInfos {
if img.Caption != "" {
enrichments = append(enrichments, img.Caption)
}
if img.OCRText != "" {
enrichments = append(enrichments, img.OCRText)
}
}
}
}
// 解析ChunkMetadata中的GeneratedQuestions
if len(result.ChunkMetadata) > 0 {
var docMeta types.DocumentChunkMetadata
err := json.Unmarshal(result.ChunkMetadata, &docMeta)
if err != nil {
pipelineWarn(ctx, "Rerank", "chunk_metadata_parse", map[string]interface{}{
"error": err.Error(),
})
} else if questionStrings := docMeta.GetQuestionStrings(); len(questionStrings) > 0 {
enrichments = append(enrichments, strings.Join(questionStrings, "; "))
}
}
if len(enrichments) == 0 {
return combinedText
}
// 组合内容和增强信息
if combinedText != "" {
combinedText += "\n\n"
}
combinedText += strings.Join(enrichments, "\n")
return combinedText
}
func logRerankInputScoreSample(ctx context.Context, results []*types.SearchResult) {
const maxLogRows = 8
limit := min(maxLogRows, len(results))
for i := 0; i < limit; i++ {
sr := results[i]
pipelineInfo(ctx, "Rerank", "input_score", map[string]interface{}{
"index": i,
"chunk_id": sr.ID,
"score": fmt.Sprintf("%.4f", sr.Score),
"match_type": sr.MatchType,
})
}
if len(results) > limit {
pipelineInfo(ctx, "Rerank", "input_score_summary", map[string]interface{}{
"total": len(results),
"logged": limit,
"truncated": len(results) - limit,
})
}
}
@@ -0,0 +1,124 @@
package chatpipeline
import (
"testing"
)
func TestCleanPassageForRerank(t *testing.T) {
tests := []struct {
name string
input string
expect string
}{
{
name: "plain text unchanged",
input: "这是一段普通的文本内容",
expect: "这是一段普通的文本内容",
},
{
name: "remove markdown images",
input: "前文 ![图片说明](https://example.com/img.png) 后文",
expect: "前文 后文",
},
{
name: "convert markdown links to text",
input: "请参考 [官方文档](https://docs.example.com) 了解详情",
expect: "请参考 官方文档 了解详情",
},
{
name: "remove standalone URLs",
input: "访问 https://example.com/path?q=1&b=2 获取更多信息",
expect: "访问 获取更多信息",
},
{
name: "remove code blocks",
input: "示例代码:\n```python\nprint('hello')\n```\n以上是示例",
expect: "示例代码:\n\n以上是示例",
},
{
name: "remove LaTeX blocks",
input: "公式如下 $$E=mc^2$$ 其中E是能量",
expect: "公式如下 其中E是能量",
},
{
name: "remove table separator rows and convert data rows",
input: "| 名称 | 值 |\n| --- | --- |\n| A | 1 |",
expect: "名称, 值\n\nA, 1",
},
{
name: "strip heading markers",
input: "## 第二章 概述\n### 2.1 背景",
expect: "第二章 概述\n2.1 背景",
},
{
name: "strip blockquote markers",
input: "> 这是一段引用\n> 第二行引用",
expect: "这是一段引用\n第二行引用",
},
{
name: "unwrap bold and italic",
input: "这是 **加粗** 和 *斜体* 以及 ***粗斜体*** 文本",
expect: "这是 加粗 和 斜体 以及 粗斜体 文本",
},
{
name: "strip list markers",
input: "- 项目一\n- 项目二\n1. 有序一\n2. 有序二",
expect: "项目一\n项目二\n有序一\n有序二",
},
{
name: "remove HTML tags",
input: "文本<br>换行<div class=\"test\">内容</div>结尾",
expect: "文本换行内容结尾",
},
{
name: "collapse excessive newlines",
input: "段落一\n\n\n\n\n段落二",
expect: "段落一\n\n段落二",
},
{
name: "combined real-world passage",
input: `## 产品介绍
这是一个 **重要的** 产品。详见 [产品页面](https://example.com/product)。
![产品截图](images/product.png)
> 用户评价:非常好用
- 功能一
- 功能二
` + "```json\n{\"key\": \"value\"}\n```",
expect: "产品介绍\n\n这是一个 重要的 产品。详见 产品页面。\n\n用户评价:非常好用\n\n功能一\n功能二",
},
{
name: "convert table data rows to plain text",
input: "| col1 | col2 | col3 |",
expect: "col1, col2, col3",
},
{
name: "multi-row table fully converted",
input: "| Header1 | Header2 |\n| --- | --- |\n| data1 | data2 |\n| data3 | data4 |",
expect: "Header1, Header2\n\ndata1, data2\ndata3, data4",
},
{
name: "table-only passage becomes empty after separator removal",
input: "| --- | --- |",
expect: "",
},
{
name: "whitespace-only after cleaning",
input: " \n\n ",
expect: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := cleanPassageForRerank(tt.input)
if got != tt.expect {
t.Errorf("cleanPassageForRerank():\ngot: %q\nexpect: %q", got, tt.expect)
}
})
}
}
@@ -0,0 +1,568 @@
package chatpipeline
import (
"context"
"fmt"
"strings"
"sync"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/searchutil"
"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
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
config *config.Config
webSearchService interfaces.WebSearchService
tenantService interfaces.TenantService
sessionService interfaces.SessionService
webSearchStateService interfaces.WebSearchStateService
}
func NewPluginSearch(eventManager *EventManager,
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
config *config.Config,
webSearchService interfaces.WebSearchService,
tenantService interfaces.TenantService,
sessionService interfaces.SessionService,
webSearchStateService interfaces.WebSearchStateService,
) *PluginSearch {
res := &PluginSearch{
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
chunkService: chunkService,
config: config,
webSearchService: webSearchService,
tenantService: tenantService,
sessionService: sessionService,
webSearchStateService: webSearchStateService,
}
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 {
// Check if we have search targets or web search enabled
hasKBTargets := len(chatManage.SearchTargets) > 0 || len(chatManage.KnowledgeBaseIDs) > 0 || len(chatManage.KnowledgeIDs) > 0
if !hasKBTargets && !chatManage.WebSearchEnabled {
pipelineError(ctx, "Search", "kb_not_found", map[string]interface{}{
"session_id": chatManage.SessionID,
})
return nil
}
pipelineInfo(ctx, "Search", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"rewrite_query": chatManage.RewriteQuery,
"search_targets": len(chatManage.SearchTargets),
"tenant_id": chatManage.TenantID,
"web_enabled": chatManage.WebSearchEnabled,
})
// Run KB search and web search concurrently
pipelineInfo(ctx, "Search", "plan", map[string]interface{}{
"search_targets": len(chatManage.SearchTargets),
"embedding_top_k": chatManage.EmbeddingTopK,
"vector_threshold": chatManage.VectorThreshold,
"keyword_threshold": chatManage.KeywordThreshold,
})
var wg sync.WaitGroup
var mu sync.Mutex
allResults := make([]*types.SearchResult, 0)
wg.Add(2)
// Goroutine 1: Knowledge base search using SearchTargets
go func() {
defer wg.Done()
kbResults := p.searchByTargets(ctx, chatManage)
if len(kbResults) > 0 {
mu.Lock()
allResults = append(allResults, kbResults...)
mu.Unlock()
}
}()
// Goroutine 2: Web search (if enabled)
go func() {
defer wg.Done()
webResults := p.searchWebIfEnabled(ctx, chatManage)
if len(webResults) > 0 {
mu.Lock()
allResults = append(allResults, webResults...)
mu.Unlock()
}
}()
wg.Wait()
chatManage.SearchResult = allResults
logSearchScoreSample(ctx, "result_score_before_normalize", chatManage.SearchResult)
// If recall is low, attempt query expansion with keyword-focused search
if chatManage.EnableQueryExpansion && len(chatManage.SearchResult) < max(1, chatManage.EmbeddingTopK) {
expResults := p.runQueryExpansion(ctx, chatManage)
if len(expResults) > 0 {
chatManage.SearchResult = append(chatManage.SearchResult, expResults...)
}
}
logSearchScoreSample(ctx, "final_score", chatManage.SearchResult)
// Return if we have results
if len(chatManage.SearchResult) != 0 {
pipelineInfo(ctx, "Search", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"result_count": len(chatManage.SearchResult),
})
return next()
}
pipelineWarn(ctx, "Search", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"result_count": 0,
})
return ErrSearchNothing
}
// getSearchResultFromHistory retrieves relevant knowledge references from chat history
func 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)
contentSig := make(map[string]string) // sig -> first chunk ID
var uniqueResults []*types.SearchResult
for _, r := range results {
// Only deduplicate by exact chunk ID — do NOT treat shared ParentChunkID
// as duplicates, because different child chunks of the same parent carry
// different content segments that may all be relevant.
if seen[r.ID] {
logger.Debugf(context.Background(), "Dedup: chunk %s removed due to duplicate ID", r.ID)
continue
}
sig := buildContentSignature(r.Content)
if sig != "" {
if firstChunk, exists := contentSig[sig]; exists {
logger.Debugf(context.Background(), "Dedup: chunk %s removed due to content signature (dup of %s, sig prefix: %.50s...)", r.ID, firstChunk, sig)
continue
}
contentSig[sig] = r.ID
}
seen[r.ID] = true
uniqueResults = append(uniqueResults, r)
}
return uniqueResults
}
func buildContentSignature(content string) string {
return searchutil.BuildContentSignature(content)
}
func logSearchScoreSample(ctx context.Context, action string, results []*types.SearchResult) {
const maxLogRows = 8
limit := min(maxLogRows, len(results))
for i := 0; i < limit; i++ {
r := results[i]
pipelineInfo(ctx, "Search", action, map[string]interface{}{
"index": i,
"chunk_id": r.ID,
"score": fmt.Sprintf("%.4f", r.Score),
"match_type": r.MatchType,
})
}
if len(results) > limit {
pipelineInfo(ctx, "Search", action+"_summary", map[string]interface{}{
"total": len(results),
"logged": limit,
"truncated": len(results) - limit,
})
}
}
// searchByTargets performs KB searches using pre-computed SearchTargets.
// Targets sharing the same underlying embedding model (identified by model
// name + endpoint, not just model ID) are grouped so the query embedding is
// computed once per model AND all full-KB targets in a group are combined into
// a single retrieval call, reducing both embedding API calls and DB round-trips.
func (p *PluginSearch) searchByTargets(
ctx context.Context,
chatManage *types.ChatManage,
) []*types.SearchResult {
if len(chatManage.SearchTargets) == 0 {
return nil
}
queryText := strings.TrimSpace(chatManage.RewriteQuery)
// Batch-fetch KB records to determine embedding model grouping.
// On failure, all targets fall into an empty-key group and HybridSearch
// computes the embedding per-KB (graceful degradation).
kbIDs := make([]string, 0, len(chatManage.SearchTargets))
for _, t := range chatManage.SearchTargets {
kbIDs = append(kbIDs, t.KnowledgeBaseID)
}
var kbList []*types.KnowledgeBase
kbMap := make(map[string]*types.KnowledgeBase)
if kbs, err := p.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, kbIDs); err == nil {
kbList = kbs
for _, kb := range kbs {
if kb != nil {
kbMap[kb.ID] = kb
}
}
} else {
pipelineWarn(ctx, "Search", "batch_kb_fetch_error", map[string]interface{}{
"error": err.Error(),
})
}
// Resolve actual model identities (name + endpoint) so that cross-tenant
// KBs backed by the same physical model share one embedding computation.
modelKeyMap := p.knowledgeBaseService.ResolveEmbeddingModelKeys(ctx, kbList)
groups := make(map[string][]*types.SearchTarget)
for _, t := range chatManage.SearchTargets {
key := modelKeyMap[t.KnowledgeBaseID] // empty string if unresolved
groups[key] = append(groups[key], t)
}
pipelineInfo(ctx, "Search", "embedding_groups", map[string]interface{}{
"total_targets": len(chatManage.SearchTargets),
"unique_models": len(groups),
})
var wg sync.WaitGroup
var mu sync.Mutex
var results []*types.SearchResult
for modelKey, targets := range groups {
wg.Add(1)
go func(modelKey string, targets []*types.SearchTarget) {
defer wg.Done()
// Compute embedding once for this model group.
var queryEmbedding []float32
if modelKey != "" {
emb, err := p.knowledgeBaseService.GetQueryEmbedding(ctx, targets[0].KnowledgeBaseID, queryText)
if err != nil {
pipelineWarn(ctx, "Search", "group_embed_error", map[string]interface{}{
"model_key": modelKey,
"kb_id": targets[0].KnowledgeBaseID,
"error": err.Error(),
})
} else {
queryEmbedding = emb
}
}
// Separate full-KB targets (can be combined into one retrieval)
// from specific-knowledge targets (need per-target direct loading).
var fullKBIDs []string
var knowledgeTargets []*types.SearchTarget
for _, t := range targets {
if t.Type == types.SearchTargetTypeKnowledgeBase {
fullKBIDs = append(fullKBIDs, t.KnowledgeBaseID)
} else {
knowledgeTargets = append(knowledgeTargets, t)
}
}
pipelineInfo(ctx, "Search", "group_plan", map[string]interface{}{
"model_key": modelKey,
"combined_kb_count": len(fullKBIDs),
"individual_targets": len(knowledgeTargets),
"vector_len": len(queryEmbedding),
})
var innerWg sync.WaitGroup
// Combined search: one HybridSearch call spanning all full-KB targets
if len(fullKBIDs) > 0 {
innerWg.Add(1)
go func() {
defer innerWg.Done()
params := types.SearchParams{
QueryText: queryText,
QueryEmbedding: queryEmbedding,
KnowledgeBaseIDs: fullKBIDs,
VectorThreshold: chatManage.VectorThreshold,
KeywordThreshold: chatManage.KeywordThreshold,
MatchCount: chatManage.EmbeddingTopK,
SkipContextEnrichment: true,
}
res, err := p.knowledgeBaseService.HybridSearch(ctx, fullKBIDs[0], params)
if err != nil {
pipelineWarn(ctx, "Search", "combined_kb_search_error", map[string]interface{}{
"kb_ids": fullKBIDs,
"error": err.Error(),
})
return
}
pipelineInfo(ctx, "Search", "combined_kb_result", map[string]interface{}{
"kb_ids": fullKBIDs,
"hit_count": len(res),
})
mu.Lock()
results = append(results, res...)
mu.Unlock()
}()
}
// Individual search: per-target handling for specific-knowledge targets
for _, target := range knowledgeTargets {
innerWg.Add(1)
go func(t *types.SearchTarget) {
defer innerWg.Done()
p.searchSingleTarget(ctx, chatManage, t, queryText, queryEmbedding, &mu, &results)
}(target)
}
innerWg.Wait()
}(modelKey, targets)
}
wg.Wait()
pipelineInfo(ctx, "Search", "kb_result_summary", map[string]interface{}{
"total_hits": len(results),
})
return results
}
// searchSingleTarget handles the search logic for a single SearchTarget
// with specific knowledge IDs, including direct chunk loading and HybridSearch.
func (p *PluginSearch) searchSingleTarget(
ctx context.Context,
chatManage *types.ChatManage,
t *types.SearchTarget,
queryText string,
queryEmbedding []float32,
mu *sync.Mutex,
results *[]*types.SearchResult,
) {
searchKnowledgeIDs := t.KnowledgeIDs
if t.Type == types.SearchTargetTypeKnowledge {
directResults, skippedIDs := p.tryDirectChunkLoading(ctx, chatManage.TenantID, t.KnowledgeIDs)
if len(directResults) > 0 {
for _, r := range directResults {
r.KnowledgeBaseID = t.KnowledgeBaseID
}
pipelineInfo(ctx, "Search", "direct_load", map[string]interface{}{
"kb_id": t.KnowledgeBaseID,
"loaded_count": len(directResults),
"skipped_ids": len(skippedIDs),
})
mu.Lock()
*results = append(*results, directResults...)
mu.Unlock()
}
if len(skippedIDs) == 0 && len(t.KnowledgeIDs) > 0 {
return
}
searchKnowledgeIDs = skippedIDs
}
if t.Type == types.SearchTargetTypeKnowledge && len(searchKnowledgeIDs) == 0 {
return
}
params := types.SearchParams{
QueryText: queryText,
QueryEmbedding: queryEmbedding,
VectorThreshold: chatManage.VectorThreshold,
KeywordThreshold: chatManage.KeywordThreshold,
MatchCount: chatManage.EmbeddingTopK,
SkipContextEnrichment: true,
}
if t.Type == types.SearchTargetTypeKnowledge {
params.KnowledgeIDs = searchKnowledgeIDs
}
res, err := p.knowledgeBaseService.HybridSearch(ctx, t.KnowledgeBaseID, params)
if err != nil {
pipelineWarn(ctx, "Search", "kb_search_error", map[string]interface{}{
"kb_id": t.KnowledgeBaseID,
"target_type": t.Type,
"query": params.QueryText,
"error": err.Error(),
})
return
}
pipelineInfo(ctx, "Search", "kb_result", map[string]interface{}{
"kb_id": t.KnowledgeBaseID,
"target_type": t.Type,
"hit_count": len(res),
})
mu.Lock()
*results = append(*results, res...)
mu.Unlock()
}
// tryDirectChunkLoading attempts to load chunks for given knowledge IDs directly
// Returns loaded results and a list of knowledge IDs that were skipped (e.g. due to size limits)
func (p *PluginSearch) tryDirectChunkLoading(ctx context.Context, tenantID uint64, knowledgeIDs []string) ([]*types.SearchResult, []string) {
if len(knowledgeIDs) == 0 {
return nil, nil
}
// Limit direct loading to avoid OOM or context overflow
// 50 chunks * ~500 chars/chunk ~= 25k chars
const maxTotalChunks = 50
var allChunks []*types.Chunk
var skippedIDs []string
loadedKnowledgeIDs := make(map[string]bool)
for _, kid := range knowledgeIDs {
// Optimization: Check chunk count first if possible?
chunks, err := p.chunkService.ListChunksByKnowledgeID(ctx, kid)
if err != nil {
logger.Warnf(ctx, "DirectLoad: Failed to list chunks for knowledge %s: %v", kid, err)
skippedIDs = append(skippedIDs, kid)
continue
}
if len(allChunks)+len(chunks) > maxTotalChunks {
logger.Infof(ctx, "DirectLoad: Skipped knowledge %s due to size limit (%d + %d > %d)",
kid, len(allChunks), len(chunks), maxTotalChunks)
skippedIDs = append(skippedIDs, kid)
continue
}
allChunks = append(allChunks, chunks...)
loadedKnowledgeIDs[kid] = true
}
if len(allChunks) == 0 {
return nil, skippedIDs
}
// Fetch Knowledge metadata
var uniqueKIDs []string
for kid := range loadedKnowledgeIDs {
uniqueKIDs = append(uniqueKIDs, kid)
}
knowledgeMap := make(map[string]*types.Knowledge)
if len(uniqueKIDs) > 0 {
knowledges, err := p.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, uniqueKIDs)
if err != nil {
logger.Warnf(ctx, "DirectLoad: Failed to fetch knowledge batch: %v", err)
// Continue without metadata
} else {
for _, k := range knowledges {
knowledgeMap[k.ID] = k
}
}
}
var results []*types.SearchResult
for _, chunk := range allChunks {
res := &types.SearchResult{
ID: chunk.ID,
Content: chunk.Content,
Score: 1.0, // Maximum score for direct matches
KnowledgeID: chunk.KnowledgeID,
ChunkIndex: chunk.ChunkIndex,
MatchType: types.MatchTypeDirectLoad,
ChunkType: string(chunk.ChunkType),
ParentChunkID: chunk.ParentChunkID,
ImageInfo: chunk.ImageInfo,
ChunkMetadata: chunk.Metadata,
StartAt: chunk.StartAt,
EndAt: chunk.EndAt,
}
if k, ok := knowledgeMap[chunk.KnowledgeID]; ok {
res.KnowledgeTitle = k.Title
res.KnowledgeFilename = k.FileName
res.KnowledgeSource = k.Source
res.Metadata = k.GetMetadata()
}
results = append(results, res)
}
return results, skippedIDs
}
// searchWebIfEnabled executes web search when enabled and returns converted results
func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult {
if !chatManage.WebSearchEnabled || p.webSearchService == nil || p.tenantService == nil {
return nil
}
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil || tenant.WebSearchConfig == nil || tenant.WebSearchConfig.Provider == "" {
pipelineWarn(ctx, "Search", "web_config_missing", map[string]interface{}{
"tenant_id": chatManage.TenantID,
})
return nil
}
pipelineInfo(ctx, "Search", "web_request", map[string]interface{}{
"tenant_id": chatManage.TenantID,
"provider": tenant.WebSearchConfig.Provider,
})
webResults, err := p.webSearchService.Search(ctx, tenant.WebSearchConfig, chatManage.RewriteQuery)
if err != nil {
pipelineWarn(ctx, "Search", "web_search_error", map[string]interface{}{
"tenant_id": chatManage.TenantID,
"error": err.Error(),
})
return nil
}
// Build questions using RewriteQuery only
questions := []string{strings.TrimSpace(chatManage.RewriteQuery)}
// Load session-scoped temp KB state from Redis using WebSearchStateRepository
tempKBID, seen, ids := p.webSearchStateService.GetWebSearchTempKBState(ctx, chatManage.SessionID)
compressed, kbID, newSeen, newIDs, err := p.webSearchService.CompressWithRAG(
ctx, chatManage.SessionID, tempKBID, questions, webResults, tenant.WebSearchConfig,
p.knowledgeBaseService, p.knowledgeService, seen, ids,
)
if err != nil {
pipelineWarn(ctx, "Search", "web_compress_error", map[string]interface{}{
"error": err.Error(),
})
} else {
webResults = compressed
// Persist temp KB state back into Redis using WebSearchStateRepository
p.webSearchStateService.SaveWebSearchTempKBState(ctx, chatManage.SessionID, kbID, newSeen, newIDs)
}
res := searchutil.ConvertWebSearchResults(webResults)
pipelineInfo(ctx, "Search", "web_hits", map[string]interface{}{
"hit_count": len(res),
})
return res
}
@@ -0,0 +1,227 @@
package chatpipeline
import (
"context"
"sync"
"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 PluginSearchEntity struct {
graphRepo interfaces.RetrieveGraphRepository
chunkRepo interfaces.ChunkRepository
knowledgeRepo interfaces.KnowledgeRepository
}
// NewPluginSearchEntity creates a new plugin search entity
func NewPluginSearchEntity(
eventManager *EventManager,
graphRepository interfaces.RetrieveGraphRepository,
chunkRepository interfaces.ChunkRepository,
knowledgeRepository interfaces.KnowledgeRepository,
) *PluginSearchEntity {
res := &PluginSearchEntity{
graphRepo: graphRepository,
chunkRepo: chunkRepository,
knowledgeRepo: knowledgeRepository,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the list of event types this plugin responds to
func (p *PluginSearchEntity) ActivationEvents() []types.EventType {
return []types.EventType{types.ENTITY_SEARCH}
}
// OnEvent processes triggered events
func (p *PluginSearchEntity) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
entity := chatManage.Entity
if len(entity) == 0 {
logger.Infof(ctx, "No entity found")
return next()
}
// Use EntityKBIDs (knowledge bases with ExtractConfig enabled)
knowledgeBaseIDs := chatManage.EntityKBIDs
// Use EntityKnowledge (KnowledgeID -> KnowledgeBaseID mapping for graph-enabled files)
entityKnowledge := chatManage.EntityKnowledge
if len(knowledgeBaseIDs) == 0 && len(entityKnowledge) == 0 {
logger.Warnf(ctx, "No knowledge base IDs or knowledge IDs with ExtractConfig enabled for entity search")
return next()
}
// Parallel search across multiple knowledge bases and individual files
var wg sync.WaitGroup
var mu sync.Mutex
var allNodes []*types.GraphNode
var allRelations []*types.GraphRelation
// If specific KnowledgeIDs are provided, search by individual files
if len(entityKnowledge) > 0 {
logger.Infof(ctx, "Searching entities across %d knowledge file(s)", len(entityKnowledge))
for knowledgeID, kbID := range entityKnowledge {
wg.Add(1)
go func(knowledgeBaseID, knowledgeID string) {
defer wg.Done()
graph, err := p.graphRepo.SearchNode(ctx, types.NameSpace{
KnowledgeBase: knowledgeBaseID,
Knowledge: knowledgeID,
}, entity)
if err != nil {
logger.Errorf(ctx, "Failed to search entity in Knowledge %s: %v", knowledgeID, err)
return
}
logger.Infof(
ctx,
"Knowledge %s entity search result count: %d nodes, %d relations",
knowledgeID,
len(graph.Node),
len(graph.Relation),
)
mu.Lock()
allNodes = append(allNodes, graph.Node...)
allRelations = append(allRelations, graph.Relation...)
mu.Unlock()
}(kbID, knowledgeID)
}
} else {
// Otherwise, search by knowledge base
logger.Infof(ctx, "Searching entities across %d knowledge base(s): %v", len(knowledgeBaseIDs), knowledgeBaseIDs)
for _, kbID := range knowledgeBaseIDs {
wg.Add(1)
go func(knowledgeBaseID string) {
defer wg.Done()
graph, err := p.graphRepo.SearchNode(ctx, types.NameSpace{KnowledgeBase: knowledgeBaseID}, entity)
if err != nil {
logger.Errorf(ctx, "Failed to search entity in KB %s: %v", knowledgeBaseID, err)
return
}
logger.Infof(
ctx,
"KB %s entity search result count: %d nodes, %d relations",
knowledgeBaseID,
len(graph.Node),
len(graph.Relation),
)
mu.Lock()
allNodes = append(allNodes, graph.Node...)
allRelations = append(allRelations, graph.Relation...)
mu.Unlock()
}(kbID)
}
}
wg.Wait()
// Merge graph data
chatManage.GraphResult = &types.GraphData{
Node: allNodes,
Relation: allRelations,
}
logger.Infof(ctx, "Total entity search result: %d nodes, %d relations", len(allNodes), len(allRelations))
chunkIDs := filterSeenChunk(ctx, chatManage.GraphResult, chatManage.SearchResult)
if len(chunkIDs) == 0 {
logger.Infof(ctx, "No new chunk found")
return next()
}
chunks, err := p.chunkRepo.ListChunksByID(ctx, types.MustTenantIDFromContext(ctx), chunkIDs)
if err != nil {
logger.Errorf(ctx, "Failed to list chunks, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
knowledgeIDs := []string{}
for _, chunk := range chunks {
knowledgeIDs = append(knowledgeIDs, chunk.KnowledgeID)
}
knowledges, err := p.knowledgeRepo.GetKnowledgeBatch(
ctx,
types.MustTenantIDFromContext(ctx),
knowledgeIDs,
)
if err != nil {
logger.Errorf(ctx, "Failed to list knowledge, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
knowledgeMap := map[string]*types.Knowledge{}
for _, knowledge := range knowledges {
knowledgeMap[knowledge.ID] = knowledge
}
for _, chunk := range chunks {
searchResult := chunk2SearchResult(chunk, knowledgeMap[chunk.KnowledgeID])
chatManage.SearchResult = append(chatManage.SearchResult, searchResult)
}
// remove duplicate results
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
if len(chatManage.SearchResult) == 0 {
logger.Infof(ctx, "No new search result, session_id: %s", chatManage.SessionID)
return ErrSearchNothing
}
logger.Infof(
ctx,
"search entity result count: %d, session_id: %s",
len(chatManage.SearchResult),
chatManage.SessionID,
)
return next()
}
// filterSeenChunk filters seen chunks from the graph
func filterSeenChunk(ctx context.Context, graph *types.GraphData, searchResult []*types.SearchResult) []string {
seen := map[string]bool{}
for _, chunk := range searchResult {
seen[chunk.ID] = true
}
logger.Infof(ctx, "filterSeenChunk: seen count: %d", len(seen))
chunkIDs := []string{}
for _, node := range graph.Node {
for _, chunkID := range node.Chunks {
if seen[chunkID] {
continue
}
seen[chunkID] = true
chunkIDs = append(chunkIDs, chunkID)
}
}
logger.Infof(ctx, "filterSeenChunk: new chunkIDs count: %d", len(chunkIDs))
return chunkIDs
}
// chunk2SearchResult converts a chunk to a search result
func chunk2SearchResult(chunk *types.Chunk, knowledge *types.Knowledge) *types.SearchResult {
return &types.SearchResult{
ID: chunk.ID,
Content: chunk.Content,
KnowledgeID: chunk.KnowledgeID,
ChunkIndex: chunk.ChunkIndex,
KnowledgeTitle: knowledge.Title,
StartAt: chunk.StartAt,
EndAt: chunk.EndAt,
Seq: chunk.ChunkIndex,
Score: 1.0,
MatchType: types.MatchTypeGraph,
Metadata: knowledge.GetMetadata(),
ChunkType: string(chunk.ChunkType),
ParentChunkID: chunk.ParentChunkID,
ImageInfo: chunk.ImageInfo,
KnowledgeFilename: knowledge.FileName,
KnowledgeSource: knowledge.Source,
ChunkMetadata: chunk.Metadata,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
}
}
@@ -0,0 +1,177 @@
package chatpipeline
import (
"context"
"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"
)
// PluginSearchParallel implements parallel search functionality combining chunk search and entity search
type PluginSearchParallel struct {
// Chunk search dependencies
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
config *config.Config
webSearchService interfaces.WebSearchService
tenantService interfaces.TenantService
sessionService interfaces.SessionService
// Entity search dependencies
graphRepo interfaces.RetrieveGraphRepository
chunkRepo interfaces.ChunkRepository
knowledgeRepo interfaces.KnowledgeRepository
// Internal plugins
searchPlugin *PluginSearch
searchEntityPlugin *PluginSearchEntity
}
// NewPluginSearchParallel creates a new parallel search plugin
func NewPluginSearchParallel(
eventManager *EventManager,
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
config *config.Config,
webSearchService interfaces.WebSearchService,
tenantService interfaces.TenantService,
sessionService interfaces.SessionService,
webSearchStateService interfaces.WebSearchStateService,
graphRepository interfaces.RetrieveGraphRepository,
chunkRepository interfaces.ChunkRepository,
knowledgeRepository interfaces.KnowledgeRepository,
) *PluginSearchParallel {
// Create internal plugins without registering them
searchPlugin := &PluginSearch{
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
chunkService: chunkService,
config: config,
webSearchService: webSearchService,
tenantService: tenantService,
sessionService: sessionService,
webSearchStateService: webSearchStateService,
}
searchEntityPlugin := &PluginSearchEntity{
graphRepo: graphRepository,
chunkRepo: chunkRepository,
knowledgeRepo: knowledgeRepository,
}
res := &PluginSearchParallel{
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
config: config,
webSearchService: webSearchService,
tenantService: tenantService,
sessionService: sessionService,
graphRepo: graphRepository,
chunkRepo: chunkRepository,
knowledgeRepo: knowledgeRepository,
searchPlugin: searchPlugin,
searchEntityPlugin: searchEntityPlugin,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginSearchParallel) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_SEARCH_PARALLEL}
}
// OnEvent handles parallel search events - runs chunk search and entity search concurrently
func (p *PluginSearchParallel) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Intent-based skip: query-understand step determined KB retrieval is unnecessary
if !chatManage.NeedsRetrieval() {
pipelineInfo(ctx, "SearchParallel", "skip", map[string]interface{}{
"session_id": chatManage.SessionID,
"reason": "intent_no_search",
})
return next()
}
pipelineInfo(ctx, "SearchParallel", "start", map[string]interface{}{
"session_id": chatManage.SessionID,
"has_entities": len(chatManage.Entity) > 0,
"rewrite_query": chatManage.RewriteQuery,
})
// Deep-copy to avoid concurrent read/write on shared slice fields
chunkCM := chatManage.Clone()
chunkCM.SearchResult = nil
entityCM := chatManage.Clone()
entityCM.SearchResult = nil
noop := func() *PluginError { return nil }
tasks := []ParallelTask{
{
Name: "chunk_search",
Run: func() *PluginError {
err := p.searchPlugin.OnEvent(ctx, types.CHUNK_SEARCH, chunkCM, noop)
pipelineInfo(ctx, "SearchParallel", "chunk_search_done", map[string]interface{}{
"result_count": len(chunkCM.SearchResult),
"has_error": err != nil && err != ErrSearchNothing,
})
if err == ErrSearchNothing {
return nil
}
return err
},
},
{
Name: "entity_search",
Run: func() *PluginError {
if len(chatManage.Entity) == 0 {
pipelineInfo(ctx, "SearchParallel", "entity_search_skip", map[string]interface{}{
"reason": "no_entities",
})
return nil
}
err := p.searchEntityPlugin.OnEvent(ctx, types.ENTITY_SEARCH, entityCM, noop)
pipelineInfo(ctx, "SearchParallel", "entity_search_done", map[string]interface{}{
"result_count": len(entityCM.SearchResult),
"has_error": err != nil && err != ErrSearchNothing,
})
if err == ErrSearchNothing {
return nil
}
return err
},
},
}
errs := RunParallel(tasks...)
// Merge results from both searches
chatManage.SearchResult = append(chunkCM.SearchResult, entityCM.SearchResult...)
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
for name, err := range errs {
logger.Warnf(ctx, "[SearchParallel] %s error: %v", name, err.Err)
}
pipelineInfo(ctx, "SearchParallel", "complete", map[string]interface{}{
"session_id": chatManage.SessionID,
"chunk_results": len(chunkCM.SearchResult),
"entity_results": len(entityCM.SearchResult),
"total_results": len(chatManage.SearchResult),
"error_count": len(errs),
})
if len(chatManage.SearchResult) == 0 {
if err, ok := errs["chunk_search"]; ok {
return err
}
return ErrSearchNothing
}
return next()
}