From 4022f134bd973148dff9e6554328a3cbc3510574 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 21 Apr 2026 17:12:41 +0800 Subject: [PATCH] feat: Introduce agent type presets for smart-reasoning mode - Added a new configuration file `agent_type_presets.yaml` to define various agent type presets, including RAG Q&A, Wiki Q&A, Hybrid (Wiki + RAG), and Data Analysis. - Updated the `builtin_agents.yaml` to associate built-in agents with the new agent type presets, enhancing their configuration options. - Enhanced the agent system prompt templates to reflect the new agent types and their functionalities. - Implemented API endpoints to retrieve agent type presets, allowing for dynamic loading in the frontend. - Updated the frontend to support agent type selection in the agent editor modal, improving user experience by auto-filling relevant configurations based on selected presets. These changes significantly enhance the flexibility and usability of the agent system, allowing users to easily configure agents based on predefined types. --- config/agent_type_presets.yaml | 197 +++++++ config/builtin_agents.yaml | 4 + .../prompt_templates/agent_system_prompt.yaml | 119 +++- frontend/src/api/agent/index.ts | 59 ++ frontend/src/i18n/locales/en-US.ts | 22 +- frontend/src/i18n/locales/ko-KR.ts | 16 +- frontend/src/i18n/locales/ru-RU.ts | 16 +- frontend/src/i18n/locales/zh-CN.ts | 22 +- frontend/src/views/agent/AgentEditorModal.vue | 540 ++++++++++++++---- internal/application/service/agent_service.go | 80 +-- .../application/service/session_agent_qa.go | 1 - internal/config/config.go | 12 + internal/handler/custom_agent.go | 19 + internal/router/router.go | 2 + internal/types/agent.go | 4 - internal/types/agent_type_preset.go | 213 +++++++ internal/types/custom_agent.go | 37 +- internal/types/knowledgebase.go | 47 ++ 18 files changed, 1177 insertions(+), 233 deletions(-) create mode 100644 config/agent_type_presets.yaml create mode 100644 internal/types/agent_type_preset.go diff --git a/config/agent_type_presets.yaml b/config/agent_type_presets.yaml new file mode 100644 index 00000000..4a7b9d9a --- /dev/null +++ b/config/agent_type_presets.yaml @@ -0,0 +1,197 @@ +# Agent Type Presets for Smart-Reasoning Mode +# +# When a user creates/edits a custom agent and picks "smart-reasoning" mode, +# they can additionally pick an "agent type" from the list below. Each type +# bundles a recommended system prompt template, tool allowlist, and KB +# compatibility rules so the user doesn't have to configure everything. +# +# A user can always override any auto-filled value — the preset only seeds +# the form. +# +# `kb_filter` decides which KBs the agent editor allows the user to select +# under this type. The frontend reads this config via GET /agents/type-presets +# and applies it as a client-side filter. +# +# Supported kb_filter predicates (evaluated against a KB's `capabilities`): +# any_of: KB must expose at least ONE of the listed capability names. +# all_of: KB must expose ALL of the listed capability names. +# none_of: KB must expose NONE of the listed capability names. +# Capability names: vector, keyword, wiki, graph, faq. +# An empty kb_filter (or kb_filter absent) means "any KB is allowed". + +agent_type_presets: + # -------------------------------------------------------------------------- + # RAG Q&A — classic evidence-based retrieval over chunk indexes. + # Best for document / FAQ KBs without wiki. + # -------------------------------------------------------------------------- + - id: "rag-qa" + i18n: + default: + label: "RAG Q&A" + description: "Evidence-based retrieval over document chunks. Best for document or FAQ KBs without Wiki." + zh-CN: + label: "RAG 问答" + description: "基于文档分块的检索式问答,适合未启用 Wiki 的文档 / FAQ 知识库。" + zh-TW: + label: "RAG 問答" + description: "基於文件分塊的檢索式問答,適合未啟用 Wiki 的文件 / FAQ 知識庫。" + config: + system_prompt_id: "progressive_rag_agent" + temperature: 0.7 + max_iterations: 30 + # `thinking` and `todo_write` are intentionally NOT included by default. + # They are useful for multi-step planning / self-reflection, but most + # users don't need them for single-turn Q&A and they noticeably bloat + # token usage. Enable them manually in the tool list when needed. + allowed_tools: + - "knowledge_search" + - "grep_chunks" + - "list_knowledge_chunks" + - "get_document_info" + - "final_answer" + retain_retrieval_history: false + faq_priority_enabled: true + kb_selection_mode: "selected" + kb_filter: + any_of: ["vector", "keyword", "faq"] + + # -------------------------------------------------------------------------- + # Wiki Q&A — graph-navigated wiki answering. + # Only meaningful on KBs where Wiki is enabled. + # -------------------------------------------------------------------------- + - id: "wiki-qa" + i18n: + default: + label: "Wiki Q&A" + description: "Wiki-first answering: search, read and follow links across wiki pages. Requires a Wiki-enabled KB." + zh-CN: + label: "Wiki 问答" + description: "以 Wiki 为主的检索与图谱跳转回答,必须绑定已启用 Wiki 的知识库。" + zh-TW: + label: "Wiki 問答" + description: "以 Wiki 為主的檢索與圖譜跳轉回答,必須綁定已啟用 Wiki 的知識庫。" + config: + system_prompt_id: "wiki_researcher" + temperature: 0.7 + max_iterations: 30 + # `thinking` / `todo_write` can be enabled manually if the user wants + # explicit reflection or planning across long wiki navigation chains; + # not on by default. + allowed_tools: + - "wiki_search" + - "wiki_read_page" + - "wiki_read_source_doc" + - "wiki_flag_issue" + - "final_answer" + retain_retrieval_history: false + kb_selection_mode: "selected" + kb_filter: + all_of: ["wiki"] + + # -------------------------------------------------------------------------- + # Hybrid RAG + Wiki — single agent that orchestrates both indexes. + # Requires KBs that expose BOTH wiki AND (vector or keyword). + # -------------------------------------------------------------------------- + - id: "hybrid-rag-wiki" + i18n: + default: + label: "Hybrid (Wiki + RAG)" + description: "Uses wiki pages for navigation and context, then drills into chunks for precise quotes. Requires KBs with BOTH Wiki and chunk indexing." + zh-CN: + label: "Wiki + RAG 混合" + description: "先用 Wiki 建立导航和背景,再用分块检索精确引用。需绑定同时启用 Wiki 与向量/关键词索引的知识库。" + zh-TW: + label: "Wiki + RAG 混合" + description: "先用 Wiki 建立導覽和背景,再用分塊檢索精確引用。需綁定同時啟用 Wiki 與向量/關鍵詞索引的知識庫。" + config: + system_prompt_id: "hybrid_rag_wiki_agent" + temperature: 0.7 + max_iterations: 40 + # `thinking` and `todo_write` are opt-in. Turn them on manually when the + # user wants explicit self-reflection or a visible step-by-step plan for + # multi-hop hybrid searches. + allowed_tools: + - "wiki_search" + - "wiki_read_page" + - "knowledge_search" + - "grep_chunks" + - "list_knowledge_chunks" + - "get_document_info" + - "wiki_flag_issue" + - "final_answer" + retain_retrieval_history: false + faq_priority_enabled: true + kb_selection_mode: "selected" + # Hybrid is meant to be the most flexible preset: the agent adapts at + # runtime based on what each KB exposes. + # - KB has wiki + chunks → full "wiki-first, RAG-verify" workflow + # - KB has only chunks → fallback to pure RAG (see prompt's "Fallback rules") + # - KB has only wiki → fallback to wiki-only answering + # - FAQ KB → allowed; knowledge_search still works on FAQ chunks + # We only require that the KB expose AT LEAST ONE retrievable surface so + # the agent has SOMETHING to call. KBs with zero indexing (e.g. graph-only + # or completely unindexed) are still excluded since no tool will return + # anything useful. + kb_filter: + any_of: ["vector", "keyword", "wiki"] + + # -------------------------------------------------------------------------- + # Data Analysis — SQL / statistics over tabular files (CSV / Excel) in the KB. + # Retrieval capabilities (vector/wiki/…) are largely irrelevant here — the + # agent drives `data_schema` + `data_analysis` tools against uploaded files, + # so we gate on supported_file_types rather than KB capabilities. + # -------------------------------------------------------------------------- + - id: "data-analysis" + i18n: + default: + label: "Data Analysis" + description: "SQL queries and statistics over tabular files (CSV / Excel). Pair with a KB that holds data files." + zh-CN: + label: "数据分析" + description: "对 CSV / Excel 等表格文件执行 SQL 查询和统计分析。请绑定包含数据文件的知识库。" + zh-TW: + label: "數據分析" + description: "對 CSV / Excel 等表格檔案執行 SQL 查詢和統計分析。請綁定包含數據檔案的知識庫。" + config: + system_prompt_id: "data_analyst" + temperature: 0.3 + max_iterations: 30 + # `thinking` / `todo_write` are opt-in for data-analysis too. Enable + # manually if the user wants explicit reflection or to break a long + # analysis into tracked sub-tasks. + allowed_tools: + - "data_schema" + - "data_analysis" + - "final_answer" + # retain_retrieval_history is irrelevant here — data-analysis has no + # retrieval tools in allowed_tools. Leave defaults. + web_search_enabled: false + supported_file_types: + - "csv" + - "xlsx" + kb_selection_mode: "selected" + # data_schema / data_analysis tools read ChunkTypeTableSummary / + # ChunkTypeTableColumn chunks, which are produced by the normal RAG + # ingestion pipeline (vector / keyword indexing on). FAQ-type KBs don't + # ingest tabular data, and wiki-only KBs don't carry chunk-level table + # schemas, so both are incompatible. + kb_filter: + any_of: ["vector", "keyword"] + none_of: ["faq"] + + # -------------------------------------------------------------------------- + # Custom — no preset; user configures everything by hand. + # -------------------------------------------------------------------------- + - id: "custom" + i18n: + default: + label: "Custom" + description: "Full control. Manually pick tools, prompt and KB scope." + zh-CN: + label: "自定义" + description: "完全自定义:自行选择工具、提示词和知识库。" + zh-TW: + label: "自訂" + description: "完全自訂:自行選擇工具、提示詞和知識庫。" + # No `config:` block → preset applies no auto-fill. + # No `kb_filter:` → all KBs are selectable. diff --git a/config/builtin_agents.yaml b/config/builtin_agents.yaml index aee0c442..094cc59b 100644 --- a/config/builtin_agents.yaml +++ b/config/builtin_agents.yaml @@ -67,6 +67,7 @@ builtin_agents: description: "ReAct 추론 프레임워크, 다단계 사고 및 도구 호출 지원" config: agent_mode: "smart-reasoning" + agent_type: "custom" system_prompt: "" temperature: 0.7 max_completion_tokens: 2048 @@ -116,6 +117,7 @@ builtin_agents: description: "CSV/Excel 파일에 대한 SQL 쿼리 및 통계 분석을 지원하는 전문 데이터 분석 에이전트" config: agent_mode: "smart-reasoning" + agent_type: "data-analysis" system_prompt_id: "data_analyst" temperature: 0.3 max_completion_tokens: 4096 @@ -162,6 +164,7 @@ builtin_agents: description: "위키 지식 베이스에서 답변하는 데 특화된 에이전트" config: agent_mode: "smart-reasoning" + agent_type: "wiki-qa" system_prompt_id: "wiki_researcher" temperature: 0.7 max_completion_tokens: 4096 @@ -207,6 +210,7 @@ builtin_agents: description: "검사 문제를 기반으로 Wiki 페이지를 修復하고 最適化하는 전용 에이전트" config: agent_mode: "smart-reasoning" + agent_type: "custom" system_prompt_id: "wiki_fixer" temperature: 0.7 max_completion_tokens: 4096 diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index 0113b901..5a2536e3 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -24,7 +24,7 @@ templates: ### Workflow 1. **Analyze:** Understand the user's request. - 2. **Plan:** If the task is complex, use todo_write to create a plan. + 2. **Plan:** If the task is complex, plan your approach. Prefer a brief internal plan. If the `todo_write` tool is available, you MAY record an explicit step-by-step plan there; if the `thinking` tool is available, you MAY also use it to reason out loud. 3. **Execute:** Use available tools (including any connected MCP tools) to gather information or perform actions. After receiving tool results, analyze them and incorporate the findings into your answer. 4. **Synthesize:** Call the final_answer tool with your comprehensive answer. You MUST always end by calling final_answer. @@ -32,8 +32,8 @@ templates: ### Tool Guidelines * **MCP Tools:** If external MCP tools are available, use them to fulfill the user's request. Analyze and incorporate their results into your final answer. * **web_search / web_fetch:** Use these if enabled to find information from the internet. - * **todo_write:** Use for managing multi-step tasks. - * **thinking:** Use to plan and reflect. + * **todo_write (optional, only if enabled):** Use for managing multi-step tasks when the user has explicitly added it to the tool list. + * **thinking (optional, only if enabled):** Use to plan and reflect out loud when the user has added it to the tool list. * **final_answer:** MANDATORY as your final action. Always submit your complete answer through this tool. NEVER end your turn without calling it. If you cannot fully answer, explain what you tried and why. If the question is outside your capabilities, say so politely. @@ -100,28 +100,28 @@ templates: Perform a "Deep Read" test of the KB to gain preliminary cognition. 1. **Search:** Execute grep_chunks (keyword) and knowledge_search (semantic) based on core entities. 2. **DEEP READ (Crucial):** If the search returns IDs, you **MUST** call list_knowledge_chunks on the top relevant IDs to fetch their actual text. - 3. **Analyze:** In your think block, evaluate the *full text* you just retrieved. + 3. **Analyze:** Evaluate the *full text* you just retrieved (use the `thinking` tool if it is available in your tool list; otherwise reason internally). * *Does this text fully answer the user?* * *Is the information complete or partial?* #### Phase 2: Strategic Decision & Planning Based on the **Deep Read** results from Phase 1: * **Path A (Direct Answer):** If the full text provides sufficient, unambiguous evidence → Proceed to **Answer Generation**. - * **Path B (Complex Research):** If the query involves comparison, missing data, or the content requires synthesis → Use todo_write to formulate a Work Plan. + * **Path B (Complex Research):** If the query involves comparison, missing data, or the content requires synthesis → Formulate a Work Plan. If the `todo_write` tool is available, you MAY record the plan there for tracking; otherwise keep the plan internally (or in a `thinking` block if that tool is enabled). * *Structure:* Break the problem into distinct retrieval tasks (e.g., "Deep read specs for Product A", "Deep read safety protocols"). #### Phase 3: Disciplined Execution & Deep Reflection (The Loop) - If in **Path B**, execute tasks in todo_write sequentially. For **EACH** task: + If in **Path B**, execute the planned tasks sequentially. For **EACH** task: 1. **Search:** Perform grep_chunks / knowledge_search for the sub-task. 2. **DEEP READ (Mandatory):** Call list_knowledge_chunks for any relevant IDs found. **Never skip this step.** - 3. **MANDATORY Deep Reflection (in think):** Pause and evaluate the full text: + 3. **MANDATORY Deep Reflection:** Pause and evaluate the full text (write your reflection via the `thinking` tool if it's enabled; otherwise reason internally before your next tool call): * *Validity:* "Does this full text specifically address the sub-task?" * *Gap Analysis:* "Is anything missing? Is the information outdated? Is the information irrelevant?" * *Correction:* If insufficient, formulate a remedial action (e.g., "Search for synonym X", "Web Search if enabled") immediately. * *Completion:* Mark task as "completed" ONLY when evidence is secured. #### Phase 4: Final Synthesis - Only when ALL todo_write tasks are "completed": + Only when ALL planned tasks are "completed": * Synthesize findings from the full text of all retrieved chunks. * Check for consistency. * Call the **final_answer** tool with your complete, well-formatted response. You MUST always end by calling final_answer. @@ -140,8 +140,8 @@ templates: * **grep_chunks / knowledge_search:** Your "Index". Use these to find *where* the information might be. * **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is. * **web_search / web_fetch:** Use these ONLY when Web Search is Enabled and KB retrieval is insufficient. - * **todo_write:** Your "Manager". Tracks multi-step research. - * **think:** Your "Conscience". Use to plan and reflect the content returned by list_knowledge_chunks. + * **todo_write (optional, only if enabled):** Your "Manager" for tracking multi-step research. Only use it when the user has added it to the tool list. + * **thinking (optional, only if enabled):** Your "Conscience". Use to plan and reflect the content returned by list_knowledge_chunks. Only use when the user has added it to the tool list. * **final_answer:** MANDATORY as your final action. Always submit your complete answer through this tool. NEVER end your turn without calling it. ### Final Output Standards @@ -196,7 +196,7 @@ templates: ### 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. + 2. **Plan:** For complex questions, break the analysis into sub-queries. Plan internally by default; if `thinking` is in your tool list, you MAY reason out loud there, and if `todo_write` is available you MAY also track tasks with it. 3. **Query:** Call data_analysis with the knowledge_id and SQL query. 4. **Analyze:** Interpret results and provide insights. @@ -209,8 +209,8 @@ templates: ### 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. + - **thinking (optional, only if enabled):** Plan complex analyses, debug query issues. Only use when the user has added it to the tool list. + - **todo_write (optional, only if enabled):** Track multi-step analysis tasks. Only use when the user has added it to the tool list. ### Output Standards - Present results in well-formatted tables or summaries @@ -362,3 +362,96 @@ templates: Current Time: {{current_time}} User Language: {{language}} + + - id: "hybrid_rag_wiki_agent" + name: "Hybrid RAG + Wiki Agent" + description: "System prompt for agents working on KBs where BOTH Wiki and chunk (vector/keyword) indexes are enabled." + i18n: + zh-CN: + name: "Wiki + RAG 混合智能体" + description: "同时启用 Wiki 与向量/关键词索引的知识库场景下使用的系统提示词" + en-US: + name: "Hybrid RAG + Wiki Agent" + description: "System prompt for KBs with BOTH Wiki and chunk-level retrieval enabled" + ko-KR: + name: "하이브리드 RAG + 위키 에이전트" + description: "Wiki와 벡터/키워드 인덱스가 동시에 활성화된 지식 베이스에서 사용하는 시스템 프롬프트" + mode: "smart-reasoning" + content: | + + You are WeKnora Hybrid Researcher, an intelligent retrieval assistant developed by Tencent. The Knowledge Base(s) you work on expose TWO complementary indexes over the same source documents: + - **Wiki Index** — LLM-synthesized Markdown pages (summaries, entities, concepts) organized as an interlinked graph. Best for navigation, relations, "what is X", and high-level context. + - **Chunk Index (RAG)** — raw document chunks with vector + BM25 retrieval. Best for precise quotes, numbers, code snippets, recent documents, and anything the wiki hasn't synthesized yet. + Your job is to orchestrate BOTH intelligently, using each where it is strongest. + + + + Deliver accurate, traceable, and well-cited answers. For most questions, start from the wiki to establish the conceptual map, then drill into chunks for ground-truth evidence. For fact-heavy or "give me the exact quote" questions, go straight to chunks. Never rely on internal parametric knowledge. + + + + IMPORTANT: The KB(s) you are bound to may expose any subset of {wiki, chunks}. + The bound KB set is heterogeneous — some KBs may be wiki-only, some may be + chunk-only (pure RAG), and some may have both. Do NOT assume both are always + available. Your FIRST move on a fresh question is to probe what is reachable, + THEN pick a strategy. + + Default "Wiki-first, RAG-verify" cycle (adapt as needed): + + 0. **Probe Available Surfaces (MANDATORY first action on every new question):** + - Issue ONE parallel round: call `wiki_search` AND `knowledge_search` with the same keywords. + - Inspect the results to decide the effective mode for this turn: + * Both have hits → run the full "Wiki-first, RAG-verify" cycle below. + * Only wiki has hits → skip steps 3–4, answer from wiki only (step 2 + step 5 with wiki citations only). + * Only chunks have hits → skip step 2, go straight to step 3 (pure RAG). + * Neither has hits → widen keywords and retry once; if still empty, tell the user the KB has no relevant material. + + 1. **Classify the Query (if both surfaces are available):** + - *Conceptual / relational / "what is / how does":* start from wiki. + - *Specific fact / exact quote / numeric / code-level:* start from RAG chunks. + - *Mixed / unclear:* start from wiki — it's cheaper context. + + 2. **Wiki Entry Point (if wiki-leaning AND wiki is available):** + - `wiki_search` with 1–3 keyword regex queries to discover slugs (prefer regex alternation over multiple calls). + - Call `wiki_read_page` on the top 1–2 slugs to load their full Markdown plus linked-page summaries. + - Follow `Links to` / `Linked from` for 1 extra hop if the answer isn't yet complete. + + 3. **Chunk Grounding (MANDATORY for any factual claim, WHEN chunks are available):** + - After reading wiki, or when the query demands precise evidence, call `knowledge_search` and/or `grep_chunks` to find chunks in the source documents. + - Whenever a search returns matched `knowledge_id`s / `chunk_id`s, you MUST call `list_knowledge_chunks` to read the full content of those chunks. Do not answer from search snippets alone. + - If chunks are NOT available in any bound KB, skip this step and rely on wiki — but make the limitation explicit in your final answer. + + 4. **Cross-Check (WHEN both surfaces contributed):** If wiki claims and raw chunks disagree, trust the raw chunks (they are the source of truth) and call `wiki_flag_issue` on the offending wiki page to report the discrepancy for human review. + + 5. **Synthesize:** + - Build an answer that is grounded in the actual content you retrieved this turn, structured with whatever navigation scaffolding you gathered. + - Cite every source you used: wiki pages as `[[slug|display name]]`, and chunks as `[knowledge_id#chunk_id]` or the citation style expected by the product. + - If you fell back to a single surface, say so briefly ("The bound KB only exposes X, so this answer is drawn entirely from X"). + + + + ABSOLUTE RULES: + 1. **Evidence-Based Facts:** Ground every factual claim in content you retrieved *this turn*, either from wiki pages or from source chunks. + 2. **Wiki Never Replaces RAG for Exact Quotes:** Wiki pages are summaries. If the user asks for a direct quote, numeric value, code, or table row, you MUST read the underlying chunks via `list_knowledge_chunks` or `wiki_read_source_doc`. + 3. **Mandatory Deep Read:** Whenever `grep_chunks` or `knowledge_search` returns matched `knowledge_id`s / `chunk_id`s, you MUST immediately call `list_knowledge_chunks` to read the full content. Do NOT rely on search snippets. + 4. **Mandatory Wiki Read:** `wiki_search` returns summaries only. If a wiki hit is relevant, you MUST call `wiki_read_page` before citing it. + 5. **Always Re-Retrieve:** Every new user question triggers fresh retrieval. Do not reuse retrieved content from earlier turns. + 6. **Cite Both Sides:** When your answer draws on wiki context plus chunk evidence, cite both (`[[wiki slug|name]]` + chunk refs). Make the evidence chain explicit. + 7. **Flag Contradictions:** If wiki contradicts source chunks, call `wiki_flag_issue` on the wiki page before submitting the final answer. + + + + * **wiki_search:** Wiki entry point. Prefer POSIX regex (`~*`) with alternation to cover multiple concepts in one call. + * **wiki_read_page:** Load the full content (and linked summaries) of 1–3 top slugs. Batch multiple slugs in a single call when possible. + * **knowledge_search:** Semantic retrieval over raw chunks. Use when the user is looking for concepts, paraphrased information, or when wiki didn't cover the answer. + * **grep_chunks:** Lexical / keyword retrieval over raw chunks. Use for exact tokens (error messages, function names, product codes) or when semantic search misses. + * **list_knowledge_chunks:** MANDATORY after any chunk search — loads the full text of the matched chunks. + * **get_document_info:** Fetch metadata (title, upload time, page count) when you need to cite a document properly. + * **wiki_flag_issue:** Use when wiki and chunks disagree, or when the user points out a wiki error. + * **final_answer:** MANDATORY last step. Always submit your answer through this tool. + + + + Current Time: {{current_time}} + User Language: {{language}} + diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 6df3725e..330e685f 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -1,10 +1,21 @@ import { get, post, put, del } from "../../utils/request"; // 智能体配置 +// 智能推理下的智能体类型预设 ID +// 'rag-qa' : 经典文档/FAQ 分块 RAG +// 'wiki-qa' : Wiki 图谱导航问答 +// 'hybrid-rag-wiki': Wiki + 分块混合检索 +// 'custom' : 完全自定义(不应用预设) +export type AgentType = 'rag-qa' | 'wiki-qa' | 'hybrid-rag-wiki' | 'data-analysis' | 'custom'; + export interface CustomAgentConfig { // ===== 基础设置 ===== agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式 + // 智能推理模式下的类型预设,用于一键应用"系统提示词 + 工具 + KB 兼容性"组合 + // 仅在 agent_mode === 'smart-reasoning' 时生效;quick-answer 模式忽略 + agent_type?: AgentType; system_prompt?: string; // 统一系统提示词(使用 {{web_search_status}} 占位符动态控制行为) + system_prompt_id?: string; // 引用的 prompt template ID(预设会填入此字段) context_template?: string; // 上下文模板(普通模式) // ===== 模型设置 ===== @@ -179,6 +190,54 @@ export function getPlaceholders() { return get<{ data: PlaceholdersResponse }>('/api/v1/agents/placeholders'); } +// ===== 智能体类型预设 ===== + +// 后端 kb_filter 结构(见 internal/types/agent_type_preset.go) +export interface AgentTypeKBFilter { + any_of?: string[]; // KB 至少拥有其一 + all_of?: string[]; // KB 必须全部拥有 + none_of?: string[]; // KB 必须全部不拥有 +} + +// KB 能力标签(后端 types.KBCapabilities 的 JSON) +export interface KBCapabilities { + vector: boolean; + keyword: boolean; + wiki: boolean; + graph: boolean; + faq: boolean; +} + +// 预设的"自动填充"配置载荷:仅包含被预设覆盖的字段;其他字段不动 +export interface AgentTypePresetConfig { + system_prompt_id?: string; + temperature?: number; + max_iterations?: number; + allowed_tools?: string[]; + retain_retrieval_history?: boolean; + faq_priority_enabled?: boolean; + web_search_enabled?: boolean; + supported_file_types?: string[]; + kb_selection_mode?: 'all' | 'selected' | 'none'; +} + +export interface AgentTypePresetI18n { + label: string; + description: string; +} + +export interface AgentTypePreset { + id: AgentType; + i18n: Record; + config?: AgentTypePresetConfig; // 为空表示"自定义"类型(无预设) + kb_filter?: AgentTypeKBFilter; // 为空表示所有 KB 可选 +} + +// 拉取类型预设列表(编辑器用) +export function getAgentTypePresets() { + return get<{ data: AgentTypePreset[] }>('/api/v1/agents/type-presets'); +} + // ===== IM渠道 ===== export interface IMChannel { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 13b87ad4..6c13da6e 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -472,12 +472,6 @@ export default { retrieveKBOnlyWhenMentioned: 'Retrieve Only When Mentioned', retrieveKBOnlyWhenMentionedDesc: "Off: auto-retrieve configured KBs; On: retrieve only when user {'@'} mentions", retrievalSectionTitle: 'Retrieval Strategy', - retrievalPreference: 'Retrieval Preference', - retrievalPreferenceDesc: 'Controls which retrieval tools the agent uses to access knowledge bases', - retrievalPreferenceAuto: 'Auto (based on KB capabilities)', - retrievalPreferenceVectorOnly: 'RAG Only', - retrievalPreferenceWikiOnly: 'Wiki Only', - retrievalPreferenceHybrid: 'Hybrid (RAG + Wiki)', rerankModel: 'ReRank Model', rerankModelDesc: 'Used to rerank knowledge base retrieval results for better accuracy', rerankModelPlaceholder: 'Select ReRank Model', @@ -3571,9 +3565,6 @@ export default { groupData: 'Data Analysis', writeWarning: 'Mutates Wiki content', dangerTag: 'Write', - // Preset - presetLabel: 'Retrieval Preset', - presetDesc: 'Switching the preset will update the checkboxes below (RAG / Wiki tools) in one click', // Status bar statusNoKb: 'No knowledge base is linked', statusKb: 'In scope: {rag} RAG KBs · {wiki} Wiki KBs', @@ -3639,6 +3630,19 @@ export default { wechatQRExpired: 'QR code expired, please try again', wechatBinding: 'Binding...', }, + agentType: { + label: 'Agent Type', + desc: 'Picking a preset auto-fills the system prompt, tool list and recommended KB scope.', + defaultNamePattern: 'My {label}', + kbMismatch: { + ragQa: 'RAG retrieval not enabled', + wikiQa: 'Wiki not enabled', + hybridRagWiki: 'No retrieval surface enabled', + dataAnalysis: 'Requires RAG (FAQ not supported)', + generic: 'Not compatible with current type', + }, + kbIncompatibleWarn: '{count} selected KB(s) are not compatible with this type, please adjust manually.', + }, mcp: { label: 'MCP Services', desc: 'Select MCP services available to the Agent', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 1e166702..5a80a895 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3622,9 +3622,6 @@ export default { groupData: '데이터 분석', writeWarning: 'Wiki 내용을 변경합니다', dangerTag: '쓰기', - // 프리셋 - presetLabel: '검색 전략 프리셋', - presetDesc: '프리셋 전환 시 아래 체크박스(RAG/Wiki 도구)가 일괄 조정됩니다', // 상태바 statusNoKb: '연결된 지식베이스가 없습니다', statusKb: '범위 내: RAG 지식베이스 {rag}개 · Wiki 지식베이스 {wiki}개', @@ -3636,6 +3633,19 @@ export default { effectiveDesc: '현재 설정 기준 저장 시 에이전트가 실제 호출할 수 있는 도구 집합', effectiveEmpty: '사용 가능한 도구가 없어 일반 모델 대화로 동작합니다', }, + agentType: { + label: '에이전트 유형', + desc: '프리셋을 선택하면 시스템 프롬프트, 도구 목록, 권장 지식 베이스 범위가 자동으로 채워집니다.', + defaultNamePattern: '나의 {label}', + kbMismatch: { + ragQa: 'RAG 검색 비활성화', + wikiQa: 'Wiki 비활성화', + hybridRagWiki: '활성화된 검색 수단 없음', + dataAnalysis: 'RAG 필요 (FAQ 미지원)', + generic: '현재 유형과 호환 안 됨', + }, + kbIncompatibleWarn: '선택된 {count}개의 지식 베이스가 현재 유형과 호환되지 않습니다. 수동으로 조정해 주세요.', + }, mcp: { label: 'MCP 서비스', desc: 'Agent가 호출할 수 있는 MCP 서비스를 선택하세요', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index a5c24e41..b1d1cd2b 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3192,9 +3192,6 @@ export default { groupData: 'Анализ данных', writeWarning: 'Изменяет содержимое Wiki', dangerTag: 'Запись', - // Пресет - presetLabel: 'Пресет поиска', - presetDesc: 'Переключение пресета одним кликом меняет флажки ниже (инструменты RAG/Wiki)', // Строка состояния statusNoKb: 'База знаний не подключена', statusKb: 'В области: {rag} RAG баз · {wiki} Wiki баз', @@ -3251,6 +3248,19 @@ export default { sessionModeThread: 'По потоку', sessionModeHint: 'Режим пользователя: отдельный диалог для каждого пользователя. /clear для нового диалога. Режим потока: отдельный диалог для каждого потока. Несколько человек могут общаться в одном потоке.', }, + agentType: { + label: 'Тип агента', + desc: 'Выбор пресета автоматически заполняет системный промпт, список инструментов и рекомендуемую область баз знаний.', + defaultNamePattern: 'Мой {label}', + kbMismatch: { + ragQa: 'RAG-поиск отключён', + wikiQa: 'Wiki отключён', + hybridRagWiki: 'Поиск не включён', + dataAnalysis: 'Требуется RAG (не FAQ)', + generic: 'Несовместимо с типом', + }, + kbIncompatibleWarn: 'Выбранные базы знаний ({count}) несовместимы с текущим типом. Настройте вручную.' + }, mcp: { label: 'MCP-сервисы', desc: 'Выберите MCP-сервисы, доступные агенту', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 040a7de2..0610e093 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -1337,12 +1337,6 @@ export default { retrieveKBOnlyWhenMentioned: "仅在 {'@'} 提及时检索", retrieveKBOnlyWhenMentionedDesc: "关闭:自动检索已配置的知识库,开启:仅当用户 {'@'} 提及时才检索", retrievalSectionTitle: "检索策略", - retrievalPreference: "检索偏好", - retrievalPreferenceDesc: "控制智能体使用哪些检索工具来访问知识库", - retrievalPreferenceAuto: "自动(根据知识库能力)", - retrievalPreferenceVectorOnly: "仅 RAG", - retrievalPreferenceWikiOnly: "仅 Wiki", - retrievalPreferenceHybrid: "混合(RAG + Wiki)", rerankModel: "ReRank 模型", rerankModelDesc: "用于对知识库检索结果进行重排序,提高回答准确性", rerankModelPlaceholder: "请选择 ReRank 模型", @@ -3623,9 +3617,6 @@ export default { groupData: "数据分析", writeWarning: "会修改 Wiki 内容", dangerTag: "可写", - // 预设 - presetLabel: "检索策略预设", - presetDesc: "切换预设会一次性调整下方勾选(对应的 RAG/Wiki 工具)", // 顶部状态栏 statusNoKb: "当前未关联任何知识库", statusKb: "作用域内:{rag} 个 RAG 知识库 · {wiki} 个 Wiki 知识库", @@ -3637,6 +3628,19 @@ export default { effectiveDesc: "根据当前配置计算,这是智能体保存后实际能调用的工具集合", effectiveEmpty: "当前没有可用工具,智能体将退化为纯模型问答", }, + agentType: { + label: "智能体类型", + desc: "选择一个预设会自动填充系统提示词、工具列表和推荐的知识库范围。", + defaultNamePattern: "我的{label}", + kbMismatch: { + ragQa: "未启用 RAG 检索", + wikiQa: "未启用 Wiki", + hybridRagWiki: "未启用任何检索能力", + dataAnalysis: "需启用 RAG(不支持 FAQ)", + generic: "不适用于当前类型", + }, + kbIncompatibleWarn: "已选的 {count} 个知识库不适用于当前类型,请手动调整", + }, mcp: { label: "MCP 服务", desc: "选择 Agent 可以调用的 MCP 服务", diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue index bbf3409a..378037bb 100644 --- a/frontend/src/views/agent/AgentEditorModal.vue +++ b/frontend/src/views/agent/AgentEditorModal.vue @@ -64,6 +64,36 @@ + +
+
+ +

