Merge upstream main and resolve conflicts

This commit is contained in:
Mao Meng
2026-04-14 14:13:00 +08:00
185 changed files with 13886 additions and 1507 deletions
@@ -60,13 +60,44 @@ func NewSQLiteRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRep
}
func initFTS5(db *gorm.DB) {
sql := `CREATE VIRTUAL TABLE IF NOT EXISTS lite_embeddings_fts USING fts5(
content, source_id, chunk_id, knowledge_id, knowledge_base_id,
content='lite_embeddings', content_rowid='id',
tokenize='unicode61'
)`
if err := db.Exec(sql).Error; err != nil {
logger.GetLogger(context.Background()).Warnf("[SQLite] Failed to create FTS5 table: %v", err)
var sqlStr string
db.Raw("SELECT sql FROM sqlite_master WHERE type='table' AND name='lite_embeddings_fts'").Scan(&sqlStr)
// If the table exists but is not contentless (i.e. uses content='lite_embeddings'), recreate it
if sqlStr != "" && strings.Contains(sqlStr, "content='lite_embeddings'") {
logger.GetLogger(context.Background()).Infof("[SQLite] Migrating FTS5 table to contentless table with manual bigram tokenization")
db.Exec("DROP TABLE IF EXISTS lite_embeddings_fts")
sqlStr = "" // Trigger recreate
}
if sqlStr == "" {
createSQL := `CREATE VIRTUAL TABLE IF NOT EXISTS lite_embeddings_fts USING fts5(
content, source_id, chunk_id, knowledge_id, knowledge_base_id,
content='',
contentless_delete=1,
tokenize='unicode61'
)`
if err := db.Exec(createSQL).Error; err != nil {
logger.GetLogger(context.Background()).Warnf("[SQLite] Failed to create FTS5 table: %v", err)
return
}
logger.GetLogger(context.Background()).Infof("[SQLite] Populating contentless FTS5 table from lite_embeddings with bigrams")
// To populate, we need to read all rows and insert them via Go to apply bigram tokenization
type Row struct {
ID uint
Content string
SourceID string
ChunkID string
KnowledgeID string
KnowledgeBaseID string
}
var rows []Row
db.Raw("SELECT id, content, source_id, chunk_id, knowledge_id, knowledge_base_id FROM lite_embeddings").Scan(&rows)
for _, r := range rows {
db.Exec(`INSERT INTO lite_embeddings_fts(rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id)
VALUES(?, ?, ?, ?, ?, ?)`,
r.ID, tokenizeCJKBigram(r.Content), r.SourceID, r.ChunkID, r.KnowledgeID, r.KnowledgeBaseID)
}
}
}
@@ -276,7 +307,7 @@ func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.Re
SELECT e.id, e.source_id, e.source_type, e.chunk_id,
e.knowledge_id, e.knowledge_base_id, e.tag_id,
e.content,
bm25(lite_embeddings_fts) AS score
(bm25(lite_embeddings_fts) * -1000000.0) AS score
FROM lite_embeddings_fts
JOIN lite_embeddings e ON e.id = lite_embeddings_fts.rowid
WHERE lite_embeddings_fts MATCH ?
@@ -290,7 +321,7 @@ func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.Re
args = append(args, wp.args...)
}
sql += " ORDER BY score ASC LIMIT ?"
sql += " ORDER BY score DESC LIMIT ?"
args = append(args, params.TopK)
type ftsResult struct {
@@ -315,11 +346,12 @@ func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.Re
items := make([]*types.IndexWithScore, len(rows))
for i, row := range rows {
// bm25 越小越相关 → 转成正向分数
score := -row.Score
// bm25 is originally negative and very small, we multiplied it by -1000000.0 in SQL
// to make it positive and human-readable.
score := row.Score
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: #%d chunk_id=%s, bm25_raw=%.4f, score=%.4f, content_preview=%.60s",
i+1, row.ChunkID, row.Score, score, row.Content)
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: #%d chunk_id=%s, score=%.4f, content_preview=%.60s",
i+1, row.ChunkID, score, row.Content)
items[i] = &types.IndexWithScore{
ID: fmt.Sprintf("%d", row.ID),
@@ -488,6 +520,9 @@ func (r *sqliteRepository) deleteRowsAndVecs(_ context.Context, rows []sqliteEmb
r.db.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = ?", tbl), id)
}
}
for _, row := range rows {
r.db.Exec("DELETE FROM lite_embeddings_fts WHERE rowid = ?", row.ID)
}
}
func (r *sqliteRepository) copyVec(_ context.Context, srcID, dstID uint, dim int) {
@@ -505,8 +540,9 @@ func (r *sqliteRepository) syncFTS5Insert(_ context.Context, row *sqliteEmbeddin
if row.ID == 0 {
return
}
tokenizedContent := tokenizeCJKBigram(row.Content)
sql := `INSERT INTO lite_embeddings_fts(rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id) VALUES(?, ?, ?, ?, ?, ?)`
r.db.Exec(sql, row.ID, row.Content, row.SourceID, row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID)
r.db.Exec(sql, row.ID, tokenizedContent, row.SourceID, row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID)
}
type whereClause struct {
@@ -553,61 +589,77 @@ func toInterfaceSlice(ss []string) []interface{} {
return out
}
// sanitizeFTS5Query builds an FTS5 query from user input.
// CJK characters are split into overlapping bigrams (mimicking CJK analyzers used
// by Elasticsearch etc.) and joined with OR for broad partial matching.
// Non-CJK words are kept intact. BM25 ranking naturally boosts documents
// that match more tokens.
// tokenizeCJKBigram splits continuous CJK character sequences into overlapping bigrams.
// Non-CJK words are kept intact. This approach maximizes recall for CJK search.
func tokenizeCJKBigram(text string) string {
var parts []string
var currentCJK []rune
var currentNonCJK strings.Builder
flushCJK := func() {
if len(currentCJK) == 0 {
return
}
if len(currentCJK) == 1 {
parts = append(parts, string(currentCJK[0]))
} else {
for i := 0; i < len(currentCJK)-1; i++ {
parts = append(parts, string(currentCJK[i])+string(currentCJK[i+1]))
}
}
currentCJK = currentCJK[:0]
}
flushNonCJK := func() {
if currentNonCJK.Len() > 0 {
parts = append(parts, currentNonCJK.String())
currentNonCJK.Reset()
}
}
for _, r := range text {
// unicode.Han covers Chinese characters
if unicode.Is(unicode.Han, r) {
flushNonCJK()
currentCJK = append(currentCJK, r)
} else if unicode.IsSpace(r) || unicode.IsPunct(r) || unicode.IsSymbol(r) {
// Delimiters
flushCJK()
flushNonCJK()
} else {
// Alphanumeric or other languages
flushCJK()
currentNonCJK.WriteRune(r)
}
}
flushCJK()
flushNonCJK()
return strings.Join(parts, " ")
}
// sanitizeFTS5Query builds an FTS5 query from user input by applying bigram tokenization.
func sanitizeFTS5Query(q string) string {
q = strings.TrimSpace(q)
if q == "" {
return q
}
var cjkRunes []rune
var nonCJKWords []string
var buf strings.Builder
flushNonCJK := func() {
if buf.Len() > 0 {
nonCJKWords = append(nonCJKWords, buf.String())
buf.Reset()
}
}
for _, r := range q {
if unicode.Is(unicode.Han, r) {
flushNonCJK()
cjkRunes = append(cjkRunes, r)
} else if unicode.IsSpace(r) || r == '|' {
flushNonCJK()
} else if r == '"' || r == '*' || r == '(' || r == ')' || r == '{' || r == '}' {
// skip FTS5 special characters
} else {
buf.WriteRune(r)
}
}
flushNonCJK()
// Tokenize input query with bigrams (same as during indexing)
tokenized := tokenizeCJKBigram(q)
fields := strings.Fields(tokenized)
var parts []string
// CJK bigrams for better matching (e.g. "苹果第四季度" → "苹果" OR "果第" OR "第四" OR ...)
if len(cjkRunes) == 1 {
parts = append(parts, `"`+string(cjkRunes[0])+`"`)
} else {
for i := 0; i < len(cjkRunes)-1; i++ {
bigram := string(cjkRunes[i]) + string(cjkRunes[i+1])
parts = append(parts, `"`+bigram+`"`)
for _, f := range fields {
if f != "" {
parts = append(parts, `"`+f+`"`)
}
}
for _, w := range nonCJKWords {
w = strings.ReplaceAll(w, `"`, `""`)
parts = append(parts, `"`+w+`"`)
}
if len(parts) == 0 {
return `"` + strings.ReplaceAll(q, `"`, `""`) + `"`
return ""
}
// Use OR because we want fuzzy match across multiple bigrams/words
return strings.Join(parts, " OR ")
}
@@ -59,6 +59,15 @@ func (r *vectorStoreRepository) Update(ctx context.Context, store *types.VectorS
).Select("name").Updates(store).Error
}
// UpdateConnectionConfig updates only the connection_config JSONB column.
// Used for saving auto-detected metadata (e.g., server version) without
// touching user-immutable fields like engine_type or index_config.
func (r *vectorStoreRepository) UpdateConnectionConfig(ctx context.Context, store *types.VectorStore) error {
return r.db.WithContext(ctx).Model(&types.VectorStore{}).Where(
"id = ? AND tenant_id = ?", store.ID, store.TenantID,
).Select("connection_config").Updates(store).Error
}
// Delete soft-deletes a vector store
func (r *vectorStoreRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).Where(
@@ -15,15 +15,15 @@ import (
// PluginSearch implements search functionality for chat pipeline
type PluginSearch struct {
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
config *config.Config
webSearchService interfaces.WebSearchService
tenantService interfaces.TenantService
sessionService interfaces.SessionService
webSearchStateService interfaces.WebSearchStateService
webSearchProviderRepo interfaces.WebSearchProviderRepository
knowledgeBaseService interfaces.KnowledgeBaseService
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
config *config.Config
webSearchService interfaces.WebSearchService
tenantService interfaces.TenantService
sessionService interfaces.SessionService
webSearchStateService interfaces.WebSearchStateService
webSearchProviderRepo interfaces.WebSearchProviderRepository
}
func NewPluginSearch(eventManager *EventManager,
@@ -620,21 +620,34 @@ func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types
return nil
}
tenant, _ := types.TenantInfoFromContext(ctx)
if tenant == nil || tenant.WebSearchConfig == nil {
providerID := chatManage.WebSearchProviderID
var webConfig *types.WebSearchConfig
if tenant != nil && tenant.WebSearchConfig != nil {
// Clone tenant config so we can safely override MaxResults
cfg := *tenant.WebSearchConfig
webConfig = &cfg
} else if providerID != "" {
webConfig = &types.WebSearchConfig{
MaxResults: 10,
}
} else {
pipelineWarn(ctx, "Search", "web_config_missing", map[string]interface{}{
"tenant_id": chatManage.TenantID,
})
return nil
}
// Use provider ID already resolved by session layer (agent config > tenant default)
providerID := chatManage.WebSearchProviderID
// Apply agent-level web search overrides
if chatManage.WebSearchMaxResults > 0 {
webConfig.MaxResults = chatManage.WebSearchMaxResults
}
pipelineInfo(ctx, "Search", "web_request", map[string]interface{}{
"tenant_id": chatManage.TenantID,
"provider_id": providerID,
})
webResults, err := p.webSearchService.Search(ctx, providerID, tenant.WebSearchConfig, chatManage.RewriteQuery)
webResults, err := p.webSearchService.Search(ctx, providerID, webConfig, chatManage.RewriteQuery)
if err != nil {
pipelineWarn(ctx, "Search", "web_search_error", map[string]interface{}{
"tenant_id": chatManage.TenantID,
@@ -643,22 +656,22 @@ func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types
return nil
}
// Build questions using RewriteQuery only
questions := []string{strings.TrimSpace(chatManage.RewriteQuery)}
// questions := []string{strings.TrimSpace(chatManage.RewriteQuery)}
// Load session-scoped temp KB state from Redis using WebSearchStateRepository
tempKBID, seen, ids := p.webSearchStateService.GetWebSearchTempKBState(ctx, chatManage.SessionID)
compressed, kbID, newSeen, newIDs, err := p.webSearchService.CompressWithRAG(
ctx, chatManage.SessionID, tempKBID, questions, webResults, tenant.WebSearchConfig,
p.knowledgeBaseService, p.knowledgeService, seen, ids,
)
if err != nil {
pipelineWarn(ctx, "Search", "web_compress_error", map[string]interface{}{
"error": err.Error(),
})
} else {
webResults = compressed
// Persist temp KB state back into Redis using WebSearchStateRepository
p.webSearchStateService.SaveWebSearchTempKBState(ctx, chatManage.SessionID, kbID, newSeen, newIDs)
}
// tempKBID, seen, ids := p.webSearchStateService.GetWebSearchTempKBState(ctx, chatManage.SessionID)
// compressed, kbID, newSeen, newIDs, err := p.webSearchService.CompressWithRAG(
// ctx, chatManage.SessionID, tempKBID, questions, webResults, webConfig,
// p.knowledgeBaseService, p.knowledgeService, seen, ids,
// )
// if err != nil {
// pipelineWarn(ctx, "Search", "web_compress_error", map[string]interface{}{
// "error": err.Error(),
// })
// } else {
// webResults = compressed
// // Persist temp KB state back into Redis using WebSearchStateRepository
// p.webSearchStateService.SaveWebSearchTempKBState(ctx, chatManage.SessionID, kbID, newSeen, newIDs)
// }
res := searchutil.ConvertWebSearchResults(webResults)
pipelineInfo(ctx, "Search", "web_hits", map[string]interface{}{
"hit_count": len(res),
@@ -101,6 +101,30 @@ func NewFileServiceFromStorageConfig(
svc, err := NewS3FileService(sec.S3.Endpoint, sec.S3.AccessKey, sec.S3.SecretKey, sec.S3.BucketName, sec.S3.Region, pathPrefix)
return svc, p, err
case "oss":
if sec == nil || sec.OSS == nil || sec.OSS.Endpoint == "" || sec.OSS.Region == "" || sec.OSS.AccessKey == "" || sec.OSS.SecretKey == "" || sec.OSS.BucketName == "" {
return nil, p, fmt.Errorf("incomplete oss config")
}
pathPrefix := strings.TrimSpace(sec.OSS.PathPrefix)
if pathPrefix == "" {
pathPrefix = "weknora/"
}
var svc interfaces.FileService
var err error
if sec.OSS.UseTempBucket && sec.OSS.TempBucketName != "" {
svc, err = NewOssFileServiceWithTempBucket(
sec.OSS.Endpoint, sec.OSS.Region, sec.OSS.AccessKey, sec.OSS.SecretKey,
sec.OSS.BucketName, pathPrefix,
sec.OSS.TempBucketName, sec.OSS.TempRegion,
)
} else {
svc, err = NewOssFileService(
sec.OSS.Endpoint, sec.OSS.Region, sec.OSS.AccessKey, sec.OSS.SecretKey,
sec.OSS.BucketName, pathPrefix,
)
}
return svc, p, err
default:
return nil, p, fmt.Errorf("unsupported provider %q", p)
}
+331
View File
@@ -0,0 +1,331 @@
package file
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"mime/multipart"
"path/filepath"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/google/uuid"
)
// ossFileService implements the FileService interface for Aliyun OSS
// using the S3-compatible protocol with virtual-hosted style addressing.
type ossFileService struct {
client *s3.Client
tempClient *s3.Client
pathPrefix string
bucketName string
tempBucketName string
}
const ossScheme = "oss://"
// newOSSClient creates a bare s3.Client configured for OSS S3-compatible mode.
// OSS uses virtual-hosted style addressing and does not support aws-chunked encoding.
func newOSSClient(endpoint, region, accessKey, secretKey string) (*s3.Client, error) {
cfg, err := config.LoadDefaultConfig(context.Background(),
config.WithRegion(region),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
// Disable automatic aws-chunked encoding — OSS does not support it.
config.WithRequestChecksumCalculation(aws.RequestChecksumCalculationWhenRequired),
config.WithResponseChecksumValidation(aws.ResponseChecksumValidationWhenRequired),
)
if err != nil {
return nil, fmt.Errorf("failed to load AWS config: %w", err)
}
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String(endpoint)
o.UsePathStyle = false
})
return client, nil
}
// ossBucketExists checks if the bucket exists using the provided client.
func ossBucketExists(ctx context.Context, client *s3.Client, bucketName string) (bool, error) {
_, err := client.HeadBucket(ctx, &s3.HeadBucketInput{
Bucket: aws.String(bucketName),
})
if err != nil {
var notFound *types.NotFound
if errors.As(err, &notFound) {
return false, nil
}
return false, err
}
return true, nil
}
// ossCreateBucket creates a new bucket using the provided client.
func ossCreateBucket(ctx context.Context, client *s3.Client, bucketName string) error {
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{
Bucket: aws.String(bucketName),
})
return err
}
// ossEnsureBucket checks if the bucket exists and creates it if missing.
func ossEnsureBucket(ctx context.Context, client *s3.Client, bucketName string) error {
exists, err := ossBucketExists(ctx, client, bucketName)
if err != nil {
return fmt.Errorf("failed to check bucket: %w", err)
}
if !exists {
if err := ossCreateBucket(ctx, client, bucketName); err != nil {
return fmt.Errorf("failed to create bucket: %w", err)
}
}
return nil
}
// NewOssFileService creates an Aliyun OSS file service.
// It verifies that the bucket exists and creates it if missing.
func NewOssFileService(endpoint, region, accessKey, secretKey, bucketName, pathPrefix string) (interfaces.FileService, error) {
return NewOssFileServiceWithTempBucket(endpoint, region, accessKey, secretKey, bucketName, pathPrefix, "", "")
}
// NewOssFileServiceWithTempBucket creates an Aliyun OSS file service with optional temp bucket.
func NewOssFileServiceWithTempBucket(endpoint, region, accessKey, secretKey, bucketName, pathPrefix, tempBucketName, tempRegion string) (interfaces.FileService, error) {
client, err := newOSSClient(endpoint, region, accessKey, secretKey)
if err != nil {
return nil, err
}
if err := ossEnsureBucket(context.Background(), client, bucketName); err != nil {
return nil, err
}
var tempClient *s3.Client
if tempBucketName != "" {
if tempRegion == "" {
tempRegion = region
}
tempClient, err = newOSSClient(endpoint, tempRegion, accessKey, secretKey)
if err != nil {
return nil, fmt.Errorf("failed to initialize OSS temp client: %w", err)
}
if err := ossEnsureBucket(context.Background(), tempClient, tempBucketName); err != nil {
return nil, err
}
}
// Normalize pathPrefix: ensure it ends with '/' if not empty
if pathPrefix != "" && !strings.HasSuffix(pathPrefix, "/") {
pathPrefix += "/"
}
return &ossFileService{
client: client,
tempClient: tempClient,
pathPrefix: pathPrefix,
bucketName: bucketName,
tempBucketName: tempBucketName,
}, nil
}
// CheckOssConnectivity tests OSS connectivity using the provided credentials.
func CheckOssConnectivity(ctx context.Context, endpoint, region, accessKey, secretKey, bucketName string) error {
client, err := newOSSClient(endpoint, region, accessKey, secretKey)
if err != nil {
return err
}
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
exists, err := ossBucketExists(checkCtx, client, bucketName)
if err != nil {
return fmt.Errorf("failed to check bucket: %w", err)
}
if !exists {
return fmt.Errorf("bucket %q does not exist", bucketName)
}
return nil
}
// parseOssFilePath extracts bucket and object key from: oss://{bucket}/{objectKey}
func parseOssFilePath(filePath string) (bucketName string, objectKey string, err error) {
if !strings.HasPrefix(filePath, ossScheme) {
return "", "", fmt.Errorf("invalid OSS file path: %s", filePath)
}
rest := strings.TrimPrefix(filePath, ossScheme)
parts := strings.SplitN(rest, "/", 2)
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return "", "", fmt.Errorf("invalid OSS file path: %s", filePath)
}
return parts[0], parts[1], nil
}
// CheckConnectivity verifies OSS is reachable and the main bucket exists.
func (s *ossFileService) CheckConnectivity(ctx context.Context) error {
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
exists, err := ossBucketExists(checkCtx, s.client, s.bucketName)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("bucket %q does not exist", s.bucketName)
}
return nil
}
// SaveFile saves a file to OSS.
func (s *ossFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint64, knowledgeID string,
) (string, error) {
ext := filepath.Ext(file.Filename)
objectName := fmt.Sprintf("%s%d/%s/%s%s", s.pathPrefix, 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()
contentType := file.Header.Get("Content-Type")
if contentType == "" {
contentType = getContentTypeByExt(ext)
}
_, err = s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucketName),
Key: aws.String(objectName),
Body: src,
ContentType: aws.String(contentType),
})
if err != nil {
return "", fmt.Errorf("failed to upload file to OSS: %w", err)
}
return fmt.Sprintf("oss://%s/%s", s.bucketName, objectName), nil
}
// SaveBytes saves bytes data to OSS.
// If temp is true and temp bucket is configured, saves to temp bucket.
// Otherwise saves to main bucket.
func (s *ossFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
safeName, err := utils.SafeFileName(fileName)
if err != nil {
return "", fmt.Errorf("invalid file name: %w", err)
}
ext := filepath.Ext(safeName)
// If requesting temp bucket and it is configured, use it
if temp && s.tempClient != nil {
objectName := fmt.Sprintf("exports/%d/%s%s", tenantID, uuid.New().String(), ext)
_, err := s.tempClient.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.tempBucketName),
Key: aws.String(objectName),
Body: bytes.NewReader(data),
ContentType: aws.String("text/csv; charset=utf-8"),
})
if err != nil {
return "", fmt.Errorf("failed to upload bytes to OSS temp bucket: %w", err)
}
return fmt.Sprintf("oss://%s/%s", s.tempBucketName, objectName), nil
}
// Save to main bucket
objectName := fmt.Sprintf("%s%d/exports/%s%s", s.pathPrefix, tenantID, uuid.New().String(), ext)
_, err = s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucketName),
Key: aws.String(objectName),
Body: bytes.NewReader(data),
ContentType: aws.String("text/csv; charset=utf-8"),
})
if err != nil {
return "", fmt.Errorf("failed to upload bytes to OSS: %w", err)
}
return fmt.Sprintf("oss://%s/%s", s.bucketName, objectName), nil
}
// GetFile retrieves a file from OSS by its path.
func (s *ossFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
bucketName, objectName, err := parseOssFilePath(filePath)
if err != nil {
return nil, err
}
if err := utils.SafeObjectKey(objectName); err != nil {
return nil, fmt.Errorf("invalid file path: %w", err)
}
resp, err := s.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectName),
})
if err != nil {
return nil, fmt.Errorf("failed to get file from OSS: %w", err)
}
return resp.Body, nil
}
// DeleteFile removes a file from OSS.
func (s *ossFileService) DeleteFile(ctx context.Context, filePath string) error {
bucketName, objectName, err := parseOssFilePath(filePath)
if err != nil {
return err
}
if err := utils.SafeObjectKey(objectName); err != nil {
return fmt.Errorf("invalid file path: %w", err)
}
_, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectName),
})
if err != nil {
return fmt.Errorf("failed to delete file from OSS: %w", err)
}
return nil
}
// GetFileURL returns a presigned download URL for the file.
func (s *ossFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
bucketName, objectName, err := parseOssFilePath(filePath)
if err != nil {
return "", err
}
if err := utils.SafeObjectKey(objectName); err != nil {
return "", fmt.Errorf("invalid file path: %w", err)
}
// Determine which client to use
var client *s3.Client
if bucketName == s.tempBucketName && s.tempClient != nil {
client = s.tempClient
} else {
client = s.client
}
presignClient := s3.NewPresignClient(client)
presignedReq, err := presignClient.PresignGetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectName),
}, s3.WithPresignExpires(24*time.Hour))
if err != nil {
return "", fmt.Errorf("failed to generate OSS presigned URL: %w", err)
}
return presignedReq.URL, nil
}
@@ -0,0 +1,208 @@
package file
import (
"context"
"strings"
"testing"
"time"
)
func TestParseOssFilePath(t *testing.T) {
tests := []struct {
name string
input string
wantBucket string
wantKey string
wantErr bool
errContains string
}{
{
name: "valid path with nested key",
input: "oss://my-bucket/123/exports/abc123.csv",
wantBucket: "my-bucket",
wantKey: "123/exports/abc123.csv",
},
{
name: "valid path with simple key",
input: "oss://test-bucket/key",
wantBucket: "test-bucket",
wantKey: "key",
},
{
name: "valid path with deep nesting",
input: "oss://bucket/prefix/tenant/exports/uuid.png",
wantBucket: "bucket",
wantKey: "prefix/tenant/exports/uuid.png",
},
{
name: "invalid scheme",
input: "s3://bucket/key",
wantErr: true,
errContains: "invalid OSS file path",
},
{
name: "empty path",
input: "",
wantErr: true,
errContains: "invalid OSS file path",
},
{
name: "bucket only no key",
input: "oss://bucket/",
wantErr: true,
errContains: "invalid OSS file path",
},
{
name: "scheme only",
input: "oss://",
wantErr: true,
errContains: "invalid OSS file path",
},
{
name: "no slash after bucket",
input: "oss://bucket",
wantErr: true,
errContains: "invalid OSS file path",
},
{
name: "empty bucket name",
input: "oss:///some-key",
wantErr: true,
errContains: "invalid OSS file path",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bucket, key, err := parseOssFilePath(tt.input)
if tt.wantErr {
if err == nil {
t.Errorf("parseOssFilePath(%q) expected error, got bucket=%q key=%q", tt.input, bucket, key)
}
if tt.errContains != "" && !strings.Contains(err.Error(), tt.errContains) {
t.Errorf("parseOssFilePath(%q) error = %v, want containing %q", tt.input, err, tt.errContains)
}
return
}
if err != nil {
t.Errorf("parseOssFilePath(%q) unexpected error: %v", tt.input, err)
return
}
if bucket != tt.wantBucket {
t.Errorf("parseOssFilePath(%q) bucket = %q, want %q", tt.input, bucket, tt.wantBucket)
}
if key != tt.wantKey {
t.Errorf("parseOssFilePath(%q) key = %q, want %q", tt.input, key, tt.wantKey)
}
})
}
}
func TestNewOSSClient(t *testing.T) {
tests := []struct {
name string
endpoint string
region string
accessKey string
secretKey string
wantErr bool
}{
{
name: "valid parameters create client",
endpoint: "https://oss-cn-hangzhou.aliyuncs.com",
region: "cn-hangzhou",
accessKey: "test-access-key",
secretKey: "test-secret-key",
wantErr: false,
},
{
name: "custom endpoint",
endpoint: "https://custom-oss-endpoint.com",
region: "cn-shanghai",
accessKey: "ak",
secretKey: "sk",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client, err := newOSSClient(tt.endpoint, tt.region, tt.accessKey, tt.secretKey)
if tt.wantErr {
if err == nil {
t.Error("expected error but got nil")
}
return
}
if err != nil {
t.Errorf("newOSSClient() unexpected error: %v", err)
return
}
if client == nil {
t.Error("expected non-nil client")
}
})
}
}
func TestCheckOssConnectivity_InvalidEndpoint(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Should fail with an invalid/unreachable endpoint
err := CheckOssConnectivity(ctx,
"https://invalid-oss-endpoint-that-does-not-exist.local",
"cn-hangzhou",
"invalid-access-key",
"invalid-secret-key",
"nonexistent-bucket",
)
if err == nil {
t.Error("CheckOssConnectivity with invalid endpoint should return an error")
}
}
func TestOssBucketExists_NonExistent(t *testing.T) {
client, err := newOSSClient(
"https://oss-cn-hangzhou.aliyuncs.com",
"cn-hangzhou",
"test-invalid-key",
"test-invalid-secret",
)
if err != nil {
t.Fatalf("newOSSClient() error: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Bucket that definitely doesn't exist - should return false, not error
// (auth may fail first, but we verify the function doesn't crash)
exists, err := ossBucketExists(ctx, client, "this-bucket-definitely-does-not-exist-12345")
// We don't assert on the result because it depends on network/auth,
// but the function should not panic or hang.
_ = exists
_ = err
}
func TestOssCreateBucket(t *testing.T) {
client, err := newOSSClient(
"https://oss-cn-hangzhou.aliyuncs.com",
"cn-hangzhou",
"test-invalid-key",
"test-invalid-secret",
)
if err != nil {
t.Fatalf("newOSSClient() error: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Should fail with invalid credentials
err = ossCreateBucket(ctx, client, "test-bucket")
if err == nil {
t.Error("ossCreateBucket with invalid credentials should return an error")
}
}
+94 -11
View File
@@ -65,6 +65,7 @@ type knowledgeService struct {
repo interfaces.KnowledgeRepository
kbService interfaces.KnowledgeBaseService
tenantRepo interfaces.TenantRepository
tenantService interfaces.TenantService
documentReader interfaces.DocumentReader
chunkService interfaces.ChunkService
chunkRepo interfaces.ChunkRepository
@@ -92,6 +93,7 @@ func NewKnowledgeService(
documentReader interfaces.DocumentReader,
kbService interfaces.KnowledgeBaseService,
tenantRepo interfaces.TenantRepository,
tenantService interfaces.TenantService,
chunkService interfaces.ChunkService,
chunkRepo interfaces.ChunkRepository,
tagRepo interfaces.KnowledgeTagRepository,
@@ -110,6 +112,7 @@ func NewKnowledgeService(
repo: repo,
kbService: kbService,
tenantRepo: tenantRepo,
tenantService: tenantService,
documentReader: documentReader,
chunkService: chunkService,
chunkRepo: chunkRepo,
@@ -1479,6 +1482,8 @@ type ProcessChunksOptions struct {
QuestionCount int
EnableMultimodel bool
StoredImages []docparser.StoredImage
IsVideo bool // true when knowledge is a standalone video file
VideoFilePath string // storage path to video file (provider:// URL)
// ParentChunks holds parent chunk data when parent-child chunking is enabled.
// When set, the chunks passed to processChunks are child chunks, and each
// child's ParentIndex references an entry in this slice.
@@ -1864,13 +1869,15 @@ func (s *knowledgeService) processChunks(ctx context.Context,
return
}
// Skip summary/question generation for image-type knowledge — the text chunk
// is just a markdown image reference, so LLM summary would be useless.
// The multimodal task will provide a caption as the description instead.
// Skip summary/question generation for image-type and video-type knowledge — the text chunk
// is just a markdown reference, so LLM summary would be useless.
// The multimodal task will provide a caption/summary as the description instead.
isImage := IsImageType(knowledge.FileType)
pendingMultimodal := isImage && options.EnableMultimodel && len(options.StoredImages) > 0
isVideo := IsVideoType(knowledge.FileType)
pendingMultimodal := (isImage && options.EnableMultimodel && len(options.StoredImages) > 0) ||
(isVideo && options.EnableMultimodel && options.IsVideo && options.VideoFilePath != "")
// For image files with pending multimodal processing, keep "processing" status
// For image/video files with pending multimodal processing, keep "processing" status
// so the frontend waits until the description is ready before showing "completed".
if pendingMultimodal {
knowledge.ParseStatus = types.ParseStatusProcessing
@@ -1884,7 +1891,7 @@ func (s *knowledgeService) processChunks(ctx context.Context,
knowledge.UpdatedAt = now
// Set summary status based on whether summary generation will be triggered
if len(textChunks) > 0 && !isImage {
if len(textChunks) > 0 && !isImage && !isVideo {
knowledge.SummaryStatus = types.SummaryStatusPending
} else {
knowledge.SummaryStatus = types.SummaryStatusNone
@@ -1895,7 +1902,7 @@ func (s *knowledgeService) processChunks(ctx context.Context,
}
// Enqueue question generation task if enabled (async, non-blocking)
if options.EnableQuestionGeneration && len(textChunks) > 0 && !isImage {
if options.EnableQuestionGeneration && len(textChunks) > 0 && !isImage && !isVideo {
questionCount := options.QuestionCount
if questionCount <= 0 {
questionCount = 3
@@ -1907,7 +1914,7 @@ func (s *knowledgeService) processChunks(ctx context.Context,
}
// Enqueue summary generation task (async, non-blocking)
if len(textChunks) > 0 && !isImage {
if len(textChunks) > 0 && !isImage && !isVideo {
s.enqueueSummaryGenerationTask(ctx, knowledge.KnowledgeBaseID, knowledge.ID)
}
@@ -1916,6 +1923,11 @@ func (s *knowledgeService) processChunks(ctx context.Context,
s.enqueueImageMultimodalTasks(ctx, knowledge, kb, options.StoredImages, chunks)
}
// Enqueue multimodal tasks for videos (async, non-blocking)
if options.EnableMultimodel && options.IsVideo && options.VideoFilePath != "" {
s.enqueueVideoMultimodalTasks(ctx, knowledge, kb, options.VideoFilePath, chunks)
}
// Update tenant's storage usage
tenantInfo.StorageUsed += totalStorageSize
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, totalStorageSize); err != nil {
@@ -3002,7 +3014,8 @@ func (s *knowledgeService) ReparseKnowledge(ctx context.Context, knowledgeID str
func isValidFileType(filename string) bool {
switch strings.ToLower(getFileType(filename)) {
case "pdf", "txt", "docx", "doc", "md", "markdown", "png", "jpg", "jpeg", "gif", "csv", "xlsx", "xls", "pptx", "ppt", "json",
"mp3", "wav", "m4a", "flac", "ogg":
"mp3", "wav", "m4a", "flac", "ogg",
"mp4", "mov", "avi", "mkv", "webm", "wmv", "flv":
return true
default:
return false
@@ -7424,6 +7437,16 @@ func IsAudioType(fileType string) bool {
}
}
// IsVideoType checks if a file type is a video format
func IsVideoType(fileType string) bool {
switch strings.ToLower(fileType) {
case "mp4", "mov", "avi", "mkv", "webm", "wmv", "flv":
return true
default:
return false
}
}
// downloadFileFromURL downloads a remote file to a temp file and returns its binary content.
// payloadFileName and payloadFileType are in/out pointers: if they point to an empty string,
// the function resolves the value from Content-Disposition / URL path and writes it back.
@@ -7899,6 +7922,8 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
QuestionCount: payload.QuestionCount,
EnableMultimodel: payload.EnableMultimodel,
StoredImages: storedImages,
IsVideo: convertResult != nil && convertResult.IsVideo,
VideoFilePath: payload.FilePath,
}
if kb.ChunkingConfig.EnableParentChild {
@@ -7972,7 +7997,7 @@ func (s *knowledgeService) convert(
logger.Infof(ctx, "[convert] kb=%s fileType=%s isURL=%v engine=%q rules=%+v",
kb.ID, fileType, isURL, parserEngine, kb.ChunkingConfig.ParserEngineRules)
var reader interfaces.DocReader = s.resolveDocReader(parserEngine, fileType, isURL, overrides)
var reader interfaces.DocReader = s.resolveDocReader(ctx, parserEngine, fileType, isURL, overrides)
if reader == nil {
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "Document parsing service is not configured. Please use text/paragraph import or set DOCREADER_ADDR."
@@ -8020,10 +8045,24 @@ func (s *knowledgeService) convert(
// resolveDocReader returns the appropriate DocReader for the given engine.
// Returns nil when the required service is unavailable.
func (s *knowledgeService) resolveDocReader(engine, fileType string, isURL bool, overrides map[string]string) interfaces.DocReader {
func (s *knowledgeService) resolveDocReader(ctx context.Context, engine, fileType string, isURL bool, overrides map[string]string) interfaces.DocReader {
switch engine {
case docparser.SimpleEngineName:
return &docparser.SimpleFormatReader{}
case docparser.WeKnoraCloudEngineName:
addr := strings.TrimSpace(overrides["docreader_addr"])
if !IsWeKnoraCloudDocReaderAddr(addr) {
return nil
}
creds := s.tenantService.GetDocreaderCredentials(ctx)
if creds == nil {
return nil
}
reader, err := docparser.NewWeKnoraCloudSignedDocumentReader(addr, creds.AppID, creds.APIKey)
if err != nil {
return nil
}
return reader
case "mineru":
return docparser.NewMinerUReader(overrides)
case "mineru_cloud":
@@ -8111,6 +8150,50 @@ func (s *knowledgeService) enqueueImageMultimodalTasks(
}
}
// enqueueVideoMultimodalTasks enqueues asynq tasks for multimodal video processing.
func (s *knowledgeService) enqueueVideoMultimodalTasks(
ctx context.Context,
knowledge *types.Knowledge,
kb *types.KnowledgeBase,
videoFilePath string,
chunks []types.ParsedChunk,
) {
if s.task == nil || videoFilePath == "" {
return
}
// Get the first chunk's ID as the parent chunk
chunkID := ""
if len(chunks) > 0 {
chunkID = chunks[0].ChunkID
}
lang, _ := types.LanguageFromContext(ctx)
payload := types.VideoMultimodalPayload{
TenantID: knowledge.TenantID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: kb.ID,
ChunkID: chunkID,
VideoURL: videoFilePath,
EnableVLM: true,
EnableASR: true,
Language: lang,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
logger.Warnf(ctx, "Failed to marshal video multimodal payload: %v", err)
return
}
task := asynq.NewTask(types.TypeVideoMultimodal, payloadBytes)
if _, err := s.task.Enqueue(task); err != nil {
logger.Warnf(ctx, "Failed to enqueue video multimodal task for %s: %v", videoFilePath, err)
} else {
logger.Infof(ctx, "Enqueued video:multimodal task for %s", videoFilePath)
}
}
// ProcessFAQImport handles Asynq FAQ import tasks (including dry run mode)
func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task) error {
var payload types.FAQImportPayload
+56 -12
View File
@@ -5,14 +5,15 @@ import (
"errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/asr"
"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/asr"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/models/vlm"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
)
// ErrModelNotFound is returned when a model cannot be found in the repository
@@ -26,7 +27,10 @@ type modelService struct {
}
// NewModelService creates a new model service instance
func NewModelService(repo interfaces.ModelRepository, ollamaService *ollama.OllamaService, pooler embedding.EmbedderPooler) interfaces.ModelService {
func NewModelService(repo interfaces.ModelRepository,
ollamaService *ollama.OllamaService,
pooler embedding.EmbedderPooler,
) interfaces.ModelService {
return &modelService{
repo: repo,
ollamaService: ollamaService,
@@ -34,6 +38,19 @@ func NewModelService(repo interfaces.ModelRepository, ollamaService *ollama.Olla
}
}
// decryptAppSecret 解密 AppSecret(如果为空或 cryptoSvc 为空则原样返回)
func (s *modelService) decryptAppSecret(encrypted string) string {
if encrypted == "" {
return encrypted
}
if key := utils.GetAESKey(); key != nil {
if encrypted, err := utils.DecryptAESGCM(encrypted, key); err == nil {
return encrypted
}
}
return encrypted
}
// 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
@@ -256,6 +273,9 @@ func (s *modelService) GetEmbeddingModel(ctx context.Context, modelId string) (e
Dimensions: model.Parameters.EmbeddingParameters.Dimension,
TruncatePromptTokens: model.Parameters.EmbeddingParameters.TruncatePromptTokens,
Provider: model.Parameters.Provider,
ExtraConfig: model.Parameters.ExtraConfig,
AppID: model.Parameters.AppID,
AppSecret: s.decryptAppSecret(model.Parameters.AppSecret),
}, s.pooler, s.ollamaService)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -311,6 +331,9 @@ func (s *modelService) GetEmbeddingModelForTenant(ctx context.Context, modelId s
Dimensions: model.Parameters.EmbeddingParameters.Dimension,
TruncatePromptTokens: model.Parameters.EmbeddingParameters.TruncatePromptTokens,
Provider: model.Parameters.Provider,
ExtraConfig: model.Parameters.ExtraConfig,
AppID: model.Parameters.AppID,
AppSecret: s.decryptAppSecret(model.Parameters.AppSecret),
}, s.pooler, s.ollamaService)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -341,11 +364,15 @@ func (s *modelService) GetRerankModel(ctx context.Context, modelId string) (rera
// 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,
ModelID: model.ID,
APIKey: model.Parameters.APIKey,
BaseURL: model.Parameters.BaseURL,
ModelName: model.Name,
Source: model.Source,
Provider: model.Parameters.Provider,
ExtraConfig: model.Parameters.ExtraConfig,
AppID: model.Parameters.AppID,
AppSecret: s.decryptAppSecret(model.Parameters.AppSecret),
})
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -389,11 +416,15 @@ func (s *modelService) GetChatModel(ctx context.Context, modelId string) (chat.C
// 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,
ModelID: model.ID,
APIKey: model.Parameters.APIKey,
BaseURL: model.Parameters.BaseURL,
ModelName: model.Name,
Source: model.Source,
Provider: model.Parameters.Provider,
ExtraConfig: model.Parameters.ExtraConfig,
AppID: model.Parameters.AppID,
AppSecret: s.decryptAppSecret(model.Parameters.AppSecret),
}, s.ollamaService)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -445,6 +476,8 @@ func (s *modelService) GetVLMModel(ctx context.Context, modelId string) (vlm.VLM
ModelName: model.Name,
Source: model.Source,
InterfaceType: ifType,
Provider: model.Parameters.Provider,
Extra: stringMapToAnyMap(model.Parameters.ExtraConfig),
}, s.ollamaService)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -500,3 +533,14 @@ func (s *modelService) GetASRModel(ctx context.Context, modelId string) (asr.ASR
return sttModel, nil
}
func stringMapToAnyMap(m map[string]string) map[string]any {
if m == nil {
return nil
}
result := make(map[string]any, len(m))
for k, v := range m {
result[k] = v
}
return result
}
@@ -115,6 +115,7 @@ func (s *sessionService) KnowledgeQA(
RewritePromptUser: s.cfg.Conversation.RewritePromptUser,
WebSearchEnabled: req.WebSearchEnabled,
WebSearchProviderID: s.resolveWebSearchProviderID(ctx, req, retrievalTenantID),
WebSearchMaxResults: s.resolveWebSearchMaxResults(ctx, req),
WebFetchEnabled: s.resolveWebFetchEnabled(req),
WebFetchTopN: s.resolveWebFetchTopN(req),
TenantID: retrievalTenantID,
@@ -846,3 +847,16 @@ func (s *sessionService) resolveWebFetchTopN(req *types.QARequest) int {
}
return 3
}
// resolveWebSearchMaxResults returns the max results for web search.
// Priority: agent config > tenant default > default (10)
func (s *sessionService) resolveWebSearchMaxResults(ctx context.Context, req *types.QARequest) int {
if req.CustomAgent != nil && req.CustomAgent.Config.WebSearchMaxResults > 0 {
return req.CustomAgent.Config.WebSearchMaxResults
}
tenantInfo, _ := types.TenantInfoFromContext(ctx)
if tenantInfo != nil && tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
return tenantInfo.WebSearchConfig.MaxResults
}
return 10
}
@@ -176,6 +176,11 @@ func (s *sessionService) applyAgentOverridesToChatManage(
cm.FallbackPrompt = customAgent.Config.FallbackPrompt
}
// Override web search settings
if customAgent.Config.WebSearchMaxResults > 0 {
cm.WebSearchMaxResults = customAgent.Config.WebSearchMaxResults
}
// Override history turns
if customAgent.Config.HistoryTurns > 0 {
cm.MaxRounds = customAgent.Config.HistoryTurns
+40
View File
@@ -342,3 +342,43 @@ func (s *tenantService) GetTenantByIDForUser(ctx context.Context, tenantID uint6
return tenant, nil
}
func (s *tenantService) GetDocreaderCredentials(ctx context.Context) *types.DocreaderCredentials {
// Try to get tenant info directly first
if tenant, ok := types.TenantInfoFromContext(ctx); ok {
if tenant.ParserEngineConfig != nil {
appID := strings.TrimSpace(tenant.ParserEngineConfig.DocreaderAppID)
if appID == "" || tenant.ParserEngineConfig.DocreaderAPIKey == "" {
return nil
}
if key := utils.GetAESKey(); key != nil {
if encrypted, err := utils.DecryptAESGCM(tenant.ParserEngineConfig.DocreaderAPIKey, key); err == nil {
return &types.DocreaderCredentials{AppID: appID, APIKey: encrypted}
}
}
return &types.DocreaderCredentials{AppID: appID, APIKey: tenant.ParserEngineConfig.DocreaderAPIKey}
}
}
// If no tenant info in context, try to get tenant ID and load tenant
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return nil
}
// Load tenant from repo if we only have tenantID
tenant, err := s.repo.GetTenantByID(ctx, tenantID)
if err == nil && tenant != nil && tenant.ParserEngineConfig != nil {
appID := strings.TrimSpace(tenant.ParserEngineConfig.DocreaderAppID)
if appID != "" && tenant.ParserEngineConfig.DocreaderAPIKey != "" {
if key := utils.GetAESKey(); key != nil {
if encrypted, err := utils.DecryptAESGCM(tenant.ParserEngineConfig.DocreaderAPIKey, key); err == nil {
return &types.DocreaderCredentials{AppID: appID, APIKey: encrypted}
}
}
return &types.DocreaderCredentials{AppID: appID, APIKey: tenant.ParserEngineConfig.DocreaderAPIKey}
}
}
return nil
}
+121
View File
@@ -0,0 +1,121 @@
package service
import (
"context"
"os"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// vectorStoreService implements interfaces.VectorStoreService
type vectorStoreService struct {
repo interfaces.VectorStoreRepository
}
// NewVectorStoreService creates a new vector store service
func NewVectorStoreService(
repo interfaces.VectorStoreRepository,
) interfaces.VectorStoreService {
return &vectorStoreService{repo: repo}
}
// CreateStore validates and creates a new vector store.
func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.VectorStore) error {
// 1. Basic validation (name, engine_type, tenant_id)
if err := store.Validate(); err != nil {
return err
}
// 2. Engine-specific connection config validation
if err := validateConnectionConfig(store.EngineType, store.ConnectionConfig); err != nil {
return err
}
// 3. Duplicate check — DB stores
endpoint := store.ConnectionConfig.GetEndpoint()
indexName := store.IndexConfig.GetIndexNameOrDefault(store.EngineType)
exists, err := s.repo.ExistsByEndpointAndIndex(ctx, store.TenantID, store.EngineType, endpoint, indexName)
if err != nil {
return errors.NewInternalServerError("failed to check for duplicates")
}
if exists {
return errors.NewConflictError("a vector store with the same endpoint and index already exists")
}
// 4. Duplicate check — env stores (pure function, no os.Getenv in types)
for _, envStore := range types.BuildEnvVectorStores(os.Getenv("RETRIEVE_DRIVER"), os.Getenv) {
if envStore.EngineType == store.EngineType &&
envStore.ConnectionConfig.GetEndpoint() == endpoint &&
envStore.IndexConfig.GetIndexNameOrDefault(store.EngineType) == indexName {
return errors.NewConflictError(
"a vector store with the same endpoint and index is already configured via environment variables")
}
}
// 5. Persist
logger.Infof(ctx, "Creating vector store: tenant=%d, name=%s, engine=%s",
store.TenantID, secutils.SanitizeForLog(store.Name), store.EngineType)
return s.repo.Create(ctx, store)
}
// UpdateStore updates an existing vector store (name only).
func (s *vectorStoreService) UpdateStore(ctx context.Context, store *types.VectorStore) error {
if store.TenantID == 0 {
return errors.NewValidationError("tenant_id is required")
}
if store.Name == "" {
return errors.NewValidationError("name is required")
}
logger.Infof(ctx, "Updating vector store: tenant=%d, id=%s", store.TenantID, store.ID)
return s.repo.Update(ctx, store)
}
// DeleteStore deletes a vector store by tenant + id.
// Phase 2: KB binding check will be added here.
func (s *vectorStoreService) DeleteStore(ctx context.Context, tenantID uint64, id string) error {
logger.Infof(ctx, "Deleting vector store: tenant=%d, id=%s", tenantID, id)
return s.repo.Delete(ctx, tenantID, id)
}
// SaveDetectedVersion updates the connection_config.version for a stored vector store.
// Works on a copy to avoid mutating the caller's object.
func (s *vectorStoreService) SaveDetectedVersion(ctx context.Context, store *types.VectorStore, version string) error {
updated := *store
updated.ConnectionConfig.Version = version
return s.repo.UpdateConnectionConfig(ctx, &updated)
}
// validateConnectionConfig validates required fields per engine type.
func validateConnectionConfig(engineType types.RetrieverEngineType, config types.ConnectionConfig) error {
switch engineType {
case types.ElasticsearchRetrieverEngineType:
if config.Addr == "" {
return errors.NewValidationError("addr is required for elasticsearch")
}
case types.PostgresRetrieverEngineType:
if !config.UseDefaultConnection && config.Addr == "" {
return errors.NewValidationError("addr or use_default_connection is required for postgres")
}
case types.QdrantRetrieverEngineType:
if config.Host == "" {
return errors.NewValidationError("host is required for qdrant")
}
case types.MilvusRetrieverEngineType:
if config.Addr == "" {
return errors.NewValidationError("addr is required for milvus")
}
case types.WeaviateRetrieverEngineType:
if config.Host == "" {
return errors.NewValidationError("host is required for weaviate")
}
case types.SQLiteRetrieverEngineType:
// No connection config needed for SQLite
}
return nil
}
@@ -0,0 +1,228 @@
package service
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"time"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
_ "github.com/jackc/pgx/v5/stdlib" // pgx driver for database/sql
"github.com/qdrant/go-client/qdrant"
"github.com/weaviate/weaviate-go-client/v5/weaviate"
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
)
const connectionTestTimeout = 10 * time.Second
// TestConnection tests connectivity to a vector database.
// Returns the detected server version on success (e.g., "7.10.1"), empty string if unknown.
func (s *vectorStoreService) TestConnection(
ctx context.Context,
engineType types.RetrieverEngineType,
config types.ConnectionConfig,
) (string, error) {
switch engineType {
case types.ElasticsearchRetrieverEngineType:
return testElasticsearchConnection(ctx, config)
case types.PostgresRetrieverEngineType:
return testPostgresConnection(ctx, config)
case types.QdrantRetrieverEngineType:
return testQdrantConnection(ctx, config)
case types.MilvusRetrieverEngineType:
return testMilvusConnection(ctx, config)
case types.WeaviateRetrieverEngineType:
return testWeaviateConnection(ctx, config)
case types.SQLiteRetrieverEngineType:
// SQLite is file-based, no remote connection to test
return "", nil
default:
return "", errors.NewBadRequestError(
fmt.Sprintf("connection test not supported for engine type: %s", engineType))
}
}
func testElasticsearchConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
// Use plain HTTP GET to the root endpoint instead of the go-elasticsearch SDK.
// The v8 SDK's TypedClient performs a product check that rejects ES7 servers,
// so we use a raw HTTP request to support both v7 and v8.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, config.Addr, nil)
if err != nil {
return "", errors.NewBadRequestError("failed to create elasticsearch request: invalid address")
}
if config.Username != "" {
req.SetBasicAuth(config.Username, config.Password)
}
client := &http.Client{Timeout: connectionTestTimeout}
resp, err := client.Do(req)
if err != nil {
logger.Warnf(ctx, "Elasticsearch connection test failed: %v", err)
return "", errors.NewBadRequestError("failed to connect to elasticsearch: connection refused or authentication failed")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Warnf(ctx, "Elasticsearch connection test returned status %d", resp.StatusCode)
return "", errors.NewBadRequestError("failed to connect to elasticsearch: authentication failed or server error")
}
// Parse version from response: {"version": {"number": "7.10.1"}, ...}
body, err := io.ReadAll(io.LimitReader(resp.Body, 4096))
if err != nil {
return "", nil // connected but version unknown
}
var esInfo struct {
Version struct {
Number string `json:"number"`
} `json:"version"`
}
if err := json.Unmarshal(body, &esInfo); err != nil {
return "", nil // connected but version unparseable
}
return esInfo.Version.Number, nil
}
func testPostgresConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
defer cancel()
if config.UseDefaultConnection {
// Using the default app DB connection — always reachable if the app is running.
// Cannot query version without a DB handle; return empty.
return "", nil
}
db, err := sql.Open("pgx", config.Addr)
if err != nil {
return "", errors.NewBadRequestError("failed to create postgres connection: invalid configuration")
}
defer db.Close()
if err := db.PingContext(testCtx); err != nil {
logger.Warnf(ctx, "Postgres connection test failed: %v", err)
return "", errors.NewBadRequestError("failed to connect to postgres: connection refused or authentication failed")
}
// Detect version
var version string
if err := db.QueryRowContext(testCtx, "SHOW server_version").Scan(&version); err != nil {
logger.Warnf(ctx, "Postgres version detection failed: %v", err)
return "", nil // connected but version unknown
}
return version, nil
}
func testQdrantConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
defer cancel()
port := config.Port
if port == 0 {
port = 6334
}
client, err := qdrant.NewClient(&qdrant.Config{
Host: config.Host,
Port: port,
APIKey: config.APIKey,
UseTLS: config.UseTLS,
})
if err != nil {
return "", errors.NewBadRequestError("failed to create qdrant client: invalid configuration")
}
defer client.Close()
result, err := client.HealthCheck(testCtx)
if err != nil {
logger.Warnf(ctx, "Qdrant connection test failed: %v", err)
return "", errors.NewBadRequestError("failed to connect to qdrant: connection refused or authentication failed")
}
return result.GetVersion(), nil
}
func testMilvusConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
// Use TCP dial instead of the Milvus SDK to avoid protobuf namespace conflict
// between milvus-proto and qdrant-client (both register "common.proto").
// A TCP dial is sufficient for connectivity verification; the Milvus SDK client
// creation in container.go (PR 3) will validate full gRPC connectivity.
// Version detection is not possible with TCP dial alone.
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
defer cancel()
addr := config.Addr
if addr == "" {
addr = "localhost:19530"
}
conn, err := (&net.Dialer{}).DialContext(testCtx, "tcp", addr)
if err != nil {
logger.Warnf(ctx, "Milvus connection test failed: %v", err)
return "", errors.NewBadRequestError("failed to connect to milvus: connection refused or server unreachable")
}
defer conn.Close()
return "", nil
}
func testWeaviateConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
defer cancel()
host := config.Host
if host == "" {
host = "weaviate:8080"
}
grpcAddress := config.GrpcAddress
if grpcAddress == "" {
grpcAddress = "weaviate:50051"
}
scheme := config.Scheme
if scheme == "" {
scheme = "http"
}
weaviateCfg := weaviate.Config{
Host: host,
GrpcConfig: &wgrpc.Config{
Host: grpcAddress,
},
Scheme: scheme,
}
if config.APIKey != "" {
weaviateCfg.AuthConfig = auth.ApiKey{Value: config.APIKey}
}
// Weaviate Go client v5 does not expose a Close() method;
// it uses HTTP + gRPC transports that are managed internally.
client, err := weaviate.NewClient(weaviateCfg)
if err != nil {
logger.Warnf(ctx, "Weaviate connection test failed: %v", err)
return "", errors.NewBadRequestError("failed to create weaviate client: invalid configuration")
}
isReady, err := client.Misc().ReadyChecker().Do(testCtx)
if err != nil || !isReady {
logger.Warnf(ctx, "Weaviate connection test failed: ready=%v, err=%v", isReady, err)
return "", errors.NewBadRequestError("failed to connect to weaviate: server not ready or authentication failed")
}
// Detect version via /v1/meta
meta, err := client.Misc().MetaGetter().Do(testCtx)
if err != nil || meta == nil {
return "", nil // connected but version unknown
}
return meta.Version, nil
}
@@ -0,0 +1,525 @@
package service
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// ---------------------------------------------------------------------------
// Mock repository
// ---------------------------------------------------------------------------
type mockVectorStoreRepo struct {
stores []*types.VectorStore
createErr error
updateErr error
deleteErr error
existsByEndpointErr error
existsByEndpoint bool
}
func (m *mockVectorStoreRepo) Create(_ context.Context, store *types.VectorStore) error {
if m.createErr != nil {
return m.createErr
}
m.stores = append(m.stores, store)
return nil
}
func (m *mockVectorStoreRepo) GetByID(_ context.Context, tenantID uint64, id string) (*types.VectorStore, error) {
for _, s := range m.stores {
if s.ID == id && s.TenantID == tenantID {
return s, nil
}
}
return nil, nil
}
func (m *mockVectorStoreRepo) List(_ context.Context, tenantID uint64) ([]*types.VectorStore, error) {
var result []*types.VectorStore
for _, s := range m.stores {
if s.TenantID == tenantID {
result = append(result, s)
}
}
return result, nil
}
func (m *mockVectorStoreRepo) Update(_ context.Context, store *types.VectorStore) error {
return m.updateErr
}
func (m *mockVectorStoreRepo) UpdateConnectionConfig(_ context.Context, _ *types.VectorStore) error {
return m.updateErr
}
func (m *mockVectorStoreRepo) Delete(_ context.Context, _ uint64, _ string) error {
return m.deleteErr
}
func (m *mockVectorStoreRepo) ExistsByEndpointAndIndex(
_ context.Context, _ uint64, _ types.RetrieverEngineType, _ string, _ string,
) (bool, error) {
if m.existsByEndpointErr != nil {
return false, m.existsByEndpointErr
}
return m.existsByEndpoint, nil
}
// ---------------------------------------------------------------------------
// CreateStore tests
// ---------------------------------------------------------------------------
func TestCreateStore_Success(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
store := &types.VectorStore{
TenantID: 1,
Name: "test-es",
EngineType: types.ElasticsearchRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
Addr: "http://es:9200",
},
}
err := svc.CreateStore(context.Background(), store)
assert.NoError(t, err)
assert.Len(t, repo.stores, 1)
}
func TestCreateStore_ValidationError(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
tests := []struct {
name string
store *types.VectorStore
}{
{
name: "empty name",
store: &types.VectorStore{TenantID: 1, EngineType: types.PostgresRetrieverEngineType},
},
{
name: "invalid engine type",
store: &types.VectorStore{TenantID: 1, Name: "test", EngineType: "unknown"},
},
{
name: "zero tenant ID",
store: &types.VectorStore{Name: "test", EngineType: types.PostgresRetrieverEngineType},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := svc.CreateStore(context.Background(), tt.store)
require.Error(t, err)
var appErr *errors.AppError
assert.ErrorAs(t, err, &appErr)
})
}
}
func TestCreateStore_ConnectionConfigValidation(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
tests := []struct {
name string
store *types.VectorStore
wantError bool
}{
{
name: "elasticsearch without addr",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.ElasticsearchRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: true,
},
{
name: "postgres without addr or default connection",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.PostgresRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: true,
},
{
name: "postgres with use_default_connection",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.PostgresRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{UseDefaultConnection: true},
},
wantError: false,
},
{
name: "qdrant without host",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.QdrantRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: true,
},
{
name: "milvus without addr",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.MilvusRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: true,
},
{
name: "weaviate without host",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.WeaviateRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: true,
},
{
name: "sqlite with no config (ok)",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.SQLiteRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := svc.CreateStore(context.Background(), tt.store)
if tt.wantError {
require.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
func TestCreateStore_DuplicateCheck_DBStore(t *testing.T) {
repo := &mockVectorStoreRepo{existsByEndpoint: true}
svc := NewVectorStoreService(repo)
store := &types.VectorStore{
TenantID: 1,
Name: "dup-store",
EngineType: types.ElasticsearchRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
Addr: "http://es:9200",
},
}
err := svc.CreateStore(context.Background(), store)
require.Error(t, err)
var appErr *errors.AppError
require.ErrorAs(t, err, &appErr)
assert.Equal(t, errors.ErrConflict, appErr.Code)
}
func TestCreateStore_DuplicateCheck_DBError(t *testing.T) {
repo := &mockVectorStoreRepo{
existsByEndpointErr: assert.AnError,
}
svc := NewVectorStoreService(repo)
store := &types.VectorStore{
TenantID: 1,
Name: "test",
EngineType: types.ElasticsearchRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
Addr: "http://es:9200",
},
}
err := svc.CreateStore(context.Background(), store)
require.Error(t, err)
}
func TestCreateStore_DuplicateCheck_EnvStore(t *testing.T) {
// Set up env to simulate an existing elasticsearch env store
t.Setenv("RETRIEVE_DRIVER", "elasticsearch_v8")
t.Setenv("ELASTICSEARCH_ADDR", "http://es:9200")
t.Setenv("ELASTICSEARCH_USERNAME", "elastic")
t.Setenv("ELASTICSEARCH_PASSWORD", "secret")
t.Setenv("ELASTICSEARCH_INDEX", "xwrag_default")
repo := &mockVectorStoreRepo{existsByEndpoint: false} // no DB duplicate
svc := NewVectorStoreService(repo)
store := &types.VectorStore{
TenantID: 1,
Name: "dup-env-store",
EngineType: types.ElasticsearchRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
Addr: "http://es:9200",
},
IndexConfig: types.IndexConfig{
IndexName: "xwrag_default",
},
}
err := svc.CreateStore(context.Background(), store)
require.Error(t, err)
var appErr *errors.AppError
require.ErrorAs(t, err, &appErr)
assert.Equal(t, errors.ErrConflict, appErr.Code)
assert.Contains(t, appErr.Error(), "environment variables")
}
func TestCreateStore_DuplicateCheck_EnvStore_DifferentIndex_Allowed(t *testing.T) {
// Same endpoint as env store but different index — should be allowed
t.Setenv("RETRIEVE_DRIVER", "elasticsearch_v8")
t.Setenv("ELASTICSEARCH_ADDR", "http://es:9200")
t.Setenv("ELASTICSEARCH_INDEX", "xwrag_default")
repo := &mockVectorStoreRepo{existsByEndpoint: false}
svc := NewVectorStoreService(repo)
store := &types.VectorStore{
TenantID: 1,
Name: "different-index",
EngineType: types.ElasticsearchRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
Addr: "http://es:9200",
},
IndexConfig: types.IndexConfig{
IndexName: "different_index",
},
}
err := svc.CreateStore(context.Background(), store)
assert.NoError(t, err)
}
func TestCreateStore_DifferentEndpointSameIndex_Allowed(t *testing.T) {
repo := &mockVectorStoreRepo{existsByEndpoint: false}
svc := NewVectorStoreService(repo)
store := &types.VectorStore{
TenantID: 1,
Name: "new-store",
EngineType: types.ElasticsearchRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
Addr: "http://es-new:9200",
},
IndexConfig: types.IndexConfig{
IndexName: "shared_index",
},
}
err := svc.CreateStore(context.Background(), store)
assert.NoError(t, err)
}
// ---------------------------------------------------------------------------
// UpdateStore tests
// ---------------------------------------------------------------------------
func TestUpdateStore_Success(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
store := &types.VectorStore{
ID: "test-id",
TenantID: 1,
Name: "updated-name",
}
err := svc.UpdateStore(context.Background(), store)
assert.NoError(t, err)
}
func TestUpdateStore_ValidationError(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
tests := []struct {
name string
store *types.VectorStore
}{
{
name: "empty name",
store: &types.VectorStore{ID: "id", TenantID: 1, Name: ""},
},
{
name: "zero tenant ID",
store: &types.VectorStore{ID: "id", TenantID: 0, Name: "test"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := svc.UpdateStore(context.Background(), tt.store)
require.Error(t, err)
})
}
}
// ---------------------------------------------------------------------------
// DeleteStore tests
// ---------------------------------------------------------------------------
func TestDeleteStore_Success(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
err := svc.DeleteStore(context.Background(), 1, "test-id")
assert.NoError(t, err)
}
func TestDeleteStore_RepoError(t *testing.T) {
repo := &mockVectorStoreRepo{deleteErr: assert.AnError}
svc := NewVectorStoreService(repo)
err := svc.DeleteStore(context.Background(), 1, "test-id")
assert.Error(t, err)
}
// ---------------------------------------------------------------------------
// TestConnection tests
// ---------------------------------------------------------------------------
func TestTestConnection_UnsupportedEngineType(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
_, err := svc.TestConnection(context.Background(), "unknown_engine", types.ConnectionConfig{})
require.Error(t, err)
var appErr *errors.AppError
require.ErrorAs(t, err, &appErr)
assert.Equal(t, errors.ErrBadRequest, appErr.Code)
}
func TestTestConnection_SQLiteAlwaysSucceeds(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
version, err := svc.TestConnection(context.Background(), types.SQLiteRetrieverEngineType, types.ConnectionConfig{})
assert.NoError(t, err)
assert.Empty(t, version)
}
func TestTestConnection_PostgresDefaultConnection(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo)
version, err := svc.TestConnection(context.Background(), types.PostgresRetrieverEngineType,
types.ConnectionConfig{UseDefaultConnection: true})
assert.NoError(t, err)
assert.Empty(t, version) // default connection cannot detect version without DB handle
}
// ---------------------------------------------------------------------------
// validateConnectionConfig tests
// ---------------------------------------------------------------------------
func TestValidateConnectionConfig(t *testing.T) {
tests := []struct {
name string
engineType types.RetrieverEngineType
config types.ConnectionConfig
wantError bool
}{
{
name: "elasticsearch valid",
engineType: types.ElasticsearchRetrieverEngineType,
config: types.ConnectionConfig{Addr: "http://es:9200"},
wantError: false,
},
{
name: "elasticsearch missing addr",
engineType: types.ElasticsearchRetrieverEngineType,
config: types.ConnectionConfig{},
wantError: true,
},
{
name: "postgres with default connection",
engineType: types.PostgresRetrieverEngineType,
config: types.ConnectionConfig{UseDefaultConnection: true},
wantError: false,
},
{
name: "postgres with addr",
engineType: types.PostgresRetrieverEngineType,
config: types.ConnectionConfig{Addr: "postgres://host:5432/db"},
wantError: false,
},
{
name: "postgres without addr or default",
engineType: types.PostgresRetrieverEngineType,
config: types.ConnectionConfig{},
wantError: true,
},
{
name: "qdrant valid",
engineType: types.QdrantRetrieverEngineType,
config: types.ConnectionConfig{Host: "qdrant-host"},
wantError: false,
},
{
name: "qdrant missing host",
engineType: types.QdrantRetrieverEngineType,
config: types.ConnectionConfig{},
wantError: true,
},
{
name: "milvus valid",
engineType: types.MilvusRetrieverEngineType,
config: types.ConnectionConfig{Addr: "milvus:19530"},
wantError: false,
},
{
name: "milvus missing addr",
engineType: types.MilvusRetrieverEngineType,
config: types.ConnectionConfig{},
wantError: true,
},
{
name: "weaviate valid",
engineType: types.WeaviateRetrieverEngineType,
config: types.ConnectionConfig{Host: "weaviate:8080"},
wantError: false,
},
{
name: "weaviate missing host",
engineType: types.WeaviateRetrieverEngineType,
config: types.ConnectionConfig{},
wantError: true,
},
{
name: "sqlite always valid",
engineType: types.SQLiteRetrieverEngineType,
config: types.ConnectionConfig{},
wantError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateConnectionConfig(tt.engineType, tt.config)
if tt.wantError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
@@ -0,0 +1,596 @@
package service
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
filesvc "github.com/Tencent/WeKnora/internal/application/service/file"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/asr"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/models/video"
"github.com/Tencent/WeKnora/internal/models/vlm"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
"github.com/hibiken/asynq"
)
const (
vlmFramePrompt = "Analyze this video frame and provide a detailed description in Chinese. Requirements:\n" +
"1. Describe visible objects, people, and their actions\n" +
"2. Describe the scene and environment\n" +
"3. Extract and describe any text on the screen\n" +
"4. Note any notable events or changes\n" +
"5. Be concise but comprehensive"
vlmSummaryPrompt = "Summarize the following video frame descriptions into a coherent video summary in Chinese. Requirements:\n" +
"1. The descriptions are ordered chronologically by timestamp\n" +
"2. Focus on the main storyline and key events\n" +
"3. Maintain the temporal flow of the video\n" +
"4. Be concise but comprehensive"
)
// VideoMultimodalService handles video:multimodal asynq tasks.
// It reads videos from storage (via FileService for provider:// URLs),
// extracts frames using FFmpeg, performs VLM analysis and ASR transcription,
// and creates child chunks.
type VideoMultimodalService struct {
chunkService interfaces.ChunkService
modelService interfaces.ModelService
kbService interfaces.KnowledgeBaseService
knowledgeRepo interfaces.KnowledgeRepository
tenantRepo interfaces.TenantRepository
retrieveEngine interfaces.RetrieveEngineRegistry
ollamaService *ollama.OllamaService
taskEnqueuer interfaces.TaskEnqueuer
}
func NewVideoMultimodalService(
chunkService interfaces.ChunkService,
modelService interfaces.ModelService,
kbService interfaces.KnowledgeBaseService,
knowledgeRepo interfaces.KnowledgeRepository,
tenantRepo interfaces.TenantRepository,
retrieveEngine interfaces.RetrieveEngineRegistry,
ollamaService *ollama.OllamaService,
taskEnqueuer interfaces.TaskEnqueuer,
) interfaces.TaskHandler {
return &VideoMultimodalService{
chunkService: chunkService,
modelService: modelService,
kbService: kbService,
knowledgeRepo: knowledgeRepo,
tenantRepo: tenantRepo,
retrieveEngine: retrieveEngine,
ollamaService: ollamaService,
taskEnqueuer: taskEnqueuer,
}
}
// Handle implements asynq handler for TypeVideoMultimodal.
func (s *VideoMultimodalService) Handle(ctx context.Context, task *asynq.Task) error {
var payload types.VideoMultimodalPayload
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
return fmt.Errorf("unmarshal video multimodal payload: %w", err)
}
logger.Infof(ctx, "[VideoMultimodal] Processing video: chunk=%s, url=%s, vlm=%v, asr=%v",
payload.ChunkID, payload.VideoURL, payload.EnableVLM, payload.EnableASR)
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
if payload.Language != "" {
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
var videoBytes []byte
videoBytes, err := s.readVideoBytes(ctx, payload)
if err != nil {
return fmt.Errorf("read video bytes: %w", err)
}
if !payload.EnableVLM && !payload.EnableASR {
logger.Infof(ctx, "[VideoMultimodal] Both VLM and ASR are disabled, nothing to do")
return nil
}
var frames []*video.Frame
var extractor video.Extractor
if payload.EnableVLM {
var extErr error
extractor, extErr = video.NewExtractor(nil)
if extErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] FFmpeg not found or not executable, frame extraction disabled: %v", extErr)
logger.Warnf(ctx, "[VideoMultimodal] Note: Please install FFmpeg to enable VLM frame analysis")
frames = []*video.Frame{}
} else {
options := video.DefaultExtractOptions()
if payload.MaxFrames > 0 {
options.MaxFrames = payload.MaxFrames
}
var extractErr error
frames, extractErr = extractor.ExtractFrames(ctx, videoBytes, options)
if extractErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] Frame extraction failed: %v", extractErr)
frames = []*video.Frame{}
}
}
} else {
logger.Infof(ctx, "[VideoMultimodal] VLM disabled, skipping frame extraction")
frames = []*video.Frame{}
}
frameDescriptions := make([]string, 0, len(frames))
if payload.EnableVLM {
vlmMdl, vlmErr := s.resolveVLM(ctx, payload.KnowledgeBaseID)
if vlmErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to resolve VLM: %v", vlmErr)
} else {
for i, frame := range frames {
desc, descErr := vlmMdl.Predict(ctx, frame.ImageData, vlmFramePrompt)
if descErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] VLM analysis failed for frame %d at %.2fs: %v",
i, frame.Timestamp, descErr)
continue
}
frameDesc := fmt.Sprintf("[%.2fs] %s", frame.Timestamp, desc)
frameDescriptions = append(frameDescriptions, frameDesc)
logger.Infof(ctx, "[VideoMultimodal] Frame %d analyzed at %.2fs, desc len=%d",
i, frame.Timestamp, len(desc))
}
}
}
var asrText string
if payload.EnableASR {
asrText, err = s.transcribeAudio(ctx, videoBytes, payload.KnowledgeBaseID)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] ASR transcription failed: %v", err)
} else if asrText != "" {
logger.Infof(ctx, "[VideoMultimodal] ASR transcription completed, len=%d", len(asrText))
}
}
var videoSummary string
if len(frameDescriptions) > 0 && payload.EnableVLM {
vlmMdl, _ := s.resolveVLM(ctx, payload.KnowledgeBaseID)
if vlmMdl != nil {
combinedInput := strings.Join(frameDescriptions, "\n")
summary, sumErr := vlmMdl.Predict(ctx, []byte(combinedInput), vlmSummaryPrompt)
if sumErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] Video summarization failed: %v", sumErr)
videoSummary = combinedInput
} else {
videoSummary = summary
}
} else {
videoSummary = strings.Join(frameDescriptions, "\n")
}
}
videoInfo := types.VideoInfo{
URL: payload.VideoURL,
FrameCount: len(frameDescriptions),
HasVLMAnalysis: len(frameDescriptions) > 0,
HasASR: asrText != "",
VideoSummary: videoSummary,
ASRText: asrText,
FrameDescriptions: frameDescriptions,
}
videoInfoJSON, _ := json.Marshal([]types.VideoInfo{videoInfo})
newChunks := s.buildVideoChunks(payload, frameDescriptions, videoSummary, asrText, string(videoInfoJSON))
if len(newChunks) == 0 {
// Even if VLM/ASR both failed, mark knowledge as completed
s.finalizeVideoKnowledge(ctx, payload, "")
return nil
}
if err := s.chunkService.CreateChunks(ctx, newChunks); err != nil {
return fmt.Errorf("create video multimodal chunks: %w", err)
}
for _, c := range newChunks {
logger.Infof(ctx, "[VideoMultimodal] Created %s chunk %s for video %s, len=%d",
c.ChunkType, c.ID, payload.VideoURL, len(c.Content))
}
// Index chunks so they can be retrieved
s.indexChunks(ctx, payload, newChunks)
// Update the parent text chunk's VideoInfo (mirrors old docreader behaviour)
s.updateParentChunkVideoInfo(ctx, payload, videoInfo)
// For standalone video files, use summary as the knowledge description
// and mark the knowledge as completed (it was kept in "processing" until now).
s.finalizeVideoKnowledge(ctx, payload, videoSummary)
// Enqueue question generation for the frame descriptions/summary/ASR content if KB has it enabled.
// During initial processChunks, question generation is skipped for video-type
// knowledge because the text chunk is just a markdown reference. Now that we
// have real textual content (frame descriptions, summary, ASR), we can generate questions.
s.enqueueQuestionGenerationIfEnabled(ctx, payload)
return nil
}
func (s *VideoMultimodalService) readVideoBytes(ctx context.Context, payload types.VideoMultimodalPayload) ([]byte, error) {
var err error
var videoBytes []byte
if types.ParseProviderScheme(payload.VideoURL) != "" {
fileSvc := s.resolveFileServiceForPayload(ctx, payload)
if fileSvc == nil {
logger.Warnf(ctx, "[VideoMultimodal] Resolve tenant file service failed, fallback to URL/local: tenant=%d kb=%s",
payload.TenantID, payload.KnowledgeBaseID)
} else {
// provider:// scheme — read via FileService
reader, getErr := fileSvc.GetFile(ctx, payload.VideoURL)
if getErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] FileService.GetFile(%s) failed: %v", payload.VideoURL, getErr)
} else {
videoBytes, err = io.ReadAll(reader)
reader.Close()
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Read provider file %s failed: %v", payload.VideoURL, err)
videoBytes = nil
}
}
}
}
if videoBytes == nil && payload.VideoLocalPath != "" {
videoBytes, err = os.ReadFile(payload.VideoLocalPath)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Local file %s not available (%v), trying URL", payload.VideoLocalPath, err)
videoBytes = nil
}
}
if videoBytes == nil {
videoBytes, err = downloadVideoFromURL(payload.VideoURL)
if err != nil {
logger.Errorf(ctx, "[VideoMultimodal] Failed to download video from URL %s: %v", payload.VideoURL, err)
return nil, fmt.Errorf("read video from URL %s failed: %w", payload.VideoURL, err)
}
logger.Infof(ctx, "[VideoMultimodal] Video downloaded from URL, len=%d", len(videoBytes))
}
return videoBytes, nil
}
// downloadVideoFromURL downloads video bytes from an HTTP(S) URL.
func downloadVideoFromURL(videoURL string) ([]byte, error) {
return secutils.DownloadBytes(videoURL)
}
// transcribeAudio extracts and transcribes audio from a video using ASR.
func (s *VideoMultimodalService) transcribeAudio(ctx context.Context, videoBytes []byte, kbID string) (string, error) {
asrMdl, err := s.resolveASR(ctx, kbID)
if err != nil {
return "", fmt.Errorf("resolve ASR: %w", err)
}
return asrMdl.Transcribe(ctx, videoBytes, "video.mp4")
}
// buildVideoChunks creates child chunks for video multimodal analysis results:
// - Frame descriptions (one chunk per frame)
// - Video summary (single chunk)
// - ASR transcription (single chunk)
func (s *VideoMultimodalService) buildVideoChunks(
payload types.VideoMultimodalPayload,
frameDescriptions []string,
videoSummary string,
asrText string,
videoInfoJSON string,
) []*types.Chunk {
var newChunks []*types.Chunk
for _, desc := range frameDescriptions {
chunk := &types.Chunk{
ID: uuid.New().String(),
TenantID: payload.TenantID,
KnowledgeID: payload.KnowledgeID,
KnowledgeBaseID: payload.KnowledgeBaseID,
Content: desc,
ChunkType: types.ChunkTypeVideoFrame,
ParentChunkID: payload.ChunkID,
IsEnabled: true,
Flags: types.ChunkFlagRecommended,
VideoInfo: videoInfoJSON,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
newChunks = append(newChunks, chunk)
}
if videoSummary != "" {
newChunks = append(newChunks, &types.Chunk{
ID: uuid.New().String(),
TenantID: payload.TenantID,
KnowledgeID: payload.KnowledgeID,
KnowledgeBaseID: payload.KnowledgeBaseID,
Content: videoSummary,
ChunkType: types.ChunkTypeVideoCaption,
ParentChunkID: payload.ChunkID,
IsEnabled: true,
Flags: types.ChunkFlagRecommended,
VideoInfo: videoInfoJSON,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
}
if asrText != "" {
newChunks = append(newChunks, &types.Chunk{
ID: uuid.New().String(),
TenantID: payload.TenantID,
KnowledgeID: payload.KnowledgeID,
KnowledgeBaseID: payload.KnowledgeBaseID,
Content: asrText,
ChunkType: types.ChunkTypeVideoASR,
ParentChunkID: payload.ChunkID,
IsEnabled: true,
Flags: types.ChunkFlagRecommended,
VideoInfo: videoInfoJSON,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
}
return newChunks
}
// finalizeVideoKnowledge updates the knowledge after multimodal processing:
// - For standalone video files: sets Description from summary and marks ParseStatus as completed.
// - For videos extracted from documents: no-op (description comes from summary generation).
func (s *VideoMultimodalService) finalizeVideoKnowledge(ctx context.Context, payload types.VideoMultimodalPayload, summary string) {
knowledge, err := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to get knowledge %s: %v", payload.KnowledgeID, err)
return
}
if knowledge == nil {
return
}
if !IsVideoType(knowledge.FileType) {
return
}
if summary != "" {
knowledge.Description = summary
}
knowledge.ParseStatus = types.ParseStatusCompleted
knowledge.UpdatedAt = time.Now()
if err := s.knowledgeRepo.UpdateKnowledge(ctx, knowledge); err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to finalize knowledge: %v", err)
} else {
logger.Infof(ctx, "[VideoMultimodal] Finalized video knowledge %s (status=completed, description=%d chars)",
payload.KnowledgeID, len(knowledge.Description))
}
}
// indexChunks indexes the newly created video chunks into the retrieval engine
// so they can participate in semantic search.
func (s *VideoMultimodalService) indexChunks(ctx context.Context, payload types.VideoMultimodalPayload, chunks []*types.Chunk) {
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
if err != nil || kb == nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to get KB for indexing: %v", err)
return
}
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to get embedding model for indexing: %v", err)
return
}
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to get tenant for indexing: %v", err)
return
}
engine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to init retrieve engine: %v", err)
return
}
indexInfoList := make([]*types.IndexInfo, 0, len(chunks))
for _, chunk := range chunks {
indexInfoList = append(indexInfoList, &types.IndexInfo{
Content: chunk.Content,
SourceID: chunk.ID,
SourceType: types.ChunkSourceType,
ChunkID: chunk.ID,
KnowledgeID: chunk.KnowledgeID,
KnowledgeBaseID: chunk.KnowledgeBaseID,
})
}
if err := engine.BatchIndex(ctx, embeddingModel, indexInfoList); err != nil {
logger.Errorf(ctx, "[VideoMultimodal] Failed to index video chunks: %v", err)
return
}
// Mark chunks as indexed.
// Must re-fetch from DB because the in-memory objects lack auto-generated fields
// (e.g. seq_id), and GORM Save would overwrite them with zero values.
for _, chunk := range chunks {
dbChunk, err := s.chunkService.GetChunkByIDOnly(ctx, chunk.ID)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to fetch chunk %s for status update: %v", chunk.ID, err)
continue
}
dbChunk.Status = int(types.ChunkStatusIndexed)
if err := s.chunkService.UpdateChunk(ctx, dbChunk); err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to update chunk %s status to indexed: %v", chunk.ID, err)
}
}
logger.Infof(ctx, "[VideoMultimodal] Indexed %d video chunks for video %s", len(chunks), payload.VideoURL)
}
// updateParentChunkVideoInfo updates the parent text chunk's VideoInfo field,
// replicating the behaviour of the old docreader flow where the parent chunk
// carried the full video metadata (URL, frame descriptions, summary, ASR).
func (s *VideoMultimodalService) updateParentChunkVideoInfo(
ctx context.Context,
payload types.VideoMultimodalPayload,
videoInfo types.VideoInfo,
) {
if payload.ChunkID == "" {
return
}
chunk, err := s.chunkService.GetChunkByIDOnly(ctx, payload.ChunkID)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to get parent chunk %s: %v", payload.ChunkID, err)
return
}
var existingInfos []types.VideoInfo
if chunk.VideoInfo != "" {
_ = json.Unmarshal([]byte(chunk.VideoInfo), &existingInfos)
}
found := false
for i, info := range existingInfos {
if info.URL == videoInfo.URL {
existingInfos[i] = videoInfo
found = true
break
}
}
if !found {
existingInfos = append(existingInfos, videoInfo)
}
videoInfoJSON, _ := json.Marshal(existingInfos)
chunk.VideoInfo = string(videoInfoJSON)
chunk.UpdatedAt = time.Now()
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to update parent chunk %s VideoInfo: %v", chunk.ID, err)
} else {
logger.Infof(ctx, "[VideoMultimodal] Updated parent chunk %s VideoInfo for video", chunk.ID)
}
}
// resolveVLM creates a vlm.VLM instance for the given knowledge base,
// supporting both new-style (ModelID) and legacy (inline BaseURL) configs.
func (s *VideoMultimodalService) resolveVLM(ctx context.Context, kbID string) (vlm.VLM, error) {
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
if err != nil {
return nil, fmt.Errorf("get knowledge base %s: %w", kbID, err)
}
if kb == nil {
return nil, fmt.Errorf("knowledge base %s not found", kbID)
}
vlmCfg := kb.VLMConfig
if !vlmCfg.IsEnabled() {
return nil, fmt.Errorf("VLM is not enabled for knowledge base %s", kbID)
}
// New-style: resolve model through ModelService
if vlmCfg.ModelID != "" {
return s.modelService.GetVLMModel(ctx, vlmCfg.ModelID)
}
// Legacy: create VLM from inline config
return vlm.NewVLMFromLegacyConfig(vlmCfg, s.ollamaService)
}
// resolveASR creates an asr.ASR instance for the given knowledge base.
func (s *VideoMultimodalService) resolveASR(ctx context.Context, kbID string) (asr.ASR, error) {
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
if err != nil {
return nil, fmt.Errorf("get knowledge base %s: %w", kbID, err)
}
if kb == nil {
return nil, fmt.Errorf("knowledge base %s not found", kbID)
}
asrCfg := kb.ASRConfig
if !asrCfg.IsASREnabled() {
return nil, fmt.Errorf("ASR is not enabled for knowledge base %s", kbID)
}
return s.modelService.GetASRModel(ctx, asrCfg.ModelID)
}
// resolveFileServiceForPayload resolves tenant/KB scoped file service for reading provider:// URLs.
func (s *VideoMultimodalService) resolveFileServiceForPayload(ctx context.Context, payload types.VideoMultimodalPayload) interfaces.FileService {
tenant, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil || tenant == nil {
logger.Warnf(ctx, "[VideoMultimodal] GetTenantByID failed: tenant=%d err=%v", payload.TenantID, err)
return nil
}
provider := types.ParseProviderScheme(payload.VideoURL)
if provider == "" {
kb, kbErr := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
if kbErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] GetKnowledgeBaseByIDOnly failed: kb=%s err=%v", payload.KnowledgeBaseID, kbErr)
} else if kb != nil {
provider = strings.ToLower(strings.TrimSpace(kb.GetStorageProvider()))
}
}
baseDir := strings.TrimSpace(os.Getenv("LOCAL_STORAGE_BASE_DIR"))
fileSvc, _, svcErr := filesvc.NewFileServiceFromStorageConfig(provider, tenant.StorageEngineConfig, baseDir)
if svcErr != nil {
logger.Warnf(ctx, "[VideoMultimodal] resolve file service failed: tenant=%d provider=%s err=%v", payload.TenantID, provider, svcErr)
return nil
}
return fileSvc
}
// enqueueQuestionGenerationIfEnabled checks if the knowledge base has question
// generation enabled and, if so, enqueues a task for the video knowledge.
func (s *VideoMultimodalService) enqueueQuestionGenerationIfEnabled(ctx context.Context, payload types.VideoMultimodalPayload) {
if s.taskEnqueuer == nil {
return
}
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
if err != nil || kb == nil {
return
}
if kb.QuestionGenerationConfig == nil || !kb.QuestionGenerationConfig.Enabled {
return
}
questionCount := kb.QuestionGenerationConfig.QuestionCount
if questionCount <= 0 {
questionCount = 3
}
if questionCount > 10 {
questionCount = 10
}
taskPayload := types.QuestionGenerationPayload{
TenantID: payload.TenantID,
KnowledgeBaseID: payload.KnowledgeBaseID,
KnowledgeID: payload.KnowledgeID,
QuestionCount: questionCount,
Language: payload.Language,
}
payloadBytes, err := json.Marshal(taskPayload)
if err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to marshal question generation payload: %v", err)
return
}
task := asynq.NewTask(types.TypeQuestionGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3))
if _, err := s.taskEnqueuer.Enqueue(task); err != nil {
logger.Warnf(ctx, "[VideoMultimodal] Failed to enqueue question generation for %s: %v", payload.KnowledgeID, err)
} else {
logger.Infof(ctx, "[VideoMultimodal] Enqueued question generation task for video knowledge %s (count=%d)",
payload.KnowledgeID, questionCount)
}
}
+3 -3
View File
@@ -7,8 +7,8 @@ import (
"strings"
"time"
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/config"
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/searchutil"
"github.com/Tencent/WeKnora/internal/types"
@@ -216,8 +216,8 @@ func (s *WebSearchService) CompressWithRAG(
for _, q := range questions {
params := types.SearchParams{
QueryText: q,
VectorThreshold: 0.5,
KeywordThreshold: 0.5,
VectorThreshold: 0.2,
KeywordThreshold: 0.2,
MatchCount: matchCount,
}
results, err := kbSvc.HybridSearch(ctx, tempKBID, params)
@@ -76,7 +76,9 @@ func isValidProviderType(provider types.WebSearchProviderType) bool {
case types.WebSearchProviderTypeBing,
types.WebSearchProviderTypeGoogle,
types.WebSearchProviderTypeDuckDuckGo,
types.WebSearchProviderTypeTavily:
types.WebSearchProviderTypeTavily,
types.WebSearchProviderTypeOllama,
types.WebSearchProviderTypeBaidu:
return true
default:
return false
@@ -101,6 +103,14 @@ func validateProviderParameters(provider types.WebSearchProviderType, params typ
if params.APIKey == "" {
return fmt.Errorf("API key is required for Tavily provider")
}
case types.WebSearchProviderTypeOllama:
if params.APIKey == "" {
return fmt.Errorf("API key is required for Ollama provider")
}
case types.WebSearchProviderTypeBaidu:
if params.APIKey == "" {
return fmt.Errorf("API key is required for Baidu provider")
}
case types.WebSearchProviderTypeDuckDuckGo:
// No API key required
}
@@ -36,6 +36,9 @@ func (s *webSearchStateService) GetWebSearchTempKBState(
ctx context.Context,
sessionID string,
) (tempKBID string, seenURLs map[string]bool, knowledgeIDs []string) {
if s.redisClient == nil {
return "", make(map[string]bool), []string{}
}
stateKey := fmt.Sprintf("tempkb:%s", sessionID)
if raw, getErr := s.redisClient.Get(ctx, stateKey).Bytes(); getErr == nil && len(raw) > 0 {
var state struct {
@@ -65,6 +68,9 @@ func (s *webSearchStateService) SaveWebSearchTempKBState(
seenURLs map[string]bool,
knowledgeIDs []string,
) {
if s.redisClient == nil {
return
}
stateKey := fmt.Sprintf("tempkb:%s", sessionID)
state := struct {
KBID string `json:"kbID"`
@@ -0,0 +1,408 @@
package service
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/models/provider"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
)
const WeKnoraCloudAPI = "https://weknora.woa.com/platform/openapi"
type weKnoraCloudService struct {
repo interfaces.ModelRepository
tenantRepo interfaces.TenantRepository
}
// NewWeKnoraCloudService 构造 WeKnoraCloudService
func NewWeKnoraCloudService(
repo interfaces.ModelRepository,
tenantRepo interfaces.TenantRepository,
) interfaces.WeKnoraCloudService {
return &weKnoraCloudService{
repo: repo,
tenantRepo: tenantRepo,
}
}
func IsWeKnoraCloudDocReaderAddr(addr string) bool {
return strings.TrimSuffix(strings.TrimSpace(addr), "/") == strings.TrimRight(provider.WeKnoraCloudBaseURL, "/")+"/api/v1/doc/reader"
}
// weKnoraCloudModelDefs 三个内置模型的静态定义
var weKnoraCloudModelDefs = []struct {
name string
modelType types.ModelType
remoteModelName string
}{
{name: "weknoracloud-chat", modelType: types.ModelTypeKnowledgeQA, remoteModelName: "chat"},
{name: "weknoracloud-embedding", modelType: types.ModelTypeEmbedding, remoteModelName: "embedding"},
{name: "weknoracloud-rerank", modelType: types.ModelTypeRerank, remoteModelName: "rerank"},
}
func (s *weKnoraCloudService) Initialize(ctx context.Context, appID, appSecret string) (*types.InitializeResult, error) {
if err := s.validateInitializeInput(appID, appSecret); err != nil {
return nil, err
}
prepared, err := s.prepareInitialize(ctx, appID, appSecret)
if err != nil {
return nil, err
}
result := &types.InitializeResult{}
actions, err := s.installBuiltinModels(ctx, prepared.tenantID, appID, prepared.encryptedSecret)
if err != nil {
return nil, s.failInitializeAndRollback(ctx, prepared.tenantID, prepared.snapshot, err)
}
result.Models = actions
if err := s.updateTenantDocReaderAddr(ctx, prepared.tenantID, appID, prepared.encryptedSecret); err != nil {
return nil, s.failInitializeAndRollback(ctx, prepared.tenantID, prepared.snapshot, err)
}
return result, nil
}
// validateInitializeInput validates that appID and appSecret are not empty.
func (s *weKnoraCloudService) validateInitializeInput(appID, appSecret string) error {
if appID == "" {
return fmt.Errorf("app_id is required")
}
if appSecret == "" {
return fmt.Errorf("app_secret is required")
}
return nil
}
// weKnoraCloudInitPrepared holds the prepared state for initialize operation.
type weKnoraCloudInitPrepared struct {
tenantID uint64
encryptedSecret string
snapshot *weKnoraCloudInitSnapshot
}
// prepareInitialize performs pre-initialization checks: ping WeKnoraCloud, encrypt secret, and snapshot current state.
func (s *weKnoraCloudService) prepareInitialize(ctx context.Context, appID, appSecret string) (*weKnoraCloudInitPrepared, error) {
// Step 1: Check WeKnoraCloud service reachability
if err := s.pingWeKnoraCloud(ctx, appID, appSecret); err != nil {
return nil, fmt.Errorf("WeKnoraCloud service reachability check failed: %w", err)
}
// Step 2: Encrypt appSecret
encryptedSecret := appSecret
if key := utils.GetAESKey(); key != nil {
if encrypted, err := utils.EncryptAESGCM(appSecret, key); err == nil {
encryptedSecret = encrypted
}
}
// Step 3: Get tenantID and take snapshot
tenantID := types.MustTenantIDFromContext(ctx)
snapshot, err := s.snapshotInitializeState(ctx, tenantID)
if err != nil {
return nil, fmt.Errorf("snapshot initialize state failed: %w", err)
}
return &weKnoraCloudInitPrepared{
tenantID: tenantID,
encryptedSecret: encryptedSecret,
snapshot: snapshot,
}, nil
}
// installBuiltinModels installs or updates the three builtin WeKnoraCloud models (chat, embedding, rerank).
// Returns a slice of ModelAction describing what was done.
func (s *weKnoraCloudService) installBuiltinModels(
ctx context.Context,
tenantID uint64,
appID, encryptedSecret string,
) ([]types.ModelAction, error) {
result := make([]types.ModelAction, 0, len(weKnoraCloudModelDefs))
for _, def := range weKnoraCloudModelDefs {
action, err := s.upsertModel(ctx, tenantID, def.name, def.modelType, def.remoteModelName, appID, encryptedSecret)
if err != nil {
return nil, fmt.Errorf("upsert model %s failed: %w", def.name, err)
}
result = append(result, types.ModelAction{
Name: def.name,
Type: string(def.modelType),
Action: action,
})
}
return result, nil
}
// weKnoraCloudInitSnapshot holds a snapshot of the state before initialization.
type weKnoraCloudInitSnapshot struct {
modelsByType map[types.ModelType][]*types.Model
tenant *types.Tenant
}
func (s *weKnoraCloudService) snapshotInitializeState(ctx context.Context, tenantID uint64) (*weKnoraCloudInitSnapshot, error) {
snapshot := &weKnoraCloudInitSnapshot{modelsByType: make(map[types.ModelType][]*types.Model, len(weKnoraCloudModelDefs))}
for _, def := range weKnoraCloudModelDefs {
models, err := s.repo.List(ctx, tenantID, def.modelType, types.ModelSourceRemote)
if err != nil {
return nil, err
}
copies := make([]*types.Model, 0, len(models))
for _, model := range models {
copies = append(copies, cloneWeKnoraCloudModel(model))
}
snapshot.modelsByType[def.modelType] = copies
}
if s.tenantRepo != nil {
tenant, err := s.tenantRepo.GetTenantByID(ctx, tenantID)
if err != nil {
return nil, err
}
snapshot.tenant = cloneWeKnoraCloudTenant(tenant)
}
return snapshot, nil
}
func (s *weKnoraCloudService) failInitializeAndRollback(ctx context.Context, tenantID uint64, snapshot *weKnoraCloudInitSnapshot, err error) error {
if rollbackErr := s.rollbackInitializeState(ctx, tenantID, snapshot); rollbackErr != nil {
return fmt.Errorf("%w;回滚失败:%v", err, rollbackErr)
}
return err
}
func (s *weKnoraCloudService) rollbackInitializeState(ctx context.Context, tenantID uint64, snapshot *weKnoraCloudInitSnapshot) error {
if snapshot == nil {
return nil
}
var rollbackErrs []string
for _, def := range weKnoraCloudModelDefs {
currentModels, err := s.repo.List(ctx, tenantID, def.modelType, types.ModelSourceRemote)
if err != nil {
rollbackErrs = append(rollbackErrs, err.Error())
continue
}
snapshotByID := map[string]*types.Model{}
for _, model := range snapshot.modelsByType[def.modelType] {
snapshotByID[model.ID] = cloneWeKnoraCloudModel(model)
}
for _, current := range currentModels {
if current == nil {
continue
}
if _, ok := snapshotByID[current.ID]; ok {
continue
}
if current.Parameters.Provider == string(provider.ProviderWeKnoraCloud) && isWeKnoraCloudBuiltinModelName(current.Name) {
if err := s.repo.Delete(ctx, tenantID, current.ID); err != nil {
rollbackErrs = append(rollbackErrs, err.Error())
}
}
}
for _, model := range snapshot.modelsByType[def.modelType] {
if err := s.repo.Update(ctx, cloneWeKnoraCloudModel(model)); err != nil {
rollbackErrs = append(rollbackErrs, err.Error())
}
}
}
if snapshot.tenant != nil && s.tenantRepo != nil {
if err := s.tenantRepo.UpdateTenant(ctx, cloneWeKnoraCloudTenant(snapshot.tenant)); err != nil {
rollbackErrs = append(rollbackErrs, err.Error())
}
}
if len(rollbackErrs) > 0 {
return fmt.Errorf("%s", strings.Join(rollbackErrs, "; "))
}
return nil
}
func isWeKnoraCloudBuiltinModelName(name string) bool {
for _, def := range weKnoraCloudModelDefs {
if def.name == name {
return true
}
}
return false
}
func cloneWeKnoraCloudModel(model *types.Model) *types.Model {
if model == nil {
return nil
}
clone := *model
if model.Parameters.ExtraConfig != nil {
clone.Parameters.ExtraConfig = make(map[string]string, len(model.Parameters.ExtraConfig))
for k, v := range model.Parameters.ExtraConfig {
clone.Parameters.ExtraConfig[k] = v
}
}
return &clone
}
func cloneWeKnoraCloudTenant(tenant *types.Tenant) *types.Tenant {
if tenant == nil {
return nil
}
clone := *tenant
if tenant.ParserEngineConfig != nil {
cfg := *tenant.ParserEngineConfig
clone.ParserEngineConfig = &cfg
}
return &clone
}
// pingWeKnoraCloud 调用 WeKnoraCloud 服务的 GET /health 接口验证可达性。
// 注意:这里仅检查服务可达,不校验 APPID / API Key 是否有效。
func (s *weKnoraCloudService) pingWeKnoraCloud(ctx context.Context, appID, appSecret string) error {
baseURL := strings.TrimRight(provider.WeKnoraCloudBaseURL, "/")
healthURL := baseURL + "/api/v1/health"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, healthURL, nil)
if err != nil {
return fmt.Errorf("创建健康检查请求失败: %w", err)
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("WeKnoraCloud 服务不可达 (%s): %w", healthURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("WeKnoraCloud 健康检查返回非 200 状态码: %d", resp.StatusCode)
}
return nil
}
// CheckStatus 检查 WeKnoraCloud 凭证是否可正常解密
func (s *weKnoraCloudService) CheckStatus(ctx context.Context) (*types.WeKnoraCloudStatusResult, error) {
tenantID := types.MustTenantIDFromContext(ctx)
tenant, err := s.tenantRepo.GetTenantByID(ctx, tenantID)
if err != nil || tenant == nil {
return &types.WeKnoraCloudStatusResult{HasModels: false, NeedsReinit: false}, nil
}
// Check if tenant has WeKnoraCloud credentials in parser config
if tenant.ParserEngineConfig == nil || tenant.ParserEngineConfig.DocreaderAppID == "" || tenant.ParserEngineConfig.DocreaderAPIKey == "" {
return &types.WeKnoraCloudStatusResult{
HasModels: true,
NeedsReinit: true,
Reason: fmt.Sprintf("WeKnoraCloud 凭证为空,请重新填写 APPID 和 API Key, 请前往:%s", WeKnoraCloudAPI),
}, nil
}
// Try to decrypt the API key
if key := utils.GetAESKey(); key != nil {
if _, err := utils.DecryptAESGCM(tenant.ParserEngineConfig.DocreaderAPIKey, key); err != nil {
return &types.WeKnoraCloudStatusResult{
HasModels: true,
NeedsReinit: true,
Reason: "WeKnoraCloud 凭证解密失败(服务重启后加密密钥已变更),请重新填写 APPID 和 API Key",
}, nil
}
}
return &types.WeKnoraCloudStatusResult{HasModels: true, NeedsReinit: false}, nil
}
// updateTenantDocReaderAddr updates tenant parser config with WeKnoraCloud credentials and DocReaderAddr
func (s *weKnoraCloudService) updateTenantDocReaderAddr(ctx context.Context, tenantID uint64, appID, encryptedSecret string) error {
if s.tenantRepo == nil {
return fmt.Errorf("tenant repository is required")
}
tenant, err := s.tenantRepo.GetTenantByID(ctx, tenantID)
if err != nil {
return err
}
if tenant.ParserEngineConfig == nil {
tenant.ParserEngineConfig = &types.ParserEngineConfig{}
}
tenant.ParserEngineConfig.DocReaderAddr = strings.TrimRight(provider.WeKnoraCloudBaseURL, "/") + "/api/v1/doc/reader"
tenant.ParserEngineConfig.DocreaderAppID = appID
tenant.ParserEngineConfig.DocreaderAPIKey = encryptedSecret
return s.tenantRepo.UpdateTenant(ctx, tenant)
}
func (s *weKnoraCloudService) upsertModel(
ctx context.Context,
tenantID uint64,
name string,
modelType types.ModelType,
remoteModelName string,
appID, encryptedSecret string,
) (string, error) {
// 列出该类型的远程模型,过滤出 weknoracloud provider
models, err := s.repo.List(ctx, tenantID, modelType, types.ModelSourceRemote)
if err != nil {
return "", err
}
var existing *types.Model
for _, m := range models {
if m.Name == name && m.Parameters.Provider == string(provider.ProviderWeKnoraCloud) {
existing = m
break
}
}
// 先清除同类型其他模型的默认标记
excludeID := ""
if existing != nil {
excludeID = existing.ID
}
if err := s.repo.ClearDefaultByType(ctx, uint(tenantID), modelType, excludeID); err != nil {
return "", err
}
if existing != nil {
// 更新凭证和默认标记
existing.Parameters.BaseURL = provider.WeKnoraCloudBaseURL
existing.Parameters.AppID = appID
existing.Parameters.AppSecret = encryptedSecret
if existing.Parameters.ExtraConfig == nil {
existing.Parameters.ExtraConfig = map[string]string{}
}
existing.Parameters.ExtraConfig["remote_model_name"] = remoteModelName
existing.IsDefault = true
if err := s.repo.Update(ctx, existing); err != nil {
return "", err
}
return "updated", nil
}
// 创建新模型
newModel := &types.Model{
ID: uuid.New().String(),
TenantID: tenantID,
Name: name,
Type: modelType,
Source: types.ModelSourceRemote,
IsBuiltin: true,
IsDefault: true,
Status: types.ModelStatusActive,
Parameters: types.ModelParameters{
Provider: string(provider.ProviderWeKnoraCloud),
BaseURL: provider.WeKnoraCloudBaseURL,
AppID: appID,
AppSecret: encryptedSecret,
ExtraConfig: map[string]string{
"remote_model_name": remoteModelName,
},
},
}
if err := s.repo.Create(ctx, newModel); err != nil {
return "", err
}
return "created", nil
}