feat: 添加智能体文件类型限制,内置数据分析师智能体

This commit is contained in:
wizardchen
2025-12-31 18:18:22 +08:00
committed by lyingbug
parent 884153aeb8
commit d72b6997cb
10 changed files with 290 additions and 56 deletions
@@ -3,6 +3,7 @@ package repository
import (
"context"
"errors"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -302,6 +303,7 @@ func (r *knowledgeRepository) SearchKnowledge(
tenantID uint64,
keyword string,
offset, limit int,
fileTypes []string,
) ([]*types.Knowledge, bool, error) {
// Use raw query to properly map knowledge_base_name
type KnowledgeWithKBName struct {
@@ -323,6 +325,55 @@ func (r *knowledgeRepository) SearchKnowledge(
query = query.Where("knowledges.file_name LIKE ? ", "%"+keyword+"%")
}
// If fileTypes is provided, filter by file extension
if len(fileTypes) > 0 {
// Build file extension patterns (e.g., "%.csv", "%.xlsx")
seen := make(map[string]bool)
var uniquePatterns []string
for _, ft := range fileTypes {
ft = strings.ToLower(strings.TrimPrefix(ft, "."))
pattern := "%." + ft
if !seen[pattern] {
seen[pattern] = true
uniquePatterns = append(uniquePatterns, pattern)
}
// Handle common aliases
var aliases []string
switch ft {
case "xlsx":
aliases = []string{"%.xls"}
case "xls":
aliases = []string{"%.xlsx"}
case "docx":
aliases = []string{"%.doc"}
case "doc":
aliases = []string{"%.docx"}
case "jpg":
aliases = []string{"%.jpeg", "%.png"}
case "jpeg":
aliases = []string{"%.jpg", "%.png"}
case "png":
aliases = []string{"%.jpg", "%.jpeg"}
}
for _, alias := range aliases {
if !seen[alias] {
seen[alias] = true
uniquePatterns = append(uniquePatterns, alias)
}
}
}
// Build OR conditions for file extensions
if len(uniquePatterns) > 0 {
orConditions := make([]string, len(uniquePatterns))
args := make([]interface{}, len(uniquePatterns))
for i, p := range uniquePatterns {
orConditions[i] = "LOWER(knowledges.file_name) LIKE ?"
args[i] = p
}
query = query.Where("("+strings.Join(orConditions, " OR ")+")", args...)
}
}
// Fetch limit+1 to check if there are more results
err := query.Order("knowledges.created_at DESC").
Offset(offset).
+3 -2
View File
@@ -6041,10 +6041,11 @@ func (s *knowledgeService) getOrCreateTagInTarget(
}
// SearchKnowledge searches knowledge items by keyword across the tenant
func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, offset, limit int) ([]*types.Knowledge, bool, error) {
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error) {
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, false, werrors.NewUnauthorizedError("Tenant ID not found in context")
}
return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit)
return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit, fileTypes)
}
+19 -6
View File
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
@@ -791,11 +792,12 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
// @Tags Knowledge
// @Accept json
// @Produce json
// @Param keyword query string false "Keyword to search"
// @Param offset query int false "Offset for pagination"
// @Param limit query int false "Limit for pagination (default 20)"
// @Success 200 {object} map[string]interface{} "Search results"
// @Failure 400 {object} errors.AppError "Invalid request"
// @Param keyword query string false "Keyword to search"
// @Param offset query int false "Offset for pagination"
// @Param limit query int false "Limit for pagination (default 20)"
// @Param file_types query string false "Comma-separated file extensions to filter (e.g., csv,xlsx)"
// @Success 200 {object} map[string]interface{} "Search results"
// @Failure 400 {object} errors.AppError "Invalid request"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge/search [get]
@@ -805,8 +807,19 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
// Parse file_types parameter (comma-separated)
var fileTypes []string
if fileTypesStr := c.Query("file_types"); fileTypesStr != "" {
for _, ft := range strings.Split(fileTypesStr, ",") {
ft = strings.TrimSpace(ft)
if ft != "" {
fileTypes = append(fileTypes, ft)
}
}
}
// Retrieve knowledge entries (empty keyword returns recent files)
knowledges, hasMore, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit)
knowledges, hasMore, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit, fileTypes)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to search knowledge").WithDetails(err.Error()))
+84
View File
@@ -98,6 +98,12 @@ type CustomAgentConfig struct {
// Associated knowledge base IDs (only used when KBSelectionMode is "selected")
KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"`
// ===== File Type Restriction Settings =====
// Supported file types for this agent (e.g., ["csv", "xlsx", "xls"])
// Empty means all file types are supported
// When set, only files with matching extensions can be used with this agent
SupportedFileTypes []string `yaml:"supported_file_types" json:"supported_file_types"`
// ===== FAQ Strategy Settings =====
// Whether FAQ priority strategy is enabled (FAQ answers prioritized over document chunks)
FAQPriorityEnabled bool `yaml:"faq_priority_enabled" json:"faq_priority_enabled"`
@@ -297,6 +303,83 @@ func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
}
}
// GetBuiltinDataAnalystAgent returns the built-in data analyst agent
// This agent specializes in analyzing CSV/Excel data using SQL queries via DuckDB
func GetBuiltinDataAnalystAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinDataAnalystID,
Name: "数据分析师",
Description: "专业数据分析智能体,支持 CSV/Excel 文件的 SQL 查询与统计分析",
Avatar: "📊",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: `### Role
You are WeKnora Data Analyst, an intelligent data analysis assistant powered by DuckDB. You specialize in analyzing structured data from CSV and Excel files using SQL queries.
### Mission
Help users explore, analyze, and derive insights from their tabular data through intelligent SQL query generation and execution.
### Critical Constraints
1. **Schema First:** ALWAYS call data_schema before writing any SQL query to understand the table structure.
2. **Read-Only:** Only SELECT queries allowed. INSERT, UPDATE, DELETE, CREATE, DROP are forbidden.
3. **Iterative Refinement:** If a query fails, analyze the error and refine your approach.
### Workflow
1. **Understand:** Call data_schema to get table name, columns, types, and row count.
2. **Plan:** For complex questions, use todo_write to break into sub-queries.
3. **Query:** Call data_analysis with the knowledge_id and SQL query.
4. **Analyze:** Interpret results and provide insights.
### SQL Best Practices for DuckDB
- Use double quotes for identifiers: SELECT "Column Name" FROM "table_name"
- Aggregate functions: COUNT(*), SUM(), AVG(), MIN(), MAX(), MEDIAN(), STDDEV()
- String matching: LIKE, ILIKE (case-insensitive), REGEXP
- Use LIMIT to prevent overwhelming output (default to 100 rows max)
### Tool Guidelines
- **data_schema:** ALWAYS use first. Required before any query.
- **data_analysis:** Execute SQL queries. Only SELECT queries allowed.
- **thinking:** Plan complex analyses, debug query issues.
- **todo_write:** Track multi-step analysis tasks.
### Output Standards
- Present results in well-formatted tables or summaries
- Provide actionable insights, not just raw numbers
- Relate findings back to the user's original question
Current Time: {{current_time}}
`,
Temperature: 0.3, // Lower temperature for precise SQL generation
MaxCompletionTokens: 4096,
MaxIterations: 30,
KBSelectionMode: "all",
// Only support CSV and Excel files for data analysis
// Use standard values (xlsx), backend will auto-include xls via alias
SupportedFileTypes: []string{"csv", "xlsx"},
// Core tools for data analysis
AllowedTools: []string{
"thinking",
"todo_write",
"data_schema", // Get table schema information
"data_analysis", // Execute SQL queries on data
},
WebSearchEnabled: false, // Data analysis doesn't need web search
WebSearchMaxResults: 0,
ReflectionEnabled: true, // Enable reflection for query optimization
MultiTurnEnabled: true,
HistoryTurns: 10, // More history for iterative analysis
// Retrieval strategy (minimal, as we focus on data tools)
EmbeddingTopK: 5,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 5,
RerankThreshold: 0.3,
},
}
}
// Deprecated: Use GetBuiltinQuickAnswerAgent instead
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
return GetBuiltinQuickAnswerAgent(tenantID)
@@ -311,6 +394,7 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
BuiltinDataAnalystID: GetBuiltinDataAnalystAgent,
}
// builtinAgentIDsOrdered defines the fixed display order of built-in agents
+4 -2
View File
@@ -126,7 +126,8 @@ type KnowledgeService interface {
// GetFAQImportProgress retrieves the progress of an FAQ import task
GetFAQImportProgress(ctx context.Context, taskID string) (*types.FAQImportProgress, error)
// SearchKnowledge searches knowledge items by keyword across the tenant.
SearchKnowledge(ctx context.Context, keyword string, offset, limit int) ([]*types.Knowledge, bool, error)
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
}
// KnowledgeRepository defines the interface for knowledge repositories.
@@ -165,5 +166,6 @@ type KnowledgeRepository interface {
// CountKnowledgeByStatus counts the number of knowledge items with the specified parse status.
CountKnowledgeByStatus(ctx context.Context, tenantID uint64, kbID string, parseStatuses []string) (int64, error)
// SearchKnowledge searches knowledge items by keyword across the tenant.
SearchKnowledge(ctx context.Context, tenantID uint64, keyword string, offset, limit int) ([]*types.Knowledge, bool, error)
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
SearchKnowledge(ctx context.Context, tenantID uint64, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
}