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.
This commit is contained in:
wizardchen
2026-04-21 17:12:41 +08:00
parent 0531700518
commit 4022f134bd
18 changed files with 1177 additions and 233 deletions
+197
View File
@@ -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.
+4
View File
@@ -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
+106 -13
View File
@@ -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}}
</system_status>
- 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: |
<role>
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.
</role>
<mission>
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.
</mission>
<workflow>
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").
</workflow>
<constraints>
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.
</constraints>
<tool_guidelines>
* **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.
</tool_guidelines>
<system_status>
Current Time: {{current_time}}
User Language: {{language}}
</system_status>
+59
View File
@@ -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<string, AgentTypePresetI18n>;
config?: AgentTypePresetConfig; // 为空表示"自定义"类型(无预设)
kb_filter?: AgentTypeKBFilter; // 为空表示所有 KB 可选
}
// 拉取类型预设列表(编辑器用)
export function getAgentTypePresets() {
return get<{ data: AgentTypePreset[] }>('/api/v1/agents/type-presets');
}
// ===== IM渠道 =====
export interface IMChannel {
+13 -9
View File
@@ -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',
+13 -3
View File
@@ -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 서비스를 선택하세요',
+13 -3
View File
@@ -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-сервисы, доступные агенту',
+13 -9
View File
@@ -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 服务",
+430 -110
View File
@@ -64,6 +64,36 @@
</div>
</div>
<!-- 智能体类型(仅智能推理模式下显示) -->
<div v-if="isAgentMode && agentTypePresets.length > 0" class="setting-row setting-row--emphasize">
<div class="setting-info">
<label>{{ $t('agentEditor.agentType.label') }}</label>
<p class="desc">{{ $t('agentEditor.agentType.desc') }}</p>
<p
v-if="activeAgentTypePreset"
class="desc agent-type-preset-desc"
>{{ agentTypePresetDescription(activeAgentTypePreset) }}</p>
</div>
<div class="setting-control">
<t-select
:value="agentType"
@change="onAgentTypeChange"
:disabled="isBuiltinAgent"
:placeholder="$t('agentEditor.agentType.label')"
:options="agentTypeSelectOptions"
:popup-props="{ overlayClassName: 'agent-type-popup' }"
class="agent-type-select"
>
<template #option="{ option }">
<div class="agent-type-option">
<span class="agent-type-option-label">{{ option.label }}</span>
<span v-if="option.desc" class="agent-type-option-desc">{{ option.desc }}</span>
</div>
</template>
</t-select>
</div>
</div>
<!-- 名称 -->
<div class="setting-row">
<div class="setting-info">
@@ -142,7 +172,7 @@
position="corner"
:hasKnowledgeBase="hasKnowledgeBase"
@select="handleSystemPromptTemplateSelect"
@reset-default="handleSystemPromptTemplateSelect"
@reset-default="handleAgentSystemPromptResetDefault"
/>
</div>
<!-- 普通模式:单个提示词 -->
@@ -627,23 +657,6 @@
<span>{{ $t('agentEditor.tools.statusInactive', { count: inactiveToolCount }) }}</span>
</div>
</div>
<div class="tools-overview-row tools-overview-row--preset">
<div class="tools-preset-label">
<span class="tools-preset-title">{{ $t('agentEditor.tools.presetLabel') }}</span>
<span class="tools-preset-hint">{{ $t('agentEditor.tools.presetDesc') }}</span>
</div>
<t-radio-group
:value="formData.config.retrieval_preference"
@change="onRetrievalPresetChange"
size="small"
variant="default-filled"
>
<t-radio-button value="auto">{{ $t('agent.editor.retrievalPreferenceAuto') }}</t-radio-button>
<t-radio-button value="vector_only">{{ $t('agent.editor.retrievalPreferenceVectorOnly') }}</t-radio-button>
<t-radio-button value="wiki_only">{{ $t('agent.editor.retrievalPreferenceWikiOnly') }}</t-radio-button>
<t-radio-button value="hybrid">{{ $t('agent.editor.retrievalPreferenceHybrid') }}</t-radio-button>
</t-radio-group>
</div>
</div>
<div class="settings-group">
@@ -876,14 +889,15 @@
filterable
:min-collapsed-num="3"
>
<t-option-group v-if="myKbOptions.length" :label="$t('agent.editor.myKnowledgeBases')">
<t-option-group v-if="filteredMyKbOptions.length" :label="$t('agent.editor.myKnowledgeBases')">
<t-option
v-for="kb in myKbOptions"
v-for="kb in filteredMyKbOptions"
:key="kb.value"
:value="kb.value"
:label="kb.label"
:disabled="kb.disabled"
>
<div class="kb-option-item">
<div class="kb-option-item" :title="kb.disabled ? kb.disabledReason : ''">
<span class="kb-option-icon" :class="kb.type === 'faq' ? 'faq-icon' : 'doc-icon'">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" />
</span>
@@ -891,17 +905,19 @@
<span v-if="kb.ragEnabled" class="kb-option-tag tag-rag">RAG</span>
<span v-if="kb.wikiEnabled" class="kb-option-tag tag-wiki">Wiki</span>
<span class="kb-option-count">{{ kb.count || 0 }}</span>
<span v-if="kb.disabled" class="kb-option-disabled-hint">{{ kb.disabledReason }}</span>
</div>
</t-option>
</t-option-group>
<t-option-group v-if="sharedKbOptions.length" :label="$t('agent.editor.sharedKnowledgeBases')">
<t-option-group v-if="filteredSharedKbOptions.length" :label="$t('agent.editor.sharedKnowledgeBases')">
<t-option
v-for="kb in sharedKbOptions"
v-for="kb in filteredSharedKbOptions"
:key="kb.value"
:value="kb.value"
:label="kb.label"
:disabled="kb.disabled"
>
<div class="kb-option-item">
<div class="kb-option-item" :title="kb.disabled ? kb.disabledReason : ''">
<span class="kb-option-icon" :class="kb.type === 'faq' ? 'faq-icon' : 'doc-icon'">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" />
</span>
@@ -910,6 +926,7 @@
<span v-if="kb.wikiEnabled" class="kb-option-tag tag-wiki">Wiki</span>
<span v-if="kb.orgName" class="kb-option-org">{{ kb.orgName }}</span>
<span class="kb-option-count">{{ kb.count || 0 }}</span>
<span v-if="kb.disabled" class="kb-option-disabled-hint">{{ kb.disabledReason }}</span>
</div>
</t-option>
</t-option-group>
@@ -1116,25 +1133,6 @@
</div>
<div class="settings-group">
<!-- 检索偏好 -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agent.editor.retrievalPreference') }}</label>
<p class="desc">{{ $t('agent.editor.retrievalPreferenceDesc') }}</p>
</div>
<div class="setting-control">
<t-select
v-model="formData.config.retrieval_preference"
style="width: 200px"
>
<t-option value="auto">{{ $t('agent.editor.retrievalPreferenceAuto') }}</t-option>
<t-option value="vector_only">{{ $t('agent.editor.retrievalPreferenceVectorOnly') }}</t-option>
<t-option value="wiki_only">{{ $t('agent.editor.retrievalPreferenceWikiOnly') }}</t-option>
<t-option value="hybrid">{{ $t('agent.editor.retrievalPreferenceHybrid') }}</t-option>
</t-select>
</div>
</div>
<!-- 查询扩展(仅普通模式) -->
<div v-if="!isAgentMode" class="setting-row">
<div class="setting-info">
@@ -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<ModelConfig[]>([]);
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<AgentTypePreset[]>([]);
// Agent 系统提示词模板缓存(用于切换智能体类型时根据 system_prompt_id 解析出实际文本填入)
const agentSystemPromptTemplates = ref<PromptTemplate[]>([]);
const mcpOptions = ref<{ label: string; value: string }[]>([]);
const webSearchProviderList = ref<WebSearchProviderEntity[]>([]);
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<AgentTypePreset | null>(() => {
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),
}));
});
// 为每个预设生成"我的 <label>"的默认名称,让用户可以一键保存
// custom 类型默认名为空(让用户自己想)
const getPresetDefaultName = (preset: AgentTypePreset | null): string => {
if (!preset || preset.id === 'custom') return '';
return t('agentEditor.agentType.defaultNamePattern', { label: agentTypePresetLabel(preset) });
};
const getPresetDefaultDescription = (preset: AgentTypePreset | null): string => {
if (!preset) return '';
return agentTypePresetDescription(preset);
};
// 判断当前名称/描述是否由系统自动填入(任一预设的默认值 或 空)
// 用于在切换类型时只覆盖"未被用户手动编辑"的值,避免覆盖用户输入
const isNameSystemGenerated = (name: string): boolean => {
if (!name) return true;
return agentTypePresets.value.some(p => getPresetDefaultName(p) === name);
};
const isDescriptionSystemGenerated = (desc: string): boolean => {
if (!desc) return true;
return agentTypePresets.value.some(p => getPresetDefaultDescription(p) === desc);
};
// 按预设 id 返回面向用户的不兼容原因文案。
// 不要直接把 "vector / keyword / wiki" 这些底层 capability 名回传给用户 —
// 用户不关心技术实现,只想知道"为什么我这个知识库不能用"。
const presetKbMismatchKeyMap: Record<string, string> = {
'rag-qa': 'ragQa',
'wiki-qa': 'wikiQa',
'hybrid-rag-wiki': 'hybridRagWiki',
'data-analysis': 'dataAnalysis',
};
const presetKbMismatchReason = (preset: AgentTypePreset): string => {
const subKey = presetKbMismatchKeyMap[preset.id];
if (subKey) return t(`agentEditor.agentType.kbMismatch.${subKey}`);
return t('agentEditor.agentType.kbMismatch.generic');
};
// 评估单个 KB 是否满足给定预设的 kb_filter
const kbSatisfiesPresetFilter = (kb: { capabilities?: KBCapabilities; ragEnabled?: boolean; wikiEnabled?: boolean; type?: string }, preset: AgentTypePreset | null): { ok: boolean; reason: string } => {
if (!preset || !preset.kb_filter) return { ok: true, reason: '' };
const caps = kb.capabilities || {
vector: !!kb.ragEnabled,
keyword: !!kb.ragEnabled,
wiki: !!kb.wikiEnabled,
graph: false,
faq: kb.type === 'faq',
};
const has = (name: string): boolean => {
switch (name) {
case 'vector': return !!caps.vector;
case 'keyword': return !!caps.keyword;
case 'wiki': return !!caps.wiki;
case 'graph': return !!caps.graph;
case 'faq': return !!caps.faq;
default: return false;
}
};
const f = preset.kb_filter;
const reason = presetKbMismatchReason(preset);
if (f.all_of && f.all_of.length > 0) {
for (const n of f.all_of) {
if (!has(n)) return { ok: false, reason };
}
}
if (f.any_of && f.any_of.length > 0) {
if (!f.any_of.some(n => has(n))) {
return { ok: false, reason };
}
}
if (f.none_of && f.none_of.length > 0) {
for (const n of f.none_of) {
if (has(n)) return { ok: false, reason };
}
}
return { ok: true, reason: '' };
};
// KB 过滤后的选项(用于"指定知识库"下拉)— 不满足的仍保留但标记 disabled + tooltip
const filteredKbOptionsForPreset = computed(() => {
const preset = activeAgentTypePreset.value;
return kbOptions.value.map(kb => {
const { ok, reason } = kbSatisfiesPresetFilter(kb, preset);
return { ...kb, disabled: !ok, disabledReason: reason };
});
});
const filteredMyKbOptions = computed(() => filteredKbOptionsForPreset.value.filter(kb => !kb.shared));
const filteredSharedKbOptions = computed(() => filteredKbOptionsForPreset.value.filter(kb => kb.shared));
// 当前选中的 KB 中,有多少个在新预设下会被禁用(用于保存前提示)
const incompatibleSelectedKbCount = computed(() => {
const preset = activeAgentTypePreset.value;
if (!preset || kbSelectionMode.value !== 'selected') return 0;
const selected = new Set(formData.value.config.knowledge_bases || []);
return filteredKbOptionsForPreset.value.filter(kb => selected.has(kb.value) && kb.disabled).length;
});
// 应用一个预设的 config 到 formData.config(仅覆盖预设里明确设置的字段,其他不动)
const applyAgentTypePreset = (preset: AgentTypePreset | null) => {
if (!preset || !preset.config) return;
const c = preset.config;
const target = formData.value.config;
if (c.system_prompt_id !== undefined) {
target.system_prompt_id = c.system_prompt_id;
// 根据 system_prompt_id 从已加载的模板列表里查出正文并回填到用户可见的 textarea
const tmpl = agentSystemPromptTemplates.value.find(t => t.id === c.system_prompt_id);
if (tmpl && typeof tmpl.content === 'string') {
target.system_prompt = tmpl.content;
} else {
// 模板列表还没加载完 / 或预设引用了不存在的 id:清空让用户感知到变化
target.system_prompt = '';
if (c.system_prompt_id) {
console.warn(`[AgentType] system_prompt_id "${c.system_prompt_id}" not found in agent_system_prompt templates`);
}
}
}
if (typeof c.temperature === 'number') target.temperature = c.temperature;
if (typeof c.max_iterations === 'number') target.max_iterations = c.max_iterations;
if (Array.isArray(c.allowed_tools)) target.allowed_tools = [...c.allowed_tools];
if (typeof c.retain_retrieval_history === 'boolean') target.retain_retrieval_history = c.retain_retrieval_history;
if (typeof c.faq_priority_enabled === 'boolean') target.faq_priority_enabled = c.faq_priority_enabled;
if (typeof c.web_search_enabled === 'boolean') target.web_search_enabled = c.web_search_enabled;
// supported_file_types 采用"强同步"语义:只有 data-analysis 需要限定 csv/xlsx,
// 其余类型切过来时必须清空,否则会从上一个类型带过来残留。
if (Array.isArray(c.supported_file_types)) {
target.supported_file_types = [...c.supported_file_types];
} else {
target.supported_file_types = [];
}
// kb_selection_mode 同步到 formData 以及 UI 状态(两处都要改,否则单选按钮不更新)
if (c.kb_selection_mode) {
target.kb_selection_mode = c.kb_selection_mode;
kbSelectionMode.value = c.kb_selection_mode;
}
};
// 用户手动切换类型 → 应用预设
const onAgentTypeChange = (val: AgentType) => {
// 切换前捕获"名称/描述是否可安全覆盖"
// 已编辑过的用户输入(不等于任何预设默认值)绝不覆盖
const canOverrideName = isNameSystemGenerated(formData.value.name);
const canOverrideDesc = isDescriptionSystemGenerated(formData.value.description);
agentType.value = val;
const preset = agentTypePresets.value.find(p => p.id === val) || null;
if (val !== 'custom') {
applyAgentTypePreset(preset);
}
// 用新预设的默认名/描述刷新自动填充字段
if (canOverrideName) {
formData.value.name = getPresetDefaultName(preset);
}
if (canOverrideDesc) {
formData.value.description = getPresetDefaultDescription(preset);
}
// 如果新预设与当前已选 KB 冲突,软提示(不强制移除)
if (incompatibleSelectedKbCount.value > 0) {
MessagePlugin.warning(
t('agentEditor.agentType.kbIncompatibleWarn', { count: incompatibleSelectedKbCount.value }),
4000,
);
}
};
// 思考模式计算属性(直接绑定 boolean)
const thinkingEnabled = computed({
get: () => formData.value.config.thinking === true,
@@ -1943,6 +2162,25 @@ watch(() => props.visible, async (val) => {
kbSelectionMode.value = 'none';
mcpSelectionMode.value = 'none';
skillsSelectionMode.value = 'none';
// 新建智能推理 agent 时,立即应用默认的 agent_type 预设
// (补齐 system_prompt / allowed_tools / kb_selection_mode 等),
// 否则用户在 modal 打开瞬间看到的"默认表单"和类型下拉显示的类型不一致。
if (newFormData.config.agent_mode === 'smart-reasoning') {
const defaultTypeId = newFormData.config.agent_type as AgentType;
const preset = agentTypePresets.value.find(p => p.id === defaultTypeId) || null;
if (defaultTypeId && defaultTypeId !== 'custom') {
applyAgentTypePreset(preset);
}
// 给新建表单补上"我的 XXX"默认名 + 预设描述,让用户可直接保存;
// 用户输入过的值不会被覆盖(此处是新建场景,字段必定为空)。
if (!formData.value.name) {
formData.value.name = getPresetDefaultName(preset);
}
if (!formData.value.description) {
formData.value.description = getPresetDefaultDescription(preset);
}
}
}
}
});
@@ -2063,9 +2301,11 @@ watch(skillsSelectionMode, (mode) => {
// 监听模式变化,自动调整配置
watch(agentMode, (val, _oldVal) => {
if (val === 'smart-reasoning') {
// 切换到 Agent 模式,根据知识库配置启用工具
// 切换到 Agent 模式,根据知识库配置启用工具。
// 注意:默认不注入 thinking / todo_write —— 它们用于显式反思或多步计划,
// 会显著增加 token 消耗,用户按需手动勾选。
if (formData.value.config.allowed_tools.length === 0) {
const tools = ['thinking', 'todo_write'];
const tools: string[] = [];
if (hasRagKnowledgeBase.value) {
tools.push(
'knowledge_search',
@@ -2154,43 +2394,6 @@ watch(hasWikiKnowledgeBase, (hasWiki, oldHasWiki) => {
}
});
// 检索策略预设:一键改写 allowed_tools
// auto -> 按作用域内知识库能力自动补齐(RAG 库 → RAG 工具;Wiki 库 → Wiki 读取工具)
// vector_only -> 只保留 RAG 工具,移除 Wiki 工具
// wiki_only -> 只保留 Wiki 读取工具,移除 RAG 工具
// hybrid -> 两者都补齐
const onRetrievalPresetChange = (val: string) => {
formData.value.config.retrieval_preference = val as 'auto' | 'vector_only' | 'wiki_only' | 'hybrid';
if (!isAgentMode.value) return;
const current = new Set(formData.value.config.allowed_tools || []);
const addAll = (list: string[]) => list.forEach(t => current.add(t));
const removeAll = (list: string[]) => list.forEach(t => current.delete(t));
switch (val) {
case 'vector_only':
if (hasRagKnowledgeBase.value) addAll(knowledgeBaseTools);
removeAll(allWikiTools);
break;
case 'wiki_only':
removeAll(knowledgeBaseTools);
if (hasWikiKnowledgeBase.value) addAll(wikiReadTools);
break;
case 'hybrid':
if (hasRagKnowledgeBase.value) addAll(knowledgeBaseTools);
if (hasWikiKnowledgeBase.value) addAll(wikiReadTools);
break;
case 'auto':
default:
if (hasRagKnowledgeBase.value) addAll(knowledgeBaseTools);
if (hasWikiKnowledgeBase.value) addAll(wikiReadTools);
break;
}
formData.value.config.allowed_tools = Array.from(current);
};
// 监听运行模式变化,自动切换页面
watch(isAgentMode, (isAgent) => {
// 如果当前在高级设置页面但切换到了Agent模式,切换到基础设置
@@ -2239,14 +2442,16 @@ const loadDependencies = async () => {
if (kbRes.data) {
kbRes.data.forEach((kb: any) => {
const strategy = kb.indexing_strategy;
const caps: KBCapabilities | undefined = kb.capabilities;
myKbs.push({
label: kb.name,
value: kb.id,
type: kb.type || 'document',
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0),
shared: false,
ragEnabled: !strategy || strategy.vector_enabled || strategy.keyword_enabled,
wikiEnabled: strategy?.wiki_enabled || false,
ragEnabled: caps ? (caps.vector || caps.keyword) : (!strategy || strategy.vector_enabled || strategy.keyword_enabled),
wikiEnabled: caps ? caps.wiki : (strategy?.wiki_enabled || false),
capabilities: caps,
});
});
}
@@ -2260,6 +2465,7 @@ const loadDependencies = async () => {
sharedList.forEach((shared: any) => {
const kb = shared.knowledge_base;
if (!kb || myKbIds.has(kb.id)) return;
const caps: KBCapabilities | undefined = kb.capabilities;
sharedKbs.push({
label: kb.name,
value: kb.id,
@@ -2267,8 +2473,9 @@ const loadDependencies = async () => {
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0),
shared: true,
orgName: shared.org_name,
ragEnabled: !kb.indexing_strategy || kb.indexing_strategy.vector_enabled || kb.indexing_strategy.keyword_enabled,
wikiEnabled: kb.indexing_strategy?.wiki_enabled || false,
ragEnabled: caps ? (caps.vector || caps.keyword) : (!kb.indexing_strategy || kb.indexing_strategy.vector_enabled || kb.indexing_strategy.keyword_enabled),
wikiEnabled: caps ? caps.wiki : (kb.indexing_strategy?.wiki_enabled || false),
capabilities: caps,
});
});
}
@@ -2302,6 +2509,27 @@ const loadDependencies = async () => {
skillsAvailable.value = false;
}
// 加载智能体类型预设(smart-reasoning 模式下的"类型"下拉)
try {
const presetsRes: any = await getAgentTypePresets();
if (presetsRes?.data && Array.isArray(presetsRes.data)) {
agentTypePresets.value = presetsRes.data as AgentTypePreset[];
}
} catch (e) {
console.warn('Failed to load agent type presets', e);
}
// 加载 Agent 系统提示词模板(供 applyAgentTypePreset 根据 system_prompt_id 回填正文)
try {
const tmplRes = await getPromptTemplates();
const cfg = tmplRes?.data;
if (cfg?.agent_system_prompt && Array.isArray(cfg.agent_system_prompt)) {
agentSystemPromptTemplates.value = cfg.agent_system_prompt;
}
} catch (e) {
console.warn('Failed to load prompt templates for agent type presets', e);
}
// 加载存储引擎可用状态(用于图片存储 provider 选择)
try {
const statusRes = await getStorageEngineStatus();
@@ -3116,6 +3344,30 @@ const handleSystemPromptTemplateSelect = (template: PromptTemplate) => {
formData.value.config.system_prompt = template.content;
};
// Agent 系统提示词的"恢复默认":
// 当前选中了非 custom 的智能体类型时,"默认"应当是该类型预设绑定的提示词
// (比如 Wiki 问答 → wiki_researcher),而不是 agent_system_prompt 模板表里
// 全局 default: true 的那一条。只有当类型为 custom 或找不到预设绑定的模板时,
// 才回退到 PromptTemplateSelector 传来的全局默认模板。
const handleAgentSystemPromptResetDefault = (fallback: PromptTemplate) => {
const typeId = agentType.value;
if (typeId && typeId !== 'custom') {
const preset = agentTypePresets.value.find(p => p.id === typeId);
const presetPromptId = preset?.config?.system_prompt_id;
if (presetPromptId) {
const tmpl = agentSystemPromptTemplates.value.find(t => t.id === presetPromptId);
if (tmpl && typeof tmpl.content === 'string') {
formData.value.config.system_prompt = tmpl.content;
formData.value.config.system_prompt_id = tmpl.id;
return;
}
}
}
// Fallback:没有合适的类型预设,用 PromptTemplateSelector 找到的全局默认
formData.value.config.system_prompt = fallback.content;
formData.value.config.system_prompt_id = fallback.id;
};
const handleContextTemplateSelect = (template: PromptTemplate) => {
formData.value.config.context_template = template.content;
};
@@ -3445,6 +3697,28 @@ const handleSave = async () => {
padding-right: 0;
}
}
// 强调行:用于"智能体类型"这类对用户影响最大、需要突出的关键配置。
// 视觉上只做极轻度强调 —— 左侧 3px 品牌色竖条 + label 加粗。
&.setting-row--emphasize {
position: relative;
padding-left: 14px;
&::before {
content: '';
position: absolute;
left: 0;
top: 22px;
bottom: 22px;
width: 3px;
border-radius: 2px;
background: var(--td-brand-color, #0052d9);
}
.setting-info label {
font-weight: 600;
}
}
}
.setting-info {
@@ -3727,24 +4001,6 @@ const handleSave = async () => {
}
}
.tools-preset-label {
display: flex;
flex-direction: column;
min-width: 0;
gap: 2px;
.tools-preset-title {
font-size: 13px;
font-weight: 600;
color: var(--td-text-color-primary);
}
.tools-preset-hint {
font-size: 12px;
color: var(--td-text-color-secondary);
}
}
// ===== 按组的卡片网格 =====
.tool-groups {
display: flex;
@@ -4404,6 +4660,32 @@ const handleSave = async () => {
white-space: nowrap;
}
.kb-option-disabled-hint {
flex-shrink: 0;
font-size: 11px;
color: var(--td-warning-color-6, #d46b08);
background: var(--td-warning-color-1, #fff7e6);
padding: 1px 6px;
border-radius: 4px;
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.agent-type-preset-desc {
margin-top: 4px;
color: var(--td-text-color-secondary);
font-size: 12px;
line-height: 1.5;
}
.agent-type-select {
width: 100%;
min-width: 240px;
max-width: 360px;
}
.kb-option-count {
flex-shrink: 0;
font-size: 11px;
@@ -4475,3 +4757,41 @@ const handleSave = async () => {
}
}
</style>
<!-- Non-scoped styles: TDesign teleports the popup outside this component, so
scoped selectors can't reach .agent-type-popup .t-select-option. -->
<style lang="less">
.agent-type-popup {
.t-select-option {
// 默认 option 是 32px 单行;我们要双行显示,取消固定高度并放宽 padding
height: auto !important;
min-height: 48px;
line-height: 1.4;
padding: 8px 12px;
white-space: normal;
}
}
.agent-type-option {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
width: 100%;
}
.agent-type-option-label {
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
line-height: 1.4;
}
.agent-type-option-desc {
font-size: 12px;
color: var(--td-text-color-secondary);
line-height: 1.4;
white-space: normal;
overflow-wrap: break-word;
}
</style>
+9 -71
View File
@@ -341,18 +341,16 @@ func (s *agentService) registerTools(
sessionID string,
) error {
// Source of truth policy:
// - `config.AllowedTools` is the explicit, user-editable whitelist.
// - We no longer silently *inject* tools the user didn't pick (esp. wiki tools).
// - `config.AllowedTools` is the explicit, user-editable whitelist —
// populated by the agent-type preset on create and freely editable
// afterwards.
// - We never silently *inject* tools the user didn't pick.
// - We still *filter out* tools whose capability prerequisites are missing
// (no KB in scope, no Wiki-capable KB, etc.) so the LLM can't call tools
// that would error at runtime.
// - Legacy agents without AllowedTools fall back to DefaultAllowedTools(),
// and for them we preserve the historical "auto-append wiki tools when
// a wiki KB is in scope" behavior for backward compatibility.
hasExplicitAllowedTools := len(config.AllowedTools) > 0
// - Legacy agents without AllowedTools fall back to DefaultAllowedTools().
var allowedTools []string
if hasExplicitAllowedTools {
if len(config.AllowedTools) > 0 {
allowedTools = make([]string, len(config.AllowedTools))
copy(allowedTools, config.AllowedTools)
logger.Infof(ctx, "Using custom allowed tools from config: %v", allowedTools)
@@ -433,31 +431,12 @@ func (s *agentService) registerTools(
allowedTools = append(allowedTools, tools.ToolWebFetch)
}
retrievalPref := config.RetrievalPreference
if retrievalPref == "" {
retrievalPref = "auto"
}
// Default wiki read-only set used for backward-compat auto-injection below.
// Edit/issue wiki tools are intentionally excluded — they must be explicitly
// opted in via AllowedTools because they can mutate data.
defaultWikiReadTools := []string{
tools.ToolWikiReadPage,
tools.ToolWikiSearch,
tools.ToolWikiReadSourceDoc,
tools.ToolWikiFlagIssue,
}
// ---- Apply retrieval preference ----
// Preference is now a *filter*, never an injector (for explicit lists).
// For legacy agents without explicit AllowedTools, we still auto-append
// wiki read tools so existing integrations keep working.
// Tool capability sets — used by the hard safety nets below to drop tools
// whose runtime prerequisite (a matching KB surface) is missing.
//
// NOTE: ragToolSet must stay in sync with frontend `knowledgeBaseTools`
// in AgentEditorModal.vue. These are *all* tools that retrieve/inspect
// content from RAG-style knowledge bases; wiki_only must strip the whole
// set, otherwise the agent can still reach RAG data via graph/db/doc
// info tools despite the user asking for Wiki only.
// content from RAG-style knowledge bases.
ragToolSet := map[string]bool{
tools.ToolKnowledgeSearch: true,
tools.ToolGrepChunks: true,
@@ -479,47 +458,6 @@ func (s *agentService) registerTools(
tools.ToolWikiUpdateIssue: true,
}
switch retrievalPref {
case "vector_only":
filtered := make([]string, 0, len(allowedTools))
dropped := make([]string, 0)
for _, t := range allowedTools {
if allWikiToolSet[t] {
dropped = append(dropped, t)
continue
}
filtered = append(filtered, t)
}
allowedTools = filtered
logger.Infof(ctx, "Retrieval preference: vector_only, wiki tools filtered out: %v", dropped)
case "wiki_only":
filtered := make([]string, 0, len(allowedTools))
dropped := make([]string, 0)
for _, t := range allowedTools {
if ragToolSet[t] {
dropped = append(dropped, t)
continue
}
filtered = append(filtered, t)
}
allowedTools = filtered
// Only legacy agents get auto-append here; explicit lists are authoritative.
if !hasExplicitAllowedTools && hasWikiKB {
allowedTools = append(allowedTools, defaultWikiReadTools...)
}
logger.Infof(ctx, "Retrieval preference: wiki_only, RAG tools filtered out: %v", dropped)
case "hybrid":
if !hasExplicitAllowedTools && hasWikiKB {
allowedTools = append(allowedTools, defaultWikiReadTools...)
logger.Infof(ctx, "Retrieval preference: hybrid (legacy), wiki read tools auto-added")
}
default: // "auto"
if !hasExplicitAllowedTools && hasWikiKB {
allowedTools = append(allowedTools, defaultWikiReadTools...)
logger.Infof(ctx, "Retrieval preference: auto (legacy), wiki read tools auto-added")
}
}
// Hard safety nets: drop tools whose runtime prerequisite is missing.
// This guards against stale configs where e.g. the user ticked wiki tools
// earlier but later swapped in a non-wiki KB (or vice versa for RAG).
@@ -226,7 +226,6 @@ func (s *sessionService) buildAgentConfig(
MCPServices: customAgent.Config.MCPServices,
Thinking: customAgent.Config.Thinking,
RetrieveKBOnlyWhenMentioned: customAgent.Config.RetrieveKBOnlyWhenMentioned,
RetrievalPreference: customAgent.Config.RetrievalPreference,
LLMCallTimeout: customAgent.Config.LLMCallTimeout,
RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory,
}
+12
View File
@@ -408,10 +408,22 @@ func LoadConfig() (*Config, error) {
fmt.Printf("Warning: failed to load builtin agents config: %v\n", err)
}
// Load smart-reasoning agent type presets (rag-qa / wiki-qa / hybrid / custom).
if err := types.LoadAgentTypePresetsConfig(configDir); err != nil {
fmt.Printf("Warning: failed to load agent type presets: %v\n", err)
}
// Resolve prompt template ID references in builtin agent configs
// (e.g. system_prompt_id -> actual content from agent_system_prompt.yaml)
if cfg.PromptTemplates != nil {
resolveBuiltinAgentPromptIDs(cfg.PromptTemplates)
// Validate that every preset references an existing prompt template.
types.ResolveAgentTypePresetPromptRefs(func(id string) string {
if t := FindTemplateByID(cfg.PromptTemplates, id); t != nil {
return t.Content
}
return ""
})
}
// Validate configuration values
+19
View File
@@ -379,6 +379,25 @@ func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
})
}
// GetAgentTypePresets godoc
// @Summary 获取智能体类型预设列表
// @Description 返回所有 smart-reasoning 下可用的智能体类型预设(RAG/Wiki/Hybrid/Custom),用于编辑器自动填充系统提示词、工具和 KB 兼容性
// @Tags 智能体
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "预设列表"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/type-presets [get]
func (h *CustomAgentHandler) GetAgentTypePresets(c *gin.Context) {
ctx := c.Request.Context()
presets := types.ListAgentTypePresetsWithContext(ctx)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": presets,
})
}
// GetSuggestedQuestions godoc
// @Summary 获取推荐问题
// @Description 基于智能体关联的知识库,返回推荐问题供用户快捷提问
+2
View File
@@ -532,6 +532,8 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
{
// Get placeholder definitions (must be before /:id to avoid conflict)
agents.GET("/placeholders", agentHandler.GetPlaceholders)
// List smart-reasoning agent type presets (rag-qa / wiki-qa / hybrid / custom)
agents.GET("/type-presets", agentHandler.GetAgentTypePresets)
// Create custom agent
agents.POST("", agentHandler.CreateAgent)
// List all agents (including built-in)
-4
View File
@@ -37,10 +37,6 @@ type AgentConfig struct {
// Whether to retrieve knowledge base only when explicitly mentioned with @ (default: false)
RetrieveKBOnlyWhenMentioned bool `json:"retrieve_kb_only_when_mentioned"`
// RetrievalPreference controls which retrieval tools the agent uses:
// "auto" (default), "vector_only", "wiki_only", "hybrid"
RetrievalPreference string `json:"retrieval_preference"`
// Whether to retain retrieval history (like wiki_read_page results) across turns (default: false)
RetainRetrievalHistory bool `json:"retain_retrieval_history"`
+213
View File
@@ -0,0 +1,213 @@
package types
import (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"gopkg.in/yaml.v3"
)
// ---------------------------------------------------------------------------
// YAML data structures for config/agent_type_presets.yaml
// ---------------------------------------------------------------------------
// AgentTypePresetI18n holds localised label and description for a single locale.
type AgentTypePresetI18n struct {
Label string `yaml:"label" json:"label"`
Description string `yaml:"description" json:"description"`
}
// AgentTypeKBFilter describes how the agent editor should filter selectable KBs
// when this preset is active. Predicates are evaluated against the KB's
// capabilities (see KBCapabilities).
//
// If all three slices are empty, the preset imposes no KB restriction.
type AgentTypeKBFilter struct {
// AnyOf: KB must expose at least ONE of these capability flags.
AnyOf []string `yaml:"any_of" json:"any_of,omitempty"`
// AllOf: KB must expose ALL of these capability flags.
AllOf []string `yaml:"all_of" json:"all_of,omitempty"`
// NoneOf: KB must expose NONE of these capability flags.
NoneOf []string `yaml:"none_of" json:"none_of,omitempty"`
}
// AgentTypePresetEntry is one entry in the agent_type_presets list in YAML.
//
// Only fields relevant for auto-filling the editor form are included under
// `config`. Everything else (retrieval thresholds, etc.) falls back to the
// user-edited defaults / CustomAgent.EnsureDefaults.
type AgentTypePresetEntry struct {
ID string `yaml:"id" json:"id"`
I18n map[string]AgentTypePresetI18n `yaml:"i18n" json:"i18n"`
Config *AgentTypePresetConfig `yaml:"config" json:"config,omitempty"`
KBFilter *AgentTypeKBFilter `yaml:"kb_filter" json:"kb_filter,omitempty"`
}
// AgentTypePresetConfig is a restricted view of CustomAgentConfig used purely
// as the preset payload. Any field left at its zero value is NOT applied by
// the preset so the user's existing value stays untouched.
//
// We mirror json tags (not yaml tags) directly from CustomAgentConfig so the
// frontend can apply them via simple Object.assign.
type AgentTypePresetConfig struct {
SystemPromptID string `yaml:"system_prompt_id" json:"system_prompt_id,omitempty"`
Temperature float64 `yaml:"temperature" json:"temperature,omitempty"`
MaxIterations int `yaml:"max_iterations" json:"max_iterations,omitempty"`
AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools,omitempty"`
RetainRetrievalHistory bool `yaml:"retain_retrieval_history" json:"retain_retrieval_history,omitempty"`
FAQPriorityEnabled bool `yaml:"faq_priority_enabled" json:"faq_priority_enabled,omitempty"`
WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled,omitempty"`
SupportedFileTypes []string `yaml:"supported_file_types" json:"supported_file_types,omitempty"`
// KBSelectionMode presets the KB picker mode: "all" | "selected" | "none".
// When empty, the user's current value stays untouched.
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode,omitempty"`
}
// agentTypePresetsFile is the top-level YAML structure.
type agentTypePresetsFile struct {
Presets []AgentTypePresetEntry `yaml:"agent_type_presets"`
}
// ---------------------------------------------------------------------------
// Global registry (populated from YAML at startup)
// ---------------------------------------------------------------------------
var (
agentTypePresets map[string]*AgentTypePresetEntry // keyed by preset ID
agentTypePresetsMu sync.RWMutex
agentTypePresetsOnce sync.Once
agentTypePresetIDs []string // insertion order, for stable UI listing
)
// LoadAgentTypePresetsConfig loads agent-type preset definitions from the given
// config directory (e.g. "./config"). The file must be named
// "agent_type_presets.yaml". Called once at startup (after LoadConfig determines
// the config directory).
//
// If the file does not exist, this is a no-op and the registry stays empty —
// in that case the frontend will simply not offer the agent-type dropdown.
func LoadAgentTypePresetsConfig(configDir string) error {
var loadErr error
agentTypePresetsOnce.Do(func() {
filePath := filepath.Join(configDir, "agent_type_presets.yaml")
data, err := os.ReadFile(filePath)
if err != nil {
if os.IsNotExist(err) {
return
}
loadErr = fmt.Errorf("read agent_type_presets.yaml: %w", err)
return
}
var file agentTypePresetsFile
if err := yaml.Unmarshal(data, &file); err != nil {
loadErr = fmt.Errorf("parse agent_type_presets.yaml: %w", err)
return
}
agentTypePresetsMu.Lock()
defer agentTypePresetsMu.Unlock()
agentTypePresets = make(map[string]*AgentTypePresetEntry, len(file.Presets))
agentTypePresetIDs = make([]string, 0, len(file.Presets))
for i := range file.Presets {
entry := &file.Presets[i]
if entry.ID == "" {
continue
}
agentTypePresets[entry.ID] = entry
agentTypePresetIDs = append(agentTypePresetIDs, entry.ID)
}
})
return loadErr
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
// ListAgentTypePresetsWithContext returns all registered agent-type presets in
// their YAML-declared order, with i18n resolved against the request locale.
//
// The returned slice is a fresh copy safe to mutate by the caller (e.g. to
// tweak the i18n label before encoding).
func ListAgentTypePresetsWithContext(ctx context.Context) []AgentTypePresetEntry {
locale := localeFromCtx(ctx)
agentTypePresetsMu.RLock()
defer agentTypePresetsMu.RUnlock()
out := make([]AgentTypePresetEntry, 0, len(agentTypePresetIDs))
for _, id := range agentTypePresetIDs {
entry := agentTypePresets[id]
if entry == nil {
continue
}
// Shallow copy and narrow i18n down to the caller's locale so the
// API response is compact. We keep both "default" and the resolved
// locale entry in case the frontend wants to fall back.
cp := *entry
if len(entry.I18n) > 0 {
cp.I18n = resolveAgentTypeI18n(entry.I18n, locale)
}
out = append(out, cp)
}
return out
}
// GetAgentTypePreset returns the raw entry for the given preset ID, or nil.
// Used by prompt-resolution at startup.
func GetAgentTypePreset(id string) *AgentTypePresetEntry {
agentTypePresetsMu.RLock()
defer agentTypePresetsMu.RUnlock()
return agentTypePresets[id]
}
// ResolveAgentTypePresetPromptRefs iterates over all presets and resolves
// system_prompt_id references into the actual prompt template content via the
// provided resolver. This lets downstream services treat the `system_prompt_id`
// field as a concrete prompt string if they need to.
//
// We keep system_prompt_id as-is in the preset (it's also what the editor
// writes back to CustomAgentConfig), so this hook is only used to validate
// that every referenced template actually exists at startup.
func ResolveAgentTypePresetPromptRefs(resolver func(id string) string) {
agentTypePresetsMu.Lock()
defer agentTypePresetsMu.Unlock()
for _, entry := range agentTypePresets {
if entry == nil || entry.Config == nil || entry.Config.SystemPromptID == "" {
continue
}
if content := resolver(entry.Config.SystemPromptID); content == "" {
fmt.Printf(
"Warning: agent type preset %q references system_prompt_id %q but template not found\n",
entry.ID, entry.Config.SystemPromptID,
)
}
}
}
// resolveAgentTypeI18n picks a reasonable subset of i18n entries for the given
// locale: the exact-match entry (if any) plus the "default" fallback. Callers
// that want full i18n can pass an empty locale to get everything.
func resolveAgentTypeI18n(m map[string]AgentTypePresetI18n, locale string) map[string]AgentTypePresetI18n {
out := make(map[string]AgentTypePresetI18n, 2)
if v, ok := m["default"]; ok {
out["default"] = v
}
if locale != "" {
if v, ok := m[locale]; ok {
out[locale] = v
}
}
// If neither matched, surface the whole map so the frontend can decide.
if len(out) == 0 {
for k, v := range m {
out[k] = v
}
}
return out
}
+27 -10
View File
@@ -36,6 +36,27 @@ const (
AgentModeSmartReasoning = "smart-reasoning"
)
// AgentType constants for Smart-Reasoning agent presets.
// These presets bundle a recommended system prompt template,
// tool allowlist, KB compatibility hint, and other defaults so users
// don't have to configure everything from scratch.
// AgentTypeCustom means the user wants full control and we won't
// auto-fill anything based on the preset.
const (
// AgentTypeRAGQA prefers vector/keyword chunk retrieval on document KBs.
AgentTypeRAGQA = "rag-qa"
// AgentTypeWikiQA prefers wiki-page navigation on wiki-enabled KBs.
AgentTypeWikiQA = "wiki-qa"
// AgentTypeHybridRAGWiki orchestrates Wiki + RAG on KBs where both are enabled.
AgentTypeHybridRAGWiki = "hybrid-rag-wiki"
// AgentTypeDataAnalysis runs SQL / statistics over tabular files (CSV, Excel)
// uploaded into the KB. Retrieval semantics (vector/wiki/…) are largely
// irrelevant — this type is about data_schema + data_analysis tools.
AgentTypeDataAnalysis = "data-analysis"
// AgentTypeCustom is the "no preset" option; user-configured end to end.
AgentTypeCustom = "custom"
)
// CustomAgent represents a configurable AI agent (similar to GPTs)
type CustomAgent struct {
// Unique identifier of the agent (composite primary key with TenantID)
@@ -69,6 +90,12 @@ type CustomAgentConfig struct {
// ===== Basic Settings =====
// Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent mode
AgentMode string `yaml:"agent_mode" json:"agent_mode"`
// AgentType is a preset category under smart-reasoning mode that pre-fills
// system prompt, allowed tools and recommended KB compatibility.
// Valid values: "rag-qa", "wiki-qa", "hybrid-rag-wiki", "custom".
// Empty / unknown values are treated as "custom" (no preset applied).
// Ignored for quick-answer mode.
AgentType string `yaml:"agent_type" json:"agent_type,omitempty"`
// System prompt for the agent (unified prompt, uses web_search_status placeholder for dynamic behavior)
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
// SystemPromptID references a template ID in prompt_templates/ YAML files.
@@ -119,13 +146,6 @@ type CustomAgentConfig struct {
// When false, knowledge base retrieval happens according to KBSelectionMode
RetrieveKBOnlyWhenMentioned bool `yaml:"retrieve_kb_only_when_mentioned" json:"retrieve_kb_only_when_mentioned"`
// RetrievalPreference controls which retrieval tools the agent uses:
// "auto" - auto-detect from KB capabilities (default, preserves existing behavior)
// "vector_only" - only use vector/keyword search tools, no wiki tools
// "wiki_only" - only use wiki tools, no vector/keyword search tools
// "hybrid" - use both vector/keyword search AND wiki tools
RetrievalPreference string `yaml:"retrieval_preference" json:"retrieval_preference"`
// Whether to retain retrieval history across turns
RetainRetrievalHistory bool `yaml:"retain_retrieval_history" json:"retain_retrieval_history"`
@@ -269,9 +289,6 @@ func (a *CustomAgent) EnsureDefaults() {
if a.Config.FallbackStrategy == "" {
a.Config.FallbackStrategy = "model"
}
if a.Config.RetrievalPreference == "" {
a.Config.RetrievalPreference = "auto"
}
if a.Config.MaxCompletionTokens == 0 {
a.Config.MaxCompletionTokens = 2048
}
+47
View File
@@ -532,6 +532,53 @@ func (kb *KnowledgeBase) EnsureDefaults() {
}
}
// KBCapabilities describes the functional features a knowledge base exposes.
// It is computed from the KB's configuration (IndexingStrategy, Type, WikiConfig, …)
// and surfaced in the JSON representation of a KnowledgeBase so that the frontend
// can filter / enable / disable KB options based on what the selected agent type needs.
type KBCapabilities struct {
// Vector means semantic (embedding) search is indexed.
Vector bool `json:"vector"`
// Keyword means BM25 / sparse keyword search is indexed.
Keyword bool `json:"keyword"`
// Wiki means the wiki feature is enabled and authored pages exist / will be generated.
Wiki bool `json:"wiki"`
// Graph means knowledge-graph extraction is enabled.
Graph bool `json:"graph"`
// FAQ means the KB is a FAQ-type KB (Q/A pairs).
FAQ bool `json:"faq"`
}
// Capabilities returns the computed capability flags for this KB.
// Safe to call on a nil KB (returns zero value).
func (kb *KnowledgeBase) Capabilities() KBCapabilities {
if kb == nil {
return KBCapabilities{}
}
return KBCapabilities{
Vector: kb.IsVectorEnabled(),
Keyword: kb.IsKeywordEnabled(),
Wiki: kb.IsWikiEnabled(),
Graph: kb.IsGraphEnabled(),
FAQ: kb.Type == KnowledgeBaseTypeFAQ,
}
}
// MarshalJSON augments the default JSON encoding of KnowledgeBase with a computed
// `capabilities` field so clients (agent editor) can filter KBs by feature.
// It preserves all existing fields verbatim.
func (kb *KnowledgeBase) MarshalJSON() ([]byte, error) {
type alias KnowledgeBase
aux := struct {
*alias
Capabilities KBCapabilities `json:"capabilities"`
}{
alias: (*alias)(kb),
Capabilities: kb.Capabilities(),
}
return json.Marshal(aux)
}
// IsWikiEnabled checks if the wiki feature is enabled for this knowledge base.
// Wiki requires both IndexingStrategy.WikiEnabled and WikiConfig with Enabled=true.
func (kb *KnowledgeBase) IsWikiEnabled() bool {