feat: Implement knowledge tag management and batch updates for FAQ entries
- Added API functions for listing, creating, updating, and deleting knowledge base tags. - Introduced batch update functionality for enabling/disabling FAQ entries and updating their tags. - Enhanced the KnowledgeBase.vue and FAQEntryManager.vue components to support tag management and batch operations. - Updated localization files to include new strings related to tag management and batch operations.
This commit is contained in:
@@ -93,7 +93,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
|
||||
|
||||
// Then query the paginated data
|
||||
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")
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata, tag_id")
|
||||
dataQuery = dataQuery.Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunkType)
|
||||
if tagID != "" {
|
||||
dataQuery = dataQuery.Where("tag_id = ?", tagID)
|
||||
@@ -125,6 +125,17 @@ func (r *chunkRepository) UpdateChunk(ctx context.Context, chunk *types.Chunk) e
|
||||
return r.db.WithContext(ctx).Save(chunk).Error
|
||||
}
|
||||
|
||||
// UpdateChunks updates chunks in batch
|
||||
func (r *chunkRepository) UpdateChunks(ctx context.Context, chunks []*types.Chunk) error {
|
||||
if len(chunks) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, chunk := range chunks {
|
||||
chunk.Content = common.CleanInvalidUTF8(chunk.Content)
|
||||
}
|
||||
return r.db.WithContext(ctx).Save(chunks).Error
|
||||
}
|
||||
|
||||
// DeleteChunk deletes a chunk by its ID
|
||||
func (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint, id string) error {
|
||||
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Chunk{}).Error
|
||||
|
||||
@@ -97,6 +97,14 @@ func (r *knowledgeRepository) UpdateKnowledge(ctx context.Context, knowledge *ty
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateKnowledgeBatch updates knowledge items in batch
|
||||
func (r *knowledgeRepository) UpdateKnowledgeBatch(ctx context.Context, knowledgeList []*types.Knowledge) error {
|
||||
if len(knowledgeList) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).Save(knowledgeList).Error
|
||||
}
|
||||
|
||||
// DeleteKnowledge deletes knowledge
|
||||
func (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint, id string) error {
|
||||
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Knowledge{}).Error
|
||||
|
||||
@@ -16,6 +16,7 @@ type VectorEmbedding struct {
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
|
||||
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
|
||||
IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled
|
||||
}
|
||||
|
||||
// VectorEmbeddingWithScore extends VectorEmbedding with similarity score
|
||||
@@ -33,6 +34,7 @@ func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string
|
||||
ChunkID: embedding.ChunkID,
|
||||
KnowledgeID: embedding.KnowledgeID,
|
||||
KnowledgeBaseID: embedding.KnowledgeBaseID,
|
||||
IsEnabled: true, // Default to enabled
|
||||
}
|
||||
// Add embedding data if available in additionalParams
|
||||
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
|
||||
@@ -40,6 +42,14 @@ func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string
|
||||
vector.Embedding = embeddingMap[embedding.SourceID]
|
||||
}
|
||||
}
|
||||
// Get is_enabled from additionalParams if available
|
||||
if additionalParams != nil {
|
||||
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
|
||||
if enabled, exists := chunkEnabledMap[embedding.ChunkID]; exists {
|
||||
vector.IsEnabled = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
return vector
|
||||
}
|
||||
|
||||
|
||||
@@ -330,7 +330,7 @@ func (e *elasticsearchRepository) deleteByFieldList(ctx context.Context, field s
|
||||
if resp.IsError() {
|
||||
errMsg := fmt.Sprintf("failed to delete by query: %s", resp.String())
|
||||
log.Errorf("[ElasticsearchV7] %s", errMsg)
|
||||
return fmt.Errorf(errMsg)
|
||||
return fmt.Errorf("failed to delete by query: %s", resp.String())
|
||||
}
|
||||
|
||||
// Try to extract deletion count from response
|
||||
@@ -361,6 +361,9 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)
|
||||
|
||||
// Build MUST_NOT conditions (negative filters)
|
||||
mustNot := make([]string, 0)
|
||||
// Exclude disabled chunks (is_enabled = false)
|
||||
// Note: Historical data without is_enabled field will be included (not matching must_not)
|
||||
mustNot = append(mustNot, `{"term": {"is_enabled": false}}`)
|
||||
if len(params.ExcludeKnowledgeIDs) > 0 {
|
||||
ids, _ := json.Marshal(params.ExcludeKnowledgeIDs)
|
||||
mustNot = append(mustNot, fmt.Sprintf(`{"terms": {"knowledge_id.keyword": %s}}`, ids))
|
||||
@@ -371,17 +374,17 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)
|
||||
}
|
||||
|
||||
// Combine conditions based on presence
|
||||
switch {
|
||||
case len(must) == 0 && len(mustNot) == 0:
|
||||
if len(must) == 0 && len(mustNot) == 0 {
|
||||
return "{}" // Empty query if no conditions
|
||||
case len(must) == 0:
|
||||
return fmt.Sprintf(`{"bool": {"must_not": [%s]}}`, strings.Join(mustNot, ","))
|
||||
case len(mustNot) == 0:
|
||||
return fmt.Sprintf(`{"bool": {"must": [%s]}}`, strings.Join(must, ","))
|
||||
default:
|
||||
return fmt.Sprintf(`{"bool": {"must": [%s], "must_not": [%s]}}`,
|
||||
strings.Join(must, ","), strings.Join(mustNot, ","))
|
||||
}
|
||||
if len(must) == 0 {
|
||||
return fmt.Sprintf(`{"bool": {"must_not": [%s]}}`, strings.Join(mustNot, ","))
|
||||
}
|
||||
if len(mustNot) == 0 {
|
||||
return fmt.Sprintf(`{"bool": {"must": [%s]}}`, strings.Join(must, ","))
|
||||
}
|
||||
return fmt.Sprintf(`{"bool": {"must": [%s], "must_not": [%s]}}`,
|
||||
strings.Join(must, ","), strings.Join(mustNot, ","))
|
||||
}
|
||||
|
||||
func (e *elasticsearchRepository) Retrieve(ctx context.Context,
|
||||
@@ -1028,3 +1031,99 @@ func (e *elasticsearchRepository) saveCopiedIndices(ctx context.Context, indexIn
|
||||
log.Infof("[ElasticsearchV7] Successfully saved %d indices", len(indexInfoList))
|
||||
return nil
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(chunkStatusMap) == 0 {
|
||||
log.Warnf("[ElasticsearchV7] Chunk status map is empty, skipping update")
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Infof("[ElasticsearchV7] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
|
||||
|
||||
// Group chunks by enabled status for batch updates
|
||||
enabledChunkIDs := make([]string, 0)
|
||||
disabledChunkIDs := make([]string, 0)
|
||||
|
||||
for chunkID, enabled := range chunkStatusMap {
|
||||
if enabled {
|
||||
enabledChunkIDs = append(enabledChunkIDs, chunkID)
|
||||
} else {
|
||||
disabledChunkIDs = append(disabledChunkIDs, chunkID)
|
||||
}
|
||||
}
|
||||
|
||||
// Batch update enabled chunks using update_by_query
|
||||
if len(enabledChunkIDs) > 0 {
|
||||
query := map[string]interface{}{
|
||||
"query": map[string]interface{}{
|
||||
"terms": map[string]interface{}{
|
||||
"chunk_id.keyword": enabledChunkIDs,
|
||||
},
|
||||
},
|
||||
"script": map[string]interface{}{
|
||||
"source": "ctx._source.is_enabled = true",
|
||||
"lang": "painless",
|
||||
},
|
||||
}
|
||||
queryJSON, _ := json.Marshal(query)
|
||||
res, err := esapi.UpdateByQueryRequest{
|
||||
Index: []string{e.index},
|
||||
Body: strings.NewReader(string(queryJSON)),
|
||||
}.Do(ctx, e.client)
|
||||
if err != nil {
|
||||
log.Errorf("[ElasticsearchV7] Failed to update enabled chunks: %v", err)
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.IsError() {
|
||||
var e map[string]interface{}
|
||||
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
|
||||
log.Errorf("[ElasticsearchV7] Error parsing the response body: %v", err)
|
||||
} else {
|
||||
log.Errorf("[ElasticsearchV7] Error updating enabled chunks: %v", e["error"])
|
||||
}
|
||||
return fmt.Errorf("elasticsearch update_by_query failed with status: %d", res.StatusCode)
|
||||
}
|
||||
log.Infof("[ElasticsearchV7] Updated %d chunks to enabled", len(enabledChunkIDs))
|
||||
}
|
||||
|
||||
// Batch update disabled chunks using update_by_query
|
||||
if len(disabledChunkIDs) > 0 {
|
||||
query := map[string]interface{}{
|
||||
"query": map[string]interface{}{
|
||||
"terms": map[string]interface{}{
|
||||
"chunk_id.keyword": disabledChunkIDs,
|
||||
},
|
||||
},
|
||||
"script": map[string]interface{}{
|
||||
"source": "ctx._source.is_enabled = false",
|
||||
"lang": "painless",
|
||||
},
|
||||
}
|
||||
queryJSON, _ := json.Marshal(query)
|
||||
res, err := esapi.UpdateByQueryRequest{
|
||||
Index: []string{e.index},
|
||||
Body: strings.NewReader(string(queryJSON)),
|
||||
}.Do(ctx, e.client)
|
||||
if err != nil {
|
||||
log.Errorf("[ElasticsearchV7] Failed to update disabled chunks: %v", err)
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.IsError() {
|
||||
var e map[string]interface{}
|
||||
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
|
||||
log.Errorf("[ElasticsearchV7] Error parsing the response body: %v", err)
|
||||
} else {
|
||||
log.Errorf("[ElasticsearchV7] Error updating disabled chunks: %v", e["error"])
|
||||
}
|
||||
return fmt.Errorf("elasticsearch update_by_query failed with status: %d", res.StatusCode)
|
||||
}
|
||||
log.Infof("[ElasticsearchV7] Updated %d chunks to disabled", len(disabledChunkIDs))
|
||||
}
|
||||
|
||||
log.Infof("[ElasticsearchV7] Successfully batch updated chunk enabled status")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/elastic/go-elasticsearch/v8"
|
||||
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
|
||||
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
|
||||
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/scriptlanguage"
|
||||
)
|
||||
|
||||
// elasticsearchRepository implements the RetrieveEngineRepository interface for Elasticsearch v8
|
||||
@@ -220,6 +221,11 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)
|
||||
}})
|
||||
}
|
||||
mustNot := make([]types.Query, 0)
|
||||
// Exclude disabled chunks (is_enabled = false)
|
||||
// Note: Historical data without is_enabled field will be included (not matching must_not)
|
||||
mustNot = append(mustNot, types.Query{Term: map[string]types.TermQuery{
|
||||
"is_enabled": {Value: false},
|
||||
}})
|
||||
if len(params.ExcludeKnowledgeIDs) > 0 {
|
||||
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
|
||||
TermsQuery: map[string]types.TermsQueryField{"knowledge_id.keyword": params.ExcludeKnowledgeIDs},
|
||||
@@ -539,3 +545,81 @@ func (e *elasticsearchRepository) CopyIndices(ctx context.Context,
|
||||
log.Infof("[Elasticsearch] Index copy completed, total copied: %d", totalCopied)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(chunkStatusMap) == 0 {
|
||||
log.Warnf("[Elasticsearch] Chunk status map is empty, skipping update")
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Infof("[Elasticsearch] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
|
||||
|
||||
// Group chunks by enabled status for batch updates
|
||||
enabledChunkIDs := make([]string, 0)
|
||||
disabledChunkIDs := make([]string, 0)
|
||||
|
||||
for chunkID, enabled := range chunkStatusMap {
|
||||
if enabled {
|
||||
enabledChunkIDs = append(enabledChunkIDs, chunkID)
|
||||
} else {
|
||||
disabledChunkIDs = append(disabledChunkIDs, chunkID)
|
||||
}
|
||||
}
|
||||
|
||||
// Batch update enabled chunks using update_by_query
|
||||
if len(enabledChunkIDs) > 0 {
|
||||
query := types.NewQuery()
|
||||
query.Bool = &types.BoolQuery{
|
||||
Must: []types.Query{
|
||||
{Terms: &types.TermsQuery{
|
||||
TermsQuery: map[string]types.TermsQueryField{
|
||||
"chunk_id.keyword": enabledChunkIDs,
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
source := "ctx._source.is_enabled = true"
|
||||
lang := scriptlanguage.Painless
|
||||
script := types.Script{
|
||||
Source: &source,
|
||||
Lang: &lang,
|
||||
}
|
||||
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("[Elasticsearch] Failed to update enabled chunks: %v", err)
|
||||
return err
|
||||
}
|
||||
log.Infof("[Elasticsearch] Updated %d chunks to enabled", len(enabledChunkIDs))
|
||||
}
|
||||
|
||||
// Batch update disabled chunks using update_by_query
|
||||
if len(disabledChunkIDs) > 0 {
|
||||
query := types.NewQuery()
|
||||
query.Bool = &types.BoolQuery{
|
||||
Must: []types.Query{
|
||||
{Terms: &types.TermsQuery{
|
||||
TermsQuery: map[string]types.TermsQueryField{
|
||||
"chunk_id.keyword": disabledChunkIDs,
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
source := "ctx._source.is_enabled = false"
|
||||
lang := scriptlanguage.Painless
|
||||
script := types.Script{
|
||||
Source: &source,
|
||||
Lang: &lang,
|
||||
}
|
||||
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("[Elasticsearch] Failed to update disabled chunks: %v", err)
|
||||
return err
|
||||
}
|
||||
log.Infof("[Elasticsearch] Updated %d chunks to disabled", len(disabledChunkIDs))
|
||||
}
|
||||
|
||||
log.Infof("[Elasticsearch] Successfully batch updated chunk enabled status")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -159,6 +159,11 @@ func (g *pgRepository) KeywordsRetrieve(ctx context.Context,
|
||||
SQL: "id @@@ paradedb.match(field => 'content', value => ?, distance => 1)",
|
||||
Vars: []interface{}{params.Query},
|
||||
})
|
||||
// Filter by is_enabled = true or NULL (NULL means enabled for historical data)
|
||||
conds = append(conds, clause.Expr{
|
||||
SQL: "(is_enabled IS NULL OR is_enabled = ?)",
|
||||
Vars: []interface{}{true},
|
||||
})
|
||||
conds = append(conds, clause.OrderBy{Columns: []clause.OrderByColumn{
|
||||
{Column: clause.Column{Name: "score"}, Desc: true},
|
||||
}})
|
||||
@@ -227,6 +232,11 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context,
|
||||
// <#> Inner product operator
|
||||
dimension := len(params.Embedding)
|
||||
conds = append(conds, clause.Expr{SQL: "dimension = ?", Vars: []interface{}{dimension}})
|
||||
// Filter by is_enabled = true or NULL (NULL means enabled for historical data)
|
||||
conds = append(conds, clause.Expr{
|
||||
SQL: "(is_enabled IS NULL OR is_enabled = ?)",
|
||||
Vars: []interface{}{true},
|
||||
})
|
||||
conds = append(conds, clause.Expr{
|
||||
SQL: fmt.Sprintf("embedding::halfvec(%d) <=> ?::halfvec < ?", dimension),
|
||||
Vars: []interface{}{pgvector.NewHalfVector(params.Embedding), 1 - params.Threshold},
|
||||
@@ -388,3 +398,52 @@ func (g *pgRepository) CopyIndices(ctx context.Context,
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Index copying completed, total copied: %d", totalCopied)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (g *pgRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
if len(chunkStatusMap) == 0 {
|
||||
logger.GetLogger(ctx).Warnf("[Postgres] Chunk status map is empty, skipping update")
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
|
||||
|
||||
// Group chunks by enabled status for batch updates
|
||||
enabledChunkIDs := make([]string, 0)
|
||||
disabledChunkIDs := make([]string, 0)
|
||||
|
||||
for chunkID, enabled := range chunkStatusMap {
|
||||
if enabled {
|
||||
enabledChunkIDs = append(enabledChunkIDs, chunkID)
|
||||
} else {
|
||||
disabledChunkIDs = append(disabledChunkIDs, chunkID)
|
||||
}
|
||||
}
|
||||
|
||||
// Batch update enabled chunks
|
||||
if len(enabledChunkIDs) > 0 {
|
||||
result := g.db.WithContext(ctx).Model(&pgVector{}).
|
||||
Where("chunk_id IN ?", enabledChunkIDs).
|
||||
Update("is_enabled", true)
|
||||
if result.Error != nil {
|
||||
logger.GetLogger(ctx).Errorf("[Postgres] Failed to update enabled chunks: %v", result.Error)
|
||||
return result.Error
|
||||
}
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Updated %d chunks to enabled, rows affected: %d", len(enabledChunkIDs), result.RowsAffected)
|
||||
}
|
||||
|
||||
// Batch update disabled chunks
|
||||
if len(disabledChunkIDs) > 0 {
|
||||
result := g.db.WithContext(ctx).Model(&pgVector{}).
|
||||
Where("chunk_id IN ?", disabledChunkIDs).
|
||||
Update("is_enabled", false)
|
||||
if result.Error != nil {
|
||||
logger.GetLogger(ctx).Errorf("[Postgres] Failed to update disabled chunks: %v", result.Error)
|
||||
return result.Error
|
||||
}
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Updated %d chunks to disabled, rows affected: %d", len(disabledChunkIDs), result.RowsAffected)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Successfully batch updated chunk enabled status")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ type pgVector struct {
|
||||
Content string `json:"content" gorm:"column:content;not null"`
|
||||
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
|
||||
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
|
||||
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`
|
||||
}
|
||||
|
||||
// pgVectorWithScore extends pgVector with similarity score field
|
||||
@@ -39,6 +40,7 @@ type pgVectorWithScore struct {
|
||||
Content string `json:"content" gorm:"column:content;not null"`
|
||||
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
|
||||
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
|
||||
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`
|
||||
Score float64 `json:"score" gorm:"column:score"`
|
||||
}
|
||||
|
||||
@@ -61,6 +63,7 @@ func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[string
|
||||
KnowledgeID: indexInfo.KnowledgeID,
|
||||
KnowledgeBaseID: indexInfo.KnowledgeBaseID,
|
||||
Content: common.CleanInvalidUTF8(indexInfo.Content),
|
||||
IsEnabled: true, // Default to enabled
|
||||
}
|
||||
// Add embedding data if available in additionalParams
|
||||
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
|
||||
@@ -69,6 +72,14 @@ func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[string
|
||||
pgVector.Dimension = len(pgVector.Embedding.Slice())
|
||||
}
|
||||
}
|
||||
// Get is_enabled from additionalParams if available
|
||||
if additionalParams != nil {
|
||||
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
|
||||
if enabled, exists := chunkEnabledMap[indexInfo.ChunkID]; exists {
|
||||
pgVector.IsEnabled = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
return pgVector
|
||||
}
|
||||
|
||||
|
||||
@@ -307,7 +307,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
|
||||
pageResult, err := s.knowledgeService.ListFAQEntries(ctx, kbID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
})
|
||||
}, "")
|
||||
if err == nil && pageResult != nil {
|
||||
docCount = int(pageResult.Total)
|
||||
if entries, ok := pageResult.Data.([]*types.FAQEntry); ok {
|
||||
@@ -336,7 +336,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
|
||||
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
})
|
||||
}, "")
|
||||
|
||||
if err == nil && pageResult != nil {
|
||||
docCount = int(pageResult.Total)
|
||||
|
||||
@@ -61,6 +61,7 @@ type knowledgeService struct {
|
||||
docReaderClient *client.Client
|
||||
chunkService interfaces.ChunkService
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
fileSvc interfaces.FileService
|
||||
modelService interfaces.ModelService
|
||||
task *asynq.Client
|
||||
@@ -81,6 +82,7 @@ func NewKnowledgeService(
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
chunkService interfaces.ChunkService,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
tagRepo interfaces.KnowledgeTagRepository,
|
||||
fileSvc interfaces.FileService,
|
||||
modelService interfaces.ModelService,
|
||||
task *asynq.Client,
|
||||
@@ -95,6 +97,7 @@ func NewKnowledgeService(
|
||||
docReaderClient: docReaderClient,
|
||||
chunkService: chunkService,
|
||||
chunkRepo: chunkRepo,
|
||||
tagRepo: tagRepo,
|
||||
fileSvc: fileSvc,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
@@ -2120,6 +2123,10 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
isEnabled := true
|
||||
if entry.IsEnabled != nil {
|
||||
isEnabled = *entry.IsEnabled
|
||||
}
|
||||
chunk := &types.Chunk{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
@@ -2127,7 +2134,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
|
||||
KnowledgeBaseID: kb.ID,
|
||||
Content: buildFAQChunkContent(meta, indexMode),
|
||||
ChunkIndex: startIndex + idx + 1,
|
||||
IsEnabled: true,
|
||||
IsEnabled: isEnabled,
|
||||
ChunkType: types.ChunkTypeFAQ,
|
||||
TagID: entry.TagID,
|
||||
}
|
||||
@@ -2191,10 +2198,30 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
|
||||
}
|
||||
chunk.Content = buildFAQChunkContent(meta, indexMode)
|
||||
chunk.TagID = payload.TagID
|
||||
isEnabledUpdated := false
|
||||
if payload.IsEnabled != nil {
|
||||
oldEnabled := chunk.IsEnabled
|
||||
chunk.IsEnabled = *payload.IsEnabled
|
||||
isEnabledUpdated = (oldEnabled != chunk.IsEnabled)
|
||||
}
|
||||
chunk.UpdatedAt = time.Now()
|
||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Sync is_enabled status to retriever engines if it was updated
|
||||
if isEnabledUpdated {
|
||||
chunkStatusMap := map[string]bool{chunk.ID: chunk.IsEnabled}
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
faqKnowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, chunk.KnowledgeID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -2202,6 +2229,312 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
|
||||
return s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, false)
|
||||
}
|
||||
|
||||
// UpdateFAQEntryStatus updates enable status for a FAQ entry.
|
||||
func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context,
|
||||
kbID string, entryID string, isEnabled bool,
|
||||
) error {
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
return werrors.NewBadRequestError("仅支持更新 FAQ 条目")
|
||||
}
|
||||
if chunk.IsEnabled == isEnabled {
|
||||
return nil
|
||||
}
|
||||
chunk.IsEnabled = isEnabled
|
||||
chunk.UpdatedAt = time.Now()
|
||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Sync update to retriever engines
|
||||
chunkStatusMap := map[string]bool{chunk.ID: isEnabled}
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateFAQEntryStatusBatch updates enable status for FAQ entries in batch.
|
||||
func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
|
||||
kbID string, updates map[string]bool,
|
||||
) error {
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
|
||||
// Get all chunks in batch
|
||||
entryIDs := make([]string, 0, len(updates))
|
||||
for entryID := range updates {
|
||||
entryIDs = append(entryIDs, entryID)
|
||||
}
|
||||
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, entryIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Group chunks by enabled status for batch update
|
||||
chunkStatusMap := make(map[string]bool)
|
||||
for _, chunk := range chunks {
|
||||
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
continue
|
||||
}
|
||||
isEnabled, exists := updates[chunk.ID]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
if chunk.IsEnabled == isEnabled {
|
||||
continue
|
||||
}
|
||||
chunk.IsEnabled = isEnabled
|
||||
chunk.UpdatedAt = time.Now()
|
||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
chunkStatusMap[chunk.ID] = isEnabled
|
||||
}
|
||||
|
||||
// Sync update to retriever engines
|
||||
if len(chunkStatusMap) > 0 {
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateKnowledgeTag updates the tag assigned to a knowledge document.
|
||||
func (s *knowledgeService) UpdateKnowledgeTag(ctx context.Context, knowledgeID string, tagID *string) error {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var resolvedTagID string
|
||||
if tagID != nil && *tagID != "" {
|
||||
tag, err := s.tagRepo.GetByID(ctx, tenantID, *tagID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.KnowledgeBaseID != knowledge.KnowledgeBaseID {
|
||||
return werrors.NewBadRequestError("标签不属于当前知识库")
|
||||
}
|
||||
resolvedTagID = tag.ID
|
||||
}
|
||||
|
||||
knowledge.TagID = resolvedTagID
|
||||
return s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
}
|
||||
|
||||
// UpdateKnowledgeTagBatch updates tags for document knowledge items in batch.
|
||||
func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error {
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
|
||||
// Get all knowledge items in batch
|
||||
knowledgeIDs := make([]string, 0, len(updates))
|
||||
for knowledgeID := range updates {
|
||||
knowledgeIDs = append(knowledgeIDs, knowledgeID)
|
||||
}
|
||||
knowledgeList, err := s.repo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Build tag ID map for validation
|
||||
tagIDSet := make(map[string]bool)
|
||||
for _, tagID := range updates {
|
||||
if tagID != nil && *tagID != "" {
|
||||
tagIDSet[*tagID] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Validate all tags in batch
|
||||
tagMap := make(map[string]*types.KnowledgeTag)
|
||||
if len(tagIDSet) > 0 {
|
||||
tagIDs := make([]string, 0, len(tagIDSet))
|
||||
for tagID := range tagIDSet {
|
||||
tagIDs = append(tagIDs, tagID)
|
||||
}
|
||||
for _, tagID := range tagIDs {
|
||||
tag, err := s.tagRepo.GetByID(ctx, tenantID, tagID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tagMap[tagID] = tag
|
||||
}
|
||||
}
|
||||
|
||||
// Update knowledge items
|
||||
knowledgeToUpdate := make([]*types.Knowledge, 0)
|
||||
for _, knowledge := range knowledgeList {
|
||||
tagID, exists := updates[knowledge.ID]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
|
||||
var resolvedTagID string
|
||||
if tagID != nil && *tagID != "" {
|
||||
tag, ok := tagMap[*tagID]
|
||||
if !ok {
|
||||
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不存在", *tagID))
|
||||
}
|
||||
if tag.KnowledgeBaseID != knowledge.KnowledgeBaseID {
|
||||
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不属于知识库 %s", *tagID, knowledge.KnowledgeBaseID))
|
||||
}
|
||||
resolvedTagID = tag.ID
|
||||
}
|
||||
|
||||
knowledge.TagID = resolvedTagID
|
||||
knowledgeToUpdate = append(knowledgeToUpdate, knowledge)
|
||||
}
|
||||
|
||||
if len(knowledgeToUpdate) > 0 {
|
||||
return s.repo.UpdateKnowledgeBatch(ctx, knowledgeToUpdate)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateFAQEntryTag updates the tag assigned to an FAQ entry.
|
||||
func (s *knowledgeService) UpdateFAQEntryTag(ctx context.Context, kbID string, entryID string, tagID *string) error {
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
return werrors.NewBadRequestError("仅支持更新 FAQ 条目标签")
|
||||
}
|
||||
|
||||
var resolvedTagID string
|
||||
if tagID != nil && *tagID != "" {
|
||||
tag, err := s.tagRepo.GetByID(ctx, tenantID, *tagID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.KnowledgeBaseID != kb.ID {
|
||||
return werrors.NewBadRequestError("标签不属于当前知识库")
|
||||
}
|
||||
resolvedTagID = tag.ID
|
||||
}
|
||||
|
||||
chunk.TagID = resolvedTagID
|
||||
chunk.UpdatedAt = time.Now()
|
||||
return s.chunkRepo.UpdateChunk(ctx, chunk)
|
||||
}
|
||||
|
||||
// UpdateFAQEntryTagBatch updates tags for FAQ entries in batch.
|
||||
func (s *knowledgeService) UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[string]*string) error {
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
|
||||
// Get all chunks in batch
|
||||
entryIDs := make([]string, 0, len(updates))
|
||||
for entryID := range updates {
|
||||
entryIDs = append(entryIDs, entryID)
|
||||
}
|
||||
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, entryIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Build tag ID map for validation
|
||||
tagIDSet := make(map[string]bool)
|
||||
for _, tagID := range updates {
|
||||
if tagID != nil && *tagID != "" {
|
||||
tagIDSet[*tagID] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Validate all tags in batch
|
||||
tagMap := make(map[string]*types.KnowledgeTag)
|
||||
if len(tagIDSet) > 0 {
|
||||
tagIDs := make([]string, 0, len(tagIDSet))
|
||||
for tagID := range tagIDSet {
|
||||
tagIDs = append(tagIDs, tagID)
|
||||
}
|
||||
for _, tagID := range tagIDs {
|
||||
tag, err := s.tagRepo.GetByID(ctx, tenantID, tagID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.KnowledgeBaseID != kb.ID {
|
||||
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不属于当前知识库", tagID))
|
||||
}
|
||||
tagMap[tagID] = tag
|
||||
}
|
||||
}
|
||||
|
||||
// Update chunks
|
||||
chunksToUpdate := make([]*types.Chunk, 0)
|
||||
for _, chunk := range chunks {
|
||||
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
continue
|
||||
}
|
||||
tagID, exists := updates[chunk.ID]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
|
||||
var resolvedTagID string
|
||||
if tagID != nil && *tagID != "" {
|
||||
tag, ok := tagMap[*tagID]
|
||||
if !ok {
|
||||
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不存在", *tagID))
|
||||
}
|
||||
resolvedTagID = tag.ID
|
||||
}
|
||||
|
||||
chunk.TagID = resolvedTagID
|
||||
chunk.UpdatedAt = time.Now()
|
||||
chunksToUpdate = append(chunksToUpdate, chunk)
|
||||
}
|
||||
|
||||
if len(chunksToUpdate) > 0 {
|
||||
return s.chunkRepo.UpdateChunks(ctx, chunksToUpdate)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SearchFAQEntries searches FAQ entries using hybrid search.
|
||||
func (s *knowledgeService) SearchFAQEntries(ctx context.Context,
|
||||
kbID string, req *types.FAQSearchRequest,
|
||||
@@ -2268,6 +2601,9 @@ func (s *knowledgeService) SearchFAQEntries(ctx context.Context,
|
||||
if chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
continue
|
||||
}
|
||||
if !chunk.IsEnabled {
|
||||
continue
|
||||
}
|
||||
|
||||
entry, err := s.chunkToFAQEntry(chunk, kb)
|
||||
if err != nil {
|
||||
@@ -2408,6 +2744,7 @@ func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.Knowled
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
TagID: chunk.TagID,
|
||||
IsEnabled: chunk.IsEnabled,
|
||||
StandardQuestion: meta.StandardQuestion,
|
||||
SimilarQuestions: meta.SimilarQuestions,
|
||||
NegativeQuestions: meta.NegativeQuestions,
|
||||
|
||||
@@ -93,6 +93,16 @@ func (c *CompositeRetrieveEngine) SupportRetriever(r types.RetrieverType) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (c *CompositeRetrieveEngine) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
return c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
|
||||
if err := engineInfo.retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// concurrentRetrieve is a helper function for concurrent processing of retrieval parameters
|
||||
// and collecting results
|
||||
func concurrentRetrieve(
|
||||
|
||||
@@ -161,3 +161,8 @@ func (v *KeywordsVectorHybridRetrieveEngineService) CopyIndices(
|
||||
ctx, sourceKnowledgeBaseID, sourceToTargetKBIDMap, sourceToTargetChunkIDMap, targetKnowledgeBaseID, dimension,
|
||||
)
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (v *KeywordsVectorHybridRetrieveEngineService) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
return v.indexRepository.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user