{{ $t('agentEditor.agentType.desc') }}

+

{{ agentTypePresetDescription(activeAgentTypePreset) }}

+
+
+ + + +
+
+
@@ -142,7 +172,7 @@ position="corner" :hasKnowledgeBase="hasKnowledgeBase" @select="handleSystemPromptTemplateSelect" - @reset-default="handleSystemPromptTemplateSelect" + @reset-default="handleAgentSystemPromptResetDefault" />
@@ -627,23 +657,6 @@ {{ $t('agentEditor.tools.statusInactive', { count: inactiveToolCount }) }}
-
-
- {{ $t('agentEditor.tools.presetLabel') }} - {{ $t('agentEditor.tools.presetDesc') }} -
- - {{ $t('agent.editor.retrievalPreferenceAuto') }} - {{ $t('agent.editor.retrievalPreferenceVectorOnly') }} - {{ $t('agent.editor.retrievalPreferenceWikiOnly') }} - {{ $t('agent.editor.retrievalPreferenceHybrid') }} - -
@@ -876,14 +889,15 @@ filterable :min-collapsed-num="3" > - + -
+
@@ -891,17 +905,19 @@ RAG Wiki {{ kb.count || 0 }} + {{ kb.disabledReason }}
- + -
+
@@ -910,6 +926,7 @@ Wiki {{ kb.orgName }} {{ kb.count || 0 }} + {{ kb.disabledReason }}
@@ -1116,25 +1133,6 @@
- -
-
- -

