diff --git a/client/agent_example.go b/client/agent_example.go deleted file mode 100644 index 7261c101..00000000 --- a/client/agent_example.go +++ /dev/null @@ -1,291 +0,0 @@ -package client - -import ( - "context" - "fmt" - "log" - "time" -) - -// ExampleAgentQABasic demonstrates basic agent QA usage -func ExampleAgentQABasic() { - // Create client - client := NewClient("http://localhost:8080", WithTimeout(60*time.Second)) - - // Create a session - ctx := context.Background() - session, err := client.CreateSession(ctx, &CreateSessionRequest{ - KnowledgeBaseID: "your_kb_id", - SessionStrategy: &SessionStrategy{ - MaxRounds: 10, - EnableRewrite: false, - FallbackStrategy: "default", - EmbeddingTopK: 10, - }, - }) - if err != nil { - log.Fatalf("Failed to create session: %v", err) - } - - fmt.Printf("Session created: %s\n", session.ID) - - // Create agent session wrapper - agentSession := client.NewAgentSession(session.ID) - - // Ask a question - err = agentSession.Ask(ctx, "What is machine learning?", func(resp *AgentStreamResponse) error { - switch resp.ResponseType { - case AgentResponseTypeThinking: - if resp.Done { - fmt.Printf("Thinking: %s\n", resp.Content) - } - case AgentResponseTypeAnswer: - fmt.Print(resp.Content) // Print answer incrementally - if resp.Done { - fmt.Println() // New line at the end - } - } - return nil - }) - - if err != nil { - log.Fatalf("Agent QA failed: %v", err) - } -} - -// ExampleAgentQAWithToolTracking demonstrates tracking tool calls -func ExampleAgentQAWithToolTracking() { - client := NewClient("http://localhost:8080") - agentSession := client.NewAgentSession("existing_session_id") - - ctx := context.Background() - toolCalls := make([]string, 0) - - err := agentSession.Ask(ctx, "Search for information about neural networks", func(resp *AgentStreamResponse) error { - switch resp.ResponseType { - case AgentResponseTypeToolCall: - if resp.Data != nil { - if toolName, ok := resp.Data["tool_name"].(string); ok { - toolCalls = append(toolCalls, toolName) - fmt.Printf("Tool called: %s\n", toolName) - } - } - case AgentResponseTypeToolResult: - fmt.Printf("Tool result: %s\n", resp.Content) - case AgentResponseTypeAnswer: - if resp.Done { - fmt.Printf("Final answer: %s\n", resp.Content) - } - } - return nil - }) - - if err != nil { - log.Fatalf("Error: %v", err) - } - - fmt.Printf("Total tool calls: %d\n", len(toolCalls)) -} - -// ExampleAgentQAWithReferences demonstrates capturing knowledge references -func ExampleAgentQAWithReferences() { - client := NewClient("http://localhost:8080") - agentSession := client.NewAgentSession("existing_session_id") - - ctx := context.Background() - var references []*SearchResult - var finalAnswer string - - err := agentSession.Ask(ctx, "Explain deep learning", func(resp *AgentStreamResponse) error { - switch resp.ResponseType { - case AgentResponseTypeReferences: - if resp.KnowledgeReferences != nil { - references = append(references, resp.KnowledgeReferences...) - fmt.Printf("Found %d references\n", len(resp.KnowledgeReferences)) - } - case AgentResponseTypeAnswer: - finalAnswer += resp.Content - } - return nil - }) - - if err != nil { - log.Fatalf("Error: %v", err) - } - - // Process results - fmt.Println("Final Answer:", finalAnswer) - fmt.Printf("\nBased on %d knowledge references:\n", len(references)) - for i, ref := range references { - fmt.Printf("%d. [Score: %.3f] %s\n", i+1, ref.Score, ref.KnowledgeTitle) - } -} - -// ExampleAgentQAWithFullEventTracking demonstrates comprehensive event tracking -func ExampleAgentQAWithFullEventTracking() { - client := NewClient("http://localhost:8080") - agentSession := client.NewAgentSession("existing_session_id") - - ctx := context.Background() - - // Tracking state - state := struct { - thinking string - toolCalls []map[string]interface{} - toolResults []string - references []*SearchResult - answer string - reflections []string - errors []string - }{} - - err := agentSession.Ask(ctx, "Your question here", func(resp *AgentStreamResponse) error { - switch resp.ResponseType { - case AgentResponseTypeThinking: - state.thinking += resp.Content - if resp.Done { - fmt.Printf("💭 Thinking: %s\n", state.thinking) - } - - case AgentResponseTypeToolCall: - toolCall := map[string]interface{}{ - "name": resp.Data["tool_name"], - "arguments": resp.Data["arguments"], - } - state.toolCalls = append(state.toolCalls, toolCall) - fmt.Printf("🔧 Tool Call: %v\n", resp.Data["tool_name"]) - - case AgentResponseTypeToolResult: - state.toolResults = append(state.toolResults, resp.Content) - success := "✓" - if resp.Data != nil { - if s, ok := resp.Data["success"].(bool); ok && !s { - success = "✗" - } - } - fmt.Printf("%s Tool Result: %s\n", success, resp.Content) - - case AgentResponseTypeReferences: - if resp.KnowledgeReferences != nil { - state.references = append(state.references, resp.KnowledgeReferences...) - fmt.Printf("📚 References: %d\n", len(resp.KnowledgeReferences)) - } - - case AgentResponseTypeAnswer: - state.answer += resp.Content - if resp.Done { - fmt.Printf("📝 Answer: %s\n", state.answer) - } - - case AgentResponseTypeReflection: - if resp.Done { - state.reflections = append(state.reflections, resp.Content) - fmt.Printf("🤔 Reflection: %s\n", resp.Content) - } - - case AgentResponseTypeError: - state.errors = append(state.errors, resp.Content) - fmt.Printf("❌ Error: %s\n", resp.Content) - } - - return nil - }) - - if err != nil { - log.Fatalf("Error: %v", err) - } - - // Print summary - fmt.Println("\n=== Summary ===") - fmt.Printf("Tool Calls: %d\n", len(state.toolCalls)) - fmt.Printf("References: %d\n", len(state.references)) - fmt.Printf("Reflections: %d\n", len(state.reflections)) - fmt.Printf("Errors: %d\n", len(state.errors)) -} - -// ExampleAgentQAWithCustomErrorHandling demonstrates custom error handling -func ExampleAgentQAWithCustomErrorHandling() { - client := NewClient("http://localhost:8080") - agentSession := client.NewAgentSession("existing_session_id") - - ctx := context.Background() - hasError := false - - err := agentSession.Ask(ctx, "Your question", func(resp *AgentStreamResponse) error { - if resp.ResponseType == AgentResponseTypeError { - hasError = true - // Log error to your monitoring system - fmt.Printf("Agent error occurred: %s\n", resp.Content) - // You can return an error here to stop processing - // return fmt.Errorf("stopping due to error: %s", resp.Content) - } - return nil - }) - - if err != nil { - log.Printf("Stream error: %v", err) - } - - if hasError { - log.Println("Agent encountered errors during processing") - } -} - -// ExampleAgentQAStreamCancellation demonstrates canceling a stream -func ExampleAgentQAStreamCancellation() { - client := NewClient("http://localhost:8080") - agentSession := client.NewAgentSession("existing_session_id") - - // Create a context with timeout - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - - // Or cancel based on a condition - maxToolCalls := 5 - toolCallCount := 0 - - err := agentSession.Ask(ctx, "Complex query that might take long", func(resp *AgentStreamResponse) error { - if resp.ResponseType == AgentResponseTypeToolCall { - toolCallCount++ - if toolCallCount > maxToolCalls { - // Stop processing if too many tool calls - return fmt.Errorf("too many tool calls: %d", toolCallCount) - } - } - return nil - }) - - if err != nil { - log.Printf("Stream stopped: %v", err) - } -} - -// ExampleMultipleAgentSessions demonstrates managing multiple agent sessions -func ExampleMultipleAgentSessions() { - client := NewClient("http://localhost:8080") - - ctx := context.Background() - - // Create multiple sessions for different purposes - sessions := map[string]*AgentSession{ - "technical": client.NewAgentSession("session_id_1"), - "general": client.NewAgentSession("session_id_2"), - "customer": client.NewAgentSession("session_id_3"), - } - - // Use appropriate session based on query type - queryType := "technical" - query := "How does gradient descent work?" - - if session, ok := sessions[queryType]; ok { - err := session.Ask(ctx, query, func(resp *AgentStreamResponse) error { - if resp.ResponseType == AgentResponseTypeAnswer && resp.Done { - fmt.Printf("[%s] Answer: %s\n", queryType, resp.Content) - } - return nil - }) - if err != nil { - log.Printf("Error in %s session: %v", queryType, err) - } - } -} diff --git a/client/tenant.go b/client/tenant.go index e2f80692..4f80cbcd 100644 --- a/client/tenant.go +++ b/client/tenant.go @@ -73,7 +73,7 @@ func (c *Client) CreateTenant(ctx context.Context, tenant *Tenant) (*Tenant, err } // GetTenant retrieves a tenant by ID -func (c *Client) GetTenant(ctx context.Context, tenantID uint) (*Tenant, error) { +func (c *Client) GetTenant(ctx context.Context, tenantID uint64) (*Tenant, error) { path := fmt.Sprintf("/api/v1/tenants/%d", tenantID) resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil) if err != nil { @@ -105,7 +105,7 @@ func (c *Client) UpdateTenant(ctx context.Context, tenant *Tenant) (*Tenant, err } // DeleteTenant removes a tenant by ID -func (c *Client) DeleteTenant(ctx context.Context, tenantID uint) error { +func (c *Client) DeleteTenant(ctx context.Context, tenantID uint64) error { path := fmt.Sprintf("/api/v1/tenants/%d", tenantID) resp, err := c.doRequest(ctx, http.MethodDelete, path, nil, nil) if err != nil { diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index 81e01cae..71e3b3db 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -233,6 +233,9 @@ const isInCreatChat = computed(() => { return route.name === 'globalCreatChat' || route.name === 'kbCreatChat'; }); +// 是否在对话详情页 +const isInChatDetail = computed(() => route.name === 'chat'); + // 统一的菜单项激活状态判断 const isMenuItemActive = (itemPath: string): boolean => { const currentRoute = route.name; @@ -301,11 +304,16 @@ const handleFaqSelectionChanged = ((event: CustomEvent<{ count: number; enabledC selectedFaqDisabledCount.value = event.detail?.disabledCount || 0 }) as EventListener -const showKbActions = computed(() => (isInKnowledgeBase.value && !!currentKbInfo.value) || isInKnowledgeBaseList.value || isInCreatChat.value) +const showKbActions = computed(() => + (isInKnowledgeBase.value && !!currentKbInfo.value) || + isInKnowledgeBaseList.value || + isInCreatChat.value || + isInChatDetail.value +) const currentKbType = computed(() => currentKbInfo.value?.type || 'document') const showDocActions = computed(() => showKbActions.value && isInKnowledgeBase.value && currentKbType.value !== 'faq') const showFaqActions = computed(() => showKbActions.value && isInKnowledgeBase.value && currentKbType.value === 'faq') -const showCreateKbAction = computed(() => showKbActions.value && (isInKnowledgeBaseList.value || isInCreatChat.value)) +const showCreateKbAction = computed(() => showKbActions.value && (isInKnowledgeBaseList.value || isInCreatChat.value || isInChatDetail.value)) // 时间分组函数 const getTimeCategory = (dateStr: string): string => { diff --git a/frontend/src/hooks/useKnowledgeBaseCreationNavigation.ts b/frontend/src/hooks/useKnowledgeBaseCreationNavigation.ts new file mode 100644 index 00000000..117c5d03 --- /dev/null +++ b/frontend/src/hooks/useKnowledgeBaseCreationNavigation.ts @@ -0,0 +1,22 @@ +import { useRouter } from 'vue-router' + +/** + * Provides a shared navigation helper for knowledge-base creation success. + * Redirects to the knowledge-base list page and highlights the newly created KB. + */ +export const useKnowledgeBaseCreationNavigation = () => { + const router = useRouter() + + const navigateToKnowledgeBaseList = (kbId: string) => { + if (!kbId) return + router.push({ + path: '/platform/knowledge-bases', + query: { highlightKbId: kbId }, + }) + } + + return { + navigateToKnowledgeBaseList, + } +} + diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 4ba33619..b44b8b04 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -31,6 +31,14 @@ > + diff --git a/internal/agent/tools/database_query.go b/internal/agent/tools/database_query.go index 734f4fb6..8bc3e708 100644 --- a/internal/agent/tools/database_query.go +++ b/internal/agent/tools/database_query.go @@ -17,11 +17,11 @@ import ( type DatabaseQueryTool struct { BaseTool db *gorm.DB - tenantID uint + tenantID uint64 } // NewDatabaseQueryTool creates a new database query tool -func NewDatabaseQueryTool(db *gorm.DB, tenantID uint) *DatabaseQueryTool { +func NewDatabaseQueryTool(db *gorm.DB, tenantID uint64) *DatabaseQueryTool { description := `Execute SQL queries to retrieve information from the database. ## Security Features diff --git a/internal/agent/tools/get_document_info.go b/internal/agent/tools/get_document_info.go index 87ff93f0..0ba069c6 100644 --- a/internal/agent/tools/get_document_info.go +++ b/internal/agent/tools/get_document_info.go @@ -12,14 +12,14 @@ import ( // GetDocumentInfoTool retrieves detailed information about a document/knowledge type GetDocumentInfoTool struct { BaseTool - tenantID uint + tenantID uint64 knowledgeService interfaces.KnowledgeService chunkService interfaces.ChunkService } // NewGetDocumentInfoTool creates a new get document info tool func NewGetDocumentInfoTool( - tenantID uint, + tenantID uint64, knowledgeService interfaces.KnowledgeService, chunkService interfaces.ChunkService, ) *GetDocumentInfoTool { diff --git a/internal/agent/tools/grep_chunks.go b/internal/agent/tools/grep_chunks.go index a049b348..e667243a 100644 --- a/internal/agent/tools/grep_chunks.go +++ b/internal/agent/tools/grep_chunks.go @@ -17,12 +17,12 @@ import ( type GrepChunksTool struct { BaseTool db *gorm.DB - tenantID uint + tenantID uint64 knowledgeBaseIDs []string } // NewGrepChunksTool creates a new grep chunks tool -func NewGrepChunksTool(db *gorm.DB, tenantID uint, knowledgeBaseIDs []string) *GrepChunksTool { +func NewGrepChunksTool(db *gorm.DB, tenantID uint64, knowledgeBaseIDs []string) *GrepChunksTool { description := `Unix-style text pattern matching tool for knowledge base chunks. Searches for text patterns in chunk content, similar to the Unix grep command. diff --git a/internal/agent/tools/knowledge_search.go b/internal/agent/tools/knowledge_search.go index b89669be..36edfa5d 100644 --- a/internal/agent/tools/knowledge_search.go +++ b/internal/agent/tools/knowledge_search.go @@ -32,7 +32,7 @@ type KnowledgeSearchTool struct { BaseTool knowledgeBaseService interfaces.KnowledgeBaseService chunkService interfaces.ChunkService - tenantID uint + tenantID uint64 allowedKBs []string rerankModel rerank.Reranker chatModel chat.Chat // Optional chat model for LLM-based reranking @@ -43,7 +43,7 @@ type KnowledgeSearchTool struct { func NewKnowledgeSearchTool( knowledgeBaseService interfaces.KnowledgeBaseService, chunkService interfaces.ChunkService, - tenantID uint, + tenantID uint64, allowedKBs []string, rerankModel rerank.Reranker, chatModel chat.Chat, diff --git a/internal/agent/tools/list_knowledge_chunks.go b/internal/agent/tools/list_knowledge_chunks.go index 3b8887f6..4bcfd921 100644 --- a/internal/agent/tools/list_knowledge_chunks.go +++ b/internal/agent/tools/list_knowledge_chunks.go @@ -12,14 +12,14 @@ import ( // ListKnowledgeChunksTool retrieves chunk snapshots for a specific knowledge document. type ListKnowledgeChunksTool struct { BaseTool - tenantID uint + tenantID uint64 chunkService interfaces.ChunkService knowledgeService interfaces.KnowledgeService } // NewListKnowledgeChunksTool creates a new tool instance. func NewListKnowledgeChunksTool( - tenantID uint, + tenantID uint64, knowledgeService interfaces.KnowledgeService, chunkService interfaces.ChunkService, ) *ListKnowledgeChunksTool { diff --git a/internal/agent/tools/web_search.go b/internal/agent/tools/web_search.go index 373a0f00..3fe776de 100644 --- a/internal/agent/tools/web_search.go +++ b/internal/agent/tools/web_search.go @@ -124,8 +124,8 @@ func (t *WebSearchTool) Execute(ctx context.Context, args map[string]interface{} logger.Infof(ctx, "[Tool][WebSearch] Searching with query: %s, max_results: %d", query, t.maxResults) // Get tenant ID from context - tenantID := uint(0) - if tid, ok := ctx.Value(types.TenantIDContextKey).(uint); ok { + tenantID := uint64(0) + if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok { tenantID = tid } diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go index bd4bf889..5cc90f11 100644 --- a/internal/application/repository/chunk.go +++ b/internal/application/repository/chunk.go @@ -29,7 +29,7 @@ func (r *chunkRepository) CreateChunks(ctx context.Context, chunks []*types.Chun } // GetChunkByID retrieves a chunk by its ID and tenant ID -func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint, id string) (*types.Chunk, error) { +func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint64, id string) (*types.Chunk, error) { var chunk types.Chunk if err := r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).First(&chunk).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -42,7 +42,7 @@ func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint, id st // ListChunksByID retrieves multiple chunks by their IDs func (r *chunkRepository) ListChunksByID( - ctx context.Context, tenantID uint, ids []string, + ctx context.Context, tenantID uint64, ids []string, ) ([]*types.Chunk, error) { var chunks []*types.Chunk if err := r.db.Debug().WithContext(ctx). @@ -55,7 +55,7 @@ func (r *chunkRepository) ListChunksByID( // ListChunksByKnowledgeID lists all chunks for a knowledge ID func (r *chunkRepository) ListChunksByKnowledgeID( - ctx context.Context, tenantID uint, knowledgeID string, + ctx context.Context, tenantID uint64, knowledgeID string, ) ([]*types.Chunk, error) { var chunks []*types.Chunk if err := r.db.WithContext(ctx). @@ -71,7 +71,7 @@ func (r *chunkRepository) ListChunksByKnowledgeID( // ListPagedChunksByKnowledgeID lists chunks for a knowledge ID with pagination func (r *chunkRepository) ListPagedChunksByKnowledgeID( ctx context.Context, - tenantID uint, + tenantID uint64, knowledgeID string, page *types.Pagination, chunkType []types.ChunkType, @@ -112,7 +112,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID( return chunks, total, nil } -func (r *chunkRepository) ListChunkByParentID(ctx context.Context, tenantID uint, 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). @@ -139,12 +139,12 @@ func (r *chunkRepository) UpdateChunks(ctx context.Context, chunks []*types.Chun } // DeleteChunk deletes a chunk by its ID -func (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint, id string) error { +func (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint64, id string) error { return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Chunk{}).Error } // DeleteChunks deletes chunks by IDs in batch -func (r *chunkRepository) DeleteChunks(ctx context.Context, tenantID uint, ids []string) error { +func (r *chunkRepository) DeleteChunks(ctx context.Context, tenantID uint64, ids []string) error { if len(ids) == 0 { return nil } @@ -152,21 +152,21 @@ func (r *chunkRepository) DeleteChunks(ctx context.Context, tenantID uint, ids [ } // DeleteChunksByKnowledgeID deletes all chunks for a knowledge ID -func (r *chunkRepository) DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) error { +func (r *chunkRepository) DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) error { return r.db.WithContext(ctx).Where( "tenant_id = ? AND knowledge_id = ?", tenantID, knowledgeID, ).Delete(&types.Chunk{}).Error } // DeleteByKnowledgeList deletes all chunks for a knowledge list -func (r *chunkRepository) DeleteByKnowledgeList(ctx context.Context, tenantID uint, knowledgeIDs []string) error { +func (r *chunkRepository) DeleteByKnowledgeList(ctx context.Context, tenantID uint64, knowledgeIDs []string) error { return r.db.WithContext(ctx).Where( "tenant_id = ? AND knowledge_id in ?", tenantID, knowledgeIDs, ).Delete(&types.Chunk{}).Error } // CountChunksByKnowledgeBaseID counts the number of chunks in a knowledge base -func (r *chunkRepository) CountChunksByKnowledgeBaseID(ctx context.Context, tenantID uint, 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 +175,7 @@ func (r *chunkRepository) CountChunksByKnowledgeBaseID(ctx context.Context, tena } // DeleteUnindexedChunks by knowledge id and chunk index range -func (r *chunkRepository) DeleteUnindexedChunks(ctx context.Context, tenantID uint, 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 +194,7 @@ 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 uint, 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 diff --git a/internal/application/repository/knowledge.go b/internal/application/repository/knowledge.go index 84f1aabc..8a6b0bb5 100644 --- a/internal/application/repository/knowledge.go +++ b/internal/application/repository/knowledge.go @@ -28,7 +28,7 @@ func (r *knowledgeRepository) CreateKnowledge(ctx context.Context, knowledge *ty } // GetKnowledgeByID gets knowledge -func (r *knowledgeRepository) GetKnowledgeByID(ctx context.Context, tenantID uint, 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) { @@ -41,7 +41,7 @@ func (r *knowledgeRepository) GetKnowledgeByID(ctx context.Context, tenantID uin // ListKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID( - ctx context.Context, tenantID uint, kbID string, + ctx context.Context, tenantID uint64, kbID string, ) ([]*types.Knowledge, error) { var knowledges []*types.Knowledge if err := r.db.WithContext(ctx).Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID). @@ -54,7 +54,7 @@ func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID( // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID( ctx context.Context, - tenantID uint, + tenantID uint64, kbID string, page *types.Pagination, tagID string, @@ -106,18 +106,18 @@ func (r *knowledgeRepository) UpdateKnowledgeBatch(ctx context.Context, knowledg } // DeleteKnowledge deletes knowledge -func (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint, id string) error { +func (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint64, id string) error { return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Knowledge{}).Error } // DeleteKnowledge deletes knowledge -func (r *knowledgeRepository) DeleteKnowledgeList(ctx context.Context, tenantID uint, ids []string) error { +func (r *knowledgeRepository) DeleteKnowledgeList(ctx context.Context, tenantID uint64, ids []string) error { return r.db.WithContext(ctx).Where("tenant_id = ? AND id in ?", tenantID, ids).Delete(&types.Knowledge{}).Error } // GetKnowledgeBatch gets knowledge in batch func (r *knowledgeRepository) GetKnowledgeBatch( - ctx context.Context, tenantID uint, ids []string, + ctx context.Context, tenantID uint64, ids []string, ) ([]*types.Knowledge, error) { var knowledge []*types.Knowledge if err := r.db.WithContext(ctx).Debug(). @@ -131,7 +131,7 @@ func (r *knowledgeRepository) GetKnowledgeBatch( // CheckKnowledgeExists checks if knowledge already exists func (r *knowledgeRepository) CheckKnowledgeExists( ctx context.Context, - tenantID uint, + tenantID uint64, kbID string, params *types.KnowledgeCheckParams, ) (bool, *types.Knowledge, error) { @@ -199,8 +199,8 @@ func (r *knowledgeRepository) CheckKnowledgeExists( func (r *knowledgeRepository) AminusB( ctx context.Context, - Atenant uint, A string, - Btenant uint, B string, + Atenant uint64, A string, + Btenant uint64, B string, ) ([]string, error) { knowledgeIDs := []string{} subQuery := r.db.Model(&types.Knowledge{}). @@ -222,7 +222,7 @@ func (r *knowledgeRepository) UpdateKnowledgeColumn(ctx context.Context, id stri } // CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base -func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint, 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). @@ -233,7 +233,7 @@ func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(ctx context.Contex // CountKnowledgeByStatus counts the number of knowledge items with the specified parse status func (r *knowledgeRepository) CountKnowledgeByStatus( ctx context.Context, - tenantID uint, + tenantID uint64, kbID string, parseStatuses []string, ) (int64, error) { diff --git a/internal/application/repository/knowledgebase.go b/internal/application/repository/knowledgebase.go index 749c208a..36e12518 100644 --- a/internal/application/repository/knowledgebase.go +++ b/internal/application/repository/knowledgebase.go @@ -49,7 +49,7 @@ func (r *knowledgeBaseRepository) ListKnowledgeBases(ctx context.Context) ([]*ty // ListKnowledgeBasesByTenantID lists all knowledge bases by tenant id func (r *knowledgeBaseRepository) ListKnowledgeBasesByTenantID( - ctx context.Context, tenantID uint, + ctx context.Context, tenantID uint64, ) ([]*types.KnowledgeBase, error) { var kbs []*types.KnowledgeBase if err := r.db.WithContext(ctx).Where("tenant_id = ? AND is_temporary = ?", tenantID, false). diff --git a/internal/application/repository/mcp_service.go b/internal/application/repository/mcp_service.go index 5c0726bf..6da3803e 100644 --- a/internal/application/repository/mcp_service.go +++ b/internal/application/repository/mcp_service.go @@ -25,7 +25,7 @@ func (r *mcpServiceRepository) Create(ctx context.Context, service *types.MCPSer } // GetByID retrieves an MCP service by ID and tenant ID -func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error) { +func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.MCPService, error) { var service types.MCPService err := r.db.WithContext(ctx). Where("id = ? AND tenant_id = ?", id, tenantID). @@ -42,7 +42,7 @@ func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint, id st } // List retrieves all MCP services for a tenant -func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint) ([]*types.MCPService, error) { +func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) { var services []*types.MCPService err := r.db.WithContext(ctx). Where("tenant_id = ?", tenantID). @@ -57,7 +57,7 @@ func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint) ([]*type } // ListEnabled retrieves all enabled MCP services for a tenant -func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint) ([]*types.MCPService, error) { +func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) { var services []*types.MCPService err := r.db.WithContext(ctx). Where("tenant_id = ? AND enabled = ?", tenantID, true). @@ -72,7 +72,7 @@ func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint) ( } // ListByIDs retrieves MCP services by multiple IDs for a tenant -func (r *mcpServiceRepository) ListByIDs(ctx context.Context, tenantID uint, 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 } @@ -134,7 +134,7 @@ func (r *mcpServiceRepository) Update(ctx context.Context, service *types.MCPSer } // Delete deletes an MCP service (soft delete) -func (r *mcpServiceRepository) Delete(ctx context.Context, tenantID uint, id string) error { +func (r *mcpServiceRepository) Delete(ctx context.Context, tenantID uint64, id string) error { return r.db.WithContext(ctx). Where("id = ? AND tenant_id = ?", id, tenantID). Delete(&types.MCPService{}).Error diff --git a/internal/application/repository/model.go b/internal/application/repository/model.go index e5f4627f..72c25bf3 100644 --- a/internal/application/repository/model.go +++ b/internal/application/repository/model.go @@ -25,7 +25,7 @@ func (r *modelRepository) Create(ctx context.Context, m *types.Model) error { } // GetByID retrieves a model by ID -func (r *modelRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.Model, error) { +func (r *modelRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.Model, error) { var m types.Model if err := r.db.WithContext(ctx).Where("id = ?", id).Where( "tenant_id = ? OR is_builtin = true", tenantID, @@ -40,7 +40,7 @@ func (r *modelRepository) GetByID(ctx context.Context, tenantID uint, id string) // List lists models with optional filtering func (r *modelRepository) List( - ctx context.Context, tenantID uint, modelType types.ModelType, source types.ModelSource, + ctx context.Context, tenantID uint64, modelType types.ModelType, source types.ModelSource, ) ([]*types.Model, error) { var models []*types.Model query := r.db.WithContext(ctx).Where( @@ -71,7 +71,7 @@ func (r *modelRepository) Update(ctx context.Context, m *types.Model) error { } // Delete deletes a model -func (r *modelRepository) Delete(ctx context.Context, tenantID uint, id string) error { +func (r *modelRepository) Delete(ctx context.Context, tenantID uint64, id string) error { return r.db.WithContext(ctx).Where( "id = ? AND tenant_id = ?", id, tenantID, ).Delete(&types.Model{}).Error diff --git a/internal/application/repository/session.go b/internal/application/repository/session.go index b0f12feb..2219f1d3 100644 --- a/internal/application/repository/session.go +++ b/internal/application/repository/session.go @@ -31,7 +31,7 @@ func (r *sessionRepository) Create(ctx context.Context, session *types.Session) } // Get retrieves a session by ID -func (r *sessionRepository) Get(ctx context.Context, tenantID uint, id string) (*types.Session, error) { +func (r *sessionRepository) Get(ctx context.Context, tenantID uint64, id string) (*types.Session, error) { var session types.Session err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&session, "id = ?", id).Error if err != nil { @@ -41,7 +41,7 @@ func (r *sessionRepository) Get(ctx context.Context, tenantID uint, id string) ( } // GetByTenantID retrieves all sessions for a tenant -func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint) ([]*types.Session, error) { +func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint64) ([]*types.Session, error) { var sessions []*types.Session err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Order("created_at DESC").Find(&sessions).Error if err != nil { @@ -52,7 +52,7 @@ func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint) ([ // GetPagedByTenantID retrieves sessions for a tenant with pagination func (r *sessionRepository) GetPagedByTenantID( - ctx context.Context, tenantID uint, page *types.Pagination, + ctx context.Context, tenantID uint64, page *types.Pagination, ) ([]*types.Session, int64, error) { var sessions []*types.Session var total int64 @@ -84,6 +84,6 @@ func (r *sessionRepository) Update(ctx context.Context, session *types.Session) } // Delete deletes a session -func (r *sessionRepository) Delete(ctx context.Context, tenantID uint, id string) error { +func (r *sessionRepository) Delete(ctx context.Context, tenantID uint64, id string) error { return r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Delete(&types.Session{}, "id = ?", id).Error } diff --git a/internal/application/repository/tag.go b/internal/application/repository/tag.go index 7f8877f0..7f1857fe 100644 --- a/internal/application/repository/tag.go +++ b/internal/application/repository/tag.go @@ -25,7 +25,7 @@ func (r *knowledgeTagRepository) Update(ctx context.Context, tag *types.Knowledg return r.db.WithContext(ctx).Save(tag).Error } -func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.KnowledgeTag, error) { +func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.KnowledgeTag, error) { var tag types.KnowledgeTag if err := r.db.WithContext(ctx). Where("tenant_id = ? AND id = ?", tenantID, id). @@ -35,7 +35,7 @@ func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint, id return &tag, nil } -func (r *knowledgeTagRepository) ListByKB(ctx context.Context, tenantID uint, 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). @@ -46,7 +46,7 @@ func (r *knowledgeTagRepository) ListByKB(ctx context.Context, tenantID uint, kb return tags, nil } -func (r *knowledgeTagRepository) Delete(ctx context.Context, tenantID uint, id string) error { +func (r *knowledgeTagRepository) Delete(ctx context.Context, tenantID uint64, id string) error { return r.db.WithContext(ctx). Where("tenant_id = ? AND id = ?", tenantID, id). Delete(&types.KnowledgeTag{}).Error @@ -55,7 +55,7 @@ func (r *knowledgeTagRepository) Delete(ctx context.Context, tenantID uint, id s // CountReferences returns how many knowledges and chunks reference this tag. func (r *knowledgeTagRepository) CountReferences( ctx context.Context, - tenantID uint, + tenantID uint64, kbID string, tagID string, ) (knowledgeCount int64, chunkCount int64, err error) { diff --git a/internal/application/repository/tenant.go b/internal/application/repository/tenant.go index 2faf007b..e44cd4e4 100644 --- a/internal/application/repository/tenant.go +++ b/internal/application/repository/tenant.go @@ -32,7 +32,7 @@ func (r *tenantRepository) CreateTenant(ctx context.Context, tenant *types.Tenan } // GetTenantByID gets tenant by ID -func (r *tenantRepository) GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) { +func (r *tenantRepository) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) { var tenant types.Tenant if err := r.db.WithContext(ctx).Where("id = ?", id).First(&tenant).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -58,11 +58,11 @@ func (r *tenantRepository) UpdateTenant(ctx context.Context, tenant *types.Tenan } // DeleteTenant deletes tenant -func (r *tenantRepository) DeleteTenant(ctx context.Context, id uint) error { +func (r *tenantRepository) DeleteTenant(ctx context.Context, id uint64) error { return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Tenant{}).Error } -func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint, delta int64) error { +func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint64, delta int64) error { return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { var tenant types.Tenant // 使用悲观锁确保并发安全 diff --git a/internal/application/repository/user.go b/internal/application/repository/user.go index 94d0d622..cfe30401 100644 --- a/internal/application/repository/user.go +++ b/internal/application/repository/user.go @@ -4,16 +4,15 @@ import ( "context" "errors" - "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "gorm.io/gorm" ) var ( - ErrUserNotFound = errors.New("user not found") + ErrUserNotFound = errors.New("user not found") ErrUserAlreadyExists = errors.New("user already exists") - ErrTokenNotFound = errors.New("token not found") + ErrTokenNotFound = errors.New("token not found") ) // userRepository implements user repository interface @@ -28,7 +27,6 @@ func NewUserRepository(db *gorm.DB) interfaces.UserRepository { // CreateUser creates a user func (r *userRepository) CreateUser(ctx context.Context, user *types.User) error { - logger.Infof(ctx, "Creating user in database: %s", user.Email) return r.db.WithContext(ctx).Create(user).Error } @@ -82,15 +80,15 @@ func (r *userRepository) DeleteUser(ctx context.Context, id string) error { func (r *userRepository) ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error) { var users []*types.User query := r.db.WithContext(ctx).Order("created_at DESC") - + if limit > 0 { query = query.Limit(limit) } - + if offset > 0 { query = query.Offset(offset) } - + if err := query.Find(&users).Error; err != nil { return nil, err } @@ -151,4 +149,4 @@ func (r *authTokenRepository) DeleteExpiredTokens(ctx context.Context) error { // RevokeTokensByUserID revokes all tokens for a user func (r *authTokenRepository) RevokeTokensByUserID(ctx context.Context, userID string) error { return r.db.WithContext(ctx).Model(&types.AuthToken{}).Where("user_id = ?", userID).Update("is_revoked", true).Error -} \ No newline at end of file +} diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index ca17e6d0..bf25a26f 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -95,8 +95,8 @@ func (s *agentService) CreateAgentEngine( } // Register MCP tools from enabled services for this tenant - tenantID := uint(0) - if tid, ok := ctx.Value(types.TenantIDContextKey).(uint); ok { + tenantID := uint64(0) + if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok { tenantID = tid } if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil { @@ -108,7 +108,7 @@ func (s *agentService) CreateAgentEngine( // Filter enabled services enabledServices := make([]*types.MCPService, 0) for _, svc := range mcpServices { - if svc.Enabled { + if svc != nil && svc.Enabled { enabledServices = append(enabledServices, svc) } } @@ -179,8 +179,8 @@ func (s *agentService) registerTools( } // Get tenant ID from context - tenantID := uint(0) - if tid, ok := ctx.Value(types.TenantIDContextKey).(uint); ok { + tenantID := uint64(0) + 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) diff --git a/internal/application/service/chat_pipline/merge.go b/internal/application/service/chat_pipline/merge.go index 0442d75c..f7ed48f9 100644 --- a/internal/application/service/chat_pipline/merge.go +++ b/internal/application/service/chat_pipline/merge.go @@ -217,7 +217,7 @@ func (p *PluginMerge) populateFAQAnswers(ctx context.Context, chatManage *types. return results } - tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint) + tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint64) if tenantID == 0 && chatManage != nil { tenantID = chatManage.TenantID } @@ -342,7 +342,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors(ctx context.Context, chatM return results } - tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint) + tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint64) if tenantID == 0 && chatManage != nil { tenantID = chatManage.TenantID } @@ -626,7 +626,7 @@ func containsID(ids []string, target string) bool { return false } -func (p *PluginMerge) fetchChunksIfMissing(ctx context.Context, tenantID uint, 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 == "" { diff --git a/internal/application/service/chat_pipline/search_entity.go b/internal/application/service/chat_pipline/search_entity.go index cc449470..3f7ffb2f 100644 --- a/internal/application/service/chat_pipline/search_entity.go +++ b/internal/application/service/chat_pipline/search_entity.go @@ -100,7 +100,7 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context, logger.Infof(ctx, "No new chunk found") return next() } - chunks, err := p.chunkRepo.ListChunksByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), chunkIDs) + chunks, err := p.chunkRepo.ListChunksByID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), chunkIDs) if err != nil { logger.Errorf(ctx, "Failed to list chunks, session_id: %s, error: %v", chatManage.SessionID, err) return next() @@ -109,7 +109,7 @@ 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).(uint), 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() diff --git a/internal/application/service/chunk.go b/internal/application/service/chunk.go index 746d0be6..7f473cff 100644 --- a/internal/application/service/chunk.go +++ b/internal/application/service/chunk.go @@ -82,7 +82,7 @@ func (s *chunkService) CreateChunks(ctx context.Context, chunks []*types.Chunk) // - *types.Chunk: Retrieved chunk if found // - error: Any error encountered during retrieval func (s *chunkService) GetChunkByID(ctx context.Context, id string) (*types.Chunk, error) { - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Getting chunk by ID, ID: %s, tenant ID: %d", id, tenantID) chunk, err := s.chunkRepository.GetChunkByID(ctx, tenantID, id) if err != nil { @@ -110,7 +110,7 @@ func (s *chunkService) ListChunksByKnowledgeID(ctx context.Context, knowledgeID logger.Info(ctx, "Start listing chunks by knowledge ID") logger.Infof(ctx, "Knowledge ID: %s", knowledgeID) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) chunks, err := s.chunkRepository.ListChunksByKnowledgeID(ctx, tenantID, knowledgeID) @@ -142,7 +142,7 @@ func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context, logger.Info(ctx, "Start listing paged chunks by knowledge ID") logger.Infof(ctx, "Knowledge ID: %s, page: %d, page size: %d", knowledgeID, page.Page, page.PageSize) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) chunks, total, err := s.chunkRepository.ListPagedChunksByKnowledgeID(ctx, tenantID, knowledgeID, page, chunkType, "") if err != nil { @@ -218,7 +218,7 @@ func (s *chunkService) DeleteChunk(ctx context.Context, id string) error { logger.Info(ctx, "Start deleting chunk") logger.Infof(ctx, "Deleting chunk, ID: %s", id) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) err := s.chunkRepository.DeleteChunk(ctx, tenantID, id) @@ -249,7 +249,7 @@ func (s *chunkService) DeleteChunks(ctx context.Context, ids []string) error { logger.Info(ctx, "Start deleting chunks in batch") logger.Infof(ctx, "Deleting %d chunks", len(ids)) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) err := s.chunkRepository.DeleteChunks(ctx, tenantID, ids) @@ -277,7 +277,7 @@ func (s *chunkService) DeleteChunksByKnowledgeID(ctx context.Context, knowledgeI logger.Info(ctx, "Start deleting all chunks by knowledge ID") logger.Infof(ctx, "Knowledge ID: %s", knowledgeID) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) err := s.chunkRepository.DeleteChunksByKnowledgeID(ctx, tenantID, knowledgeID) @@ -297,7 +297,7 @@ func (s *chunkService) DeleteByKnowledgeList(ctx context.Context, ids []string) logger.Info(ctx, "Start deleting all chunks by knowledge IDs") logger.Infof(ctx, "Knowledge IDs: %v", ids) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) err := s.chunkRepository.DeleteByKnowledgeList(ctx, tenantID, ids) @@ -313,7 +313,7 @@ func (s *chunkService) DeleteByKnowledgeList(ctx context.Context, ids []string) return nil } -func (s *chunkService) ListChunkByParentID(ctx context.Context, tenantID uint, 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) diff --git a/internal/application/service/evaluation.go b/internal/application/service/evaluation.go index fd3b4157..a5b60270 100644 --- a/internal/application/service/evaluation.go +++ b/internal/application/service/evaluation.go @@ -109,7 +109,7 @@ func (e *EvaluationService) EvaluationResult(ctx context.Context, taskID string) return nil, err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof( ctx, "Checking tenant ID match, task tenant ID: %d, current tenant ID: %d", @@ -138,7 +138,7 @@ func (e *EvaluationService) Evaluation(ctx context.Context, datasetID, knowledgeBaseID, chatModelID, rerankModelID) // Get tenant ID from context for multi-tenancy support - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) // Handle knowledge base creation if not provided @@ -154,6 +154,9 @@ func (e *EvaluationService) Evaluation(ctx context.Context, var embeddingModelID, llmModelID string for _, model := range models { + if model == nil { + continue + } if model.Type == types.ModelTypeEmbedding { embeddingModelID = model.ID } @@ -212,6 +215,9 @@ func (e *EvaluationService) Evaluation(ctx context.Context, models, err := e.modelService.ListModels(ctx) if err == nil { for _, model := range models { + if model == nil { + continue + } if model.Type == types.ModelTypeRerank { rerankModelID = model.ID break @@ -230,6 +236,9 @@ func (e *EvaluationService) Evaluation(ctx context.Context, models, err := e.modelService.ListModels(ctx) if err == nil { for _, model := range models { + if model == nil { + continue + } if model.Type == types.ModelTypeKnowledgeQA { chatModelID = model.ID break diff --git a/internal/application/service/extract.go b/internal/application/service/extract.go index cd898911..ff35479d 100644 --- a/internal/application/service/extract.go +++ b/internal/application/service/extract.go @@ -16,7 +16,7 @@ import ( "github.com/hibiken/asynq" ) -func NewChunkExtractTask(ctx context.Context, client *asynq.Client, tenantID uint, 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 diff --git a/internal/application/service/file/cos.go b/internal/application/service/file/cos.go index 69c817ff..8d921b21 100644 --- a/internal/application/service/file/cos.go +++ b/internal/application/service/file/cos.go @@ -46,7 +46,7 @@ func NewCosFileService(bucketName, region, secretId, secretKey, cosPathPrefix st // SaveFile saves a file to COS storage // It generates a unique name for the file and organizes it by tenant and knowledge ID func (s *cosFileService) SaveFile(ctx context.Context, - file *multipart.FileHeader, tenantID uint, knowledgeID string, + file *multipart.FileHeader, tenantID uint64, knowledgeID string, ) (string, error) { ext := filepath.Ext(file.Filename) objectName := fmt.Sprintf("%s/%d/%s/%s%s", s.cosPathPrefix, tenantID, knowledgeID, uuid.New().String(), ext) diff --git a/internal/application/service/file/dummy.go b/internal/application/service/file/dummy.go index 3c9e5ce9..c7bee75a 100644 --- a/internal/application/service/file/dummy.go +++ b/internal/application/service/file/dummy.go @@ -22,7 +22,7 @@ func NewDummyFileService() interfaces.FileService { // SaveFile pretends to save a file but just returns a random UUID // This is useful for testing without actual file operations func (s *DummyFileService) SaveFile(ctx context.Context, - file *multipart.FileHeader, tenantID uint, knowledgeID string, + file *multipart.FileHeader, tenantID uint64, knowledgeID string, ) (string, error) { return uuid.New().String(), nil } diff --git a/internal/application/service/file/local.go b/internal/application/service/file/local.go index de2c6821..7174dcef 100644 --- a/internal/application/service/file/local.go +++ b/internal/application/service/file/local.go @@ -29,7 +29,7 @@ func NewLocalFileService(baseDir string) interfaces.FileService { // The file is stored in a directory structure: baseDir/tenantID/knowledgeID/filename // Returns the full file path or an error if saving fails func (s *localFileService) SaveFile(ctx context.Context, - file *multipart.FileHeader, tenantID uint, knowledgeID string, + file *multipart.FileHeader, tenantID uint64, knowledgeID string, ) (string, error) { logger.Info(ctx, "Starting to save file locally") logger.Infof(ctx, "File information: name=%s, size=%d, tenant ID=%d, knowledge ID=%s", diff --git a/internal/application/service/file/minio.go b/internal/application/service/file/minio.go index af2141f6..a2841908 100644 --- a/internal/application/service/file/minio.go +++ b/internal/application/service/file/minio.go @@ -52,7 +52,7 @@ func NewMinioFileService(endpoint, // SaveFile saves a file to MinIO func (s *minioFileService) SaveFile(ctx context.Context, - file *multipart.FileHeader, tenantID uint, knowledgeID string, + file *multipart.FileHeader, tenantID uint64, knowledgeID string, ) (string, error) { // Generate object name ext := filepath.Ext(file.Filename) diff --git a/internal/application/service/graph.go b/internal/application/service/graph.go index d1271db0..c627c556 100644 --- a/internal/application/service/graph.go +++ b/internal/application/service/graph.go @@ -131,6 +131,9 @@ func (b *graphBuilder) extractEntities(ctx context.Context, chunk *types.Chunk) // Print detailed entity information in a clear format log.Info("=========== EXTRACTED ENTITIES ===========") for i, entity := range extractedEntities { + if entity == nil { + continue + } log.Infof("[Entity %d] Title: '%s', Description: '%s'", i+1, entity.Title, entity.Description) } log.Info("=========================================") @@ -156,6 +159,10 @@ func (b *graphBuilder) extractEntities(ctx context.Context, chunk *types.Chunk) entities = append(entities, entity) log.Debugf("New entity added: %s (ID: %s)", entity.Title, entity.ID) } else { + if existEntity == nil { + log.Warnf("existEntity is nil, skip update") + continue + } // Entity already exists, update its ChunkIDs if !slices.Contains(existEntity.ChunkIDs, chunk.ID) { existEntity.ChunkIDs = append(existEntity.ChunkIDs, chunk.ID) @@ -231,6 +238,9 @@ func (b *graphBuilder) extractRelationships(ctx context.Context, // Print detailed relationship information in a clear format log.Info("========= EXTRACTED RELATIONSHIPS =========") for i, rel := range extractedRelationships { + if rel == nil { + continue + } log.Infof("[Relation %d] Source: '%s', Target: '%s', Description: '%s', Strength: %d", i+1, rel.Source, rel.Target, rel.Description, rel.Strength) } @@ -243,6 +253,9 @@ func (b *graphBuilder) extractRelationships(ctx context.Context, relationshipsAdded := 0 relationshipsUpdated := 0 for _, relationship := range extractedRelationships { + if relationship == nil { + continue + } key := fmt.Sprintf("%s#%s", relationship.Source, relationship.Target) relationChunkIDs := b.findRelationChunkIDs(relationship.Source, relationship.Target, entities) if len(relationChunkIDs) == 0 { @@ -291,6 +304,9 @@ func (b *graphBuilder) findRelationChunkIDs(source, target string, entities []*t // Collect all document chunk IDs for source and target entities for _, entity := range entities { + if entity == nil { + continue + } if entity.Title == source || entity.Title == target { for _, chunkID := range entity.ChunkIDs { relationChunkIDs[chunkID] = struct{}{} @@ -475,6 +491,9 @@ func (b *graphBuilder) calculateWeights(ctx context.Context) { entityFrequency := make(map[string]int) for _, entity := range b.entityMap { + if entity == nil { + continue + } frequency := len(entity.ChunkIDs) entityFrequency[entity.Title] = frequency totalEntityOccurrences += frequency @@ -483,6 +502,9 @@ func (b *graphBuilder) calculateWeights(ctx context.Context) { // Calculate total relationship occurrences totalRelOccurrences := 0 for _, rel := range b.relationshipMap { + if rel == nil { + continue + } totalRelOccurrences += len(rel.ChunkIDs) } @@ -499,6 +521,9 @@ func (b *graphBuilder) calculateWeights(ctx context.Context) { // First calculate PMI and find maximum values pmiValues := make(map[string]float64) for _, rel := range b.relationshipMap { + if rel == nil { + continue + } sourceFreq := entityFrequency[rel.Source] targetFreq := entityFrequency[rel.Target] relFreq := len(rel.ChunkIDs) @@ -564,11 +589,17 @@ func (b *graphBuilder) calculateDegrees(ctx context.Context) { // Set degree for each entity for _, entity := range b.entityMap { + if entity == nil { + continue + } entity.Degree = inDegree[entity.Title] + outDegree[entity.Title] } // Set combined degree for relationships for _, rel := range b.relationshipMap { + if rel == nil { + continue + } sourceEntity := b.getEntityByTitle(rel.Source) targetEntity := b.getEntityByTitle(rel.Target) @@ -588,6 +619,9 @@ func (b *graphBuilder) buildChunkGraph(ctx context.Context) { // Create document chunk relationship graph based on entity relationships for _, rel := range b.relationshipMap { + if rel == nil { + continue + } // Ensure source and target entities exist for the relationship sourceEntity := b.entityMapByTitle[rel.Source] targetEntity := b.entityMapByTitle[rel.Target] @@ -665,6 +699,9 @@ func (b *graphBuilder) GetRelationChunks(chunkID string, topK int) []string { // Collect related chunks with their weights and degrees weightedChunks := make([]weightedChunk, 0) for relationChunkID, relation := range b.chunkGraph[chunkID] { + if relation == nil { + continue + } weightedChunks = append(weightedChunks, weightedChunk{ id: relationChunkID, weight: relation.Weight, @@ -737,8 +774,14 @@ func (b *graphBuilder) GetIndirectRelationChunks(chunkID string, topK int) []str // Get first-degree connections for directChunkID, directRelation := range b.chunkGraph[chunkID] { + if directRelation == nil { + continue + } // Get second-degree connections for indirectChunkID, indirectRelation := range b.chunkGraph[directChunkID] { + if indirectRelation == nil { + continue + } // Skip self and all direct connections if _, isDirect := directChunks[indirectChunkID]; isDirect { continue @@ -764,6 +807,9 @@ func (b *graphBuilder) GetIndirectRelationChunks(chunkID string, topK int) []str // Convert to sortable slice weightedChunks := make([]weightedChunk, 0, len(indirectChunkMap)) for id, relation := range indirectChunkMap { + if relation == nil { + continue + } weightedChunks = append(weightedChunks, weightedChunk{ id: id, weight: relation.Weight, diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index 30bb22fc..605ac8e3 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -190,7 +190,7 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context, } // Check if file already exists - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if file exists, tenant ID: %d", tenantID) exists, existingKnowledge, err := s.repo.CheckKnowledgeExists(ctx, tenantID, kbID, &types.KnowledgeCheckParams{ Type: "file", @@ -339,7 +339,7 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context, } // Check if URL already exists in the knowledge base - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if URL exists, tenant ID: %d", tenantID) fileHash := calculateStr(url) exists, existingKnowledge, err := s.repo.CheckKnowledgeExists(ctx, tenantID, kbID, &types.KnowledgeCheckParams{ @@ -479,7 +479,7 @@ func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context, return nil, err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) now := time.Now() title := safeTitle if title == "" { @@ -566,7 +566,7 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex } knowledge := &types.Knowledge{ ID: uuid.New().String(), - TenantID: ctx.Value(types.TenantIDContextKey).(uint), + TenantID: ctx.Value(types.TenantIDContextKey).(uint64), KnowledgeBaseID: kbID, Type: "passage", ParseStatus: "pending", @@ -591,7 +591,7 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex } else { // Enqueue passage processing task to Asynq logger.Info(ctx, "Enqueuing passage processing task to Asynq") - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) taskPayload := types.DocumentProcessPayload{ TenantID: tenantID, KnowledgeID: knowledge.ID, @@ -624,7 +624,7 @@ func (s *knowledgeService) GetKnowledgeByID(ctx context.Context, id string) (*ty logger.Info(ctx, "Start getting knowledge by ID") logger.Infof(ctx, "Knowledge ID: %s", id) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, id) @@ -644,7 +644,7 @@ func (s *knowledgeService) GetKnowledgeByID(ctx context.Context, id string) (*ty func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string, ) ([]*types.Knowledge, error) { - return s.repo.ListKnowledgeByKnowledgeBaseID(ctx, ctx.Value(types.TenantIDContextKey).(uint), kbID) + return s.repo.ListKnowledgeByKnowledgeBaseID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), kbID) } // ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base @@ -652,7 +652,7 @@ func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Conte kbID string, page *types.Pagination, tagID string, ) (*types.PageResult, error) { knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx, - ctx.Value(types.TenantIDContextKey).(uint), kbID, page, tagID) + ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, tagID) if err != nil { return nil, err } @@ -663,7 +663,7 @@ func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Conte // DeleteKnowledge deletes a knowledge entry and all related resources func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error { // Get the knowledge entry - knowledge, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), id) + knowledge, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), id) if err != nil { return err } @@ -726,7 +726,7 @@ func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error return err } // Delete the knowledge entry itself from the database - return s.repo.DeleteKnowledge(ctx, ctx.Value(types.TenantIDContextKey).(uint), id) + return s.repo.DeleteKnowledge(ctx, ctx.Value(types.TenantIDContextKey).(uint64), id) } // DeleteKnowledge deletes a knowledge entry and all related resources @@ -1544,7 +1544,8 @@ func (s *knowledgeService) getSummary(ctx context.Context, // GetKnowledgeFile retrieves the physical file associated with a knowledge entry func (s *knowledgeService) GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error) { // Get knowledge record - knowledge, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), id) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) + knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, id) if err != nil { return nil, "", err } @@ -1559,7 +1560,7 @@ func (s *knowledgeService) GetKnowledgeFile(ctx context.Context, id string) (io. } func (s *knowledgeService) UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error { - record, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), knowledge.ID) + record, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), knowledge.ID) if err != nil { logger.Errorf(ctx, "Failed to get knowledge record: %v", err) return err @@ -1608,7 +1609,7 @@ func (s *knowledgeService) UpdateManualKnowledge(ctx context.Context, return nil, werrors.NewValidationError("状态仅支持 draft 或 publish") } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) existing, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID) if err != nil { logger.Errorf(ctx, "Failed to load knowledge: %v", err) @@ -1714,7 +1715,7 @@ func isValidURL(url string) bool { // GetKnowledgeBatch retrieves multiple knowledge entries by their IDs func (s *knowledgeService) GetKnowledgeBatch(ctx context.Context, - tenantID uint, ids []string, + tenantID uint64, ids []string, ) ([]*types.Knowledge, error) { if len(ids) == 0 { return nil, nil @@ -1885,7 +1886,7 @@ func (s *knowledgeService) UpdateImageInfo(ctx context.Context, knowledgeID stri return err } chunk.ImageInfo = imageInfo - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) chunkChildren, err := s.chunkService.ListChunkByParentID(ctx, tenantID, chunkID) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ @@ -2140,7 +2141,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context, if err != nil { return nil, err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kb.ID) if err != nil { return nil, err @@ -2188,7 +2189,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context, return "", err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // 检查是否有正在进行的导入任务 runningKnowledge, err := s.getRunningFAQImportTask(ctx, kbID, tenantID) @@ -2246,7 +2247,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context, // calculateAppendOperations 计算Append模式下需要处理的条目,跳过已存在且内容相同的条目 func (s *knowledgeService) calculateAppendOperations(ctx context.Context, - tenantID uint, knowledgeID string, entries []types.FAQEntryPayload) ([]types.FAQEntryPayload, int, error) { + tenantID uint64, knowledgeID string, entries []types.FAQEntryPayload) ([]types.FAQEntryPayload, int, error) { if len(entries) == 0 { return []types.FAQEntryPayload{}, 0, nil } @@ -2255,7 +2256,7 @@ func (s *knowledgeService) calculateAppendOperations(ctx context.Context, // calculateReplaceOperations 计算Replace模式下需要删除、创建、更新的条目 func (s *knowledgeService) calculateReplaceOperations(ctx context.Context, - tenantID uint, knowledgeID string, newEntries []types.FAQEntryPayload) ([]types.FAQEntryPayload, []*types.Chunk, int, error) { + tenantID uint64, knowledgeID string, newEntries []types.FAQEntryPayload) ([]types.FAQEntryPayload, []*types.Chunk, int, error) { // 计算所有新条目的 content hash,并同时构建 hash 到 entry 的映射 type entryWithHash struct { entry types.FAQEntryPayload @@ -2322,7 +2323,7 @@ func (s *knowledgeService) calculateReplaceOperations(ctx context.Context, // executeFAQImport 执行实际的FAQ导入逻辑 func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string, kbID string, - payload *types.FAQBatchUpsertPayload, tenantID uint, processedCount int) (err error) { + payload *types.FAQBatchUpsertPayload, tenantID uint64, processedCount int) (err error) { // 保存知识库和embedding模型信息,用于清理索引 var kb *types.KnowledgeBase var embeddingModel embedding.Embedder @@ -2521,7 +2522,7 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context, return err } kb.EnsureDefaults() - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID) if err != nil { return err @@ -2592,7 +2593,7 @@ func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context, if err != nil { return err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID) if err != nil { return err @@ -2634,7 +2635,7 @@ func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context, if err != nil { return err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Get all chunks in batch entryIDs := make([]string, 0, len(updates)) @@ -2684,7 +2685,7 @@ func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context, // 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) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID) if err != nil { return err @@ -2711,7 +2712,7 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates if len(updates) == 0 { return nil } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Get all knowledge items in batch knowledgeIDs := make([]string, 0, len(updates)) @@ -2784,7 +2785,7 @@ func (s *knowledgeService) UpdateFAQEntryTag(ctx context.Context, kbID string, e if err != nil { return err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID) if err != nil { return err @@ -2819,7 +2820,7 @@ func (s *knowledgeService) UpdateFAQEntryTagBatch(ctx context.Context, kbID stri if err != nil { return err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Get all chunks in batch entryIDs := make([]string, 0, len(updates)) @@ -2942,7 +2943,7 @@ func (s *knowledgeService) SearchFAQEntries(ctx context.Context, } // Batch fetch chunks - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs) if err != nil { return nil, err @@ -2997,7 +2998,7 @@ func (s *knowledgeService) DeleteFAQEntries(ctx context.Context, return err } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) var faqKnowledge *types.Knowledge chunksToRemove := make([]*types.Chunk, 0, len(entryIDs)) for _, id := range entryIDs { @@ -3045,7 +3046,7 @@ func (s *knowledgeService) validateFAQKnowledgeBase(ctx context.Context, kbID st return kb, nil } -func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint, 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 @@ -3058,7 +3059,7 @@ func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint, return nil, nil } -func (s *knowledgeService) ensureFAQKnowledge(ctx context.Context, tenantID uint, 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 @@ -3093,7 +3094,7 @@ func (s *knowledgeService) updateFAQImportStatus(ctx context.Context, knowledgeI // updateFAQImportStatusWithRanges 更新FAQ Knowledge的导入任务状态,包含NextChunkIndex func (s *knowledgeService) updateFAQImportStatusWithRanges(ctx context.Context, knowledgeID string, status types.FAQImportTaskStatus, progress, total, processed int, errorMsg string) error { - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID) if err != nil { return err @@ -3129,7 +3130,7 @@ func (s *knowledgeService) updateFAQImportStatusWithRanges(ctx context.Context, } // getRunningFAQImportTask 获取指定知识库的进行中导入任务 -func (s *knowledgeService) getRunningFAQImportTask(ctx context.Context, kbID string, tenantID uint) (*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 diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go index 2b4ef0b7..c8cb1cbf 100644 --- a/internal/application/service/knowledgebase.go +++ b/internal/application/service/knowledgebase.go @@ -73,7 +73,7 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context, kb.ID = uuid.New().String() } kb.CreatedAt = time.Now() - kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint) + kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint64) kb.UpdatedAt = time.Now() kb.EnsureDefaults() @@ -112,7 +112,7 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id stri // ListKnowledgeBases returns all knowledge bases for a tenant func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) { - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID) if err != nil { @@ -222,7 +222,7 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin logger.Infof(ctx, "Deleting knowledge base, ID: %s", id) // Get tenant ID from context - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Step 1: Get all knowledge entries in this knowledge base logger.Infof(ctx, "Fetching all knowledge entries in knowledge base, ID: %s", id) @@ -390,7 +390,7 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context, return nil, nil, err } sourceKB.EnsureDefaults() - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) var targetKB *types.KnowledgeBase if dstKB != "" { targetKB, err = s.repo.GetKnowledgeBaseByID(ctx, dstKB) @@ -685,7 +685,7 @@ func (s *knowledgeBaseService) filterByNegativeQuestions(ctx context.Context, return chunks } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Collect chunk IDs chunkIDs := make([]string, 0, len(chunks)) @@ -772,7 +772,7 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context, return nil, nil } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Prepare data structures for efficient processing var knowledgeIDs []string @@ -950,7 +950,7 @@ func (s *knowledgeBaseService) isValidTextChunk(chunk *types.Chunk) bool { // fetchKnowledgeData gets knowledge data in batch func (s *knowledgeBaseService) fetchKnowledgeData(ctx context.Context, - tenantID uint, + tenantID uint64, knowledgeIDs []string, ) (map[string]*types.Knowledge, error) { knowledges, err := s.kgRepo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs) diff --git a/internal/application/service/mcp_service.go b/internal/application/service/mcp_service.go index 512dbff3..6891859a 100644 --- a/internal/application/service/mcp_service.go +++ b/internal/application/service/mcp_service.go @@ -49,7 +49,7 @@ func (s *mcpServiceService) CreateMCPService(ctx context.Context, service *types } // GetMCPServiceByID retrieves an MCP service by ID -func (s *mcpServiceService) GetMCPServiceByID(ctx context.Context, tenantID uint, 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) @@ -64,7 +64,7 @@ func (s *mcpServiceService) GetMCPServiceByID(ctx context.Context, tenantID uint } // ListMCPServices lists all MCP services for a tenant -func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint) ([]*types.MCPService, error) { +func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) { services, err := s.mcpServiceRepo.List(ctx, tenantID) if err != nil { logger.GetLogger(ctx).Errorf("Failed to list MCP services: %v", err) @@ -80,7 +80,7 @@ func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint) } // ListMCPServicesByIDs retrieves multiple MCP services by IDs -func (s *mcpServiceService) ListMCPServicesByIDs(ctx context.Context, tenantID uint, 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 } @@ -198,7 +198,7 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types } // DeleteMCPService deletes an MCP service -func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint, id string) error { +func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint64, id string) error { // Check if service exists existing, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id) if err != nil { @@ -221,7 +221,7 @@ func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint, } // TestMCPService tests the connection to an MCP service and returns available tools/resources -func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint, 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 { @@ -288,7 +288,7 @@ func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint, i } // GetMCPServiceTools retrieves the list of tools from an MCP service -func (s *mcpServiceService) GetMCPServiceTools(ctx context.Context, tenantID uint, 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 +314,7 @@ 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 uint, 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 { diff --git a/internal/application/service/message.go b/internal/application/service/message.go index 5304de9f..fed31037 100644 --- a/internal/application/service/message.go +++ b/internal/application/service/message.go @@ -43,7 +43,7 @@ func (s *messageService) CreateMessage(ctx context.Context, message *types.Messa logger.Infof(ctx, "Creating message for session ID: %s", message.SessionID) // Check if the session exists to validate the message belongs to a valid session - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if session exists, tenant ID: %d, session ID: %s", tenantID, message.SessionID) _, err := s.sessionRepo.Get(ctx, tenantID, message.SessionID) if err != nil { @@ -77,7 +77,7 @@ func (s *messageService) GetMessage(ctx context.Context, sessionID string, messa logger.Infof(ctx, "Getting message, session ID: %s, message ID: %s", sessionID, messageID) // Verify the session exists before attempting to retrieve the message - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID) _, err := s.sessionRepo.Get(ctx, tenantID, sessionID) if err != nil { @@ -115,7 +115,7 @@ func (s *messageService) GetMessagesBySession(ctx context.Context, logger.Infof(ctx, "Getting messages for session ID: %s, page: %d, pageSize: %d", sessionID, page, pageSize) // Verify the session exists before retrieving messages - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID) _, err := s.sessionRepo.Get(ctx, tenantID, sessionID) if err != nil { @@ -154,7 +154,7 @@ func (s *messageService) GetRecentMessagesBySession(ctx context.Context, logger.Infof(ctx, "Getting recent messages for session ID: %s, limit: %d", sessionID, limit) // Verify the session exists before retrieving messages - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID) _, err := s.sessionRepo.Get(ctx, tenantID, sessionID) if err != nil { @@ -193,7 +193,7 @@ func (s *messageService) GetMessagesBySessionBeforeTime(ctx context.Context, logger.Infof(ctx, "Getting messages before %v for session ID: %s, limit: %d", beforeTime, sessionID, limit) // Verify the session exists before retrieving messages - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID) _, err := s.sessionRepo.Get(ctx, tenantID, sessionID) if err != nil { @@ -228,7 +228,7 @@ func (s *messageService) UpdateMessage(ctx context.Context, message *types.Messa logger.Infof(ctx, "Updating message, ID: %s, session ID: %s", message.ID, message.SessionID) // Verify the session exists before updating the message - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID) _, err := s.sessionRepo.Get(ctx, tenantID, message.SessionID) if err != nil { @@ -263,7 +263,7 @@ func (s *messageService) DeleteMessage(ctx context.Context, sessionID string, me logger.Infof(ctx, "Deleting message, session ID: %s, message ID: %s", sessionID, messageID) // Verify the session exists before deleting the message - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID) _, err := s.sessionRepo.Get(ctx, tenantID, sessionID) if err != nil { diff --git a/internal/application/service/model.go b/internal/application/service/model.go index 6782e1e7..02119ac9 100644 --- a/internal/application/service/model.go +++ b/internal/application/service/model.go @@ -101,7 +101,7 @@ func (s *modelService) GetModelByID(ctx context.Context, id string) (*types.Mode return nil, errors.New("model ID cannot be empty") } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Fetch model from repository model, err := s.repo.GetByID(ctx, tenantID, id) @@ -145,7 +145,7 @@ func (s *modelService) GetModelByID(ctx context.Context, id string) (*types.Mode func (s *modelService) ListModels(ctx context.Context) ([]*types.Model, error) { logger.Info(ctx, "Start listing models") - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Listing models for tenant ID: %d", tenantID) // List models from repository with no additional filters @@ -167,7 +167,7 @@ func (s *modelService) UpdateModel(ctx context.Context, model *types.Model) erro logger.Infof(ctx, "Updating model ID: %s, name: %s", model.ID, model.Name) // Check if the model is builtin - builtin models cannot be updated - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) existingModel, err := s.repo.GetByID(ctx, tenantID, model.ID) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ @@ -199,7 +199,7 @@ func (s *modelService) DeleteModel(ctx context.Context, id string) error { logger.Info(ctx, "Start deleting model") logger.Infof(ctx, "Deleting model ID: %s", id) - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Tenant ID: %d", tenantID) // Check if the model is builtin - builtin models cannot be deleted @@ -308,7 +308,7 @@ func (s *modelService) GetChatModel(ctx context.Context, modelId string) (chat.C return nil, errors.New("model ID cannot be empty") } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Get the model directly from repository to avoid status checks model, err := s.repo.GetByID(ctx, tenantID, modelId) diff --git a/internal/application/service/retriever/composite.go b/internal/application/service/retriever/composite.go index d12865d0..03527c2a 100644 --- a/internal/application/service/retriever/composite.go +++ b/internal/application/service/retriever/composite.go @@ -38,6 +38,9 @@ func (c *CompositeRetrieveEngine) Retrieve(ctx context.Context, func(ctx context.Context, param types.RetrieveParams, results *[]*types.RetrieveResult, mu *sync.Mutex) error { found := false for _, engineInfo := range c.engineInfos { + if engineInfo == nil { + continue + } if slices.Contains(engineInfo.retrieverType, param.RetrieverType) { result, err := engineInfo.retrieveEngine.Retrieve(ctx, param) if err != nil { @@ -86,6 +89,9 @@ func NewCompositeRetrieveEngine(registry interfaces.RetrieveEngineRegistry, engi // SupportRetriever checks if a retriever type is supported by any of the registered engines func (c *CompositeRetrieveEngine) SupportRetriever(r types.RetrieverType) bool { for _, engineInfo := range c.engineInfos { + if engineInfo == nil { + continue + } if slices.Contains(engineInfo.retrieverType, r) { return true } diff --git a/internal/application/service/session.go b/internal/application/service/session.go index ec937a72..d84d6f73 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -108,7 +108,7 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess } // Get tenant ID from context - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Retrieving session, ID: %s, tenant ID: %d", id, tenantID) // Get session from repository @@ -128,7 +128,7 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess // GetSessionsByTenant retrieves all sessions for the current tenant func (s *sessionService) GetSessionsByTenant(ctx context.Context) ([]*types.Session, error) { // Get tenant ID from context - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) logger.Infof(ctx, "Retrieving all sessions for tenant, tenant ID: %d", tenantID) // Get sessions from repository @@ -151,7 +151,7 @@ func (s *sessionService) GetPagedSessionsByTenant(ctx context.Context, pagination *types.Pagination, ) (*types.PageResult, error) { // Get tenant ID from context - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Get paged sessions from repository sessions, total, err := s.sessionRepo.GetPagedByTenantID(ctx, tenantID, pagination) if err != nil { @@ -197,7 +197,7 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error { } // Get tenant ID from context - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) // Cleanup temporary KB stored in Redis for this session if err := s.DeleteWebSearchTempKBState(ctx, id); err != nil { @@ -267,6 +267,9 @@ func (s *sessionService) GenerateTitle(ctx context.Context, } // Find first available KnowledgeQA model for _, model := range models { + if model == nil { + continue + } if model.Type == types.ModelTypeKnowledgeQA { modelID = model.ID logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID) @@ -746,6 +749,9 @@ func (s *sessionService) SearchKnowledge(ctx context.Context, // Find the first available rerank model for _, model := range models { + if model == nil { + continue + } if model.Type == types.ModelTypeRerank { chatManage.RerankModelID = model.ID break @@ -808,7 +814,7 @@ 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 { sessionID := session.ID - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) sessionJSON, err := json.Marshal(session) if err != nil { logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err) @@ -892,6 +898,9 @@ func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, qu // Extract knowledge base IDs agentConfig.KnowledgeBases = make([]string, len(allKBs)) for i, kb := range allKBs { + if kb == nil { + continue + } agentConfig.KnowledgeBases[i] = kb.ID } logger.Infof(ctx, "Agent defaulting to all %d knowledge base(s) in tenant: %v", diff --git a/internal/application/service/tag.go b/internal/application/service/tag.go index 9e69bfd6..69844d1d 100644 --- a/internal/application/service/tag.go +++ b/internal/application/service/tag.go @@ -48,6 +48,9 @@ func (s *knowledgeTagService) ListTags(ctx context.Context, kbID string) ([]*typ results := make([]*types.KnowledgeTagWithStats, 0, len(tags)) for _, tag := range tags { + if tag == nil { + continue + } kCount, cCount, err := s.repo.CountReferences(ctx, tenantID, kbID, tag.ID) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ @@ -97,7 +100,7 @@ func (s *knowledgeTagService) UpdateTag(ctx context.Context, id string, name *st if id == "" { return nil, werrors.NewBadRequestError("标签ID不能为空") } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) tag, err := s.repo.GetByID(ctx, tenantID, id) if err != nil { return nil, err @@ -128,7 +131,7 @@ func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bo if id == "" { return werrors.NewBadRequestError("标签ID不能为空") } - tenantID := ctx.Value(types.TenantIDContextKey).(uint) + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) tag, err := s.repo.GetByID(ctx, tenantID, id) if err != nil { return err diff --git a/internal/application/service/tenant.go b/internal/application/service/tenant.go index d9353ed7..04485afd 100644 --- a/internal/application/service/tenant.go +++ b/internal/application/service/tenant.go @@ -80,7 +80,7 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant) } // GetTenantByID retrieves a tenant by their ID -func (s *tenantService) GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) { +func (s *tenantService) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) { if id == 0 { logger.Error(ctx, "Tenant ID cannot be 0") return nil, errors.New("tenant ID cannot be 0") @@ -139,7 +139,7 @@ func (s *tenantService) UpdateTenant(ctx context.Context, tenant *types.Tenant) } // DeleteTenant removes a tenant by their ID -func (s *tenantService) DeleteTenant(ctx context.Context, id uint) error { +func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error { logger.Info(ctx, "Start deleting tenant") if id == 0 { @@ -177,7 +177,7 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint) error { } // UpdateAPIKey updates the API key for a specific tenant -func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint) (string, error) { +func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, error) { logger.Info(ctx, "Start updating tenant API Key") if id == 0 { @@ -208,7 +208,7 @@ func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint) (string, erro } // generateApiKey generates a secure API key for tenant authentication -func (r *tenantService) generateApiKey(tenantID uint) string { +func (r *tenantService) generateApiKey(tenantID uint64) string { // 1. Convert tenant_id to bytes idBytes := make([]byte, 8) binary.LittleEndian.PutUint64(idBytes, uint64(tenantID)) @@ -240,7 +240,7 @@ func (r *tenantService) generateApiKey(tenantID uint) string { } // ExtractTenantIDFromAPIKey extracts the tenant ID from an API key -func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint, error) { +func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) { // 1. Validate format and extract encrypted part parts := strings.SplitN(apiKey, "-", 2) if len(parts) != 2 || parts[0] != "sk" { @@ -278,5 +278,5 @@ func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint, error) { // 5. Convert back to tenant_id tenantID := binary.LittleEndian.Uint64(plaintext) - return uint(tenantID), nil + return tenantID, nil } diff --git a/internal/application/service/user.go b/internal/application/service/user.go index 671d12e8..3ed06a61 100644 --- a/internal/application/service/user.go +++ b/internal/application/service/user.go @@ -99,7 +99,7 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest) } } egs = uniqueRetrieverEngine(egs) - logger.Debugf(ctx, "user register retriever engines: %v", egs) + logger.Debug(ctx, "user register retriever engines") // Create default tenant for the user tenant := &types.Tenant{ @@ -111,7 +111,7 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest) createdTenant, err := s.tenantService.CreateTenant(ctx, tenant) if err != nil { - logger.Errorf(ctx, "Failed to create tenant: %v", err) + logger.Errorf(ctx, "Failed to create tenant") return nil, errors.New("failed to create workspace") } @@ -133,36 +133,33 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest) return nil, errors.New("failed to create user") } - logger.Infof(ctx, "User registered successfully: %s", user.Email) + logger.Info(ctx, "User registered successfully") return user, nil } // Login authenticates a user and returns tokens func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error) { - logger.Infof(ctx, "Start user login for email: %s", req.Email) - + logger.Info(ctx, "Start user login") // Get user by email user, err := s.userRepo.GetUserByEmail(ctx, req.Email) if err != nil { - logger.Errorf(ctx, "Failed to get user by email %s: %v", req.Email, err) + logger.Errorf(ctx, "Failed to get user by email: %v", err) return &types.LoginResponse{ Success: false, Message: "Invalid email or password", }, nil } if user == nil { - logger.Warnf(ctx, "User not found for email: %s", req.Email) + logger.Warn(ctx, "User not found for email") return &types.LoginResponse{ Success: false, Message: "Invalid email or password", }, nil } - logger.Infof(ctx, "Found user: ID=%s, Email=%s, IsActive=%t", user.ID, user.Email, user.IsActive) - // Check if user is active if !user.IsActive { - logger.Warnf(ctx, "User account is disabled for email: %s", req.Email) + logger.Warn(ctx, "User account is disabled") return &types.LoginResponse{ Success: false, Message: "Account is disabled", @@ -170,39 +167,37 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type } // Verify password - logger.Infof(ctx, "Verifying password for user: %s", user.Email) err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)) if err != nil { - logger.Warnf(ctx, "Password verification failed for user %s: %v", user.Email, err) + logger.Warn(ctx, "Password verification failed") return &types.LoginResponse{ Success: false, Message: "Invalid email or password", }, nil } - logger.Infof(ctx, "Password verification successful for user: %s", user.Email) + logger.Info(ctx, "Password verification successful") // Generate tokens - logger.Infof(ctx, "Generating tokens for user: %s", user.Email) + logger.Info(ctx, "Generating tokens") accessToken, refreshToken, err := s.GenerateTokens(ctx, user) if err != nil { - logger.Errorf(ctx, "Failed to generate tokens for user %s: %v", user.Email, err) + logger.Errorf(ctx, "Failed to generate tokens: %v", err) return &types.LoginResponse{ Success: false, Message: "Login failed", }, nil } - logger.Infof(ctx, "Tokens generated successfully for user: %s", user.Email) + logger.Info(ctx, "Tokens generated successfully") // Get tenant information - logger.Infof(ctx, "Getting tenant information for user %s, tenant ID: %s", user.Email, user.TenantID) tenant, err := s.tenantService.GetTenantByID(ctx, user.TenantID) if err != nil { - logger.Warnf(ctx, "Failed to get tenant info for user %s, tenant ID %s: %v", user.Email, user.TenantID, err) + logger.Warn(ctx, "Failed to get tenant info") } else { - logger.Infof(ctx, "Tenant information retrieved successfully for user: %s", user.Email) + logger.Info(ctx, "Tenant information retrieved successfully") } - logger.Infof(ctx, "User logged in successfully: %s", user.Email) + logger.Info(ctx, "User logged in successfully") return &types.LoginResponse{ Success: true, Message: "Login successful", diff --git a/internal/application/service/web_search.go b/internal/application/service/web_search.go index bf19994f..3a28bec9 100644 --- a/internal/application/service/web_search.go +++ b/internal/application/service/web_search.go @@ -365,6 +365,9 @@ func ConvertWebSearchResults(webResults []*types.WebSearchResult) []*types.Searc results := make([]*types.SearchResult, 0, len(webResults)) for i, webResult := range webResults { + if webResult == nil { + continue + } // Use URL as ChunkID for web search results chunkID := webResult.URL if chunkID == "" { diff --git a/internal/application/service/web_search/duckduckgo_test.go b/internal/application/service/web_search/duckduckgo_test.go index c253c5b1..6d77bc36 100644 --- a/internal/application/service/web_search/duckduckgo_test.go +++ b/internal/application/service/web_search/duckduckgo_test.go @@ -82,6 +82,9 @@ func TestDuckDuckGoProvider_Search_HTMLSuccess(t *testing.T) { // Build provider and inject our test client prov, _ := NewDuckDuckGoProvider(config.WebSearchProviderConfig{}) dp := prov.(*DuckDuckGoProvider) + if dp == nil { + t.Fatalf("failed to build provider") + } dp.client = newTestClient(ts) ctx := context.Background() @@ -138,6 +141,9 @@ func TestDuckDuckGoProvider_Search_APIFallback(t *testing.T) { prov, _ := NewDuckDuckGoProvider(config.WebSearchProviderConfig{}) dp := prov.(*DuckDuckGoProvider) + if dp == nil { + t.Fatalf("failed to build provider") + } dp.client = newTestClient(ts) ctx := context.Background() @@ -167,6 +173,9 @@ func TestDuckDuckGoProvider_Search_Real(t *testing.T) { if err != nil { t.Fatalf("Failed to create DuckDuckGo provider: %v", err) } + if provider == nil { + t.Fatalf("failed to build provider") + } // Test with a simple, general query that should return results query := "Go programming language" @@ -186,6 +195,9 @@ func TestDuckDuckGoProvider_Search_Real(t *testing.T) { // Verify result structure for i, result := range results { + if result == nil { + t.Fatalf("Result[%d]: is nil", i) + } if result.Title == "" { t.Errorf("Result[%d]: Title is empty", i) } @@ -229,6 +241,9 @@ func TestDuckDuckGoProvider_Search_Real_Chinese(t *testing.T) { if err != nil { t.Fatalf("Failed to create DuckDuckGo provider: %v", err) } + if provider == nil { + t.Fatalf("failed to build provider") + } // Test with a Chinese query query := "WeKnora 企业级RAG框架 介绍 文档" @@ -248,6 +263,9 @@ func TestDuckDuckGoProvider_Search_Real_Chinese(t *testing.T) { // Verify result structure for i, result := range results { + if result == nil { + t.Fatalf("Result[%d]: is nil", i) + } if result.Title == "" { t.Errorf("Result[%d]: Title is empty", i) } diff --git a/internal/handler/chunk.go b/internal/handler/chunk.go index c37ae16a..1f7e5235 100644 --- a/internal/handler/chunk.go +++ b/internal/handler/chunk.go @@ -58,7 +58,7 @@ func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) { } // Validate tenant ID - if chunk.TenantID != tenantID.(uint) { + if chunk.TenantID != tenantID.(uint64) { logger.Warnf( ctx, "Tenant has no permission to access chunk, chunk ID: %s, req tenant: %d, chunk tenant: %d", @@ -184,11 +184,11 @@ func (h *ChunkHandler) validateAndGetChunk(c *gin.Context) (*types.Chunk, string } // Validate tenant ID - if chunk.TenantID != tenantID.(uint) || chunk.KnowledgeID != knowledgeID { + if chunk.TenantID != tenantID.(uint64) || chunk.KnowledgeID != knowledgeID { logger.Warnf( ctx, "Tenant has no permission to access chunk, knowledge ID: %s, chunk ID: %s, req tenant: %d, chunk tenant: %d", - knowledgeID, id, tenantID.(uint), chunk.TenantID, + knowledgeID, id, tenantID, chunk.TenantID, ) return nil, knowledgeID, errors.NewForbiddenError("No permission to access this chunk") } diff --git a/internal/handler/evaluation.go b/internal/handler/evaluation.go index ac620923..ad25dc37 100644 --- a/internal/handler/evaluation.go +++ b/internal/handler/evaluation.go @@ -87,9 +87,6 @@ func (e *EvaluationHandler) GetEvaluationResult(c *gin.Context) { c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error())) return } - - logger.Infof(ctx, "Retrieving evaluation result, task ID: %s", request.TaskID) - result, err := e.evaluationService.EvaluationResult(ctx, request.TaskID) if err != nil { logger.ErrorWithFields(ctx, err, nil) @@ -97,7 +94,7 @@ func (e *EvaluationHandler) GetEvaluationResult(c *gin.Context) { return } - logger.Infof(ctx, "Retrieved evaluation result successfully, task ID: %s", request.TaskID) + logger.Info(ctx, "Retrieved evaluation result successfully") c.JSON(http.StatusOK, gin.H{ "success": true, "data": result, diff --git a/internal/handler/initialization.go b/internal/handler/initialization.go index 8994c9f5..8666eaac 100644 --- a/internal/handler/initialization.go +++ b/internal/handler/initialization.go @@ -205,7 +205,6 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) { c.Error(errors.NewBadRequestError(err.Error())) return } - logger.Infof(ctx, "Starting KB configuration update with model IDs, kbId: %s", kbIdStr) // 获取知识库信息 kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbIdStr) @@ -233,14 +232,14 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) { // 从数据库获取模型详情并验证 llmModel, err := h.modelService.GetModelByID(ctx, req.LLMModelID) if err != nil || llmModel == nil { - logger.Error(ctx, "LLM model not found", "modelId", req.LLMModelID) + logger.Error(ctx, "LLM model not found") c.Error(errors.NewBadRequestError("LLM模型不存在")) return } embeddingModel, err := h.modelService.GetModelByID(ctx, req.EmbeddingModelID) if err != nil || embeddingModel == nil { - logger.Error(ctx, "Embedding model not found", "modelId", req.EmbeddingModelID) + logger.Error(ctx, "Embedding model not found") c.Error(errors.NewBadRequestError("Embedding模型不存在")) return } @@ -254,7 +253,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) { if req.VLMConfig != nil && req.Multimodal.Enabled && req.VLMConfig.ModelID != "" { vllmModel, err := h.modelService.GetModelByID(ctx, req.VLMConfig.ModelID) if err != nil || vllmModel == nil { - logger.Warn(ctx, "VLM model not found", "modelId", req.VLMConfig.ModelID) + logger.Warn(ctx, "VLM model not found") } else { kb.VLMConfig.Enabled = req.VLMConfig.Enabled kb.VLMConfig.ModelID = req.VLMConfig.ModelID @@ -335,7 +334,6 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) { return } - logger.Info(ctx, "KB configuration updated successfully", "kbId", kbIdStr) c.JSON(http.StatusOK, gin.H{ "success": true, "message": "配置更新成功", @@ -1133,6 +1131,9 @@ func (h *InitializationHandler) buildConfigResponse(ctx context.Context, models // 按类型分组模型 for _, model := range models { + if model == nil { + continue + } // Hide sensitive information for builtin models baseURL := model.Parameters.BaseURL apiKey := model.Parameters.APIKey diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index 6c748e60..bfb38274 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -48,12 +48,12 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.K } // Verify tenant permissions - if kb.TenantID != c.GetUint(types.TenantIDContextKey.String()) { + if kb.TenantID != c.GetUint64(types.TenantIDContextKey.String()) { logger.Warnf( ctx, "Permission denied to access this knowledge base, tenant ID mismatch, "+ "requested tenant ID: %d, knowledge base tenant ID: %d", - c.GetUint(types.TenantIDContextKey.String()), + c.GetUint64(types.TenantIDContextKey.String()), kb.TenantID, ) return nil, kbID, errors.NewForbiddenError("Permission denied to access this knowledge base") @@ -422,11 +422,11 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) { logger.Infof( ctx, "Batch retrieving knowledge, tenant ID: %d, number of knowledge IDs: %d", - tenantID.(uint), len(req.IDs), + tenantID, len(req.IDs), ) // Retrieve knowledge entries in batch - knowledges, err := h.kgService.GetKnowledgeBatch(ctx, tenantID.(uint), req.IDs) + knowledges, err := h.kgService.GetKnowledgeBatch(ctx, tenantID.(uint64), req.IDs) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(errors.NewInternalServerError("Failed to retrieve knowledge list").WithDetails(err.Error())) diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go index 724923b3..885879f2 100644 --- a/internal/handler/knowledgebase.go +++ b/internal/handler/knowledgebase.go @@ -121,7 +121,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ } // Verify tenant ownership - if kb.TenantID != tenantID.(uint) { + if kb.TenantID != tenantID.(uint64) { logger.Warnf( ctx, "Tenant has no permission to access this knowledge base, knowledge base ID: %s, "+ diff --git a/internal/handler/mcp_service.go b/internal/handler/mcp_service.go index f428409c..65164f5e 100644 --- a/internal/handler/mcp_service.go +++ b/internal/handler/mcp_service.go @@ -34,7 +34,7 @@ func (h *MCPServiceHandler) CreateMCPService(c *gin.Context) { return } - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -60,7 +60,7 @@ func (h *MCPServiceHandler) CreateMCPService(c *gin.Context) { func (h *MCPServiceHandler) ListMCPServices(c *gin.Context) { ctx := c.Request.Context() - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -86,7 +86,7 @@ func (h *MCPServiceHandler) GetMCPService(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -112,7 +112,7 @@ func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -229,7 +229,7 @@ func (h *MCPServiceHandler) DeleteMCPService(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -255,7 +255,7 @@ func (h *MCPServiceHandler) TestMCPService(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -290,7 +290,7 @@ func (h *MCPServiceHandler) GetMCPServiceTools(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -316,7 +316,7 @@ func (h *MCPServiceHandler) GetMCPServiceResources(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) diff --git a/internal/handler/model.go b/internal/handler/model.go index 46466248..f0b11028 100644 --- a/internal/handler/model.go +++ b/internal/handler/model.go @@ -84,7 +84,7 @@ func (h *ModelHandler) CreateModel(c *gin.Context) { return } - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) @@ -173,7 +173,7 @@ func (h *ModelHandler) ListModels(c *gin.Context) { logger.Info(ctx, "Start retrieving model list") - tenantID := c.GetUint(types.TenantIDContextKey.String()) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) if tenantID == 0 { logger.Error(ctx, "Tenant ID is empty") c.Error(errors.NewBadRequestError("Tenant ID cannot be empty")) diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index 5d10ba02..a6da8ff9 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -69,7 +69,7 @@ func (h *Handler) CreateSession(c *gin.Context) { logger.Infof( ctx, "Processing session creation request, tenant ID: %d, knowledge base ID: %s, agent mode: %v, agent KBs: %v", - tenantID.(uint), + tenantID, request.KnowledgeBaseID, isAgentMode, hasAgentKnowledgeBases, @@ -77,7 +77,7 @@ func (h *Handler) CreateSession(c *gin.Context) { // Create session object with base properties createdSession := &types.Session{ - TenantID: tenantID.(uint), + TenantID: tenantID.(uint64), KnowledgeBaseID: request.KnowledgeBaseID, AgentConfig: request.AgentConfig, // Set agent config if provided } @@ -281,7 +281,7 @@ func (h *Handler) UpdateSession(c *gin.Context) { } session.ID = id - session.TenantID = tenantID.(uint) + session.TenantID = tenantID.(uint64) // Call service to update session if err := h.sessionService.UpdateSession(ctx, &session); err != nil { diff --git a/internal/handler/session/stream.go b/internal/handler/session/stream.go index 04701a05..77c4c831 100644 --- a/internal/handler/session/stream.go +++ b/internal/handler/session/stream.go @@ -192,7 +192,7 @@ func (h *Handler) StopSession(c *gin.Context) { c.JSON(401, gin.H{"error": "Unauthorized"}) return } - tenantIDUint := tenantID.(uint) + tenantIDUint := tenantID.(uint64) // Verify message ownership and status message, err := h.messageService.GetMessage(ctx, sessionID, assistantMessageID) diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go index c2f5a897..3b5bc339 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -91,7 +91,7 @@ func (h *TenantHandler) GetTenant(c *gin.Context) { return } - tenant, err := h.service.GetTenantByID(ctx, uint(id)) + tenant, err := h.service.GetTenantByID(ctx, id) if err != nil { // Check if this is an application-specific error if appErr, ok := errors.IsAppError(err); ok { @@ -136,7 +136,7 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) { logger.Infof(ctx, "Updating tenant, ID: %d, Name: %s", id, tenantData.Name) - tenantData.ID = uint(id) + tenantData.ID = id updatedTenant, err := h.service.UpdateTenant(ctx, &tenantData) if err != nil { // Check if this is an application-specific error @@ -176,7 +176,7 @@ func (h *TenantHandler) DeleteTenant(c *gin.Context) { logger.Infof(ctx, "Deleting tenant, ID: %d", id) - if err := h.service.DeleteTenant(ctx, uint(id)); err != nil { + if err := h.service.DeleteTenant(ctx, id); err != nil { // Check if this is an application-specific error if appErr, ok := errors.IsAppError(err); ok { logger.Error(ctx, "Failed to delete tenant: application error", appErr) @@ -337,6 +337,11 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) { // Get existing tenant tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) + if tenant == nil { + logger.Error(ctx, "Tenant is empty") + c.Error(errors.NewBadRequestError("Tenant is empty")) + return + } // Update agent configuration useCustomPrompt := false if tenant.AgentConfig != nil { @@ -557,15 +562,13 @@ func (h *TenantHandler) GetTenantConversationConfig(c *gin.Context) { // If tenant has no conversation config, return defaults from config.yaml var response *types.ConversationConfig - if tenant.ConversationConfig == nil { + if tc := tenant.ConversationConfig; tc == nil { logger.Info(ctx, "Tenant has no conversation config, returning defaults") response = h.buildDefaultConversationConfig() } else { logger.Infof(ctx, "Tenant has conversation config, merging with defaults, Tenant ID: %d", tenant.ID) // Merge tenant config with defaults, so that newly added fields always have valid values defaultCfg := h.buildDefaultConversationConfig() - tc := tenant.ConversationConfig - // Prompt related defaultCfg.UseCustomSystemPrompt = tc.UseCustomSystemPrompt if !defaultCfg.UseCustomSystemPrompt && tc.Prompt != "" { diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index 334162e1..9e0bbf06 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -104,7 +104,7 @@ func Auth(tenantService interfaces.TenantService, userService interfaces.UserSer // Verify API key validity (matches the one in database) t, err := tenantService.GetTenantByID(c.Request.Context(), tenantID) if err != nil { - log.Printf("Error getting tenant by ID: %v, tenantID: %d, apiKey: %s", err, tenantID, apiKey) + log.Printf("Error getting tenant by ID: %v, tenantID: %d", err, tenantID) c.JSON(http.StatusUnauthorized, gin.H{ "error": "Unauthorized: invalid API key", }) diff --git a/internal/middleware/trace.go b/internal/middleware/trace.go index e7febfc9..9dbb2d85 100644 --- a/internal/middleware/trace.go +++ b/internal/middleware/trace.go @@ -11,7 +11,6 @@ import ( "go.opentelemetry.io/otel/codes" "github.com/Tencent/WeKnora/internal/tracing" - "github.com/Tencent/WeKnora/internal/types" ) // Custom ResponseWriter to capture response content @@ -36,12 +35,6 @@ func TracingMiddleware() gin.HandlerFunc { return } - // Get request ID as Span ID - requestID := c.GetString(string(types.RequestIDContextKey)) - if requestID == "" { - requestID = c.GetHeader("X-Request-ID") - } - // Create new span spanName := fmt.Sprintf("%s %s", c.Request.Method, c.FullPath()) ctx, span := tracing.ContextWithSpan(c.Request.Context(), spanName) diff --git a/internal/models/embedding/batch.go b/internal/models/embedding/batch.go index 3c8e2269..506948f0 100644 --- a/internal/models/embedding/batch.go +++ b/internal/models/embedding/batch.go @@ -62,6 +62,9 @@ func (e *batchEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, } mu.Lock() for i, text := range texts { + if text == nil { + continue + } text.results = embedding[i] } mu.Unlock() diff --git a/internal/types/chat_manage.go b/internal/types/chat_manage.go index af51eb17..21c362a4 100644 --- a/internal/types/chat_manage.go +++ b/internal/types/chat_manage.go @@ -48,8 +48,8 @@ type ChatManage struct { MessageID string `json:"-"` // Assistant message ID for event emission // Web search configuration (internal use) - TenantID uint `json:"-"` // Tenant ID for retrieving web search config - WebSearchEnabled bool `json:"-"` // Whether web search is enabled for this request + TenantID uint64 `json:"-"` // Tenant ID for retrieving web search config + WebSearchEnabled bool `json:"-"` // Whether web search is enabled for this request } // Clone creates a deep copy of the ChatManage object diff --git a/internal/types/chunk.go b/internal/types/chunk.go index f1edfa39..b64fdd22 100644 --- a/internal/types/chunk.go +++ b/internal/types/chunk.go @@ -67,7 +67,7 @@ type Chunk struct { // Unique identifier of the chunk, using UUID format ID string `json:"id" gorm:"type:varchar(36);primaryKey"` // Tenant ID, used for multi-tenant isolation - TenantID uint `json:"tenant_id"` + TenantID uint64 `json:"tenant_id"` // ID of the parent knowledge, associated with the Knowledge model KnowledgeID string `json:"knowledge_id"` // ID of the knowledge base, for quick location diff --git a/internal/types/evaluation.go b/internal/types/evaluation.go index 5e477c6e..3e8d1d07 100644 --- a/internal/types/evaluation.go +++ b/internal/types/evaluation.go @@ -23,7 +23,7 @@ const ( // EvaluationTask contains information about an evaluation task type EvaluationTask struct { ID string `json:"id"` // Unique task ID - TenantID uint `json:"tenant_id"` // Tenant/Organization ID + TenantID uint64 `json:"tenant_id"` // Tenant/Organization ID DatasetID string `json:"dataset_id"` // Dataset ID for evaluation StartTime time.Time `json:"start_time"` // Task start time diff --git a/internal/types/extract_graph.go b/internal/types/extract_graph.go index c7bb0fa0..cdd0b488 100644 --- a/internal/types/extract_graph.go +++ b/internal/types/extract_graph.go @@ -7,7 +7,7 @@ const ( ) type ExtractChunkPayload struct { - TenantID uint `json:"tenant_id"` + TenantID uint64 `json:"tenant_id"` ChunkID string `json:"chunk_id"` ModelID string `json:"model_id"` } @@ -15,7 +15,7 @@ type ExtractChunkPayload struct { // DocumentProcessPayload 文档处理任务payload type DocumentProcessPayload struct { RequestId string `json:"request_id"` - TenantID uint `json:"tenant_id"` + TenantID uint64 `json:"tenant_id"` KnowledgeID string `json:"knowledge_id"` KnowledgeBaseID string `json:"knowledge_base_id"` FilePath string `json:"file_path,omitempty"` // 文件路径(文件导入时使用) @@ -28,7 +28,7 @@ type DocumentProcessPayload struct { // FAQImportPayload FAQ导入任务payload type FAQImportPayload struct { - TenantID uint `json:"tenant_id"` + TenantID uint64 `json:"tenant_id"` TaskID string `json:"task_id"` KBID string `json:"kb_id"` KnowledgeID string `json:"knowledge_id"` diff --git a/internal/types/interfaces/chunk.go b/internal/types/interfaces/chunk.go index b31b0768..dbcd6e6f 100644 --- a/internal/types/interfaces/chunk.go +++ b/internal/types/interfaces/chunk.go @@ -11,40 +11,40 @@ type ChunkRepository interface { // CreateChunks creates chunks CreateChunks(ctx context.Context, chunks []*types.Chunk) error // GetChunkByID gets a chunk by id - GetChunkByID(ctx context.Context, tenantID uint, id string) (*types.Chunk, error) + GetChunkByID(ctx context.Context, tenantID uint64, id string) (*types.Chunk, error) // ListChunksByID lists chunks by ids - ListChunksByID(ctx context.Context, tenantID uint, ids []string) ([]*types.Chunk, error) + ListChunksByID(ctx context.Context, tenantID uint64, ids []string) ([]*types.Chunk, error) // ListChunksByKnowledgeID lists chunks by knowledge id - ListChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error) + ListChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) // ListPagedChunksByKnowledgeID lists paged chunks by knowledge id. // When tagID is non-empty, results are filtered by tag_id. ListPagedChunksByKnowledgeID( ctx context.Context, - tenantID uint, + tenantID uint64, knowledgeID string, page *types.Pagination, chunkType []types.ChunkType, tagID string, ) ([]*types.Chunk, int64, error) - ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error) + ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error) // UpdateChunk updates a chunk UpdateChunk(ctx context.Context, chunk *types.Chunk) error // UpdateChunks updates chunks in batch UpdateChunks(ctx context.Context, chunks []*types.Chunk) error // DeleteChunk deletes a chunk - DeleteChunk(ctx context.Context, tenantID uint, id string) error + DeleteChunk(ctx context.Context, tenantID uint64, id string) error // DeleteChunks deletes chunks by IDs in batch - DeleteChunks(ctx context.Context, tenantID uint, ids []string) error + DeleteChunks(ctx context.Context, tenantID uint64, ids []string) error // DeleteChunksByKnowledgeID deletes chunks by knowledge id - DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) error + DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) error // DeleteByKnowledgeList deletes all chunks for a knowledge list - DeleteByKnowledgeList(ctx context.Context, tenantID uint, knowledgeIDs []string) error + DeleteByKnowledgeList(ctx context.Context, tenantID uint64, knowledgeIDs []string) error // CountChunksByKnowledgeBaseID counts the number of chunks in a knowledge base. - CountChunksByKnowledgeBaseID(ctx context.Context, tenantID uint, kbID string) (int64, error) + CountChunksByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error) // DeleteUnindexedChunks deletes unindexed chunks by knowledge id and chunk index range - DeleteUnindexedChunks(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error) + DeleteUnindexedChunks(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) // ListAllFAQChunksByKnowledgeID lists all FAQ chunks for a knowledge ID (only ID and ContentHash fields for efficiency) - ListAllFAQChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error) + ListAllFAQChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) } // ChunkService defines the interface for chunk service operations @@ -75,7 +75,7 @@ type ChunkService interface { // DeleteByKnowledgeList deletes all chunks for a knowledge list DeleteByKnowledgeList(ctx context.Context, ids []string) error // ListChunkByParentID lists chunks by parent id - ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error) + ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error) // GetRepository gets the chunk repository GetRepository() ChunkRepository } diff --git a/internal/types/interfaces/file.go b/internal/types/interfaces/file.go index 307aaea1..448121f2 100644 --- a/internal/types/interfaces/file.go +++ b/internal/types/interfaces/file.go @@ -10,7 +10,7 @@ import ( // FileService provides methods to save, retrieve, and delete files. type FileService interface { // SaveFile saves a file. - SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint, knowledgeID string) (string, error) + SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) // GetFile retrieves a file. GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) // DeleteFile deletes a file. diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.go index 7aa4e41c..5d6ae569 100644 --- a/internal/types/interfaces/knowledge.go +++ b/internal/types/interfaces/knowledge.go @@ -31,7 +31,7 @@ type KnowledgeService interface { // GetKnowledgeByID retrieves knowledge by ID. GetKnowledgeByID(ctx context.Context, id string) (*types.Knowledge, error) // GetKnowledgeBatch retrieves a batch of knowledge by IDs. - GetKnowledgeBatch(ctx context.Context, tenantID uint, ids []string) ([]*types.Knowledge, error) + GetKnowledgeBatch(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error) // ListKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base. ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string) ([]*types.Knowledge, error) // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination. @@ -83,34 +83,34 @@ type KnowledgeService interface { // KnowledgeRepository defines the interface for knowledge repositories. type KnowledgeRepository interface { CreateKnowledge(ctx context.Context, knowledge *types.Knowledge) error - GetKnowledgeByID(ctx context.Context, tenantID uint, id string) (*types.Knowledge, error) - ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint, kbID string) ([]*types.Knowledge, error) + GetKnowledgeByID(ctx context.Context, tenantID uint64, id string) (*types.Knowledge, error) + ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) ([]*types.Knowledge, error) // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination. // When tagID is non-empty, results are filtered by tag_id. ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context, - tenantID uint, kbID string, page *types.Pagination, tagID string, + tenantID uint64, kbID string, page *types.Pagination, tagID string, ) ([]*types.Knowledge, int64, error) UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error // UpdateKnowledgeBatch updates knowledge items in batch UpdateKnowledgeBatch(ctx context.Context, knowledgeList []*types.Knowledge) error - DeleteKnowledge(ctx context.Context, tenantID uint, id string) error - DeleteKnowledgeList(ctx context.Context, tenantID uint, ids []string) error - GetKnowledgeBatch(ctx context.Context, tenantID uint, ids []string) ([]*types.Knowledge, error) + DeleteKnowledge(ctx context.Context, tenantID uint64, id string) error + DeleteKnowledgeList(ctx context.Context, tenantID uint64, ids []string) error + GetKnowledgeBatch(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error) // CheckKnowledgeExists checks if knowledge already exists. // For file types, check by fileHash or (fileName+fileSize). // For URL types, check by URL. // Returns whether it exists, the existing knowledge object (if any), and possible error. CheckKnowledgeExists( ctx context.Context, - tenantID uint, + tenantID uint64, kbID string, params *types.KnowledgeCheckParams, ) (bool, *types.Knowledge, error) // AminusB returns the difference set of A and B. - AminusB(ctx context.Context, Atenant uint, A string, Btenant uint, B string) ([]string, error) + AminusB(ctx context.Context, Atenant uint64, A string, Btenant uint64, B string) ([]string, error) UpdateKnowledgeColumn(ctx context.Context, id string, column string, value interface{}) error // CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base. - CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint, kbID string) (int64, error) + CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error) // CountKnowledgeByStatus counts the number of knowledge items with the specified parse status. - CountKnowledgeByStatus(ctx context.Context, tenantID uint, kbID string, parseStatuses []string) (int64, error) + CountKnowledgeByStatus(ctx context.Context, tenantID uint64, kbID string, parseStatuses []string) (int64, error) } diff --git a/internal/types/interfaces/knowledgebase.go b/internal/types/interfaces/knowledgebase.go index 80a60c63..e8e91e86 100644 --- a/internal/types/interfaces/knowledgebase.go +++ b/internal/types/interfaces/knowledgebase.go @@ -126,7 +126,7 @@ type KnowledgeBaseRepository interface { // Returns: // - List of knowledge base objects // - Possible errors such as database errors, etc. - ListKnowledgeBasesByTenantID(ctx context.Context, tenantID uint) ([]*types.KnowledgeBase, error) + ListKnowledgeBasesByTenantID(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBase, error) // UpdateKnowledgeBase updates a knowledge base record // Parameters: diff --git a/internal/types/interfaces/mcp_service.go b/internal/types/interfaces/mcp_service.go index 1875c81a..c1803350 100644 --- a/internal/types/interfaces/mcp_service.go +++ b/internal/types/interfaces/mcp_service.go @@ -12,22 +12,22 @@ type MCPServiceRepository interface { Create(ctx context.Context, service *types.MCPService) error // GetByID retrieves an MCP service by ID and tenant ID - GetByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error) + GetByID(ctx context.Context, tenantID uint64, id string) (*types.MCPService, error) // List retrieves all MCP services for a tenant - List(ctx context.Context, tenantID uint) ([]*types.MCPService, error) + List(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) // ListEnabled retrieves all enabled MCP services for a tenant - ListEnabled(ctx context.Context, tenantID uint) ([]*types.MCPService, error) + ListEnabled(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) // ListByIDs retrieves MCP services by multiple IDs for a tenant - ListByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error) + ListByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.MCPService, error) // Update updates an MCP service Update(ctx context.Context, service *types.MCPService) error // Delete deletes an MCP service (soft delete) - Delete(ctx context.Context, tenantID uint, id string) error + Delete(ctx context.Context, tenantID uint64, id string) error } // MCPServiceService defines the interface for MCP service business logic @@ -36,27 +36,26 @@ type MCPServiceService interface { CreateMCPService(ctx context.Context, service *types.MCPService) error // GetMCPServiceByID retrieves an MCP service by ID - GetMCPServiceByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error) + GetMCPServiceByID(ctx context.Context, tenantID uint64, id string) (*types.MCPService, error) // ListMCPServices lists all MCP services for a tenant - ListMCPServices(ctx context.Context, tenantID uint) ([]*types.MCPService, error) + ListMCPServices(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) // ListMCPServicesByIDs retrieves multiple MCP services by IDs - ListMCPServicesByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error) + ListMCPServicesByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.MCPService, error) // UpdateMCPService updates an MCP service UpdateMCPService(ctx context.Context, service *types.MCPService) error // DeleteMCPService deletes an MCP service - DeleteMCPService(ctx context.Context, tenantID uint, id string) error + DeleteMCPService(ctx context.Context, tenantID uint64, id string) error // TestMCPService tests the connection to an MCP service and returns available tools/resources - TestMCPService(ctx context.Context, tenantID uint, id string) (*types.MCPTestResult, error) + TestMCPService(ctx context.Context, tenantID uint64, id string) (*types.MCPTestResult, error) // GetMCPServiceTools retrieves the list of tools from an MCP service - GetMCPServiceTools(ctx context.Context, tenantID uint, id string) ([]*types.MCPTool, error) + GetMCPServiceTools(ctx context.Context, tenantID uint64, id string) ([]*types.MCPTool, error) // GetMCPServiceResources retrieves the list of resources from an MCP service - GetMCPServiceResources(ctx context.Context, tenantID uint, id string) ([]*types.MCPResource, error) + GetMCPServiceResources(ctx context.Context, tenantID uint64, id string) ([]*types.MCPResource, error) } - diff --git a/internal/types/interfaces/model.go b/internal/types/interfaces/model.go index c1f60113..efcd5ec2 100644 --- a/internal/types/interfaces/model.go +++ b/internal/types/interfaces/model.go @@ -34,18 +34,18 @@ type ModelRepository interface { // Create creates a model Create(ctx context.Context, model *types.Model) error // GetByID gets a model by ID - GetByID(ctx context.Context, tenantID uint, id string) (*types.Model, error) + GetByID(ctx context.Context, tenantID uint64, id string) (*types.Model, error) // List lists all models List( ctx context.Context, - tenantID uint, + tenantID uint64, modelType types.ModelType, source types.ModelSource, ) ([]*types.Model, error) // Update updates a model Update(ctx context.Context, model *types.Model) error // Delete deletes a model - Delete(ctx context.Context, tenantID uint, id string) error + Delete(ctx context.Context, tenantID uint64, id string) error // ClearDefaultByType clears the default flag for all models of a specific type, optionally excluding a specific model ID ClearDefaultByType(ctx context.Context, tenantID uint, modelType types.ModelType, excludeID string) error } diff --git a/internal/types/interfaces/session.go b/internal/types/interfaces/session.go index 94d59911..a25c29d3 100644 --- a/internal/types/interfaces/session.go +++ b/internal/types/interfaces/session.go @@ -56,13 +56,13 @@ type SessionRepository interface { // Create creates a session Create(ctx context.Context, session *types.Session) (*types.Session, error) // Get gets a session - Get(ctx context.Context, tenantID uint, id string) (*types.Session, error) + Get(ctx context.Context, tenantID uint64, id string) (*types.Session, error) // GetByTenantID gets all sessions of a tenant - GetByTenantID(ctx context.Context, tenantID uint) ([]*types.Session, error) + GetByTenantID(ctx context.Context, tenantID uint64) ([]*types.Session, error) // GetPagedByTenantID gets paged sessions of a tenant - GetPagedByTenantID(ctx context.Context, tenantID uint, page *types.Pagination) ([]*types.Session, int64, error) + GetPagedByTenantID(ctx context.Context, tenantID uint64, page *types.Pagination) ([]*types.Session, int64, error) // Update updates a session Update(ctx context.Context, session *types.Session) error // Delete deletes a session - Delete(ctx context.Context, tenantID uint, id string) error + Delete(ctx context.Context, tenantID uint64, id string) error } diff --git a/internal/types/interfaces/tag.go b/internal/types/interfaces/tag.go index 1f5e6566..cb0069a0 100644 --- a/internal/types/interfaces/tag.go +++ b/internal/types/interfaces/tag.go @@ -22,9 +22,9 @@ type KnowledgeTagService interface { type KnowledgeTagRepository interface { Create(ctx context.Context, tag *types.KnowledgeTag) error Update(ctx context.Context, tag *types.KnowledgeTag) error - GetByID(ctx context.Context, tenantID uint, id string) (*types.KnowledgeTag, error) - ListByKB(ctx context.Context, tenantID uint, kbID string) ([]*types.KnowledgeTag, error) - Delete(ctx context.Context, tenantID uint, id string) error + GetByID(ctx context.Context, tenantID uint64, id string) (*types.KnowledgeTag, error) + ListByKB(ctx context.Context, tenantID uint64, kbID string) ([]*types.KnowledgeTag, error) + Delete(ctx context.Context, tenantID uint64, id string) error // CountReferences returns number of knowledges and chunks that reference the tag. - CountReferences(ctx context.Context, tenantID uint, kbID string, tagID string) (knowledgeCount int64, chunkCount int64, err error) + CountReferences(ctx context.Context, tenantID uint64, kbID string, tagID string) (knowledgeCount int64, chunkCount int64, err error) } diff --git a/internal/types/interfaces/tenant.go b/internal/types/interfaces/tenant.go index df5839e7..1a3320cd 100644 --- a/internal/types/interfaces/tenant.go +++ b/internal/types/interfaces/tenant.go @@ -11,17 +11,17 @@ type TenantService interface { // CreateTenant creates a tenant CreateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error) // GetTenantByID gets a tenant by ID - GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) + GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) // ListTenants lists all tenants ListTenants(ctx context.Context) ([]*types.Tenant, error) // UpdateTenant updates a tenant UpdateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error) // DeleteTenant deletes a tenant - DeleteTenant(ctx context.Context, id uint) error + DeleteTenant(ctx context.Context, id uint64) error // UpdateAPIKey updates the API key - UpdateAPIKey(ctx context.Context, id uint) (string, error) + UpdateAPIKey(ctx context.Context, id uint64) (string, error) // ExtractTenantIDFromAPIKey extracts the tenant ID from the API key - ExtractTenantIDFromAPIKey(apiKey string) (uint, error) + ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) } // TenantRepository defines the tenant repository interface @@ -29,13 +29,13 @@ type TenantRepository interface { // CreateTenant creates a tenant CreateTenant(ctx context.Context, tenant *types.Tenant) error // GetTenantByID gets a tenant by ID - GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) + GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) // ListTenants lists all tenants ListTenants(ctx context.Context) ([]*types.Tenant, error) // UpdateTenant updates a tenant UpdateTenant(ctx context.Context, tenant *types.Tenant) error // DeleteTenant deletes a tenant - DeleteTenant(ctx context.Context, id uint) error + DeleteTenant(ctx context.Context, id uint64) error // AdjustStorageUsed adjusts the storage used for a tenant - AdjustStorageUsed(ctx context.Context, tenantID uint, delta int64) error + AdjustStorageUsed(ctx context.Context, tenantID uint64, delta int64) error } diff --git a/internal/types/knowledge.go b/internal/types/knowledge.go index 8aaf5963..11096a7b 100644 --- a/internal/types/knowledge.go +++ b/internal/types/knowledge.go @@ -27,7 +27,7 @@ type Knowledge struct { // Unique identifier of the knowledge ID string `json:"id" gorm:"type:varchar(36);primaryKey"` // Tenant ID - TenantID uint `json:"tenant_id"` + TenantID uint64 `json:"tenant_id"` // ID of the knowledge base KnowledgeBaseID string `json:"knowledge_base_id"` // Optional tag ID for categorization within a knowledge base diff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.go index 25f18e5d..3df1215e 100644 --- a/internal/types/knowledgebase.go +++ b/internal/types/knowledgebase.go @@ -46,7 +46,7 @@ type KnowledgeBase struct { // Description of the knowledge base Description string `yaml:"description" json:"description"` // Tenant ID - TenantID uint `yaml:"tenant_id" json:"tenant_id"` + TenantID uint64 `yaml:"tenant_id" json:"tenant_id"` // Chunking configuration ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config" gorm:"type:json"` // Image processing configuration diff --git a/internal/types/mcp.go b/internal/types/mcp.go index c64de5be..9f21de43 100644 --- a/internal/types/mcp.go +++ b/internal/types/mcp.go @@ -21,7 +21,7 @@ const ( // MCPService represents an MCP (Model Context Protocol) service configuration type MCPService struct { ID string `json:"id" gorm:"type:varchar(36);primaryKey"` - TenantID uint `json:"tenant_id" gorm:"index"` + TenantID uint64 `json:"tenant_id" gorm:"index"` Name string `json:"name" gorm:"type:varchar(255);not null"` Description string `json:"description" gorm:"type:text"` Enabled bool `json:"enabled" gorm:"default:true;index"` diff --git a/internal/types/model.go b/internal/types/model.go index 7fdc1685..1d86cbde 100644 --- a/internal/types/model.go +++ b/internal/types/model.go @@ -54,7 +54,7 @@ type Model struct { // Unique identifier of the model ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"` // Tenant ID - TenantID uint `yaml:"tenant_id" json:"tenant_id"` + TenantID uint64 `yaml:"tenant_id" json:"tenant_id"` // Name of the model Name string `yaml:"name" json:"name"` // Type of the model diff --git a/internal/types/session.go b/internal/types/session.go index 9f339d06..65865120 100644 --- a/internal/types/session.go +++ b/internal/types/session.go @@ -77,7 +77,7 @@ type Session struct { // Description Description string `json:"description"` // Tenant ID - TenantID uint `json:"tenant_id" gorm:"index"` + TenantID uint64 `json:"tenant_id" gorm:"index"` // Strategy configuration KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID @@ -93,8 +93,8 @@ type Session struct { RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值 SummaryModelID string `json:"summary_model_id"` // 总结模型ID SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数 - AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases) - ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选) + AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases) + ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选) CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` diff --git a/internal/types/tag.go b/internal/types/tag.go index 7bc79bb9..5b9de754 100644 --- a/internal/types/tag.go +++ b/internal/types/tag.go @@ -9,7 +9,7 @@ type KnowledgeTag struct { // Unique identifier of the tag (UUID) ID string `json:"id" gorm:"type:varchar(36);primaryKey"` // Tenant ID - TenantID uint `json:"tenant_id"` + TenantID uint64 `json:"tenant_id"` // Knowledge base ID that this tag belongs to KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"` // Tag name, unique within the same knowledge base diff --git a/internal/types/tenant.go b/internal/types/tenant.go index b568ab01..904ab0ad 100644 --- a/internal/types/tenant.go +++ b/internal/types/tenant.go @@ -11,7 +11,7 @@ import ( // Tenant represents the tenant type Tenant struct { // ID - ID uint `yaml:"id" json:"id" gorm:"primaryKey"` + ID uint64 `yaml:"id" json:"id" gorm:"primaryKey"` // Name Name string `yaml:"name" json:"name"` // Description diff --git a/internal/types/user.go b/internal/types/user.go index 59b80193..09e64321 100644 --- a/internal/types/user.go +++ b/internal/types/user.go @@ -19,7 +19,7 @@ type User struct { // Avatar URL of the user Avatar string `json:"avatar" gorm:"type:varchar(500)"` // Tenant ID that the user belongs to - TenantID uint `json:"tenant_id" gorm:"index"` + TenantID uint64 `json:"tenant_id" gorm:"index"` // Whether the user is active IsActive bool `json:"is_active" gorm:"default:true"` // Creation time of the user @@ -93,7 +93,7 @@ type UserInfo struct { Username string `json:"username"` Email string `json:"email"` Avatar string `json:"avatar"` - TenantID uint `json:"tenant_id"` + TenantID uint64 `json:"tenant_id"` IsActive bool `json:"is_active"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"`