init commit

This commit is contained in:
wizardchen
2025-08-05 15:08:07 +08:00
commit 56eb2bce33
282 changed files with 49077 additions and 0 deletions
+127
View File
@@ -0,0 +1,127 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// chunkRepository implements the ChunkRepository interface
type chunkRepository struct {
db *gorm.DB
}
// NewChunkRepository creates a new chunk repository
func NewChunkRepository(db *gorm.DB) interfaces.ChunkRepository {
return &chunkRepository{db: db}
}
// CreateChunks creates multiple chunks in batches
func (r *chunkRepository) CreateChunks(ctx context.Context, chunks []*types.Chunk) error {
return r.db.WithContext(ctx).CreateInBatches(chunks, 100).Error
}
// GetChunkByID retrieves a chunk by its ID and tenant ID
func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint, id string) (*types.Chunk, error) {
var chunk types.Chunk
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).First(&chunk).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("chunk not found")
}
return nil, err
}
return &chunk, nil
}
// ListChunksByID retrieves multiple chunks by their IDs
func (r *chunkRepository) ListChunksByID(
ctx context.Context, tenantID uint, ids []string,
) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id IN ?", tenantID, ids).
Find(&chunks).Error; err != nil {
return nil, err
}
return chunks, nil
}
// ListChunksByKnowledgeID lists all chunks for a knowledge ID
func (r *chunkRepository) ListChunksByKnowledgeID(
ctx context.Context, tenantID uint, knowledgeID string,
) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.WithContext(ctx).
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info").
Where("tenant_id = ? AND knowledge_id = ? and chunk_type = ?", tenantID, knowledgeID, "text").
Order("chunk_index ASC").
Find(&chunks).Error; err != nil {
return nil, err
}
return chunks, nil
}
// ListPagedChunksByKnowledgeID lists chunks for a knowledge ID with pagination
func (r *chunkRepository) ListPagedChunksByKnowledgeID(
ctx context.Context, tenantID uint, knowledgeID string, page *types.Pagination, chunk_type []types.ChunkType,
) ([]*types.Chunk, int64, error) {
var chunks []*types.Chunk
var total int64
// First query the total count
if err := r.db.WithContext(ctx).Model(&types.Chunk{}).
Where("tenant_id = ? AND knowledge_id = ?", tenantID, knowledgeID).
Count(&total).Error; err != nil {
return nil, 0, err
}
// Then query the paginated data
if err := r.db.WithContext(ctx).
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info").
Where("tenant_id = ? AND knowledge_id = ? and chunk_type in (?)", tenantID, knowledgeID, chunk_type).
Order("chunk_index ASC").
Offset(page.Offset()).
Limit(page.Limit()).
Find(&chunks).Error; err != nil {
return nil, 0, err
}
return chunks, total, nil
}
func (r *chunkRepository) ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND parent_chunk_id = ?", tenantID, parentID).
Find(&chunks).Error; err != nil {
return nil, err
}
return chunks, nil
}
// UpdateChunk updates a chunk
func (r *chunkRepository) UpdateChunk(ctx context.Context, chunk *types.Chunk) error {
return r.db.WithContext(ctx).Save(chunk).Error
}
// DeleteChunk deletes a chunk by its ID
func (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Chunk{}).Error
}
// DeleteChunksByKnowledgeID deletes all chunks for a knowledge ID
func (r *chunkRepository) DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) error {
return r.db.WithContext(ctx).Where(
"tenant_id = ? AND knowledge_id = ?", tenantID, knowledgeID,
).Delete(&types.Chunk{}).Error
}
// DeleteByKnowledgeList deletes all chunks for a knowledge list
func (r *chunkRepository) DeleteByKnowledgeList(ctx context.Context, tenantID uint, knowledgeIDs []string) error {
return r.db.WithContext(ctx).Where(
"tenant_id = ? AND knowledge_id in ?", tenantID, knowledgeIDs,
).Delete(&types.Chunk{}).Error
}
@@ -0,0 +1,187 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
var ErrKnowledgeNotFound = errors.New("knowledge not found")
// knowledgeRepository implements knowledge base and knowledge repository interface
type knowledgeRepository struct {
db *gorm.DB
}
// NewKnowledgeRepository creates a new knowledge repository
func NewKnowledgeRepository(db *gorm.DB) interfaces.KnowledgeRepository {
return &knowledgeRepository{db: db}
}
// CreateKnowledge creates knowledge
func (r *knowledgeRepository) CreateKnowledge(ctx context.Context, knowledge *types.Knowledge) error {
err := r.db.WithContext(ctx).Create(knowledge).Error
return err
}
// GetKnowledgeByID gets knowledge
func (r *knowledgeRepository) GetKnowledgeByID(ctx context.Context, tenantID uint, id string) (*types.Knowledge, error) {
var knowledge types.Knowledge
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).First(&knowledge).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrKnowledgeNotFound
}
return nil, err
}
return &knowledge, nil
}
// ListKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base
func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID(
ctx context.Context, tenantID uint, kbID string,
) ([]*types.Knowledge, error) {
var knowledges []*types.Knowledge
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
Order("created_at DESC").Find(&knowledges).Error; err != nil {
return nil, err
}
return knowledges, nil
}
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination
func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
ctx context.Context,
tenantID uint,
kbID string,
page *types.Pagination,
) ([]*types.Knowledge, int64, error) {
var knowledges []*types.Knowledge
var total int64
// Query total count first
if err := r.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
Count(&total).Error; err != nil {
return nil, 0, err
}
// Then query paginated data
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
Order("created_at DESC").
Offset(page.Offset()).
Limit(page.Limit()).
Find(&knowledges).Error; err != nil {
return nil, 0, err
}
return knowledges, total, nil
}
// UpdateKnowledge updates knowledge
func (r *knowledgeRepository) UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error {
err := r.db.WithContext(ctx).Save(knowledge).Error
return err
}
// DeleteKnowledge deletes knowledge
func (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Knowledge{}).Error
}
// DeleteKnowledge deletes knowledge
func (r *knowledgeRepository) DeleteKnowledgeList(ctx context.Context, tenantID uint, ids []string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id in ?", tenantID, ids).Delete(&types.Knowledge{}).Error
}
// GetKnowledgeBatch gets knowledge in batch
func (r *knowledgeRepository) GetKnowledgeBatch(
ctx context.Context, tenantID uint, ids []string,
) ([]*types.Knowledge, error) {
var knowledge []*types.Knowledge
if err := r.db.WithContext(ctx).Debug().
Where("tenant_id = ? AND id IN ?", tenantID, ids).
Find(&knowledge).Error; err != nil {
return nil, err
}
return knowledge, nil
}
// CheckKnowledgeExists checks if knowledge already exists
func (r *knowledgeRepository) CheckKnowledgeExists(
ctx context.Context,
tenantID uint,
kbID string,
params *types.KnowledgeCheckParams,
) (bool, *types.Knowledge, error) {
query := r.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("tenant_id = ? AND knowledge_base_id = ? AND enable_status = ?", tenantID, kbID, "enabled")
if params.Type == "file" {
// If file hash exists, prioritize exact match using hash
if params.FileHash != "" {
var knowledge types.Knowledge
err := query.Where("file_hash = ?", params.FileHash).First(&knowledge).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, nil, nil
}
return false, nil, err
}
return true, &knowledge, nil
}
// If no hash or hash doesn't match, use filename and size
if params.FileName != "" && params.FileSize > 0 {
var knowledge types.Knowledge
err := query.Where(
"file_name = ? AND file_size = ?",
params.FileName, params.FileSize,
).First(&knowledge).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, nil, nil
}
return false, nil, err
}
return true, &knowledge, nil
}
} else if params.Type == "url" {
if params.URL != "" {
var knowledge types.Knowledge
err := query.Where("type = 'url' AND source = ?", params.URL).First(&knowledge).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, nil, nil
}
return false, nil, err
}
return true, &knowledge, nil
}
}
// No valid parameters, default to not existing
return false, nil, nil
}
func (r *knowledgeRepository) AminusB(
ctx context.Context,
Atenant uint, A string,
Btenant uint, B string,
) ([]string, error) {
knowledgeIDs := []string{}
subQuery := r.db.Model(&types.Knowledge{}).
Where("tenant_id = ? AND knowledge_base_id = ?", Btenant, B).Select("file_hash")
err := r.db.Model(&types.Knowledge{}).
Where("tenant_id = ? AND knowledge_base_id = ?", Atenant, A).
Where("file_hash NOT IN (?)", subQuery).
Pluck("id", &knowledgeIDs).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return knowledgeIDs, nil
}
return knowledgeIDs, err
}
@@ -0,0 +1,70 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
var ErrKnowledgeBaseNotFound = errors.New("knowledge base not found")
// knowledgeBaseRepository implements the KnowledgeBaseRepository interface
type knowledgeBaseRepository struct {
db *gorm.DB
}
// NewKnowledgeBaseRepository creates a new knowledge base repository
func NewKnowledgeBaseRepository(db *gorm.DB) interfaces.KnowledgeBaseRepository {
return &knowledgeBaseRepository{db: db}
}
// CreateKnowledgeBase creates a new knowledge base
func (r *knowledgeBaseRepository) CreateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error {
return r.db.WithContext(ctx).Create(kb).Error
}
// GetKnowledgeBaseByID gets a knowledge base by id
func (r *knowledgeBaseRepository) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
var kb types.KnowledgeBase
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&kb).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrKnowledgeBaseNotFound
}
return nil, err
}
return &kb, nil
}
// ListKnowledgeBases lists all knowledge bases
func (r *knowledgeBaseRepository) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
var kbs []*types.KnowledgeBase
if err := r.db.WithContext(ctx).Find(&kbs).Error; err != nil {
return nil, err
}
return kbs, nil
}
// ListKnowledgeBasesByTenantID lists all knowledge bases by tenant id
func (r *knowledgeBaseRepository) ListKnowledgeBasesByTenantID(
ctx context.Context, tenantID uint,
) ([]*types.KnowledgeBase, error) {
var kbs []*types.KnowledgeBase
if err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).
Order("created_at DESC").Find(&kbs).Error; err != nil {
return nil, err
}
return kbs, nil
}
// UpdateKnowledgeBase updates a knowledge base
func (r *knowledgeBaseRepository) UpdateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error {
return r.db.WithContext(ctx).Save(kb).Error
}
// DeleteKnowledgeBase deletes a knowledge base
func (r *knowledgeBaseRepository) DeleteKnowledgeBase(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.KnowledgeBase{}).Error
}
+153
View File
@@ -0,0 +1,153 @@
package repository
import (
"context"
"slices"
"time"
"gorm.io/gorm"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// messageRepository implements the message repository interface
type messageRepository struct {
db *gorm.DB
}
// NewMessageRepository creates a new message repository
func NewMessageRepository(db *gorm.DB) interfaces.MessageRepository {
return &messageRepository{
db: db,
}
}
// CreateMessage creates a new message
func (r *messageRepository) CreateMessage(
ctx context.Context, message *types.Message,
) (*types.Message, error) {
if err := r.db.WithContext(ctx).Create(message).Error; err != nil {
return nil, err
}
return message, nil
}
// GetMessage retrieves a message
func (r *messageRepository) GetMessage(
ctx context.Context, sessionID string, messageID string,
) (*types.Message, error) {
var message types.Message
if err := r.db.WithContext(ctx).Where(
"id = ? AND session_id = ?", messageID, sessionID,
).First(&message).Error; err != nil {
return nil, err
}
return &message, nil
}
// GetMessagesBySession retrieves all messages for a session with pagination
func (r *messageRepository) GetMessagesBySession(
ctx context.Context, sessionID string, page int, pageSize int,
) ([]*types.Message, error) {
var messages []*types.Message
if err := r.db.WithContext(ctx).Where("session_id = ?", sessionID).Order("created_at ASC").
Offset((page - 1) * pageSize).Limit(pageSize).Find(&messages).Error; err != nil {
return nil, err
}
return messages, nil
}
// GetRecentMessagesBySession retrieves recent messages for a session
func (r *messageRepository) GetRecentMessagesBySession(
ctx context.Context, sessionID string, limit int,
) ([]*types.Message, error) {
var messages []*types.Message
if err := r.db.WithContext(ctx).Where(
"session_id = ?", sessionID,
).Order("created_at DESC").Limit(limit).Find(&messages).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
slices.SortFunc(messages, func(a, b *types.Message) int {
cmp := a.CreatedAt.Compare(b.CreatedAt)
if cmp == 0 {
if a.Role == "user" { // User messages come first
return -1
}
return 1 // Assistant messages come last
}
return cmp
})
return messages, nil
}
// GetMessagesBySessionBeforeTime retrieves messages from a session created before a specific time
func (r *messageRepository) GetMessagesBySessionBeforeTime(
ctx context.Context, sessionID string, beforeTime time.Time, limit int,
) ([]*types.Message, error) {
var messages []*types.Message
if err := r.db.WithContext(ctx).Where(
"session_id = ? AND created_at < ?", sessionID, beforeTime,
).Order("created_at DESC").Limit(limit).Find(&messages).Error; err != nil {
return nil, err
}
slices.SortFunc(messages, func(a, b *types.Message) int {
cmp := a.CreatedAt.Compare(b.CreatedAt)
if cmp == 0 {
if a.Role == "user" { // User messages come first
return -1
}
return 1 // Assistant messages come last
}
return cmp
})
return messages, nil
}
// UpdateMessage updates an existing message
func (r *messageRepository) UpdateMessage(ctx context.Context, message *types.Message) error {
return r.db.WithContext(ctx).Model(&types.Message{}).Where(
"id = ? AND session_id = ?", message.ID, message.SessionID,
).Updates(message).Error
}
// DeleteMessage deletes a message
func (r *messageRepository) DeleteMessage(ctx context.Context, sessionID string, messageID string) error {
return r.db.WithContext(ctx).Where(
"id = ? AND session_id = ?", messageID, sessionID,
).Delete(&types.Message{}).Error
}
// GetFirstMessageOfUser retrieves the first message from a user in a session
func (r *messageRepository) GetFirstMessageOfUser(ctx context.Context, sessionID string) (*types.Message, error) {
var message types.Message
if err := r.db.WithContext(ctx).Where(
"session_id = ? and role = ?", sessionID, "user",
).Order("created_at ASC").First(&message).Error; err != nil {
return nil, err
}
return &message, nil
}
// GetMessageByRequestID retrieves a message by request ID
func (r *messageRepository) GetMessageByRequestID(
ctx context.Context, sessionID string, requestID string,
) (*types.Message, error) {
var message types.Message
result := r.db.WithContext(ctx).
Where("session_id = ? AND request_id = ?", sessionID, requestID).
First(&message)
if result.Error != nil {
if result.Error == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, result.Error
}
return &message, nil
}
+77
View File
@@ -0,0 +1,77 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// modelRepository implements the model repository interface
type modelRepository struct {
db *gorm.DB
}
// NewModelRepository creates a new model repository
func NewModelRepository(db *gorm.DB) interfaces.ModelRepository {
return &modelRepository{db: db}
}
// Create creates a new model
func (r *modelRepository) Create(ctx context.Context, m *types.Model) error {
return r.db.WithContext(ctx).Create(m).Error
}
// GetByID retrieves a model by ID
func (r *modelRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.Model, error) {
var m types.Model
if err := r.db.WithContext(ctx).Where("id = ?", id).Where(
"tenant_id = ? or tenant_id = 0", tenantID,
).First(&m).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &m, nil
}
// List lists models with optional filtering
func (r *modelRepository) List(
ctx context.Context, tenantID uint, modelType types.ModelType, source types.ModelSource,
) ([]*types.Model, error) {
var models []*types.Model
query := r.db.WithContext(ctx).Where(
"tenant_id = ? or tenant_id = 0", tenantID,
)
if modelType != "" {
query = query.Where("type = ?", modelType)
}
if source != "" {
query = query.Where("source = ?", source)
}
if err := query.Find(&models).Error; err != nil {
return nil, err
}
return models, nil
}
// Update updates a model
func (r *modelRepository) Update(ctx context.Context, m *types.Model) error {
return r.db.WithContext(ctx).Debug().Model(&types.Model{}).Where(
"id = ? AND tenant_id = ?", m.ID, m.TenantID,
).Updates(m).Error
}
// Delete deletes a model
func (r *modelRepository) Delete(ctx context.Context, tenantID uint, id string) error {
return r.db.WithContext(ctx).Where(
"id = ? AND tenant_id = ?", id, tenantID,
).Delete(&types.Model{}).Error
}
@@ -0,0 +1,62 @@
package elasticsearch
import (
"maps"
"slices"
"github.com/Tencent/WeKnora/internal/types"
)
// VectorEmbedding defines the Elasticsearch document structure for vector embeddings
type VectorEmbedding struct {
Content string `json:"content" gorm:"column:content;not null"` // Text content of the chunk
SourceID string `json:"source_id" gorm:"column:source_id;not null"` // ID of the source document
SourceType int `json:"source_type" gorm:"column:source_type;not null"` // Type of the source document
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"` // Unique ID of the text chunk
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
}
// VectorEmbeddingWithScore extends VectorEmbedding with similarity score
type VectorEmbeddingWithScore struct {
VectorEmbedding
Score float64 // Similarity score from vector search
}
// ToDBVectorEmbedding converts IndexInfo to Elasticsearch document format
func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string]interface{}) *VectorEmbedding {
vector := &VectorEmbedding{
Content: embedding.Content,
SourceID: embedding.SourceID,
SourceType: int(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
}
// Add embedding data if available in additionalParams
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
if embeddingMap, ok := additionalParams["embedding"].(map[string][]float32); ok {
vector.Embedding = embeddingMap[embedding.SourceID]
}
}
return vector
}
// FromDBVectorEmbeddingWithScore converts Elasticsearch document to IndexWithScore domain model
func FromDBVectorEmbeddingWithScore(id string,
embedding *VectorEmbeddingWithScore,
matchType types.MatchType,
) *types.IndexWithScore {
return &types.IndexWithScore{
ID: id,
SourceID: embedding.SourceID,
SourceType: types.SourceType(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
Content: embedding.Content,
Score: embedding.Score,
MatchType: matchType,
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,541 @@
package v8
import (
"context"
"encoding/json"
"fmt"
"os"
elasticsearchRetriever "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
typesLocal "github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
)
// elasticsearchRepository implements the RetrieveEngineRepository interface for Elasticsearch v8
type elasticsearchRepository struct {
client *elasticsearch.TypedClient // Elasticsearch client instance
index string // Name of the Elasticsearch index to use
}
// NewElasticsearchEngineRepository creates and initializes a new Elasticsearch v8 repository
// It sets up the index and returns a repository instance ready for use
func NewElasticsearchEngineRepository(client *elasticsearch.TypedClient,
config *config.Config,
) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[Elasticsearch] Initializing Elasticsearch v8 retriever engine repository")
// Get index name from environment variable or use default
indexName := os.Getenv("ELASTICSEARCH_INDEX")
if indexName == "" {
log.Warn("[Elasticsearch] ELASTICSEARCH_INDEX environment variable not set, using default index name")
indexName = "xwrag_default"
}
// Create repository instance and ensure index exists
res := &elasticsearchRepository{client: client, index: indexName}
if err := res.createIndexIfNotExists(context.Background()); err != nil {
log.Errorf("[Elasticsearch] Failed to create index: %v", err)
} else {
log.Info("[Elasticsearch] Successfully initialized repository")
}
return res
}
// EngineType returns the type of retriever engine (Elasticsearch)
func (e *elasticsearchRepository) EngineType() typesLocal.RetrieverEngineType {
return typesLocal.ElasticsearchRetrieverEngineType
}
// Support returns the retrieval types supported by this repository (Keywords and Vector)
func (e *elasticsearchRepository) Support() []typesLocal.RetrieverType {
return []typesLocal.RetrieverType{typesLocal.KeywordsRetrieverType, typesLocal.VectorRetrieverType}
}
// calculateStorageSize estimates the storage size in bytes for a single index document
func (e *elasticsearchRepository) calculateStorageSize(embedding *elasticsearchRetriever.VectorEmbedding) int64 {
// 1. Content text size
contentSizeBytes := int64(len(embedding.Content))
// 2. Vector embedding size
var vectorSizeBytes int64 = 0
if embedding.Embedding != nil {
// 4 bytes per dimension (full precision float)
vectorSizeBytes = int64(len(embedding.Embedding) * 4)
}
// 3. Metadata size (IDs, timestamps, and other fixed overhead)
metadataSizeBytes := int64(250) // Approximately 250 bytes of metadata
// 4. Index overhead (Elasticsearch index expansion factor ~1.5)
indexOverheadBytes := (contentSizeBytes + vectorSizeBytes) * 5 / 10
// Total size in bytes
totalSizeBytes := contentSizeBytes + vectorSizeBytes + metadataSizeBytes + indexOverheadBytes
return totalSizeBytes
}
// EstimateStorageSize calculates the estimated storage size for a list of indices
// Returns the total size in bytes
func (e *elasticsearchRepository) EstimateStorageSize(ctx context.Context,
indexInfoList []*typesLocal.IndexInfo, params map[string]any,
) int64 {
var totalStorageSize int64 = 0
for _, embedding := range indexInfoList {
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, params)
totalStorageSize += e.calculateStorageSize(embeddingDB)
}
logger.GetLogger(ctx).Infof(
"[Elasticsearch] Storage size for %d indices: %d bytes", len(indexInfoList), totalStorageSize,
)
return totalStorageSize
}
// Save stores a single index document in Elasticsearch
// Returns an error if the operation fails
func (e *elasticsearchRepository) Save(ctx context.Context,
embedding *typesLocal.IndexInfo,
additionalParams map[string]any,
) error {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Saving index for chunk ID: %s", embedding.ChunkID)
// Convert to database format
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, additionalParams)
if len(embeddingDB.Embedding) == 0 {
err := fmt.Errorf("empty embedding vector for chunk ID: %s", embedding.ChunkID)
log.Errorf("[Elasticsearch] %v", err)
return err
}
// Index the document
resp, err := e.client.Index(e.index).Request(embeddingDB).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to save index: %v", err)
return err
}
log.Infof("[Elasticsearch] Successfully saved index for chunk ID: %s, document ID: %s", embedding.ChunkID, resp.Id_)
return nil
}
// BatchSave stores multiple index documents in Elasticsearch using bulk API
// Returns an error if the operation fails
func (e *elasticsearchRepository) BatchSave(ctx context.Context,
embeddingList []*typesLocal.IndexInfo, additionalParams map[string]any,
) error {
log := logger.GetLogger(ctx)
if len(embeddingList) == 0 {
log.Warn("[Elasticsearch] Empty list provided to BatchSave, skipping")
return nil
}
log.Infof("[Elasticsearch] Batch saving %d indices", len(embeddingList))
indexRequest := e.client.Bulk().Index(e.index)
// Add each document to the bulk request
for _, embedding := range embeddingList {
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, additionalParams)
err := indexRequest.CreateOp(types.CreateOperation{Index_: &e.index}, embeddingDB)
if err != nil {
log.Errorf("[Elasticsearch] Failed to create bulk operation: %v", err)
return fmt.Errorf("failed to create op: %w", err)
}
log.Debugf("[Elasticsearch] Added chunk ID %s to bulk request", embedding.ChunkID)
}
// Execute the bulk request
_, err := indexRequest.Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to execute bulk operation: %v", err)
return fmt.Errorf("failed to do bulk: %w", err)
}
log.Infof("[Elasticsearch] Successfully batch saved %d indices", len(embeddingList))
return nil
}
// DeleteByChunkIDList removes documents from the index based on chunk IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int) error {
log := logger.GetLogger(ctx)
if len(chunkIDList) == 0 {
log.Warn("[Elasticsearch] Empty chunk ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by chunk IDs, count: %d", len(chunkIDList))
// Use DeleteByQuery to delete all documents matching the chunk IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{"chunk_id.keyword": chunkIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by chunk IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by chunk IDs")
return nil
}
// DeleteByKnowledgeIDList removes documents from the index based on knowledge IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteByKnowledgeIDList(ctx context.Context,
knowledgeIDList []string, dimension int,
) error {
log := logger.GetLogger(ctx)
if len(knowledgeIDList) == 0 {
log.Warn("[Elasticsearch] Empty knowledge ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by knowledge IDs, count: %d", len(knowledgeIDList))
// Use DeleteByQuery to delete all documents matching the knowledge IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{"knowledge_id.keyword": knowledgeIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by knowledge IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by knowledge IDs")
return nil
}
// getBaseConds creates the base query conditions for retrieval operations
// Returns a slice of Query objects with must and must_not conditions
func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams) []types.Query {
must := []types.Query{}
if len(params.KnowledgeBaseIDs) > 0 {
must = append(must, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
"knowledge_base_id.keyword": params.KnowledgeBaseIDs,
},
}})
}
mustNot := make([]types.Query, 0)
if len(params.ExcludeKnowledgeIDs) > 0 {
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{"knowledge_id.keyword": params.ExcludeKnowledgeIDs},
}})
}
if len(params.ExcludeChunkIDs) > 0 {
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{"chunk_id.keyword": params.ExcludeChunkIDs},
}})
}
return []types.Query{{Bool: &types.BoolQuery{Must: must, MustNot: mustNot}}}
}
// createIndexIfNotExists checks if the specified index exists and creates it if not
// Returns an error if the operation fails
func (e *elasticsearchRepository) createIndexIfNotExists(ctx context.Context) error {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Checking if index exists: %s", e.index)
// Check if index exists
exists, err := e.client.Indices.Exists(e.index).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to check if index exists: %v", err)
return err
}
if exists {
log.Debugf("[Elasticsearch] Index already exists: %s", e.index)
return nil
}
// Create index if it doesn't exist
log.Infof("[Elasticsearch] Creating index: %s", e.index)
_, err = e.client.Indices.Create(e.index).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to create index: %v", err)
return err
}
log.Infof("[Elasticsearch] Index created successfully: %s", e.index)
return nil
}
// Retrieve dispatches the retrieval operation to the appropriate method based on retriever type
// Returns a slice of RetrieveResult and an error if the operation fails
func (e *elasticsearchRepository) Retrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Processing retrieval request of type: %s", params.RetrieverType)
// Route to appropriate retrieval method
switch params.RetrieverType {
case typesLocal.VectorRetrieverType:
return e.VectorRetrieve(ctx, params)
case typesLocal.KeywordsRetrieverType:
return e.KeywordsRetrieve(ctx, params)
}
err := fmt.Errorf("invalid retriever type: %v", params.RetrieverType)
log.Errorf("[Elasticsearch] %v", err)
return nil, err
}
// VectorRetrieve performs vector similarity search using cosine similarity
// Returns a slice of RetrieveResult containing matching documents
func (e *elasticsearchRepository) VectorRetrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Infof("[Elasticsearch] Vector retrieval: dim=%d, topK=%d, threshold=%.4f",
len(params.Embedding), params.TopK, params.Threshold)
filter := e.getBaseConds(params)
// Build script scoring query with cosine similarity
queryVectorJSON, err := json.Marshal(params.Embedding)
if err != nil {
log.Errorf("[Elasticsearch] Failed to marshal query vector: %v", err)
return nil, fmt.Errorf("failed to marshal query embedding: %w", err)
}
scoreSource := "cosineSimilarity(params.query_vector, 'embedding')"
minScore := float32(params.Threshold)
scriptScore := &types.ScriptScoreQuery{
Query: types.Query{Bool: &types.BoolQuery{Filter: filter}},
Script: types.Script{
Source: &scoreSource,
Params: map[string]json.RawMessage{
"query_vector": json.RawMessage(queryVectorJSON),
},
},
MinScore: &minScore,
}
log.Debugf("[Elasticsearch] Executing vector search in index: %s", e.index)
// Execute search with minimum score threshold
response, err := e.client.Search().Index(e.index).Request(&search.Request{
Query: &types.Query{ScriptScore: scriptScore},
Size: &params.TopK,
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Vector search failed: %v", err)
return nil, err
}
// Process search results
var results []*typesLocal.IndexWithScore
for _, hit := range response.Hits.Hits {
var embedding *elasticsearchRetriever.VectorEmbeddingWithScore
if err := json.Unmarshal(hit.Source_, &embedding); err != nil {
log.Errorf("[Elasticsearch] Failed to unmarshal search result: %v", err)
return nil, err
}
embedding.Score = float64(*hit.Score_)
results = append(results,
elasticsearchRetriever.FromDBVectorEmbeddingWithScore(*hit.Id_, embedding, typesLocal.MatchTypeEmbedding))
}
if len(results) == 0 {
log.Warnf("[Elasticsearch] No vector matches found that meet threshold %.4f", params.Threshold)
} else {
log.Infof("[Elasticsearch] Vector retrieval found %d results", len(results))
log.Debugf("[Elasticsearch] Top result score: %.4f", results[0].Score)
}
return []*typesLocal.RetrieveResult{
{
Results: results,
RetrieverEngineType: typesLocal.ElasticsearchRetrieverEngineType,
RetrieverType: typesLocal.VectorRetrieverType,
Error: nil,
},
}, nil
}
// KeywordsRetrieve performs keyword-based search in document content
// Returns a slice of RetrieveResult containing matching documents
func (e *elasticsearchRepository) KeywordsRetrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Infof("[Elasticsearch] Performing keywords retrieval with query: %s, topK: %d", params.Query, params.TopK)
filter := e.getBaseConds(params)
// Build must conditions for content matching
must := []types.Query{
{Match: map[string]types.MatchQuery{"content": {Query: params.Query}}},
}
log.Debugf("[Elasticsearch] Executing keyword search in index: %s", e.index)
response, err := e.client.Search().Index(e.index).Request(&search.Request{
Query: &types.Query{Bool: &types.BoolQuery{Filter: filter, Must: must}},
Size: &params.TopK,
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Keywords search failed: %v", err)
return nil, err
}
// Process search results
var results []*typesLocal.IndexWithScore
for _, hit := range response.Hits.Hits {
var embedding *elasticsearchRetriever.VectorEmbeddingWithScore
if err := json.Unmarshal(hit.Source_, &embedding); err != nil {
log.Errorf("[Elasticsearch] Failed to unmarshal search result: %v", err)
return nil, err
}
embedding.Score = float64(*hit.Score_)
results = append(results,
elasticsearchRetriever.FromDBVectorEmbeddingWithScore(*hit.Id_, embedding, typesLocal.MatchTypeKeywords),
)
}
if len(results) == 0 {
log.Warnf("[Elasticsearch] No keyword matches found for query: %s", params.Query)
} else {
log.Infof("[Elasticsearch] Keywords retrieval found %d results", len(results))
log.Debugf("[Elasticsearch] Top result score: %.4f", results[0].Score)
}
return []*typesLocal.RetrieveResult{
{
Results: results,
RetrieverEngineType: typesLocal.ElasticsearchRetrieverEngineType,
RetrieverType: typesLocal.KeywordsRetrieverType,
Error: nil,
},
}, nil
}
// CopyIndices 复制索引数据
func (e *elasticsearchRepository) CopyIndices(ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
) error {
log := logger.GetLogger(ctx)
log.Infof(
"[Elasticsearch] Copying indices from source knowledge base %s to target knowledge base %s, count: %d",
sourceKnowledgeBaseID, targetKnowledgeBaseID, len(sourceToTargetChunkIDMap),
)
if len(sourceToTargetChunkIDMap) == 0 {
log.Warn("[Elasticsearch] Empty mapping, skipping copy")
return nil
}
// Build query parameters
params := typesLocal.RetrieveParams{
KnowledgeBaseIDs: []string{sourceKnowledgeBaseID},
}
// Build base query conditions
filter := e.getBaseConds(params)
// Set batch processing parameters
batchSize := 500
from := 0
totalCopied := 0
for {
// Execute pagination query
searchResponse, err := e.client.Search().Index(e.index).
Query(&types.Query{Bool: &types.BoolQuery{Filter: filter}}).
From(from).
Size(batchSize).
Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to query source index data: %v", err)
return err
}
hitsCount := len(searchResponse.Hits.Hits)
if hitsCount == 0 {
break
}
log.Infof("[Elasticsearch] Found %d source index data, batch start position: %d", hitsCount, from)
// Prepare index list for BatchSave
var indexInfoList []*typesLocal.IndexInfo
// Collect all embedding vector data for additionalParams
embeddingMap := make(map[string][]float32)
for _, hit := range searchResponse.Hits.Hits {
// Parse source document
var sourceDoc elasticsearchRetriever.VectorEmbedding
if err := json.Unmarshal(hit.Source_, &sourceDoc); err != nil {
log.Errorf("[Elasticsearch] Failed to parse source index data: %v", err)
continue
}
// Get mapped target chunk ID and knowledge ID
targetChunkID, ok := sourceToTargetChunkIDMap[sourceDoc.ChunkID]
if !ok {
log.Warnf("[Elasticsearch] Source chunk %s not found in target mapping, skipping", sourceDoc.ChunkID)
continue
}
targetKnowledgeID, ok := sourceToTargetKBIDMap[sourceDoc.KnowledgeID]
if !ok {
log.Warnf(
"[Elasticsearch] Source knowledge %s not found in target mapping, skipping",
sourceDoc.KnowledgeID,
)
continue
}
// Save embedding vector to embeddingMap
if len(sourceDoc.Embedding) > 0 {
embeddingMap[targetChunkID] = sourceDoc.Embedding
}
// Create new index information
indexInfo := &typesLocal.IndexInfo{
Content: sourceDoc.Content,
SourceID: targetChunkID,
SourceType: typesLocal.SourceType(sourceDoc.SourceType),
ChunkID: targetChunkID,
KnowledgeID: targetKnowledgeID,
KnowledgeBaseID: targetKnowledgeBaseID,
}
indexInfoList = append(indexInfoList, indexInfo)
totalCopied++
}
// Use BatchSave function to save index
if len(indexInfoList) > 0 {
// Add embedding vector to additional parameters
additionalParams := map[string]any{
"embedding": embeddingMap,
}
if err := e.BatchSave(ctx, indexInfoList, additionalParams); err != nil {
log.Errorf("[Elasticsearch] Failed to batch save index: %v", err)
return err
}
log.Infof("[Elasticsearch] Successfully copied batch data, batch size: %d, total copied: %d",
len(indexInfoList), totalCopied)
}
// Move to next batch
from += hitsCount
// If the number of returned records is less than the request size, it means the last page has been reached
if hitsCount < batchSize {
break
}
}
log.Infof("[Elasticsearch] Index copy completed, total copied: %d", totalCopied)
return nil
}
@@ -0,0 +1,390 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/pgvector/pgvector-go"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// pgRepository implements PostgreSQL-based retrieval operations
type pgRepository struct {
db *gorm.DB // Database connection
}
// NewPostgresRetrieveEngineRepository creates a new PostgreSQL retriever repository
func NewPostgresRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRepository {
logger.GetLogger(context.Background()).Info("[Postgres] Initializing PostgreSQL retriever engine repository")
return &pgRepository{db: db}
}
// EngineType returns the retriever engine type (PostgreSQL)
func (r *pgRepository) EngineType() types.RetrieverEngineType {
return types.PostgresRetrieverEngineType
}
// Support returns supported retriever types (keywords and vector)
func (r *pgRepository) Support() []types.RetrieverType {
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
}
// calculateIndexStorageSize calculates storage size for a single index entry
func (g *pgRepository) calculateIndexStorageSize(embeddingDB *pgVector) int64 {
// 1. Text content size
contentSizeBytes := int64(len(embeddingDB.Content))
// 2. Vector storage size (2 bytes per dimension for half-precision float)
var vectorSizeBytes int64 = 0
if embeddingDB.Dimension > 0 {
vectorSizeBytes = int64(embeddingDB.Dimension * 2)
}
// 3. Metadata size (fixed overhead for IDs, timestamps etc.)
metadataSizeBytes := int64(200)
// 4. Index overhead (HNSW index is ~2x vector size)
indexOverheadBytes := vectorSizeBytes * 2
// Total size in bytes
totalSizeBytes := contentSizeBytes + vectorSizeBytes + metadataSizeBytes + indexOverheadBytes
return totalSizeBytes
}
// EstimateStorageSize estimates total storage size for multiple indices
func (g *pgRepository) EstimateStorageSize(
ctx context.Context, indexInfoList []*types.IndexInfo, additionalParams map[string]any,
) int64 {
var totalStorageSize int64 = 0
for _, indexInfo := range indexInfoList {
embeddingDB := toDBVectorEmbedding(indexInfo, additionalParams)
totalStorageSize += g.calculateIndexStorageSize(embeddingDB)
}
logger.GetLogger(ctx).Infof(
"[Postgres] Estimated storage size for %d indices: %d bytes",
len(indexInfoList), totalStorageSize,
)
return totalStorageSize
}
// Save stores a single index entry
func (g *pgRepository) Save(ctx context.Context, indexInfo *types.IndexInfo, additionalParams map[string]any) error {
logger.GetLogger(ctx).Debugf("[Postgres] Saving index for source ID: %s", indexInfo.SourceID)
embeddingDB := toDBVectorEmbedding(indexInfo, additionalParams)
err := g.db.WithContext(ctx).Create(embeddingDB).Error
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to save index: %v", err)
return err
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully saved index for source ID: %s", indexInfo.SourceID)
return nil
}
// BatchSave stores multiple index entries in batch
func (g *pgRepository) BatchSave(
ctx context.Context, indexInfoList []*types.IndexInfo, additionalParams map[string]any,
) error {
logger.GetLogger(ctx).Infof("[Postgres] Batch saving %d indices", len(indexInfoList))
indexInfoDBList := make([]*pgVector, len(indexInfoList))
for i := range indexInfoList {
indexInfoDBList[i] = toDBVectorEmbedding(indexInfoList[i], additionalParams)
}
err := g.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(indexInfoDBList).Error
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Batch save failed: %v", err)
return err
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully batch saved %d indices", len(indexInfoList))
return nil
}
// DeleteByChunkIDList deletes indices by chunk IDs
func (g *pgRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int) error {
logger.GetLogger(ctx).Infof("[Postgres] Deleting indices by chunk IDs, count: %d", len(chunkIDList))
result := g.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Delete(&pgVector{})
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to delete indices by chunk IDs: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully deleted %d indices by chunk IDs", result.RowsAffected)
return nil
}
// DeleteByKnowledgeIDList deletes indices by knowledge IDs
func (g *pgRepository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error {
logger.GetLogger(ctx).Infof("[Postgres] Deleting indices by knowledge IDs, count: %d", len(knowledgeIDList))
result := g.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Delete(&pgVector{})
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to delete indices by knowledge IDs: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully deleted %d indices by knowledge IDs", result.RowsAffected)
return nil
}
// Retrieve handles retrieval requests and routes to appropriate method
func (g *pgRepository) Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
logger.GetLogger(ctx).Debugf("[Postgres] Processing retrieval request of type: %s", params.RetrieverType)
switch params.RetrieverType {
case types.KeywordsRetrieverType:
return g.KeywordsRetrieve(ctx, params)
case types.VectorRetrieverType:
return g.VectorRetrieve(ctx, params)
}
err := errors.New("invalid retriever type")
logger.GetLogger(ctx).Errorf("[Postgres] %v: %s", err, params.RetrieverType)
return nil, err
}
// KeywordsRetrieve performs keyword-based search using PostgreSQL full-text search
func (g *pgRepository) KeywordsRetrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
logger.GetLogger(ctx).Infof("[Postgres] Keywords retrieval: query=%s, topK=%d", params.Query, params.TopK)
conds := make([]clause.Expression, 0)
if len(params.KnowledgeBaseIDs) > 0 {
logger.GetLogger(ctx).Debugf("[Postgres] Filtering by knowledge base IDs: %v", params.KnowledgeBaseIDs)
conds = append(conds, clause.Expr{
SQL: fmt.Sprintf("knowledge_base_id @@@ 'in (%s)'", common.StringSliceJoin(params.KnowledgeBaseIDs)),
})
}
conds = append(conds, clause.Expr{
SQL: "id @@@ paradedb.match(field => 'content', value => ?, distance => 1)",
Vars: []interface{}{params.Query},
})
conds = append(conds, clause.OrderBy{Columns: []clause.OrderByColumn{
{Column: clause.Column{Name: "score"}, Desc: true},
}})
var embeddingDBList []pgVectorWithScore
err := g.db.WithContext(ctx).Clauses(conds...).Debug().
Select([]string{
"paradedb.score(id) as score",
"id",
"content",
"source_id",
"source_type",
"chunk_id",
"knowledge_id",
"knowledge_base_id",
}).
Limit(int(params.TopK)).
Find(&embeddingDBList).Error
if err == gorm.ErrRecordNotFound {
logger.GetLogger(ctx).Warnf("[Postgres] No records found for keywords query: %s", params.Query)
return nil, nil
}
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Keywords retrieval failed: %v", err)
return nil, err
}
logger.GetLogger(ctx).Infof("[Postgres] Keywords retrieval found %d results", len(embeddingDBList))
results := make([]*types.IndexWithScore, len(embeddingDBList))
for i := range embeddingDBList {
results[i] = fromDBVectorEmbeddingWithScore(&embeddingDBList[i], types.MatchTypeKeywords)
logger.GetLogger(ctx).Debugf("[Postgres] Keywords result %d: chunk=%s, score=%f",
i, results[i].ChunkID, results[i].Score)
}
return []*types.RetrieveResult{
{
Results: results,
RetrieverEngineType: types.PostgresRetrieverEngineType,
RetrieverType: types.KeywordsRetrieverType,
Error: nil,
},
}, nil
}
// VectorRetrieve performs vector similarity search using pgvector
func (g *pgRepository) VectorRetrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
logger.GetLogger(ctx).Infof("[Postgres] Vector retrieval: dim=%d, topK=%d, threshold=%.4f",
len(params.Embedding), params.TopK, params.Threshold)
conds := make([]clause.Expression, 0)
if len(params.KnowledgeBaseIDs) > 0 {
logger.GetLogger(ctx).Debugf(
"[Postgres] Filtering vector search by knowledge base IDs: %v",
params.KnowledgeBaseIDs,
)
conds = append(conds, clause.IN{
Column: "knowledge_base_id",
Values: common.ToInterfaceSlice(params.KnowledgeBaseIDs),
})
}
// <=> Cosine similarity operator
// <-> L2 distance operator
// <#> Inner product operator
dimension := len(params.Embedding)
conds = append(conds, clause.Expr{SQL: "dimension = ?", Vars: []interface{}{dimension}})
conds = append(conds, clause.Expr{
SQL: fmt.Sprintf("embedding::halfvec(%d) <=> ?::halfvec < ?", dimension),
Vars: []interface{}{pgvector.NewHalfVector(params.Embedding), 1 - params.Threshold},
})
conds = append(conds, clause.OrderBy{Expression: clause.Expr{
SQL: fmt.Sprintf("embedding::halfvec(%d) <=> ?::halfvec", dimension),
Vars: []interface{}{pgvector.NewHalfVector(params.Embedding)},
}})
var embeddingDBList []pgVectorWithScore
err := g.db.WithContext(ctx).Clauses(conds...).
Select(fmt.Sprintf(
"id, content, source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, "+
"(1 - (embedding::halfvec(%d) <=> ?::halfvec)) as score",
dimension,
), pgvector.NewHalfVector(params.Embedding)).
Limit(int(params.TopK)).
Find(&embeddingDBList).Error
if err == gorm.ErrRecordNotFound {
logger.GetLogger(ctx).Warnf("[Postgres] No vector matches found that meet threshold %.4f", params.Threshold)
return nil, nil
}
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Vector retrieval failed: %v", err)
return nil, err
}
logger.GetLogger(ctx).Infof("[Postgres] Vector retrieval found %d results", len(embeddingDBList))
results := make([]*types.IndexWithScore, len(embeddingDBList))
for i := range embeddingDBList {
results[i] = fromDBVectorEmbeddingWithScore(&embeddingDBList[i], types.MatchTypeEmbedding)
logger.GetLogger(ctx).Debugf("[Postgres] Vector search result %d: chunk_id %s, score %.4f",
i, results[i].ChunkID, results[i].Score)
}
return []*types.RetrieveResult{
{
Results: results,
RetrieverEngineType: types.PostgresRetrieverEngineType,
RetrieverType: types.VectorRetrieverType,
Error: nil,
},
}, nil
}
// CopyIndices copies index data
func (g *pgRepository) CopyIndices(ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
) error {
logger.GetLogger(ctx).Infof(
"[Postgres] Copying indices, source knowledge base: %s, target knowledge base: %s, mapping count: %d",
sourceKnowledgeBaseID, targetKnowledgeBaseID, len(sourceToTargetChunkIDMap),
)
if len(sourceToTargetChunkIDMap) == 0 {
logger.GetLogger(ctx).Warnf("[Postgres] Mapping is empty, no need to copy")
return nil
}
// Batch processing parameters
batchSize := 500 // Number of records to process per batch
offset := 0 // Offset for pagination
totalCopied := 0 // Total number of copied records
for {
// Paginated query for source data
var sourceVectors []*pgVector
if err := g.db.WithContext(ctx).
Where("knowledge_base_id = ?", sourceKnowledgeBaseID).
Limit(batchSize).
Offset(offset).
Find(&sourceVectors).Error; err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to query source index data: %v", err)
return err
}
// If no more data, exit the loop
if len(sourceVectors) == 0 {
if offset == 0 {
logger.GetLogger(ctx).Warnf("[Postgres] No source index data found")
}
break
}
batchCount := len(sourceVectors)
logger.GetLogger(ctx).Infof(
"[Postgres] Found %d source index data, batch start position: %d",
batchCount, offset,
)
// Create target vector index
targetVectors := make([]*pgVector, 0, batchCount)
for _, sourceVector := range sourceVectors {
// Get the mapped target chunk ID
targetChunkID, ok := sourceToTargetChunkIDMap[sourceVector.ChunkID]
if !ok {
logger.GetLogger(ctx).Warnf(
"[Postgres] Source chunk %s not found in target chunk mapping, skipping",
sourceVector.ChunkID,
)
continue
}
// Get the mapped target knowledge ID
targetKnowledgeID, ok := sourceToTargetKBIDMap[sourceVector.KnowledgeID]
if !ok {
logger.GetLogger(ctx).Warnf(
"[Postgres] Source knowledge %s not found in target knowledge mapping, skipping",
sourceVector.KnowledgeID,
)
continue
}
// Create new vector index, copy the content and vector of the source index
targetVector := &pgVector{
Content: sourceVector.Content,
SourceID: targetChunkID, // Update to target chunk ID
SourceType: sourceVector.SourceType,
ChunkID: targetChunkID, // Update to target chunk ID
KnowledgeID: targetKnowledgeID, // Update to target knowledge ID
KnowledgeBaseID: targetKnowledgeBaseID, // Update to target knowledge base ID
Dimension: sourceVector.Dimension,
Embedding: sourceVector.Embedding, // Copy the vector embedding directly, avoid recalculation
}
targetVectors = append(targetVectors, targetVector)
}
// Batch insert target vector index
if len(targetVectors) > 0 {
if err := g.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).Create(targetVectors).Error; err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to batch create target index: %v", err)
return err
}
totalCopied += len(targetVectors)
logger.GetLogger(ctx).Infof(
"[Postgres] Successfully copied batch data, batch size: %d, total copied: %d",
len(targetVectors),
totalCopied,
)
}
// Move to the next batch
offset += batchCount
// If the number of returned records is less than the requested size, it means the last page has been reached
if batchCount < batchSize {
break
}
}
logger.GetLogger(ctx).Infof("[Postgres] Index copying completed, total copied: %d", totalCopied)
return nil
}
@@ -0,0 +1,87 @@
package postgres
import (
"maps"
"slices"
"strconv"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/pgvector/pgvector-go"
)
// pgVector defines the database model for vector embeddings storage
type pgVector struct {
ID uint `json:"id" gorm:"primarykey"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"`
Content string `json:"content" gorm:"column:content;not null"`
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
}
// pgVectorWithScore extends pgVector with similarity score field
type pgVectorWithScore struct {
ID uint `json:"id" gorm:"primarykey"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"`
Content string `json:"content" gorm:"column:content;not null"`
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
Score float64 `json:"score" gorm:"column:score"`
}
// TableName specifies the database table name for pgVectorWithScore
func (pgVectorWithScore) TableName() string {
return "embeddings"
}
// TableName specifies the database table name for pgVector
func (pgVector) TableName() string {
return "embeddings"
}
// toDBVectorEmbedding converts IndexInfo to pgVector database model
func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[string]any) *pgVector {
pgVector := &pgVector{
SourceID: indexInfo.SourceID,
SourceType: int(indexInfo.SourceType),
ChunkID: indexInfo.ChunkID,
KnowledgeID: indexInfo.KnowledgeID,
KnowledgeBaseID: indexInfo.KnowledgeBaseID,
Content: indexInfo.Content,
}
// Add embedding data if available in additionalParams
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
if embeddingMap, ok := additionalParams["embedding"].(map[string][]float32); ok {
pgVector.Embedding = pgvector.NewHalfVector(embeddingMap[indexInfo.SourceID])
pgVector.Dimension = len(pgVector.Embedding.Slice())
}
}
return pgVector
}
// fromDBVectorEmbeddingWithScore converts pgVectorWithScore to IndexWithScore domain model
func fromDBVectorEmbeddingWithScore(embedding *pgVectorWithScore, matchType types.MatchType) *types.IndexWithScore {
return &types.IndexWithScore{
ID: strconv.FormatInt(int64(embedding.ID), 10),
SourceID: embedding.SourceID,
SourceType: types.SourceType(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
Content: embedding.Content,
Score: embedding.Score,
MatchType: matchType,
}
}
@@ -0,0 +1,89 @@
package repository
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// sessionRepository implements the SessionRepository interface
type sessionRepository struct {
db *gorm.DB
}
// NewSessionRepository creates a new session repository instance
func NewSessionRepository(db *gorm.DB) interfaces.SessionRepository {
return &sessionRepository{db: db}
}
// Create creates a new session
func (r *sessionRepository) Create(ctx context.Context, session *types.Session) (*types.Session, error) {
session.CreatedAt = time.Now()
session.UpdatedAt = time.Now()
if err := r.db.WithContext(ctx).Create(session).Error; err != nil {
return nil, err
}
// Return the session with generated ID
return session, nil
}
// Get retrieves a session by ID
func (r *sessionRepository) Get(ctx context.Context, tenantID uint, id string) (*types.Session, error) {
var session types.Session
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&session, "id = ?", id).Error
if err != nil {
return nil, err
}
return &session, nil
}
// GetByTenantID retrieves all sessions for a tenant
func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint) ([]*types.Session, error) {
var sessions []*types.Session
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Order("created_at DESC").Find(&sessions).Error
if err != nil {
return nil, err
}
return sessions, nil
}
// GetPagedByTenantID retrieves sessions for a tenant with pagination
func (r *sessionRepository) GetPagedByTenantID(
ctx context.Context, tenantID uint, page *types.Pagination,
) ([]*types.Session, int64, error) {
var sessions []*types.Session
var total int64
// First query the total count
err := r.db.WithContext(ctx).Model(&types.Session{}).Where("tenant_id = ?", tenantID).Count(&total).Error
if err != nil {
return nil, 0, err
}
// Then query the paginated data
err = r.db.WithContext(ctx).
Where("tenant_id = ?", tenantID).
Order("created_at DESC").
Offset(page.Offset()).
Limit(page.Limit()).
Find(&sessions).Error
if err != nil {
return nil, 0, err
}
return sessions, total, nil
}
// Update updates a session
func (r *sessionRepository) Update(ctx context.Context, session *types.Session) error {
session.UpdatedAt = time.Now()
return r.db.WithContext(ctx).Where("tenant_id = ?", session.TenantID).Save(session).Error
}
// Delete deletes a session
func (r *sessionRepository) Delete(ctx context.Context, tenantID uint, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Delete(&types.Session{}, "id = ?", id).Error
}
+82
View File
@@ -0,0 +1,82 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
var (
ErrTenantNotFound = errors.New("tenant not found")
ErrTenantHasKnowledgeBase = errors.New("tenant has associated knowledge bases")
)
// tenantRepository implements tenant repository interface
type tenantRepository struct {
db *gorm.DB
}
// NewTenantRepository creates a new tenant repository
func NewTenantRepository(db *gorm.DB) interfaces.TenantRepository {
return &tenantRepository{db: db}
}
// CreateTenant creates tenant
func (r *tenantRepository) CreateTenant(ctx context.Context, tenant *types.Tenant) error {
return r.db.WithContext(ctx).Create(tenant).Error
}
// GetTenantByID gets tenant by ID
func (r *tenantRepository) GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) {
var tenant types.Tenant
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&tenant).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrTenantNotFound
}
return nil, err
}
return &tenant, nil
}
// ListTenants lists all tenants
func (r *tenantRepository) ListTenants(ctx context.Context) ([]*types.Tenant, error) {
var tenants []*types.Tenant
if err := r.db.WithContext(ctx).Order("created_at DESC").Find(&tenants).Error; err != nil {
return nil, err
}
return tenants, nil
}
// UpdateTenant updates tenant
func (r *tenantRepository) UpdateTenant(ctx context.Context, tenant *types.Tenant) error {
return r.db.WithContext(ctx).Model(&types.Tenant{}).Where("id = ?", tenant.ID).Updates(tenant).Error
}
// DeleteTenant deletes tenant
func (r *tenantRepository) DeleteTenant(ctx context.Context, id uint) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Tenant{}).Error
}
func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint, delta int64) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var tenant types.Tenant
// 使用悲观锁确保并发安全
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&tenant, tenantID).Error; err != nil {
return err
}
tenant.StorageUsed += delta
// 保存更新并验证业务规则
if tenant.StorageUsed < 0 {
logger.Error(ctx, "tenant storage used is negative %s: %d", tenant.ID, tenant.StorageUsed)
tenant.StorageUsed = 0
}
return tx.Save(&tenant).Error
})
}
@@ -0,0 +1,60 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginChatCompletion implements chat completion functionality
// as a plugin that can be registered to EventManager
type PluginChatCompletion struct {
modelService interfaces.ModelService // Interface for model operations
}
// NewPluginChatCompletion creates a new PluginChatCompletion instance
// and registers it with the EventManager
func NewPluginChatCompletion(eventManager *EventManager, modelService interfaces.ModelService) *PluginChatCompletion {
res := &PluginChatCompletion{
modelService: modelService,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginChatCompletion) ActivationEvents() []types.EventType {
return []types.EventType{types.CHAT_COMPLETION}
}
// OnEvent handles chat completion events
// It prepares the chat model, messages, and calls the model to generate responses
func (p *PluginChatCompletion) OnEvent(
ctx context.Context, eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting chat completion")
// Prepare chat model and options
chatModel, opt, err := prepareChatModel(ctx, p.modelService, chatManage)
if err != nil {
return ErrGetChatModel.WithError(err)
}
// Prepare messages including conversation history
logger.Info(ctx, "Preparing chat messages with history")
chatMessages := prepareMessagesWithHistory(chatManage)
// Call the chat model to generate response
logger.Info(ctx, "Calling chat model")
chatResponse, err := chatModel.Chat(ctx, chatMessages, opt)
if err != nil {
logger.Errorf(ctx, "Failed to call chat model: %v", err)
return ErrModelCall.WithError(err)
}
logger.Info(ctx, "Chat completion successful")
chatManage.ChatResponse = chatResponse
return next()
}
@@ -0,0 +1,62 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginChatCompletionStream implements streaming chat completion functionality
// as a plugin that can be registered to EventManager
type PluginChatCompletionStream struct {
modelService interfaces.ModelService // Interface for model operations
}
// NewPluginChatCompletionStream creates a new PluginChatCompletionStream instance
// and registers it with the EventManager
func NewPluginChatCompletionStream(eventManager *EventManager,
modelService interfaces.ModelService,
) *PluginChatCompletionStream {
res := &PluginChatCompletionStream{
modelService: modelService,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginChatCompletionStream) ActivationEvents() []types.EventType {
return []types.EventType{types.CHAT_COMPLETION_STREAM}
}
// OnEvent handles streaming chat completion events
// It prepares the chat model, messages, and initiates streaming response
func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting chat completion stream")
// Prepare chat model and options
chatModel, opt, err := prepareChatModel(ctx, p.modelService, chatManage)
if err != nil {
return ErrGetChatModel.WithError(err)
}
// Prepare base messages without history
logger.Info(ctx, "Preparing chat messages")
chatMessages := prepareMessagesWithHistory(chatManage)
// Initiate streaming chat model call
logger.Info(ctx, "Calling chat stream model")
responseChan, err := chatModel.ChatStream(ctx, chatMessages, opt)
if err != nil {
logger.Errorf(ctx, "Failed to call chat stream model: %v", err)
return ErrModelCall.WithError(err)
}
logger.Info(ctx, "Chat stream initiated successfully")
chatManage.ResponseChan = responseChan
return next()
}
@@ -0,0 +1,161 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// Plugin defines the interface for chat pipeline plugins
// Plugins can handle specific events in the chat pipeline
type Plugin interface {
// OnEvent handles the event with given context and chat management object
OnEvent(
ctx context.Context,
eventType types.EventType,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError
// ActivationEvents returns the event types this plugin can handle
ActivationEvents() []types.EventType
}
// EventManager manages plugins and their event handling
type EventManager struct {
// Map of event types to registered plugins
listeners map[types.EventType][]Plugin
// Map of event types to handler functions
handlers map[types.EventType]func(context.Context, types.EventType, *types.ChatManage) *PluginError
}
// NewEventManager creates and initializes a new EventManager
func NewEventManager() *EventManager {
return &EventManager{
listeners: make(map[types.EventType][]Plugin),
handlers: make(map[types.EventType]func(context.Context, types.EventType, *types.ChatManage) *PluginError),
}
}
// Register adds a plugin to the EventManager and sets up its event handlers
func (e *EventManager) Register(plugin Plugin) {
if e.listeners == nil {
e.listeners = make(map[types.EventType][]Plugin)
}
if e.handlers == nil {
e.handlers = make(map[types.EventType]func(context.Context, types.EventType, *types.ChatManage) *PluginError)
}
for _, eventType := range plugin.ActivationEvents() {
e.listeners[eventType] = append(e.listeners[eventType], plugin)
e.handlers[eventType] = e.buildHandler(e.listeners[eventType])
}
}
// buildHandler constructs a handler chain for the given plugins
func (e *EventManager) buildHandler(plugins []Plugin) func(
ctx context.Context, eventType types.EventType, chatManage *types.ChatManage,
) *PluginError {
next := func(context.Context, types.EventType, *types.ChatManage) *PluginError { return nil }
for i := len(plugins) - 1; i >= 0; i-- {
current := plugins[i]
prevNext := next
next = func(ctx context.Context, eventType types.EventType, chatManage *types.ChatManage) *PluginError {
return current.OnEvent(ctx, eventType, chatManage, func() *PluginError {
return prevNext(ctx, eventType, chatManage)
})
}
}
return next
}
// Trigger invokes the handler for the specified event type
func (e *EventManager) Trigger(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage,
) *PluginError {
if handler, ok := e.handlers[eventType]; ok {
return handler(ctx, eventType, chatManage)
}
return nil
}
// PluginError represents an error in plugin execution
type PluginError struct {
Err error // Original error
Description string // Human-readable description
ErrorType string // Error type identifier
}
// Predefined plugin errors
var (
ErrSearchNothing = &PluginError{
Description: "No relevant content found",
ErrorType: "search_nothing",
}
ErrSearch = &PluginError{
Description: "Failed to search knowledge base",
ErrorType: "search_failed",
}
ErrRerank = &PluginError{
Description: "Reranking failed",
ErrorType: "rerank_failed",
}
ErrGetRerankModel = &PluginError{
Description: "Failed to get rerank model",
ErrorType: "get_rerank_model_failed",
}
ErrGetChatModel = &PluginError{
Description: "Failed to get chat model",
ErrorType: "get_chat_model_failed",
}
ErrTemplateParse = &PluginError{
Description: "Failed to parse context template",
ErrorType: "template_parse_failed",
}
ErrTemplateExecute = &PluginError{
Description: "Failed to generate search content",
ErrorType: "template_execution_failed",
}
ErrModelCall = &PluginError{
Description: "Failed to call model",
ErrorType: "model_call_failed",
}
ErrGetHistory = &PluginError{
Description: "Failed to get conversation history",
ErrorType: "get_history_failed",
}
)
// clone creates a copy of the PluginError
func (p *PluginError) clone() *PluginError {
return &PluginError{
Description: p.Description,
ErrorType: p.ErrorType,
}
}
// WithError attaches an error to the PluginError and returns a new instance
func (p *PluginError) WithError(err error) *PluginError {
pp := p.clone()
pp.Err = err
return pp
}
// NewFallbackChan creates a channel with a single fallback response
func NewFallbackChan(ctx context.Context, fallbackResponse string) <-chan types.StreamResponse {
fallabackChan := make(chan types.StreamResponse)
go func() {
fallabackChan <- NewFallback(ctx, fallbackResponse)
close(fallabackChan)
}()
return fallabackChan
}
// NewFallback creates a fallback stream response with the given content
func NewFallback(ctx context.Context, fallbackResponse string) types.StreamResponse {
requestID := ctx.Value(types.RequestIDContextKey).(string)
return types.StreamResponse{
ID: requestID,
ResponseType: types.ResponseTypeAnswer,
Content: fallbackResponse,
Done: true,
}
}
@@ -0,0 +1,125 @@
package chatpipline
import (
"context"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
// Define a test Plugin implementation
type testPlugin struct {
name string
events []types.EventType
shouldError bool
errorToReturn *PluginError
}
func (p *testPlugin) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
if p.shouldError {
return p.errorToReturn
}
fmt.Printf("Plugin %s triggered\n", p.name)
err := next()
fmt.Printf("Plugin %s finished\n", p.name)
return err
}
func (p *testPlugin) ActivationEvents() []types.EventType {
return p.events
}
func TestTrigger(t *testing.T) {
// Prepare test data
ctx := context.Background()
chatManage := &types.ChatManage{}
testEvent := types.EventType("test_event")
// Test scenario 1: No plugins registered
t.Run("NoPluginsRegistered", func(t *testing.T) {
manager := &EventManager{}
err := manager.Trigger(ctx, testEvent, chatManage)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
})
// Test scenario 2: Register a normally working plugin
t.Run("SinglePluginSuccess", func(t *testing.T) {
manager := &EventManager{}
plugin := &testPlugin{
name: "test_plugin",
events: []types.EventType{testEvent},
}
manager.Register(plugin)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
})
// Test scenario 3: Plugin chain call
t.Run("PluginChain", func(t *testing.T) {
manager := &EventManager{}
plugin1 := &testPlugin{
name: "plugin1",
events: []types.EventType{testEvent},
}
plugin2 := &testPlugin{
name: "plugin2",
events: []types.EventType{testEvent},
}
manager.Register(plugin1)
manager.Register(plugin2)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
})
// Test scenario 4: Plugin returns error
t.Run("PluginReturnsError", func(t *testing.T) {
manager := &EventManager{}
expectedErr := &PluginError{Description: "test error"}
plugin := &testPlugin{
name: "error_plugin",
events: []types.EventType{testEvent},
shouldError: true,
errorToReturn: expectedErr,
}
manager.Register(plugin)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != expectedErr {
t.Errorf("Expected error %v, got %v", expectedErr, err)
}
})
// Test scenario 5: A plugin in the chain returns error
t.Run("ErrorInPluginChain", func(t *testing.T) {
manager := &EventManager{}
expectedErr := &PluginError{Description: "test error"}
plugin1 := &testPlugin{
name: "plugin1",
events: []types.EventType{testEvent},
}
plugin2 := &testPlugin{
name: "plugin2",
events: []types.EventType{testEvent},
shouldError: true,
errorToReturn: expectedErr,
}
manager.Register(plugin1)
manager.Register(plugin2)
err := manager.Trigger(ctx, testEvent, chatManage)
if err != expectedErr {
t.Errorf("Expected error %v, got %v", expectedErr, err)
}
})
}
@@ -0,0 +1,67 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// prepareChatModel shared logic to prepare chat model and options
func prepareChatModel(ctx context.Context, modelService interfaces.ModelService,
chatManage *types.ChatManage,
) (chat.Chat, *chat.ChatOptions, error) {
logger.Infof(ctx, "Getting chat model, model ID: %s", chatManage.ChatModelID)
chatModel, err := modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get chat model: %v", err)
return nil, nil, err
}
logger.Info(ctx, "Setting up chat options")
opt := &chat.ChatOptions{
Temperature: chatManage.SummaryConfig.Temperature,
TopP: chatManage.SummaryConfig.TopP,
Seed: chatManage.SummaryConfig.Seed,
MaxTokens: chatManage.SummaryConfig.MaxTokens,
MaxCompletionTokens: chatManage.SummaryConfig.MaxCompletionTokens,
FrequencyPenalty: chatManage.SummaryConfig.FrequencyPenalty,
PresencePenalty: chatManage.SummaryConfig.PresencePenalty,
}
return chatModel, opt, nil
}
// prepareBaseMessages prepare basic messages (system prompt and current user content)
func prepareBaseMessages(chatManage *types.ChatManage) []chat.Message {
var chatMessages []chat.Message
chatMessages = append(chatMessages, chat.Message{Role: "system", Content: chatManage.SummaryConfig.Prompt})
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: chatManage.UserContent})
return chatMessages
}
// prepareMessagesWithHistory prepare complete messages including history
func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
chatMessages := []chat.Message{
{Role: "system", Content: chatManage.SummaryConfig.Prompt},
}
chatHistory := chatManage.History
if len(chatHistory) > 2 {
chatHistory = chatHistory[len(chatHistory)-2:]
}
// Add conversation history
for _, history := range chatHistory {
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query})
chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer})
}
// Add current user message
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: chatManage.UserContent})
return chatMessages
}
@@ -0,0 +1,53 @@
package chatpipline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginFilterTopK is a plugin that filters search results to keep only the top K items
type PluginFilterTopK struct{}
// NewPluginFilterTopK creates a new instance of PluginFilterTopK and registers it with the event manager
func NewPluginFilterTopK(eventManager *EventManager) *PluginFilterTopK {
res := &PluginFilterTopK{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types that this plugin responds to
func (p *PluginFilterTopK) ActivationEvents() []types.EventType {
return []types.EventType{types.FILTER_TOP_K}
}
// OnEvent handles the FILTER_TOP_K event by filtering results to keep only the top K items
// It can filter MergeResult, RerankResult, or SearchResult depending on which is available
func (p *PluginFilterTopK) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting filter top-K process")
logger.Infof(ctx, "Filter configuration: top-K = %d", chatManage.RerankTopK)
filterTopK := func(searchResult []*types.SearchResult, topK int) []*types.SearchResult {
if topK > 0 && len(searchResult) > topK {
logger.Infof(ctx, "Filtering results: before=%d, after=%d", len(searchResult), topK)
searchResult = searchResult[:topK]
}
return searchResult
}
if len(chatManage.MergeResult) > 0 {
chatManage.MergeResult = filterTopK(chatManage.MergeResult, chatManage.RerankTopK)
} else if len(chatManage.RerankResult) > 0 {
chatManage.RerankResult = filterTopK(chatManage.RerankResult, chatManage.RerankTopK)
} else if len(chatManage.SearchResult) > 0 {
chatManage.SearchResult = filterTopK(chatManage.SearchResult, chatManage.RerankTopK)
} else {
logger.Info(ctx, "No results to filter")
}
logger.Info(ctx, "Filter top-K process completed")
return next()
}
@@ -0,0 +1,183 @@
package chatpipline
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginIntoChatMessage handles the transformation of search results into chat messages
type PluginIntoChatMessage struct{}
// NewPluginIntoChatMessage creates and registers a new PluginIntoChatMessage instance
func NewPluginIntoChatMessage(eventManager *EventManager) *PluginIntoChatMessage {
res := &PluginIntoChatMessage{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginIntoChatMessage) ActivationEvents() []types.EventType {
return []types.EventType{types.INTO_CHAT_MESSAGE}
}
// OnEvent processes the INTO_CHAT_MESSAGE event to format chat message content
func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Extract content from merge results
passages := make([]string, len(chatManage.MergeResult))
for i, result := range chatManage.MergeResult {
// 合并内容和图片信息
passages[i] = getEnrichedPassageForChat(ctx, result)
}
// Parse the context template
tmpl, err := template.New("searchContent").Parse(chatManage.SummaryConfig.ContextTemplate)
if err != nil {
return ErrTemplateParse.WithError(err)
}
// Prepare weekday names for template
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
var userContent bytes.Buffer
// Execute template with context data
err = tmpl.Execute(&userContent, map[string]interface{}{
"Query": chatManage.Query, // User's original query
"Contexts": passages, // Extracted passages from search results
"CurrentTime": time.Now().Format("2006-01-02 15:04:05"), // Formatted current time
"CurrentWeek": weekdayName[time.Now().Weekday()], // Current weekday in Chinese
})
if err != nil {
return ErrTemplateExecute.WithError(err)
}
// Set formatted content back to chat management
chatManage.UserContent = userContent.String()
return next()
}
// getEnrichedPassageForChat 合并Content和ImageInfo的文本内容,为聊天消息准备
func getEnrichedPassageForChat(ctx context.Context, result *types.SearchResult) string {
// 如果没有图片信息,直接返回内容
if result.Content == "" && result.ImageInfo == "" {
return ""
}
// 如果只有内容,没有图片信息
if result.ImageInfo == "" {
return result.Content
}
// 处理图片信息并与内容合并
return enrichContentWithImageInfo(ctx, result.Content, result.ImageInfo)
}
// 正则表达式用于匹配Markdown图片链接
var markdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
// enrichContentWithImageInfo 将图片信息与文本内容合并
func enrichContentWithImageInfo(ctx context.Context, content string, imageInfoJSON string) string {
// 解析ImageInfo
var imageInfos []types.ImageInfo
err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos)
if err != nil {
logger.Warnf(ctx, "Failed to parse ImageInfo: %v, using content only", err)
return content
}
if len(imageInfos) == 0 {
return content
}
// 创建图片URL到信息的映射
imageInfoMap := make(map[string]*types.ImageInfo)
for i := range imageInfos {
if imageInfos[i].URL != "" {
imageInfoMap[imageInfos[i].URL] = &imageInfos[i]
}
// 同时检查原始URL
if imageInfos[i].OriginalURL != "" {
imageInfoMap[imageInfos[i].OriginalURL] = &imageInfos[i]
}
}
// 查找内容中的所有Markdown图片链接
matches := markdownImageRegex.FindAllStringSubmatch(content, -1)
// 用于存储已处理的图片URL
processedURLs := make(map[string]bool)
logger.Infof(ctx, "Found %d Markdown image links in content", len(matches))
// 替换每个图片链接,添加描述和OCR文本
for _, match := range matches {
if len(match) < 3 {
continue
}
// 提取图片URL,忽略alt文本
imgURL := match[2]
// 标记该URL已处理
processedURLs[imgURL] = true
// 查找匹配的图片信息
imgInfo, found := imageInfoMap[imgURL]
// 如果找到匹配的图片信息,添加描述和OCR文本
if found && imgInfo != nil {
replacement := match[0] + "\n"
if imgInfo.Caption != "" {
replacement += fmt.Sprintf("图片描述: %s\n", imgInfo.Caption)
}
if imgInfo.OCRText != "" {
replacement += fmt.Sprintf("图片文本: %s\n", imgInfo.OCRText)
}
content = strings.Replace(content, match[0], replacement, 1)
}
}
// 处理未在内容中找到但存在于ImageInfo中的图片
var additionalImageTexts []string
for _, imgInfo := range imageInfos {
// 如果图片URL已经处理过,跳过
if processedURLs[imgInfo.URL] || processedURLs[imgInfo.OriginalURL] {
continue
}
var imgTexts []string
if imgInfo.Caption != "" {
imgTexts = append(imgTexts, fmt.Sprintf("图片 %s 的描述信息: %s", imgInfo.URL, imgInfo.Caption))
}
if imgInfo.OCRText != "" {
imgTexts = append(imgTexts, fmt.Sprintf("图片 %s 的文本: %s", imgInfo.URL, imgInfo.OCRText))
}
if len(imgTexts) > 0 {
additionalImageTexts = append(additionalImageTexts, imgTexts...)
}
}
// 如果有额外的图片信息,添加到内容末尾
if len(additionalImageTexts) > 0 {
if content != "" {
content += "\n\n"
}
content += "附加图片信息:\n" + strings.Join(additionalImageTexts, "\n")
}
logger.Debugf(ctx, "Enhanced content with image info: found %d Markdown images, added %d additional images",
len(matches), len(additionalImageTexts))
return content
}
@@ -0,0 +1,175 @@
package chatpipline
import (
"context"
"encoding/json"
"sort"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginMerge handles merging of search result chunks
type PluginMerge struct{}
// NewPluginMerge creates and registers a new PluginMerge instance
func NewPluginMerge(eventManager *EventManager) *PluginMerge {
res := &PluginMerge{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginMerge) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_MERGE}
}
// OnEvent processes the CHUNK_MERGE event to merge search result chunks
func (p *PluginMerge) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting chunk merge process")
// Use rerank results if available, fallback to search results
searchResult := chatManage.RerankResult
if len(searchResult) == 0 {
logger.Info(ctx, "No rerank results available, using search results")
searchResult = chatManage.SearchResult
}
logger.Infof(ctx, "Processing %d chunks for merging", len(searchResult))
if len(searchResult) == 0 {
logger.Info(ctx, "No chunks available for merging")
return next()
}
// Group chunks by their knowledge source ID
knowledgeGroup := make(map[string][]*types.SearchResult)
for _, chunk := range searchResult {
knowledgeGroup[chunk.KnowledgeID] = append(knowledgeGroup[chunk.KnowledgeID], chunk)
}
logger.Infof(ctx, "Grouped chunks by knowledge ID, %d knowledge sources", len(knowledgeGroup))
mergedChunks := []*types.SearchResult{}
// Process each knowledge source separately
for knowledgeID, chunks := range knowledgeGroup {
logger.Infof(ctx, "Processing knowledge ID: %s with %d chunks", knowledgeID, len(chunks))
// Sort chunks by their start position in the original document
sort.Slice(chunks, func(i, j int) bool {
if chunks[i].StartAt == chunks[j].StartAt {
return chunks[i].EndAt < chunks[j].EndAt
}
return chunks[i].StartAt < chunks[j].StartAt
})
// Merge overlapping or adjacent chunks
knowledgeMergedChunks := []*types.SearchResult{}
if chunks[0].ChunkType == types.ChunkTypeSummary {
knowledgeMergedChunks = append(knowledgeMergedChunks, chunks[0])
// skip the first chunk if it is summary chunk
// This is to avoid merging the summary chunk with the first content chunk
chunks = chunks[1:]
}
if len(chunks) > 0 {
knowledgeMergedChunks = append(knowledgeMergedChunks, chunks[0])
}
for i := 1; i < len(chunks); i++ {
lastChunk := knowledgeMergedChunks[len(knowledgeMergedChunks)-1]
// If the current chunk starts after the last chunk ends, add it to the merged chunks
if chunks[i].StartAt > lastChunk.EndAt {
knowledgeMergedChunks = append(knowledgeMergedChunks, chunks[i])
continue
}
// Merge overlapping chunks
if chunks[i].EndAt > lastChunk.EndAt {
lastChunk.Content = lastChunk.Content +
string([]rune(chunks[i].Content)[lastChunk.EndAt-chunks[i].StartAt:])
lastChunk.EndAt = chunks[i].EndAt
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
// 合并 ImageInfo
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
logger.Warnf(ctx, "Failed to merge ImageInfo: %v", err)
}
}
if chunks[i].Score > lastChunk.Score {
lastChunk.Score = chunks[i].Score
}
}
logger.Infof(ctx, "Merged %d chunks into %d chunks for knowledge ID: %s",
len(chunks), len(knowledgeMergedChunks), knowledgeID)
mergedChunks = append(mergedChunks, knowledgeMergedChunks...)
}
// Sort merged chunks by their score (highest first)
sort.Slice(mergedChunks, func(i, j int) bool {
return mergedChunks[i].Score > mergedChunks[j].Score
})
logger.Infof(ctx, "Final merged result: %d chunks, sorted by score", len(mergedChunks))
chatManage.MergeResult = mergedChunks
return next()
}
// mergeImageInfo 合并两个chunk的ImageInfo
func mergeImageInfo(ctx context.Context, target *types.SearchResult, source *types.SearchResult) error {
// 如果source没有ImageInfo,不需要合并
if source.ImageInfo == "" {
return nil
}
var sourceImageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(source.ImageInfo), &sourceImageInfos); err != nil {
logger.Warnf(ctx, "Failed to unmarshal source ImageInfo: %v", err)
return err
}
// 如果source的ImageInfo为空,不需要合并
if len(sourceImageInfos) == 0 {
return nil
}
// 处理target的ImageInfo
var targetImageInfos []types.ImageInfo
if target.ImageInfo != "" {
if err := json.Unmarshal([]byte(target.ImageInfo), &targetImageInfos); err != nil {
logger.Warnf(ctx, "Failed to unmarshal target ImageInfo: %v", err)
// 如果目标解析失败,直接使用源数据
target.ImageInfo = source.ImageInfo
return nil
}
}
// 合并ImageInfo
targetImageInfos = append(targetImageInfos, sourceImageInfos...)
// 去重
uniqueMap := make(map[string]bool)
uniqueImageInfos := make([]types.ImageInfo, 0, len(targetImageInfos))
for _, imgInfo := range targetImageInfos {
// 使用URL作为唯一标识
if imgInfo.URL != "" && !uniqueMap[imgInfo.URL] {
uniqueMap[imgInfo.URL] = true
uniqueImageInfos = append(uniqueImageInfos, imgInfo)
}
}
// 序列化合并后的ImageInfo
mergedImageInfoJSON, err := json.Marshal(uniqueImageInfos)
if err != nil {
logger.Warnf(ctx, "Failed to marshal merged ImageInfo: %v", err)
return err
}
// 更新目标chunk的ImageInfo
target.ImageInfo = string(mergedImageInfoJSON)
logger.Infof(ctx, "Successfully merged ImageInfo, total count: %d", len(uniqueImageInfos))
return nil
}
@@ -0,0 +1,180 @@
package chatpipline
import (
"context"
"regexp"
"strings"
"unicode"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/yanyiwu/gojieba"
)
// PluginPreprocess Query preprocessing plugin
type PluginPreprocess struct {
config *config.Config
jieba *gojieba.Jieba
stopwords map[string]struct{}
}
// Regular expressions for text cleaning
var (
multiSpaceRegex = regexp.MustCompile(`\s+`) // Multiple spaces
urlRegex = regexp.MustCompile(`https?://\S+`) // URLs
emailRegex = regexp.MustCompile(`\b[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}\b`) // Email addresses
punctRegex = regexp.MustCompile(`[^\p{L}\p{N}\s]`) // Punctuation marks
)
// NewPluginPreprocess Creates a new query preprocessing plugin
func NewPluginPreprocess(
eventManager *EventManager,
config *config.Config,
cleaner interfaces.ResourceCleaner,
) *PluginPreprocess {
// Use default dictionary for Jieba tokenizer
jieba := gojieba.NewJieba()
// Load stopwords from built-in stopword library
stopwords := loadStopwords()
res := &PluginPreprocess{
config: config,
jieba: jieba,
stopwords: stopwords,
}
// Register resource cleanup function
if cleaner != nil {
cleaner.RegisterWithName("JiebaPreprocessor", func() error {
res.Close()
return nil
})
}
eventManager.Register(res)
return res
}
// Load stopwords
func loadStopwords() map[string]struct{} {
// Directly use some common stopwords built into Jieba
commonStopwords := []string{
"的", "了", "和", "是", "在", "我", "你", "他", "她", "它",
"这", "那", "什么", "怎么", "如何", "为什么", "哪里", "什么时候",
"the", "is", "are", "am", "I", "you", "he", "she", "it", "this",
"that", "what", "how", "a", "an", "and", "or", "but", "if", "of",
"to", "in", "on", "at", "by", "for", "with", "about", "from",
"有", "无", "好", "来", "去", "说", "看", "想", "会", "可以",
"吗", "呢", "啊", "吧", "的话", "就是", "只是", "因为", "所以",
}
result := make(map[string]struct{}, len(commonStopwords))
for _, word := range commonStopwords {
result[word] = struct{}{}
}
return result
}
// ActivationEvents Register activation events
func (p *PluginPreprocess) ActivationEvents() []types.EventType {
return []types.EventType{types.PREPROCESS_QUERY}
}
// OnEvent Process events
func (p *PluginPreprocess) OnEvent(ctx context.Context, eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError) *PluginError {
if chatManage.RewriteQuery == "" {
return next()
}
logger.GetLogger(ctx).Infof("Starting query preprocessing, original query: %s", chatManage.RewriteQuery)
// 1. Basic text cleaning
processed := p.cleanText(chatManage.RewriteQuery)
// 2. Tokenization
segments := p.segmentText(processed)
// 3. Stopword filtering and reconstruction
filteredSegments := p.filterStopwords(segments)
// Update preprocessed query
chatManage.ProcessedQuery = strings.Join(filteredSegments, " ")
logger.GetLogger(ctx).Infof("Query preprocessing complete, processed query: %s", chatManage.ProcessedQuery)
return next()
}
// cleanText Basic text cleaning
func (p *PluginPreprocess) cleanText(text string) string {
// Remove URLs
text = urlRegex.ReplaceAllString(text, " ")
// Remove email addresses
text = emailRegex.ReplaceAllString(text, " ")
// Remove excessive spaces
text = multiSpaceRegex.ReplaceAllString(text, " ")
// Remove punctuation marks
text = punctRegex.ReplaceAllString(text, " ")
// Trim leading and trailing spaces
text = strings.TrimSpace(text)
return text
}
// segmentText Text tokenization
func (p *PluginPreprocess) segmentText(text string) []string {
// Use Jieba tokenizer for tokenization, using search engine mode
segments := p.jieba.CutForSearch(text, true)
return segments
}
// filterStopwords Filter stopwords
func (p *PluginPreprocess) filterStopwords(segments []string) []string {
var filtered []string
for _, word := range segments {
// If not a stopword and not blank, keep it
if _, isStopword := p.stopwords[word]; !isStopword && !isBlank(word) {
filtered = append(filtered, word)
}
}
// If filtering results in empty list, return original tokenization results
if len(filtered) == 0 {
return segments
}
return filtered
}
// isBlank Check if a string is blank
func isBlank(str string) bool {
for _, r := range str {
if !unicode.IsSpace(r) {
return false
}
}
return true
}
// Ensure resources are properly released
func (p *PluginPreprocess) Close() {
if p.jieba != nil {
p.jieba.Free()
p.jieba = nil
}
}
// ShutdownHandler Returns shutdown function
func (p *PluginPreprocess) ShutdownHandler() func() {
return func() {
p.Close()
}
}
@@ -0,0 +1,171 @@
package chatpipline
import (
"context"
"encoding/json"
"fmt"
"math"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginRerank implements reranking functionality for chat pipeline
type PluginRerank struct {
modelService interfaces.ModelService // Service to access rerank models
}
// NewPluginRerank creates a new rerank plugin instance
func NewPluginRerank(eventManager *EventManager, modelService interfaces.ModelService) *PluginRerank {
res := &PluginRerank{
modelService: modelService,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginRerank) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_RERANK}
}
// OnEvent handles reranking events in the chat pipeline
func (p *PluginRerank) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting reranking process")
logger.Infof(ctx, "Getting rerank model, model ID: %s", chatManage.RerankModelID)
if len(chatManage.SearchResult) == 0 {
logger.Infof(ctx, "No search result, skip reranking")
return next()
}
if chatManage.RerankModelID == "" {
logger.Warn(ctx, "Rerank model ID is empty, skipping reranking")
return next()
}
// Get rerank model from service
rerankModel, err := p.modelService.GetRerankModel(ctx, chatManage.RerankModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get rerank model: %v, rerank model ID: %s", err, chatManage.RerankModelID)
return ErrGetRerankModel.WithError(err)
}
// Prepare passages for reranking
logger.Infof(ctx, "Preparing passages for reranking, search result count: %d", len(chatManage.SearchResult))
var passages []string
for _, result := range chatManage.SearchResult {
// 合并Content和ImageInfo的文本内容
passage := getEnrichedPassage(ctx, result)
passages = append(passages, passage)
}
// Try reranking with different query variants in priority order
rerankResp := p.rerank(ctx, chatManage, rerankModel, chatManage.RewriteQuery, passages)
if len(rerankResp) == 0 {
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.ProcessedQuery, passages)
if len(rerankResp) == 0 {
rerankResp = p.rerank(ctx, chatManage, rerankModel, chatManage.Query, passages)
}
}
// Update search results with reranked scores
logger.Infof(ctx, "Filtered rerank results, original: %d, filtered: %d", len(rerankResp), len(rerankResp))
result := []*types.SearchResult{}
for _, rr := range rerankResp {
chatManage.SearchResult[rr.Index].Score = rr.RelevanceScore
result = append(result, chatManage.SearchResult[rr.Index])
}
chatManage.RerankResult = result
if len(chatManage.RerankResult) == 0 {
logger.Warn(ctx, "Reranking produced no results above threshold")
return ErrSearchNothing
}
logger.Infof(ctx, "Reranking process completed successfully, result count: %d", len(chatManage.RerankResult))
return next()
}
// rerank performs the actual reranking operation with given query and passages
func (p *PluginRerank) rerank(ctx context.Context,
chatManage *types.ChatManage, rerankModel rerank.Reranker, query string, passages []string,
) []rerank.RankResult {
logger.Infof(ctx, "Executing reranking with query: %s, passage count: %d", query, len(passages))
rerankResp, err := rerankModel.Rerank(ctx, query, passages)
if err != nil {
logger.Errorf(ctx, "Reranking failed: %v", err)
return nil
}
// Log top scores for debugging
logger.Infof(ctx, "Reranking completed, filtering results with threshold: %f", chatManage.RerankThreshold)
for i := range min(3, len(rerankResp)) {
logger.Infof(ctx, "Top %d score of rerankResp: %f, passages: %s, index: %d",
i+1, rerankResp[i].RelevanceScore, rerankResp[i].Document.Text, rerankResp[i].Index,
)
}
// Filter results based on threshold with special handling for history matches
rankFilter := []rerank.RankResult{}
for _, result := range rerankResp {
th := chatManage.RerankThreshold
matchType := chatManage.SearchResult[result.Index].MatchType
if matchType == types.MatchTypeHistory {
th = math.Max(th-0.1, 0.5) // Lower threshold for history matches
}
if result.RelevanceScore > th {
rankFilter = append(rankFilter, result)
}
}
return rankFilter
}
// getEnrichedPassage 合并Content和ImageInfo的文本内容
func getEnrichedPassage(ctx context.Context, result *types.SearchResult) string {
if result.ImageInfo == "" {
return result.Content
}
// 解析ImageInfo
var imageInfos []types.ImageInfo
err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos)
if err != nil {
logger.Warnf(ctx, "Failed to parse ImageInfo: %v, using content only", err)
return result.Content
}
if len(imageInfos) == 0 {
return result.Content
}
// 提取所有图片的描述和OCR文本
var imageTexts []string
for _, img := range imageInfos {
if img.Caption != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片描述: %s", img.Caption))
}
if img.OCRText != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片文本: %s", img.OCRText))
}
}
if len(imageTexts) == 0 {
return result.Content
}
// 组合内容和图片信息
combinedText := result.Content
if combinedText != "" {
combinedText += "\n\n"
}
combinedText += strings.Join(imageTexts, "\n")
logger.Debugf(ctx, "Enhanced passage with image info: content length %d, image texts length %d",
len(result.Content), len(strings.Join(imageTexts, "\n")))
return combinedText
}
@@ -0,0 +1,174 @@
// Package chatpipline provides chat pipeline processing capabilities
// Including query rewriting, history processing, model invocation and other features
package chatpipline
import (
"bytes"
"context"
"html/template"
"regexp"
"slices"
"sort"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginRewrite is a plugin for rewriting user queries
// It uses historical dialog context and large language models to optimize the user's original query
type PluginRewrite struct {
modelService interfaces.ModelService // Model service for calling large language models
messageService interfaces.MessageService // Message service for retrieving historical messages
config *config.Config // System configuration
}
// reg is a regular expression used to match and remove content between <think></think> tags
var reg = regexp.MustCompile(`(?s)<think>.*?</think>`)
// NewPluginRewrite creates a new query rewriting plugin instance
// Also registers the plugin with the event manager
func NewPluginRewrite(eventManager *EventManager,
modelService interfaces.ModelService, messageService interfaces.MessageService,
config *config.Config,
) *PluginRewrite {
res := &PluginRewrite{
modelService: modelService,
messageService: messageService,
config: config,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the list of event types this plugin responds to
// This plugin only responds to REWRITE_QUERY events
func (p *PluginRewrite) ActivationEvents() []types.EventType {
return []types.EventType{types.REWRITE_QUERY}
}
// OnEvent processes triggered events
// When receiving a REWRITE_QUERY event, it rewrites the user query using conversation history and the language model
func (p *PluginRewrite) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Initialize rewritten query as original query
chatManage.RewriteQuery = chatManage.Query
// Get conversation history
history, err := p.messageService.GetRecentMessagesBySession(ctx, chatManage.SessionID, 20)
if err != nil {
logger.Errorf(ctx, "Failed to get conversation history, session_id: %s, error: %v", chatManage.SessionID, err)
}
// Convert historical messages to conversation history structure
historyMap := make(map[string]*types.History)
// Process historical messages, grouped by requestID
for _, message := range history {
history, ok := historyMap[message.RequestID]
if !ok {
history = &types.History{}
}
if message.Role == "user" {
// User message as query
history.Query = message.Content
history.CreateAt = message.CreatedAt
} else {
// System message as answer, while removing thinking process
history.Answer = reg.ReplaceAllString(message.Content, "")
history.KnowledgeReferences = message.KnowledgeReferences
}
historyMap[message.RequestID] = history
}
// Convert to list and filter incomplete conversations
historyList := make([]*types.History, 0)
for _, history := range historyMap {
if history.Answer != "" && history.Query != "" {
historyList = append(historyList, history)
}
}
// Sort by time, keep the most recent conversations
sort.Slice(historyList, func(i, j int) bool {
return historyList[i].CreateAt.After(historyList[j].CreateAt)
})
// Limit the number of historical records
if len(historyList) > p.config.Conversation.MaxRounds {
historyList = historyList[:p.config.Conversation.MaxRounds]
}
// Reverse to chronological order
slices.Reverse(historyList)
chatManage.History = historyList
userTmpl, err := template.New("rewriteContent").Parse(p.config.Conversation.RewritePromptUser)
if err != nil {
logger.Errorf(ctx, "Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
systemTmpl, err := template.New("rewriteContent").Parse(p.config.Conversation.RewritePromptSystem)
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
currentTime := time.Now().Format("2006-01-02 15:04:05")
var userContent, systemContent bytes.Buffer
err = userTmpl.Execute(&userContent, map[string]interface{}{
"Query": chatManage.Query,
"CurrentTime": currentTime,
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
"Conversation": historyList,
})
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
err = systemTmpl.Execute(&systemContent, map[string]interface{}{
"Query": chatManage.Query,
"CurrentTime": currentTime,
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
"Conversation": historyList,
})
if err != nil {
logger.Errorf(ctx, "Failed to execute template, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get model, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
// Call model to rewrite query
thinking := false
response, err := rewriteModel.Chat(ctx, []chat.Message{
{
Role: "system",
Content: systemContent.String(),
},
{
Role: "user",
Content: userContent.String(),
},
}, &chat.ChatOptions{
Temperature: 0.3,
MaxCompletionTokens: 50,
Thinking: &thinking,
})
if err != nil {
logger.Errorf(ctx, "Failed to execute model, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
}
// Update rewritten query
chatManage.RewriteQuery = response.Content
logger.GetLogger(ctx).Infof("Rewritten query, session_id: %s, rewrite_query: %s",
chatManage.SessionID, chatManage.RewriteQuery)
return next()
}
@@ -0,0 +1,124 @@
package chatpipline
import (
"context"
"strings"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginSearch implements search functionality for chat pipeline
type PluginSearch struct {
knowledgeBaseService interfaces.KnowledgeBaseService
modelService interfaces.ModelService
config *config.Config
}
func NewPluginSearch(eventManager *EventManager,
knowledgeBaseService interfaces.KnowledgeBaseService,
modelService interfaces.ModelService,
config *config.Config,
) *PluginSearch {
res := &PluginSearch{
knowledgeBaseService: knowledgeBaseService,
modelService: modelService,
config: config,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginSearch) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_SEARCH}
}
// OnEvent handles search events in the chat pipeline
func (p *PluginSearch) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Prepare search parameters
searchParams := types.SearchParams{
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
VectorThreshold: chatManage.VectorThreshold,
KeywordThreshold: chatManage.KeywordThreshold,
MatchCount: chatManage.EmbeddingTopK,
}
logger.Infof(ctx, "Search parameters: %v", searchParams)
// Perform initial hybrid search
searchResults, err := p.knowledgeBaseService.HybridSearch(ctx, chatManage.KnowledgeBaseID, searchParams)
logger.Infof(ctx, "Search results count: %d, error: %v", len(searchResults), err)
if err != nil {
return ErrSearch.WithError(err)
}
chatManage.SearchResult = searchResults
logger.Infof(ctx, "Search result count: %d", len(chatManage.SearchResult))
// Add relevant results from chat history
historyResult := p.getSearchResultFromHistory(chatManage)
if historyResult != nil {
logger.Infof(ctx, "Add history result, result count: %d", len(historyResult))
chatManage.SearchResult = append(chatManage.SearchResult, historyResult...)
}
// Try search with processed query if different from rewrite query
if chatManage.RewriteQuery != chatManage.ProcessedQuery {
searchParams.QueryText = strings.TrimSpace(chatManage.ProcessedQuery)
searchResults, err = p.knowledgeBaseService.HybridSearch(ctx, chatManage.KnowledgeBaseID, searchParams)
logger.Infof(ctx, "Search by processed query: %s, results count: %d, error: %v",
searchParams.QueryText, len(searchResults), err,
)
if err != nil {
return ErrSearch.WithError(err)
}
chatManage.SearchResult = append(chatManage.SearchResult, searchResults...)
}
// remove duplicate results
chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult)
// Return if we have results
if len(chatManage.SearchResult) != 0 {
logger.Infof(
ctx,
"Get search results, count: %d, session_id: %s",
len(chatManage.SearchResult), chatManage.SessionID,
)
return next()
}
logger.Infof(ctx, "No search result, session_id: %s", chatManage.SessionID)
return ErrSearchNothing
}
// getSearchResultFromHistory retrieves relevant knowledge references from chat history
func (p *PluginSearch) getSearchResultFromHistory(chatManage *types.ChatManage) []*types.SearchResult {
if len(chatManage.History) == 0 {
return nil
}
// Search history in reverse chronological order
for i := len(chatManage.History) - 1; i >= 0; i-- {
if len(chatManage.History[i].KnowledgeReferences) > 0 {
// Mark all references as history matches
for _, reference := range chatManage.History[i].KnowledgeReferences {
reference.MatchType = types.MatchTypeHistory
}
return chatManage.History[i].KnowledgeReferences
}
}
return nil
}
func removeDuplicateResults(results []*types.SearchResult) []*types.SearchResult {
seen := make(map[string]bool)
var uniqueResults []*types.SearchResult
for _, result := range results {
if !seen[result.ID] {
seen[result.ID] = true
uniqueResults = append(uniqueResults, result)
}
}
return uniqueResults
}
@@ -0,0 +1,84 @@
package chatpipline
import (
"context"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginStreamFilter implements stream filtering functionality for chat pipeline
type PluginStreamFilter struct{}
// NewPluginStreamFilter creates a new stream filter plugin instance
func NewPluginStreamFilter(eventManager *EventManager) *PluginStreamFilter {
res := &PluginStreamFilter{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginStreamFilter) ActivationEvents() []types.EventType {
return []types.EventType{types.STREAM_FILTER}
}
// OnEvent handles stream filtering events in the chat pipeline
func (p *PluginStreamFilter) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting stream filter")
logger.Info(ctx, "Creating new stream channel")
// Create new stream channel and replace the original one
oldStream := chatManage.ResponseChan
newStream := make(chan types.StreamResponse)
chatManage.ResponseChan = newStream
// Initialize response builder and check if no-match prefix filtering is needed
responseBuilder := &strings.Builder{}
matchNoMatchBuilderPrefix := chatManage.SummaryConfig.NoMatchPrefix != ""
if matchNoMatchBuilderPrefix {
logger.Infof(ctx, "Using no match prefix filter: %s", chatManage.SummaryConfig.NoMatchPrefix)
}
// Start goroutine to filter the stream
go func() {
logger.Info(ctx, "Starting stream filter goroutine")
for resp := range oldStream {
// Accumulate answer content
if resp.ResponseType == types.ResponseTypeAnswer {
responseBuilder.WriteString(resp.Content)
}
// Skip filtering if no prefix matching is required
if !matchNoMatchBuilderPrefix {
newStream <- resp
continue
}
// Check if content matches the no-match prefix
if !strings.HasPrefix(chatManage.SummaryConfig.NoMatchPrefix, responseBuilder.String()) {
resp.Content = responseBuilder.String()
newStream <- resp
logger.Info(
ctx, "Content does not match no-match prefix, passing through, content: ",
responseBuilder.String(),
)
matchNoMatchBuilderPrefix = false
}
}
// Handle NO_MATCH case when stream ends
if matchNoMatchBuilderPrefix {
logger.Info(ctx, "Content matches no-match prefix, using fallback response")
newStream <- NewFallback(ctx, chatManage.FallbackResponse)
}
logger.Info(ctx, "Stream filter completed, closing new stream")
close(newStream)
}()
logger.Info(ctx, "Stream filter initialized")
return next()
}
@@ -0,0 +1,270 @@
package chatpipline
import (
"context"
"encoding/json"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/types"
"go.opentelemetry.io/otel/attribute"
)
// PluginTracing implements tracing functionality for chat pipeline events
type PluginTracing struct{}
// NewPluginTracing creates a new tracing plugin instance
func NewPluginTracing(eventManager *EventManager) *PluginTracing {
res := &PluginTracing{}
eventManager.Register(res)
return res
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginTracing) ActivationEvents() []types.EventType {
return []types.EventType{
types.CHUNK_SEARCH,
types.CHUNK_RERANK,
types.CHUNK_MERGE,
types.INTO_CHAT_MESSAGE,
types.CHAT_COMPLETION,
types.CHAT_COMPLETION_STREAM,
types.FILTER_TOP_K,
types.REWRITE_QUERY,
types.PREPROCESS_QUERY,
}
}
// OnEvent handles incoming events and routes them to the appropriate tracing handler based on event type.
// It acts as the central dispatcher for all tracing-related events in the chat pipeline.
//
// Parameters:
// - ctx: context.Context for request-scoped values, cancellation signals, and deadlines
// - eventType: the type of event being processed (e.g., CHUNK_SEARCH, CHAT_COMPLETION)
// - chatManage: contains all the chat-related data and state for the current request
// - next: callback function to continue processing in the pipeline
//
// Returns:
// - *PluginError: error if any occurred during processing, or nil if successful
func (p *PluginTracing) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
switch eventType {
case types.CHUNK_SEARCH:
return p.Search(ctx, eventType, chatManage, next)
case types.CHUNK_RERANK:
return p.Rerank(ctx, eventType, chatManage, next)
case types.CHUNK_MERGE:
return p.Merge(ctx, eventType, chatManage, next)
case types.INTO_CHAT_MESSAGE:
return p.IntoChatMessage(ctx, eventType, chatManage, next)
case types.CHAT_COMPLETION:
return p.ChatCompletion(ctx, eventType, chatManage, next)
case types.CHAT_COMPLETION_STREAM:
return p.ChatCompletionStream(ctx, eventType, chatManage, next)
case types.FILTER_TOP_K:
return p.FilterTopK(ctx, eventType, chatManage, next)
case types.REWRITE_QUERY:
return p.RewriteQuery(ctx, eventType, chatManage, next)
case types.PREPROCESS_QUERY:
return p.PreprocessQuery(ctx, eventType, chatManage, next)
}
return next()
}
// Search traces search operations in the chat pipeline
func (p *PluginTracing) Search(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.Search")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
attribute.Float64("vector_threshold", chatManage.VectorThreshold),
attribute.Float64("keyword_threshold", chatManage.KeywordThreshold),
attribute.Int("match_count", chatManage.EmbeddingTopK),
)
err := next()
searchResultJson, _ := json.Marshal(chatManage.SearchResult)
span.SetAttributes(
attribute.String("hybrid_search", string(searchResultJson)),
attribute.String("processed_query", chatManage.ProcessedQuery),
)
return err
}
// Rerank traces rerank operations in the chat pipeline
func (p *PluginTracing) Rerank(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.Rerank")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
attribute.Int("passages_count", len(chatManage.SearchResult)),
attribute.String("rerank_model_id", chatManage.RerankModelID),
attribute.Float64("rerank_filter_threshold", chatManage.RerankThreshold),
attribute.Int("rerank_filter_topk", chatManage.RerankTopK),
)
err := next()
resultJson, _ := json.Marshal(chatManage.RerankResult)
span.SetAttributes(
attribute.Int("rerank_resp_count", len(chatManage.RerankResult)),
attribute.String("rerank_resp_results", string(resultJson)),
)
return err
}
// Merge traces merge operations in the chat pipeline
func (p *PluginTracing) Merge(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.Merge")
defer span.End()
span.SetAttributes(
attribute.Int("search_results_count", len(chatManage.SearchResult)),
attribute.Int("rerank_results_count", len(chatManage.RerankResult)),
)
err := next()
mergeResultJson, _ := json.Marshal(chatManage.MergeResult)
span.SetAttributes(
attribute.Int("merge_results_count", len(chatManage.MergeResult)),
attribute.String("merge_results", string(mergeResultJson)),
)
return err
}
// IntoChatMessage traces message conversion operations
func (p *PluginTracing) IntoChatMessage(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.IntoChatMessage")
defer span.End()
span.SetAttributes(
attribute.Int("search_results_count", len(chatManage.SearchResult)),
attribute.Int("rerank_results_count", len(chatManage.RerankResult)),
attribute.Int("merge_results_count", len(chatManage.MergeResult)),
)
err := next()
span.SetAttributes(attribute.Int("generated_content_length", len(chatManage.UserContent)))
return err
}
// ChatCompletion traces chat completion operations
func (p *PluginTracing) ChatCompletion(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.ChatCompletion")
defer span.End()
span.SetAttributes(
attribute.String("model_id", chatManage.ChatModelID),
attribute.String("system_prompt", chatManage.SummaryConfig.Prompt),
attribute.String("user_prompt", chatManage.UserContent),
attribute.Int("total_references", len(chatManage.RerankResult)),
)
err := next()
span.SetAttributes(
attribute.String("chat_response", chatManage.ChatResponse.Content),
attribute.Int("chat_response_tokens", chatManage.ChatResponse.Usage.TotalTokens),
attribute.Int("chat_response_prompt_tokens", chatManage.ChatResponse.Usage.PromptTokens),
attribute.Int("chat_response_completion_tokens", chatManage.ChatResponse.Usage.CompletionTokens),
)
return err
}
// ChatCompletionStream traces streaming chat completion operations
func (p *PluginTracing) ChatCompletionStream(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
ctx, span := tracing.ContextWithSpan(ctx, "PluginTracing.ChatCompletionStream")
startTime := time.Now()
span.SetAttributes(
attribute.String("model_id", chatManage.ChatModelID),
attribute.String("system_prompt", chatManage.SummaryConfig.Prompt),
attribute.String("user_prompt", chatManage.UserContent),
attribute.Int("total_references", len(chatManage.RerankResult)),
)
responseBuilder := &strings.Builder{}
oldStream := chatManage.ResponseChan
newStream := make(chan types.StreamResponse)
chatManage.ResponseChan = newStream
go func(ctx context.Context) {
for resp := range oldStream {
if resp.ResponseType == types.ResponseTypeAnswer {
responseBuilder.WriteString(resp.Content)
}
newStream <- resp
}
elapsedMS := time.Since(startTime).Milliseconds()
span.SetAttributes(
attribute.Bool("chat_completion_success", true),
attribute.Int64("response_time_ms", elapsedMS),
attribute.String("chat_response", responseBuilder.String()),
attribute.Int("final_response_length", responseBuilder.Len()),
attribute.Float64("tokens_per_second", float64(responseBuilder.Len())/float64(elapsedMS)*1000),
)
span.End()
close(newStream)
}(ctx)
return next()
}
// FilterTopK traces filtering operations in the chat pipeline
func (p *PluginTracing) FilterTopK(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.FilterTopK")
defer span.End()
span.SetAttributes(
attribute.Int("before_filter_search_results_count", len(chatManage.SearchResult)),
attribute.Int("before_filter_rerank_results_count", len(chatManage.RerankResult)),
attribute.Int("before_filter_merge_results_count", len(chatManage.MergeResult)),
)
err := next()
span.SetAttributes(
attribute.Int("after_filter_search_results_count", len(chatManage.SearchResult)),
attribute.Int("after_filter_rerank_results_count", len(chatManage.RerankResult)),
attribute.Int("after_filter_merge_results_count", len(chatManage.MergeResult)),
)
return err
}
// RewriteQuery traces query rewriting operations
func (p *PluginTracing) RewriteQuery(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.RewriteQuery")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
)
err := next()
span.SetAttributes(
attribute.String("rewrite_query", chatManage.RewriteQuery),
)
return err
}
// PreprocessQuery traces query preprocessing operations
func (p *PluginTracing) PreprocessQuery(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
_, span := tracing.ContextWithSpan(ctx, "PluginTracing.PreprocessQuery")
defer span.End()
span.SetAttributes(
attribute.String("query", chatManage.Query),
)
err := next()
span.SetAttributes(
attribute.String("processed_query", chatManage.ProcessedQuery),
)
return err
}
+278
View File
@@ -0,0 +1,278 @@
// Package service provides business logic implementations for WeKnora application
// This package contains service layer implementations that coordinate between
// repositories and handlers, applying business rules and transaction management
package service
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// chunkService implements the ChunkService interface
// It provides operations for managing document chunks in the knowledge base
// Chunks are segments of documents that have been processed and prepared for indexing
type chunkService struct {
chunkRepository interfaces.ChunkRepository // Repository for chunk data persistence
kbRepository interfaces.KnowledgeBaseRepository
modelService interfaces.ModelService
}
// NewChunkService creates a new chunk service
// It initializes a service with the provided chunk repository
// Parameters:
// - chunkRepository: Repository for chunk operations
//
// Returns:
// - interfaces.ChunkService: Initialized chunk service implementation
func NewChunkService(
chunkRepository interfaces.ChunkRepository,
kbRepository interfaces.KnowledgeBaseRepository,
modelService interfaces.ModelService,
) interfaces.ChunkService {
return &chunkService{
chunkRepository: chunkRepository,
kbRepository: kbRepository,
modelService: modelService,
}
}
// CreateChunks creates multiple chunks
// This method persists a batch of document chunks to the repository
// Parameters:
// - ctx: Context with authentication and request information
// - chunks: Slice of document chunks to create
//
// Returns:
// - error: Any error encountered during chunk creation
func (s *chunkService) CreateChunks(ctx context.Context, chunks []*types.Chunk) error {
logger.Info(ctx, "Start creating chunks")
logger.Infof(ctx, "Creating %d chunks", len(chunks))
err := s.chunkRepository.CreateChunks(ctx, chunks)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"chunk_count": len(chunks),
})
return err
}
logger.Info(ctx, "Chunks created successfully")
return nil
}
// GetChunkByID retrieves a chunk by its ID
// This method fetches a specific chunk using its ID and validates tenant access
// Parameters:
// - ctx: Context with authentication and request information
// - knowledgeID: ID of the knowledge document containing the chunk
// - id: ID of the chunk to retrieve
//
// Returns:
// - *types.Chunk: Retrieved chunk if found
// - error: Any error encountered during retrieval
func (s *chunkService) GetChunkByID(ctx context.Context, knowledgeID string, id string) (*types.Chunk, error) {
logger.Info(ctx, "Start getting chunk by ID")
logger.Infof(ctx, "Getting chunk, ID: %s, knowledge ID: %s", id, knowledgeID)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
chunk, err := s.chunkRepository.GetChunkByID(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"chunk_id": id,
"knowledge_id": knowledgeID,
"tenant_id": tenantID,
})
return nil, err
}
logger.Info(ctx, "Chunk retrieved successfully")
return chunk, nil
}
// ListChunksByKnowledgeID lists all chunks for a knowledge ID
// This method retrieves all chunks belonging to a specific knowledge document
// Parameters:
// - ctx: Context with authentication and request information
// - knowledgeID: ID of the knowledge document
//
// Returns:
// - []*types.Chunk: List of chunks belonging to the knowledge document
// - error: Any error encountered during retrieval
func (s *chunkService) ListChunksByKnowledgeID(ctx context.Context, knowledgeID string) ([]*types.Chunk, error) {
logger.Info(ctx, "Start listing chunks by knowledge ID")
logger.Infof(ctx, "Knowledge ID: %s", knowledgeID)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
chunks, err := s.chunkRepository.ListChunksByKnowledgeID(ctx, tenantID, knowledgeID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": knowledgeID,
"tenant_id": tenantID,
})
return nil, err
}
logger.Infof(ctx, "Retrieved %d chunks successfully", len(chunks))
return chunks, nil
}
// ListPagedChunksByKnowledgeID lists chunks for a knowledge ID with pagination
// This method retrieves chunks with pagination support for better performance with large datasets
// Parameters:
// - ctx: Context with authentication and request information
// - knowledgeID: ID of the knowledge document
// - page: Pagination parameters including page number and page size
//
// Returns:
// - *types.PageResult: Paginated result containing chunks and pagination metadata
// - error: Any error encountered during retrieval
func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context,
knowledgeID string, page *types.Pagination,
) (*types.PageResult, error) {
logger.Info(ctx, "Start listing paged chunks by knowledge ID")
logger.Infof(ctx, "Knowledge ID: %s, page: %d, page size: %d", knowledgeID, page.Page, page.PageSize)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
chunkType := []types.ChunkType{types.ChunkTypeText}
chunks, total, err := s.chunkRepository.ListPagedChunksByKnowledgeID(ctx, tenantID, knowledgeID, page, chunkType)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": knowledgeID,
"tenant_id": tenantID,
"page": page.Page,
"page_size": page.PageSize,
})
return nil, err
}
logger.Infof(ctx, "Retrieved %d chunks out of %d total chunks", len(chunks), total)
return types.NewPageResult(total, page, chunks), nil
}
// updateChunk updates a chunk
// This method updates an existing chunk in the repository
// Parameters:
// - ctx: Context with authentication and request information
// - chunk: Chunk with updated fields
//
// Returns:
// - error: Any error encountered during update
//
// This method handles the actual update logic for a chunk, including updating the vector database representation
func (s *chunkService) UpdateChunk(ctx context.Context, chunk *types.Chunk) error {
logger.Infof(ctx, "Updating chunk, ID: %s, knowledge ID: %s", chunk.ID, chunk.KnowledgeID)
// Update the chunk in the repository
err := s.chunkRepository.UpdateChunk(ctx, chunk)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"chunk_id": chunk.ID,
"knowledge_id": chunk.KnowledgeID,
})
return err
}
logger.Info(ctx, "Chunk updated successfully")
return nil
}
// DeleteChunk deletes a chunk by ID
// This method removes a specific chunk from the repository
// Parameters:
// - ctx: Context with authentication and request information
// - id: ID of the chunk to delete
//
// Returns:
// - error: Any error encountered during deletion
func (s *chunkService) DeleteChunk(ctx context.Context, id string) error {
logger.Info(ctx, "Start deleting chunk")
logger.Infof(ctx, "Deleting chunk, ID: %s", id)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
err := s.chunkRepository.DeleteChunk(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"chunk_id": id,
"tenant_id": tenantID,
})
return err
}
logger.Info(ctx, "Chunk deleted successfully")
return nil
}
// DeleteChunksByKnowledgeID deletes all chunks for a knowledge ID
// This method removes all chunks belonging to a specific knowledge document
// Parameters:
// - ctx: Context with authentication and request information
// - knowledgeID: ID of the knowledge document
//
// Returns:
// - error: Any error encountered during bulk deletion
func (s *chunkService) DeleteChunksByKnowledgeID(ctx context.Context, knowledgeID string) error {
logger.Info(ctx, "Start deleting all chunks by knowledge ID")
logger.Infof(ctx, "Knowledge ID: %s", knowledgeID)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
err := s.chunkRepository.DeleteChunksByKnowledgeID(ctx, tenantID, knowledgeID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": knowledgeID,
"tenant_id": tenantID,
})
return err
}
logger.Info(ctx, "All chunks under knowledge deleted successfully")
return nil
}
func (s *chunkService) DeleteByKnowledgeList(ctx context.Context, ids []string) error {
logger.Info(ctx, "Start deleting all chunks by knowledge IDs")
logger.Infof(ctx, "Knowledge IDs: %v", ids)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
err := s.chunkRepository.DeleteByKnowledgeList(ctx, tenantID, ids)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": ids,
"tenant_id": tenantID,
})
return err
}
logger.Info(ctx, "All chunks under knowledge deleted successfully")
return nil
}
func (s *chunkService) ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error) {
logger.Info(ctx, "Start listing chunk by parent ID")
logger.Infof(ctx, "Parent ID: %s", parentID)
chunks, err := s.chunkRepository.ListChunkByParentID(ctx, tenantID, parentID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"parent_id": parentID,
"tenant_id": tenantID,
})
return nil, err
}
logger.Info(ctx, "Chunk listed successfully")
return chunks, nil
}
+243
View File
@@ -0,0 +1,243 @@
package service
import (
"context"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/parquet-go/parquet-go"
)
// DatasetService provides operations for working with datasets
type DatasetService struct{}
// NewDatasetService creates a new DatasetService instance
func NewDatasetService() interfaces.DatasetService {
return &DatasetService{}
}
// TextInfo represents text data with ID in parquet format
type TextInfo struct {
ID int64 `parquet:"id"` // Unique identifier
Text string `parquet:"text"` // Text content
}
// RelsInfo represents question-passage relations in parquet format
type RelsInfo struct {
QID int64 `parquet:"qid"` // Question ID
PID int64 `parquet:"pid"` // Passage ID
}
// QaInfo represents question-answer relations in parquet format
type QaInfo struct {
QID int64 `parquet:"qid"` // Question ID
AID int64 `parquet:"aid"` // Answer ID
}
// GetDatasetByID retrieves QA pairs from dataset by ID
func (d *DatasetService) GetDatasetByID(ctx context.Context, datasetID string) ([]*types.QAPair, error) {
logger.Info(ctx, "Start getting dataset by ID")
logger.Infof(ctx, "Getting dataset with ID: %s", datasetID)
dataset := DefaultDataset()
dataset.PrintStats(ctx)
qaPairs := dataset.Iterate()
logger.Infof(ctx, "Retrieved %d QA pairs from dataset", len(qaPairs))
return qaPairs, nil
}
// DefaultDataset loads and initializes the default dataset from parquet files
func DefaultDataset() dataset {
datasetDir := "./dataset/samples"
queries, err := loadParquet[TextInfo](fmt.Sprintf("%s/queries.parquet", datasetDir))
if err != nil {
panic(err)
}
corpus, err := loadParquet[TextInfo](fmt.Sprintf("%s/corpus.parquet", datasetDir))
if err != nil {
panic(err)
}
answers, err := loadParquet[TextInfo](fmt.Sprintf("%s/answers.parquet", datasetDir))
if err != nil {
panic(err)
}
qrels, err := loadParquet[RelsInfo](fmt.Sprintf("%s/qrels.parquet", datasetDir))
if err != nil {
panic(err)
}
qas, err := loadParquet[QaInfo](fmt.Sprintf("%s/qas.parquet", datasetDir))
if err != nil {
panic(err)
}
res := dataset{
queries: make(map[int64]string), // qid -> question text
corpus: make(map[int64]string), // pid -> passage text
answers: make(map[int64]string), // aid -> answer text
qrels: make(map[int64][]int64), // qid -> list of pid
qas: make(map[int64]int64), // qid -> aid
}
for _, qi := range queries {
res.queries[qi.ID] = qi.Text
}
for _, ci := range corpus {
res.corpus[ci.ID] = ci.Text
}
for _, ai := range answers {
res.answers[ai.ID] = ai.Text
}
for _, ri := range qrels {
res.qrels[ri.QID] = append(res.qrels[ri.QID], ri.PID)
}
for _, qi := range qas {
res.qas[qi.QID] = qi.AID
}
return res
}
// dataset represents the in-memory dataset structure
type dataset struct {
queries map[int64]string // qid -> question text
corpus map[int64]string // pid -> passage text
answers map[int64]string // aid -> answer text
qrels map[int64][]int64 // qid -> list of related pids
qas map[int64]int64 // qid -> aid
}
// Iterate generates QA pairs from the dataset
func (d *dataset) Iterate() []*types.QAPair {
var pairs []*types.QAPair
for qid, question := range d.queries {
// Get answer info
aid, hasAnswer := d.qas[qid]
answer := ""
if hasAnswer {
answer = d.answers[aid]
}
// Get related passages
pids := d.qrels[qid]
var pidStr []int
for _, pid := range pids {
pidStr = append(pidStr, int(pid))
}
var passages []string
for _, pid := range pids {
passages = append(passages, d.corpus[pid])
}
pairs = append(pairs, &types.QAPair{
QID: int(qid),
Question: question,
PIDs: pidStr,
Passages: passages,
AID: int(aid),
Answer: answer,
})
}
return pairs
}
// GetContextForQID retrieves context passages for a given question ID
func (d *dataset) GetContextForQID(qid int64) ([]string, error) {
pids, ok := d.qrels[qid]
if !ok {
return nil, errors.New("question ID not found")
}
var contextParts []string
for _, pid := range pids {
if text, exists := d.corpus[pid]; exists {
contextParts = append(contextParts, text)
}
}
return contextParts, nil
}
// PrintStats prints dataset statistics to the logger
func (d *dataset) PrintStats(ctx context.Context) {
logger.Infof(ctx, "QA System Statistics:")
logger.Infof(ctx, "- Total queries: %d", len(d.queries))
logger.Infof(ctx, "- Total corpus passages: %d", len(d.corpus))
logger.Infof(ctx, "- Total answers: %d", len(d.answers))
// Calculate average passages per query
totalRelations := 0
for _, pids := range d.qrels {
totalRelations += len(pids)
}
avgPassages := float64(totalRelations) / float64(len(d.qrels))
logger.Infof(ctx, "- Average passages per query: %.2f", avgPassages)
// Calculate coverage
coveredQueries := len(d.qas)
coverage := float64(coveredQueries) / float64(len(d.queries)) * 100
logger.Infof(ctx, "- Answer coverage: %.2f%% (%d/%d)", coverage, coveredQueries, len(d.queries))
}
// PrintRandomQA prints a random question with its related passages and answer
func (d *dataset) PrintRandomQA() error {
// Get a random qid
var qid int64
for k := range d.qas {
qid = k
break
}
if qid == 0 {
return errors.New("no questions available")
}
// Get question text
question, ok := d.queries[qid]
if !ok {
return fmt.Errorf("question %d not found", qid)
}
// Get answer info
aid, ok := d.qas[qid]
if !ok {
return fmt.Errorf("answer for question %d not found", qid)
}
answer, ok := d.answers[aid]
if !ok {
return fmt.Errorf("answer %d not found", aid)
}
// Print formatted QA
fmt.Println("===== Random QA =====")
fmt.Printf("QID: %d\n", qid)
fmt.Printf("Question: %s\n", question)
// Print passages if available
if pids, exists := d.qrels[qid]; exists && len(pids) > 0 {
fmt.Println("\nRelated passages:")
for i, pid := range pids {
if text, exists := d.corpus[pid]; exists {
fmt.Printf("\nPassage %d (PID: %d):\n%s\n", i+1, pid, text)
}
}
} else {
fmt.Println("\nNo related passages found")
}
// Print answer
fmt.Printf("\nAnswer (AID: %d):\n%s\n", aid, answer)
return nil
}
// loadParquet loads data from parquet file into specified type
func loadParquet[T any](filePath string) ([]T, error) {
rows, err := parquet.ReadFile[T](filePath)
if err != nil {
return nil, err
}
return rows, nil
}
+407
View File
@@ -0,0 +1,407 @@
package service
import (
"context"
"errors"
"runtime"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
)
/*
corpus: pid -> content
queries: qid -> content
answers: aid -> content
qrels: qid -> pid
arels: qid -> aid
*/
// EvaluationService handles evaluation tasks for knowledge base and chat models
type EvaluationService struct {
config *config.Config // Application configuration
dataset interfaces.DatasetService // Service for dataset operations
knowledgeBaseService interfaces.KnowledgeBaseService // Service for knowledge base operations
knowledgeService interfaces.KnowledgeService // Service for knowledge operations
sessionService interfaces.SessionService // Service for chat sessions
testData *TestDataService // Service for test data
evaluationMemoryStorage *evaluationMemoryStorage // In-memory storage for evaluation tasks
}
func NewEvaluationService(
config *config.Config,
dataset interfaces.DatasetService,
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
sessionService interfaces.SessionService,
testData *TestDataService,
) interfaces.EvaluationService {
evaluationMemoryStorage := newEvaluationMemoryStorage()
return &EvaluationService{
config: config,
dataset: dataset,
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
sessionService: sessionService,
testData: testData,
evaluationMemoryStorage: evaluationMemoryStorage,
}
}
// evaluationMemoryStorage stores evaluation tasks in memory with thread-safe access
type evaluationMemoryStorage struct {
store map[string]*types.EvaluationDetail // Map of taskID to evaluation details
mu *sync.RWMutex // Read-write lock for concurrent access
}
func newEvaluationMemoryStorage() *evaluationMemoryStorage {
res := &evaluationMemoryStorage{
store: make(map[string]*types.EvaluationDetail),
mu: &sync.RWMutex{},
}
return res
}
func (e *evaluationMemoryStorage) register(params *types.EvaluationDetail) {
e.mu.Lock()
defer e.mu.Unlock()
logger.Infof(context.Background(), "Registering evaluation task: %s", params.Task.ID)
e.store[params.Task.ID] = params
}
func (e *evaluationMemoryStorage) get(taskID string) (*types.EvaluationDetail, error) {
e.mu.RLock()
defer e.mu.RUnlock()
logger.Infof(context.Background(), "Getting evaluation task: %s", taskID)
res, ok := e.store[taskID]
if !ok {
return nil, errors.New("task not found")
}
return res, nil
}
func (e *evaluationMemoryStorage) update(taskID string, fn func(params *types.EvaluationDetail)) error {
e.mu.Lock()
defer e.mu.Unlock()
params, ok := e.store[taskID]
if !ok {
return errors.New("task not found")
}
fn(params)
return nil
}
func (e *EvaluationService) EvaluationResult(ctx context.Context, taskID string) (*types.EvaluationDetail, error) {
logger.Info(ctx, "Start getting evaluation result")
logger.Infof(ctx, "Task ID: %s", taskID)
detail, err := e.evaluationMemoryStorage.get(taskID)
if err != nil {
logger.Errorf(ctx, "Failed to get evaluation task: %v", err)
return nil, err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(
ctx,
"Checking tenant ID match, task tenant ID: %d, current tenant ID: %d",
detail.Task.TenantID, tenantID,
)
if tenantID != detail.Task.TenantID {
logger.Error(ctx, "Tenant ID mismatch")
return nil, errors.New("tenant ID does not match")
}
logger.Info(ctx, "Evaluation result retrieved successfully")
return detail, nil
}
// Evaluation starts a new evaluation task with given parameters
// datasetID: ID of the dataset to evaluate against
// knowledgeBaseID: ID of the knowledge base to use (empty to create new)
// chatModelID: ID of the chat model to evaluate
// rerankModelID: ID of the rerank model to evaluate
func (e *EvaluationService) Evaluation(ctx context.Context,
datasetID string, knowledgeBaseID string, chatModelID string, rerankModelID string,
) (*types.EvaluationDetail, error) {
logger.Info(ctx, "Start evaluation")
logger.Infof(ctx, "Dataset ID: %s, Knowledge Base ID: %s, Chat Model ID: %s, Rerank Model ID: %s",
datasetID, knowledgeBaseID, chatModelID, rerankModelID)
// Get tenant ID from context for multi-tenancy support
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
// Handle knowledge base creation if not provided
if knowledgeBaseID == "" {
logger.Info(ctx, "No knowledge base ID provided, creating new knowledge base")
// Create new knowledge base with default evaluation settings
kb, err := e.knowledgeBaseService.CreateKnowledgeBase(ctx, &types.KnowledgeBase{
Name: "evaluation",
Description: "evaluation",
EmbeddingModelID: e.testData.EmbedModel.GetModelID(),
SummaryModelID: e.testData.LLMModel.GetModelID(),
})
if err != nil {
logger.Errorf(ctx, "Failed to create knowledge base: %v", err)
return nil, err
}
knowledgeBaseID = kb.ID
logger.Infof(ctx, "Created new knowledge base with ID: %s", knowledgeBaseID)
} else {
logger.Infof(ctx, "Using existing knowledge base ID: %s", knowledgeBaseID)
// Create evaluation-specific knowledge base based on existing one
kb, err := e.knowledgeBaseService.GetKnowledgeBaseByID(ctx, knowledgeBaseID)
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
return nil, err
}
kb, err = e.knowledgeBaseService.CreateKnowledgeBase(ctx, &types.KnowledgeBase{
Name: "evaluation",
Description: "evaluation",
EmbeddingModelID: kb.EmbeddingModelID,
SummaryModelID: kb.SummaryModelID,
})
if err != nil {
logger.Errorf(ctx, "Failed to create knowledge base: %v", err)
return nil, err
}
knowledgeBaseID = kb.ID
logger.Infof(ctx, "Created new knowledge base with ID: %s based on existing one", knowledgeBaseID)
}
// Set default values for optional parameters
if datasetID == "" {
datasetID = "default"
logger.Info(ctx, "Using default dataset")
}
if rerankModelID == "" {
rerankModelID = e.testData.RerankModel.GetModelID()
logger.Infof(ctx, "Using default rerank model: %s", rerankModelID)
}
if chatModelID == "" {
chatModelID = e.testData.LLMModel.GetModelID()
logger.Infof(ctx, "Using default chat model: %s", chatModelID)
}
// Create evaluation task with unique ID
logger.Info(ctx, "Creating evaluation task")
taskID := uuid.New().String()
logger.Infof(ctx, "Generated task ID: %s", taskID)
// Prepare evaluation detail with all parameters
detail := &types.EvaluationDetail{
Task: &types.EvaluationTask{
ID: taskID,
TenantID: tenantID,
DatasetID: datasetID,
Status: types.EvaluationStatuePending,
StartTime: time.Now(),
},
Params: &types.ChatManage{
KnowledgeBaseID: knowledgeBaseID,
VectorThreshold: e.config.Conversation.VectorThreshold,
KeywordThreshold: e.config.Conversation.KeywordThreshold,
EmbeddingTopK: e.config.Conversation.EmbeddingTopK,
RerankModelID: rerankModelID,
RerankTopK: e.config.Conversation.RerankTopK,
RerankThreshold: e.config.Conversation.RerankThreshold,
ChatModelID: chatModelID,
SummaryConfig: types.SummaryConfig{
MaxTokens: e.config.Conversation.Summary.MaxTokens,
RepeatPenalty: e.config.Conversation.Summary.RepeatPenalty,
TopK: e.config.Conversation.Summary.TopK,
TopP: e.config.Conversation.Summary.TopP,
Prompt: e.config.Conversation.Summary.Prompt,
ContextTemplate: e.config.Conversation.Summary.ContextTemplate,
FrequencyPenalty: e.config.Conversation.Summary.FrequencyPenalty,
PresencePenalty: e.config.Conversation.Summary.PresencePenalty,
NoMatchPrefix: e.config.Conversation.Summary.NoMatchPrefix,
Temperature: e.config.Conversation.Summary.Temperature,
Seed: e.config.Conversation.Summary.Seed,
MaxCompletionTokens: e.config.Conversation.Summary.MaxCompletionTokens,
},
FallbackResponse: e.config.Conversation.FallbackResponse,
},
}
// Store evaluation task in memory storage
logger.Info(ctx, "Registering evaluation task")
e.evaluationMemoryStorage.register(detail)
// Start evaluation in background goroutine
logger.Info(ctx, "Starting evaluation in background")
go func() {
// Create new context with logger for background task
newCtx := logger.CloneContext(ctx)
logger.Infof(newCtx, "Background evaluation started for task ID: %s", taskID)
// Update task status to running
detail.Task.Status = types.EvaluationStatueRunning
logger.Info(newCtx, "Evaluation task status set to running")
// Execute actual evaluation
if err := e.EvalDataset(newCtx, detail); err != nil {
detail.Task.Status = types.EvaluationStatueFailed
detail.Task.ErrMsg = err.Error()
logger.Errorf(newCtx, "Evaluation task failed: %v, task ID: %s", err, taskID)
return
}
// Mark task as completed successfully
logger.Infof(newCtx, "Evaluation task completed successfully, task ID: %s", taskID)
detail.Task.Status = types.EvaluationStatueSuccess
}()
logger.Infof(ctx, "Evaluation task created successfully, task ID: %s", taskID)
return detail, nil
}
// EvalDataset performs the actual evaluation of a dataset
// Processes each QA pair in parallel and records metrics
func (e *EvaluationService) EvalDataset(ctx context.Context, detail *types.EvaluationDetail) error {
logger.Info(ctx, "Start evaluating dataset")
logger.Infof(ctx, "Task ID: %s, Dataset ID: %s", detail.Task.ID, detail.Task.DatasetID)
// Retrieve dataset from storage
dataset, err := e.dataset.GetDatasetByID(ctx, detail.Task.DatasetID)
if err != nil {
logger.Errorf(ctx, "Failed to get dataset: %v", err)
return err
}
logger.Infof(ctx, "Dataset retrieved successfully with %d QA pairs", len(dataset))
// Update total QA pairs count in task details
e.evaluationMemoryStorage.update(detail.Task.ID, func(params *types.EvaluationDetail) {
params.Task.Total = len(dataset)
logger.Infof(ctx, "Updated task total to %d QA pairs", params.Task.Total)
})
// Extract and organize passages from dataset
passages := getPassageList(dataset)
logger.Infof(ctx, "Creating knowledge from %d passages", len(passages))
// Create knowledge base from passages
knowledge, err := e.knowledgeService.CreateKnowledgeFromPassage(ctx, detail.Params.KnowledgeBaseID, passages)
if err != nil {
logger.Errorf(ctx, "Failed to create knowledge from passages: %v", err)
return err
}
logger.Infof(ctx, "Knowledge created successfully, ID: %s", knowledge.ID)
// Setup cleanup of temporary resources
defer func() {
logger.Infof(ctx, "Cleaning up resources - deleting knowledge: %s", knowledge.ID)
if err := e.knowledgeService.DeleteKnowledge(ctx, knowledge.ID); err != nil {
logger.Errorf(ctx, "Failed to delete knowledge: %v, knowledge ID: %s", err, knowledge.ID)
}
logger.Infof(ctx, "Cleaning up resources - deleting knowledge base: %s", detail.Params.KnowledgeBaseID)
if err := e.knowledgeBaseService.DeleteKnowledgeBase(ctx, detail.Params.KnowledgeBaseID); err != nil {
logger.Errorf(
ctx,
"Failed to delete knowledge base: %v, knowledge base ID: %s",
err, detail.Params.KnowledgeBaseID,
)
}
}()
// Initialize parallel evaluation metrics
var finished int
var mu sync.Mutex
var g errgroup.Group
metricHook := NewHookMetric(len(dataset))
// Set worker limit based on available CPUs
g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1))
logger.Infof(ctx, "Starting evaluation with %d parallel workers", max(runtime.GOMAXPROCS(0)-1, 1))
// Process each QA pair in parallel
for i, qaPair := range dataset {
qaPair := qaPair
i := i
g.Go(func() error {
logger.Infof(ctx, "Processing QA pair %d, question: %s", i, qaPair.Question)
// Prepare chat management parameters for this QA pair
chatManage := detail.Params.Clone()
chatManage.Query = qaPair.Question
// Execute knowledge QA pipeline
logger.Infof(ctx, "Running knowledge QA for question: %s", qaPair.Question)
err = e.sessionService.KnowledgeQAByEvent(ctx, chatManage, types.Pipline["rag"])
if err != nil {
logger.Errorf(ctx, "Failed to process question %d: %v", i, err)
return err
}
// Record evaluation metrics
logger.Infof(ctx, "Recording metrics for QA pair %d", i)
metricHook.recordInit(i)
metricHook.recordQaPair(i, qaPair)
metricHook.recordSearchResult(i, chatManage.SearchResult)
metricHook.recordRerankResult(i, chatManage.RerankResult)
metricHook.recordChatResponse(i, chatManage.ChatResponse)
metricHook.recordFinish(i)
// Update progress metrics
mu.Lock()
finished += 1
metricResult := metricHook.MetricResult()
mu.Unlock()
e.evaluationMemoryStorage.update(detail.Task.ID, func(params *types.EvaluationDetail) {
params.Metric = metricResult
params.Task.Finished = finished
logger.Infof(ctx, "Updated task progress: %d/%d completed", finished, params.Task.Total)
})
return nil
})
}
// Wait for all parallel evaluations to complete
logger.Info(ctx, "Waiting for all evaluation tasks to complete")
if err := g.Wait(); err != nil {
logger.Errorf(ctx, "Evaluation error: %v", err)
return err
}
// Final update of evaluation metrics
e.evaluationMemoryStorage.update(detail.Task.ID, func(params *types.EvaluationDetail) {
params.Metric = metricHook.MetricResult()
params.Task.Finished = finished
})
logger.Infof(ctx, "Dataset evaluation completed successfully, task ID: %s", detail.Task.ID)
return nil
}
// getPassageList extracts and organizes passages from QA pairs
// Returns a slice of passages indexed by their passage IDs
func getPassageList(dataset []*types.QAPair) []string {
pIDMap := make(map[int]string)
maxPID := 0
for _, qaPair := range dataset {
for i := 0; i < len(qaPair.PIDs); i++ {
pIDMap[qaPair.PIDs[i]] = qaPair.Passages[i]
maxPID = max(maxPID, qaPair.PIDs[i])
}
}
passages := make([]string, maxPID)
for i := 0; i < maxPID; i++ {
if _, ok := pIDMap[i]; ok {
passages[i] = pIDMap[i]
}
}
return passages
}
+83
View File
@@ -0,0 +1,83 @@
package file
import (
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"path/filepath"
"strings"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"github.com/tencentyun/cos-go-sdk-v5"
)
// cosFileService implements the FileService interface for Tencent Cloud COS
type cosFileService struct {
client *cos.Client
bucketURL string
cosPathPrefix string
}
// NewCosFileService creates a new COS file service instance
func NewCosFileService(appId, region, secretId, secretKey, cosPathPrefix string) (interfaces.FileService, error) {
bucketURL := fmt.Sprintf("https://%s.cos.%s.myqcloud.com", appId, region)
u, err := url.Parse(bucketURL)
if err != nil {
return nil, fmt.Errorf("failed to parse bucketURL: %w", err)
}
b := &cos.BaseURL{BucketURL: u}
client := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: secretId,
SecretKey: secretKey,
},
})
return &cosFileService{
client: client,
bucketURL: bucketURL,
cosPathPrefix: cosPathPrefix,
}, nil
}
// SaveFile saves a file to COS storage
// It generates a unique name for the file and organizes it by tenant and knowledge ID
func (s *cosFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
) (string, error) {
ext := filepath.Ext(file.Filename)
objectName := fmt.Sprintf("%s/%d/%s/%s%s", s.cosPathPrefix, tenantID, knowledgeID, uuid.New().String(), ext)
src, err := file.Open()
if err != nil {
return "", fmt.Errorf("failed to open file: %w", err)
}
defer src.Close()
_, err = s.client.Object.Put(ctx, objectName, src, nil)
if err != nil {
return "", fmt.Errorf("failed to upload file to COS: %w", err)
}
return fmt.Sprintf("https://%s/%s", s.bucketURL, objectName), nil
}
// GetFile retrieves a file from COS storage by its path URL
func (s *cosFileService) GetFile(ctx context.Context, filePathUrl string) (io.ReadCloser, error) {
objectName := strings.TrimPrefix(filePathUrl, s.bucketURL)
resp, err := s.client.Object.Get(ctx, objectName, nil)
if err != nil {
return nil, fmt.Errorf("failed to get file from COS: %w", err)
}
return resp.Body, nil
}
// DeleteFile removes a file from COS storage
func (s *cosFileService) DeleteFile(ctx context.Context, filePath string) error {
objectName := strings.TrimPrefix(filePath, s.bucketURL)
_, err := s.client.Object.Delete(ctx, objectName)
if err != nil {
return fmt.Errorf("failed to delete file: %w", err)
}
return nil
}
@@ -0,0 +1,38 @@
package file
import (
"context"
"errors"
"io"
"mime/multipart"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// DummyFileService is a no-op implementation of the FileService interface
// used for testing or when file storage is not required
type DummyFileService struct{}
// NewDummyFileService creates a new instance of DummyFileService
func NewDummyFileService() interfaces.FileService {
return &DummyFileService{}
}
// SaveFile pretends to save a file but just returns a random UUID
// This is useful for testing without actual file operations
func (s *DummyFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
) (string, error) {
return uuid.New().String(), nil
}
// GetFile always returns an error as dummy service doesn't store files
func (s *DummyFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
return nil, errors.New("not implemented")
}
// DeleteFile is a no-op operation that always succeeds
func (s *DummyFileService) DeleteFile(ctx context.Context, filePath string) error {
return nil
}
+111
View File
@@ -0,0 +1,111 @@
package file
import (
"context"
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// localFileService implements the FileService interface for local file system storage
type localFileService struct {
baseDir string // Base directory for file storage
}
// NewLocalFileService creates a new local file service instance
func NewLocalFileService(baseDir string) interfaces.FileService {
return &localFileService{
baseDir: baseDir,
}
}
// SaveFile stores an uploaded file to the local file system
// The file is stored in a directory structure: baseDir/tenantID/knowledgeID/filename
// Returns the full file path or an error if saving fails
func (s *localFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
) (string, error) {
logger.Info(ctx, "Starting to save file locally")
logger.Infof(ctx, "File information: name=%s, size=%d, tenant ID=%d, knowledge ID=%s",
file.Filename, file.Size, tenantID, knowledgeID)
// Create storage directory with tenant and knowledge ID
dir := filepath.Join(s.baseDir, fmt.Sprintf("%d", tenantID), knowledgeID)
logger.Infof(ctx, "Creating directory: %s", dir)
if err := os.MkdirAll(dir, 0o755); err != nil {
logger.Errorf(ctx, "Failed to create directory: %v", err)
return "", fmt.Errorf("failed to create directory: %w", err)
}
// Generate unique filename using timestamp
ext := filepath.Ext(file.Filename)
filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
filePath := filepath.Join(dir, filename)
logger.Infof(ctx, "Generated file path: %s", filePath)
// Open source file for reading
logger.Info(ctx, "Opening source file")
src, err := file.Open()
if err != nil {
logger.Errorf(ctx, "Failed to open source file: %v", err)
return "", fmt.Errorf("failed to open file: %w", err)
}
defer src.Close()
// Create destination file for writing
logger.Info(ctx, "Creating destination file")
dst, err := os.Create(filePath)
if err != nil {
logger.Errorf(ctx, "Failed to create destination file: %v", err)
return "", fmt.Errorf("failed to create file: %w", err)
}
defer dst.Close()
// Copy content from source to destination
logger.Info(ctx, "Copying file content")
if _, err := io.Copy(dst, src); err != nil {
logger.Errorf(ctx, "Failed to copy file content: %v", err)
return "", fmt.Errorf("failed to save file: %w", err)
}
logger.Infof(ctx, "File saved successfully: %s", filePath)
return filePath, nil
}
// GetFile retrieves a file from the local file system by its path
// Returns a ReadCloser for reading the file content
func (s *localFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
logger.Infof(ctx, "Getting file: %s", filePath)
// Open the file for reading
file, err := os.Open(filePath)
if err != nil {
logger.Errorf(ctx, "Failed to open file: %v", err)
return nil, fmt.Errorf("failed to open file: %w", err)
}
logger.Info(ctx, "File opened successfully")
return file, nil
}
// DeleteFile removes a file from the local file system
// Returns an error if deletion fails
func (s *localFileService) DeleteFile(ctx context.Context, filePath string) error {
logger.Infof(ctx, "Deleting file: %s", filePath)
// Remove the file
err := os.Remove(filePath)
if err != nil {
logger.Errorf(ctx, "Failed to delete file: %v", err)
return fmt.Errorf("failed to delete file: %w", err)
}
logger.Info(ctx, "File deleted successfully")
return nil
}
+126
View File
@@ -0,0 +1,126 @@
package file
import (
"context"
"fmt"
"io"
"mime/multipart"
"path/filepath"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// minioFileService MinIO file service implementation
type minioFileService struct {
client *minio.Client
bucketName string
}
// NewMinioFileService creates a MinIO file service
func NewMinioFileService(endpoint,
accessKeyID, secretAccessKey, bucketName string, useSSL bool) (interfaces.FileService, error) {
// Initialize MinIO client
client, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: useSSL,
})
if err != nil {
return nil, fmt.Errorf("failed to initialize MinIO client: %w", err)
}
// Check if bucket exists, create if not
exists, err := client.BucketExists(context.Background(), bucketName)
if err != nil {
return nil, fmt.Errorf("failed to check bucket: %w", err)
}
if !exists {
err = client.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{})
if err != nil {
return nil, fmt.Errorf("failed to create bucket: %w", err)
}
}
return &minioFileService{
client: client,
bucketName: bucketName,
}, nil
}
// SaveFile saves a file to MinIO
func (s *minioFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
) (string, error) {
// Generate object name
ext := filepath.Ext(file.Filename)
objectName := fmt.Sprintf("%d/%s/%s%s", tenantID, knowledgeID, uuid.New().String(), ext)
// Open file
src, err := file.Open()
if err != nil {
return "", fmt.Errorf("failed to open file: %w", err)
}
defer src.Close()
// Upload file to MinIO
_, err = s.client.PutObject(ctx, s.bucketName, objectName, src, file.Size, minio.PutObjectOptions{
ContentType: file.Header.Get("Content-Type"),
})
if err != nil {
return "", fmt.Errorf("failed to upload file to MinIO: %w", err)
}
// Return the complete path to the object
return fmt.Sprintf("minio://%s/%s", s.bucketName, objectName), nil
}
// GetFile gets a file from MinIO
func (s *minioFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
// Parse MinIO path
// Format: minio://bucketName/objectName
if len(filePath) < 9 || filePath[:8] != "minio://" {
return nil, fmt.Errorf("invalid MinIO file path: %s", filePath)
}
// Extract object name
objectName := filePath[9+len(s.bucketName):]
if objectName[0] == '/' {
objectName = objectName[1:]
}
// Get object
obj, err := s.client.GetObject(ctx, s.bucketName, objectName, minio.GetObjectOptions{})
if err != nil {
return nil, fmt.Errorf("failed to get file from MinIO: %w", err)
}
return obj, nil
}
// DeleteFile deletes a file
func (s *minioFileService) DeleteFile(ctx context.Context, filePath string) error {
// Parse MinIO path
// Format: minio://bucketName/objectName
if len(filePath) < 9 || filePath[:8] != "minio://" {
return fmt.Errorf("invalid MinIO file path: %s", filePath)
}
// Extract object name
objectName := filePath[9+len(s.bucketName):]
if objectName[0] == '/' {
objectName = objectName[1:]
}
// Delete object
err := s.client.RemoveObject(ctx, s.bucketName, objectName, minio.RemoveObjectOptions{
GovernanceBypass: true,
})
if err != nil {
return fmt.Errorf("failed to delete file: %w", err)
}
return nil
}
+995
View File
@@ -0,0 +1,995 @@
package service
import (
"context"
"encoding/json"
"fmt"
"math"
"slices"
"strings"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/utils"
"github.com/Tencent/WeKnora/internal/types"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
)
const (
// DefaultLLMTemperature Use low temperature for more deterministic results
DefaultLLMTemperature = 0.1
// PMIWeight Proportion of PMI in calculating relationship weight
PMIWeight = 0.6
// StrengthWeight Proportion of relationship strength in calculating relationship weight
StrengthWeight = 0.4
// IndirectRelationWeightDecay Decay coefficient for indirect relationship weights
IndirectRelationWeightDecay = 0.5
// MaxConcurrentEntityExtractions Maximum concurrency for entity extraction
MaxConcurrentEntityExtractions = 4
// MaxConcurrentRelationExtractions Maximum concurrency for relationship extraction
MaxConcurrentRelationExtractions = 4
// DefaultRelationBatchSize Default batch size for relationship extraction
DefaultRelationBatchSize = 5
// MinEntitiesForRelation Minimum number of entities required for relationship extraction
MinEntitiesForRelation = 2
// MinWeightValue Minimum weight value to avoid division by zero
MinWeightValue = 1.0
// WeightScaleFactor Weight scaling factor to normalize weights to 1-10 range
WeightScaleFactor = 9.0
)
// ChunkRelation represents a relationship between two Chunks
type ChunkRelation struct {
// Weight relationship weight, calculated based on PMI and strength
Weight float64
// Degree total degree of related entities
Degree int
}
// graphBuilder implements knowledge graph construction functionality
type graphBuilder struct {
config *config.Config
entityMap map[string]*types.Entity // Entities indexed by ID
entityMapByTitle map[string]*types.Entity // Entities indexed by title
relationshipMap map[string]*types.Relationship // Relationship mapping
chatModel chat.Chat
chunkGraph map[string]map[string]*ChunkRelation // Document chunk relationship graph
mutex sync.RWMutex // Mutex for concurrent operations
}
// NewGraphBuilder creates a new graph builder
func NewGraphBuilder(config *config.Config, chatModel chat.Chat) types.GraphBuilder {
logger.Info(context.Background(), "Creating new graph builder")
return &graphBuilder{
config: config,
chatModel: chatModel,
entityMap: make(map[string]*types.Entity),
entityMapByTitle: make(map[string]*types.Entity),
relationshipMap: make(map[string]*types.Relationship),
chunkGraph: make(map[string]map[string]*ChunkRelation),
}
}
// extractEntities extracts entities from text chunks
// It uses LLM to analyze text content and identify relevant entities
func (b *graphBuilder) extractEntities(ctx context.Context, chunk *types.Chunk) ([]*types.Entity, error) {
log := logger.GetLogger(ctx)
log.Infof("Extracting entities from chunk: %s", chunk.ID)
if chunk.Content == "" {
log.Warn("Empty chunk content, skipping entity extraction")
return []*types.Entity{}, nil
}
// Create prompt for entity extraction
thinking := false
messages := []chat.Message{
{
Role: "system",
Content: b.config.Conversation.ExtractEntitiesPrompt,
},
{
Role: "user",
Content: chunk.Content,
},
}
// Call LLM to extract entities
log.Debug("Calling LLM to extract entities")
resp, err := b.chatModel.Chat(ctx, messages, &chat.ChatOptions{
Temperature: DefaultLLMTemperature,
Thinking: &thinking,
})
if err != nil {
log.WithError(err).Error("Failed to extract entities from chunk")
return nil, fmt.Errorf("LLM entity extraction failed: %w", err)
}
// Parse JSON response
var extractedEntities []*types.Entity
if err := common.ParseLLMJsonResponse(resp.Content, &extractedEntities); err != nil {
log.WithError(err).Errorf("Failed to parse entity extraction response, rsp content: %s", resp.Content)
return nil, fmt.Errorf("failed to parse entity extraction response: %w", err)
}
log.Infof("Extracted %d entities from chunk", len(extractedEntities))
// Print detailed entity information in a clear format
log.Info("=========== EXTRACTED ENTITIES ===========")
for i, entity := range extractedEntities {
log.Infof("[Entity %d] Title: '%s', Description: '%s'", i+1, entity.Title, entity.Description)
}
log.Info("=========================================")
var entities []*types.Entity
// Process entities and update entityMap
b.mutex.Lock()
defer b.mutex.Unlock()
for _, entity := range extractedEntities {
if entity.Title == "" || entity.Description == "" {
log.WithField("entity", entity).Warn("Invalid entity with empty title or description")
continue
}
if existEntity, exists := b.entityMapByTitle[entity.Title]; !exists {
// This is a new entity
entity.ID = uuid.New().String()
entity.ChunkIDs = []string{chunk.ID}
entity.Frequency = 1
b.entityMapByTitle[entity.Title] = entity
b.entityMap[entity.ID] = entity
entities = append(entities, entity)
log.Debugf("New entity added: %s (ID: %s)", entity.Title, entity.ID)
} else {
// Entity already exists, update its ChunkIDs
if !slices.Contains(existEntity.ChunkIDs, chunk.ID) {
existEntity.ChunkIDs = append(existEntity.ChunkIDs, chunk.ID)
log.Debugf("Updated existing entity: %s with chunk: %s", entity.Title, chunk.ID)
}
existEntity.Frequency++
entities = append(entities, existEntity)
}
}
log.Infof("Completed entity extraction for chunk %s: %d entities", chunk.ID, len(entities))
return entities, nil
}
// extractRelationships extracts relationships between entities
// It analyzes semantic connections between multiple entities and establishes relationships
func (b *graphBuilder) extractRelationships(ctx context.Context,
chunks []*types.Chunk, entities []*types.Entity) error {
log := logger.GetLogger(ctx)
log.Infof("Extracting relationships from %d entities across %d chunks", len(entities), len(chunks))
if len(entities) < MinEntitiesForRelation {
log.Info("Not enough entities to form relationships (minimum 2)")
return nil
}
// Serialize entities to build prompt
entitiesJSON, err := json.Marshal(entities)
if err != nil {
log.WithError(err).Error("Failed to serialize entities to JSON")
return fmt.Errorf("failed to serialize entities: %w", err)
}
// Merge chunk contents
content := b.mergeChunkContents(chunks)
if content == "" {
log.Warn("No content to extract relationships from")
return nil
}
// Create relationship extraction prompt
thinking := false
messages := []chat.Message{
{
Role: "system",
Content: b.config.Conversation.ExtractRelationshipsPrompt,
},
{
Role: "user",
Content: fmt.Sprintf("Entities: %s\n\nText: %s", string(entitiesJSON), content),
},
}
// Call LLM to extract relationships
log.Debug("Calling LLM to extract relationships")
resp, err := b.chatModel.Chat(ctx, messages, &chat.ChatOptions{
Temperature: DefaultLLMTemperature,
Thinking: &thinking,
})
if err != nil {
log.WithError(err).Error("Failed to extract relationships")
return fmt.Errorf("LLM relationship extraction failed: %w", err)
}
// Parse JSON response
var extractedRelationships []*types.Relationship
if err := common.ParseLLMJsonResponse(resp.Content, &extractedRelationships); err != nil {
log.WithError(err).Error("Failed to parse relationship extraction response")
return fmt.Errorf("failed to parse relationship extraction response: %w", err)
}
log.Infof("Extracted %d relationships", len(extractedRelationships))
// Print detailed relationship information in a clear format
log.Info("========= EXTRACTED RELATIONSHIPS =========")
for i, rel := range extractedRelationships {
log.Infof("[Relation %d] Source: '%s', Target: '%s', Description: '%s', Strength: %d",
i+1, rel.Source, rel.Target, rel.Description, rel.Strength)
}
log.Info("===========================================")
// Process relationships and update relationshipMap
b.mutex.Lock()
defer b.mutex.Unlock()
relationshipsAdded := 0
relationshipsUpdated := 0
for _, relationship := range extractedRelationships {
key := fmt.Sprintf("%s#%s", relationship.Source, relationship.Target)
relationChunkIDs := b.findRelationChunkIDs(relationship.Source, relationship.Target, entities)
if len(relationChunkIDs) == 0 {
log.Debugf("Skipping relationship %s -> %s: no common chunks", relationship.Source, relationship.Target)
continue
}
if existingRel, exists := b.relationshipMap[key]; !exists {
// This is a new relationship
relationship.ID = uuid.New().String()
relationship.ChunkIDs = relationChunkIDs
b.relationshipMap[key] = relationship
relationshipsAdded++
log.Debugf("New relationship added: %s -> %s (ID: %s)",
relationship.Source, relationship.Target, relationship.ID)
} else {
// This relationship already exists, update its properties
chunkIDsAdded := 0
for _, chunkID := range relationChunkIDs {
if !slices.Contains(existingRel.ChunkIDs, chunkID) {
existingRel.ChunkIDs = append(existingRel.ChunkIDs, chunkID)
chunkIDsAdded++
}
}
// Update strength, considering weighted average of existing strength and new relationship strength
if len(existingRel.ChunkIDs) > 0 {
existingRel.Strength = (existingRel.Strength*len(existingRel.ChunkIDs) + relationship.Strength) /
(len(existingRel.ChunkIDs) + 1)
}
if chunkIDsAdded > 0 {
relationshipsUpdated++
log.Debugf("Updated relationship: %s -> %s with %d new chunks",
relationship.Source, relationship.Target, chunkIDsAdded)
}
}
}
log.Infof("Relationship extraction completed: added %d, updated %d relationships",
relationshipsAdded, relationshipsUpdated)
return nil
}
// findRelationChunkIDs finds common document chunk IDs between two entities
func (b *graphBuilder) findRelationChunkIDs(source, target string, entities []*types.Entity) []string {
relationChunkIDs := make(map[string]struct{})
// Collect all document chunk IDs for source and target entities
for _, entity := range entities {
if entity.Title == source || entity.Title == target {
for _, chunkID := range entity.ChunkIDs {
relationChunkIDs[chunkID] = struct{}{}
}
}
}
if len(relationChunkIDs) == 0 {
return []string{}
}
// Convert map keys to slice
result := make([]string, 0, len(relationChunkIDs))
for chunkID := range relationChunkIDs {
result = append(result, chunkID)
}
return result
}
// mergeChunkContents merges content from multiple document chunks
// It accounts for overlapping portions between chunks to ensure coherent content
func (b *graphBuilder) mergeChunkContents(chunks []*types.Chunk) string {
if len(chunks) == 0 {
return ""
}
var chunkContents = chunks[0].Content
preChunk := chunks[0]
for i := 1; i < len(chunks); i++ {
// Only add non-overlapping content parts
if preChunk.EndAt > chunks[i].StartAt {
// Calculate overlap starting position
startPos := preChunk.EndAt - chunks[i].StartAt
if startPos >= 0 && startPos < len([]rune(chunks[i].Content)) {
chunkContents = chunkContents + string([]rune(chunks[i].Content)[startPos:])
}
} else {
// If there's no overlap between chunks, add all content
chunkContents = chunkContents + chunks[i].Content
}
preChunk = chunks[i]
}
return chunkContents
}
// BuildGraph constructs the knowledge graph
// It serves as the main entry point for the graph building process, coordinating all components
func (b *graphBuilder) BuildGraph(ctx context.Context, chunks []*types.Chunk) error {
log := logger.GetLogger(ctx)
log.Infof("Building knowledge graph from %d chunks", len(chunks))
startTime := time.Now()
// Concurrently extract entities from each document chunk
var chunkEntities = make([][]*types.Entity, len(chunks))
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(MaxConcurrentEntityExtractions) // Limit concurrency
for i, chunk := range chunks {
i, chunk := i, chunk // Create local variables to avoid closure issues
g.Go(func() error {
log.Debugf("Processing chunk %d/%d (ID: %s)", i+1, len(chunks), chunk.ID)
entities, err := b.extractEntities(gctx, chunk)
if err != nil {
log.WithError(err).Errorf("Failed to extract entities from chunk %s", chunk.ID)
return fmt.Errorf("entity extraction failed for chunk %s: %w", chunk.ID, err)
}
chunkEntities[i] = entities
return nil
})
}
// Wait for all entity extractions to complete
if err := g.Wait(); err != nil {
log.WithError(err).Error("Entity extraction failed")
return fmt.Errorf("entity extraction process failed: %w", err)
}
// Count total extracted entities
totalEntityCount := 0
for _, entities := range chunkEntities {
totalEntityCount += len(entities)
}
log.Infof("Successfully extracted %d total entities across %d chunks",
totalEntityCount, len(chunks))
// Process relationships in batches concurrently
relationChunkSize := DefaultRelationBatchSize
log.Infof("Processing relationships concurrently in batches of %d chunks", relationChunkSize)
// prepare relationship extraction batches
var relationBatches []struct {
batchChunks []*types.Chunk
relationUseEntities []*types.Entity
batchIndex int
}
for i, batchChunks := range utils.ChunkSlice(chunks, relationChunkSize) {
start := i * relationChunkSize
end := start + relationChunkSize
if end > len(chunkEntities) {
end = len(chunkEntities)
}
// Merge all entities in this batch
relationUseEntities := make([]*types.Entity, 0)
for j := start; j < end; j++ {
if j < len(chunkEntities) {
relationUseEntities = append(relationUseEntities, chunkEntities[j]...)
}
}
if len(relationUseEntities) < MinEntitiesForRelation {
log.Debugf("Skipping batch %d: not enough entities (%d)", i+1, len(relationUseEntities))
continue
}
relationBatches = append(relationBatches, struct {
batchChunks []*types.Chunk
relationUseEntities []*types.Entity
batchIndex int
}{
batchChunks: batchChunks,
relationUseEntities: relationUseEntities,
batchIndex: i,
})
}
// extract relationships concurrently
relG, relGctx := errgroup.WithContext(ctx)
relG.SetLimit(MaxConcurrentRelationExtractions) // use dedicated relationship extraction concurrency limit
for _, batch := range relationBatches {
relG.Go(func() error {
log.Debugf("Processing relationship batch %d (chunks %d)", batch.batchIndex+1, len(batch.batchChunks))
err := b.extractRelationships(relGctx, batch.batchChunks, batch.relationUseEntities)
if err != nil {
log.WithError(err).Errorf("Failed to extract relationships for batch %d", batch.batchIndex+1)
}
return nil // continue to process other batches even if the current batch fails
})
}
// wait for all relationship extractions to complete
if err := relG.Wait(); err != nil {
log.WithError(err).Error("Some relationship extraction tasks failed")
// but we continue to process the next steps because some relationship extractions are still useful
}
// Calculate relationship weights
log.Info("Calculating weights for relationships")
b.calculateWeights(ctx)
// Calculate entity degrees
log.Info("Calculating degrees for entities")
b.calculateDegrees(ctx)
// Build Chunk graph
log.Info("Building chunk relationship graph")
b.buildChunkGraph(ctx)
log.Infof("Graph building completed in %.2f seconds: %d entities, %d relationships",
time.Since(startTime).Seconds(), len(b.entityMap), len(b.relationshipMap))
// generate knowledge graph visualization diagram
mermaidDiagram := b.generateKnowledgeGraphDiagram(ctx)
log.Info("Knowledge graph visualization diagram:")
log.Info(mermaidDiagram)
return nil
}
// calculateWeights calculates relationship weights
// It uses Point Mutual Information (PMI) and strength values to calculate relationship weights
func (b *graphBuilder) calculateWeights(ctx context.Context) {
log := logger.GetLogger(ctx)
log.Info("Calculating relationship weights using PMI and strength")
// Calculate total entity occurrences
totalEntityOccurrences := 0
entityFrequency := make(map[string]int)
for _, entity := range b.entityMap {
frequency := len(entity.ChunkIDs)
entityFrequency[entity.Title] = frequency
totalEntityOccurrences += frequency
}
// Calculate total relationship occurrences
totalRelOccurrences := 0
for _, rel := range b.relationshipMap {
totalRelOccurrences += len(rel.ChunkIDs)
}
// Skip calculation if insufficient data
if totalEntityOccurrences == 0 || totalRelOccurrences == 0 {
log.Warn("Insufficient data for weight calculation")
return
}
// Track maximum PMI and Strength values for normalization
maxPMI := 0.0
maxStrength := MinWeightValue // Avoid division by zero
// First calculate PMI and find maximum values
pmiValues := make(map[string]float64)
for _, rel := range b.relationshipMap {
sourceFreq := entityFrequency[rel.Source]
targetFreq := entityFrequency[rel.Target]
relFreq := len(rel.ChunkIDs)
if sourceFreq > 0 && targetFreq > 0 && relFreq > 0 {
sourceProbability := float64(sourceFreq) / float64(totalEntityOccurrences)
targetProbability := float64(targetFreq) / float64(totalEntityOccurrences)
relProbability := float64(relFreq) / float64(totalRelOccurrences)
// PMI calculation: log(P(x,y) / (P(x) * P(y)))
pmi := math.Max(math.Log2(relProbability/(sourceProbability*targetProbability)), 0)
pmiValues[rel.ID] = pmi
if pmi > maxPMI {
maxPMI = pmi
}
}
// Record maximum Strength value
if float64(rel.Strength) > maxStrength {
maxStrength = float64(rel.Strength)
}
}
// Combine PMI and Strength to calculate final weights
for _, rel := range b.relationshipMap {
pmi := pmiValues[rel.ID]
// Normalize PMI and Strength (0-1 range)
normalizedPMI := 0.0
if maxPMI > 0 {
normalizedPMI = pmi / maxPMI
}
normalizedStrength := float64(rel.Strength) / maxStrength
// Combine PMI and Strength using configured weights
combinedWeight := normalizedPMI*PMIWeight + normalizedStrength*StrengthWeight
// Scale weight to 1-10 range
scaledWeight := 1.0 + WeightScaleFactor*combinedWeight
rel.Weight = scaledWeight
}
log.Infof("Weight calculation completed for %d relationships", len(b.relationshipMap))
}
// calculateDegrees calculates entity degrees
// Degree represents the number of connections an entity has with other entities, a key metric in graph structures
func (b *graphBuilder) calculateDegrees(ctx context.Context) {
log := logger.GetLogger(ctx)
log.Info("Calculating entity degrees")
// Calculate in-degree and out-degree for each entity
inDegree := make(map[string]int)
outDegree := make(map[string]int)
for _, rel := range b.relationshipMap {
outDegree[rel.Source]++
inDegree[rel.Target]++
}
// Set degree for each entity
for _, entity := range b.entityMap {
entity.Degree = inDegree[entity.Title] + outDegree[entity.Title]
}
// Set combined degree for relationships
for _, rel := range b.relationshipMap {
sourceEntity := b.getEntityByTitle(rel.Source)
targetEntity := b.getEntityByTitle(rel.Target)
if sourceEntity != nil && targetEntity != nil {
rel.CombinedDegree = sourceEntity.Degree + targetEntity.Degree
}
}
log.Info("Entity degree calculation completed")
}
// buildChunkGraph builds relationship graph between Chunks
// It creates a network of relationships between document chunks based on entity relationships
func (b *graphBuilder) buildChunkGraph(ctx context.Context) {
log := logger.GetLogger(ctx)
log.Info("Building chunk relationship graph")
// Create document chunk relationship graph based on entity relationships
for _, rel := range b.relationshipMap {
// Ensure source and target entities exist for the relationship
sourceEntity := b.entityMapByTitle[rel.Source]
targetEntity := b.entityMapByTitle[rel.Target]
if sourceEntity == nil || targetEntity == nil {
log.Warnf("Missing entity for relationship %s -> %s", rel.Source, rel.Target)
continue
}
// Build Chunk graph - connect all related document chunks
for _, sourceChunkID := range sourceEntity.ChunkIDs {
if _, exists := b.chunkGraph[sourceChunkID]; !exists {
b.chunkGraph[sourceChunkID] = make(map[string]*ChunkRelation)
}
for _, targetChunkID := range targetEntity.ChunkIDs {
if _, exists := b.chunkGraph[targetChunkID]; !exists {
b.chunkGraph[targetChunkID] = make(map[string]*ChunkRelation)
}
relation := &ChunkRelation{
Weight: rel.Weight,
Degree: rel.CombinedDegree,
}
b.chunkGraph[sourceChunkID][targetChunkID] = relation
b.chunkGraph[targetChunkID][sourceChunkID] = relation
}
}
}
log.Infof("Chunk graph built with %d nodes", len(b.chunkGraph))
}
// GetAllEntities returns all entities
func (b *graphBuilder) GetAllEntities() []*types.Entity {
b.mutex.RLock()
defer b.mutex.RUnlock()
entities := make([]*types.Entity, 0, len(b.entityMap))
for _, entity := range b.entityMap {
entities = append(entities, entity)
}
return entities
}
// GetAllRelationships returns all relationships
func (b *graphBuilder) GetAllRelationships() []*types.Relationship {
b.mutex.RLock()
defer b.mutex.RUnlock()
relationships := make([]*types.Relationship, 0, len(b.relationshipMap))
for _, relationship := range b.relationshipMap {
relationships = append(relationships, relationship)
}
return relationships
}
// GetRelationChunks retrieves document chunks directly related to the given chunkID
// It returns a list of related document chunk IDs sorted by weight and degree
func (b *graphBuilder) GetRelationChunks(chunkID string, topK int) []string {
b.mutex.RLock()
defer b.mutex.RUnlock()
log := logger.GetLogger(context.Background())
log.Debugf("Getting related chunks for %s (topK=%d)", chunkID, topK)
// Create weighted chunk structure for sorting
type weightedChunk struct {
id string
weight float64
degree int
}
// Collect related chunks with their weights and degrees
weightedChunks := make([]weightedChunk, 0)
for relationChunkID, relation := range b.chunkGraph[chunkID] {
weightedChunks = append(weightedChunks, weightedChunk{
id: relationChunkID,
weight: relation.Weight,
degree: relation.Degree,
})
}
// Sort by weight and degree in descending order
slices.SortFunc(weightedChunks, func(a, b weightedChunk) int {
// Sort by weight first
if a.weight > b.weight {
return -1 // Descending order
} else if a.weight < b.weight {
return 1
}
// If weights are equal, sort by degree
if a.degree > b.degree {
return -1 // Descending order
} else if a.degree < b.degree {
return 1
}
return 0
})
// Take top K results
resultCount := len(weightedChunks)
if topK > 0 && topK < resultCount {
resultCount = topK
}
// Extract chunk IDs
chunks := make([]string, 0, resultCount)
for i := 0; i < resultCount; i++ {
chunks = append(chunks, weightedChunks[i].id)
}
log.Debugf("Found %d related chunks for %s (limited to %d)",
len(weightedChunks), chunkID, resultCount)
return chunks
}
// GetIndirectRelationChunks retrieves document chunks indirectly related to the given chunkID
// It returns document chunk IDs found through second-degree connections
func (b *graphBuilder) GetIndirectRelationChunks(chunkID string, topK int) []string {
b.mutex.RLock()
defer b.mutex.RUnlock()
log := logger.GetLogger(context.Background())
log.Debugf("Getting indirectly related chunks for %s (topK=%d)", chunkID, topK)
// Create weighted chunk structure for sorting
type weightedChunk struct {
id string
weight float64
degree int
}
// Get directly related chunks (first-degree connections)
directChunks := make(map[string]struct{})
directChunks[chunkID] = struct{}{} // Add original chunkID
for directChunkID := range b.chunkGraph[chunkID] {
directChunks[directChunkID] = struct{}{}
}
log.Debugf("Found %d directly related chunks to exclude", len(directChunks))
// Use map to deduplicate and store second-degree connections
indirectChunkMap := make(map[string]*ChunkRelation)
// Get first-degree connections
for directChunkID, directRelation := range b.chunkGraph[chunkID] {
// Get second-degree connections
for indirectChunkID, indirectRelation := range b.chunkGraph[directChunkID] {
// Skip self and all direct connections
if _, isDirect := directChunks[indirectChunkID]; isDirect {
continue
}
// Weight decay: second-degree relationship weight is the product of two direct relationship weights
// multiplied by decay coefficient
combinedWeight := directRelation.Weight * indirectRelation.Weight * IndirectRelationWeightDecay
// Degree calculation: take the maximum degree from the two path segments
combinedDegree := max(directRelation.Degree, indirectRelation.Degree)
// If already exists, take the higher weight
if existingRel, exists := indirectChunkMap[indirectChunkID]; !exists ||
combinedWeight > existingRel.Weight {
indirectChunkMap[indirectChunkID] = &ChunkRelation{
Weight: combinedWeight,
Degree: combinedDegree,
}
}
}
}
// Convert to sortable slice
weightedChunks := make([]weightedChunk, 0, len(indirectChunkMap))
for id, relation := range indirectChunkMap {
weightedChunks = append(weightedChunks, weightedChunk{
id: id,
weight: relation.Weight,
degree: relation.Degree,
})
}
// Sort by weight and degree in descending order
slices.SortFunc(weightedChunks, func(a, b weightedChunk) int {
// Sort by weight first
if a.weight > b.weight {
return -1 // Descending order
} else if a.weight < b.weight {
return 1
}
// If weights are equal, sort by degree
if a.degree > b.degree {
return -1 // Descending order
} else if a.degree < b.degree {
return 1
}
return 0
})
// Take top K results
resultCount := len(weightedChunks)
if topK > 0 && topK < resultCount {
resultCount = topK
}
// Extract chunk IDs
chunks := make([]string, 0, resultCount)
for i := 0; i < resultCount; i++ {
chunks = append(chunks, weightedChunks[i].id)
}
log.Debugf("Found %d indirect related chunks for %s (limited to %d)",
len(weightedChunks), chunkID, resultCount)
return chunks
}
// getEntityByTitle retrieves an entity by its title
func (b *graphBuilder) getEntityByTitle(title string) *types.Entity {
return b.entityMapByTitle[title]
}
// dfs depth-first search to find connected components
func dfs(entityTitle string,
adjacencyList map[string]map[string]*types.Relationship,
visited map[string]bool, component *[]string) {
visited[entityTitle] = true
*component = append(*component, entityTitle)
// traverse all relationships of the current entity
for targetEntity := range adjacencyList[entityTitle] {
if !visited[targetEntity] {
dfs(targetEntity, adjacencyList, visited, component)
}
}
// check reverse relationships (check if other entities point to the current entity)
for source, targets := range adjacencyList {
for target := range targets {
if target == entityTitle && !visited[source] {
dfs(source, adjacencyList, visited, component)
}
}
}
}
// generateKnowledgeGraphDiagram generate Mermaid diagram for knowledge graph
func (b *graphBuilder) generateKnowledgeGraphDiagram(ctx context.Context) string {
log := logger.GetLogger(ctx)
log.Info("Generating knowledge graph visualization diagram...")
var sb strings.Builder
// Mermaid diagram header
sb.WriteString("```mermaid\ngraph TD\n")
sb.WriteString(" %% entity style definition\n")
sb.WriteString(" classDef entity fill:#f9f,stroke:#333,stroke-width:1px;\n")
sb.WriteString(" classDef highFreq fill:#bbf,stroke:#333,stroke-width:2px;\n\n")
// get all entities and sort by frequency
entities := b.GetAllEntities()
slices.SortFunc(entities, func(a, b *types.Entity) int {
if a.Frequency > b.Frequency {
return -1
} else if a.Frequency < b.Frequency {
return 1
}
return 0
})
// get relationships and sort by weight
relationships := b.GetAllRelationships()
slices.SortFunc(relationships, func(a, b *types.Relationship) int {
if a.Weight > b.Weight {
return -1
} else if a.Weight < b.Weight {
return 1
}
return 0
})
// create entity ID mapping
entityMap := make(map[string]string) // store entity title to node ID mapping
for i, entity := range entities {
nodeID := fmt.Sprintf("E%d", i)
entityMap[entity.Title] = nodeID
}
// create adjacency list to represent graph structure
adjacencyList := make(map[string]map[string]*types.Relationship)
for _, entity := range entities {
adjacencyList[entity.Title] = make(map[string]*types.Relationship)
}
// fill adjacency list
for _, rel := range relationships {
if _, sourceExists := entityMap[rel.Source]; sourceExists {
if _, targetExists := entityMap[rel.Target]; targetExists {
adjacencyList[rel.Source][rel.Target] = rel
}
}
}
// use DFS to find connected components (subgraphs)
visited := make(map[string]bool)
subgraphs := make([][]string, 0) // store entity titles in each subgraph
for _, entity := range entities {
if !visited[entity.Title] {
component := make([]string, 0)
dfs(entity.Title, adjacencyList, visited, &component)
if len(component) > 0 {
subgraphs = append(subgraphs, component)
}
}
}
// generate Mermaid subgraphs
subgraphCount := 0
for _, component := range subgraphs {
// check if this component has relationships
hasRelations := false
nodeCount := len(component)
// if there is only 1 node, check if it has relationships
if nodeCount == 1 {
entityTitle := component[0]
// check if this entity appears as source or target in any relationship
for _, rel := range relationships {
if rel.Source == entityTitle || rel.Target == entityTitle {
hasRelations = true
break
}
}
// if there is only 1 node and no relationships, skip this subgraph
if !hasRelations {
continue
}
} else if nodeCount > 1 {
// a subgraph with more than 1 node must have relationships
hasRelations = true
}
// only draw if there are multiple entities or at least one relationship in the subgraph
if hasRelations {
subgraphCount++
sb.WriteString(fmt.Sprintf("\n subgraph 子图%d\n", subgraphCount))
// add all entities in this subgraph
entitiesInComponent := make(map[string]bool)
for _, entityTitle := range component {
nodeID := entityMap[entityTitle]
entitiesInComponent[entityTitle] = true
// add node definition for each entity
entity := b.entityMapByTitle[entityTitle]
if entity != nil {
sb.WriteString(fmt.Sprintf(" %s[\"%s\"]\n", nodeID, entityTitle))
}
}
// add relationships in this subgraph
for _, rel := range relationships {
if entitiesInComponent[rel.Source] && entitiesInComponent[rel.Target] {
sourceID := entityMap[rel.Source]
targetID := entityMap[rel.Target]
linkStyle := "-->"
// adjust link style based on relationship strength
if rel.Strength > 7 {
linkStyle = "==>"
}
sb.WriteString(fmt.Sprintf(" %s %s|%s| %s\n",
sourceID, linkStyle, rel.Description, targetID))
}
}
// subgraph ends
sb.WriteString(" end\n")
// apply style class
for _, entityTitle := range component {
nodeID := entityMap[entityTitle]
entity := b.entityMapByTitle[entityTitle]
if entity != nil {
if entity.Frequency > 5 {
sb.WriteString(fmt.Sprintf(" class %s highFreq;\n", nodeID))
} else {
sb.WriteString(fmt.Sprintf(" class %s entity;\n", nodeID))
}
}
}
}
}
// close Mermaid diagram
sb.WriteString("```\n")
log.Infof("Knowledge graph visualization diagram generated with %d subgraphs", subgraphCount)
return sb.String()
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,574 @@
package service
import (
"context"
"errors"
"slices"
"time"
"encoding/json"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// ErrInvalidTenantID represents an error for invalid tenant ID
var ErrInvalidTenantID = errors.New("invalid tenant ID")
// knowledgeBaseService implements the knowledge base service interface
type knowledgeBaseService struct {
repo interfaces.KnowledgeBaseRepository
kgRepo interfaces.KnowledgeRepository
chunkRepo interfaces.ChunkRepository
modelService interfaces.ModelService
}
// NewKnowledgeBaseService creates a new knowledge base service
func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
kgRepo interfaces.KnowledgeRepository,
chunkRepo interfaces.ChunkRepository,
modelService interfaces.ModelService,
) interfaces.KnowledgeBaseService {
return &knowledgeBaseService{
repo: repo,
kgRepo: kgRepo,
chunkRepo: chunkRepo,
modelService: modelService,
}
}
// CreateKnowledgeBase creates a new knowledge base
func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
kb *types.KnowledgeBase,
) (*types.KnowledgeBase, error) {
// Generate UUID and set creation timestamps
kb.ID = uuid.New().String()
kb.CreatedAt = time.Now()
kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint)
kb.UpdatedAt = time.Now()
logger.Infof(ctx, "Creating knowledge base, ID: %s, tenant ID: %d, name: %s", kb.ID, kb.TenantID, kb.Name)
if err := s.repo.CreateKnowledgeBase(ctx, kb); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": kb.ID,
"tenant_id": kb.TenantID,
})
return nil, err
}
logger.Infof(ctx, "Knowledge base created successfully, ID: %s, name: %s", kb.ID, kb.Name)
return kb, nil
}
// GetKnowledgeBaseByID retrieves a knowledge base by its ID
func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
if id == "" {
logger.Error(ctx, "Knowledge base ID is empty")
return nil, errors.New("knowledge base ID cannot be empty")
}
logger.Infof(ctx, "Retrieving knowledge base, ID: %s", id)
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
})
return nil, err
}
logger.Infof(ctx, "Knowledge base retrieved successfully, ID: %s, name: %s", kb.ID, kb.Name)
return kb, nil
}
// ListKnowledgeBases returns all knowledge bases for a tenant
func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Retrieving knowledge base list for tenant, tenant ID: %d", tenantID)
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
})
return nil, err
}
logger.Infof(
ctx,
"Knowledge base list retrieved successfully, tenant ID: %d, knowledge base count: %d",
tenantID,
len(kbs),
)
return kbs, nil
}
// UpdateKnowledgeBase updates a knowledge base's properties
func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
id string,
name string,
description string,
config *types.KnowledgeBaseConfig,
) (*types.KnowledgeBase, error) {
if id == "" {
logger.Error(ctx, "Knowledge base ID is empty")
return nil, errors.New("knowledge base ID cannot be empty")
}
logger.Infof(ctx, "Updating knowledge base, ID: %s, name: %s", id, name)
// Get existing knowledge base
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
})
return nil, err
}
// Update the knowledge base properties
kb.Name = name
kb.Description = description
kb.ChunkingConfig = config.ChunkingConfig
kb.ImageProcessingConfig = config.ImageProcessingConfig
kb.UpdatedAt = time.Now()
logger.Info(ctx, "Saving knowledge base update")
if err := s.repo.UpdateKnowledgeBase(ctx, kb); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
})
return nil, err
}
logger.Infof(ctx, "Knowledge base updated successfully, ID: %s, name: %s", kb.ID, kb.Name)
return kb, nil
}
// DeleteKnowledgeBase deletes a knowledge base by its ID
func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id string) error {
if id == "" {
logger.Error(ctx, "Knowledge base ID is empty")
return errors.New("knowledge base ID cannot be empty")
}
logger.Infof(ctx, "Deleting knowledge base, ID: %s", id)
err := s.repo.DeleteKnowledgeBase(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
})
return err
}
logger.Infof(ctx, "Knowledge base deleted successfully, ID: %s", id)
return nil
}
// SetEmbeddingModel sets the embedding model for a knowledge base
func (s *knowledgeBaseService) SetEmbeddingModel(ctx context.Context, id string, modelID string) error {
if id == "" {
logger.Error(ctx, "Knowledge base ID is empty")
return errors.New("knowledge base ID cannot be empty")
}
if modelID == "" {
logger.Error(ctx, "Model ID is empty")
return errors.New("model ID cannot be empty")
}
logger.Infof(ctx, "Setting embedding model for knowledge base, knowledge base ID: %s, model ID: %s", id, modelID)
// Get the knowledge base
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
})
return err
}
// Update the knowledge base's embedding model
kb.EmbeddingModelID = modelID
kb.UpdatedAt = time.Now()
logger.Info(ctx, "Saving knowledge base embedding model update")
err = s.repo.UpdateKnowledgeBase(ctx, kb)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
"embedding_model_id": modelID,
})
return err
}
logger.Infof(
ctx,
"Knowledge base embedding model set successfully, knowledge base ID: %s, model ID: %s",
id,
modelID,
)
return nil
}
// CopyKnowledgeBase copies a knowledge base to a new knowledge base
// 浅拷贝
func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
srcKB string, dstKB string,
) (*types.KnowledgeBase, *types.KnowledgeBase, error) {
sourceKB, err := s.repo.GetKnowledgeBaseByID(ctx, srcKB)
if err != nil {
logger.Errorf(ctx, "Get source knowledge base failed: %v", err)
return nil, nil, err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
var targetKB *types.KnowledgeBase
if dstKB != "" {
targetKB, err = s.repo.GetKnowledgeBaseByID(ctx, dstKB)
if err != nil {
return nil, nil, err
}
} else {
targetKB = &types.KnowledgeBase{
ID: uuid.New().String(),
Name: sourceKB.Name,
Description: sourceKB.Description,
TenantID: tenantID,
ChunkingConfig: sourceKB.ChunkingConfig,
ImageProcessingConfig: sourceKB.ImageProcessingConfig,
EmbeddingModelID: sourceKB.EmbeddingModelID,
SummaryModelID: sourceKB.SummaryModelID,
}
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
return nil, nil, err
}
}
return sourceKB, targetKB, nil
}
// HybridSearch performs hybrid search, including vector retrieval and keyword retrieval
func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
id string,
params types.SearchParams,
) ([]*types.SearchResult, error) {
logger.Infof(ctx, "Hybrid search parameters, knowledge base ID: %s, query text: %s", id, params.QueryText)
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
logger.Infof(ctx, "Creating composite retrieval engine, tenant ID: %d", tenantInfo.ID)
// Create a composite retrieval engine with tenant's configured retrievers
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(tenantInfo.RetrieverEngines.Engines)
if err != nil {
logger.Errorf(ctx, "Failed to create retrieval engine: %v", err)
return nil, err
}
var retrieveParams []types.RetrieveParams
var embeddingModel embedding.Embedder
var kb *types.KnowledgeBase
// Add vector retrieval params if supported
if retrieveEngine.SupportRetriever(types.VectorRetrieverType) {
logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters")
kb, err = s.repo.GetKnowledgeBaseByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
})
return nil, err
}
logger.Infof(ctx, "Getting embedding model, model ID: %s", kb.EmbeddingModelID)
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get embedding model, model ID: %s, error: %v", kb.EmbeddingModelID, err)
return nil, err
}
logger.Infof(ctx, "Embedding model retrieved: %v", embeddingModel)
// Generate embedding vector for the query text
logger.Info(ctx, "Starting to generate query embedding")
queryEmbedding, err := embeddingModel.Embed(ctx, params.QueryText)
if err != nil {
logger.Errorf(ctx, "Failed to embed query text, query text: %s, error: %v", params.QueryText, err)
return nil, err
}
logger.Infof(ctx, "Query embedding generated successfully, embedding vector length: %d", len(queryEmbedding))
retrieveParams = append(retrieveParams, types.RetrieveParams{
Query: params.QueryText,
Embedding: queryEmbedding,
KnowledgeBaseIDs: []string{id},
TopK: params.MatchCount,
Threshold: params.VectorThreshold,
RetrieverType: types.VectorRetrieverType,
})
logger.Info(ctx, "Vector retrieval parameters setup completed")
}
// Add keyword retrieval params if supported
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) {
logger.Info(ctx, "Keyword retrieval supported, preparing keyword retrieval parameters")
retrieveParams = append(retrieveParams, types.RetrieveParams{
Query: params.QueryText,
KnowledgeBaseIDs: []string{id},
TopK: params.MatchCount,
Threshold: params.KeywordThreshold,
RetrieverType: types.KeywordsRetrieverType,
})
logger.Info(ctx, "Keyword retrieval parameters setup completed")
}
if len(retrieveParams) == 0 {
logger.Error(ctx, "No retrieval parameters available")
return nil, errors.New("no retrieve params")
}
// Execute retrieval using the configured engines
logger.Infof(ctx, "Starting retrieval, parameter count: %d", len(retrieveParams))
retrieveResults, err := retrieveEngine.Retrieve(ctx, retrieveParams)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_base_id": id,
"query_text": params.QueryText,
})
return nil, err
}
// Collect all results from different retrievers and deduplicate by chunk ID
logger.Infof(ctx, "Processing retrieval results")
matchResults := []*types.IndexWithScore{}
for _, retrieveResult := range retrieveResults {
logger.Infof(ctx, "Retrieval results, engine: %v, retriever: %v, count: %v",
retrieveResult.RetrieverEngineType,
retrieveResult.RetrieverType,
len(retrieveResult.Results),
)
matchResults = append(matchResults, retrieveResult.Results...)
}
// Early return if no results
if len(matchResults) == 0 {
logger.Info(ctx, "No search results found")
return nil, nil
}
// Deduplicate results by chunk ID
logger.Infof(ctx, "Result count before deduplication: %d", len(matchResults))
deduplicatedChunks := common.Deduplicate(func(r *types.IndexWithScore) string { return r.ChunkID }, matchResults...)
logger.Infof(ctx, "Result count after deduplication: %d", len(deduplicatedChunks))
return s.processSearchResults(ctx, deduplicatedChunks)
}
// processSearchResults handles the processing of search results, optimizing database queries
func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
chunks []*types.IndexWithScore) ([]*types.SearchResult, error) {
if len(chunks) == 0 {
return nil, nil
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
// Prepare data structures for efficient processing
var knowledgeIDs []string
var chunkIDs []string
chunkScores := make(map[string]float64)
chunkMatchTypes := make(map[string]types.MatchType)
processedKnowledgeIDs := make(map[string]bool)
// Collect all knowledge and chunk IDs
for _, chunk := range chunks {
if !processedKnowledgeIDs[chunk.KnowledgeID] {
knowledgeIDs = append(knowledgeIDs, chunk.KnowledgeID)
processedKnowledgeIDs[chunk.KnowledgeID] = true
}
chunkIDs = append(chunkIDs, chunk.ChunkID)
chunkScores[chunk.ChunkID] = chunk.Score
chunkMatchTypes[chunk.ChunkID] = chunk.MatchType
}
// Batch fetch knowledge data
logger.Infof(ctx, "Fetching knowledge data for %d IDs", len(knowledgeIDs))
knowledgeMap, err := s.fetchKnowledgeData(ctx, tenantID, knowledgeIDs)
if err != nil {
return nil, err
}
// Batch fetch all chunks in one go
logger.Infof(ctx, "Fetching chunk data for %d IDs", len(chunkIDs))
allChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
"chunk_ids": chunkIDs,
})
return nil, err
}
// Build chunk map and collect additional IDs to fetch
chunkMap := make(map[string]*types.Chunk, len(allChunks))
var additionalChunkIDs []string
processedChunkIDs := make(map[string]bool)
// First pass: Build chunk map and collect parent IDs
for _, chunk := range allChunks {
chunkMap[chunk.ID] = chunk
processedChunkIDs[chunk.ID] = true
// Collect parent chunks
if chunk.ParentChunkID != "" && !processedChunkIDs[chunk.ParentChunkID] {
additionalChunkIDs = append(additionalChunkIDs, chunk.ParentChunkID)
processedChunkIDs[chunk.ParentChunkID] = true
// Pass score to parent
chunkScores[chunk.ParentChunkID] = chunkScores[chunk.ID]
chunkMatchTypes[chunk.ParentChunkID] = types.MatchTypeParentChunk
}
// Collect related chunks
relationChunkIDs := s.collectRelatedChunkIDs(chunk, processedChunkIDs)
for _, chunkID := range relationChunkIDs {
additionalChunkIDs = append(additionalChunkIDs, chunkID)
chunkMatchTypes[chunkID] = types.MatchTypeRelationChunk
}
// Add nearby chunks (prev and next)
if chunk.ChunkType == types.ChunkTypeText {
if chunk.NextChunkID != "" && !processedChunkIDs[chunk.NextChunkID] {
additionalChunkIDs = append(additionalChunkIDs, chunk.NextChunkID)
processedChunkIDs[chunk.NextChunkID] = true
chunkMatchTypes[chunk.NextChunkID] = types.MatchTypeNearByChunk
}
if chunk.PreChunkID != "" && !processedChunkIDs[chunk.PreChunkID] {
additionalChunkIDs = append(additionalChunkIDs, chunk.PreChunkID)
processedChunkIDs[chunk.PreChunkID] = true
chunkMatchTypes[chunk.PreChunkID] = types.MatchTypeNearByChunk
}
}
}
// Fetch all additional chunks in one go if needed
if len(additionalChunkIDs) > 0 {
logger.Infof(ctx, "Fetching %d additional chunks", len(additionalChunkIDs))
additionalChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, additionalChunkIDs)
if err != nil {
logger.Warnf(ctx, "Failed to fetch some additional chunks: %v", err)
// Continue with what we have
} else {
// Add to chunk map
for _, chunk := range additionalChunks {
chunkMap[chunk.ID] = chunk
}
}
}
// Build final search results
var searchResults []*types.SearchResult
for chunkID, chunk := range chunkMap {
if !s.isValidTextChunk(chunk) {
continue
}
score, hasScore := chunkScores[chunkID]
if !hasScore || score <= 0 {
score = 0.0
}
if knowledge, ok := knowledgeMap[chunk.KnowledgeID]; ok {
matchType := types.MatchTypeParentChunk
if specificType, exists := chunkMatchTypes[chunkID]; exists {
matchType = specificType
} else {
logger.Warnf(ctx, "Unkonwn match type for chunk: %s", chunkID)
continue
}
searchResults = append(searchResults, s.buildSearchResult(chunk, knowledge, score, matchType))
}
}
logger.Infof(ctx, "Search results processed, total: %d", len(searchResults))
return searchResults, nil
}
// collectRelatedChunkIDs extracts related chunk IDs from a chunk
func (s *knowledgeBaseService) collectRelatedChunkIDs(chunk *types.Chunk, processedIDs map[string]bool) []string {
var relatedIDs []string
// Process direct relations
if len(chunk.RelationChunks) > 0 {
var relations []string
if err := json.Unmarshal(chunk.RelationChunks, &relations); err == nil {
for _, id := range relations {
if !processedIDs[id] {
relatedIDs = append(relatedIDs, id)
processedIDs[id] = true
}
}
}
}
return relatedIDs
}
// buildSearchResult creates a search result from chunk and knowledge
func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
knowledge *types.Knowledge,
score float64,
matchType types.MatchType) *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: score,
MatchType: matchType,
Metadata: knowledge.GetMetadata(),
ChunkType: string(chunk.ChunkType),
ParentChunkID: chunk.ParentChunkID,
ImageInfo: chunk.ImageInfo,
KnowledgeFilename: knowledge.FileName,
KnowledgeSource: knowledge.Source,
}
}
// isValidTextChunk checks if a chunk is a valid text chunk
func (s *knowledgeBaseService) isValidTextChunk(chunk *types.Chunk) bool {
return slices.Contains([]types.ChunkType{
types.ChunkTypeText, types.ChunkTypeSummary,
}, chunk.ChunkType)
}
// fetchKnowledgeData gets knowledge data in batch
func (s *knowledgeBaseService) fetchKnowledgeData(ctx context.Context,
tenantID uint,
knowledgeIDs []string,
) (map[string]*types.Knowledge, error) {
knowledges, err := s.kgRepo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
"knowledge_ids": knowledgeIDs,
})
return nil, err
}
knowledgeMap := make(map[string]*types.Knowledge, len(knowledges))
for _, knowledge := range knowledges {
knowledgeMap[knowledge.ID] = knowledge
}
return knowledgeMap, nil
}
+287
View File
@@ -0,0 +1,287 @@
package service
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// messageService implements the MessageService interface for managing messaging operations
// It handles creating, retrieving, updating, and deleting messages within sessions
type messageService struct {
messageRepo interfaces.MessageRepository // Repository for message storage operations
sessionRepo interfaces.SessionRepository // Repository for session validation
}
// NewMessageService creates a new message service instance with the required repositories
// Parameters:
// - messageRepo: Repository for persisting and retrieving messages
// - sessionRepo: Repository for validating session existence
//
// Returns an implementation of the MessageService interface
func NewMessageService(messageRepo interfaces.MessageRepository,
sessionRepo interfaces.SessionRepository,
) interfaces.MessageService {
return &messageService{
messageRepo: messageRepo,
sessionRepo: sessionRepo,
}
}
// CreateMessage creates a new message within an existing session
// It validates that the session exists before creating the message
// Parameters:
// - ctx: Context containing tenant information
// - message: The message to be created
//
// Returns the created message or an error if creation fails
func (s *messageService) CreateMessage(ctx context.Context, message *types.Message) (*types.Message, error) {
logger.Info(ctx, "Start creating message")
logger.Infof(ctx, "Creating message for session ID: %s", message.SessionID)
// Check if the session exists to validate the message belongs to a valid session
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d, session ID: %s", tenantID, message.SessionID)
_, err := s.sessionRepo.Get(ctx, tenantID, message.SessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
}
// Create the message in the repository
logger.Info(ctx, "Session exists, creating message")
createdMessage, err := s.messageRepo.CreateMessage(ctx, message)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": message.SessionID,
})
return nil, err
}
logger.Infof(ctx, "Message created successfully, ID: %s", createdMessage.ID)
return createdMessage, nil
}
// GetMessage retrieves a specific message by its ID within a session
// Parameters:
// - ctx: Context containing tenant information
// - sessionID: The ID of the session containing the message
// - messageID: The ID of the message to retrieve
//
// Returns the requested message or an error if retrieval fails
func (s *messageService) GetMessage(ctx context.Context, sessionID string, messageID string) (*types.Message, error) {
logger.Info(ctx, "Start getting message")
logger.Infof(ctx, "Getting message, session ID: %s, message ID: %s", sessionID, messageID)
// Verify the session exists before attempting to retrieve the message
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
}
// Retrieve the message from the repository
logger.Info(ctx, "Session exists, getting message")
message, err := s.messageRepo.GetMessage(ctx, sessionID, messageID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"message_id": messageID,
})
return nil, err
}
logger.Info(ctx, "Message retrieved successfully")
return message, nil
}
// GetMessagesBySession retrieves paginated messages for a specific session
// Parameters:
// - ctx: Context containing tenant information
// - sessionID: The ID of the session to get messages from
// - page: The page number for pagination (0-based)
// - pageSize: The number of messages per page
//
// Returns a slice of messages or an error if retrieval fails
func (s *messageService) GetMessagesBySession(ctx context.Context,
sessionID string, page int, pageSize int,
) ([]*types.Message, error) {
logger.Info(ctx, "Start getting messages by session")
logger.Infof(ctx, "Getting messages for session ID: %s, page: %d, pageSize: %d", sessionID, page, pageSize)
// Verify the session exists before retrieving messages
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
}
// Retrieve paginated messages
logger.Info(ctx, "Session exists, getting messages")
messages, err := s.messageRepo.GetMessagesBySession(ctx, sessionID, page, pageSize)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"page": page,
"page_size": pageSize,
})
return nil, err
}
logger.Infof(ctx, "Retrieved %d messages successfully", len(messages))
return messages, nil
}
// GetRecentMessagesBySession retrieves the most recent messages from a session
// This is typically used for loading the initial conversation history
// Parameters:
// - ctx: Context containing tenant information
// - sessionID: The ID of the session to get messages from
// - limit: Maximum number of messages to retrieve
//
// Returns a slice of recent messages or an error if retrieval fails
func (s *messageService) GetRecentMessagesBySession(ctx context.Context,
sessionID string, limit int,
) ([]*types.Message, error) {
logger.Info(ctx, "Start getting recent messages by session")
logger.Infof(ctx, "Getting recent messages for session ID: %s, limit: %d", sessionID, limit)
// Verify the session exists before retrieving messages
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
}
// Retrieve the most recent messages
logger.Info(ctx, "Session exists, getting recent messages")
messages, err := s.messageRepo.GetRecentMessagesBySession(ctx, sessionID, limit)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"limit": limit,
})
return nil, err
}
logger.Infof(ctx, "Retrieved %d recent messages successfully", len(messages))
return messages, nil
}
// GetMessagesBySessionBeforeTime retrieves messages sent before a specific time
// This is typically used for pagination when scrolling through conversation history
// Parameters:
// - ctx: Context containing tenant information
// - sessionID: The ID of the session to get messages from
// - beforeTime: Timestamp to retrieve messages before
// - limit: Maximum number of messages to retrieve
//
// Returns a slice of messages or an error if retrieval fails
func (s *messageService) GetMessagesBySessionBeforeTime(ctx context.Context,
sessionID string, beforeTime time.Time, limit int,
) ([]*types.Message, error) {
logger.Info(ctx, "Start getting messages before time")
logger.Infof(ctx, "Getting messages before %v for session ID: %s, limit: %d", beforeTime, sessionID, limit)
// Verify the session exists before retrieving messages
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
}
// Retrieve messages before the specified time
logger.Info(ctx, "Session exists, getting messages before time")
messages, err := s.messageRepo.GetMessagesBySessionBeforeTime(ctx, sessionID, beforeTime, limit)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"before_time": beforeTime,
"limit": limit,
})
return nil, err
}
logger.Infof(ctx, "Retrieved %d messages before time successfully", len(messages))
return messages, nil
}
// UpdateMessage updates an existing message's content or metadata
// Parameters:
// - ctx: Context containing tenant information
// - message: The message with updated fields
//
// Returns an error if the update fails
func (s *messageService) UpdateMessage(ctx context.Context, message *types.Message) error {
logger.Info(ctx, "Start updating message")
logger.Infof(ctx, "Updating message, ID: %s, session ID: %s", message.ID, message.SessionID)
// Verify the session exists before updating the message
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, message.SessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return err
}
// Update the message in the repository
logger.Info(ctx, "Session exists, updating message")
err = s.messageRepo.UpdateMessage(ctx, message)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": message.SessionID,
"message_id": message.ID,
})
return err
}
logger.Info(ctx, "Message updated successfully")
return nil
}
// DeleteMessage removes a message from a session
// Parameters:
// - ctx: Context containing tenant information
// - sessionID: The ID of the session containing the message
// - messageID: The ID of the message to delete
//
// Returns an error if deletion fails
func (s *messageService) DeleteMessage(ctx context.Context, sessionID string, messageID string) error {
logger.Info(ctx, "Start deleting message")
logger.Infof(ctx, "Deleting message, session ID: %s, message ID: %s", sessionID, messageID)
// Verify the session exists before deleting the message
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return err
}
// Delete the message from the repository
logger.Info(ctx, "Session exists, deleting message")
err = s.messageRepo.DeleteMessage(ctx, sessionID, messageID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"message_id": messageID,
})
return err
}
logger.Info(ctx, "Message deleted successfully")
return nil
}
+165
View File
@@ -0,0 +1,165 @@
package metric
// references: https://github.com/waygo/bleu
// Package bleu implements the BLEU method, which is used to evaluate
// the quality of machine translation. [1]
//
// The code in this package was largely ported from the corresponding package
// in Python NLTK. [2]
//
// [1] Papineni, Kishore, et al. "BLEU: a method for automatic evaluation of
// machine translation." Proceedings of the 40th annual meeting on
// association for computational linguistics. Association for Computational
// Linguistics, 2002.
//
// [2] http://www.nltk.org/_modules/nltk/align/bleu.html
import (
"encoding/json"
"log"
"math"
"strings"
"github.com/Tencent/WeKnora/internal/types"
)
type BLEUMetric struct {
smoothing bool
weights BLEUWeight
}
func NewBLEUMetric(smoothing bool, weights BLEUWeight) *BLEUMetric {
return &BLEUMetric{smoothing: smoothing, weights: weights}
}
type Sentence []string
type BLEUWeight []float64
var (
BLEU1Gram BLEUWeight = []float64{1.0, 0.0, 0.0, 0.0}
BLEU2Gram BLEUWeight = []float64{0.5, 0.5, 0.0, 0.0}
BLEU3Gram BLEUWeight = []float64{0.33, 0.33, 0.33, 0.0}
BLEU4Gram BLEUWeight = []float64{0.25, 0.25, 0.25, 0.25}
)
func (b *BLEUMetric) Compute(metricInput *types.MetricInput) float64 {
candidate := splitIntoWords(splitSentences(metricInput.GeneratedTexts))
references := []Sentence{splitIntoWords(splitSentences(metricInput.GeneratedGT))}
for i := range candidate {
candidate[i] = strings.ToLower(candidate[i])
}
for i := range references {
for u := range references[i] {
references[i][u] = strings.ToLower(references[i][u])
}
}
ps := make([]float64, len(b.weights))
for i := range b.weights {
ps[i] = b.modifiedPrecision(candidate, references, i+1)
}
s := 0.0
overlap := 0
for i := range b.weights {
w := b.weights[i]
pn := ps[i]
if pn > 0.0 {
overlap++
s += w * math.Log(pn)
}
}
if overlap == 0 {
return 0
}
bp := b.brevityPenalty(candidate, references)
return bp * math.Exp(s)
}
type phrase []string
func (p phrase) String() string {
b, err := json.Marshal(p)
if err != nil {
log.Fatal("encode error:", err)
}
return string(b)
}
func (b *BLEUMetric) getNphrase(s Sentence, n int) []phrase {
nphrase := []phrase{}
for i := 0; i < len(s)-n+1; i++ {
nphrase = append(nphrase, phrase(s[i:i+n]))
}
return nphrase
}
func (b *BLEUMetric) countNphrase(nphrase []phrase) map[string]int {
counts := map[string]int{}
for _, gram := range nphrase {
counts[gram.String()]++
}
return counts
}
func (b *BLEUMetric) modifiedPrecision(candidate Sentence, references []Sentence, n int) float64 {
nphrase := b.getNphrase(candidate, n)
if len(nphrase) == 0 {
return 0.0
}
counts := b.countNphrase(nphrase)
if len(counts) == 0 {
return 0.0
}
maxCounts := map[string]int{}
for i := range references {
referenceCounts := b.countNphrase(b.getNphrase(references[i], n))
for ngram := range counts {
if v, ok := maxCounts[ngram]; !ok {
maxCounts[ngram] = referenceCounts[ngram]
} else if v < referenceCounts[ngram] {
maxCounts[ngram] = referenceCounts[ngram]
}
}
}
clippedCounts := map[string]int{}
for ngram, count := range counts {
clippedCounts[ngram] = min(count, maxCounts[ngram])
}
smoothingFactor := 0.0
if b.smoothing {
smoothingFactor = 1.0
}
return (float64(sum(clippedCounts)) + smoothingFactor) / (float64(sum(counts)) + smoothingFactor)
}
func (b *BLEUMetric) brevityPenalty(candidate Sentence, references []Sentence) float64 {
c := len(candidate)
refLens := []int{}
for i := range references {
refLens = append(refLens, len(references[i]))
}
minDiffInd, minDiff := 0, -1
for i := range refLens {
if minDiff == -1 || abs(refLens[i]-c) < minDiff {
minDiffInd = i
minDiff = abs(refLens[i] - c)
}
}
r := refLens[minDiffInd]
if c > r {
return 1
}
return math.Exp(float64(1 - float64(r)/float64(c)))
}
@@ -0,0 +1,133 @@
package metric
import (
"regexp"
"strings"
"github.com/Tencent/WeKnora/internal/types"
)
func sum(m map[string]int) int {
s := 0
for _, v := range m {
s += v
}
return s
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func splitSentences(text string) []string {
// 编译正则表达式(匹配中文句号或英文句号)
re := regexp.MustCompile(`([。.])`)
// 分割文本并保留分隔符用于定位
split := re.Split(text, -1)
var sentences []string
current := strings.Builder{}
for i, s := range split {
// 交替获取文本段和分隔符(奇数为分隔符)
if i%2 == 0 {
current.WriteString(s)
} else {
// 当遇到分隔符时,完成当前句子
if current.Len() > 0 {
sentence := strings.TrimSpace(current.String())
if sentence != "" {
sentences = append(sentences, sentence)
}
current.Reset()
}
}
}
// 处理最后一个无分隔符的文本段
if remaining := strings.TrimSpace(current.String()); remaining != "" {
sentences = append(sentences, remaining)
}
return sentences
}
func splitIntoWords(sentences []string) []string {
// 正则匹配中英文段落(中文块、英文块、其他字符)
re := regexp.MustCompile(`([\p{Han}]+)|([a-zA-Z0-9_.,!?]+)|(\p{P})`)
var tokens []string
for _, text := range sentences {
matches := re.FindAllStringSubmatch(text, -1)
for _, groups := range matches {
chineseBlock := groups[1]
englishBlock := groups[2]
punctuation := groups[3]
switch {
case chineseBlock != "": // 处理中文部分
words := types.Jieba.Cut(chineseBlock, true)
tokens = append(tokens, words...)
case englishBlock != "": // 处理英文部分
engTokens := strings.Fields(englishBlock)
tokens = append(tokens, engTokens...)
case punctuation != "": // 保留标点符号
tokens = append(tokens, punctuation)
}
}
}
return tokens
}
func ToSet[T comparable](li []T) map[T]struct{} {
res := make(map[T]struct{}, len(li))
for _, v := range li {
res[v] = struct{}{}
}
return res
}
func SliceMap[T any, Y any](li []T, fn func(T) Y) []Y {
res := make([]Y, len(li))
for i, v := range li {
res[i] = fn(v)
}
return res
}
func Hit[T comparable](li []T, set map[T]struct{}) int {
count := 0
for _, v := range li {
if _, exist := set[v]; exist {
count++
}
}
return count
}
func Fold[T any, Y any](slice []T, initial Y, f func(Y, T) Y) Y {
accumulator := initial
for _, item := range slice {
accumulator = f(accumulator, item)
}
return accumulator
}
@@ -0,0 +1,70 @@
package metric
import (
"github.com/Tencent/WeKnora/internal/types"
)
// MAPMetric calculates Mean Average Precision for retrieval evaluation
type MAPMetric struct{}
// NewMAPMetric creates a new MAPMetric instance
func NewMAPMetric() *MAPMetric {
return &MAPMetric{}
}
// Compute calculates the Mean Average Precision score
func (m *MAPMetric) Compute(metricInput *types.MetricInput) float64 {
// Convert ground truth to sets for efficient lookup
gts := metricInput.RetrievalGT
ids := metricInput.RetrievalIDs
// Create sets of relevant document IDs for each query
gtSets := make([]map[int]struct{}, len(gts))
for i, gt := range gts {
gtSets[i] = make(map[int]struct{})
for _, docID := range gt {
gtSets[i][docID] = struct{}{}
}
}
var apSum float64 // Sum of average precision for all queries
// Calculate average precision for each query
for _, gtSet := range gtSets {
// Mark which predicted documents are relevant
predHits := make([]bool, len(ids))
for i, predID := range ids {
if _, ok := gtSet[predID]; ok {
predHits[i] = true
} else {
predHits[i] = false
}
}
var (
ap float64 // Average precision for current query
hitCount int // Number of relevant documents found
)
// Calculate precision at each rank position
for k := 0; k < len(predHits); k++ {
if predHits[k] {
hitCount++
// Precision at k: relevant docs found up to k / k
ap += float64(hitCount) / float64(k+1)
}
}
// Normalize by number of relevant documents
if hitCount > 0 {
ap /= float64(hitCount)
}
apSum += ap
}
// Handle case with no ground truth
if len(gtSets) == 0 {
return 0
}
// Return mean of average precision across all queries
return apSum / float64(len(gtSets))
}
@@ -0,0 +1,85 @@
package metric
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestMAPMetric_Compute(t *testing.T) {
tests := []struct {
name string
input *types.MetricInput
expected float64
}{
{
name: "total match",
input: &types.MetricInput{
RetrievalGT: [][]int{{2, 4, 6}},
RetrievalIDs: []int{2, 4, 6},
},
expected: 1.0,
},
{
name: "no match",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2}},
RetrievalIDs: []int{3, 4},
},
expected: 0.0,
},
{
name: "partial match",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}},
RetrievalIDs: []int{2, 5, 1, 3},
},
// AP = (1/1 + 2/3 + 3/4)/3 ≈ 0.80555555
expected: 0.8055555555555555,
},
{
name: "empty ground truth",
input: &types.MetricInput{
RetrievalGT: [][]int{},
RetrievalIDs: []int{1, 2},
},
expected: 0.0,
},
{
name: "multiple queries",
input: &types.MetricInput{
RetrievalGT: [][]int{
{1, 2},
{3, 4},
},
RetrievalIDs: []int{1, 3, 2, 4},
},
// Query1 AP: (1/1 + 2/3)/2 ≈ 0.8333
// Query2 AP: (1/2 + 2/4)/2 = 0.5
// MAP: (0.8333 + 0.5)/2 ≈ 0.6667
expected: 0.6666666666666666,
},
}
metric := NewMAPMetric()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := metric.Compute(tt.input)
if !almostEqual(got, tt.expected, 1e-6) {
t.Errorf("Compute() = %v, want %v", got, tt.expected)
}
})
}
}
// Helper function to compare floating point numbers with tolerance
func almostEqual(a, b, tolerance float64) bool {
if a == b {
return true
}
diff := a - b
if diff < 0 {
diff = -diff
}
return diff < tolerance
}
@@ -0,0 +1,48 @@
package metric
import (
"github.com/Tencent/WeKnora/internal/types"
)
// MRRMetric calculates Mean Reciprocal Rank for retrieval evaluation
type MRRMetric struct{}
// NewMRRMetric creates a new MRRMetric instance
func NewMRRMetric() *MRRMetric {
return &MRRMetric{}
}
// Compute calculates the Mean Reciprocal Rank score
func (m *MRRMetric) Compute(metricInput *types.MetricInput) float64 {
// Get ground truth and predicted IDs
gts := metricInput.RetrievalGT
ids := metricInput.RetrievalIDs
// Convert ground truth to sets for efficient lookup
gtSets := make([]map[int]struct{}, len(gts))
for i, gt := range gts {
gtSets[i] = make(map[int]struct{})
for _, docID := range gt {
gtSets[i][docID] = struct{}{}
}
}
var sumRR float64 // Sum of reciprocal ranks
// Calculate reciprocal rank for each query
for _, gtSet := range gtSets {
// Find first relevant document in results
for i, predID := range ids {
if _, ok := gtSet[predID]; ok {
// Reciprocal rank is 1/position (1-based)
sumRR += 1.0 / float64(i+1)
break // Only consider first relevant document
}
}
}
// Handle case with no ground truth
if len(gtSets) == 0 {
return 0
}
// Return mean of reciprocal ranks
return sumRR / float64(len(gtSets))
}
@@ -0,0 +1,72 @@
package metric
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestMRRMetric_Compute(t *testing.T) {
tests := []struct {
name string
input *types.MetricInput
expected float64
}{
{
name: "perfect match - first position",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2}},
RetrievalIDs: []int{1, 2, 3},
},
// RR = 1/1 = 1.0
expected: 1.0,
},
{
name: "match at second position",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2}},
RetrievalIDs: []int{3, 1, 2},
},
// RR = 1/2 = 0.5
expected: 0.5,
},
{
name: "no match",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2}},
RetrievalIDs: []int{3, 4},
},
expected: 0.0,
},
{
name: "multiple queries",
input: &types.MetricInput{
RetrievalGT: [][]int{
{1, 2}, // RR = 1/1 = 1.0
{3, 4}, // RR = 1/2 = 0.5
},
RetrievalIDs: []int{1, 3, 2, 4},
},
// MRR = (1.0 + 0.5)/2 = 0.75
expected: 0.75,
},
{
name: "empty ground truth",
input: &types.MetricInput{
RetrievalGT: [][]int{},
RetrievalIDs: []int{1, 2},
},
expected: 0.0,
},
}
metric := NewMRRMetric()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := metric.Compute(tt.input)
if !almostEqual(got, tt.expected, 1e-6) {
t.Errorf("Compute() = %v, want %v", got, tt.expected)
}
})
}
}
@@ -0,0 +1,78 @@
package metric
import (
"math"
"github.com/Tencent/WeKnora/internal/types"
)
// NDCGMetric calculates Normalized Discounted Cumulative Gain
type NDCGMetric struct {
k int // Top k results to consider
}
// NewNDCGMetric creates a new NDCGMetric instance with given k value
func NewNDCGMetric(k int) *NDCGMetric {
return &NDCGMetric{k: k}
}
// Compute calculates the NDCG score
func (n *NDCGMetric) Compute(metricInput *types.MetricInput) float64 {
gts := metricInput.RetrievalGT
ids := metricInput.RetrievalIDs
// Limit results to top k
if len(ids) > n.k {
ids = ids[:n.k]
}
// Create set of relevant documents and count total relevant
gtSets := make(map[int]struct{}, len(gts))
countGt := 0
for _, gt := range gts {
countGt += len(gt)
for _, g := range gt {
gtSets[g] = struct{}{}
}
}
// Assign relevance scores (1 for relevant, 0 otherwise)
relevanceScores := make(map[int]int)
for _, docID := range ids {
if _, exist := gtSets[docID]; exist {
relevanceScores[docID] = 1
} else {
relevanceScores[docID] = 0
}
}
// Calculate DCG (Discounted Cumulative Gain)
var dcg float64
for i, docID := range ids {
dcg += (math.Pow(2, float64(relevanceScores[docID])) - 1) / math.Log2(float64(i+2))
}
// Create ideal ranking (all relevant docs first)
idealLen := min(countGt, len(ids))
idealPred := make([]int, len(ids))
for i := 0; i < len(ids); i++ {
if i < idealLen {
idealPred[i] = 1
} else {
idealPred[i] = 0
}
}
// Calculate IDCG (Ideal DCG)
var idcg float64
for i, relevance := range idealPred {
idcg += float64(relevance) / math.Log2(float64(i+2))
}
// Handle division by zero case
if idcg == 0 {
return 0
}
// NDCG = DCG / IDCG
return dcg / idcg
}
@@ -0,0 +1,33 @@
package metric
import (
"github.com/Tencent/WeKnora/internal/types"
)
// PrecisionMetric calculates precision for retrieval evaluation
type PrecisionMetric struct{}
// NewPrecisionMetric creates a new PrecisionMetric instance
func NewPrecisionMetric() *PrecisionMetric {
return &PrecisionMetric{}
}
// Compute calculates the precision score
func (r *PrecisionMetric) Compute(metricInput *types.MetricInput) float64 {
// Get ground truth and predicted IDs
gts := metricInput.RetrievalGT
ids := metricInput.RetrievalIDs
// Convert ground truth to sets for efficient lookup
gtSets := SliceMap(gts, ToSet)
// Count total hits across all queries
ahit := Fold(gtSets, 0, func(a int, b map[int]struct{}) int { return a + Hit(ids, b) })
// Handle case with no ground truth
if len(gts) == 0 {
return 0.0
}
// Precision = total hits / number of queries
return float64(ahit) / float64(len(gts))
}
@@ -0,0 +1,67 @@
package metric
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestPrecisionMetric_Compute(t *testing.T) {
tests := []struct {
name string
input *types.MetricInput
expected float64
}{
{
name: "perfect match",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 3, 5}},
RetrievalIDs: []int{1, 3, 5},
},
expected: 1.0,
},
{
name: "half match",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}},
RetrievalIDs: []int{1, 4, 2},
},
expected: 0.6666666666666666,
},
{
name: "no match",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}},
RetrievalIDs: []int{4, 5, 6},
},
expected: 0.0,
},
{
name: "empty retrieval",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}},
RetrievalIDs: []int{},
},
expected: 0.0,
},
{
name: "multiple ground truths",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2}, {3, 4}},
RetrievalIDs: []int{1, 3, 5},
},
expected: 0.3333333333333333,
},
}
pm := NewPrecisionMetric()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := pm.Compute(tt.input)
if got != tt.expected {
t.Errorf("Compute() = %v, want %v", got, tt.expected)
}
})
}
}
@@ -0,0 +1,33 @@
package metric
import (
"github.com/Tencent/WeKnora/internal/types"
)
// RecallMetric calculates recall for retrieval evaluation
type RecallMetric struct{}
// NewRecallMetric creates a new RecallMetric instance
func NewRecallMetric() *RecallMetric {
return &RecallMetric{}
}
// Compute calculates the recall score
func (r *RecallMetric) Compute(metricInput *types.MetricInput) float64 {
// Get ground truth and predicted IDs
gts := metricInput.RetrievalGT
ids := metricInput.RetrievalIDs
// Convert ground truth to sets for efficient lookup
gtSets := SliceMap(gts, ToSet)
// Count total hits across all relevant documents
ahit := Fold(gtSets, 0, func(a int, b map[int]struct{}) int { return a + Hit(ids, b) })
// Handle case with no ground truth
if len(gtSets) == 0 {
return 0.0
}
// Recall = total hits / total relevant documents
return float64(ahit) / float64(len(gtSets))
}
@@ -0,0 +1,70 @@
package metric
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestRecallMetric_Compute(t *testing.T) {
tests := []struct {
name string
input *types.MetricInput
expected float64
}{
{
name: "perfect recall - all ground truth retrieved",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}},
RetrievalIDs: []int{1, 2, 3, 4},
},
expected: 1.0,
},
{
name: "partial recall - some ground truth retrieved",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}, {4, 5}},
RetrievalIDs: []int{1, 4, 6},
},
// 命中2个ground truth集合中的元素(a和d)
expected: 0.41666666666666663, // (1/3 + 1/2) / 2 = 0.41666 (每个ground truth集合只要命中一个就算召回)
},
{
name: "no recall - no ground truth retrieved",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}},
RetrievalIDs: []int{4, 5, 6},
},
expected: 0.0,
},
{
name: "empty retrieval list",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2, 3}},
RetrievalIDs: []int{},
},
expected: 0.0,
},
{
name: "multiple ground truth sets",
input: &types.MetricInput{
RetrievalGT: [][]int{{1, 2}, {3, 4}, {5, 6}},
RetrievalIDs: []int{1, 3, 7},
},
// 命中了前两个ground truth集合(a和c)
expected: 0.3333333333333333, // 1/3≈0.333...
},
}
rm := NewRecallMetric()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := rm.Compute(tt.input)
if got != tt.expected {
t.Errorf("Compute() = %v, want %v", got, tt.expected)
}
})
}
}
@@ -0,0 +1,72 @@
package metric
import "github.com/Tencent/WeKnora/internal/types"
// reference: https://github.com/dd-Rebecca/rouge
// RougeMetric implements ROUGE (Recall-Oriented Understudy for Gisting Evaluation) metrics
// for evaluating text summarization quality by comparing generated text to reference text
type RougeMetric struct {
exclusive bool // Whether to use exclusive matching mode
metric string // ROUGE metric type (e.g. "rouge-1", "rouge-l")
stats string // Statistic to return (e.g. "f", "p", "r")
}
// AvailableMetrics defines all supported ROUGE variants and their calculation functions
var AvailableMetrics = map[string]func([]string, []string, bool) map[string]float64{
"rouge-1": func(hyp, ref []string, exclusive bool) map[string]float64 {
return rougeN(hyp, ref, 1, false, exclusive) // Unigram-based ROUGE
},
"rouge-2": func(hyp, ref []string, exclusive bool) map[string]float64 {
return rougeN(hyp, ref, 2, false, exclusive) // Bigram-based ROUGE
},
"rouge-3": func(hyp, ref []string, exclusive bool) map[string]float64 {
return rougeN(hyp, ref, 3, false, exclusive) // Trigram-based ROUGE
},
"rouge-4": func(hyp, ref []string, exclusive bool) map[string]float64 {
return rougeN(hyp, ref, 4, false, exclusive) // 4-gram based ROUGE
},
"rouge-5": func(hyp, ref []string, exclusive bool) map[string]float64 {
return rougeN(hyp, ref, 5, false, exclusive) // 5-gram based ROUGE
},
"rouge-l": func(hyp, ref []string, exclusive bool) map[string]float64 {
return rougeLSummaryLevel(hyp, ref, false, exclusive) // Longest common subsequence based ROUGE
},
}
// NewRougeMetric creates a new ROUGE metric calculator
func NewRougeMetric(exclusive bool, metrics, stats string) *RougeMetric {
r := &RougeMetric{
exclusive: exclusive,
metric: metrics,
stats: stats,
}
return r
}
// Compute calculates the ROUGE score between generated text and reference text
func (r *RougeMetric) Compute(metricInput *types.MetricInput) float64 {
hyps := []string{metricInput.GeneratedTexts} // Generated/hypothesis text
refs := []string{metricInput.GeneratedGT} // Reference/ground truth text
scores := 0.0
count := 0
// Calculate scores for each hypothesis-reference pair
for i := 0; i < len(hyps); i++ {
hyp := splitSentences(hyps[i]) // Split into sentences
ref := splitSentences(refs[i])
// Get appropriate ROUGE calculation function
fn := AvailableMetrics[r.metric]
sc := fn(hyp, ref, r.exclusive)
scores += sc[r.stats] // Accumulate specified statistic (f1/precision/recall)
count++
}
if count == 0 {
return 0 // Avoid division by zero
}
return scores / float64(count) // Return average score
}
@@ -0,0 +1,252 @@
package metric
/*
# -*- coding: utf-8 -*-
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ROUGE Metric Implementation
This is a very slightly version of:
https://github.com/pltrdy/seq2seq/blob/master/seq2seq/metrics/rouge.py
---
ROUGe metric implementation.
This is a modified and slightly extended verison of
https://github.com/miso-belica/sumy/blob/dev/sumy/evaluation/rouge.py.
*/
import (
"strings"
)
type Ngrams struct {
ngrams map[string]int
exclusive bool
}
func NewNgrams(exclusive bool) *Ngrams {
return &Ngrams{ngrams: make(map[string]int), exclusive: exclusive}
}
func (n *Ngrams) Add(o string) {
if n.exclusive {
n.ngrams[o] = 1
} else {
n.ngrams[o]++
}
}
func (n *Ngrams) Len() int {
return len(n.ngrams)
}
func (n *Ngrams) Intersection(o *Ngrams) *Ngrams {
intersection := NewNgrams(n.exclusive)
for k := range n.ngrams {
if _, ok := o.ngrams[k]; ok {
intersection.Add(k)
}
}
return intersection
}
func (n *Ngrams) BatchAdd(o []string) {
for _, v := range o {
n.Add(v)
}
}
func (n *Ngrams) Union(others ...*Ngrams) *Ngrams {
union := NewNgrams(n.exclusive)
for k := range n.ngrams {
union.Add(k)
}
for _, other := range others {
for k := range other.ngrams {
union.Add(k)
}
}
return union
}
func getNgrams(n int, text []string, exclusive bool) *Ngrams {
ngramSet := NewNgrams(exclusive)
for i := 0; i <= len(text)-n; i++ {
ngramSet.Add(strings.Join(text[i:i+n], " "))
}
return ngramSet
}
func getWordNgrams(n int, sentences []string, exclusive bool) *Ngrams {
words := splitIntoWords(sentences)
return getNgrams(n, words, exclusive)
}
func lenLcs(x, y []string) int {
table := lcs(x, y)
return table[len(x)][len(y)]
}
func lcs(x, y []string) [][]int {
n, m := len(x), len(y)
table := make([][]int, n+1)
for i := range table {
table[i] = make([]int, m+1)
}
for i := 1; i <= n; i++ {
for j := 1; j <= m; j++ {
if x[i-1] == y[j-1] {
table[i][j] = table[i-1][j-1] + 1
} else {
table[i][j] = max(table[i-1][j], table[i][j-1])
}
}
}
return table
}
func reconLcs(x, y []string, exclusive bool) *Ngrams {
i, j := len(x), len(y)
table := lcs(x, y)
var reconFunc func(int, int) []string
reconFunc = func(i, j int) []string {
if i == 0 || j == 0 {
return []string{}
} else if x[i-1] == y[j-1] {
return append(reconFunc(i-1, j-1), x[i-1])
} else if table[i-1][j] > table[i][j-1] {
return reconFunc(i-1, j)
} else {
return reconFunc(i, j-1)
}
}
reconList := reconFunc(i, j)
ngramList := NewNgrams(exclusive)
for _, word := range reconList {
ngramList.Add(word)
}
return ngramList
}
func rougeN(evaluatedSentences, referenceSentences []string, n int, rawResults, exclusive bool) map[string]float64 {
evaluatedNgrams := getWordNgrams(n, evaluatedSentences, exclusive)
referenceNgrams := getWordNgrams(n, referenceSentences, exclusive)
referenceCount := referenceNgrams.Len()
evaluatedCount := evaluatedNgrams.Len()
overlappingNgrams := evaluatedNgrams.Intersection(referenceNgrams)
overlappingCount := overlappingNgrams.Len()
results := make(map[string]float64)
if rawResults {
results["hyp"] = float64(evaluatedCount)
results["ref"] = float64(referenceCount)
results["overlap"] = float64(overlappingCount)
return results
} else {
return calculateRougeN(evaluatedCount, referenceCount, overlappingCount)
}
}
func calculateRougeN(evaluatedCount, referenceCount, overlappingCount int) map[string]float64 {
results := make(map[string]float64)
if evaluatedCount == 0 {
results["p"] = 0.0
} else {
results["p"] = float64(overlappingCount) / float64(evaluatedCount)
}
if referenceCount == 0 {
results["r"] = 0.0
} else {
results["r"] = float64(overlappingCount) / float64(referenceCount)
}
results["f"] = 2.0 * ((results["p"] * results["r"]) / (results["p"] + results["r"] + 1e-8))
return results
}
func unionLcs(evaluatedSentences []string, referenceSentence string, prevUnion *Ngrams, exclusive bool) (int, *Ngrams) {
if prevUnion == nil {
prevUnion = NewNgrams(exclusive)
}
lcsUnion := prevUnion
prevCount := len(prevUnion.ngrams)
referenceWords := splitIntoWords([]string{referenceSentence})
combinedLcsLength := 0
for _, evalS := range evaluatedSentences {
evaluatedWords := splitIntoWords([]string{evalS})
lcs := reconLcs(referenceWords, evaluatedWords, exclusive)
combinedLcsLength += lcs.Len()
lcsUnion = lcsUnion.Union(lcs)
}
newLcsCount := lcsUnion.Len() - prevCount
return newLcsCount, lcsUnion
}
func rougeLSummaryLevel(evaluatedSentences, referenceSentences []string, rawResults, exclusive bool) map[string]float64 {
referenceNgrams := NewNgrams(exclusive)
referenceNgrams.BatchAdd(splitIntoWords(referenceSentences))
m := referenceNgrams.Len()
evaluatedNgrams := NewNgrams(exclusive)
evaluatedNgrams.BatchAdd(splitIntoWords(evaluatedSentences))
n := evaluatedNgrams.Len()
unionLcsSumAcrossAllReferences := 0
union := NewNgrams(exclusive)
for _, refS := range referenceSentences {
lcsCount, newUnion := unionLcs(evaluatedSentences, refS, union, exclusive)
union = newUnion
unionLcsSumAcrossAllReferences += lcsCount
}
llcs := unionLcsSumAcrossAllReferences
var rLcs float64
if m == 0 {
rLcs = 0.0
} else {
rLcs = float64(llcs) / float64(m)
}
var pLcs float64
if n == 0 {
pLcs = 0.0
} else {
pLcs = float64(llcs) / float64(n)
}
fLcs := 2.0 * ((pLcs * rLcs) / (pLcs + rLcs + 1e-8))
results := make(map[string]float64)
if rawResults {
results["hyp"] = float64(n)
results["ref"] = float64(m)
results["overlap"] = float64(llcs)
return results
} else {
results["f"] = fLcs
results["p"] = pLcs
results["r"] = rLcs
return results
}
}
+167
View File
@@ -0,0 +1,167 @@
package service
import (
"context"
"sync"
"github.com/Tencent/WeKnora/internal/application/service/metric"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// MetricList stores and aggregates metric results
type MetricList struct {
results []*types.MetricResult
}
// metricCalculators defines all metrics to be calculated
var metricCalculators = []struct {
calc interfaces.Metrics // Metric calculator implementation
getField func(*types.MetricResult) *float64 // Field accessor for result
}{
// Retrieval Metrics
{metric.NewPrecisionMetric(), func(r *types.MetricResult) *float64 { return &r.RetrievalMetrics.Precision }},
{metric.NewRecallMetric(), func(r *types.MetricResult) *float64 { return &r.RetrievalMetrics.Recall }},
{metric.NewNDCGMetric(3), func(r *types.MetricResult) *float64 { return &r.RetrievalMetrics.NDCG3 }},
{metric.NewNDCGMetric(10), func(r *types.MetricResult) *float64 { return &r.RetrievalMetrics.NDCG10 }},
{metric.NewMRRMetric(), func(r *types.MetricResult) *float64 { return &r.RetrievalMetrics.MRR }},
{metric.NewMAPMetric(), func(r *types.MetricResult) *float64 { return &r.RetrievalMetrics.MAP }},
// Generation Metrics
{metric.NewBLEUMetric(true, metric.BLEU1Gram), func(r *types.MetricResult) *float64 {
return &r.GenerationMetrics.BLEU1
}},
{metric.NewBLEUMetric(true, metric.BLEU2Gram), func(r *types.MetricResult) *float64 {
return &r.GenerationMetrics.BLEU2
}},
{metric.NewBLEUMetric(true, metric.BLEU4Gram), func(r *types.MetricResult) *float64 {
return &r.GenerationMetrics.BLEU4
}},
{metric.NewRougeMetric(true, "rouge-1", "f"), func(r *types.MetricResult) *float64 {
return &r.GenerationMetrics.ROUGE1
}},
{metric.NewRougeMetric(true, "rouge-2", "f"), func(r *types.MetricResult) *float64 {
return &r.GenerationMetrics.ROUGE2
}},
{metric.NewRougeMetric(true, "rouge-l", "f"), func(r *types.MetricResult) *float64 {
return &r.GenerationMetrics.ROUGEL
}},
}
// Append calculates and stores metrics for given input
func (m *MetricList) Append(metricInput *types.MetricInput) {
result := &types.MetricResult{}
// Calculate all configured metrics
for _, c := range metricCalculators {
score := c.calc.Compute(metricInput)
*c.getField(result) = score
}
logger.Infof(context.Background(), "metric: %v", result)
m.results = append(m.results, result)
}
// Avg calculates average of all stored metric results
func (m *MetricList) Avg() *types.MetricResult {
if len(m.results) == 0 {
return &types.MetricResult{}
}
avgResult := &types.MetricResult{}
count := float64(len(m.results))
// Calculate average for each metric
for _, config := range metricCalculators {
sum := 0.0
for _, r := range m.results {
sum += *config.getField(r)
}
*config.getField(avgResult) = sum / count
}
return avgResult
}
// HookMetric tracks evaluation metrics for QA pairs
type HookMetric struct {
task *types.EvaluationTask
qaPairMetricList []*qaPairMetric // Per-QA pair metrics
metricResults *MetricList // Aggregated results
mu *sync.RWMutex // Thread safety
}
// qaPairMetric stores metrics for a single QA pair
type qaPairMetric struct {
qaPair *types.QAPair
searchResult []*types.SearchResult
rerankResult []*types.SearchResult
chatResponse *types.ChatResponse
}
// NewHookMetric creates a new HookMetric with given capacity
func NewHookMetric(capacity int) *HookMetric {
return &HookMetric{
metricResults: &MetricList{},
qaPairMetricList: make([]*qaPairMetric, capacity),
mu: &sync.RWMutex{},
}
}
// recordInit initializes metric tracking for a QA pair
func (h *HookMetric) recordInit(index int) {
h.qaPairMetricList[index] = &qaPairMetric{}
}
// recordQaPair records the QA pair data
func (h *HookMetric) recordQaPair(index int, qaPair *types.QAPair) {
h.qaPairMetricList[index].qaPair = qaPair
}
// recordSearchResult records search results
func (h *HookMetric) recordSearchResult(index int, searchResult []*types.SearchResult) {
h.qaPairMetricList[index].searchResult = searchResult
}
// recordRerankResult records reranked results
func (h *HookMetric) recordRerankResult(index int, rerankResult []*types.SearchResult) {
h.qaPairMetricList[index].rerankResult = rerankResult
}
// recordChatResponse records the generated chat response
func (h *HookMetric) recordChatResponse(index int, chatResponse *types.ChatResponse) {
h.qaPairMetricList[index].chatResponse = chatResponse
}
// recordFinish finalizes metrics for a QA pair
func (h *HookMetric) recordFinish(index int) {
// Prepare retrieval IDs from rerank results
retrievalIDs := make([]int, len(h.qaPairMetricList[index].rerankResult))
for i, r := range h.qaPairMetricList[index].rerankResult {
retrievalIDs[i] = r.ChunkIndex
}
// Get generated text if available
generatedTexts := ""
if h.qaPairMetricList[index].chatResponse != nil {
generatedTexts = h.qaPairMetricList[index].chatResponse.Content
}
// Prepare metric input data
metricInput := &types.MetricInput{
RetrievalGT: [][]int{h.qaPairMetricList[index].qaPair.PIDs},
RetrievalIDs: retrievalIDs,
GeneratedTexts: generatedTexts,
GeneratedGT: h.qaPairMetricList[index].qaPair.Answer,
}
// Thread-safe append of metrics
h.mu.Lock()
defer h.mu.Unlock()
h.metricResults.Append(metricInput)
}
// MetricResult returns the averaged metric results
func (h *HookMetric) MetricResult() *types.MetricResult {
h.mu.RLock()
defer h.mu.RUnlock()
return h.metricResults.Avg()
}
+327
View File
@@ -0,0 +1,327 @@
package service
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// ErrModelNotFound is returned when a model cannot be found in the repository
var ErrModelNotFound = errors.New("model not found")
// modelService implements the model service interface
type modelService struct {
repo interfaces.ModelRepository
ollamaService *ollama.OllamaService
}
// NewModelService creates a new model service instance
func NewModelService(repo interfaces.ModelRepository, ollamaService *ollama.OllamaService) interfaces.ModelService {
return &modelService{
repo: repo,
ollamaService: ollamaService,
}
}
// CreateModel creates a new model in the repository
// For local models, it initiates an asynchronous download process
// Remote models are immediately set to active status
func (s *modelService) CreateModel(ctx context.Context, model *types.Model) error {
logger.Info(ctx, "Start creating model")
logger.Infof(ctx, "Creating model: %s, type: %s, source: %s", model.Name, model.Type, model.Source)
// Handle remote models (e.g., OpenAI, Azure)
if model.Source == types.ModelSourceRemote {
logger.Info(ctx, "Remote model detected, setting status to active")
model.Status = types.ModelStatusActive
logger.Info(ctx, "Saving remote model to repository")
err := s.repo.Create(ctx, model)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_name": model.Name,
"model_type": model.Type,
})
return err
}
logger.Infof(ctx, "Remote model created successfully: %s", model.ID)
return nil
}
// Handle local models (e.g., Ollama)
logger.Info(ctx, "Local model detected, setting status to downloading")
model.Status = types.ModelStatusDownloading
logger.Info(ctx, "Saving local model to repository")
err := s.repo.Create(ctx, model)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_name": model.Name,
"model_type": model.Type,
})
return err
}
// Start asynchronous model download
logger.Infof(ctx, "Starting background download for model: %s", model.Name)
newCtx := logger.CloneContext(ctx)
go func() {
logger.Info(newCtx, "Background download started")
err := s.ollamaService.PullModel(newCtx, model.Name)
if err != nil {
logger.ErrorWithFields(newCtx, err, map[string]interface{}{
"model_name": model.Name,
})
model.Status = types.ModelStatusDownloadFailed
} else {
logger.Infof(newCtx, "Model download completed successfully: %s", model.Name)
model.Status = types.ModelStatusActive
}
logger.Infof(newCtx, "Updating model status to: %s", model.Status)
s.repo.Update(newCtx, model)
}()
logger.Infof(ctx, "Model creation initiated successfully: %s", model.ID)
return nil
}
// GetModelByID retrieves a model by its ID
// Returns an error if the model is not found or is in a non-active state
func (s *modelService) GetModelByID(ctx context.Context, id string) (*types.Model, error) {
logger.Info(ctx, "Start getting model by ID")
logger.Infof(ctx, "Getting model with ID: %s", id)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
// Fetch model from repository
model, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": id,
"tenant_id": tenantID,
})
return nil, err
}
// Check if model exists
if model == nil {
logger.Error(ctx, "Model not found")
return nil, ErrModelNotFound
}
logger.Infof(ctx, "Model found, name: %s, status: %s", model.Name, model.Status)
// Check model status
if model.Status == types.ModelStatusActive {
logger.Info(ctx, "Model is active and ready to use")
return model, nil
}
if model.Status == types.ModelStatusDownloading {
logger.Warn(ctx, "Model is currently downloading")
return nil, errors.New("model is currently downloading")
}
if model.Status == types.ModelStatusDownloadFailed {
logger.Error(ctx, "Model download failed")
return nil, errors.New("model download failed")
}
logger.Error(ctx, "Model status is abnormal")
return nil, errors.New("abnormal model status")
}
// ListModels returns all models belonging to the tenant
func (s *modelService) ListModels(ctx context.Context) ([]*types.Model, error) {
logger.Info(ctx, "Start listing models")
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Listing models for tenant ID: %d", tenantID)
// List models from repository with no additional filters
models, err := s.repo.List(ctx, tenantID, "", "")
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
})
return nil, err
}
logger.Infof(ctx, "Retrieved %d models successfully", len(models))
return models, nil
}
// UpdateModel updates an existing model in the repository
func (s *modelService) UpdateModel(ctx context.Context, model *types.Model) error {
logger.Info(ctx, "Start updating model")
logger.Infof(ctx, "Updating model ID: %s, name: %s", model.ID, model.Name)
// Update model in repository
err := s.repo.Update(ctx, model)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": model.ID,
"model_name": model.Name,
})
return err
}
logger.Infof(ctx, "Model updated successfully: %s", model.ID)
return nil
}
// DeleteModel removes a model from the repository
func (s *modelService) DeleteModel(ctx context.Context, id string) error {
logger.Info(ctx, "Start deleting model")
logger.Infof(ctx, "Deleting model ID: %s", id)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
// Delete model from repository
err := s.repo.Delete(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": id,
"tenant_id": tenantID,
})
return err
}
logger.Infof(ctx, "Model deleted successfully: %s", id)
return nil
}
// GetEmbeddingModel retrieves and initializes an embedding model instance
// Takes a model ID and returns an Embedder interface implementation
func (s *modelService) GetEmbeddingModel(ctx context.Context, modelId string) (embedding.Embedder, error) {
logger.Info(ctx, "Start getting embedding model")
logger.Infof(ctx, "Getting embedding model with ID: %s", modelId)
// Get the model details
model, err := s.GetModelByID(ctx, modelId)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": modelId,
})
return nil, err
}
logger.Info(ctx, "Creating embedder instance")
logger.Infof(ctx, "Model name: %s, source: %s", model.Name, model.Source)
// Initialize the embedder with model configuration
embedder, err := embedding.NewEmbedder(embedding.Config{
Source: model.Source,
BaseURL: model.Parameters.BaseURL,
APIKey: model.Parameters.APIKey,
ModelID: model.ID,
ModelName: model.Name,
Dimensions: model.Parameters.EmbeddingParameters.Dimension,
TruncatePromptTokens: model.Parameters.EmbeddingParameters.TruncatePromptTokens,
})
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": model.ID,
"model_name": model.Name,
})
return nil, err
}
logger.Info(ctx, "Embedding model initialized successfully")
return embedder, nil
}
// GetRerankModel retrieves and initializes a reranking model instance
// Takes a model ID and returns a Reranker interface implementation
func (s *modelService) GetRerankModel(ctx context.Context, modelId string) (rerank.Reranker, error) {
logger.Info(ctx, "Start getting rerank model")
logger.Infof(ctx, "Getting rerank model with ID: %s", modelId)
// Get the model details
model, err := s.GetModelByID(ctx, modelId)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": modelId,
})
return nil, err
}
logger.Info(ctx, "Creating reranker instance")
logger.Infof(ctx, "Model name: %s, source: %s", model.Name, model.Source)
// Initialize the reranker with model configuration
reranker, err := rerank.NewReranker(&rerank.RerankerConfig{
ModelID: model.ID,
APIKey: model.Parameters.APIKey,
BaseURL: model.Parameters.BaseURL,
ModelName: model.Name,
Source: model.Source,
})
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": model.ID,
"model_name": model.Name,
})
return nil, err
}
logger.Info(ctx, "Rerank model initialized successfully")
return reranker, nil
}
// GetChatModel retrieves and initializes a chat model instance
// Takes a model ID and returns a Chat interface implementation
func (s *modelService) GetChatModel(ctx context.Context, modelId string) (chat.Chat, error) {
logger.Info(ctx, "Start getting chat model")
logger.Infof(ctx, "Getting chat model with ID: %s", modelId)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
// Get the model directly from repository to avoid status checks
model, err := s.repo.GetByID(ctx, tenantID, modelId)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": modelId,
"tenant_id": tenantID,
})
return nil, err
}
if model == nil {
logger.Error(ctx, "Chat model not found")
return nil, ErrModelNotFound
}
logger.Info(ctx, "Creating chat model instance")
logger.Infof(ctx, "Model name: %s, source: %s", model.Name, model.Source)
// Initialize the chat model with model configuration
chatModel, err := chat.NewChat(&chat.ChatConfig{
ModelID: model.ID,
APIKey: model.Parameters.APIKey,
BaseURL: model.Parameters.BaseURL,
ModelName: model.Name,
Source: model.Source,
})
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": model.ID,
"model_name": model.Name,
})
return nil, err
}
logger.Info(ctx, "Chat model initialized successfully")
return chatModel, nil
}
@@ -0,0 +1,289 @@
package retriever
import (
"context"
"fmt"
"maps"
"slices"
"sync"
"sync/atomic"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/runtime"
"github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"go.opentelemetry.io/otel/attribute"
)
// engineInfo holds information about a retrieve engine and its supported retriever types
type engineInfo struct {
retrieveEngine interfaces.RetrieveEngineService
retrieverType []types.RetrieverType
}
// CompositeRetrieveEngine implements a composite pattern for retrieval engines,
// delegating operations to all registered engines
type CompositeRetrieveEngine struct {
engineInfos []*engineInfo
}
// Retrieve performs retrieval operations by delegating to the appropriate engine
// based on the retriever type specified in the parameters
func (c *CompositeRetrieveEngine) Retrieve(ctx context.Context,
retrieveParams []types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
return concurrentRetrieve(ctx, retrieveParams,
func(ctx context.Context, param types.RetrieveParams, results *[]*types.RetrieveResult, mu *sync.Mutex) error {
found := false
for _, engineInfo := range c.engineInfos {
if slices.Contains(engineInfo.retrieverType, param.RetrieverType) {
result, err := engineInfo.retrieveEngine.Retrieve(ctx, param)
if err != nil {
return err
}
mu.Lock()
*results = append(*results, result...)
mu.Unlock()
found = true
break
}
}
if !found {
return fmt.Errorf("retriever type %s not found", param.RetrieverType)
}
return nil
},
)
}
// NewCompositeRetrieveEngine creates a new composite retrieve engine with the given parameters
func NewCompositeRetrieveEngine(engineParams []types.RetrieverEngineParams) (*CompositeRetrieveEngine, error) {
var registry interfaces.RetrieveEngineRegistry
runtime.GetContainer().Invoke(func(r interfaces.RetrieveEngineRegistry) {
registry = r
})
engineInfos := make(map[types.RetrieverEngineType]*engineInfo)
for _, engineParam := range engineParams {
repo, err := registry.GetRetrieveEngineService(engineParam.RetrieverEngineType)
if err != nil {
return nil, err
}
if !slices.Contains(repo.Support(), engineParam.RetrieverType) {
return nil, fmt.Errorf("retrieval engine %s does not support retriever type: %s",
repo.EngineType(), engineParam.RetrieverType)
}
if _, exists := engineInfos[repo.EngineType()]; exists {
engineInfos[repo.EngineType()].retrieverType = append(engineInfos[repo.EngineType()].retrieverType,
engineParam.RetrieverType)
continue
}
engineInfos[repo.EngineType()] = &engineInfo{
retrieveEngine: repo,
retrieverType: []types.RetrieverType{engineParam.RetrieverType},
}
}
return &CompositeRetrieveEngine{engineInfos: slices.Collect(maps.Values(engineInfos))}, nil
}
// SupportRetriever checks if a retriever type is supported by any of the registered engines
func (c *CompositeRetrieveEngine) SupportRetriever(r types.RetrieverType) bool {
for _, engineInfo := range c.engineInfos {
if slices.Contains(engineInfo.retrieverType, r) {
return true
}
}
return false
}
// concurrentRetrieve is a helper function for concurrent processing of retrieval parameters
// and collecting results
func concurrentRetrieve(
ctx context.Context,
retrieveParams []types.RetrieveParams,
fn func(ctx context.Context, param types.RetrieveParams, results *[]*types.RetrieveResult, mu *sync.Mutex) error,
) ([]*types.RetrieveResult, error) {
var results []*types.RetrieveResult
var mu sync.Mutex
var wg sync.WaitGroup
errCh := make(chan error, len(retrieveParams))
for _, param := range retrieveParams {
wg.Add(1)
p := param // Create local copy for safe use in closure
go func() {
defer wg.Done()
if err := fn(ctx, p, &results, &mu); err != nil {
errCh <- err
}
}()
}
wg.Wait()
close(errCh)
// Check for errors
for err := range errCh {
if err != nil {
return nil, err
}
}
return results, nil
}
// concurrentExecWithError is a generic function for concurrent execution of operations
// and handling errors
func (c *CompositeRetrieveEngine) concurrentExecWithError(
ctx context.Context,
fn func(ctx context.Context, engineInfo *engineInfo) error,
) error {
var wg sync.WaitGroup
errCh := make(chan error, len(c.engineInfos))
for _, engineInfo := range c.engineInfos {
wg.Add(1)
eng := engineInfo // Create local copy for safe use in closure
go func() {
defer wg.Done()
if err := fn(ctx, eng); err != nil {
errCh <- err
}
}()
}
wg.Wait()
close(errCh)
// Return the first error (if any)
for err := range errCh {
if err != nil {
return err
}
}
return nil
}
// Index saves vector embeddings to all registered repositories
func (c *CompositeRetrieveEngine) Index(ctx context.Context,
embedder embedding.Embedder, indexInfo *types.IndexInfo,
) error {
ctx, span := tracing.ContextWithSpan(ctx, "CompositeRetrieveEngine.Index")
defer span.End()
err := c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
if err := engineInfo.retrieveEngine.Index(ctx, embedder, indexInfo, engineInfo.retrieverType); err != nil {
logger.Errorf(ctx, "Repository %s failed to save: %v", engineInfo.retrieveEngine.EngineType(), err)
return err
}
return nil
})
span.RecordError(err)
span.SetAttributes(
attribute.String("embedder", embedder.GetModelName()),
attribute.String("source_id", indexInfo.SourceID),
)
return err
}
// BatchIndex batch saves vector embeddings to all registered repositories
func (c *CompositeRetrieveEngine) BatchIndex(ctx context.Context,
embedder embedding.Embedder, indexInfoList []*types.IndexInfo,
) error {
ctx, span := tracing.ContextWithSpan(ctx, "CompositeRetrieveEngine.BatchIndex")
defer span.End()
// Deduplicate sourceIDs
indexInfoList = common.Deduplicate(func(info *types.IndexInfo) string { return info.SourceID }, indexInfoList...)
err := c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
if err := engineInfo.retrieveEngine.BatchIndex(
ctx,
embedder,
indexInfoList,
engineInfo.retrieverType,
); err != nil {
logger.Errorf(ctx, "Repository %s failed to batch save: %v", engineInfo.retrieveEngine.EngineType(), err)
return err
}
return nil
})
span.RecordError(err)
span.SetAttributes(
attribute.String("embedder", embedder.GetModelName()),
attribute.Int("index_info_count", len(indexInfoList)),
)
return err
}
// DeleteByChunkIDList deletes vector embeddings by chunk ID list from all registered repositories
func (c *CompositeRetrieveEngine) DeleteByChunkIDList(ctx context.Context,
chunkIDList []string, dimension int,
) error {
return c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
if err := engineInfo.retrieveEngine.DeleteByChunkIDList(ctx, chunkIDList, dimension); err != nil {
logger.GetLogger(ctx).Errorf("Repository %s failed to delete chunk ID list: %v",
engineInfo.retrieveEngine.EngineType(), err)
return err
}
return nil
})
}
// CopyIndices copies indices from a source knowledge base to a target knowledge base
func (c *CompositeRetrieveEngine) CopyIndices(
ctx context.Context,
sourceKnowledgeBaseID string,
targetKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
dimension int,
) error {
return c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
if err := engineInfo.retrieveEngine.CopyIndices(
ctx,
sourceKnowledgeBaseID,
sourceToTargetKBIDMap,
sourceToTargetChunkIDMap,
targetKnowledgeBaseID,
dimension,
); err != nil {
logger.Errorf(ctx, "Repository %s failed to copy indices: %v", engineInfo.retrieveEngine.EngineType(), err)
return err
}
return nil
})
}
// DeleteByKnowledgeIDList deletes vector embeddings by knowledge ID list from all registered repositories
func (c *CompositeRetrieveEngine) DeleteByKnowledgeIDList(ctx context.Context,
knowledgeIDList []string, dimension int,
) error {
return c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
if err := engineInfo.retrieveEngine.DeleteByKnowledgeIDList(ctx, knowledgeIDList, dimension); err != nil {
logger.GetLogger(ctx).Errorf("Repository %s failed to delete knowledge ID list: %v",
engineInfo.retrieveEngine.EngineType(), err)
return err
}
return nil
})
}
// EstimateStorageSize estimates the storage size required for the provided index information
func (c *CompositeRetrieveEngine) EstimateStorageSize(ctx context.Context,
embedder embedding.Embedder, indexInfoList []*types.IndexInfo,
) int64 {
ctx, span := tracing.ContextWithSpan(ctx, "CompositeRetrieveEngine.EstimateStorageSize")
defer span.End()
sum := atomic.Int64{}
err := c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
sum.Add(engineInfo.retrieveEngine.EstimateStorageSize(ctx, embedder, indexInfoList, engineInfo.retrieverType))
return nil
})
span.RecordError(err)
span.SetAttributes(
attribute.String("embedder", embedder.GetModelName()),
attribute.Int("index_info_count", len(indexInfoList)),
attribute.Int64("storage_size", sum.Load()),
)
return sum.Load()
}
@@ -0,0 +1,163 @@
package retriever
import (
"context"
"slices"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/utils"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// KeywordsVectorHybridRetrieveEngineService implements a hybrid retrieval engine
// that supports both keyword-based and vector-based retrieval
type KeywordsVectorHybridRetrieveEngineService struct {
indexRepository interfaces.RetrieveEngineRepository
engineType types.RetrieverEngineType
}
// NewKVHybridRetrieveEngine creates a new instance of the hybrid retrieval engine
// KV stands for KeywordsVector
func NewKVHybridRetrieveEngine(indexRepository interfaces.RetrieveEngineRepository,
engineType types.RetrieverEngineType,
) interfaces.RetrieveEngineService {
return &KeywordsVectorHybridRetrieveEngineService{indexRepository: indexRepository, engineType: engineType}
}
// EngineType returns the type of the retrieval engine
func (v *KeywordsVectorHybridRetrieveEngineService) EngineType() types.RetrieverEngineType {
return v.engineType
}
// Retrieve performs retrieval based on the provided parameters
func (v *KeywordsVectorHybridRetrieveEngineService) Retrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
return v.indexRepository.Retrieve(ctx, params)
}
// Index creates embeddings for the content and saves it to the repository
// if vector retrieval is enabled in the retriever types
func (v *KeywordsVectorHybridRetrieveEngineService) Index(ctx context.Context,
embedder embedding.Embedder, indexInfo *types.IndexInfo, retrieverTypes []types.RetrieverType,
) error {
params := make(map[string]any)
embeddingMap := make(map[string][]float32)
if slices.Contains(retrieverTypes, types.VectorRetrieverType) {
embedding, err := embedder.Embed(ctx, indexInfo.Content)
if err != nil {
return err
}
embeddingMap[indexInfo.ChunkID] = embedding
}
params["embedding"] = embeddingMap
return v.indexRepository.Save(ctx, indexInfo, params)
}
// BatchIndex creates embeddings for multiple content items and saves them to the repository
// in batches for efficiency
func (v *KeywordsVectorHybridRetrieveEngineService) BatchIndex(ctx context.Context,
embedder embedding.Embedder, indexInfoList []*types.IndexInfo, retrieverTypes []types.RetrieverType,
) error {
if len(indexInfoList) == 0 {
return nil
}
params := make(map[string]any)
if slices.Contains(retrieverTypes, types.VectorRetrieverType) {
var contentList []string
for _, indexInfo := range indexInfoList {
contentList = append(contentList, indexInfo.Content)
}
var embeddings [][]float32
var err error
for range 5 {
embeddings, err = embedder.BatchEmbedWithPool(ctx, embedder, contentList)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
if err != nil {
return err
}
batchSize := 20
for i, indexChunk := range utils.ChunkSlice(indexInfoList, batchSize) {
embeddingMap := make(map[string][]float32)
for j, indexInfo := range indexChunk {
embeddingMap[indexInfo.SourceID] = embeddings[i*batchSize+j]
}
params["embedding"] = embeddingMap
err = v.indexRepository.BatchSave(ctx, indexChunk, params)
if err != nil {
return err
}
}
return nil
}
var err error
for _, indexChunk := range utils.ChunkSlice(indexInfoList, 10) {
err = v.indexRepository.BatchSave(ctx, indexChunk, params)
if err != nil {
return err
}
}
return nil
}
// DeleteByChunkIDList deletes vectors by their chunk IDs
func (v *KeywordsVectorHybridRetrieveEngineService) DeleteByChunkIDList(ctx context.Context,
indexIDList []string, dimension int,
) error {
return v.indexRepository.DeleteByChunkIDList(ctx, indexIDList, dimension)
}
// DeleteByKnowledgeIDList deletes vectors by their knowledge IDs
func (v *KeywordsVectorHybridRetrieveEngineService) DeleteByKnowledgeIDList(ctx context.Context,
knowledgeIDList []string, dimension int,
) error {
return v.indexRepository.DeleteByKnowledgeIDList(ctx, knowledgeIDList, dimension)
}
// Support returns the retriever types supported by this engine
func (v *KeywordsVectorHybridRetrieveEngineService) Support() []types.RetrieverType {
return v.indexRepository.Support()
}
// EstimateStorageSize estimates the storage space needed for the provided index information
func (v *KeywordsVectorHybridRetrieveEngineService) EstimateStorageSize(
ctx context.Context,
embedder embedding.Embedder,
indexInfoList []*types.IndexInfo,
retrieverTypes []types.RetrieverType,
) int64 {
params := make(map[string]any)
if slices.Contains(retrieverTypes, types.VectorRetrieverType) {
embeddingMap := make(map[string][]float32)
// just for estimate storage size
for _, indexInfo := range indexInfoList {
embeddingMap[indexInfo.ChunkID] = make([]float32, embedder.GetDimensions())
}
params["embedding"] = embeddingMap
}
return v.indexRepository.EstimateStorageSize(ctx, indexInfoList, params)
}
// CopyIndices copies indices from a source knowledge base to a target knowledge base
func (v *KeywordsVectorHybridRetrieveEngineService) CopyIndices(
ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
) error {
logger.Infof(ctx, "Copy indices from knowledge base %s to %s, mapping relation count: %d",
sourceKnowledgeBaseID, targetKnowledgeBaseID, len(sourceToTargetChunkIDMap),
)
return v.indexRepository.CopyIndices(
ctx, sourceKnowledgeBaseID, sourceToTargetKBIDMap, sourceToTargetChunkIDMap, targetKnowledgeBaseID, dimension,
)
}
@@ -0,0 +1,64 @@
package retriever
import (
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// RetrieveEngineRegistry implements the retrieval engine registry
type RetrieveEngineRegistry struct {
repositories map[types.RetrieverEngineType]interfaces.RetrieveEngineService
mu sync.RWMutex
}
// NewRetrieveEngineRegistry creates a new retrieval engine registry
func NewRetrieveEngineRegistry() interfaces.RetrieveEngineRegistry {
return &RetrieveEngineRegistry{
repositories: make(map[types.RetrieverEngineType]interfaces.RetrieveEngineService),
}
}
// Register registers a retrieval engine service
func (r *RetrieveEngineRegistry) Register(repo interfaces.RetrieveEngineService) error {
r.mu.Lock()
defer r.mu.Unlock()
if _, exists := r.repositories[repo.EngineType()]; exists {
return fmt.Errorf("Repository type %s already registered", repo.EngineType())
}
r.repositories[repo.EngineType()] = repo
return nil
}
// GetRetrieveEngineService retrieves a retrieval engine service by type
func (r *RetrieveEngineRegistry) GetRetrieveEngineService(repoType types.RetrieverEngineType) (
interfaces.RetrieveEngineService, error,
) {
r.mu.RLock()
defer r.mu.RUnlock()
repo, exists := r.repositories[repoType]
if !exists {
return nil, fmt.Errorf("Repository of type %s not found", repoType)
}
return repo, nil
}
// GetAllRetrieveEngineServices retrieves all registered retrieval engine services
func (r *RetrieveEngineRegistry) GetAllRetrieveEngineServices() []interfaces.RetrieveEngineService {
r.mu.RLock()
defer r.mu.RUnlock()
// Create a copy to avoid modifying the original map
result := make([]interfaces.RetrieveEngineService, 0, len(r.repositories))
for _, v := range r.repositories {
result = append(result, v)
}
return result
}
+517
View File
@@ -0,0 +1,517 @@
package service
import (
"context"
"errors"
"strings"
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
)
// sessionService implements the SessionService interface for managing conversation sessions
type sessionService struct {
cfg *config.Config // Application configuration
sessionRepo interfaces.SessionRepository // Repository for session data
messageRepo interfaces.MessageRepository // Repository for message data
knowledgeBaseService interfaces.KnowledgeBaseService // Service for knowledge base operations
modelService interfaces.ModelService // Service for model operations
eventManager *chatpipline.EventManager // Event manager for chat pipeline
}
// NewSessionService creates a new session service instance with all required dependencies
func NewSessionService(cfg *config.Config,
sessionRepo interfaces.SessionRepository,
messageRepo interfaces.MessageRepository,
knowledgeBaseService interfaces.KnowledgeBaseService,
modelService interfaces.ModelService,
eventManager *chatpipline.EventManager,
) interfaces.SessionService {
return &sessionService{
cfg: cfg,
sessionRepo: sessionRepo,
messageRepo: messageRepo,
knowledgeBaseService: knowledgeBaseService,
modelService: modelService,
eventManager: eventManager,
}
}
// CreateSession creates a new conversation session
func (s *sessionService) CreateSession(ctx context.Context, session *types.Session) (*types.Session, error) {
logger.Info(ctx, "Start creating session")
// Validate tenant ID
if session.TenantID == 0 {
logger.Error(ctx, "Failed to create session: tenant ID cannot be empty")
return nil, errors.New("tenant ID is required")
}
logger.Infof(ctx, "Creating session, tenant ID: %d, model ID: %s, knowledge base ID: %s",
session.TenantID, session.SummaryModelID, session.KnowledgeBaseID)
// Create session in repository
createdSession, err := s.sessionRepo.Create(ctx, session)
if err != nil {
return nil, err
}
logger.Infof(ctx, "Session created successfully, ID: %s, tenant ID: %d", createdSession.ID, createdSession.TenantID)
return createdSession, nil
}
// GetSession retrieves a session by its ID
func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Session, error) {
logger.Info(ctx, "Start retrieving session")
// Validate session ID
if id == "" {
logger.Error(ctx, "Failed to get session: session ID cannot be empty")
return nil, errors.New("session id is required")
}
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Retrieving session, ID: %s, tenant ID: %d", id, tenantID)
// Get session from repository
session, err := s.sessionRepo.Get(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": id,
"tenant_id": tenantID,
})
return nil, err
}
logger.Infof(ctx, "Session retrieved successfully, ID: %s, tenant ID: %d", session.ID, session.TenantID)
return session, nil
}
// GetSessionsByTenant retrieves all sessions for the current tenant
func (s *sessionService) GetSessionsByTenant(ctx context.Context) ([]*types.Session, error) {
logger.Info(ctx, "Start retrieving all sessions for tenant")
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Retrieving all sessions for tenant, tenant ID: %d", tenantID)
// Get sessions from repository
sessions, err := s.sessionRepo.GetByTenantID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
})
return nil, err
}
logger.Infof(
ctx, "Tenant sessions retrieved successfully, tenant ID: %d, session count: %d", tenantID, len(sessions),
)
return sessions, nil
}
// GetPagedSessionsByTenant retrieves sessions for the current tenant with pagination
func (s *sessionService) GetPagedSessionsByTenant(ctx context.Context,
pagination *types.Pagination,
) (*types.PageResult, error) {
logger.Info(ctx, "Start retrieving paged sessions for tenant")
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Retrieving paged sessions for tenant, tenant ID: %d, page: %d, page size: %d",
tenantID, pagination.Page, pagination.PageSize)
// Get paged sessions from repository
sessions, total, err := s.sessionRepo.GetPagedByTenantID(ctx, tenantID, pagination)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
"page": pagination.Page,
"page_size": pagination.PageSize,
})
return nil, err
}
logger.Infof(ctx, "Tenant paged sessions retrieved successfully, tenant ID: %d, total: %d", tenantID, total)
return types.NewPageResult(total, pagination, sessions), nil
}
// UpdateSession updates an existing session's properties
func (s *sessionService) UpdateSession(ctx context.Context, session *types.Session) error {
logger.Info(ctx, "Start updating session")
// Validate session ID
if session.ID == "" {
logger.Error(ctx, "Failed to update session: session ID cannot be empty")
return errors.New("session id is required")
}
logger.Infof(ctx, "Updating session, ID: %s, tenant ID: %d", session.ID, session.TenantID)
// Update session in repository
err := s.sessionRepo.Update(ctx, session)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": session.ID,
"tenant_id": session.TenantID,
})
return err
}
logger.Infof(ctx, "Session updated successfully, ID: %s", session.ID)
return nil
}
// DeleteSession removes a session by its ID
func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
logger.Info(ctx, "Start deleting session")
// Validate session ID
if id == "" {
logger.Error(ctx, "Failed to delete session: session ID cannot be empty")
return errors.New("session id is required")
}
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Deleting session, ID: %s, tenant ID: %d", id, tenantID)
// Delete session from repository
err := s.sessionRepo.Delete(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": id,
"tenant_id": tenantID,
})
return err
}
logger.Infof(ctx, "Session deleted successfully, ID: %s", id)
return nil
}
// GenerateTitle generates a title for the current conversation content
func (s *sessionService) GenerateTitle(ctx context.Context,
sessionID string, messages []types.Message,
) (string, error) {
logger.Info(ctx, "Start generating session title")
// Validate session ID
if sessionID == "" {
logger.Error(ctx, "Failed to generate title: session ID cannot be empty")
return "", errors.New("session id is required")
}
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Getting session info, session ID: %s, tenant ID: %d", sessionID, tenantID)
// Get session from repository
session, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"tenant_id": tenantID,
})
return "", err
}
// Skip if title already exists
if session.Title != "" {
logger.Infof(ctx, "Session already has a title, session ID: %s, title: %s", sessionID, session.Title)
return session.Title, nil
}
// Get the first user message, either from provided messages or repository
var message *types.Message
if len(messages) == 0 {
logger.Info(ctx, "Message list is empty, getting the first user message")
message, err = s.messageRepo.GetFirstMessageOfUser(ctx, sessionID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
})
return "", err
}
} else {
logger.Info(ctx, "Searching for user message in message list")
for _, m := range messages {
if m.Role == "user" {
message = &m
break
}
}
}
// Ensure a user message was found
if message == nil {
logger.Error(ctx, "No user message found, cannot generate title")
return "", errors.New("no user message found")
}
// Get chat model
logger.Infof(ctx, "Getting chat model, model ID: %s", session.SummaryModelID)
chatModel, err := s.modelService.GetChatModel(ctx, session.SummaryModelID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": session.SummaryModelID,
})
return "", err
}
// Prepare messages for title generation
logger.Info(ctx, "Preparing to generate session title")
var chatMessages []chat.Message
chatMessages = append(chatMessages,
chat.Message{Role: "system", Content: s.cfg.Conversation.GenerateSessionTitlePrompt},
)
chatMessages = append(chatMessages,
chat.Message{Role: "user", Content: message.Content + " /no_think"},
)
// Call model to generate title
thinking := false
logger.Info(ctx, "Calling model to generate title")
response, err := chatModel.Chat(ctx, chatMessages, &chat.ChatOptions{
Temperature: 0.3,
Thinking: &thinking,
})
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return "", err
}
// Process and store the generated title
session.Title = strings.TrimPrefix(response.Content, "<think>\n\n</think>")
logger.Infof(ctx, "Title generated successfully: %s", session.Title)
// Update session with new title
logger.Info(ctx, "Updating session title")
err = s.sessionRepo.Update(ctx, session)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return "", err
}
logger.Infof(ctx, "Session title updated successfully, ID: %s, title: %s", sessionID, session.Title)
return session.Title, nil
}
// KnowledgeQA performs knowledge base question answering with LLM summarization
func (s *sessionService) KnowledgeQA(ctx context.Context, sessionID, query string) (
[]*types.SearchResult, <-chan types.StreamResponse, error,
) {
logger.Info(ctx, "Start knowledge base question answering")
logger.Infof(ctx, "Knowledge base question answering parameters, session ID: %s, query: %s", sessionID, query)
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
logger.Infof(ctx, "Getting session info, session ID: %s, tenant ID: %d", sessionID, tenantID)
// Get session information
session, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
return nil, nil, err
}
// Validate knowledge base association
if session.KnowledgeBaseID == "" {
logger.Warnf(ctx, "Session has no associated knowledge base, session ID: %s", sessionID)
return nil, nil, errors.New("session has no knowledge base")
}
// Create chat management object with session settings
logger.Infof(ctx, "Creating chat manage object, knowledge base ID: %s", session.KnowledgeBaseID)
chatManage := &types.ChatManage{
Query: query,
RewriteQuery: query,
SessionID: sessionID,
KnowledgeBaseID: session.KnowledgeBaseID,
VectorThreshold: session.VectorThreshold,
KeywordThreshold: session.KeywordThreshold,
EmbeddingTopK: session.EmbeddingTopK,
RerankModelID: session.RerankModelID,
RerankTopK: session.RerankTopK,
RerankThreshold: session.RerankThreshold,
ChatModelID: session.SummaryModelID,
SummaryConfig: types.SummaryConfig{
MaxTokens: session.SummaryParameters.MaxTokens,
RepeatPenalty: session.SummaryParameters.RepeatPenalty,
TopK: session.SummaryParameters.TopK,
TopP: session.SummaryParameters.TopP,
FrequencyPenalty: session.SummaryParameters.FrequencyPenalty,
PresencePenalty: session.SummaryParameters.PresencePenalty,
Prompt: session.SummaryParameters.Prompt,
ContextTemplate: session.SummaryParameters.ContextTemplate,
Temperature: session.SummaryParameters.Temperature,
Seed: session.SummaryParameters.Seed,
NoMatchPrefix: session.SummaryParameters.NoMatchPrefix,
MaxCompletionTokens: session.SummaryParameters.MaxCompletionTokens,
},
FallbackResponse: session.FallbackResponse,
}
// Start knowledge QA event processing
logger.Info(ctx, "Triggering knowledge base question answering event")
err = s.KnowledgeQAByEvent(ctx, chatManage, types.Pipline["rag_stream"])
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"knowledge_base_id": session.KnowledgeBaseID,
})
return nil, nil, err
}
logger.Info(ctx, "Knowledge base question answering completed")
return chatManage.MergeResult, chatManage.ResponseChan, nil
}
// KnowledgeQAByEvent processes knowledge QA through a series of events in the pipeline
func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
chatManage *types.ChatManage, eventList []types.EventType,
) error {
ctx, span := tracing.ContextWithSpan(ctx, "SessionService.KnowledgeQAByEvent")
defer span.End()
logger.Info(ctx, "Start processing knowledge base question answering through events")
logger.Infof(ctx, "Knowledge base question answering parameters, session ID: %s, knowledge base ID: %s, query: %s",
chatManage.SessionID, chatManage.KnowledgeBaseID, chatManage.Query)
// Prepare method list for logging and tracing
methods := []string{}
for _, event := range eventList {
methods = append(methods, string(event))
}
// Set up tracing attributes
logger.Infof(ctx, "Trigger event list: %v", methods)
span.SetAttributes(
attribute.String("request_id", ctx.Value(types.RequestIDContextKey).(string)),
attribute.String("query", chatManage.Query),
attribute.String("method", strings.Join(methods, ",")),
)
// Process each event in sequence
for _, event := range eventList {
logger.Infof(ctx, "Starting to trigger event: %v", event)
err := s.eventManager.Trigger(ctx, event, chatManage)
// Handle case where search returns no results
if err == chatpipline.ErrSearchNothing {
logger.Warnf(ctx, "Event %v triggered, search result is empty, using fallback response", event)
chatManage.ResponseChan = chatpipline.NewFallbackChan(ctx, chatManage.FallbackResponse)
chatManage.ChatResponse = &types.ChatResponse{Content: chatManage.FallbackResponse}
return nil
}
// Handle other errors
if err != nil {
logger.Errorf(ctx, "Event triggering failed, event: %v, error type: %s, description: %s, error: %v",
event, err.ErrorType, err.Description, err.Err)
span.RecordError(err.Err)
span.SetStatus(codes.Error, err.Description)
span.SetAttributes(attribute.String("error_type", err.ErrorType))
return err.Err
}
logger.Infof(ctx, "Event %v triggered successfully", event)
}
logger.Info(ctx, "All events triggered successfully")
return nil
}
// SearchKnowledge performs knowledge base search without LLM summarization
func (s *sessionService) SearchKnowledge(ctx context.Context,
knowledgeBaseID, query string,
) ([]*types.SearchResult, error) {
logger.Info(ctx, "Start knowledge base search without LLM summary")
logger.Infof(ctx, "Knowledge base search parameters, knowledge base ID: %s, query: %s", knowledgeBaseID, query)
// Create default retrieval parameters
chatManage := &types.ChatManage{
Query: query,
RewriteQuery: query,
KnowledgeBaseID: knowledgeBaseID,
VectorThreshold: s.cfg.Conversation.VectorThreshold, // Use default configuration
KeywordThreshold: s.cfg.Conversation.KeywordThreshold, // Use default configuration
EmbeddingTopK: s.cfg.Conversation.EmbeddingTopK, // Use default configuration
RerankTopK: s.cfg.Conversation.RerankTopK, // Use default configuration
RerankThreshold: s.cfg.Conversation.RerankThreshold, // Use default configuration
}
// Get default models
models, err := s.modelService.ListModels(ctx)
if err != nil {
logger.Errorf(ctx, "Failed to get models: %v", err)
return nil, err
}
// Find the first available rerank model
for _, model := range models {
if model.Type == types.ModelTypeRerank {
chatManage.RerankModelID = model.ID
break
}
}
// Use specific event list, only including retrieval-related events, not LLM summarization
searchEvents := []types.EventType{
types.PREPROCESS_QUERY, // Preprocess query
types.CHUNK_SEARCH, // Vector search
types.CHUNK_RERANK, // Rerank search results
types.CHUNK_MERGE, // Merge search results
types.FILTER_TOP_K, // Filter top K results
}
ctx, span := tracing.ContextWithSpan(ctx, "SessionService.SearchKnowledge")
defer span.End()
// Prepare method list for logging and tracing
methods := []string{}
for _, event := range searchEvents {
methods = append(methods, string(event))
}
// Set up tracing attributes
logger.Infof(ctx, "Trigger search event list: %v", methods)
span.SetAttributes(
attribute.String("query", query),
attribute.String("knowledge_base_id", knowledgeBaseID),
attribute.String("method", strings.Join(methods, ",")),
)
// Process each search event in sequence
for _, event := range searchEvents {
logger.Infof(ctx, "Starting to trigger search event: %v", event)
err := s.eventManager.Trigger(ctx, event, chatManage)
// Handle case where search returns no results
if err == chatpipline.ErrSearchNothing {
logger.Warnf(ctx, "Event %v triggered, search result is empty", event)
return []*types.SearchResult{}, nil
}
// Handle other errors
if err != nil {
logger.Errorf(ctx, "Event triggering failed, event: %v, error type: %s, description: %s, error: %v",
event, err.ErrorType, err.Description, err.Err)
span.RecordError(err.Err)
span.SetStatus(codes.Error, err.Description)
span.SetAttributes(attribute.String("error_type", err.ErrorType))
return nil, err.Err
}
logger.Infof(ctx, "Event %v triggered successfully", event)
}
logger.Infof(ctx, "Knowledge base search completed, found %d results", len(chatManage.MergeResult))
return chatManage.MergeResult, nil
}
+289
View File
@@ -0,0 +1,289 @@
package service
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"errors"
"io"
"os"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
var apiKeySecret = []byte(os.Getenv("TENANT_AES_KEY"))
// ListTenantsParams defines parameters for listing tenants with filtering and pagination
type ListTenantsParams struct {
Page int // Page number for pagination
PageSize int // Number of items per page
Status string // Filter by tenant status
Name string // Filter by tenant name
}
// tenantService implements the TenantService interface
type tenantService struct {
repo interfaces.TenantRepository // Repository for tenant data operations
}
// NewTenantService creates a new tenant service instance
func NewTenantService(repo interfaces.TenantRepository) interfaces.TenantService {
return &tenantService{repo: repo}
}
// CreateTenant creates a new tenant
func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error) {
logger.Info(ctx, "Start creating tenant")
if tenant.Name == "" {
logger.Error(ctx, "Tenant name cannot be empty")
return nil, errors.New("tenant name cannot be empty")
}
logger.Infof(ctx, "Creating tenant, name: %s", tenant.Name)
// Create tenant with initial values
tenant.APIKey = s.generateApiKey(0)
tenant.Status = "active"
tenant.CreatedAt = time.Now()
tenant.UpdatedAt = time.Now()
logger.Info(ctx, "Saving tenant information to database")
if err := s.repo.CreateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_name": tenant.Name,
})
return nil, err
}
logger.Infof(ctx, "Tenant created successfully, ID: %d, generating official API Key", tenant.ID)
tenant.APIKey = s.generateApiKey(tenant.ID)
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenant.ID,
"tenant_name": tenant.Name,
})
return nil, err
}
logger.Infof(ctx, "Tenant creation and update completed, ID: %d, name: %s", tenant.ID, tenant.Name)
return tenant, nil
}
// GetTenantByID retrieves a tenant by their ID
func (s *tenantService) GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) {
logger.Info(ctx, "Start retrieving tenant")
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return nil, errors.New("tenant ID cannot be 0")
}
logger.Infof(ctx, "Retrieving tenant, ID: %d", id)
tenant, err := s.repo.GetTenantByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return nil, err
}
logger.Infof(ctx, "Tenant retrieved successfully, ID: %d, name: %s", tenant.ID, tenant.Name)
return tenant, nil
}
// ListTenants retrieves a list of all tenants
func (s *tenantService) ListTenants(ctx context.Context) ([]*types.Tenant, error) {
logger.Info(ctx, "Start retrieving tenant list")
tenants, err := s.repo.ListTenants(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return nil, err
}
logger.Infof(ctx, "Tenant list retrieved successfully, total: %d", len(tenants))
return tenants, nil
}
// UpdateTenant updates an existing tenant's information
func (s *tenantService) UpdateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error) {
if tenant.ID == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return nil, errors.New("tenant ID cannot be 0")
}
logger.Infof(ctx, "Updating tenant, ID: %d, name: %s", tenant.ID, tenant.Name)
// Generate new API key if empty
if tenant.APIKey == "" {
logger.Info(ctx, "API Key is empty, generating new API Key")
tenant.APIKey = s.generateApiKey(tenant.ID)
}
tenant.UpdatedAt = time.Now()
logger.Info(ctx, "Saving tenant information to database")
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenant.ID,
})
return nil, err
}
logger.Infof(ctx, "Tenant updated successfully, ID: %d", tenant.ID)
return tenant, nil
}
// DeleteTenant removes a tenant by their ID
func (s *tenantService) DeleteTenant(ctx context.Context, id uint) error {
logger.Info(ctx, "Start deleting tenant")
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return errors.New("tenant ID cannot be 0")
}
logger.Infof(ctx, "Deleting tenant, ID: %d", id)
// Get tenant information for logging
tenant, err := s.repo.GetTenantByID(ctx, id)
if err != nil {
if err.Error() == "record not found" {
logger.Warnf(ctx, "Tenant to be deleted does not exist, ID: %d", id)
} else {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return err
}
} else {
logger.Infof(ctx, "Deleting tenant, ID: %d, name: %s", id, tenant.Name)
}
err = s.repo.DeleteTenant(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return err
}
logger.Infof(ctx, "Tenant deleted successfully, ID: %d", id)
return nil
}
// UpdateAPIKey updates the API key for a specific tenant
func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint) (string, error) {
logger.Info(ctx, "Start updating tenant API Key")
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return "", errors.New("tenant ID cannot be 0")
}
logger.Infof(ctx, "Retrieving tenant information, ID: %d", id)
tenant, err := s.repo.GetTenantByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return "", err
}
logger.Infof(ctx, "Generating new API Key for tenant, ID: %d", id)
tenant.APIKey = s.generateApiKey(tenant.ID)
if err := s.repo.UpdateTenant(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": id,
})
return "", err
}
logger.Infof(ctx, "Tenant API Key updated successfully, ID: %d", id)
return tenant.APIKey, nil
}
// generateApiKey generates a secure API key for tenant authentication
func (r *tenantService) generateApiKey(tenantID uint) string {
// 1. Convert tenant_id to bytes
idBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(idBytes, uint64(tenantID))
// 2. Encrypt tenant_id using AES-GCM
block, err := aes.NewCipher(apiKeySecret)
if err != nil {
panic("Failed to create AES cipher: " + err.Error())
}
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic("Failed to create GCM cipher: " + err.Error())
}
ciphertext := aesgcm.Seal(nil, nonce, idBytes, nil)
// 3. Combine nonce and ciphertext, then encode with base64
combined := append(nonce, ciphertext...)
encoded := base64.RawURLEncoding.EncodeToString(combined)
// Create final API Key in format: sk-{encrypted_part}
return "sk-" + encoded
}
// ExtractTenantIDFromAPIKey extracts the tenant ID from an API key
func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint, error) {
// 1. Validate format and extract encrypted part
parts := strings.SplitN(apiKey, "-", 2)
if len(parts) != 2 || parts[0] != "sk" {
return 0, errors.New("invalid API key format")
}
// 2. Decode the base64 part
encryptedData, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return 0, errors.New("invalid API key encoding")
}
// 3. Separate nonce and ciphertext
if len(encryptedData) < 12 {
return 0, errors.New("invalid API key length")
}
nonce, ciphertext := encryptedData[:12], encryptedData[12:]
// 4. Decrypt
block, err := aes.NewCipher(apiKeySecret)
if err != nil {
return 0, errors.New("decryption error")
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return 0, errors.New("decryption error")
}
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return 0, errors.New("API key is invalid or has been tampered with")
}
// 5. Convert back to tenant_id
tenantID := binary.LittleEndian.Uint64(plaintext)
return uint(tenantID), nil
}
+443
View File
@@ -0,0 +1,443 @@
// Package service 提供应用程序的核心业务逻辑服务层
// 此包包含了知识库管理、用户租户管理、模型服务等核心功能实现
package service
import (
"context"
"fmt"
"os"
"strconv"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// TestDataService 测试数据服务
// 负责初始化测试环境所需的数据,包括创建测试租户、测试知识库
// 以及配置必要的模型服务实例
type TestDataService struct {
config *config.Config // 应用程序配置
kbRepo interfaces.KnowledgeBaseRepository // 知识库存储库接口
tenantService interfaces.TenantService // 租户服务接口
ollamaService *ollama.OllamaService // Ollama模型服务
modelService interfaces.ModelService // 模型服务接口
EmbedModel embedding.Embedder // 嵌入模型实例
RerankModel rerank.Reranker // 重排模型实例
LLMModel chat.Chat // 大语言模型实例
}
// NewTestDataService 创建测试数据服务
// 注入所需的依赖服务和组件
func NewTestDataService(
config *config.Config,
kbRepo interfaces.KnowledgeBaseRepository,
tenantService interfaces.TenantService,
ollamaService *ollama.OllamaService,
modelService interfaces.ModelService,
) *TestDataService {
return &TestDataService{
config: config,
kbRepo: kbRepo,
tenantService: tenantService,
ollamaService: ollamaService,
modelService: modelService,
}
}
// initTenant 初始化测试租户
// 通过环境变量获取租户ID,如果租户不存在则创建新租户,否则更新现有租户
// 同时配置租户的检索引擎参数
func (s *TestDataService) initTenant(ctx context.Context) error {
logger.Info(ctx, "Start initializing test tenant")
// 从环境变量获取租户ID
tenantID := os.Getenv("INIT_TEST_TENANT_ID")
logger.Infof(ctx, "Test tenant ID from environment: %s", tenantID)
// 将字符串ID转换为uint64
tenantIDUint, err := strconv.ParseUint(tenantID, 10, 64)
if err != nil {
logger.Errorf(ctx, "Failed to parse tenant ID: %v", err)
return err
}
// 创建租户配置
tenantConfig := &types.Tenant{
Name: "Test Tenant",
Description: "Test Tenant for Testing",
RetrieverEngines: types.RetrieverEngines{
Engines: []types.RetrieverEngineParams{
{
RetrieverType: types.KeywordsRetrieverType,
RetrieverEngineType: types.PostgresRetrieverEngineType,
},
{
RetrieverType: types.VectorRetrieverType,
RetrieverEngineType: types.PostgresRetrieverEngineType,
},
},
},
}
// 获取或创建测试租户
logger.Infof(ctx, "Attempting to get tenant with ID: %d", tenantIDUint)
tenant, err := s.tenantService.GetTenantByID(ctx, uint(tenantIDUint))
if err != nil {
// 租户不存在,创建新租户
logger.Info(ctx, "Tenant not found, creating a new test tenant")
tenant, err = s.tenantService.CreateTenant(ctx, tenantConfig)
if err != nil {
logger.Errorf(ctx, "Failed to create tenant: %v", err)
return err
}
logger.Infof(ctx, "Created new test tenant with ID: %d", tenant.ID)
} else {
// 租户存在,更新检索引擎配置
logger.Info(ctx, "Test tenant found, updating retriever engines")
tenant.RetrieverEngines = tenantConfig.RetrieverEngines
tenant, err = s.tenantService.UpdateTenant(ctx, tenant)
if err != nil {
logger.Errorf(ctx, "Failed to update tenant: %v", err)
return err
}
logger.Info(ctx, "Test tenant updated successfully")
}
logger.Infof(ctx, "Test tenant configured - ID: %d, Name: %s, API Key: %s",
tenant.ID, tenant.Name, tenant.APIKey)
return nil
}
// initKnowledgeBase 初始化测试知识库
// 从环境变量获取知识库ID,创建或更新知识库
// 配置知识库的分块策略、嵌入模型和摘要模型
func (s *TestDataService) initKnowledgeBase(ctx context.Context) error {
logger.Info(ctx, "Start initializing test knowledge base")
// 检查上下文中的租户ID
if ctx.Value(types.TenantIDContextKey).(uint) == 0 {
logger.Warn(ctx, "Tenant ID is 0, skipping knowledge base initialization")
return nil
}
// 从环境变量获取知识库ID
knowledgeBaseID := os.Getenv("INIT_TEST_KNOWLEDGE_BASE_ID")
logger.Infof(ctx, "Test knowledge base ID from environment: %s", knowledgeBaseID)
// 创建知识库配置
kbConfig := &types.KnowledgeBase{
ID: knowledgeBaseID,
Name: "Test Knowledge Base",
Description: "Knowledge Base for Testing",
TenantID: ctx.Value(types.TenantIDContextKey).(uint),
ChunkingConfig: types.ChunkingConfig{
ChunkSize: s.config.KnowledgeBase.ChunkSize,
ChunkOverlap: s.config.KnowledgeBase.ChunkOverlap,
Separators: s.config.KnowledgeBase.SplitMarkers,
EnableMultimodal: s.config.KnowledgeBase.ImageProcessing.EnableMultimodal,
},
EmbeddingModelID: s.EmbedModel.GetModelID(),
SummaryModelID: s.LLMModel.GetModelID(),
}
// 初始化测试知识库
logger.Info(ctx, "Attempting to get existing knowledge base")
_, err := s.kbRepo.GetKnowledgeBaseByID(ctx, knowledgeBaseID)
if err != nil {
// 知识库不存在,创建新知识库
logger.Info(ctx, "Knowledge base not found, creating a new one")
logger.Infof(ctx, "Creating knowledge base with ID: %s, tenant ID: %d",
kbConfig.ID, kbConfig.TenantID)
if err := s.kbRepo.CreateKnowledgeBase(ctx, kbConfig); err != nil {
logger.Errorf(ctx, "Failed to create knowledge base: %v", err)
return err
}
logger.Info(ctx, "Knowledge base created successfully")
} else {
// 知识库存在,更新配置
logger.Info(ctx, "Knowledge base found, updating configuration")
logger.Infof(ctx, "Updating knowledge base with ID: %s", kbConfig.ID)
err = s.kbRepo.UpdateKnowledgeBase(ctx, kbConfig)
if err != nil {
logger.Errorf(ctx, "Failed to update knowledge base: %v", err)
return err
}
logger.Info(ctx, "Knowledge base updated successfully")
}
logger.Infof(ctx, "Test knowledge base configured - ID: %s, Name: %s", kbConfig.ID, kbConfig.Name)
return nil
}
// InitializeTestData 初始化测试数据
// 这是对外暴露的主要方法,负责协调所有测试数据的初始化过程
// 包括初始化租户、嵌入模型、重排模型、LLM模型和知识库
func (s *TestDataService) InitializeTestData(ctx context.Context) error {
logger.Info(ctx, "Start initializing test data")
// 从环境变量获取租户ID
tenantID := os.Getenv("INIT_TEST_TENANT_ID")
logger.Infof(ctx, "Test tenant ID from environment: %s", tenantID)
// 解析租户ID
tenantIDUint, err := strconv.ParseUint(tenantID, 10, 64)
if err != nil {
// 解析失败时使用默认值0
logger.Warn(ctx, "Failed to parse tenant ID, using default value 0")
tenantIDUint = 0
} else {
// 初始化租户
logger.Info(ctx, "Initializing tenant")
err = s.initTenant(ctx)
if err != nil {
logger.Errorf(ctx, "Failed to initialize tenant: %v", err)
return err
}
logger.Info(ctx, "Tenant initialized successfully")
}
// 创建带有租户ID的新上下文
newCtx := context.Background()
newCtx = context.WithValue(newCtx, types.TenantIDContextKey, uint(tenantIDUint))
logger.Infof(ctx, "Created new context with tenant ID: %d", tenantIDUint)
// 初始化模型
modelInitFuncs := []struct {
name string
fn func(context.Context) error
}{
{"embedding model", s.initEmbeddingModel},
{"rerank model", s.initRerankModel},
{"LLM model", s.initLLMModel},
}
for _, initFunc := range modelInitFuncs {
logger.Infof(ctx, "Initializing %s", initFunc.name)
if err := initFunc.fn(newCtx); err != nil {
logger.Errorf(ctx, "Failed to initialize %s: %v", initFunc.name, err)
return err
}
logger.Infof(ctx, "%s initialized successfully", initFunc.name)
}
// 初始化知识库
logger.Info(ctx, "Initializing knowledge base")
if err := s.initKnowledgeBase(newCtx); err != nil {
logger.Errorf(ctx, "Failed to initialize knowledge base: %v", err)
return err
}
logger.Info(ctx, "Knowledge base initialized successfully")
logger.Info(ctx, "Test data initialization completed")
return nil
}
// getEnvOrError 获取环境变量值,如果不存在则返回错误
func (s *TestDataService) getEnvOrError(name string) (string, error) {
value := os.Getenv(name)
if value == "" {
return "", fmt.Errorf("%s environment variable is not set", name)
}
return value, nil
}
// updateOrCreateModel 更新或创建模型
func (s *TestDataService) updateOrCreateModel(ctx context.Context, modelConfig *types.Model) error {
model, err := s.modelService.GetModelByID(ctx, modelConfig.ID)
if err != nil {
// 模型不存在,创建新模型
return s.modelService.CreateModel(ctx, modelConfig)
}
// 模型存在,更新属性
model.TenantID = modelConfig.TenantID
model.Name = modelConfig.Name
model.Source = modelConfig.Source
model.Type = modelConfig.Type
model.Parameters = modelConfig.Parameters
model.Status = modelConfig.Status
return s.modelService.UpdateModel(ctx, model)
}
// initEmbeddingModel 初始化嵌入模型
func (s *TestDataService) initEmbeddingModel(ctx context.Context) error {
// 从环境变量获取模型参数
modelName, err := s.getEnvOrError("INIT_EMBEDDING_MODEL_NAME")
if err != nil {
return err
}
dimensionStr := os.Getenv("INIT_EMBEDDING_MODEL_DIMENSION")
dimension, err := strconv.Atoi(dimensionStr)
if err != nil || dimension == 0 {
return fmt.Errorf("invalid embedding model dimension: %s", dimensionStr)
}
baseURL := os.Getenv("INIT_EMBEDDING_MODEL_BASE_URL")
apiKey := os.Getenv("INIT_EMBEDDING_MODEL_API_KEY")
// 确定模型来源
source := types.ModelSourceRemote
if baseURL == "" {
source = types.ModelSourceLocal
}
// 确定模型ID
modelID := os.Getenv("INIT_EMBEDDING_MODEL_ID")
if modelID == "" {
modelID = fmt.Sprintf("builtin:%s:%d", modelName, dimension)
}
// 创建嵌入模型实例
s.EmbedModel, err = embedding.NewEmbedder(embedding.Config{
Source: source,
BaseURL: baseURL,
ModelName: modelName,
APIKey: apiKey,
Dimensions: dimension,
ModelID: modelID,
})
if err != nil {
return fmt.Errorf("failed to create embedder: %w", err)
}
// 如果是本地模型,使用Ollama拉取模型
if source == types.ModelSourceLocal && s.ollamaService != nil {
if err := s.ollamaService.PullModel(context.Background(), modelName); err != nil {
return fmt.Errorf("failed to pull embedding model: %w", err)
}
}
// 创建模型配置
modelConfig := &types.Model{
ID: modelID,
TenantID: ctx.Value(types.TenantIDContextKey).(uint),
Name: modelName,
Source: source,
Type: types.ModelTypeEmbedding,
Parameters: types.ModelParameters{
BaseURL: baseURL,
APIKey: apiKey,
EmbeddingParameters: types.EmbeddingParameters{
Dimension: dimension,
},
},
Status: "active",
}
// 更新或创建模型
return s.updateOrCreateModel(ctx, modelConfig)
}
// initRerankModel 初始化重排模型
func (s *TestDataService) initRerankModel(ctx context.Context) error {
// 从环境变量获取模型参数
modelName, err := s.getEnvOrError("INIT_RERANK_MODEL_NAME")
if err != nil {
logger.Warnf(ctx, "Skip Rerank Model: %v", err)
return nil
}
baseURL, err := s.getEnvOrError("INIT_RERANK_MODEL_BASE_URL")
if err != nil {
return err
}
apiKey := os.Getenv("INIT_RERANK_MODEL_API_KEY")
modelID := fmt.Sprintf("builtin:%s:rerank:%s", types.ModelSourceRemote, modelName)
// 创建重排模型实例
s.RerankModel, err = rerank.NewReranker(&rerank.RerankerConfig{
Source: types.ModelSourceRemote,
BaseURL: baseURL,
ModelName: modelName,
APIKey: apiKey,
ModelID: modelID,
})
if err != nil {
return fmt.Errorf("failed to create reranker: %w", err)
}
// 创建模型配置
modelConfig := &types.Model{
ID: modelID,
TenantID: ctx.Value(types.TenantIDContextKey).(uint),
Name: modelName,
Source: types.ModelSourceRemote,
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{
BaseURL: baseURL,
APIKey: apiKey,
},
Status: "active",
}
// 更新或创建模型
return s.updateOrCreateModel(ctx, modelConfig)
}
// initLLMModel 初始化大语言模型
func (s *TestDataService) initLLMModel(ctx context.Context) error {
// 从环境变量获取模型参数
modelName, err := s.getEnvOrError("INIT_LLM_MODEL_NAME")
if err != nil {
return err
}
baseURL := os.Getenv("INIT_LLM_MODEL_BASE_URL")
apiKey := os.Getenv("INIT_LLM_MODEL_API_KEY")
// 确定模型来源
source := types.ModelSourceRemote
if baseURL == "" {
source = types.ModelSourceLocal
}
// 确定模型ID
modelID := fmt.Sprintf("builtin:%s:llm:%s", source, modelName)
// 创建大语言模型实例
s.LLMModel, err = chat.NewChat(&chat.ChatConfig{
Source: source,
BaseURL: baseURL,
ModelName: modelName,
APIKey: apiKey,
ModelID: modelID,
})
if err != nil {
return fmt.Errorf("failed to create llm: %w", err)
}
// 如果是本地模型,使用Ollama拉取模型
if source == types.ModelSourceLocal && s.ollamaService != nil {
if err := s.ollamaService.PullModel(context.Background(), modelName); err != nil {
return fmt.Errorf("failed to pull llm model: %w", err)
}
}
// 创建模型配置
modelConfig := &types.Model{
ID: modelID,
TenantID: ctx.Value(types.TenantIDContextKey).(uint),
Name: modelName,
Source: source,
Type: types.ModelTypeKnowledgeQA,
Parameters: types.ModelParameters{
BaseURL: baseURL,
APIKey: apiKey,
},
Status: "active",
}
// 更新或创建模型
return s.updateOrCreateModel(ctx, modelConfig)
}