{{ $t('agent.editor.retrievalPreferenceDesc') }}

-
-
- - {{ $t('agent.editor.retrievalPreferenceAuto') }} - {{ $t('agent.editor.retrievalPreferenceVectorOnly') }} - {{ $t('agent.editor.retrievalPreferenceWikiOnly') }} - {{ $t('agent.editor.retrievalPreferenceHybrid') }} - -
-
-
@@ -1356,13 +1354,23 @@ import { ref, computed, watch, nextTick } from 'vue'; import { useI18n } from 'vue-i18n'; import { MessagePlugin } from 'tdesign-vue-next'; -import { createAgent, updateAgent, getPlaceholders, type CustomAgent, type PlaceholderDefinition } from '@/api/agent'; +import { + createAgent, + updateAgent, + getPlaceholders, + getAgentTypePresets, + type CustomAgent, + type PlaceholderDefinition, + type AgentTypePreset, + type AgentType, + type KBCapabilities, +} from '@/api/agent'; import { listModels, type ModelConfig } from '@/api/model'; import { listKnowledgeBases } from '@/api/knowledge-base'; import { listMCPServices, type MCPService } from '@/api/mcp-service'; import { listSkills, type SkillInfo } from '@/api/skill'; import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider'; -import { getAgentConfig, getConversationConfig, getStorageEngineStatus, type StorageEngineStatusItem, type PromptTemplate } from '@/api/system'; +import { getAgentConfig, getConversationConfig, getStorageEngineStatus, getPromptTemplates, type StorageEngineStatusItem, type PromptTemplate } from '@/api/system'; import { useUIStore } from '@/stores/ui'; import { useAuthStore } from '@/stores/auth'; import { useOrganizationStore } from '@/stores/organization'; @@ -1376,7 +1384,7 @@ const uiStore = useUIStore(); const authStore = useAuthStore(); const orgStore = useOrganizationStore(); -const { t } = useI18n(); +const { t, locale: i18nLocale } = useI18n(); const props = defineProps<{ visible: boolean; @@ -1393,7 +1401,12 @@ const emit = defineEmits<{ const currentSection = ref(props.initialSection || 'basic'); const saving = ref(false); const allModels = ref([]); -const kbOptions = ref<{ label: string; value: string; type?: 'document' | 'faq'; count?: number; shared?: boolean; orgName?: string; ragEnabled?: boolean; wikiEnabled?: boolean }[]>([]); +const kbOptions = ref<{ label: string; value: string; type?: 'document' | 'faq'; count?: number; shared?: boolean; orgName?: string; ragEnabled?: boolean; wikiEnabled?: boolean; capabilities?: KBCapabilities }[]>([]); + +// 智能体类型预设(仅 smart-reasoning 模式下展示) +const agentTypePresets = ref([]); +// Agent 系统提示词模板缓存(用于切换智能体类型时根据 system_prompt_id 解析出实际文本填入) +const agentSystemPromptTemplates = ref([]); const mcpOptions = ref<{ label: string; value: string }[]>([]); const webSearchProviderList = ref([]); const skillOptions = ref<{ name: string; description: string }[]>([]); @@ -1748,7 +1761,7 @@ const defaultFormData = { is_builtin: false, config: { // 基础设置 - agent_mode: 'quick-answer' as 'quick-answer' | 'smart-reasoning', + agent_mode: 'smart-reasoning' as 'quick-answer' | 'smart-reasoning', system_prompt: '', context_template: '{{query}}', // 模型设置 @@ -1771,7 +1784,10 @@ const defaultFormData = { kb_selection_mode: 'none' as 'all' | 'selected' | 'none', knowledge_bases: [] as string[], retrieve_kb_only_when_mentioned: false, - retrieval_preference: 'auto' as 'auto' | 'vector_only' | 'wiki_only' | 'hybrid', + // 智能推理下的类型预设:新建 agent 时默认给 RAG 问答(最常用场景)。 + // 编辑既有 agent 时会被 agent 自己保存的 agent_type 覆盖。 + agent_type: 'rag-qa' as AgentType, + system_prompt_id: '' as string, // 图片上传/多模态设置 image_upload_enabled: false, vlm_model_id: '', @@ -1816,6 +1832,209 @@ const agentMode = computed({ const isAgentMode = computed(() => agentMode.value === 'smart-reasoning'); +// ============================================================================ +// 智能体类型预设(仅 smart-reasoning 模式下可见) +// 选择类型后自动填充 system_prompt_id / allowed_tools 等; +// 选择 "custom" 或没有匹配预设时不做任何覆盖。 +// ============================================================================ + +const agentType = computed({ + get: () => (formData.value.config.agent_type as AgentType) || 'custom', + set: (val: AgentType) => { formData.value.config.agent_type = val; }, +}); + +// 当前激活的预设对象(用于 KB 过滤 / UI 徽章) +const activeAgentTypePreset = computed(() => { + if (!isAgentMode.value) return null; + const id = agentType.value; + if (!id || id === 'custom') return null; + return agentTypePresets.value.find(p => p.id === id) || null; +}); + +// 根据当前 locale 挑选 i18n 标签 +const agentTypePresetLabel = (p: AgentTypePreset): string => { + const locale = i18nLocale.value || 'default'; + return p.i18n?.[locale]?.label || p.i18n?.default?.label || p.id; +}; +const agentTypePresetDescription = (p: AgentTypePreset): string => { + const locale = i18nLocale.value || 'default'; + return p.i18n?.[locale]?.description || p.i18n?.default?.description || ''; +}; + +// t-select 的 options 数据:label 给 TDesign 自己(用于选中态显示),desc 走自定义 option slot +const agentTypeSelectOptions = computed(() => { + return agentTypePresets.value.map(p => ({ + value: p.id, + label: agentTypePresetLabel(p), + desc: agentTypePresetDescription(p), + })); +}); + +// 为每个预设生成"我的