From 5dd4b9f2ee0a8bebc041631c699463cf07c4c632 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 10 Apr 2026 11:58:22 +0800 Subject: [PATCH] feat: Introduce `wiki_flag_issue` tool for reporting wiki page issues - Added a new tool, `wiki_flag_issue`, enabling users to report factual errors, mixed entities, or outdated information on wiki pages. - Updated the agent system prompt and tool definitions to include the new tool, enhancing the agent's capabilities for maintaining wiki accuracy. - Implemented backend functionality for creating, listing, and updating the status of flagged issues, ensuring effective tracking and resolution. These changes significantly improve the agent's ability to manage and report issues within the wiki, fostering a more reliable knowledge base. --- config/builtin_agents.yaml | 1 + .../prompt_templates/agent_system_prompt.yaml | 2 + internal/agent/tools/definitions.go | 2 + internal/agent/tools/wiki_flag_issue.go | 105 ++++++++++++++++++ internal/application/repository/wiki_page.go | 26 +++++ internal/application/service/agent_service.go | 3 + internal/application/service/wiki_page.go | 21 ++++ internal/handler/wiki_page.go | 78 +++++++++++++ internal/router/router.go | 4 + internal/types/interfaces/wiki_page.go | 18 +++ internal/types/wiki_page.go | 22 ++++ .../000033_wiki_page_issues.down.sql | 1 + .../versioned/000033_wiki_page_issues.up.sql | 19 ++++ 13 files changed, 302 insertions(+) create mode 100644 internal/agent/tools/wiki_flag_issue.go create mode 100644 migrations/versioned/000033_wiki_page_issues.down.sql create mode 100644 migrations/versioned/000033_wiki_page_issues.up.sql diff --git a/config/builtin_agents.yaml b/config/builtin_agents.yaml index 3b500ffd..dfdfae66 100644 --- a/config/builtin_agents.yaml +++ b/config/builtin_agents.yaml @@ -174,6 +174,7 @@ builtin_agents: - "wiki_search" - "wiki_read_page" - "wiki_read_source_doc" + - "wiki_flag_issue" web_search_enabled: false web_search_max_results: 0 reflection_enabled: false diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index 77841410..bf8b6d31 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -255,6 +255,7 @@ templates: If the current page doesn't fully answer the question, you MUST call `wiki_read_page` again on these related slugs (1-2 hops). 4. **Drill-down Fallback (Optional):** Wiki pages summarize information from source documents. If the user asks for highly specific details (e.g. exact quotes, raw data, or specific code snippets) that are not present in the wiki page, check the `` section of that wiki page. Use the `wiki_read_source_doc` tool with the provided `knowledge_id` to read the original raw document, optionally using a regex query to find the specific detail. 5. **Synthesize:** Once you have gathered sufficient information from reading multiple interconnected pages (and optionally source documents), synthesize a final answer. If you encountered images (e.g. ``) in the source documents that are relevant to the user's query, be sure to output them in your final response using Markdown format (`![alt](url)`). + 6. **Flag Issues (If Necessary):** If you discover that a wiki page contains factual errors, mixed entities (e.g., two different products combined into one page), or outdated information, OR if the user points out such errors, use the `wiki_flag_issue` tool to submit a maintenance report for that page. @@ -269,6 +270,7 @@ templates: * **wiki_search:** Use this to find entry points. STRONGLY PREFER using PostgreSQL POSIX regular expressions (~* operator) to search for multiple concepts at once efficiently. Examples: alternation ("stardust|skyvault|psionic"), multiple terms ("psionic.*engine"), prefix ("^entity/.*"). Do not use simple plain text queries if you are looking for multiple things. You can provide multiple queries at once to search in parallel. * **wiki_read_page:** Your primary tool. Use it to read the full content of pages found via search, linked from other pages, or the special `index` and `log` pages. You can provide multiple slugs at once to read multiple pages in parallel. * **wiki_read_source_doc:** Use this ONLY as a fallback when a wiki page's content is insufficient and you need to dive into the raw source document listed in the page's `` section. Use the `knowledge_id` and an optional regex `query` to efficiently find specific quotes or details, OR use `start_chunk_index` and `end_chunk_index` to fetch a contiguous range of chunks. + * **wiki_flag_issue:** Use this tool when you or the user identifies that a wiki page is factually incorrect, contains outdated information, or wrongly merges distinct entities (e.g., merging a competitor's product into the current page). This logs an issue for human review or automated maintenance. Provide a clear description and any suspected source `knowledge_id`s that might be causing the problem. diff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.go index 28cdb7de..48b658f2 100644 --- a/internal/agent/tools/definitions.go +++ b/internal/agent/tools/definitions.go @@ -26,6 +26,7 @@ const ( ToolWikiReadPage = "wiki_read_page" ToolWikiSearch = "wiki_search" ToolWikiReadSourceDoc = "wiki_read_source_doc" + ToolWikiFlagIssue = "wiki_flag_issue" ) // AvailableTool defines a simple tool metadata used by settings APIs. @@ -55,6 +56,7 @@ func AvailableToolDefinitions() []AvailableTool { {Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"}, {Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"}, {Name: ToolWikiReadSourceDoc, Label: "精读源文档", Description: "使用知识点深入阅读特定原始文档"}, + {Name: ToolWikiFlagIssue, Label: "标记Wiki问题", Description: "标记页面中存在的事实错误或合并冲突问题"}, } } diff --git a/internal/agent/tools/wiki_flag_issue.go b/internal/agent/tools/wiki_flag_issue.go new file mode 100644 index 00000000..7767d66c --- /dev/null +++ b/internal/agent/tools/wiki_flag_issue.go @@ -0,0 +1,105 @@ +package tools + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +type wikiFlagIssueTool struct { + BaseTool + wikiService interfaces.WikiPageService + kbIDs []string +} + +func NewWikiFlagIssueTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool { + return &wikiFlagIssueTool{ + BaseTool: NewBaseTool( + ToolWikiFlagIssue, + `Flag a wiki page that contains errors, mixed entities, or outdated information. +Use this tool when you or the user identifies that a wiki page is factually incorrect or wrongly merged (e.g., a page contains information about two different products). +This will log an issue for human review or automated maintenance.`, + json.RawMessage(`{ + "type": "object", + "properties": { + "slug": { + "type": "string", + "description": "The slug of the wiki page that has an issue (e.g. 'entity/hunyuan-damoxing')" + }, + "issue_type": { + "type": "string", + "enum": ["mixed_entities", "contradictory_facts", "out_of_date", "other"], + "description": "The category of the issue" + }, + "description": { + "type": "string", + "description": "A detailed explanation of what is wrong with the page and what should be fixed." + }, + "suspected_knowledge_ids": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional list of knowledge_ids (from the block) that you suspect are causing the pollution or error." + } + }, + "required": ["slug", "issue_type", "description"] +}`), + ), + wikiService: wikiService, + kbIDs: kbIDs, + } +} + +func (t *wikiFlagIssueTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) { + var params struct { + Slug string `json:"slug"` + IssueType string `json:"issue_type"` + Description string `json:"description"` + SuspectedKnowledgeIDs []string `json:"suspected_knowledge_ids"` + } + if err := json.Unmarshal(args, ¶ms); err != nil { + return &types.ToolResult{Success: false, Error: "Invalid parameters: " + err.Error()}, nil + } + + slug := strings.TrimSpace(params.Slug) + if slug == "" { + return &types.ToolResult{Success: false, Error: "slug is required"}, nil + } + + if len(t.kbIDs) == 0 { + return &types.ToolResult{Success: false, Error: "No knowledge bases available for issue tracking"}, nil + } + + // Default to first KB ID if multiple (normally there's only one in this context) + kbID := t.kbIDs[0] + + // Verify the page exists + page, err := t.wikiService.GetPageBySlug(ctx, kbID, slug) + if err != nil || page == nil { + return &types.ToolResult{Success: false, Error: fmt.Sprintf("Wiki page with slug '%s' not found", slug)}, nil + } + + issue := &types.WikiPageIssue{ + TenantID: page.TenantID, + KnowledgeBaseID: kbID, + Slug: slug, + IssueType: params.IssueType, + Description: params.Description, + SuspectedKnowledgeIDs: params.SuspectedKnowledgeIDs, + ReportedBy: "wiki-researcher-agent", + Status: "pending", + } + + _, err = t.wikiService.CreateIssue(ctx, issue) + if err != nil { + return &types.ToolResult{Success: false, Error: "Failed to create issue: " + err.Error()}, nil + } + + return &types.ToolResult{ + Success: true, + Output: fmt.Sprintf("Successfully flagged issue for %s. A maintenance ticket has been created for review.", slug), + }, nil +} \ No newline at end of file diff --git a/internal/application/repository/wiki_page.go b/internal/application/repository/wiki_page.go index 57b2278d..b533d7d9 100644 --- a/internal/application/repository/wiki_page.go +++ b/internal/application/repository/wiki_page.go @@ -292,3 +292,29 @@ func (r *wikiPageRepository) CountOrphans(ctx context.Context, kbID string) (int } return count, nil } + +func (r *wikiPageRepository) CreateIssue(ctx context.Context, issue *types.WikiPageIssue) error { + return r.db.WithContext(ctx).Create(issue).Error +} + +func (r *wikiPageRepository) ListIssues(ctx context.Context, kbID string, slug string, status string) ([]*types.WikiPageIssue, error) { + query := r.db.WithContext(ctx).Where("knowledge_base_id = ?", kbID) + if slug != "" { + query = query.Where("slug = ?", slug) + } + if status != "" { + query = query.Where("status = ?", status) + } + + var issues []*types.WikiPageIssue + if err := query.Order("created_at DESC").Find(&issues).Error; err != nil { + return nil, err + } + return issues, nil +} + +func (r *wikiPageRepository) UpdateIssueStatus(ctx context.Context, issueID string, status string) error { + return r.db.WithContext(ctx).Model(&types.WikiPageIssue{}). + Where("id = ?", issueID). + Update("status", status).Error +} diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index efec93e2..c0f35c38 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -382,6 +382,7 @@ func (s *agentService) registerTools( tools.ToolWikiReadPage, tools.ToolWikiSearch, tools.ToolWikiReadSourceDoc, + tools.ToolWikiFlagIssue, ) logger.Infof(ctx, "Wiki KBs detected (%d), wiki tools added", len(wikiKBIDs)) } @@ -453,6 +454,8 @@ func (s *agentService) registerTools( toolToRegister = tools.NewWikiSearchTool(s.wikiPageService, wikiKBIDs) case tools.ToolWikiReadSourceDoc: toolToRegister = tools.NewWikiReadSourceDocTool(s.knowledgeService, s.chunkService) + case tools.ToolWikiFlagIssue: + toolToRegister = tools.NewWikiFlagIssueTool(s.wikiPageService, wikiKBIDs) default: logger.Warnf(ctx, "Unknown tool: %s", toolName) diff --git a/internal/application/service/wiki_page.go b/internal/application/service/wiki_page.go index efeb9002..0d9b9aca 100644 --- a/internal/application/service/wiki_page.go +++ b/internal/application/service/wiki_page.go @@ -477,3 +477,24 @@ func removeString(slice []string, s string) types.StringArray { } return result } + +// CreateIssue logs a new issue for a wiki page +func (s *wikiPageService) CreateIssue(ctx context.Context, issue *types.WikiPageIssue) (*types.WikiPageIssue, error) { + if issue.ID == "" { + issue.ID = uuid.New().String() + } + if err := s.repo.CreateIssue(ctx, issue); err != nil { + return nil, fmt.Errorf("create wiki page issue: %w", err) + } + return issue, nil +} + +// ListIssues retrieves issues for a knowledge base +func (s *wikiPageService) ListIssues(ctx context.Context, kbID string, slug string, status string) ([]*types.WikiPageIssue, error) { + return s.repo.ListIssues(ctx, kbID, slug, status) +} + +// UpdateIssueStatus updates an issue's status +func (s *wikiPageService) UpdateIssueStatus(ctx context.Context, issueID string, status string) error { + return s.repo.UpdateIssueStatus(ctx, issueID, status) +} diff --git a/internal/handler/wiki_page.go b/internal/handler/wiki_page.go index a4b6c27b..e24f3588 100644 --- a/internal/handler/wiki_page.go +++ b/internal/handler/wiki_page.go @@ -373,6 +373,84 @@ func (h *WikiPageHandler) GetStats(c *gin.Context) { c.JSON(http.StatusOK, stats) } +// ListIssues godoc +// @Summary List wiki page issues +// @Description List issues flagged on wiki pages with optional filtering +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param slug query string false "Filter by page slug" +// @Param status query string false "Filter by status (pending, ignored, resolved)" +// @Success 200 {array} types.WikiPageIssue +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/issues [get] +func (h *WikiPageHandler) ListIssues(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + slug := c.Query("slug") + status := c.Query("status") + + issues, err := h.wikiService.ListIssues(c.Request.Context(), kbID, slug, status) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, issues) +} + +// UpdateIssueStatus godoc +// @Summary Update wiki page issue status +// @Description Update the status of a flagged wiki page issue +// @Tags Wiki +// @Accept json +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param issue_id path string true "Issue ID" +// @Param status body object true "New status {'status': 'ignored'}" +// @Success 200 {object} map[string]string +// @Failure 400 {object} errors.AppError +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/issues/{issue_id}/status [put] +func (h *WikiPageHandler) UpdateIssueStatus(c *gin.Context) { + _, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + issueID := secutils.SanitizeForLog(c.Param("issue_id")) + if issueID == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Issue ID is required"}) + return + } + + var req struct { + Status string `json:"status" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()}) + return + } + + validStatuses := map[string]bool{"pending": true, "ignored": true, "resolved": true} + if !validStatuses[req.Status] { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status. Must be pending, ignored, or resolved"}) + return + } + + if err := h.wikiService.UpdateIssueStatus(c.Request.Context(), issueID, req.Status); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Issue status updated successfully"}) +} + // SearchPages godoc // @Summary Search wiki pages // @Description Full-text search over wiki pages diff --git a/internal/router/router.go b/internal/router/router.go index be2cf870..0574029b 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -860,5 +860,9 @@ func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHan wiki.POST("/rebuild-links", wikiHandler.RebuildLinks) wiki.GET("/lint", wikiHandler.Lint) wiki.POST("/auto-fix", wikiHandler.AutoFix) + + // Issues + wiki.GET("/issues", wikiHandler.ListIssues) + wiki.PUT("/issues/:issue_id/status", wikiHandler.UpdateIssueStatus) } } diff --git a/internal/types/interfaces/wiki_page.go b/internal/types/interfaces/wiki_page.go index 3982bf7a..3a5b02b2 100644 --- a/internal/types/interfaces/wiki_page.go +++ b/internal/types/interfaces/wiki_page.go @@ -58,6 +58,15 @@ type WikiPageService interface { // SearchPages performs full-text search over wiki pages. SearchPages(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error) + + // CreateIssue logs a new issue for a wiki page. + CreateIssue(ctx context.Context, issue *types.WikiPageIssue) (*types.WikiPageIssue, error) + + // ListIssues retrieves issues for a knowledge base, optionally filtered by slug and status. + ListIssues(ctx context.Context, kbID string, slug string, status string) ([]*types.WikiPageIssue, error) + + // UpdateIssueStatus updates the status of an issue (e.g. pending -> resolved/ignored). + UpdateIssueStatus(ctx context.Context, issueID string, status string) error } // WikiPageRepository defines the wiki page data persistence interface. @@ -103,4 +112,13 @@ type WikiPageRepository interface { // CountOrphans returns the number of pages with no inbound links. CountOrphans(ctx context.Context, kbID string) (int64, error) + + // CreateIssue inserts a new wiki page issue record. + CreateIssue(ctx context.Context, issue *types.WikiPageIssue) error + + // ListIssues retrieves issues with optional filtering by slug and status. + ListIssues(ctx context.Context, kbID string, slug string, status string) ([]*types.WikiPageIssue, error) + + // UpdateIssueStatus updates an issue's status. + UpdateIssueStatus(ctx context.Context, issueID string, status string) error } diff --git a/internal/types/wiki_page.go b/internal/types/wiki_page.go index 77c8ab24..b8a80f3a 100644 --- a/internal/types/wiki_page.go +++ b/internal/types/wiki_page.go @@ -171,3 +171,25 @@ type WikiStats struct { PendingTasks int64 `json:"pending_tasks"` // number of documents waiting to be ingested IsActive bool `json:"is_active"` // whether wiki ingestion is currently running } + +// WikiPageIssue represents an issue flagged on a specific wiki page. +// These issues are typically identified by agents or linters and stored for review. +type WikiPageIssue struct { + ID string `json:"id" gorm:"type:varchar(36);primaryKey"` + TenantID uint64 `json:"tenant_id" gorm:"index"` + KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"` + Slug string `json:"slug" gorm:"type:varchar(255);index"` + IssueType string `json:"issue_type" gorm:"type:varchar(50)"` + Description string `json:"description" gorm:"type:text"` + SuspectedKnowledgeIDs StringArray `json:"suspected_knowledge_ids" gorm:"type:json"` + Status string `json:"status" gorm:"type:varchar(20);default:'pending';index"` + ReportedBy string `json:"reported_by" gorm:"type:varchar(100)"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"` +} + +// TableName specifies the database table name +func (WikiPageIssue) TableName() string { + return "wiki_page_issues" +} diff --git a/migrations/versioned/000033_wiki_page_issues.down.sql b/migrations/versioned/000033_wiki_page_issues.down.sql new file mode 100644 index 00000000..d347dde0 --- /dev/null +++ b/migrations/versioned/000033_wiki_page_issues.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS wiki_page_issues; diff --git a/migrations/versioned/000033_wiki_page_issues.up.sql b/migrations/versioned/000033_wiki_page_issues.up.sql new file mode 100644 index 00000000..e9fed1f9 --- /dev/null +++ b/migrations/versioned/000033_wiki_page_issues.up.sql @@ -0,0 +1,19 @@ +CREATE TABLE IF NOT EXISTS wiki_page_issues ( + id VARCHAR(36) PRIMARY KEY, + tenant_id BIGINT NOT NULL, + knowledge_base_id VARCHAR(36) NOT NULL, + slug VARCHAR(255) NOT NULL, + issue_type VARCHAR(50) NOT NULL, + description TEXT NOT NULL, + suspected_knowledge_ids JSONB, + status VARCHAR(20) DEFAULT 'pending' NOT NULL, + reported_by VARCHAR(100) NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + deleted_at TIMESTAMP WITH TIME ZONE +); + +CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_tenant_id ON wiki_page_issues(tenant_id); +CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_knowledge_base_id ON wiki_page_issues(knowledge_base_id); +CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_slug ON wiki_page_issues(slug); +CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_status ON wiki_page_issues(status);