refactor: Update function signatures across multiple files to improve readability by adding context parameters and enhancing code structure
This commit is contained in:
@@ -112,7 +112,11 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
|
||||
return chunks, total, nil
|
||||
}
|
||||
|
||||
func (r *chunkRepository) ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error) {
|
||||
func (r *chunkRepository) ListChunkByParentID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
parentID string,
|
||||
) ([]*types.Chunk, error) {
|
||||
var chunks []*types.Chunk
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND parent_chunk_id = ?", tenantID, parentID).
|
||||
@@ -166,7 +170,11 @@ func (r *chunkRepository) DeleteByKnowledgeList(ctx context.Context, tenantID ui
|
||||
}
|
||||
|
||||
// CountChunksByKnowledgeBaseID counts the number of chunks in a knowledge base
|
||||
func (r *chunkRepository) CountChunksByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error) {
|
||||
func (r *chunkRepository) CountChunksByKnowledgeBaseID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.Chunk{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
|
||||
@@ -175,7 +183,11 @@ func (r *chunkRepository) CountChunksByKnowledgeBaseID(ctx context.Context, tena
|
||||
}
|
||||
|
||||
// DeleteUnindexedChunks by knowledge id and chunk index range
|
||||
func (r *chunkRepository) DeleteUnindexedChunks(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) {
|
||||
func (r *chunkRepository) DeleteUnindexedChunks(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeID string,
|
||||
) ([]*types.Chunk, error) {
|
||||
var chunks []*types.Chunk
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_id = ? AND status = ?", tenantID, knowledgeID, types.ChunkStatusStored).
|
||||
@@ -194,7 +206,11 @@ func (r *chunkRepository) DeleteUnindexedChunks(ctx context.Context, tenantID ui
|
||||
|
||||
// ListAllFAQChunksByKnowledgeID lists all FAQ chunks for a knowledge ID (only essential fields for efficiency)
|
||||
// Uses batch query to handle large datasets
|
||||
func (r *chunkRepository) ListAllFAQChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) {
|
||||
func (r *chunkRepository) ListAllFAQChunksByKnowledgeID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeID string,
|
||||
) ([]*types.Chunk, error) {
|
||||
const batchSize = 1000 // 每批查询1000条
|
||||
var allChunks []*types.Chunk
|
||||
offset := 0
|
||||
|
||||
@@ -28,7 +28,11 @@ func (r *knowledgeRepository) CreateKnowledge(ctx context.Context, knowledge *ty
|
||||
}
|
||||
|
||||
// GetKnowledgeByID gets knowledge
|
||||
func (r *knowledgeRepository) GetKnowledgeByID(ctx context.Context, tenantID uint64, id string) (*types.Knowledge, error) {
|
||||
func (r *knowledgeRepository) GetKnowledgeByID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
id string,
|
||||
) (*types.Knowledge, error) {
|
||||
var knowledge types.Knowledge
|
||||
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).First(&knowledge).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -217,13 +221,22 @@ func (r *knowledgeRepository) AminusB(
|
||||
return knowledgeIDs, err
|
||||
}
|
||||
|
||||
func (r *knowledgeRepository) UpdateKnowledgeColumn(ctx context.Context, id string, column string, value interface{}) error {
|
||||
func (r *knowledgeRepository) UpdateKnowledgeColumn(
|
||||
ctx context.Context,
|
||||
id string,
|
||||
column string,
|
||||
value interface{},
|
||||
) error {
|
||||
err := r.db.WithContext(ctx).Model(&types.Knowledge{}).Where("id = ?", id).Update(column, value).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base
|
||||
func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error) {
|
||||
func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
|
||||
|
||||
@@ -69,7 +69,11 @@ func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint64)
|
||||
}
|
||||
|
||||
// ListByIDs retrieves MCP services by multiple IDs for a tenant
|
||||
func (r *mcpServiceRepository) ListByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.MCPService, error) {
|
||||
func (r *mcpServiceRepository) ListByIDs(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
ids []string,
|
||||
) ([]*types.MCPService, error) {
|
||||
if len(ids) == 0 {
|
||||
return []*types.MCPService{}, nil
|
||||
}
|
||||
|
||||
@@ -79,7 +79,12 @@ func (r *modelRepository) Delete(ctx context.Context, tenantID uint64, id string
|
||||
|
||||
// ClearDefaultByType clears the default flag for all models of a specific type
|
||||
// This is a batch operation that updates all matching records in one query
|
||||
func (r *modelRepository) ClearDefaultByType(ctx context.Context, tenantID uint, modelType types.ModelType, excludeID string) error {
|
||||
func (r *modelRepository) ClearDefaultByType(
|
||||
ctx context.Context,
|
||||
tenantID uint,
|
||||
modelType types.ModelType,
|
||||
excludeID string,
|
||||
) error {
|
||||
query := r.db.WithContext(ctx).Model(&types.Model{}).Where(
|
||||
"tenant_id = ? AND type = ? AND is_default = ?", tenantID, modelType, true,
|
||||
)
|
||||
|
||||
@@ -9,14 +9,14 @@ import (
|
||||
|
||||
// VectorEmbedding defines the Elasticsearch document structure for vector embeddings
|
||||
type VectorEmbedding struct {
|
||||
Content string `json:"content" gorm:"column:content;not null"` // Text content of the chunk
|
||||
SourceID string `json:"source_id" gorm:"column:source_id;not null"` // ID of the source document
|
||||
SourceType int `json:"source_type" gorm:"column:source_type;not null"` // Type of the source document
|
||||
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"` // Unique ID of the text chunk
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
|
||||
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
|
||||
IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled
|
||||
Content string `json:"content" gorm:"column:content;not null"` // Text content of the chunk
|
||||
SourceID string `json:"source_id" gorm:"column:source_id;not null"` // ID of the source document
|
||||
SourceType int `json:"source_type" gorm:"column:source_type;not null"` // Type of the source document
|
||||
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"` // Unique ID of the text chunk
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
|
||||
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
|
||||
IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled
|
||||
}
|
||||
|
||||
// VectorEmbeddingWithScore extends VectorEmbedding with similarity score
|
||||
|
||||
@@ -1094,7 +1094,10 @@ func (e *elasticsearchRepository) saveCopiedIndices(ctx context.Context, indexIn
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
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")
|
||||
|
||||
@@ -547,7 +547,10 @@ func (e *elasticsearchRepository) CopyIndices(ctx context.Context,
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
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")
|
||||
|
||||
@@ -152,7 +152,11 @@ func (n *Neo4jRepository) DelGraph(ctx context.Context, namespaces []types.NameS
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *Neo4jRepository) SearchNode(ctx context.Context, namespace types.NameSpace, nodes []string) (*types.GraphData, error) {
|
||||
func (n *Neo4jRepository) SearchNode(
|
||||
ctx context.Context,
|
||||
namespace types.NameSpace,
|
||||
nodes []string,
|
||||
) (*types.GraphData, error) {
|
||||
if n.driver == nil {
|
||||
logger.Warnf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
|
||||
return nil, nil
|
||||
|
||||
@@ -481,7 +481,8 @@ func (g *pgRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkS
|
||||
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)
|
||||
logger.GetLogger(ctx).
|
||||
Infof("[Postgres] Updated %d chunks to enabled, rows affected: %d", len(enabledChunkIDs), result.RowsAffected)
|
||||
}
|
||||
|
||||
// Batch update disabled chunks
|
||||
@@ -493,7 +494,8 @@ func (g *pgRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkS
|
||||
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] Updated %d chunks to disabled, rows affected: %d", len(disabledChunkIDs), result.RowsAffected)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Successfully batch updated chunk enabled status")
|
||||
|
||||
@@ -13,35 +13,35 @@ import (
|
||||
|
||||
// pgVector defines the database model for vector embeddings storage
|
||||
type pgVector struct {
|
||||
ID uint `json:"id" gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
|
||||
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
|
||||
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
|
||||
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
|
||||
ID uint `json:"id" gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
|
||||
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
|
||||
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
|
||||
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"`
|
||||
Content string `json:"content" gorm:"column:content;not null"`
|
||||
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
|
||||
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
|
||||
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`
|
||||
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
|
||||
type pgVectorWithScore struct {
|
||||
ID uint `json:"id" gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
|
||||
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
|
||||
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
|
||||
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
|
||||
ID uint `json:"id" gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
|
||||
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
|
||||
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
|
||||
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"`
|
||||
Content string `json:"content" gorm:"column:content;not null"`
|
||||
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
|
||||
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
|
||||
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`
|
||||
Score float64 `json:"score" gorm:"column:score"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// TableName specifies the database table name for pgVectorWithScore
|
||||
|
||||
@@ -35,7 +35,11 @@ func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint64, i
|
||||
return &tag, nil
|
||||
}
|
||||
|
||||
func (r *knowledgeTagRepository) ListByKB(ctx context.Context, tenantID uint64, kbID string) ([]*types.KnowledgeTag, error) {
|
||||
func (r *knowledgeTagRepository) ListByKB(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
) ([]*types.KnowledgeTag, error) {
|
||||
var tags []*types.KnowledgeTag
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
|
||||
|
||||
@@ -184,7 +184,13 @@ func (s *agentService) registerTools(
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
logger.Infof(ctx, "Registering tools: %v, tenant ID: %d, webSearchEnabled: %v", allowedTools, tenantID, config.WebSearchEnabled)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Registering tools: %v, tenant ID: %d, webSearchEnabled: %v",
|
||||
allowedTools,
|
||||
tenantID,
|
||||
config.WebSearchEnabled,
|
||||
)
|
||||
|
||||
// Register each allowed tool
|
||||
for _, toolName := range allowedTools {
|
||||
@@ -224,7 +230,12 @@ func (s *agentService) registerTools(
|
||||
sessionID,
|
||||
config.WebSearchMaxResults,
|
||||
))
|
||||
logger.Infof(ctx, "Registered web_search tool for session: %s, maxResults: %d", sessionID, config.WebSearchMaxResults)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Registered web_search tool for session: %s, maxResults: %d",
|
||||
sessionID,
|
||||
config.WebSearchMaxResults,
|
||||
)
|
||||
|
||||
case "web_fetch":
|
||||
registry.RegisterTool(tools.NewWebFetchTool(chatModel))
|
||||
|
||||
@@ -212,7 +212,11 @@ func mergeImageInfo(ctx context.Context, target *types.SearchResult, source *typ
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PluginMerge) populateFAQAnswers(ctx context.Context, chatManage *types.ChatManage, results []*types.SearchResult) []*types.SearchResult {
|
||||
func (p *PluginMerge) populateFAQAnswers(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
results []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
if len(results) == 0 || p.chunkRepo == nil {
|
||||
return results
|
||||
}
|
||||
@@ -332,7 +336,11 @@ func buildFAQAnswerContent(meta *types.FAQChunkMetadata) string {
|
||||
return strings.TrimSpace(builder.String())
|
||||
}
|
||||
|
||||
func (p *PluginMerge) expandShortContextWithNeighbors(ctx context.Context, chatManage *types.ChatManage, results []*types.SearchResult) []*types.SearchResult {
|
||||
func (p *PluginMerge) expandShortContextWithNeighbors(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
results []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
const (
|
||||
minLen = 350
|
||||
maxLen = 850
|
||||
@@ -495,7 +503,8 @@ func (p *PluginMerge) expandShortContextWithNeighbors(ctx context.Context, chatM
|
||||
expanded := false
|
||||
if prevCursor != "" {
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor)
|
||||
if prevChunk := chunkMap[prevCursor]; prevChunk != nil && prevChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
if prevChunk := chunkMap[prevCursor]; prevChunk != nil &&
|
||||
prevChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
prevContent = concatNoOverlap(prevChunk.Content, prevContent)
|
||||
prevIDs = append([]string{prevChunk.ID}, prevIDs...)
|
||||
prevCursor = prevChunk.PreChunkID
|
||||
@@ -512,7 +521,8 @@ func (p *PluginMerge) expandShortContextWithNeighbors(ctx context.Context, chatM
|
||||
|
||||
if nextCursor != "" {
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, nextCursor)
|
||||
if nextChunk := chunkMap[nextCursor]; nextChunk != nil && nextChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
if nextChunk := chunkMap[nextCursor]; nextChunk != nil &&
|
||||
nextChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
nextContent = concatNoOverlap(nextContent, nextChunk.Content)
|
||||
nextIDs = append(nextIDs, nextChunk.ID)
|
||||
nextCursor = nextChunk.NextChunkID
|
||||
@@ -625,7 +635,12 @@ func containsID(ids []string, target string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *PluginMerge) fetchChunksIfMissing(ctx context.Context, tenantID uint64, chunkMap map[string]*types.Chunk, chunkIDs ...string) {
|
||||
func (p *PluginMerge) fetchChunksIfMissing(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
chunkMap map[string]*types.Chunk,
|
||||
chunkIDs ...string,
|
||||
) {
|
||||
missing := make([]string, 0, len(chunkIDs))
|
||||
for _, id := range chunkIDs {
|
||||
if id == "" {
|
||||
|
||||
@@ -91,7 +91,12 @@ func (p *PluginPreprocess) ActivationEvents() []types.EventType {
|
||||
}
|
||||
|
||||
// OnEvent Process events
|
||||
func (p *PluginPreprocess) OnEvent(ctx context.Context, eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError) *PluginError {
|
||||
func (p *PluginPreprocess) OnEvent(
|
||||
ctx context.Context,
|
||||
eventType types.EventType,
|
||||
chatManage *types.ChatManage,
|
||||
next func() *PluginError,
|
||||
) *PluginError {
|
||||
rawQuery := strings.TrimSpace(chatManage.RewriteQuery)
|
||||
if rawQuery == "" {
|
||||
return next()
|
||||
@@ -270,15 +275,30 @@ type intentResp struct {
|
||||
|
||||
func (p *PluginPreprocess) detectIntentLLM(ctx context.Context, chatManage *types.ChatManage, text string) string {
|
||||
if p.modelService == nil || chatManage.ChatModelID == "" {
|
||||
pipelineWarn(ctx, "IntentDetect", "skip", map[string]interface{}{"reason": "no_model", "session_id": chatManage.SessionID})
|
||||
pipelineWarn(
|
||||
ctx,
|
||||
"IntentDetect",
|
||||
"skip",
|
||||
map[string]interface{}{"reason": "no_model", "session_id": chatManage.SessionID},
|
||||
)
|
||||
return "general"
|
||||
}
|
||||
chatModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "IntentDetect", "get_model_failed", map[string]interface{}{"error": err.Error(), "model_id": chatManage.ChatModelID})
|
||||
pipelineWarn(
|
||||
ctx,
|
||||
"IntentDetect",
|
||||
"get_model_failed",
|
||||
map[string]interface{}{"error": err.Error(), "model_id": chatManage.ChatModelID},
|
||||
)
|
||||
return "general"
|
||||
}
|
||||
pipelineInfo(ctx, "IntentDetect", "start", map[string]interface{}{"session_id": chatManage.SessionID, "model_id": chatManage.ChatModelID})
|
||||
pipelineInfo(
|
||||
ctx,
|
||||
"IntentDetect",
|
||||
"start",
|
||||
map[string]interface{}{"session_id": chatManage.SessionID, "model_id": chatManage.ChatModelID},
|
||||
)
|
||||
sys := "You are a query intent classifier. Classify the user's query into one of: definition, howto, compare, qa, general. Respond ONLY with a JSON object {\"intent\": \"...\", \"confidence\": 0.0 } inside a markdown fenced block."
|
||||
usr := text
|
||||
think := false
|
||||
@@ -296,7 +316,12 @@ func (p *PluginPreprocess) detectIntentLLM(ctx context.Context, chatManage *type
|
||||
pipelineWarn(ctx, "IntentDetect", "parse_failed", map[string]interface{}{"body": body, "error": err.Error()})
|
||||
return "general"
|
||||
}
|
||||
pipelineInfo(ctx, "IntentDetect", "result", map[string]interface{}{"intent": ir.Intent, "confidence": ir.Confidence})
|
||||
pipelineInfo(
|
||||
ctx,
|
||||
"IntentDetect",
|
||||
"result",
|
||||
map[string]interface{}{"intent": ir.Intent, "confidence": ir.Confidence},
|
||||
)
|
||||
switch strings.ToLower(strings.TrimSpace(ir.Intent)) {
|
||||
case "definition", "howto", "compare", "qa", "general":
|
||||
return strings.ToLower(ir.Intent)
|
||||
|
||||
@@ -222,7 +222,13 @@ func compositeScore(sr *types.SearchResult, modelScore, baseScore float64, chatM
|
||||
return composite
|
||||
}
|
||||
|
||||
func applyMMR(ctx context.Context, results []*types.SearchResult, chatManage *types.ChatManage, k int, lambda float64) []*types.SearchResult {
|
||||
func applyMMR(
|
||||
ctx context.Context,
|
||||
results []*types.SearchResult,
|
||||
chatManage *types.ChatManage,
|
||||
k int,
|
||||
lambda float64,
|
||||
) []*types.SearchResult {
|
||||
if k <= 0 || len(results) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -299,7 +299,11 @@ func buildContentSignature(content string) string {
|
||||
}
|
||||
|
||||
// searchKnowledgeBases performs KB searches for rewrite and processed queries across KB IDs
|
||||
func (p *PluginSearch) searchKnowledgeBases(ctx context.Context, knowledgeBaseIDs []string, chatManage *types.ChatManage) []*types.SearchResult {
|
||||
func (p *PluginSearch) searchKnowledgeBases(
|
||||
ctx context.Context,
|
||||
knowledgeBaseIDs []string,
|
||||
chatManage *types.ChatManage,
|
||||
) []*types.SearchResult {
|
||||
// Build base params for rewrite query
|
||||
baseParams := types.SearchParams{
|
||||
QueryText: strings.TrimSpace(chatManage.RewriteQuery),
|
||||
|
||||
@@ -77,7 +77,13 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context,
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KB %s entity search result count: %d nodes, %d relations", knowledgeBaseID, len(graph.Node), len(graph.Relation))
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"KB %s entity search result count: %d nodes, %d relations",
|
||||
knowledgeBaseID,
|
||||
len(graph.Node),
|
||||
len(graph.Relation),
|
||||
)
|
||||
|
||||
mu.Lock()
|
||||
allNodes = append(allNodes, graph.Node...)
|
||||
@@ -109,7 +115,11 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context,
|
||||
for _, chunk := range chunks {
|
||||
knowledgeIDs = append(knowledgeIDs, chunk.KnowledgeID)
|
||||
}
|
||||
knowledges, err := p.knowledgeRepo.GetKnowledgeBatch(ctx, ctx.Value(types.TenantIDContextKey).(uint64), knowledgeIDs)
|
||||
knowledges, err := p.knowledgeRepo.GetKnowledgeBatch(
|
||||
ctx,
|
||||
ctx.Value(types.TenantIDContextKey).(uint64),
|
||||
knowledgeIDs,
|
||||
)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to list knowledge, session_id: %s, error: %v", chatManage.SessionID, err)
|
||||
return next()
|
||||
@@ -129,7 +139,12 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context,
|
||||
logger.Infof(ctx, "No new search result, session_id: %s", chatManage.SessionID)
|
||||
return ErrSearchNothing
|
||||
}
|
||||
logger.Infof(ctx, "search entity result count: %d, session_id: %s", len(chatManage.SearchResult), chatManage.SessionID)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"search entity result count: %d, session_id: %s",
|
||||
len(chatManage.SearchResult),
|
||||
chatManage.SessionID,
|
||||
)
|
||||
return next()
|
||||
}
|
||||
|
||||
|
||||
@@ -138,7 +138,14 @@ func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context,
|
||||
knowledgeID string, page *types.Pagination, chunkType []types.ChunkType,
|
||||
) (*types.PageResult, error) {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
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,
|
||||
@@ -298,7 +305,11 @@ func (s *chunkService) DeleteByKnowledgeList(ctx context.Context, ids []string)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *chunkService) ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error) {
|
||||
func (s *chunkService) ListChunkByParentID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
parentID string,
|
||||
) ([]*types.Chunk, error) {
|
||||
logger.Info(ctx, "Start listing chunk by parent ID")
|
||||
logger.Infof(ctx, "Parent ID: %s", parentID)
|
||||
|
||||
|
||||
@@ -16,7 +16,13 @@ import (
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
func NewChunkExtractTask(ctx context.Context, client *asynq.Client, tenantID uint64, chunkID string, modelID string) error {
|
||||
func NewChunkExtractTask(
|
||||
ctx context.Context,
|
||||
client *asynq.Client,
|
||||
tenantID uint64,
|
||||
chunkID string,
|
||||
modelID string,
|
||||
) error {
|
||||
if strings.ToLower(os.Getenv("NEO4J_ENABLE")) != "true" {
|
||||
logger.Warn(ctx, "NEO4J is not enabled, skip chunk extract task")
|
||||
return nil
|
||||
|
||||
@@ -307,7 +307,13 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
|
||||
// 即使入队失败,也返回knowledge,因为文件已保存
|
||||
return knowledge, nil
|
||||
}
|
||||
logger.Infof(ctx, "Enqueued document process task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, knowledge.ID)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Enqueued document process task: id=%s queue=%s knowledge_id=%s",
|
||||
info.ID,
|
||||
info.Queue,
|
||||
knowledge.ID,
|
||||
)
|
||||
|
||||
logger.Infof(ctx, "Knowledge from file created successfully, ID: %s", knowledge.ID)
|
||||
return knowledge, nil
|
||||
@@ -664,7 +670,10 @@ func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error
|
||||
// Delete knowledge embeddings from vector store
|
||||
wg.Go(func() error {
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieveEngine,
|
||||
tenantInfo.RetrieverEngines.Engines,
|
||||
)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge delete knowledge embedding failed")
|
||||
return err
|
||||
@@ -738,7 +747,10 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
||||
// 2. Delete knowledge embeddings from vector store
|
||||
wg.Go(func() error {
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieveEngine,
|
||||
tenantInfo.RetrieverEngines.Engines,
|
||||
)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge delete knowledge embedding failed")
|
||||
return err
|
||||
@@ -754,7 +766,9 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
||||
return err
|
||||
}
|
||||
if err := retrieveEngine.DeleteByKnowledgeIDList(ctx, knowledgeList, embeddingModel.GetDimensions()); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge delete knowledge embedding failed")
|
||||
logger.GetLogger(ctx).
|
||||
WithField("error", err).
|
||||
Errorf("DeleteKnowledge delete knowledge embedding failed")
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -792,7 +806,10 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
||||
wg.Go(func() error {
|
||||
namespaces := []types.NameSpace{}
|
||||
for _, knowledge := range knowledgeList {
|
||||
namespaces = append(namespaces, types.NameSpace{KnowledgeBase: knowledge.KnowledgeBaseID, Knowledge: knowledge.ID})
|
||||
namespaces = append(
|
||||
namespaces,
|
||||
types.NameSpace{KnowledgeBase: knowledge.KnowledgeBaseID, Knowledge: knowledge.ID},
|
||||
)
|
||||
}
|
||||
if err := s.graphEngine.DelGraph(ctx, namespaces); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge delete knowledge graph failed")
|
||||
@@ -808,7 +825,11 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
||||
return s.repo.DeleteKnowledgeList(ctx, tenantInfo.ID, ids)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) cloneKnowledge(ctx context.Context, src *types.Knowledge, targetKB *types.KnowledgeBase) (err error) {
|
||||
func (s *knowledgeService) cloneKnowledge(
|
||||
ctx context.Context,
|
||||
src *types.Knowledge,
|
||||
targetKB *types.KnowledgeBase,
|
||||
) (err error) {
|
||||
if src.ParseStatus != "completed" {
|
||||
logger.GetLogger(ctx).WithField("knowledge_id", src.ID).Errorf("MoveKnowledge parse status is not completed")
|
||||
return nil
|
||||
@@ -1657,7 +1678,12 @@ func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, c
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) UpdateImageInfo(ctx context.Context, knowledgeID string, chunkID string, imageInfo string) error {
|
||||
func (s *knowledgeService) UpdateImageInfo(
|
||||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
chunkID string,
|
||||
imageInfo string,
|
||||
) error {
|
||||
var images []*types.ImageInfo
|
||||
if err := json.Unmarshal([]byte(imageInfo), &images); err != nil {
|
||||
logger.Errorf(ctx, "Failed to unmarshal image info: %v", err)
|
||||
@@ -2165,7 +2191,12 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
|
||||
|
||||
if payload.Mode == types.FAQBatchModeReplace {
|
||||
// Replace模式:计算需要删除、创建、更新的条目
|
||||
entriesToProcess, chunksToDelete, skippedCount, err = s.calculateReplaceOperations(ctx, tenantID, faqKnowledge.ID, payload.Entries)
|
||||
entriesToProcess, chunksToDelete, skippedCount, err = s.calculateReplaceOperations(
|
||||
ctx,
|
||||
tenantID,
|
||||
faqKnowledge.ID,
|
||||
payload.Entries,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to calculate replace operations: %w", err)
|
||||
}
|
||||
@@ -2193,7 +2224,14 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "FAQ import task %s: total entries: %d, to process: %d, skipped: %d", taskID, len(payload.Entries), len(entriesToProcess), skippedCount)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"FAQ import task %s: total entries: %d, to process: %d, skipped: %d",
|
||||
taskID,
|
||||
len(payload.Entries),
|
||||
len(entriesToProcess),
|
||||
skippedCount,
|
||||
)
|
||||
|
||||
// 如果没有需要处理的条目,直接返回
|
||||
if len(entriesToProcess) == 0 {
|
||||
@@ -2206,7 +2244,14 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
|
||||
totalStartTime := time.Now()
|
||||
actualProcessed := skippedCount + processedCount
|
||||
|
||||
logger.Infof(ctx, "FAQ import task %s: starting batch processing, remaining entries: %d, total entries: %d, batch size: %d", taskID, remainingEntries, totalEntries, faqImportBatchSize)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"FAQ import task %s: starting batch processing, remaining entries: %d, total entries: %d, batch size: %d",
|
||||
taskID,
|
||||
remainingEntries,
|
||||
totalEntries,
|
||||
faqImportBatchSize,
|
||||
)
|
||||
|
||||
for i := 0; i < remainingEntries; i += faqImportBatchSize {
|
||||
batchStartTime := time.Now()
|
||||
@@ -2263,7 +2308,15 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
|
||||
return fmt.Errorf("failed to create chunks: %w", err)
|
||||
}
|
||||
createDuration := time.Since(createStartTime)
|
||||
logger.Infof(ctx, "FAQ import task %s: batch %d-%d created %d chunks in %v", taskID, i+1, end, len(chunks), createDuration)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"FAQ import task %s: batch %d-%d created %d chunks in %v",
|
||||
taskID,
|
||||
i+1,
|
||||
end,
|
||||
len(chunks),
|
||||
createDuration,
|
||||
)
|
||||
|
||||
// 索引chunks
|
||||
indexStartTime := time.Now()
|
||||
@@ -2272,7 +2325,15 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
|
||||
return fmt.Errorf("failed to index chunks: %w", err)
|
||||
}
|
||||
indexDuration := time.Since(indexStartTime)
|
||||
logger.Infof(ctx, "FAQ import task %s: batch %d-%d indexed %d chunks in %v", taskID, i+1, end, len(chunks), indexDuration)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"FAQ import task %s: batch %d-%d indexed %d chunks in %v",
|
||||
taskID,
|
||||
i+1,
|
||||
end,
|
||||
len(chunks),
|
||||
indexDuration,
|
||||
)
|
||||
|
||||
// 更新chunks的Status为已索引
|
||||
chunksToUpdate := make([]*types.Chunk, 0, len(chunks))
|
||||
@@ -2292,13 +2353,32 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
|
||||
}
|
||||
|
||||
batchDuration := time.Since(batchStartTime)
|
||||
logger.Infof(ctx, "FAQ import task %s: batch %d-%d completed in %v (build: %v, create: %v, index: %v), total progress: %d/%d (%d%%)",
|
||||
taskID, i+1, end, batchDuration, buildDuration, createDuration, indexDuration, actualProcessed, totalEntries, progress)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"FAQ import task %s: batch %d-%d completed in %v (build: %v, create: %v, index: %v), total progress: %d/%d (%d%%)",
|
||||
taskID,
|
||||
i+1,
|
||||
end,
|
||||
batchDuration,
|
||||
buildDuration,
|
||||
createDuration,
|
||||
indexDuration,
|
||||
actualProcessed,
|
||||
totalEntries,
|
||||
progress,
|
||||
)
|
||||
}
|
||||
|
||||
totalDuration := time.Since(totalStartTime)
|
||||
logger.Infof(ctx, "FAQ import task %s: all batches completed, processed: %d entries (skipped: %d) in %v, avg: %v per entry",
|
||||
taskID, actualProcessed, skippedCount, totalDuration, totalDuration/time.Duration(actualProcessed))
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"FAQ import task %s: all batches completed, processed: %d entries (skipped: %d) in %v, avg: %v per entry",
|
||||
taskID,
|
||||
actualProcessed,
|
||||
skippedCount,
|
||||
totalDuration,
|
||||
totalDuration/time.Duration(actualProcessed),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -2358,7 +2438,10 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
|
||||
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)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieveEngine,
|
||||
tenantInfo.RetrieverEngines.Engines,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2464,7 +2547,10 @@ func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
|
||||
// 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)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieveEngine,
|
||||
tenantInfo.RetrieverEngines.Engines,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2839,7 +2925,11 @@ func (s *knowledgeService) validateFAQKnowledgeBase(ctx context.Context, kbID st
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint64, kbID string) (*types.Knowledge, error) {
|
||||
func (s *knowledgeService) findFAQKnowledge(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
) (*types.Knowledge, error) {
|
||||
knowledges, err := s.repo.ListKnowledgeByKnowledgeBaseID(ctx, tenantID, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -2852,7 +2942,11 @@ func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint64
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) ensureFAQKnowledge(ctx context.Context, tenantID uint64, kb *types.KnowledgeBase) (*types.Knowledge, error) {
|
||||
func (s *knowledgeService) ensureFAQKnowledge(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kb *types.KnowledgeBase,
|
||||
) (*types.Knowledge, error) {
|
||||
existing, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -2879,15 +2973,23 @@ func (s *knowledgeService) ensureFAQKnowledge(ctx context.Context, tenantID uint
|
||||
return knowledge, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) updateFAQImportStatus(ctx context.Context, knowledgeID string, status types.FAQImportTaskStatus,
|
||||
progress, total, processed int, errorMsg string,
|
||||
func (s *knowledgeService) updateFAQImportStatus(
|
||||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
status types.FAQImportTaskStatus,
|
||||
progress, total, processed int,
|
||||
errorMsg string,
|
||||
) error {
|
||||
return s.updateFAQImportStatusWithRanges(ctx, knowledgeID, status, progress, total, processed, errorMsg)
|
||||
}
|
||||
|
||||
// updateFAQImportStatusWithRanges 更新FAQ Knowledge的导入任务状态,包含NextChunkIndex
|
||||
func (s *knowledgeService) updateFAQImportStatusWithRanges(ctx context.Context, knowledgeID string, status types.FAQImportTaskStatus,
|
||||
progress, total, processed int, errorMsg string,
|
||||
func (s *knowledgeService) updateFAQImportStatusWithRanges(
|
||||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
status types.FAQImportTaskStatus,
|
||||
progress, total, processed int,
|
||||
errorMsg string,
|
||||
) error {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
|
||||
@@ -2925,7 +3027,11 @@ func (s *knowledgeService) updateFAQImportStatusWithRanges(ctx context.Context,
|
||||
}
|
||||
|
||||
// getRunningFAQImportTask 获取指定知识库的进行中导入任务
|
||||
func (s *knowledgeService) getRunningFAQImportTask(ctx context.Context, kbID string, tenantID uint64) (*types.Knowledge, error) {
|
||||
func (s *knowledgeService) getRunningFAQImportTask(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
tenantID uint64,
|
||||
) (*types.Knowledge, error) {
|
||||
faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -3023,7 +3129,11 @@ func buildFAQIndexContent(meta *types.FAQChunkMetadata, mode types.FAQIndexMode)
|
||||
}
|
||||
|
||||
// buildFAQIndexInfoList 构建FAQ索引信息列表,支持分别索引模式
|
||||
func (s *knowledgeService) buildFAQIndexInfoList(ctx context.Context, kb *types.KnowledgeBase, chunk *types.Chunk) ([]*types.IndexInfo, error) {
|
||||
func (s *knowledgeService) buildFAQIndexInfoList(
|
||||
ctx context.Context,
|
||||
kb *types.KnowledgeBase,
|
||||
chunk *types.Chunk,
|
||||
) ([]*types.IndexInfo, error) {
|
||||
indexMode := types.FAQIndexModeQuestionAnswer
|
||||
questionIndexMode := types.FAQQuestionIndexModeCombined
|
||||
if kb.FAQConfig != nil {
|
||||
@@ -3137,7 +3247,13 @@ func (s *knowledgeService) indexFAQChunks(ctx context.Context,
|
||||
chunkIDs = append(chunkIDs, chunk.ID)
|
||||
}
|
||||
buildIndexInfoDuration := time.Since(buildIndexInfoStartTime)
|
||||
logger.Debugf(ctx, "indexFAQChunks: built %d index info entries for %d chunks in %v", len(indexInfo), len(chunks), buildIndexInfoDuration)
|
||||
logger.Debugf(
|
||||
ctx,
|
||||
"indexFAQChunks: built %d index info entries for %d chunks in %v",
|
||||
len(indexInfo),
|
||||
len(chunks),
|
||||
buildIndexInfoDuration,
|
||||
)
|
||||
|
||||
var size int64
|
||||
if adjustStorage {
|
||||
@@ -3195,8 +3311,16 @@ func (s *knowledgeService) indexFAQChunks(ctx context.Context,
|
||||
}
|
||||
|
||||
totalDuration := time.Since(indexStartTime)
|
||||
logger.Debugf(ctx, "indexFAQChunks: completed indexing %d chunks in %v (build: %v, delete: %v, batchIndex: %v, update: %v)",
|
||||
len(chunks), totalDuration, buildIndexInfoDuration, deleteDuration, batchIndexDuration, updateDuration)
|
||||
logger.Debugf(
|
||||
ctx,
|
||||
"indexFAQChunks: completed indexing %d chunks in %v (build: %v, delete: %v, batchIndex: %v, update: %v)",
|
||||
len(chunks),
|
||||
totalDuration,
|
||||
buildIndexInfoDuration,
|
||||
deleteDuration,
|
||||
batchIndexDuration,
|
||||
updateDuration,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -3311,7 +3435,9 @@ func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
|
||||
Separators: kb.ChunkingConfig.Separators,
|
||||
EnableMultimodal: enableMultimodel,
|
||||
StorageConfig: &proto.StorageConfig{
|
||||
Provider: proto.StorageProvider(proto.StorageProvider_value[strings.ToUpper(kb.StorageConfig.Provider)]),
|
||||
Provider: proto.StorageProvider(
|
||||
proto.StorageProvider_value[strings.ToUpper(kb.StorageConfig.Provider)],
|
||||
),
|
||||
Region: kb.StorageConfig.Region,
|
||||
BucketName: kb.StorageConfig.BucketName,
|
||||
AccessKeyId: kb.StorageConfig.SecretID,
|
||||
@@ -3354,7 +3480,10 @@ func (s *knowledgeService) cleanupKnowledgeResources(ctx context.Context, knowle
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if knowledge.EmbeddingModelID != "" {
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieveEngine,
|
||||
tenantInfo.RetrieverEngines.Engines,
|
||||
)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Error("Failed to init retrieve engine during cleanup")
|
||||
cleanupErr = errors.Join(cleanupErr, err)
|
||||
@@ -3470,12 +3599,18 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
if knowledge.ParseStatus == "failed" {
|
||||
// 检查是否可恢复(例如:超时、临时错误等)
|
||||
// 对于不可恢复的错误,直接返回
|
||||
logger.Warnf(ctx, "Document processing previously failed: %s, error: %s", payload.KnowledgeID, knowledge.ErrorMessage)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Document processing previously failed: %s, error: %s",
|
||||
payload.KnowledgeID,
|
||||
knowledge.ErrorMessage,
|
||||
)
|
||||
// 这里可以根据错误类型判断是否可恢复,暂时允许重试
|
||||
}
|
||||
|
||||
// 检查是否有部分处理(有chunks但状态不是completed)
|
||||
if knowledge.ParseStatus != "completed" && knowledge.ParseStatus != "pending" && knowledge.ParseStatus != "processing" {
|
||||
if knowledge.ParseStatus != "completed" && knowledge.ParseStatus != "pending" &&
|
||||
knowledge.ParseStatus != "processing" {
|
||||
// 状态异常,记录日志但继续处理
|
||||
logger.Warnf(ctx, "Unexpected parse status: %s for knowledge: %s", knowledge.ParseStatus, payload.KnowledgeID)
|
||||
}
|
||||
@@ -3546,7 +3681,9 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
|
||||
Separators: kb.ChunkingConfig.Separators,
|
||||
EnableMultimodal: payload.EnableMultimodel,
|
||||
StorageConfig: &proto.StorageConfig{
|
||||
Provider: proto.StorageProvider(proto.StorageProvider_value[strings.ToUpper(kb.StorageConfig.Provider)]),
|
||||
Provider: proto.StorageProvider(
|
||||
proto.StorageProvider_value[strings.ToUpper(kb.StorageConfig.Provider)],
|
||||
),
|
||||
Region: kb.StorageConfig.Region,
|
||||
BucketName: kb.StorageConfig.BucketName,
|
||||
AccessKeyId: kb.StorageConfig.SecretID,
|
||||
@@ -3721,7 +3858,10 @@ func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task)
|
||||
// 删除索引数据
|
||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err == nil {
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieveEngine,
|
||||
tenantInfo.RetrieverEngines.Engines,
|
||||
)
|
||||
if err == nil {
|
||||
chunkIDs := make([]string, 0, len(chunksDeleted))
|
||||
for _, chunk := range chunksDeleted {
|
||||
@@ -3740,7 +3880,12 @@ func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task)
|
||||
payload.Entries = payload.Entries[processedCount:]
|
||||
}
|
||||
// Replace 模式使用hash去重,不截断payload.Entries
|
||||
logger.Infof(ctx, "Continuing FAQ import from entry %d, remaining: %d entries", processedCount, len(payload.Entries))
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Continuing FAQ import from entry %d, remaining: %d entries",
|
||||
processedCount,
|
||||
len(payload.Entries),
|
||||
)
|
||||
}
|
||||
|
||||
// 更新任务状态为运行中
|
||||
|
||||
@@ -248,7 +248,10 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
|
||||
// Delete embeddings from vector store
|
||||
logger.Infof(ctx, "Deleting embeddings from vector store")
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
s.retrieveEngine,
|
||||
tenantInfo.RetrieverEngines.Engines,
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to create retrieve engine: %v", err)
|
||||
} else {
|
||||
@@ -489,7 +492,8 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
}
|
||||
|
||||
// Add keyword retrieval params if supported and not FAQ
|
||||
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) && !params.DisableKeywordsMatch && kb.Type != types.KnowledgeBaseTypeFAQ {
|
||||
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) && !params.DisableKeywordsMatch &&
|
||||
kb.Type != types.KnowledgeBaseTypeFAQ {
|
||||
logger.Info(ctx, "Keyword retrieval supported, preparing keyword retrieval parameters")
|
||||
retrieveParams = append(retrieveParams, types.RetrieveParams{
|
||||
Query: params.QueryText,
|
||||
@@ -537,7 +541,9 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
logger.Infof(ctx, "Result count before deduplication: %d", len(matchResults))
|
||||
|
||||
// First, try standard deduplication
|
||||
deduplicatedChunks := common.DeduplicateWithScore(func(r *types.IndexWithScore) string { return r.ChunkID }, matchResults...)
|
||||
deduplicatedChunks := common.DeduplicateWithScore(
|
||||
func(r *types.IndexWithScore) string { return r.ChunkID },
|
||||
matchResults...)
|
||||
logger.Infof(ctx, "Result count after deduplication: %d", len(deduplicatedChunks))
|
||||
|
||||
kb.EnsureDefaults()
|
||||
@@ -549,7 +555,13 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
if needsIterativeRetrieval {
|
||||
logger.Info(ctx, "Not enough unique chunks, using iterative retrieval for FAQ")
|
||||
// Use iterative retrieval to get more unique chunks (with negative question filtering inside)
|
||||
deduplicatedChunks = s.iterativeRetrieveWithDeduplication(ctx, retrieveEngine, retrieveParams, params.MatchCount, params.QueryText)
|
||||
deduplicatedChunks = s.iterativeRetrieveWithDeduplication(
|
||||
ctx,
|
||||
retrieveEngine,
|
||||
retrieveParams,
|
||||
params.MatchCount,
|
||||
params.QueryText,
|
||||
)
|
||||
} else if kb.Type == types.KnowledgeBaseTypeFAQ {
|
||||
// Filter by negative questions if not using iterative retrieval
|
||||
deduplicatedChunks = s.filterByNegativeQuestions(ctx, deduplicatedChunks, params.QueryText)
|
||||
@@ -606,7 +618,12 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co
|
||||
// Check if we got fewer results than requested - means no more results available
|
||||
totalRetrieved := len(iterationResults)
|
||||
if totalRetrieved < currentTopK {
|
||||
logger.Infof(ctx, "Retrieved %d results (less than TopK %d), no more results available", totalRetrieved, currentTopK)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Retrieved %d results (less than TopK %d), no more results available",
|
||||
totalRetrieved,
|
||||
currentTopK,
|
||||
)
|
||||
}
|
||||
|
||||
// Deduplicate and merge (keep highest score for each chunk)
|
||||
@@ -631,8 +648,14 @@ func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Co
|
||||
uniqueChunks[chunk.ChunkID] = chunk
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "After iteration %d: retrieved %d results, found %d unique chunks after filtering (target: %d)",
|
||||
i+1, totalRetrieved, len(uniqueChunks), matchCount)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"After iteration %d: retrieved %d results, found %d unique chunks after filtering (target: %d)",
|
||||
i+1,
|
||||
totalRetrieved,
|
||||
len(uniqueChunks),
|
||||
matchCount,
|
||||
)
|
||||
|
||||
// Early stop: Check if we have enough unique chunks after deduplication and filtering
|
||||
if len(uniqueChunks) >= matchCount {
|
||||
|
||||
@@ -24,7 +24,11 @@ func NewSlidingWindowStrategy(recentMessageCount int) interfaces.CompressionStra
|
||||
|
||||
// Compress implements the sliding window compression
|
||||
// Keeps system messages and the most recent N messages
|
||||
func (s *slidingWindowStrategy) Compress(ctx context.Context, messages []chat.Message, maxTokens int) ([]chat.Message, error) {
|
||||
func (s *slidingWindowStrategy) Compress(
|
||||
ctx context.Context,
|
||||
messages []chat.Message,
|
||||
maxTokens int,
|
||||
) ([]chat.Message, error) {
|
||||
if len(messages) <= s.recentMessageCount {
|
||||
return messages, nil
|
||||
}
|
||||
@@ -83,7 +87,11 @@ type smartCompressionStrategy struct {
|
||||
}
|
||||
|
||||
// NewSmartCompressionStrategy creates a new smart compression strategy
|
||||
func NewSmartCompressionStrategy(recentMessageCount int, chatModel chat.Chat, summarizeThreshold int) interfaces.CompressionStrategy {
|
||||
func NewSmartCompressionStrategy(
|
||||
recentMessageCount int,
|
||||
chatModel chat.Chat,
|
||||
summarizeThreshold int,
|
||||
) interfaces.CompressionStrategy {
|
||||
return &smartCompressionStrategy{
|
||||
recentMessageCount: recentMessageCount,
|
||||
chatModel: chatModel,
|
||||
@@ -93,7 +101,11 @@ func NewSmartCompressionStrategy(recentMessageCount int, chatModel chat.Chat, su
|
||||
|
||||
// Compress implements smart compression with LLM summarization
|
||||
// Summarizes old messages and keeps recent messages intact
|
||||
func (s *smartCompressionStrategy) Compress(ctx context.Context, messages []chat.Message, maxTokens int) ([]chat.Message, error) {
|
||||
func (s *smartCompressionStrategy) Compress(
|
||||
ctx context.Context,
|
||||
messages []chat.Message,
|
||||
maxTokens int,
|
||||
) ([]chat.Message, error) {
|
||||
if len(messages) <= s.recentMessageCount {
|
||||
return messages, nil
|
||||
}
|
||||
@@ -156,8 +168,15 @@ func (s *smartCompressionStrategy) Compress(ctx context.Context, messages []chat
|
||||
})
|
||||
result = append(result, recentMessages...)
|
||||
|
||||
logger.Infof(ctx, "[SmartCompression] Compressed %d messages to %d messages (summarized %d old + kept %d recent + %d system)",
|
||||
len(messages), len(result), len(oldMessages), len(recentMessages), len(systemMessages))
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[SmartCompression] Compressed %d messages to %d messages (summarized %d old + kept %d recent + %d system)",
|
||||
len(messages),
|
||||
len(result),
|
||||
len(oldMessages),
|
||||
len(recentMessages),
|
||||
len(systemMessages),
|
||||
)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -18,7 +18,11 @@ type contextManager struct {
|
||||
}
|
||||
|
||||
// NewContextManager creates a new context manager with the specified storage and compression strategy
|
||||
func NewContextManager(storage ContextStorage, compressionStrategy interfaces.CompressionStrategy, maxTokens int) interfaces.ContextManager {
|
||||
func NewContextManager(
|
||||
storage ContextStorage,
|
||||
compressionStrategy interfaces.CompressionStrategy,
|
||||
maxTokens int,
|
||||
) interfaces.ContextManager {
|
||||
return &contextManager{
|
||||
storage: storage,
|
||||
compressionStrategy: compressionStrategy,
|
||||
@@ -27,7 +31,10 @@ func NewContextManager(storage ContextStorage, compressionStrategy interfaces.Co
|
||||
}
|
||||
|
||||
// NewContextManagerWithMemory creates a context manager with in-memory storage (for backward compatibility)
|
||||
func NewContextManagerWithMemory(compressionStrategy interfaces.CompressionStrategy, maxTokens int) interfaces.ContextManager {
|
||||
func NewContextManagerWithMemory(
|
||||
compressionStrategy interfaces.CompressionStrategy,
|
||||
maxTokens int,
|
||||
) interfaces.ContextManager {
|
||||
return &contextManager{
|
||||
storage: NewMemoryStorage(),
|
||||
compressionStrategy: compressionStrategy,
|
||||
@@ -86,7 +93,12 @@ func (cm *contextManager) AddMessage(ctx context.Context, sessionID string, mess
|
||||
return fmt.Errorf("failed to save context: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[ContextManager][Session-%s] Successfully added message (total: %d messages)", sessionID, len(messages))
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[ContextManager][Session-%s] Successfully added message (total: %d messages)",
|
||||
sessionID,
|
||||
len(messages),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,11 @@ const (
|
||||
)
|
||||
|
||||
// NewContextManagerFromConfig creates a ContextManager based on configuration
|
||||
func NewContextManagerFromConfig(contextCfg *types.ContextConfig, storage ContextStorage, chatModel chat.Chat) interfaces.ContextManager {
|
||||
func NewContextManagerFromConfig(
|
||||
contextCfg *types.ContextConfig,
|
||||
storage ContextStorage,
|
||||
chatModel chat.Chat,
|
||||
) interfaces.ContextManager {
|
||||
// Use default values if config is nil
|
||||
if contextCfg == nil {
|
||||
logger.Info(context.TODO(), "ContextManager config not found, using default memory-based context manager")
|
||||
|
||||
@@ -49,7 +49,11 @@ func (s *mcpServiceService) CreateMCPService(ctx context.Context, service *types
|
||||
}
|
||||
|
||||
// GetMCPServiceByID retrieves an MCP service by ID
|
||||
func (s *mcpServiceService) GetMCPServiceByID(ctx context.Context, tenantID uint64, id string) (*types.MCPService, error) {
|
||||
func (s *mcpServiceService) GetMCPServiceByID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
id string,
|
||||
) (*types.MCPService, error) {
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to get MCP service: %v", err)
|
||||
@@ -80,7 +84,11 @@ func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint64
|
||||
}
|
||||
|
||||
// ListMCPServicesByIDs retrieves multiple MCP services by IDs
|
||||
func (s *mcpServiceService) ListMCPServicesByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.MCPService, error) {
|
||||
func (s *mcpServiceService) ListMCPServicesByIDs(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
ids []string,
|
||||
) ([]*types.MCPService, error) {
|
||||
if len(ids) == 0 {
|
||||
return []*types.MCPService{}, nil
|
||||
}
|
||||
@@ -221,7 +229,11 @@ func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint6
|
||||
}
|
||||
|
||||
// TestMCPService tests the connection to an MCP service and returns available tools/resources
|
||||
func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint64, id string) (*types.MCPTestResult, error) {
|
||||
func (s *mcpServiceService) TestMCPService(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
id string,
|
||||
) (*types.MCPTestResult, error) {
|
||||
// Get service
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
@@ -280,15 +292,23 @@ func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint64,
|
||||
}
|
||||
|
||||
return &types.MCPTestResult{
|
||||
Success: true,
|
||||
Message: fmt.Sprintf("Connected successfully to %s v%s", initResult.ServerInfo.Name, initResult.ServerInfo.Version),
|
||||
Success: true,
|
||||
Message: fmt.Sprintf(
|
||||
"Connected successfully to %s v%s",
|
||||
initResult.ServerInfo.Name,
|
||||
initResult.ServerInfo.Version,
|
||||
),
|
||||
Tools: tools,
|
||||
Resources: resources,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetMCPServiceTools retrieves the list of tools from an MCP service
|
||||
func (s *mcpServiceService) GetMCPServiceTools(ctx context.Context, tenantID uint64, id string) ([]*types.MCPTool, error) {
|
||||
func (s *mcpServiceService) GetMCPServiceTools(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
id string,
|
||||
) ([]*types.MCPTool, error) {
|
||||
// Get service
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
@@ -314,7 +334,11 @@ func (s *mcpServiceService) GetMCPServiceTools(ctx context.Context, tenantID uin
|
||||
}
|
||||
|
||||
// GetMCPServiceResources retrieves the list of resources from an MCP service
|
||||
func (s *mcpServiceService) GetMCPServiceResources(ctx context.Context, tenantID uint64, id string) ([]*types.MCPResource, error) {
|
||||
func (s *mcpServiceService) GetMCPServiceResources(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
id string,
|
||||
) ([]*types.MCPResource, error) {
|
||||
// Get service
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
|
||||
@@ -198,7 +198,10 @@ func unionLcs(evaluatedSentences []string, referenceSentence string, prevUnion *
|
||||
return newLcsCount, lcsUnion
|
||||
}
|
||||
|
||||
func rougeLSummaryLevel(evaluatedSentences, referenceSentences []string, rawResults, exclusive bool) map[string]float64 {
|
||||
func rougeLSummaryLevel(
|
||||
evaluatedSentences, referenceSentences []string,
|
||||
rawResults, exclusive bool,
|
||||
) map[string]float64 {
|
||||
referenceNgrams := NewNgrams(exclusive)
|
||||
referenceNgrams.BatchAdd(splitIntoWords(referenceSentences))
|
||||
m := referenceNgrams.Len()
|
||||
|
||||
@@ -62,7 +62,10 @@ func (c *CompositeRetrieveEngine) Retrieve(ctx context.Context,
|
||||
}
|
||||
|
||||
// NewCompositeRetrieveEngine creates a new composite retrieve engine with the given parameters
|
||||
func NewCompositeRetrieveEngine(registry interfaces.RetrieveEngineRegistry, engineParams []types.RetrieverEngineParams) (*CompositeRetrieveEngine, error) {
|
||||
func NewCompositeRetrieveEngine(
|
||||
registry interfaces.RetrieveEngineRegistry,
|
||||
engineParams []types.RetrieverEngineParams,
|
||||
) (*CompositeRetrieveEngine, error) {
|
||||
engineInfos := make(map[types.RetrieverEngineType]*engineInfo)
|
||||
for _, engineParam := range engineParams {
|
||||
repo, err := registry.GetRetrieveEngineService(engineParam.RetrieverEngineType)
|
||||
@@ -100,7 +103,10 @@ func (c *CompositeRetrieveEngine) SupportRetriever(r types.RetrieverType) bool {
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (c *CompositeRetrieveEngine) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
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
|
||||
|
||||
@@ -165,6 +165,9 @@ func (v *KeywordsVectorHybridRetrieveEngineService) CopyIndices(
|
||||
}
|
||||
|
||||
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
|
||||
func (v *KeywordsVectorHybridRetrieveEngineService) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
func (v *KeywordsVectorHybridRetrieveEngineService) BatchUpdateChunkEnabledStatus(
|
||||
ctx context.Context,
|
||||
chunkStatusMap map[string]bool,
|
||||
) error {
|
||||
return v.indexRepository.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap)
|
||||
}
|
||||
|
||||
@@ -326,7 +326,12 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
|
||||
// GenerateTitleAsync generates a title for the session asynchronously
|
||||
// This method clones the session and generates the title in a goroutine
|
||||
// It emits an event when the title is generated
|
||||
func (s *sessionService) GenerateTitleAsync(ctx context.Context, session *types.Session, userQuery string, eventBus *event.EventBus) {
|
||||
func (s *sessionService) GenerateTitleAsync(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
userQuery string,
|
||||
eventBus *event.EventBus,
|
||||
) {
|
||||
// Extract values from context before cloning
|
||||
tenantID := ctx.Value(types.TenantIDContextKey)
|
||||
requestID := ctx.Value(types.RequestIDContextKey)
|
||||
@@ -384,8 +389,23 @@ func (s *sessionService) GenerateTitleAsync(ctx context.Context, session *types.
|
||||
|
||||
// KnowledgeQA performs knowledge base question answering with LLM summarization
|
||||
// Events are emitted through eventBus (references, answer chunks, completion)
|
||||
func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session, query string, knowledgeBaseIDs []string, assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus) error {
|
||||
logger.Infof(ctx, "Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v", session.ID, query, webSearchEnabled)
|
||||
func (s *sessionService) KnowledgeQA(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
query string,
|
||||
knowledgeBaseIDs []string,
|
||||
assistantMessageID string,
|
||||
summaryModelID string,
|
||||
webSearchEnabled bool,
|
||||
eventBus *event.EventBus,
|
||||
) error {
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v",
|
||||
session.ID,
|
||||
query,
|
||||
webSearchEnabled,
|
||||
)
|
||||
|
||||
// If no knowledge base IDs provided, fall back to session's default
|
||||
if len(knowledgeBaseIDs) == 0 {
|
||||
@@ -492,7 +512,12 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
|
||||
}
|
||||
|
||||
// Create chat management object with session settings
|
||||
logger.Infof(ctx, "Creating chat manage object, knowledge base IDs: %v, chat model ID: %s", knowledgeBaseIDs, chatModelID)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Creating chat manage object, knowledge base IDs: %v, chat model ID: %s",
|
||||
knowledgeBaseIDs,
|
||||
chatModelID,
|
||||
)
|
||||
chatManage := &types.ChatManage{
|
||||
Query: query,
|
||||
RewriteQuery: query,
|
||||
@@ -563,13 +588,23 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
|
||||
// 3. First knowledge base with a Remote model
|
||||
// 4. Session's SummaryModelID (if not Remote)
|
||||
// 5. First knowledge base's SummaryModelID
|
||||
func (s *sessionService) selectChatModelIDWithOverride(ctx context.Context, session *types.Session, knowledgeBaseIDs []string, summaryModelID string) (string, error) {
|
||||
func (s *sessionService) selectChatModelIDWithOverride(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
knowledgeBaseIDs []string,
|
||||
summaryModelID string,
|
||||
) (string, error) {
|
||||
// First, check if request has summaryModelID override
|
||||
if summaryModelID != "" {
|
||||
// Validate that the model exists
|
||||
model, err := s.modelService.GetModelByID(ctx, summaryModelID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Request provided invalid summary model ID %s: %v, falling back to default selection", summaryModelID, err)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Request provided invalid summary model ID %s: %v, falling back to default selection",
|
||||
summaryModelID,
|
||||
err,
|
||||
)
|
||||
} else if model != nil {
|
||||
logger.Infof(ctx, "Using request's summary model override: %s", summaryModelID)
|
||||
return summaryModelID, nil
|
||||
@@ -586,7 +621,11 @@ func (s *sessionService) selectChatModelIDWithOverride(ctx context.Context, sess
|
||||
// 2. First knowledge base with a Remote model
|
||||
// 3. Session's SummaryModelID (if not Remote)
|
||||
// 4. First knowledge base's SummaryModelID
|
||||
func (s *sessionService) selectChatModelID(ctx context.Context, session *types.Session, knowledgeBaseIDs []string) (string, error) {
|
||||
func (s *sessionService) selectChatModelID(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
knowledgeBaseIDs []string,
|
||||
) (string, error) {
|
||||
// First, check if session has a SummaryModelID and if it's a Remote model
|
||||
if session.SummaryModelID != "" {
|
||||
model, err := s.modelService.GetModelByID(ctx, session.SummaryModelID)
|
||||
@@ -630,7 +669,12 @@ func (s *sessionService) selectChatModelID(ctx context.Context, session *types.S
|
||||
return "", fmt.Errorf("failed to get knowledge base %s: %w", knowledgeBaseIDs[0], err)
|
||||
}
|
||||
if kb != nil && kb.SummaryModelID != "" {
|
||||
logger.Infof(ctx, "Using summary model from first knowledge base %s: %s", knowledgeBaseIDs[0], kb.SummaryModelID)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Using summary model from first knowledge base %s: %s",
|
||||
knowledgeBaseIDs[0],
|
||||
kb.SummaryModelID,
|
||||
)
|
||||
return kb.SummaryModelID, nil
|
||||
} else {
|
||||
logger.Errorf(ctx, "Knowledge base %s has no summary model ID", knowledgeBaseIDs[0])
|
||||
@@ -639,7 +683,9 @@ func (s *sessionService) selectChatModelID(ctx context.Context, session *types.S
|
||||
}
|
||||
|
||||
logger.Error(ctx, "No chat model ID available")
|
||||
return "", errors.New("no chat model ID available: session has no SummaryModelID and knowledge bases have no SummaryModelID")
|
||||
return "", errors.New(
|
||||
"no chat model ID available: session has no SummaryModelID and knowledge bases have no SummaryModelID",
|
||||
)
|
||||
}
|
||||
|
||||
// KnowledgeQAByEvent processes knowledge QA through a series of events in the pipeline
|
||||
@@ -674,7 +720,12 @@ func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
|
||||
|
||||
// Handle case where search returns no results
|
||||
if err == chatpipline.ErrSearchNothing {
|
||||
logger.Warnf(ctx, "Event %v triggered, search result is empty, using fallback response, strategy: %v", eventType, chatManage.FallbackStrategy)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Event %v triggered, search result is empty, using fallback response, strategy: %v",
|
||||
eventType,
|
||||
chatManage.FallbackStrategy,
|
||||
)
|
||||
s.handleFallbackResponse(ctx, chatManage)
|
||||
return nil
|
||||
}
|
||||
@@ -800,7 +851,13 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
|
||||
}
|
||||
|
||||
// AgentQA performs agent-based question answering with conversation history and streaming support
|
||||
func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, query string, assistantMessageID string, eventBus *event.EventBus) error {
|
||||
func (s *sessionService) AgentQA(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
query string,
|
||||
assistantMessageID string,
|
||||
eventBus *event.EventBus,
|
||||
) error {
|
||||
sessionID := session.ID
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
sessionJSON, err := json.Marshal(session)
|
||||
@@ -940,7 +997,16 @@ func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, qu
|
||||
|
||||
// Create agent engine with EventBus and ContextManager
|
||||
logger.Info(ctx, "Creating agent engine")
|
||||
engine, err := s.agentService.CreateAgentEngine(ctx, agentConfig, summaryModel, rerankModel, eventBus, contextManager, session.ID, s)
|
||||
engine, err := s.agentService.CreateAgentEngine(
|
||||
ctx,
|
||||
agentConfig,
|
||||
summaryModel,
|
||||
rerankModel,
|
||||
eventBus,
|
||||
contextManager,
|
||||
session.ID,
|
||||
s,
|
||||
)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create agent engine: %v", err)
|
||||
return err
|
||||
@@ -968,7 +1034,11 @@ func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, qu
|
||||
|
||||
// getContextManagerForSession creates a context manager for the session based on configuration
|
||||
// Returns the configured context manager (tenant-level or session-level) or default
|
||||
func (s *sessionService) getContextManagerForSession(ctx context.Context, session *types.Session, chatModel chat.Chat) interfaces.ContextManager {
|
||||
func (s *sessionService) getContextManagerForSession(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
chatModel chat.Chat,
|
||||
) interfaces.ContextManager {
|
||||
// Get tenant to access global context configuration
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
// Determine which context config to use: session-specific or tenant-level
|
||||
@@ -995,7 +1065,11 @@ func (s *sessionService) getContextManagerForSession(ctx context.Context, sessio
|
||||
}
|
||||
|
||||
// getContextForSession retrieves LLM context for a session
|
||||
func (s *sessionService) getContextForSession(ctx context.Context, contextManager interfaces.ContextManager, sessionID string) ([]chat.Message, error) {
|
||||
func (s *sessionService) getContextForSession(
|
||||
ctx context.Context,
|
||||
contextManager interfaces.ContextManager,
|
||||
sessionID string,
|
||||
) ([]chat.Message, error) {
|
||||
history, err := contextManager.GetContext(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get context: %w", err)
|
||||
@@ -1019,7 +1093,10 @@ func (s *sessionService) ClearContext(ctx context.Context, sessionID string) err
|
||||
}
|
||||
|
||||
// GetWebSearchTempKBState retrieves the temporary KB state for web search from Redis
|
||||
func (s *sessionService) GetWebSearchTempKBState(ctx context.Context, sessionID string) (tempKBID string, seenURLs map[string]bool, knowledgeIDs []string) {
|
||||
func (s *sessionService) GetWebSearchTempKBState(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
) (tempKBID string, seenURLs map[string]bool, knowledgeIDs []string) {
|
||||
stateKey := fmt.Sprintf("tempkb:%s", sessionID)
|
||||
if raw, getErr := s.redisClient.Get(ctx, stateKey).Bytes(); getErr == nil && len(raw) > 0 {
|
||||
var state struct {
|
||||
@@ -1042,7 +1119,13 @@ func (s *sessionService) GetWebSearchTempKBState(ctx context.Context, sessionID
|
||||
}
|
||||
|
||||
// SaveWebSearchTempKBState saves the temporary KB state for web search to Redis
|
||||
func (s *sessionService) SaveWebSearchTempKBState(ctx context.Context, sessionID string, tempKBID string, seenURLs map[string]bool, knowledgeIDs []string) {
|
||||
func (s *sessionService) SaveWebSearchTempKBState(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
tempKBID string,
|
||||
seenURLs map[string]bool,
|
||||
knowledgeIDs []string,
|
||||
) {
|
||||
stateKey := fmt.Sprintf("tempkb:%s", sessionID)
|
||||
state := struct {
|
||||
KBID string `json:"kbID"`
|
||||
@@ -1207,7 +1290,11 @@ func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *t
|
||||
}
|
||||
|
||||
// consumeFallbackStream consumes the streaming response and emits events
|
||||
func (s *sessionService) consumeFallbackStream(ctx context.Context, chatManage *types.ChatManage, responseChan <-chan types.StreamResponse) {
|
||||
func (s *sessionService) consumeFallbackStream(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
responseChan <-chan types.StreamResponse,
|
||||
) {
|
||||
fallbackID := generateEventID("fallback")
|
||||
eventBus := chatManage.EventBus
|
||||
var finalContent string
|
||||
|
||||
@@ -69,7 +69,13 @@ func (s *knowledgeTagService) ListTags(ctx context.Context, kbID string) ([]*typ
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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和标签名称不能为空")
|
||||
@@ -96,7 +102,13 @@ func (s *knowledgeTagService) CreateTag(ctx context.Context, kbID string, name s
|
||||
}
|
||||
|
||||
// UpdateTag updates tag basic information.
|
||||
func (s *knowledgeTagService) UpdateTag(ctx context.Context, id string, name *string, color *string, sortOrder *int) (*types.KnowledgeTag, error) {
|
||||
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不能为空")
|
||||
}
|
||||
|
||||
@@ -52,7 +52,11 @@ type userService struct {
|
||||
}
|
||||
|
||||
// NewUserService creates a new user service instance
|
||||
func NewUserService(userRepo interfaces.UserRepository, tokenRepo interfaces.AuthTokenRepository, tenantService interfaces.TenantService) interfaces.UserService {
|
||||
func NewUserService(
|
||||
userRepo interfaces.UserRepository,
|
||||
tokenRepo interfaces.AuthTokenRepository,
|
||||
tenantService interfaces.TenantService,
|
||||
) interfaces.UserService {
|
||||
return &userService{
|
||||
userRepo: userRepo,
|
||||
tokenRepo: tokenRepo,
|
||||
@@ -294,7 +298,10 @@ func (s *userService) ValidatePassword(ctx context.Context, userID string, passw
|
||||
}
|
||||
|
||||
// GenerateTokens generates access and refresh tokens for user
|
||||
func (s *userService) GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error) {
|
||||
func (s *userService) GenerateTokens(
|
||||
ctx context.Context,
|
||||
user *types.User,
|
||||
) (accessToken, refreshToken string, err error) {
|
||||
// Generate access token (expires in 24 hours)
|
||||
accessClaims := jwt.MapClaims{
|
||||
"user_id": user.ID,
|
||||
@@ -385,7 +392,10 @@ func (s *userService) ValidateToken(ctx context.Context, tokenString string) (*t
|
||||
}
|
||||
|
||||
// RefreshToken refreshes access token using refresh token
|
||||
func (s *userService) RefreshToken(ctx context.Context, refreshTokenString string) (accessToken, newRefreshToken string, err error) {
|
||||
func (s *userService) RefreshToken(
|
||||
ctx context.Context,
|
||||
refreshTokenString string,
|
||||
) (accessToken, newRefreshToken string, err error) {
|
||||
token, err := jwt.Parse(refreshTokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
|
||||
@@ -55,7 +55,10 @@ func (s *WebSearchService) CompressWithRAG(
|
||||
}
|
||||
createdKB, err = kbSvc.CreateKnowledgeBase(ctx, kb)
|
||||
if err != nil {
|
||||
return nil, tempKBID, seenURLs, knowledgeIDs, fmt.Errorf("failed to create temporary knowledge base: %w", err)
|
||||
return nil, tempKBID, seenURLs, knowledgeIDs, fmt.Errorf(
|
||||
"failed to create temporary knowledge base: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
tempKBID = createdKB.ID
|
||||
}
|
||||
@@ -240,7 +243,11 @@ func stripMarker(content string) string {
|
||||
|
||||
// Search performs web search using the specified provider
|
||||
// This method implements the interface expected by PluginSearch
|
||||
func (s *WebSearchService) Search(ctx context.Context, config *types.WebSearchConfig, query string) ([]*types.WebSearchResult, error) {
|
||||
func (s *WebSearchService) Search(
|
||||
ctx context.Context,
|
||||
config *types.WebSearchConfig,
|
||||
query string,
|
||||
) ([]*types.WebSearchResult, error) {
|
||||
if config == nil {
|
||||
return nil, fmt.Errorf("web search config is required")
|
||||
}
|
||||
@@ -310,7 +317,10 @@ func NewWebSearchService(cfg *config.Config) (interfaces.WebSearchService, error
|
||||
}
|
||||
|
||||
// filterBlacklist filters results based on blacklist rules
|
||||
func (s *WebSearchService) filterBlacklist(results []*types.WebSearchResult, blacklist []string) []*types.WebSearchResult {
|
||||
func (s *WebSearchService) filterBlacklist(
|
||||
results []*types.WebSearchResult,
|
||||
blacklist []string,
|
||||
) []*types.WebSearchResult {
|
||||
if len(blacklist) == 0 {
|
||||
return results
|
||||
}
|
||||
|
||||
@@ -38,7 +38,12 @@ func (p *DuckDuckGoProvider) Name() string {
|
||||
}
|
||||
|
||||
// Search performs a web search using DuckDuckGo HTML endpoint with API fallback
|
||||
func (p *DuckDuckGoProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
func (p *DuckDuckGoProvider) Search(
|
||||
ctx context.Context,
|
||||
query string,
|
||||
maxResults int,
|
||||
includeDate bool,
|
||||
) ([]*types.WebSearchResult, error) {
|
||||
if maxResults <= 0 {
|
||||
maxResults = 5
|
||||
}
|
||||
@@ -58,7 +63,11 @@ func (p *DuckDuckGoProvider) Search(ctx context.Context, query string, maxResult
|
||||
return nil, fmt.Errorf("duckduckgo API search failed: %w", apiErr)
|
||||
}
|
||||
|
||||
func (p *DuckDuckGoProvider) searchHTML(ctx context.Context, query string, maxResults int) ([]*types.WebSearchResult, error) {
|
||||
func (p *DuckDuckGoProvider) searchHTML(
|
||||
ctx context.Context,
|
||||
query string,
|
||||
maxResults int,
|
||||
) ([]*types.WebSearchResult, error) {
|
||||
baseURL := "https://html.duckduckgo.com/html/"
|
||||
params := url.Values{}
|
||||
params.Set("q", query)
|
||||
@@ -71,10 +80,16 @@ func (p *DuckDuckGoProvider) searchHTML(ctx context.Context, query string, maxRe
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
// Use a realistic UA to avoid blocks
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||||
req.Header.Set(
|
||||
"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
)
|
||||
|
||||
// print curl of request
|
||||
curlCommand := fmt.Sprintf("curl -X GET '%s' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'", req.URL.String())
|
||||
curlCommand := fmt.Sprintf(
|
||||
"curl -X GET '%s' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'",
|
||||
req.URL.String(),
|
||||
)
|
||||
logger.Infof(ctx, "Curl of request: %s", secutils.SanitizeForLog(curlCommand))
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
@@ -119,7 +134,11 @@ func (p *DuckDuckGoProvider) searchHTML(ctx context.Context, query string, maxRe
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (p *DuckDuckGoProvider) searchAPI(ctx context.Context, query string, maxResults int) ([]*types.WebSearchResult, error) {
|
||||
func (p *DuckDuckGoProvider) searchAPI(
|
||||
ctx context.Context,
|
||||
query string,
|
||||
maxResults int,
|
||||
) ([]*types.WebSearchResult, error) {
|
||||
baseURL := "https://api.duckduckgo.com/"
|
||||
params := url.Values{}
|
||||
params.Set("q", query)
|
||||
|
||||
@@ -95,10 +95,12 @@ func TestDuckDuckGoProvider_Search_HTMLSuccess(t *testing.T) {
|
||||
if len(results) != 2 {
|
||||
t.Fatalf("expected 2 results, got %d", len(results))
|
||||
}
|
||||
if results[0].Title != "Example One" || !strings.HasPrefix(results[0].URL, "https://example.com/") || results[0].Snippet != "Snippet one" {
|
||||
if results[0].Title != "Example One" || !strings.HasPrefix(results[0].URL, "https://example.com/") ||
|
||||
results[0].Snippet != "Snippet one" {
|
||||
t.Fatalf("unexpected first result: %+v", results[0])
|
||||
}
|
||||
if results[1].Title != "Example Two" || !strings.HasPrefix(results[1].URL, "https://example.org/") || results[1].Snippet != "Snippet two" {
|
||||
if results[1].Title != "Example Two" || !strings.HasPrefix(results[1].URL, "https://example.org/") ||
|
||||
results[1].Snippet != "Snippet two" {
|
||||
t.Fatalf("unexpected second result: %+v", results[1])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user