diff --git a/config/builtin_agents.yaml b/config/builtin_agents.yaml index dfdfae66..72ec93ba 100644 --- a/config/builtin_agents.yaml +++ b/config/builtin_agents.yaml @@ -186,3 +186,54 @@ builtin_agents: rerank_top_k: 10 rerank_threshold: 0.3 + - id: "builtin-wiki-fixer" + avatar: "🔧" + is_builtin: true + i18n: + default: + name: "Wiki Fixer" + description: "Specialized agent for repairing and optimizing Wiki pages based on linter issues" + zh-CN: + name: "维基修复助手" + description: "专门用于根据巡检问题修复和优化 Wiki 页面的智能体" + zh-TW: + name: "維基修復助手" + description: "專門用於根據巡檢問題修復和優化 Wiki 頁面的智能體" + ja-JP: + name: "Wiki修正アシスタント" + description: "リンターの問題に基づいてWikiページを修復および最適化するための専用エージェント" + ko-KR: + name: "위키 수정 도우미" + description: "린터 문제를 기반으로 Wiki 페이지를 복구하고 최적화하는 전용 에이전트" + config: + agent_mode: "smart-reasoning" + system_prompt_id: "wiki_fixer" + temperature: 0.7 + max_completion_tokens: 4096 + max_iterations: 30 + kb_selection_mode: "selected" + retrieve_kb_only_when_mentioned: false + retain_retrieval_history: true + allowed_tools: + - "thinking" + - "todo_write" + - "wiki_search" + - "wiki_read_page" + - "wiki_read_source_doc" + - "wiki_write_page" + - "wiki_replace_text" + - "wiki_rename_page" + - "wiki_delete_page" + - "wiki_read_issue" + - "wiki_update_issue" + web_search_enabled: false + web_search_max_results: 0 + reflection_enabled: false + multi_turn_enabled: true + history_turns: 10 + embedding_top_k: 10 + keyword_threshold: 0.3 + vector_threshold: 0.5 + rerank_top_k: 10 + rerank_threshold: 0.3 + diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index bf8b6d31..fe6109fc 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -277,3 +277,73 @@ templates: Current Time: {{current_time}} User Language: {{language}} + + - id: "wiki_fixer" + name: "Wiki Fixer System Prompt" + description: "System prompt for repairing and optimizing Wiki pages based on linter issues" + i18n: + zh-CN: + name: "Wiki 修复系统提示词" + description: "用于根据巡检问题修复和优化 Wiki 页面的系统提示词" + en-US: + name: "Wiki Fixer System Prompt" + description: "System prompt for repairing and optimizing Wiki pages based on linter issues" + mode: "smart-reasoning" + content: | + + You are the WeKnora Wiki Fixer, a specialized AI agent responsible for maintaining, repairing, and optimizing pages in a Markdown-based Wiki knowledge base. + + + + Your primary goal is to resolve "Issues" reported by the Wiki Linter or users. These issues usually involve factual conflicts, mixed entities (e.g. merging two different products), or outdated information. + You must carefully investigate the reported issue, trace back to the original source documents if necessary, determine the correct information, and apply fixes directly to the Wiki pages. + + + + You must follow these steps for EVERY fixing task: + 1. **Understand the Issue:** The user will provide you with the target page slug, issue description, and optionally suspected knowledge IDs. Use `wiki_read_issue` if you need to list other pending issues. + 2. **Read the Current State:** Call `wiki_read_page` on the target slug to see the current content and related links. Use `wiki_search` if you need to find related entities or check if a page already exists for separated content. + 3. **Investigate Sources:** If the issue involves conflicting facts or mixed entities, the current wiki page might be poisoned. You MUST call `wiki_read_source_doc` using the `knowledge_id`s listed in the page's `` or provided in the issue description. Read the raw text to discover the truth. + 4. **Determine the Fix Strategy:** + - *Correction:* Fix minor errors efficiently using the `wiki_replace_text` tool, or rewrite the page using `wiki_write_page`. + - *Renaming:* If the page title or slug is fundamentally wrong, use `wiki_rename_page` to change the slug. Incoming links will be updated automatically! + - *Separation (Disambiguation):* Rewrite the target page to only focus on its true subject (using `wiki_write_page`), and remove the competitor's info. + - *Creation:* Create a new page for the separated entity using `wiki_write_page`. + - *Deletion:* If a page is completely redundant or should not exist, use `wiki_delete_page`. Incoming links will be cleaned up automatically! + 5. **Plan & Confirm:** Before calling any write/replace/rename/delete tool, you MUST present a plan of what you intend to change to the user and ask for their confirmation. Wait for the user to say "yes" or "approved" or express general agreement before making the actual edits. You should be robust to conversational affirmative responses (e.g. "好的", "ok", "go ahead", "没问题") instead of requiring exact phrase matches. + 6. **Apply the Fix:** After user confirmation, use the appropriate tool. + - For `wiki_replace_text`, provide the exact `old_text` and the `new_text`. + - For `wiki_rename_page`, provide the `new_slug`. + - For `wiki_write_page`, provide the `title`, a concise 1-sentence `summary` for the index, the `page_type`, and the FULL, complete, corrected Markdown `content`. Do not output diffs in `content`. + - For `wiki_delete_page`, just provide the `slug`. + 7. **Update Issue Status:** Use `wiki_update_issue` to mark the issue as "resolved" after successfully editing the page. + + + + ABSOLUTE RULES: + 1. **Never Guess:** Always base your fixes on evidence found in the raw source documents (`wiki_read_source_doc`). + 2. **Require Confirmation:** NEVER edit without first presenting your plan and getting explicit approval from the user in the conversation. Accept variations of affirmative responses (like "ok", "好的", "没问题", "可以"). + 3. **Complete Content for Write:** When using `wiki_write_page`, you must provide the ENTIRE page content. Do not truncate or use placeholders like "...rest of the content...". Also, NEVER forget to provide the one-sentence `summary` field. + 4. **Exact Match for Replace:** When using `wiki_replace_text`, the `old_text` must EXACTLY match the text currently in the page. + 5. **Maintain Links:** When rewriting a page, try to preserve valid Wiki links `[[slug|Display Name]]`. + 6. **Writing Style:** You must strictly follow the standard Wiki writing style: + - Use proper heading hierarchy (`##` for sections, `###` for subsections). + - Include a "## Key Takeaways" section with bullet points at the end. + - Preserve any valid image links `![alt](url)`. + 7. **Source Refs:** When calling `wiki_write_page` or `wiki_replace_text`, you MUST provide the `source_refs` array containing the `knowledge_id`s of the source documents you used to verify the information. + + + + * **wiki_read_page:** Use this first to see what the broken page looks like. + * **wiki_search:** Use this to explore the wiki if you need to find related concepts or verify if another page already exists. + * **wiki_read_source_doc:** Use this to find the ground truth. It is crucial for resolving "contradictory_facts" or "mixed_entities" issues. + * **wiki_read_issue:** Use this to read specific issue details or list pending issues for a page. + * **todo_write:** Use this to write down the plan and modifications you intend to make, so that you can remember them across conversation turns, and present them to the user. + * **wiki_write_page / wiki_replace_text / wiki_rename_page / wiki_delete_page:** Use these to apply your fix ONLY AFTER the user confirms your plan. + * **wiki_update_issue:** Use this to set the issue status to "resolved" after the page is fixed. + + + + Current Time: {{current_time}} + User Language: {{language}} + diff --git a/frontend/src/api/wiki/index.ts b/frontend/src/api/wiki/index.ts index 485c8c7b..21ac8302 100644 --- a/frontend/src/api/wiki/index.ts +++ b/frontend/src/api/wiki/index.ts @@ -41,9 +41,24 @@ export interface WikiStats { orphan_count: number; recent_updates: WikiPage[]; pending_tasks: number; + pending_issues: number; is_active: boolean; } +export interface WikiPageIssue { + id: string; + tenant_id: number; + knowledge_base_id: string; + slug: string; + issue_type: string; + description: string; + suspected_knowledge_ids: string[]; + status: string; + reported_by: string; + created_at: string; + updated_at: string; +} + // Wiki API Functions export function listWikiPages(kbId: string, params?: { page_type?: string; @@ -104,6 +119,17 @@ export function searchWikiPages(kbId: string, q: string, limit?: number) { return get(`/api/v1/knowledgebase/${kbId}/wiki/search?${params.toString()}`); } +export function listWikiIssues(kbId: string, slug?: string, status?: string) { + const params = new URLSearchParams(); + if (slug) params.set('slug', slug); + if (status) params.set('status', status); + return get(`/api/v1/knowledgebase/${kbId}/wiki/issues?${params.toString()}`); +} + +export function updateWikiIssueStatus(kbId: string, issueId: string, status: string) { + return put(`/api/v1/knowledgebase/${kbId}/wiki/issues/${issueId}/status`, { status }); +} + export function rebuildWikiLinks(kbId: string) { return post(`/api/v1/knowledgebase/${kbId}/wiki/rebuild-links`, {}); } diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 04ee3b5b..7a2e66f1 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -1704,17 +1704,16 @@ const getBuiltinAgentNotReadyReasons = (agent: CustomAgent, isAgentMode: boolean const reasons: string[] = [] const config = agent.config || {} - // 检查对话模型(Summary Model) - if (!config.model_id || config.model_id.trim() === '') { - reasons.push(t('input.customAgentMissingSummaryModel')) - } + // 内置智能体会自动回退到租户的默认模型,因此不再在前端强制校验 model_id - // 检查重排模型(Rerank Model)- 如果使用知识库则需要 - if (config.kb_selection_mode !== 'none') { - if (!config.rerank_model_id || config.rerank_model_id.trim() === '') { - reasons.push(t('input.customAgentMissingRerankModel')) - } - } + // 检查重排模型(Rerank Model)- 仅当允许使用 knowledge_search 工具时需要 + // 内置智能体允许重排模型为空(使用默认配置) + // const hasKnowledgeSearchTool = config.allowed_tools && config.allowed_tools.includes('knowledge_search') + // if (hasKnowledgeSearchTool) { + // if (!config.rerank_model_id || config.rerank_model_id.trim() === '') { + // reasons.push(t('input.customAgentMissingRerankModel')) + // } + // } // Agent 模式还需要检查允许的工具 if (isAgentMode) { @@ -1735,8 +1734,9 @@ const getCustomAgentNotReadyReasons = (agent: CustomAgent): string[] => { if (!config.model_id || config.model_id.trim() === '') { reasons.push(t('input.customAgentMissingSummaryModel')) } - // 检查重排模型(Rerank Model)- 如果使用知识库则需要 - if (config.kb_selection_mode !== 'none') { + // 检查重排模型(Rerank Model)- 仅当允许使用 knowledge_search 工具时需要 + const hasKnowledgeSearchTool = config.allowed_tools && config.allowed_tools.includes('knowledge_search') + if (hasKnowledgeSearchTool) { if (!config.rerank_model_id || config.rerank_model_id.trim() === '') { reasons.push(t('input.customAgentMissingRerankModel')) } @@ -2211,13 +2211,17 @@ const getImgSrc = (url: string) => { z-index: 99; bottom: 60px; left: 50%; - transform: translateX(-400px); + transform: translateX(-50%); + width: 100%; + display: flex; + justify-content: center; } /* 富文本输入框容器 */ .rich-input-container { position: relative; - width: 800px; + width: 100%; + max-width: 800px; background: var(--td-bg-color-container, #FFF); border-radius: 12px; border: .5px solid var(--td-component-border, #E7E7E7); diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index c6207050..72853317 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -1638,6 +1638,27 @@ export default { hideArrows: 'Hide arrows', healthCheck: 'Health Check', queueStatus: '{count} pending tasks in Wiki queue', + issueTitle: 'This page has {count} pending knowledge conflicts or errors', + issueFixBtn: 'AI Auto-Fix', + issueMixed: 'Mixed Info', + issueConflict: 'Factual Conflict', + issueOutdated: 'Outdated', + issueAttention: 'Needs Attention', + issueReportedBy: 'Reported by {reporter}', + issueAiLinter: 'AI Linter', + issueIgnore: 'Ignore False Alarm', + globalIssuesTitle: 'Global Pending Content Issues', + globalIssuesCount: '{count} Pending Content Issues', + globalIssuesEmpty: 'No pending content issues', + issuePagePrefix: 'Page: ', + issueGoFix: 'Go to fix', + fixAssistantTitle: 'Wiki Smart Fix Assistant', + issueFixSuggestions: 'Content Optimization Suggestions ({count})', + issueFixSingle: 'Fix', + fixStartError: 'Failed to start fix assistant', + issueFixPromptSingle: 'Please help me fix the following issue on page [[{slug}]]:\n\n- [{type}] {desc}\n\nOnce resolved, please call the `wiki_update_issue` tool to mark this issue (ID: {id}) as resolved.', + issueFixPromptAutoStart: 'Please help me fix all pending issues on page [[{slug}]]:', + issueFixPromptAutoEnd: 'Once resolved, please call the `wiki_update_issue` tool to mark these issues as resolved.', }, buttons: { create: 'Create Knowledge Base', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 30db3267..fcac177c 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -2161,6 +2161,27 @@ export default { hideArrows: '화살표 숨기기', healthCheck: "상태 점검", queueStatus: "Wiki 대기열에 {count}개의 보류 중인 작업", + issueTitle: "이 페이지에는 {count}개의 대기 중인 지식 충돌 또는 오류가 있습니다", + issueFixBtn: "AI 자동 수정", + issueMixed: "혼합된 정보", + issueConflict: "사실 충돌", + issueOutdated: "오래된 정보", + issueAttention: "주의 필요", + issueReportedBy: "{reporter} 보고함", + issueAiLinter: "AI 검사기", + issueIgnore: "오탐지 무시", + globalIssuesTitle: "전체 보류 중인 콘텐츠 문제", + globalIssuesCount: "보류 중인 콘텐츠 문제: {count}개", + globalIssuesEmpty: "보류 중인 콘텐츠 문제가 없습니다", + issuePagePrefix: "페이지: ", + issueGoFix: "수정하러 가기", + fixAssistantTitle: "Wiki 스마트 수정 도우미", + issueFixSuggestions: "콘텐츠 최적화 제안 ({count})", + issueFixSingle: "수정", + fixStartError: "수정 도우미 시작 실패", + issueFixPromptSingle: "페이지 [[{slug}]] 의 다음 문제를 수정해 주세요:\n\n- [{type}] {desc}\n\n해결 완료 후 `wiki_update_issue` 도구를 호출하여 이 문제(ID: {id})를 해결됨으로 표시해 주세요.", + issueFixPromptAutoStart: "페이지 [[{slug}]] 의 모든 보류 중인 문제를 수정해 주세요:", + issueFixPromptAutoEnd: "해결 완료 후 `wiki_update_issue` 도구를 호출하여 이 문제들을 해결됨으로 표시해 주세요.", }, buttons: { create: "지식베이스 생성", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 4a1055d5..e8519227 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1840,6 +1840,27 @@ export default { hideArrows: 'Скрыть стрелки', healthCheck: 'Проверка здоровья', queueStatus: '{count} ожидающих задач в очереди Wiki', + issueTitle: 'На этой странице есть {count} неразрешенных конфликтов или ошибок знаний', + issueFixBtn: 'AI Автоисправление', + issueMixed: 'Смешанная инфо', + issueConflict: 'Фактический конфликт', + issueOutdated: 'Устарело', + issueAttention: 'Требует внимания', + issueReportedBy: 'Сообщил {reporter}', + issueAiLinter: 'AI Линтер', + issueIgnore: 'Игнорировать', + globalIssuesTitle: 'Глобальные проблемы содержимого', + globalIssuesCount: 'Ожидающие проблемы содержимого: {count}', + globalIssuesEmpty: 'Нет ожидающих проблем содержимого', + issuePagePrefix: 'Страница: ', + issueGoFix: 'Исправить', + fixAssistantTitle: 'Wiki Умный помощник исправления', + issueFixSuggestions: 'Предложения по оптимизации ({count})', + issueFixSingle: 'Исправить', + fixStartError: 'Не удалось запустить помощник исправления', + issueFixPromptSingle: 'Пожалуйста, помогите исправить следующую проблему на странице [[{slug}]]:\n\n- [{type}] {desc}\n\nПосле устранения проблемы, пожалуйста, вызовите инструмент `wiki_update_issue`, чтобы пометить эту проблему (ID: {id}) как решенную.', + issueFixPromptAutoStart: 'Пожалуйста, помогите исправить все ожидающие проблемы на странице [[{slug}]]:', + issueFixPromptAutoEnd: 'После устранения проблем, пожалуйста, вызовите инструмент `wiki_update_issue`, чтобы пометить эти проблемы как решенные.', }, buttons: { create: 'Создать базу знаний', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 242d5191..c790d2eb 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2146,6 +2146,27 @@ export default { hideArrows: '隐藏箭头', healthCheck: "健康检查", queueStatus: "Wiki 队列中 {count} 个待处理任务", + issueTitle: "此页面存在 {count} 个待处理的知识冲突或错误", + issueFixBtn: "AI 一键修复", + issueMixed: "信息混杂", + issueConflict: "事实冲突", + issueOutdated: "信息过时", + issueAttention: "需要关注", + issueReportedBy: "由 {reporter} 报告", + issueAiLinter: "AI 巡检", + issueIgnore: "忽略误报", + globalIssuesTitle: "全库待修复内容问题", + globalIssuesCount: "待修复内容问题: {count} 项", + globalIssuesEmpty: "暂无待处理的内容问题", + issuePagePrefix: "页面: ", + issueGoFix: "去处理", + fixAssistantTitle: "Wiki 智能修复助手", + issueFixSuggestions: "内容优化建议 ({count})", + issueFixSingle: "修复", + fixStartError: "启动修复助手失败", + issueFixPromptSingle: "请帮我修复页面 [[{slug}]] 上的以下问题:\n\n- [{type}] {desc}\n\n解决完毕后,请调用 `wiki_update_issue` 工具将该问题 (ID: {id}) 标记为已解决。", + issueFixPromptAutoStart: "请帮我修复页面 [[{slug}]] 上的所有待处理问题:", + issueFixPromptAutoEnd: "解决完毕后,请调用 `wiki_update_issue` 工具将这些问题标记为已解决。", }, buttons: { create: "创建知识库", diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index 98db8b54..80910ccd 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -1,5 +1,5 @@