feat: add knowldege tags
This commit is contained in:
@@ -70,22 +70,36 @@ func (r *chunkRepository) ListChunksByKnowledgeID(
|
||||
|
||||
// ListPagedChunksByKnowledgeID lists chunks for a knowledge ID with pagination
|
||||
func (r *chunkRepository) ListPagedChunksByKnowledgeID(
|
||||
ctx context.Context, tenantID uint, knowledgeID string, page *types.Pagination, chunk_type []types.ChunkType,
|
||||
ctx context.Context,
|
||||
tenantID uint,
|
||||
knowledgeID string,
|
||||
page *types.Pagination,
|
||||
chunkType []types.ChunkType,
|
||||
tagID string,
|
||||
) ([]*types.Chunk, int64, error) {
|
||||
var chunks []*types.Chunk
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&types.Chunk{}).
|
||||
Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunkType)
|
||||
if tagID != "" {
|
||||
query = query.Where("tag_id = ?", tagID)
|
||||
}
|
||||
|
||||
// First query the total count
|
||||
if err := r.db.WithContext(ctx).Model(&types.Chunk{}).
|
||||
Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunk_type).
|
||||
Count(&total).Error; err != nil {
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Then query the paginated data
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata").
|
||||
Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunk_type).
|
||||
dataQuery := r.db.WithContext(ctx).
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata")
|
||||
dataQuery = dataQuery.Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunkType)
|
||||
if tagID != "" {
|
||||
dataQuery = dataQuery.Where("tag_id = ?", tagID)
|
||||
}
|
||||
|
||||
if err := dataQuery.
|
||||
Order("chunk_index ASC").
|
||||
Offset(page.Offset()).
|
||||
Limit(page.Limit()).
|
||||
|
||||
@@ -57,20 +57,30 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
|
||||
tenantID uint,
|
||||
kbID string,
|
||||
page *types.Pagination,
|
||||
tagID string,
|
||||
) ([]*types.Knowledge, int64, error) {
|
||||
var knowledges []*types.Knowledge
|
||||
var total int64
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
|
||||
if tagID != "" {
|
||||
query = query.Where("tag_id = ?", tagID)
|
||||
}
|
||||
|
||||
// Query total count first
|
||||
if err := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
|
||||
Count(&total).Error; err != nil {
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Then query paginated data
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
|
||||
dataQuery := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
|
||||
if tagID != "" {
|
||||
dataQuery = dataQuery.Where("tag_id = ?", tagID)
|
||||
}
|
||||
|
||||
if err := dataQuery.
|
||||
Order("created_at DESC").
|
||||
Offset(page.Offset()).
|
||||
Limit(page.Limit()).
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type knowledgeTagRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewKnowledgeTagRepository creates a new tag repository.
|
||||
func NewKnowledgeTagRepository(db *gorm.DB) interfaces.KnowledgeTagRepository {
|
||||
return &knowledgeTagRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *knowledgeTagRepository) Create(ctx context.Context, tag *types.KnowledgeTag) error {
|
||||
return r.db.WithContext(ctx).Create(tag).Error
|
||||
}
|
||||
|
||||
func (r *knowledgeTagRepository) Update(ctx context.Context, tag *types.KnowledgeTag) error {
|
||||
return r.db.WithContext(ctx).Save(tag).Error
|
||||
}
|
||||
|
||||
func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.KnowledgeTag, error) {
|
||||
var tag types.KnowledgeTag
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
First(&tag).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tag, nil
|
||||
}
|
||||
|
||||
func (r *knowledgeTagRepository) ListByKB(ctx context.Context, tenantID uint, kbID string) ([]*types.KnowledgeTag, error) {
|
||||
var tags []*types.KnowledgeTag
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
|
||||
Order("sort_order ASC, created_at ASC").
|
||||
Find(&tags).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tags, nil
|
||||
}
|
||||
|
||||
func (r *knowledgeTagRepository) Delete(ctx context.Context, tenantID uint, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id = ?", tenantID, id).
|
||||
Delete(&types.KnowledgeTag{}).Error
|
||||
}
|
||||
|
||||
// CountReferences returns how many knowledges and chunks reference this tag.
|
||||
func (r *knowledgeTagRepository) CountReferences(
|
||||
ctx context.Context,
|
||||
tenantID uint,
|
||||
kbID string,
|
||||
tagID string,
|
||||
) (knowledgeCount int64, chunkCount int64, err error) {
|
||||
if err = r.db.WithContext(ctx).
|
||||
Model(&types.Knowledge{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ? AND tag_id = ?", tenantID, kbID, tagID).
|
||||
Count(&knowledgeCount).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if err = r.db.WithContext(ctx).
|
||||
Model(&types.Chunk{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ? AND tag_id = ?", tenantID, kbID, tagID).
|
||||
Count(&chunkCount).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -129,15 +129,14 @@ func (s *chunkService) ListChunksByKnowledgeID(ctx context.Context, knowledgeID
|
||||
// - *types.PageResult: Paginated result containing chunks and pagination metadata
|
||||
// - error: Any error encountered during retrieval
|
||||
func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context,
|
||||
knowledgeID string, page *types.Pagination,
|
||||
knowledgeID string, page *types.Pagination, chunkType []types.ChunkType,
|
||||
) (*types.PageResult, error) {
|
||||
logger.Info(ctx, "Start listing paged chunks by knowledge ID")
|
||||
logger.Infof(ctx, "Knowledge ID: %s, page: %d, page size: %d", knowledgeID, page.Page, page.PageSize)
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
logger.Infof(ctx, "Tenant ID: %d", tenantID)
|
||||
chunkType := []types.ChunkType{types.ChunkTypeText}
|
||||
chunks, total, err := s.chunkRepository.ListPagedChunksByKnowledgeID(ctx, tenantID, knowledgeID, page, chunkType)
|
||||
chunks, total, err := s.chunkRepository.ListPagedChunksByKnowledgeID(ctx, tenantID, knowledgeID, page, chunkType, "")
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
|
||||
@@ -553,10 +553,10 @@ func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
|
||||
|
||||
// ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base
|
||||
func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
|
||||
kbID string, page *types.Pagination,
|
||||
kbID string, page *types.Pagination, tagID string,
|
||||
) (*types.PageResult, error) {
|
||||
knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx,
|
||||
ctx.Value(types.TenantIDContextKey).(uint), kbID, page)
|
||||
ctx.Value(types.TenantIDContextKey).(uint), kbID, page, tagID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1949,6 +1949,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
PageSize: chunkPageSize,
|
||||
},
|
||||
chunkType,
|
||||
"",
|
||||
)
|
||||
chunkPage++
|
||||
if err != nil {
|
||||
@@ -2023,7 +2024,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
|
||||
// ListFAQEntries lists FAQ entries under a FAQ knowledge base.
|
||||
func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
kbID string, page *types.Pagination,
|
||||
kbID string, page *types.Pagination, tagID string,
|
||||
) (*types.PageResult, error) {
|
||||
if page == nil {
|
||||
page = &types.Pagination{}
|
||||
@@ -2042,7 +2043,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
}
|
||||
chunkType := []types.ChunkType{types.ChunkTypeFAQ}
|
||||
chunks, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(
|
||||
ctx, tenantID, faqKnowledge.ID, page, chunkType,
|
||||
ctx, tenantID, faqKnowledge.ID, page, chunkType, tagID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -2098,6 +2099,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
|
||||
faqKnowledge.ID,
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeFAQ},
|
||||
"",
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -2127,6 +2129,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
|
||||
ChunkIndex: startIndex + idx + 1,
|
||||
IsEnabled: true,
|
||||
ChunkType: types.ChunkTypeFAQ,
|
||||
TagID: entry.TagID,
|
||||
}
|
||||
if err := chunk.SetFAQMetadata(meta); err != nil {
|
||||
return err
|
||||
@@ -2187,6 +2190,7 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
|
||||
indexMode = kb.FAQConfig.IndexMode
|
||||
}
|
||||
chunk.Content = buildFAQChunkContent(meta, indexMode)
|
||||
chunk.TagID = payload.TagID
|
||||
chunk.UpdatedAt = time.Now()
|
||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||
return err
|
||||
@@ -2403,6 +2407,7 @@ func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.Knowled
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
TagID: chunk.TagID,
|
||||
StandardQuestion: meta.StandardQuestion,
|
||||
SimilarQuestions: meta.SimilarQuestions,
|
||||
NegativeQuestions: meta.NegativeQuestions,
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
werrors "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"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// knowledgeTagService implements KnowledgeTagService.
|
||||
type knowledgeTagService struct {
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
repo interfaces.KnowledgeTagRepository
|
||||
}
|
||||
|
||||
// NewKnowledgeTagService creates a new tag service.
|
||||
func NewKnowledgeTagService(
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
repo interfaces.KnowledgeTagRepository,
|
||||
) (interfaces.KnowledgeTagService, error) {
|
||||
return &knowledgeTagService{
|
||||
kbService: kbService,
|
||||
repo: repo,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListTags lists all tags for a knowledge base with usage stats.
|
||||
func (s *knowledgeTagService) ListTags(ctx context.Context, kbID string) ([]*types.KnowledgeTagWithStats, error) {
|
||||
if kbID == "" {
|
||||
return nil, werrors.NewBadRequestError("知识库ID不能为空")
|
||||
}
|
||||
// Ensure KB exists and belongs to current tenant
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantID := kb.TenantID
|
||||
|
||||
tags, err := s.repo.ListByKB(ctx, tenantID, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
results := make([]*types.KnowledgeTagWithStats, 0, len(tags))
|
||||
for _, tag := range tags {
|
||||
kCount, cCount, err := s.repo.CountReferences(ctx, tenantID, kbID, tag.ID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
"tag_id": tag.ID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
results = append(results, &types.KnowledgeTagWithStats{
|
||||
KnowledgeTag: *tag,
|
||||
KnowledgeCount: kCount,
|
||||
ChunkCount: cCount,
|
||||
})
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// CreateTag creates a new tag under a KB.
|
||||
func (s *knowledgeTagService) CreateTag(ctx context.Context, kbID string, name string, color string, sortOrder int) (*types.KnowledgeTag, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if kbID == "" || name == "" {
|
||||
return nil, werrors.NewBadRequestError("知识库ID和标签名称不能为空")
|
||||
}
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now()
|
||||
tag := &types.KnowledgeTag{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: kb.TenantID,
|
||||
KnowledgeBaseID: kb.ID,
|
||||
Name: name,
|
||||
Color: strings.TrimSpace(color),
|
||||
SortOrder: sortOrder,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := s.repo.Create(ctx, tag); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
// UpdateTag updates tag basic information.
|
||||
func (s *knowledgeTagService) UpdateTag(ctx context.Context, id string, name *string, color *string, sortOrder *int) (*types.KnowledgeTag, error) {
|
||||
if id == "" {
|
||||
return nil, werrors.NewBadRequestError("标签ID不能为空")
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
tag, err := s.repo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if name != nil {
|
||||
newName := strings.TrimSpace(*name)
|
||||
if newName == "" {
|
||||
return nil, werrors.NewBadRequestError("标签名称不能为空")
|
||||
}
|
||||
tag.Name = newName
|
||||
}
|
||||
if color != nil {
|
||||
tag.Color = strings.TrimSpace(*color)
|
||||
}
|
||||
if sortOrder != nil {
|
||||
tag.SortOrder = *sortOrder
|
||||
}
|
||||
tag.UpdatedAt = time.Now()
|
||||
if err := s.repo.Update(ctx, tag); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
// DeleteTag deletes a tag. When force=false, deletion is only allowed if no references exist.
|
||||
func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bool) error {
|
||||
if id == "" {
|
||||
return werrors.NewBadRequestError("标签ID不能为空")
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
tag, err := s.repo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kCount, cCount, err := s.repo.CountReferences(ctx, tenantID, tag.KnowledgeBaseID, tag.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !force && (kCount > 0 || cCount > 0) {
|
||||
return werrors.NewBadRequestError("标签仍有知识或FAQ条目引用,无法删除")
|
||||
}
|
||||
return s.repo.Delete(ctx, tenantID, id)
|
||||
}
|
||||
Reference in New Issue
Block a user