Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor: 调整智能体配置,增强智能体选择与状态管理
wizardchen0ca947981aab
diff --git a/config/config.yaml b/config/config.yamlindex 693a7064c..7cdb6e31e 100644--- a/config/config.yaml+++ b/config/config.yaml@@ -23,7 +23,7 @@ conversation:- 使用礼貌、专业的语气## 用户的问题是:- {{.Query}}+ {{query}}enable_rewrite: trueenable_query_expansion: trueenable_rerank: true@@ -82,15 +82,10 @@ conversation:改写后: 国外手机号是否可以注册微信账号rewrite_prompt_user: |## 历史对话背景- {{range .Conversation}}- ------BEGIN------- 用户的问题是:{{.Query}}- 助手的回答是:{{.Answer}}- ------END------- {{end}}+ {{conversation}}## 需要改写的用户问题- {{.Query}}+ {{query}}## 改写后的问题keywords_extraction_prompt: |@@ -134,7 +129,7 @@ conversation:Output: iPhone, 连接WiFi, 使用iPhone连接WiFi# Real Data- USER: {{.Query}}+ USER: {{query}}keywords_extraction_prompt_user: |Output:@@ -483,11 +478,11 @@ conversation:generate_questions_prompt: |你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。- {{.Context}}+ {{context}}## 主要内容(请基于此内容生成问题)- 文档名称:{{.DocName}}+ 文档名称:{{doc_name}}文档内容:- {{.Content}}+ {{content}}## 核心要求- 生成的问题必须与【主要内容】直接相关@@ -496,7 +491,7 @@ conversation:- 问题应该是用户在实际场景中可能会提出的自然问题- 问题应该多样化,覆盖内容的不同方面- 每个问题应该简洁明了,长度控制在30字以内- - 生成的问题数量为 {{.QuestionCount}} 个+ - 生成的问题数量为 {{question_count}} 个## 问题类型建议- 定义类:什么是...?...是什么?diff --git a/config/prompt_templates/fallback.yaml b/config/prompt_templates/fallback.yamlindex e1902d116..5f0e722ae 100644--- a/config/prompt_templates/fallback.yaml+++ b/config/prompt_templates/fallback.yaml@@ -44,4 +44,4 @@ templates:2. 如果问题涉及特定领域或需要最新信息,建议用户查阅官方资料3. 保持回答的准确性和客观性- 用户问题:{{.Query}}+ 用户问题:{{query}}diff --git a/config/prompt_templates/rewrite_user.yaml b/config/prompt_templates/rewrite_user.yamlindex 54e0f9941..8605c1af1 100644--- a/config/prompt_templates/rewrite_user.yaml+++ b/config/prompt_templates/rewrite_user.yaml@@ -5,15 +5,10 @@ templates:description: "标准的改写用户提示词格式"content: |## 历史对话背景- {{range .Conversation}}- ------BEGIN------- 用户的问题是:{{.Query}}- 助手的回答是:{{.Answer}}- ------END------- {{end}}+ {{conversation}}## 需要改写的用户问题- {{.Query}}+ {{query}}## 改写后的问题@@ -24,14 +19,10 @@ templates:## 历史对话背景以下是用户与助手的对话历史,请仔细阅读以理解上下文:- {{range .Conversation}}- 【用户】{{.Query}}- 【助手】{{.Answer}}-- {{end}}+ {{conversation}}## 当前用户问题- {{.Query}}+ {{query}}## 任务要求请根据以上对话历史,将当前问题改写为一个独立、完整、可以脱离上下文理解的问题。diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.tsindex 43987153f..927daa63f 100644--- a/frontend/src/api/agent/index.ts+++ b/frontend/src/api/agent/index.ts@@ -1,12 +1,9 @@import { get, post, put, del } from "../../utils/request";-// 智能体类型-export type CustomAgentType = 'normal' | 'agent' | 'custom';-// 智能体配置export interface CustomAgentConfig {// ===== 基础设置 =====- agent_mode?: 'normal' | 'agent'; // 运行模式:normal=RAG模式, agent=ReAct Agent模式+ agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式system_prompt?: string; // 系统提示词(普通模式,或Agent模式网络搜索关闭时)system_prompt_web_enabled?: string; // Agent模式网络搜索开启时的系统提示词context_template?: string; // 上下文模板(普通模式)@@ -21,15 +18,14 @@ export interface CustomAgentConfig {max_iterations?: number; // 最大迭代次数allowed_tools?: string[]; // 允许的工具reflection_enabled?: boolean; // 是否启用反思+ // MCP服务选择模式:all=全部启用的MCP服务, selected=指定服务, none=不使用MCP+ mcp_selection_mode?: 'all' | 'selected' | 'none';+ mcp_services?: string[]; // 选择的MCP服务ID列表// ===== 知识库设置 =====// 知识库选择模式:all=全部知识库, selected=指定知识库, none=不使用知识库kb_selection_mode?: 'all' | 'selected' | 'none';knowledge_bases?: string[];- // 当没有配置知识库时,是否允许用户自由选择知识库- // true (默认): 用户可以自由选择任意知识库- // false: 禁用知识库选择功能- allow_user_kb_selection?: boolean;// ===== 网络搜索设置 =====web_search_enabled?: boolean;@@ -67,7 +63,6 @@ export interface CustomAgent {description?: string;avatar?: string;is_builtin: boolean;- type: CustomAgentType;tenant_id?: number;created_by?: string;config: CustomAgentConfig;@@ -80,7 +75,6 @@ export interface CreateAgentRequest {name: string;description?: string;avatar?: string;- type?: CustomAgentType;config?: CustomAgentConfig;}@@ -89,13 +83,27 @@ export interface UpdateAgentRequest {name: string;description?: string;avatar?: string;- type?: CustomAgentType;config?: CustomAgentConfig;}// 内置智能体 ID-export const BUILTIN_AGENT_NORMAL_ID = 'builtin-normal';-export const BUILTIN_AGENT_AGENT_ID = 'builtin-agent';+export const BUILTIN_QUICK_ANSWER_ID = 'builtin-quick-answer';+export const BUILTIN_SMART_REASONING_ID = 'builtin-smart-reasoning';++// AgentMode 常量+export const AGENT_MODE_QUICK_ANSWER = 'quick-answer';+export const AGENT_MODE_SMART_REASONING = 'smart-reasoning';++// Deprecated: Use BUILTIN_QUICK_ANSWER_ID instead+export const BUILTIN_AGENT_NORMAL_ID = BUILTIN_QUICK_ANSWER_ID;+// Deprecated: Use BUILTIN_SMART_REASONING_ID instead+export const BUILTIN_AGENT_AGENT_ID = BUILTIN_SMART_REASONING_ID;++// 所有内置智能体 ID 列表(便于扩展)+export const BUILTIN_AGENT_IDS = [+ BUILTIN_QUICK_ANSWER_ID,+ BUILTIN_SMART_REASONING_ID,+] as const;// 获取智能体列表(包括内置智能体)export function listAgents() {@@ -122,7 +130,35 @@ export function deleteAgent(id: string) {return del<{ success: boolean }>(`/api/v1/agents/${id}`);}+// 复制智能体+export function copyAgent(id: string) {+ return post<{ data: CustomAgent }>(`/api/v1/agents/${id}/copy`);+}+// 判断是否为内置智能体export function isBuiltinAgent(agentId: string): boolean {- return agentId === BUILTIN_AGENT_NORMAL_ID || agentId === BUILTIN_AGENT_AGENT_ID;+ return (BUILTIN_AGENT_IDS as readonly string[]).includes(agentId);+}++// 占位符定义+export interface PlaceholderDefinition {+ name: string;+ label: string;+ description: string;+}++// 占位符响应+export interface PlaceholdersResponse {+ all: PlaceholderDefinition[];+ system_prompt: PlaceholderDefinition[];+ agent_system_prompt: PlaceholderDefinition[];+ context_template: PlaceholderDefinition[];+ rewrite_system_prompt: PlaceholderDefinition[];+ rewrite_prompt: PlaceholderDefinition[];+ fallback_prompt: PlaceholderDefinition[];+}++// 获取占位符定义+export function getPlaceholders() {+ return get<{ data: PlaceholdersResponse }>('/api/v1/agents/placeholders');}diff --git a/frontend/src/components/AgentAvatar.vue b/frontend/src/components/AgentAvatar.vueindex 570e51816..af91eb241 100644--- a/frontend/src/components/AgentAvatar.vue+++ b/frontend/src/components/AgentAvatar.vue@@ -110,12 +110,17 @@ const letterStyle = computed(() => {overflow: hidden;&.agent-avatar-small {- width: 24px;- height: 24px;- border-radius: 6px;+ width: 22px;+ height: 22px;+ border-radius: 5px;+ box-shadow: none;.agent-avatar-letter {- font-size: 12px;+ font-size: 11px;+ }++ .agent-sparkles {+ display: none;}}diff --git a/frontend/src/components/AgentSelector.vue b/frontend/src/components/AgentSelector.vueindex e8d6701fc..701da0ae2 100644--- a/frontend/src/components/AgentSelector.vue+++ b/frontend/src/components/AgentSelector.vue@@ -32,8 +32,8 @@:class="{ 'selected': currentAgentId === agent.id }"@click="selectAgent(agent)">- <div class="builtin-icon" :class="agent.type">- <TIcon :name="agent.type === 'agent' ? 'control-platform' : 'chat'" size="14px" />+ <div class="builtin-icon" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">+ <TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" /></div><span class="agent-option-name">{{ agent.name }}</span><svg@@ -95,7 +95,7 @@import { ref, computed, watch, onMounted, nextTick } from 'vue';import { useI18n } from 'vue-i18n';import { Icon as TIcon } from 'tdesign-vue-next';-import { listAgents, type CustomAgent } from '@/api/agent';+import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';import AgentAvatar from '@/components/AgentAvatar.vue';const { t } = useI18n();@@ -118,18 +118,18 @@ const dropdownStyle = ref<Record<string, string>>({});const builtinAgents = computed(() => {return [{- id: 'builtin-normal',+ id: BUILTIN_QUICK_ANSWER_ID,name: t('input.normalMode'),description: t('input.normalModeDesc'),- type: 'normal',- is_builtin: true+ is_builtin: true,+ config: { agent_mode: 'quick-answer' as const }},{- id: 'builtin-agent',+ id: BUILTIN_SMART_REASONING_ID,name: t('input.agentMode'),description: t('input.agentModeDesc'),- type: 'agent',- is_builtin: true+ is_builtin: true,+ config: { agent_mode: 'smart-reasoning' as const }}] as CustomAgent[];});@@ -143,9 +143,9 @@ const customAgents = computed(() => {const getAgentCapabilities = (agent: CustomAgent): string => {// 内置智能体if (agent.is_builtin) {- if (agent.type === 'normal') {+ if (agent.config?.agent_mode === 'quick-answer') {return t('agent.capabilities.normal');- } else if (agent.type === 'agent') {+ } else if (agent.config?.agent_mode === 'smart-reasoning') {return t('agent.capabilities.agent');}return '';@@ -158,10 +158,12 @@ const getAgentCapabilities = (agent: CustomAgent): string => {if (config.model_id) {capabilities.push(t('agent.capabilities.modelSpecified'));}- if (config.knowledge_bases && config.knowledge_bases.length > 0) {- capabilities.push(t('agent.capabilities.kbCount', { count: config.knowledge_bases.length }));- } else if (config.allow_user_kb_selection === false) {+ if (config.kb_selection_mode === 'none') {capabilities.push(t('agent.capabilities.kbDisabled'));+ } else if (config.knowledge_bases && config.knowledge_bases.length > 0) {+ capabilities.push(t('agent.capabilities.kbCount', { count: config.knowledge_bases.length }));+ } else if (config.kb_selection_mode === 'all') {+ capabilities.push(t('agent.capabilities.kbAll'));}if (config.rerank_model_id) {capabilities.push(t('agent.capabilities.rerankSpecified'));diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vueindex 739b90273..5d6316f54 100644--- a/frontend/src/components/Input-field.vue+++ b/frontend/src/components/Input-field.vue@@ -12,7 +12,7 @@ import MentionSelector from './MentionSelector.vue';import AgentSelector from './AgentSelector.vue';import { getCaretCoordinates } from '@/utils/caret';import { listModels, type ModelConfig } from '@/api/model';-import { listAgents, type CustomAgent } from '@/api/agent';+import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';import { getTenantWebSearchConfig } from '@/api/web-search';import { getConversationConfig, updateConversationConfig, type ConversationConfig } from '@/api/system';import { useI18n } from 'vue-i18n';@@ -31,80 +31,92 @@ const agentModeDropdownStyle = ref<Record<string, string>>({});// 智能体相关状态const agents = ref<CustomAgent[]>([]);const selectedAgentId = computed({- get: () => settingsStore.selectedAgentId || 'builtin-normal',+ get: () => settingsStore.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,set: (val: string) => settingsStore.selectAgent(val)});const selectedAgent = computed(() => {return agents.value.find(a => a.id === selectedAgentId.value) || {- id: 'builtin-normal',+ id: BUILTIN_QUICK_ANSWER_ID,name: t('input.normalMode'),- type: 'normal',- is_builtin: true+ is_builtin: true,+ config: { agent_mode: 'quick-answer' as const }} as CustomAgent;});// 判断是否为自定义智能体(非内置)const isCustomAgent = computed(() => {const agent = selectedAgent.value;- return agent && !agent.is_builtin && agent.type === 'custom';+ return agent && !agent.is_builtin;+});++// 判断是否有智能体配置(包括内置智能体)+const hasAgentConfig = computed(() => {+ const agent = selectedAgent.value;+ // 内置智能体需要从 agents 列表中获取实际配置+ if (agent?.is_builtin) {+ const builtinAgent = agents.value.find(a => a.id === agent.id);+ return !!builtinAgent?.config;+ }+ return !!agent?.config;+});++// 获取当前智能体的实际配置(内置智能体从 agents 列表获取)+const currentAgentConfig = computed(() => {+ const agent = selectedAgent.value;+ if (agent?.is_builtin) {+ const builtinAgent = agents.value.find(a => a.id === agent.id);+ return builtinAgent?.config || {};+ }+ return agent?.config || {};});// 智能体预配置的知识库 IDsconst agentKnowledgeBases = computed(() => {- if (!isCustomAgent.value) return [];- return selectedAgent.value?.config?.knowledge_bases || [];+ if (!hasAgentConfig.value) return [];+ return currentAgentConfig.value?.knowledge_bases || [];});// 智能体的知识库选择模式const agentKBSelectionMode = computed(() => {- if (!isCustomAgent.value) return null; // null 表示不受智能体控制- return selectedAgent.value?.config?.kb_selection_mode || 'none';+ if (!hasAgentConfig.value) return null; // null 表示不受智能体控制+ return currentAgentConfig.value?.kb_selection_mode || 'all';});// 智能体是否启用了网络搜索const agentWebSearchEnabled = computed(() => {- if (!isCustomAgent.value) return null; // null 表示不受智能体控制- return selectedAgent.value?.config?.web_search_enabled ?? false;+ if (!hasAgentConfig.value) return null; // null 表示不受智能体控制+ return currentAgentConfig.value?.web_search_enabled ?? true;});-// 网络搜索是否被智能体禁用(只读状态)+// 网络搜索是否被智能体禁用(只读状态)- 只有明确设置为 false 时才禁用const isWebSearchDisabledByAgent = computed(() => {- return isCustomAgent.value && agentWebSearchEnabled.value === false;-});--// 网络搜索是否被智能体强制启用-const isWebSearchForcedByAgent = computed(() => {- return isCustomAgent.value && agentWebSearchEnabled.value === true;+ return hasAgentConfig.value && agentWebSearchEnabled.value === false;});// 知识库选择是否被智能体锁定// 1. 如果智能体配置了 kb_selection_mode = 'none' → 完全禁用知识库-// 2. 如果智能体配置了 kb_selection_mode = 'selected' 且 allow_user_kb_selection=false → 锁定到指定知识库-// 3. 如果智能体配置了 kb_selection_mode = 'all' 且 allow_user_kb_selection=false → 锁定到全部知识库(但不允许用户选择)+// 其他情况用户都可以在允许的范围内通过 @ 选择知识库const isKnowledgeBaseLockedByAgent = computed(() => {- if (!isCustomAgent.value) return false;- // 如果禁用了知识库,返回 true(锁定状态)- if (agentKBSelectionMode.value === 'none') return true;- // 如果不允许用户选择知识库,返回 true- const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection;- return allowUserKBSelection === false;+ if (!hasAgentConfig.value) return false;+ // 只有禁用了知识库才锁定+ return agentKBSelectionMode.value === 'none';});// 知识库是否被智能体完全禁用(kb_selection_mode = 'none')const isKnowledgeBaseDisabledByAgent = computed(() => {- if (!isCustomAgent.value) return false;+ if (!hasAgentConfig.value) return false;return agentKBSelectionMode.value === 'none';});// 智能体配置的模型 IDconst agentModelId = computed(() => {- if (!isCustomAgent.value) return null;- return selectedAgent.value?.config?.model_id || null;+ if (!hasAgentConfig.value) return null;+ return currentAgentConfig.value?.model_id || null;});// 模型选择是否被智能体锁定const isModelLockedByAgent = computed(() => {- return isCustomAgent.value && !!agentModelId.value;+ return hasAgentConfig.value && !!agentModelId.value;});// Mention related state@@ -566,8 +578,8 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>// 获取可选的知识库列表let availableKbs = knowledgeBases.value;- // 如果是自定义智能体,根据 kb_selection_mode 过滤- if (isCustomAgent.value) {+ // 如果智能体有配置,根据 kb_selection_mode 过滤+ if (hasAgentConfig.value) {const kbMode = agentKBSelectionMode.value;if (kbMode === 'none') {// 不使用知识库,不显示任何知识库@@ -596,7 +608,7 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>// Fetch Files from API// 如果智能体禁用了知识库,也不显示文件let fileItems: any[] = [];- const shouldLoadFiles = !isCustomAgent.value || agentKBSelectionMode.value !== 'none';+ const shouldLoadFiles = !hasAgentConfig.value || agentKBSelectionMode.value !== 'none';if (shouldLoadFiles) {mentionLoading.value = true;@@ -606,8 +618,8 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>if (res.data && Array.isArray(res.data)) {let files = res.data;- // 如果是自定义智能体且 kb_selection_mode === 'selected',只显示指定知识库中的文件- if (isCustomAgent.value && agentKBSelectionMode.value === 'selected') {+ // 如果智能体配置了 kb_selection_mode === 'selected',只显示指定知识库中的文件+ if (hasAgentConfig.value && agentKBSelectionMode.value === 'selected') {const configuredKbIds = agentKnowledgeBases.value;files = files.filter((f: any) => configuredKbIds.includes(f.knowledge_base_id));}@@ -1136,18 +1148,24 @@ const toggleAgentModeSelector = () => {}}-const selectAgentMode = (mode: 'normal' | 'agent') => {- if (mode === 'agent' && !settingsStore.isAgentReady) {- toggleAgentMode();- showAgentModeSelector.value = false;- return;+const selectAgentMode = (mode: 'quick-answer' | 'smart-reasoning') => {+ const builtinAgentId = mode === 'smart-reasoning' ? BUILTIN_SMART_REASONING_ID : BUILTIN_QUICK_ANSWER_ID;+ const builtinAgent = agents.value.find(a => a.id === builtinAgentId);++ if (builtinAgent) {+ const notReadyReasons = getBuiltinAgentNotReadyReasons(builtinAgent, mode === 'smart-reasoning');+ if (notReadyReasons.length > 0) {+ showBuiltinAgentNotReadyMessage(mode, notReadyReasons);+ showAgentModeSelector.value = false;+ return;+ }}- const shouldEnableAgent = mode === 'agent';+ const shouldEnableAgent = mode === 'smart-reasoning';if (shouldEnableAgent !== isAgentEnabled.value) {settingsStore.toggleAgent(shouldEnableAgent);// 同时更新选中的智能体- settingsStore.selectAgent(shouldEnableAgent ? 'builtin-agent' : 'builtin-normal');+ settingsStore.selectAgent(shouldEnableAgent ? BUILTIN_SMART_REASONING_ID : BUILTIN_QUICK_ANSWER_ID);MessagePlugin.success(shouldEnableAgent ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff'));}showAgentModeSelector.value = false;@@ -1155,21 +1173,36 @@ const selectAgentMode = (mode: 'normal' | 'agent') => {// 选择智能体(新版)const handleSelectAgent = (agent: CustomAgent) => {- selectedAgentId.value = agent.id;-- // 根据智能体类型切换 Agent 模式- const isAgentType = agent.type === 'agent' || (agent.type === 'custom' && (agent.config?.max_iterations ?? 0) > 1);+ // 根据智能体的 agent_mode 判断是否为 Agent 模式+ const isAgentType = agent.config?.agent_mode === 'smart-reasoning';++ // 内置智能体检查 - 从实际的智能体配置来判断+ if (agent.is_builtin) {+ // 从 agents 列表中获取实际的内置智能体数据+ const builtinAgent = agents.value.find(a => a.id === agent.id);+ if (builtinAgent) {+ const notReadyReasons = getBuiltinAgentNotReadyReasons(builtinAgent, isAgentType);+ if (notReadyReasons.length > 0) {+ showBuiltinAgentNotReadyMessage(isAgentType ? 'smart-reasoning' : 'quick-answer', notReadyReasons);+ return;+ }+ }+ }- if (isAgentType && !settingsStore.isAgentReady) {- // Agent 模式未就绪,显示提示- toggleAgentMode();- return;+ // 自定义智能体检查+ if (!agent.is_builtin) {+ const notReadyReasons = getCustomAgentNotReadyReasons(agent);+ if (notReadyReasons.length > 0) {+ showCustomAgentNotReadyMessage(agent, notReadyReasons);+ return;+ }}+ selectedAgentId.value = agent.id;settingsStore.toggleAgent(!!isAgentType);// 如果是自定义智能体,同步网络搜索状态和模型- if (!agent.is_builtin && agent.type === 'custom') {+ if (!agent.is_builtin) {const agentWebSearch = agent.config?.web_search_enabled;if (agentWebSearch !== undefined) {// 智能体配置了网络搜索设置,同步到 store@@ -1250,75 +1283,125 @@ const handleGoToWebSearchSettings = () => {}};-const handleGoToAgentSettings = () => {- // 使用 uiStore 打开设置并跳转到 agent 部分- uiStore.openSettings('agent');- // 如果当前不在设置页面,导航到设置页面- if (route.path !== '/platform/settings') {- router.push('/platform/settings');+const handleGoToAgentSettings = (section?: string) => {+ // 跳转到智能体列表页并打开编辑弹窗+ if (selectedAgent.value && !selectedAgent.value.is_builtin) {+ const query: Record<string, string> = { edit: selectedAgent.value.id };+ if (section) {+ query.section = section;+ }+ router.push({ path: '/platform/agents', query });+ } else {+ router.push('/platform/agents');}-}+};-// 获取 Agent 不就绪的原因-const getAgentNotReadyReasons = (): string[] => {+// 获取内置智能体不就绪的原因+const getBuiltinAgentNotReadyReasons = (agent: CustomAgent, isAgentMode: boolean): string[] => {const reasons: string[] = []- const config = settingsStore.agentConfig || { allowedTools: [] }- const models = settingsStore.conversationModels || { summaryModelId: '', rerankModelId: '' }+ const config = agent.config || {}- if (!config.allowedTools || config.allowedTools.length === 0) {- reasons.push(t('input.agentMissingAllowedTools'))+ // 检查对话模型(Summary Model)+ if (!config.model_id || config.model_id.trim() === '') {+ reasons.push(t('input.customAgentMissingSummaryModel'))}- if (!models.summaryModelId || models.summaryModelId.trim() === '') {- reasons.push(t('input.agentMissingSummaryModel'))++ // 检查重排模型(Rerank Model)- 如果使用知识库则需要+ if (config.kb_selection_mode !== 'none') {+ if (!config.rerank_model_id || config.rerank_model_id.trim() === '') {+ reasons.push(t('input.customAgentMissingRerankModel'))+ }}- if (!models.rerankModelId || models.rerankModelId.trim() === '') {- reasons.push(t('input.agentMissingRerankModel'))++ // Agent 模式还需要检查允许的工具+ if (isAgentMode) {+ if (!config.allowed_tools || config.allowed_tools.length === 0) {+ reasons.push(t('input.agentMissingAllowedTools'))+ }}return reasons}-const toggleAgentMode = () => {- // 如果要启用 Agent,先检查是否就绪- // 注意:isAgentReady 是从 store 中计算的,需要确保 store 中的配置是最新的- if (!isAgentEnabled.value) {- // 尝试启用 Agent,先检查是否就绪- const agentReady = settingsStore.isAgentReady- if (!agentReady) {- const reasons = getAgentNotReadyReasons()- const reasonsText = reasons.join('、')-- // 创建带跳转链接的自定义消息- const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 8px; max-width: 320px;' }, [- h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.messages.agentNotReadyDetail', { reasons: reasonsText })),- h('a', {- href: '#',- onClick: (e: Event) => {- e.preventDefault();- handleGoToAgentSettings();- },- style: 'color: #07C05F; text-decoration: none; font-weight: 500; cursor: pointer; align-self: flex-start;',- onMouseenter: (e: Event) => {- (e.target as HTMLElement).style.textDecoration = 'underline';- },- onMouseleave: (e: Event) => {- (e.target as HTMLElement).style.textDecoration = 'none';- }- }, t('input.goToSettings'))- ]);-- MessagePlugin.warning({- content: () => messageContent,- duration: 5000- });- return+// 获取自定义智能体不就绪的原因(非 Agent 模式,快速回答)+const getCustomAgentNotReadyReasons = (agent: CustomAgent): string[] => {+ const reasons: string[] = []+ const config = agent.config || {}++ // 检查对话模型(Summary Model)+ if (!config.model_id || config.model_id.trim() === '') {+ reasons.push(t('input.customAgentMissingSummaryModel'))+ }+ // 检查重排模型(Rerank Model)- 如果使用知识库则需要+ if (config.kb_selection_mode !== 'none') {+ if (!config.rerank_model_id || config.rerank_model_id.trim() === '') {+ reasons.push(t('input.customAgentMissingRerankModel'))}}- // 正常切换 Agent 状态- settingsStore.toggleAgent(!isAgentEnabled.value);- const message = isAgentEnabled.value ? t('input.messages.agentEnabled') : t('input.messages.agentDisabled');- MessagePlugin.success(message);+ return reasons+}++// 显示自定义智能体未就绪的消息+const showCustomAgentNotReadyMessage = (agent: CustomAgent, reasons: string[]) => {+ const reasonsText = reasons.join('、')++ const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 8px; max-width: 320px;' }, [+ h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.customAgentNotReadyDetail', { reasons: reasonsText })),+ h('a', {+ href: '#',+ onClick: (e: Event) => {+ e.preventDefault();+ // 跳转到智能体编辑页面+ router.push(`/platform/agents?edit=${agent.id}`);+ },+ style: 'color: #07C05F; text-decoration: none; font-weight: 500; cursor: pointer; align-self: flex-start;',+ onMouseenter: (e: Event) => {+ (e.target as HTMLElement).style.textDecoration = 'underline';+ },+ onMouseleave: (e: Event) => {+ (e.target as HTMLElement).style.textDecoration = 'none';+ }+ }, t('input.goToAgentEditor'))+ ]);++ MessagePlugin.warning({+ content: () => messageContent,+ duration: 5000+ });+}++// 显示内置智能体未就绪的消息+const showBuiltinAgentNotReadyMessage = (mode: 'smart-reasoning' | 'quick-answer', reasons: string[]) => {+ const agentName = mode === 'smart-reasoning'+ ? t('input.builtinAgentSettingName')+ : t('input.builtinNormalSettingName');+ const builtinAgentId = mode === 'smart-reasoning' ? BUILTIN_SMART_REASONING_ID : BUILTIN_QUICK_ANSWER_ID;+ const reasonsText = reasons.join('、')++ const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 8px; max-width: 320px;' }, [+ h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.builtinAgentNotReadyDetail', { agentName, reasons: reasonsText })),+ h('a', {+ href: '#',+ onClick: (e: Event) => {+ e.preventDefault();+ // 跳转到内置智能体编辑页面+ router.push(`/platform/agents?edit=${builtinAgentId}`);+ },+ style: 'color: #07C05F; text-decoration: none; font-weight: 500; cursor: pointer; align-self: flex-start;',+ onMouseenter: (e: Event) => {+ (e.target as HTMLElement).style.textDecoration = 'underline';+ },+ onMouseleave: (e: Event) => {+ (e.target as HTMLElement).style.textDecoration = 'none';+ }+ }, t('input.goToAgentEditor'))+ ]);++ MessagePlugin.warning({+ content: () => messageContent,+ duration: 5000+ });}const toggleWebSearch = () => {@@ -1332,12 +1415,6 @@ const toggleWebSearch = () => {MessagePlugin.warning(t('input.webSearchDisabledByAgent'));return;}-- // 如果智能体强制启用了网络搜索,不允许关闭- if (isWebSearchForcedByAgent.value) {- MessagePlugin.warning(t('input.webSearchForcedByAgent'));- return;- }if (!isWebSearchConfigured.value) {const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 6px; max-width: 280px;' }, [@@ -1472,8 +1549,9 @@ onBeforeRouteUpdate((to, from, next) => {ref="agentModeButtonRef"class="control-btn agent-mode-btn":class="{- 'active': isAgentEnabled,- 'agent-active': isAgentEnabled+ 'is-normal': !isCustomAgent && !isAgentEnabled,+ 'is-agent': !isCustomAgent && isAgentEnabled,+ 'is-custom': isCustomAgent}"@click.stop="toggleAgentModeSelector">@@ -1502,12 +1580,14 @@ onBeforeRouteUpdate((to, from, next) => {/><!-- WebSearch 开关按钮 -->- <t-tooltip placement="top">+ <t-tooltip placement="top" theme="light" :popupProps="{ overlayClassName: 'input-field-tooltip' }"><template #content>- <span v-if="isWebSearchDisabledByAgent">{{ $t('input.webSearchDisabledByAgent') }}</span>- <span v-else-if="isWebSearchForcedByAgent">{{ $t('input.webSearchForcedByAgent') }}</span>+ <div v-if="isWebSearchDisabledByAgent" class="tooltip-with-link">+ <span>{{ $t('input.webSearchDisabledByAgent') }}</span>+ <a href="#" @click.prevent="handleGoToAgentSettings('websearch')">{{ $t('input.goToAgentSettings') }}</a>+ </div><span v-else-if="isWebSearchConfigured">{{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }}</span>- <div v-else class="websearch-tooltip-disabled">+ <div v-else class="tooltip-with-link"><span>{{ $t('input.webSearch.notConfigured') }}</span><a href="#" @click.prevent="handleGoToWebSearchSettings">{{ $t('input.goToSettings') }}</a></div>@@ -1515,9 +1595,8 @@ onBeforeRouteUpdate((to, from, next) => {<divclass="control-btn websearch-btn":class="{- 'active': (isWebSearchEnabled && isWebSearchConfigured) || isWebSearchForcedByAgent,- 'disabled': !isWebSearchConfigured,- 'agent-controlled': isWebSearchDisabledByAgent || isWebSearchForcedByAgent+ 'active': isWebSearchEnabled && isWebSearchConfigured,+ 'disabled': !isWebSearchConfigured || isWebSearchDisabledByAgent}"@click.stop="toggleWebSearch">@@ -1528,7 +1607,7 @@ onBeforeRouteUpdate((to, from, next) => {fill="none"xmlns="http://www.w3.org/2000/svg"class="control-icon websearch-icon"- :class="{ 'active': (isWebSearchEnabled && isWebSearchConfigured) || isWebSearchForcedByAgent }"+ :class="{ 'active': isWebSearchEnabled && isWebSearchConfigured }"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none"/><path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>@@ -1540,13 +1619,20 @@ onBeforeRouteUpdate((to, from, next) => {</t-tooltip><!-- @ 知识库/文件选择按钮 -->- <t-tooltip :content="isKnowledgeBaseDisabledByAgent ? $t('input.kbDisabledByAgent') : (isKnowledgeBaseLockedByAgent ? $t('input.kbLockedByAgent') : (allSelectedItems.length > 0 ? $t('input.knowledgeBaseWithCount', { count: allSelectedItems.length }) : $t('input.knowledgeBase')))">+ <t-tooltip placement="top" theme="light" :popupProps="{ overlayClassName: 'input-field-tooltip' }">+ <template #content>+ <div v-if="isKnowledgeBaseDisabledByAgent" class="tooltip-with-link">+ <span>{{ $t('input.kbDisabledByAgent') }}</span>+ <a href="#" @click.prevent="handleGoToAgentSettings('knowledge')">{{ $t('input.goToAgentSettings') }}</a>+ </div>+ <span v-else>{{ allSelectedItems.length > 0 ? $t('input.knowledgeBaseWithCount', { count: allSelectedItems.length }) : $t('input.knowledgeBase') }}</span>+ </template><divref="atButtonRef"class="control-btn kb-btn":class="{'active': allSelectedItems.length > 0,- 'agent-controlled': isKnowledgeBaseLockedByAgent+ 'disabled': isKnowledgeBaseDisabledByAgent}"@click.stop@mousedown.prevent="triggerMention"@@ -1882,46 +1968,63 @@ const getImgSrc = (url: string) => {transition: background 0.12s, border-color 0.12s;position: relative;- &.active,- &.agent-active {- background: linear-gradient(135deg, rgba(16, 185, 129, 0.15) 0%, rgba(16, 185, 129, 0.1) 100%);- border-color: rgba(16, 185, 129, 0.4);- box-shadow: 0 2px 6px rgba(16, 185, 129, 0.12);+ // 内置普通模式 - 绿色+ &.is-normal {+ background: linear-gradient(135deg, rgba(16, 185, 129, 0.12) 0%, rgba(16, 185, 129, 0.08) 100%);+ border-color: rgba(16, 185, 129, 0.35);.agent-mode-text {- color: #07C05F;+ color: #059669;font-weight: 600;}- .agent-icon {- filter: brightness(0) saturate(100%) invert(58%) sepia(87%) saturate(1234%) hue-rotate(95deg) brightness(98%) contrast(89%);+ .dropdown-arrow {+ color: #059669;+ }++ &:hover {+ background: linear-gradient(135deg, rgba(16, 185, 129, 0.18) 0%, rgba(16, 185, 129, 0.12) 100%);+ border-color: rgba(16, 185, 129, 0.5);+ }+ }++ // 内置 Agent 模式 - 紫色+ &.is-agent {+ background: linear-gradient(135deg, rgba(124, 77, 255, 0.12) 0%, rgba(124, 77, 255, 0.08) 100%);+ border-color: rgba(124, 77, 255, 0.35);++ .agent-mode-text {+ color: #7c4dff;+ font-weight: 600;}.dropdown-arrow {- color: #07C05F;+ color: #7c4dff;}&:hover {- background: linear-gradient(135deg, rgba(16, 185, 129, 0.2) 0%, rgba(16, 185, 129, 0.15) 100%);- border-color: rgba(16, 185, 129, 0.6);+ background: linear-gradient(135deg, rgba(124, 77, 255, 0.18) 0%, rgba(124, 77, 255, 0.12) 100%);+ border-color: rgba(124, 77, 255, 0.5);}}- &:not(.agent-active) {- background: var(--td-bg-color-container, #fff);- border-color: var(--td-component-border, #e0e0e0);+ // 自定义智能体 - 蓝色+ &.is-custom {+ background: linear-gradient(135deg, rgba(59, 130, 246, 0.12) 0%, rgba(59, 130, 246, 0.08) 100%);+ border-color: rgba(59, 130, 246, 0.35);.agent-mode-text {- color: var(--td-text-color-secondary, #666);+ color: #3b82f6;+ font-weight: 600;}- .normal-mode-icon {- color: var(--td-text-color-secondary, #666);+ .dropdown-arrow {+ color: #3b82f6;}&:hover {- background: var(--td-bg-color-container-hover, #fff);- border-color: var(--td-component-stroke, #b0b0b0);+ background: linear-gradient(135deg, rgba(59, 130, 246, 0.18) 0%, rgba(59, 130, 246, 0.12) 100%);+ border-color: rgba(59, 130, 246, 0.5);}}}@@ -1932,6 +2035,26 @@ const getImgSrc = (url: string) => {flex-shrink: 0;}+.agent-btn-icon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 20px;+ height: 20px;+ border-radius: 5px;+ flex-shrink: 0;++ &.normal {+ background: rgba(7, 192, 95, 0.12);+ color: #059669;+ }++ &.agent {+ background: rgba(124, 77, 255, 0.12);+ color: #7c4dff;+ }+}+.agent-mode-text {font-size: 13px;color: var(--td-text-color-secondary, #666);@@ -2052,22 +2175,29 @@ const getImgSrc = (url: string) => {}}-:global(.websearch-tooltip-disabled) {+:global(.input-field-tooltip) {+ .t-popup__content {+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);+ border: 1px solid var(--td-component-border, #e7e7e7);+ }+}++:global(.tooltip-with-link) {display: flex;flex-direction: column;- gap: 4px;+ gap: 6px;max-width: 220px;font-size: 12px;- color: var(--td-text-color-secondary, #666);+ color: var(--td-text-color-primary, #333);}-:global(.websearch-tooltip-disabled a) {+:global(.tooltip-with-link a) {color: #07C05F;font-weight: 500;text-decoration: none;}-:global(.websearch-tooltip-disabled a:hover) {+:global(.tooltip-with-link a:hover) {text-decoration: underline;}diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vueindex 969b6fe6b..a835c0d89 100644--- a/frontend/src/components/UserMenu.vue+++ b/frontend/src/components/UserMenu.vue@@ -24,10 +24,6 @@<t-icon name="server" class="menu-icon" /><span>Ollama</span></div>- <div class="menu-item" @click="handleQuickNav('agent')">- <t-icon name="chat" class="menu-icon" />- <span>{{ $t('settings.conversationStrategy') }}</span>- </div><div class="menu-item" @click="handleQuickNav('websearch')"><svgwidth="16"diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex fb116d5ed..a4b6b5c38 100644--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -221,6 +221,7 @@ export default {agent: 'Multi-step thinking, deep analysis for complex questions',modelSpecified: 'Model specified',kbCount: '{count} knowledge base(s) specified',+ kbAll: 'Access to all knowledge bases',kbDisabled: 'Knowledge base disabled',rerankSpecified: 'ReRank model specified',webSearchOn: 'Web search enabled',@@ -258,6 +259,8 @@ export default {deleteFailed: 'Delete failed',saveFailed: 'Save failed',builtinReadonly: 'Built-in agents cannot be edited',+ copied: 'Agent copied successfully',+ copyFailed: 'Copy failed',},editor: {createTitle: 'Create Agent',@@ -313,9 +316,6 @@ export default {noKnowledgeBase: 'No Knowledge Base',noKnowledgeBaseDesc: 'Pure model conversation, no knowledge retrieval',selectKnowledgeBases: 'Select Knowledge Bases',- allowUserKBSelection: 'Allow User KB Selection',- allowUserKBSelectionDescAll: 'When enabled, users can select from all knowledge bases during conversation; when disabled, all knowledge bases will be used automatically',- allowUserKBSelectionDescSelected: 'When enabled, users can select from associated knowledge bases during conversation; when disabled, all associated knowledge bases will be used automatically',rerankModel: 'ReRank Model',rerankModelDesc: 'Used to rerank knowledge base retrieval results for better accuracy',rerankModelPlaceholder: 'Select ReRank Model',@@ -759,6 +759,7 @@ export default {save: 'Save',delete: 'Delete',edit: 'Edit',+ copy: 'Copy',default: 'Default',create: 'Create',search: 'Search',@@ -918,6 +919,14 @@ export default {agentMissingSummaryModel: 'Chat Model (Summary Model)',agentMissingRerankModel: 'Rerank Model',goToSettings: 'Go to settings →',+ customAgentNotReadyTooltip: 'Agent is not ready. Please finish configuration first.',+ customAgentNotReadyDetail: 'Agent is not ready. Please configure the following: {reasons}',+ customAgentMissingSummaryModel: 'Chat Model (Summary Model)',+ customAgentMissingRerankModel: 'Rerank Model',+ goToAgentEditor: 'Go to configure →',+ builtinAgentNotReadyDetail: 'Built-in agent "{agentName}" is not ready. Please configure: {reasons}',+ builtinAgentSettingName: 'Intelligent Reasoning',+ builtinNormalSettingName: 'Quick Q&A',webSearch: {toggleOn: 'Enable Web Search',toggleOff: 'Disable Web Search',@@ -936,8 +945,8 @@ export default {enterContent: 'Please enter content first!',selectKnowledge: 'Please select a knowledge base first!',replying: 'Currently replying, please try again later!',- agentSwitchedOn: 'Switched to Agent Mode',- agentSwitchedOff: 'Switched to Normal Mode',+ agentSwitchedOn: 'Switched to Intelligent Reasoning',+ agentSwitchedOff: 'Switched to Quick Q&A',agentSelected: 'Selected agent "{name}"',agentEnabled: 'Agent Mode enabled',agentDisabled: 'Agent Mode disabled',@@ -959,7 +968,8 @@ export default {kbDisabledByAgent: 'Knowledge base is disabled by the current agent',cannotRemoveAgentKb: 'Cannot remove knowledge base configured by agent',agentConfiguredKb: 'Configured by agent, cannot be removed',- modelLockedByAgent: 'Model selection is locked by the current agent'+ modelLockedByAgent: 'Model selection is locked by the current agent',+ goToAgentSettings: 'Go to agent settings'},createChat: {title: 'Knowledge-base Q&A - AI Assistant',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex fe6b30ead..4ef52ba0e 100644--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -689,6 +689,7 @@ export default {save: "保存",delete: "删除",edit: "编辑",+ copy: "复制",default: "默认",create: "创建",search: "搜索",@@ -750,6 +751,7 @@ export default {agent: "多步思考,深度分析复杂问题",modelSpecified: "指定模型",kbCount: "指定 {count} 个知识库",+ kbAll: "可访问全部知识库",kbDisabled: "禁用知识库",rerankSpecified: "指定 ReRank 模型",webSearchOn: "启用网络搜索",@@ -787,6 +789,8 @@ export default {deleteFailed: "删除失败",saveFailed: "保存失败",builtinReadonly: "内置智能体不可编辑",+ copied: "智能体复制成功",+ copyFailed: "复制失败",},editor: {createTitle: "创建智能体",@@ -842,9 +846,6 @@ export default {noKnowledgeBase: "不使用知识库",noKnowledgeBaseDesc: "纯模型对话,不检索知识库",selectKnowledgeBases: "选择知识库",- allowUserKBSelection: "允许用户选择知识库",- allowUserKBSelectionDescAll: "开启后,用户可以在对话时从全部知识库中选择;关闭后,将自动使用全部知识库",- allowUserKBSelectionDescSelected: "开启后,用户可以在对话时从关联的知识库中选择;关闭后,将自动使用全部关联的知识库",rerankModel: "ReRank 模型",rerankModelDesc: "用于对知识库检索结果进行重排序,提高回答准确性",rerankModelPlaceholder: "请选择 ReRank 模型",@@ -1598,6 +1599,14 @@ export default {agentMissingSummaryModel: "对话模型(Summary Model)",agentMissingRerankModel: "重排模型(Rerank Model)",goToSettings: "前往设置 →",+ customAgentNotReadyTooltip: "智能体未就绪,请先完成配置",+ customAgentNotReadyDetail: "智能体未就绪,需要配置以下内容:{reasons}",+ customAgentMissingSummaryModel: "对话模型(Summary Model)",+ customAgentMissingRerankModel: "重排模型(Rerank Model)",+ goToAgentEditor: "前往配置 →",+ builtinAgentNotReadyDetail: "内置智能体「{agentName}」未就绪,需要配置以下内容:{reasons}",+ builtinAgentSettingName: "智能推理",+ builtinNormalSettingName: "快速问答",webSearch: {toggleOn: "开启网络搜索",toggleOff: "关闭网络搜索",@@ -1616,8 +1625,8 @@ export default {enterContent: "请先输入内容!",selectKnowledge: "请先选择知识库!",replying: "正在回复中,请稍后再试!",- agentSwitchedOn: "已切换到 Agent 模式",- agentSwitchedOff: "已切换到普通模式",+ agentSwitchedOn: "已切换到智能推理",+ agentSwitchedOff: "已切换到快速问答",agentSelected: "已选择智能体「{name}」",agentEnabled: "Agent 模式已启用",agentDisabled: "Agent 模式已禁用",@@ -1639,6 +1648,7 @@ export default {cannotRemoveAgentKb: "智能体配置的知识库无法移除",agentConfiguredKb: "由智能体配置,不可删除",modelLockedByAgent: "当前智能体已锁定模型配置",+ goToAgentSettings: "去设置智能体",},agentSettings: {title: "Agent 配置",diff --git a/frontend/src/stores/settings.ts b/frontend/src/stores/settings.tsindex 5cae4a068..47d819ab3 100644--- a/frontend/src/stores/settings.ts+++ b/frontend/src/stores/settings.ts@@ -1,4 +1,5 @@import { defineStore } from "pinia";+import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent";// 定义设置接口interface Settings {@@ -89,7 +90,7 @@ const defaultSettings: Settings = {rerankModelId: "",selectedChatModelId: "", // 用户当前选择的对话模型ID},- selectedAgentId: "builtin-normal", // 默认选中普通模式+ selectedAgentId: BUILTIN_QUICK_ANSWER_ID, // 默认选中快速问答模式};export const useSettingsStore = defineStore("settings", {@@ -114,6 +115,16 @@ export const useSettingsStore = defineStore("settings", {)},+ // 普通模式(快速回答)是否就绪+ // 需要满足:1) 设置了对话模型 2) 设置了重排模型+ isNormalModeReady: (state) => {+ const models = state.settings.conversationModels || defaultSettings.conversationModels+ return Boolean(+ models.summaryModelId && models.summaryModelId.trim() !== '' &&+ models.rerankModelId && models.rerankModelId.trim() !== ''+ )+ },+// 获取 Agent 配置agentConfig: (state) => state.settings.agentConfig || defaultSettings.agentConfig,@@ -126,7 +137,7 @@ export const useSettingsStore = defineStore("settings", {isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,// 当前选中的智能体ID- selectedAgentId: (state) => state.settings.selectedAgentId || "builtin-normal",+ selectedAgentId: (state) => state.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,},actions: {@@ -309,9 +320,9 @@ export const useSettingsStore = defineStore("settings", {selectAgent(agentId: string) {this.settings.selectedAgentId = agentId;// 根据智能体类型自动切换 Agent 模式- if (agentId === "builtin-normal") {+ if (agentId === BUILTIN_QUICK_ANSWER_ID) {this.settings.isAgentEnabled = false;- } else if (agentId === "builtin-agent") {+ } else if (agentId === BUILTIN_SMART_REASONING_ID) {this.settings.isAgentEnabled = true;}// 自定义智能体需要根据其配置来决定@@ -320,7 +331,7 @@ export const useSettingsStore = defineStore("settings", {// 获取选中的智能体IDgetSelectedAgentId(): string {- return this.settings.selectedAgentId || "builtin-normal";+ return this.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID;},},});diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vueindex 286c3778f..327b6c376 100644--- a/frontend/src/views/agent/AgentEditorModal.vue+++ b/frontend/src/views/agent/AgentEditorModal.vue@@ -50,14 +50,14 @@<div class="setting-row"><div class="setting-info"><label>{{ $t('agent.editor.mode') }} <span class="required">*</span></label>- <p class="desc">{{ agentMode === 'agent' ? $t('agent.editor.agentDesc') : $t('agent.editor.normalDesc') }}</p>+ <p class="desc">{{ agentMode === 'smart-reasoning' ? $t('agent.editor.agentDesc') : $t('agent.editor.normalDesc') }}</p></div><div class="setting-control"><t-radio-group v-model="agentMode" :disabled="isBuiltinAgent">- <t-radio-button value="normal">+ <t-radio-button value="quick-answer">{{ $t('agent.type.normal') }}</t-radio-button>- <t-radio-button value="agent">+ <t-radio-button value="smart-reasoning">{{ $t('agent.type.agent') }}</t-radio-button></t-radio-group>@@ -72,7 +72,12 @@</div><div class="setting-control"><div class="name-input-wrapper">- <AgentAvatar :name="formData.name || '?'" size="large" />+ <!-- 内置智能体使用简洁图标 -->+ <div v-if="isBuiltinAgent" class="builtin-avatar" :class="isAgentMode ? 'agent' : 'normal'">+ <t-icon :name="isAgentMode ? 'control-platform' : 'chat'" size="24px" />+ </div>+ <!-- 自定义智能体使用 AgentAvatar -->+ <AgentAvatar v-else :name="formData.name || '?'" size="large" /><t-inputv-model="formData.name":placeholder="$t('agent.editor.namePlaceholder')"@@ -104,14 +109,21 @@<div class="setting-info"><label>{{ $t('agent.editor.systemPrompt') }} <span v-if="!isBuiltinAgent" class="required">*</span></label><p class="desc">自定义系统提示词,定义智能体的行为和角色{{ isBuiltinAgent ? '(留空则使用系统默认)' : '' }}</p>- <div class="placeholder-hint">- <p class="hint-title">{{ $t('agent.editor.availablePlaceholders') }}</p>- <ul class="placeholder-list">- <li v-for="placeholder in availablePlaceholders" :key="placeholder.name">- <code v-html="`{{${placeholder.name}}}`"></code> - {{ placeholder.description }}- </li>- </ul>- <p class="hint-tip">{{ $t('agent.editor.placeholderHint') }}</p>+ <div class="placeholder-tags">+ <span class="placeholder-label">可用变量:</span>+ <t-tooltip+ v-for="placeholder in availablePlaceholders"+ :key="placeholder.name"+ :content="placeholder.description + '(点击插入)'"+ placement="top"+ >+ <span+ class="placeholder-tag"+ @click="handlePlaceholderClick('system', placeholder.name)"+ v-text="'{{' + placeholder.name + '}}'"+ ></span>+ </t-tooltip>+ <span class="placeholder-hint" v-text="'(点击插入,或输入 {{ 唤起列表)'"></span></div></div><div class="setting-control setting-control-full" style="position: relative;">@@ -123,7 +135,7 @@<t-textarearef="promptTextareaRef"v-model="formData.config.system_prompt"- :placeholder="systemPromptPlaceholder"+ :placeholder="systemPromptWebDisabledPlaceholder":autosize="{ minRows: 10, maxRows: 25 }"@input="handlePromptInput"class="system-prompt-textarea"@@ -140,7 +152,7 @@<div class="textarea-with-template"><t-textareav-model="formData.config.system_prompt_web_enabled"- :placeholder="$t('agent.editor.systemPromptWebEnabledPlaceholder') || '网络搜索开启时使用的系统提示词'"+ :placeholder="systemPromptWebEnabledPlaceholder":autosize="{ minRows: 10, maxRows: 25 }"class="system-prompt-textarea"/>@@ -184,7 +196,7 @@:key="placeholder.name"class="placeholder-item":class="{ active: selectedPlaceholderIndex === index }"- @mousedown.prevent="insertPlaceholder(placeholder.name)"+ @mousedown.prevent="insertPlaceholder(placeholder.name, true)"@mouseenter="selectedPlaceholderIndex = index"><div class="placeholder-name">@@ -203,13 +215,21 @@<div class="setting-info"><label>{{ $t('agent.editor.contextTemplate') || '上下文模板' }} <span v-if="!isBuiltinAgent" class="required">*</span></label><p class="desc">定义如何将检索到的内容格式化后传递给模型{{ isBuiltinAgent ? '(留空则使用系统默认)' : '' }}</p>- <div class="placeholder-hint">- <p class="hint-title">{{ $t('agent.editor.availableContextPlaceholders') || '可用占位符' }}</p>- <ul class="placeholder-list">- <li v-for="placeholder in contextTemplatePlaceholders" :key="placeholder.name">- <code v-html="`{{${placeholder.name}}}`"></code> - {{ placeholder.description }}- </li>- </ul>+ <div class="placeholder-tags">+ <span class="placeholder-label">可用变量:</span>+ <t-tooltip+ v-for="placeholder in contextTemplatePlaceholders"+ :key="placeholder.name"+ :content="placeholder.description + '(点击插入)'"+ placement="top"+ >+ <span+ class="placeholder-tag"+ @click="handlePlaceholderClick('context', placeholder.name)"+ v-text="'{{' + placeholder.name + '}}'"+ ></span>+ </t-tooltip>+ <span class="placeholder-hint" v-text="'(点击插入,或输入 {{ 唤起列表)'"></span></div></div><div class="setting-control setting-control-full" style="position: relative;">@@ -242,7 +262,7 @@:key="placeholder.name"class="placeholder-item":class="{ active: selectedContextPlaceholderIndex === index }"- @mousedown.prevent="insertContextPlaceholder(placeholder.name)"+ @mousedown.prevent="insertContextPlaceholder(placeholder.name, true)"@mouseenter="selectedContextPlaceholderIndex = index"><div class="placeholder-name">@@ -274,14 +294,14 @@<p class="desc">选择智能体使用的大语言模型</p></div><div class="setting-control">- <t-select v-model="formData.config.model_id" :placeholder="$t('agent.editor.modelPlaceholder')" filterable>- <t-option- v-for="model in modelOptions"- :key="model.value"- :value="model.value"- :label="model.label"- />- </t-select>+ <ModelSelector+ model-type="KnowledgeQA"+ :selected-model-id="formData.config.model_id"+ :all-models="allModels"+ @update:selected-model-id="(val: string) => formData.config.model_id = val"+ @add-model="handleAddModel('llm')"+ :placeholder="$t('agent.editor.modelPlaceholder')"+ /></div></div>@@ -299,8 +319,8 @@</div></div>- <!-- 最大生成Token数 -->- <div class="setting-row">+ <!-- 最大生成Token数(仅普通模式) -->+ <div v-if="!isAgentMode" class="setting-row"><div class="setting-info"><label>{{ $t('agent.editor.maxCompletionTokens') || '最大生成Token数' }}</label><p class="desc">模型生成回复的最大Token数量</p>@@ -358,13 +378,31 @@<div class="setting-info"><label>{{ $t('agent.editor.rewritePromptSystem') || '改写系统提示词' }}</label><p class="desc">用于问题改写的系统提示词(留空使用默认)</p>+ <div class="placeholder-tags" v-if="rewriteSystemPlaceholders.length > 0">+ <span class="placeholder-label">可用变量:</span>+ <t-tooltip+ v-for="placeholder in rewriteSystemPlaceholders"+ :key="placeholder.name"+ :content="placeholder.description + '(点击插入)'"+ placement="top"+ >+ <span+ class="placeholder-tag"+ @click="handlePlaceholderClick('rewriteSystem', placeholder.name)"+ v-text="'{{' + placeholder.name + '}}'"+ ></span>+ </t-tooltip>+ <span class="placeholder-hint" v-text="'(点击插入,或输入 {{ 唤起列表)'"></span>+ </div></div>- <div class="setting-control setting-control-full">+ <div class="setting-control setting-control-full" style="position: relative;"><div class="textarea-with-template"><t-textarea+ ref="rewriteSystemTextareaRef"v-model="formData.config.rewrite_prompt_system":placeholder="defaultRewritePromptSystem || $t('agent.editor.rewritePromptSystemPlaceholder') || '留空使用系统默认提示词'":autosize="{ minRows: 4, maxRows: 10 }"+ @input="handleRewriteSystemInput"/><PromptTemplateSelectortype="rewriteSystem"@@ -372,6 +410,29 @@@select="handleRewriteSystemTemplateSelect"/></div>+ <Teleport to="body">+ <div+ v-if="rewriteSystemPopup.show && filteredRewriteSystemPlaceholders.length > 0"+ class="placeholder-popup-wrapper"+ :style="rewriteSystemPopup.style"+ >+ <div class="placeholder-popup">+ <div+ v-for="(placeholder, index) in filteredRewriteSystemPlaceholders"+ :key="placeholder.name"+ class="placeholder-item"+ :class="{ active: rewriteSystemPopup.selectedIndex === index }"+ @mousedown.prevent="insertGenericPlaceholder('rewriteSystem', placeholder.name, true)"+ @mouseenter="rewriteSystemPopup.selectedIndex = index"+ >+ <div class="placeholder-name">+ <code v-html="`{{${placeholder.name}}}`"></code>+ </div>+ <div class="placeholder-desc">{{ placeholder.description }}</div>+ </div>+ </div>+ </div>+ </Teleport></div></div>@@ -380,13 +441,31 @@<div class="setting-info"><label>{{ $t('agent.editor.rewritePromptUser') || '改写用户提示词' }}</label><p class="desc">用于问题改写的用户提示词模板(留空使用默认)</p>+ <div class="placeholder-tags" v-if="rewritePlaceholders.length > 0">+ <span class="placeholder-label">可用变量:</span>+ <t-tooltip+ v-for="placeholder in rewritePlaceholders"+ :key="placeholder.name"+ :content="placeholder.description + '(点击插入)'"+ placement="top"+ >+ <span+ class="placeholder-tag"+ @click="handlePlaceholderClick('rewriteUser', placeholder.name)"+ v-text="'{{' + placeholder.name + '}}'"+ ></span>+ </t-tooltip>+ <span class="placeholder-hint" v-text="'(点击插入,或输入 {{ 唤起列表)'"></span>+ </div></div>- <div class="setting-control setting-control-full">+ <div class="setting-control setting-control-full" style="position: relative;"><div class="textarea-with-template"><t-textarea+ ref="rewriteUserTextareaRef"v-model="formData.config.rewrite_prompt_user":placeholder="defaultRewritePromptUser || $t('agent.editor.rewritePromptUserPlaceholder') || '留空使用系统默认提示词'":autosize="{ minRows: 4, maxRows: 10 }"+ @input="handleRewriteUserInput"/><PromptTemplateSelectortype="rewriteUser"@@ -394,6 +473,29 @@@select="handleRewriteUserTemplateSelect"/></div>+ <Teleport to="body">+ <div+ v-if="rewriteUserPopup.show && filteredRewriteUserPlaceholders.length > 0"+ class="placeholder-popup-wrapper"+ :style="rewriteUserPopup.style"+ >+ <div class="placeholder-popup">+ <div+ v-for="(placeholder, index) in filteredRewriteUserPlaceholders"+ :key="placeholder.name"+ class="placeholder-item"+ :class="{ active: rewriteUserPopup.selectedIndex === index }"+ @mousedown.prevent="insertGenericPlaceholder('rewriteUser', placeholder.name, true)"+ @mouseenter="rewriteUserPopup.selectedIndex = index"+ >+ <div class="placeholder-name">+ <code v-html="`{{${placeholder.name}}}`"></code>+ </div>+ <div class="placeholder-desc">{{ placeholder.description }}</div>+ </div>+ </div>+ </div>+ </Teleport></div></div></div>@@ -442,6 +544,44 @@<t-input-number v-model="formData.config.max_iterations" :min="1" :max="50" theme="column" /></div></div>++ <!-- MCP 服务选择 -->+ <div class="setting-row">+ <div class="setting-info">+ <label>MCP 服务</label>+ <p class="desc">选择 Agent 可以调用的 MCP 服务</p>+ </div>+ <div class="setting-control">+ <t-radio-group v-model="mcpSelectionMode">+ <t-radio-button value="all">全部</t-radio-button>+ <t-radio-button value="selected">指定</t-radio-button>+ <t-radio-button value="none">禁用</t-radio-button>+ </t-radio-group>+ </div>+ </div>++ <!-- 选择指定 MCP 服务 -->+ <div v-if="mcpSelectionMode === 'selected' && mcpOptions.length > 0" class="setting-row">+ <div class="setting-info">+ <label>选择 MCP 服务</label>+ <p class="desc">选择要启用的 MCP 服务</p>+ </div>+ <div class="setting-control">+ <t-select+ v-model="formData.config.mcp_services"+ multiple+ placeholder="选择 MCP 服务"+ filterable+ >+ <t-option+ v-for="mcp in mcpOptions"+ :key="mcp.value"+ :value="mcp.value"+ :label="mcp.label"+ />+ </t-select>+ </div>+ </div></div></div>@@ -491,36 +631,21 @@</div></div>- <!-- 允许用户选择知识库(有知识库能力时显示) -->- <div v-if="kbSelectionMode !== 'none'" class="setting-row">- <div class="setting-info">- <label>{{ $t('agent.editor.allowUserKBSelection') }}</label>- <p class="desc">{{ allowUserKBSelectionDesc }}</p>- </div>- <div class="setting-control">- <t-switch v-model="formData.config.allow_user_kb_selection" />- </div>- </div>-- <!-- ReRank 模型(当配置了知识库或允许用户选择知识库时显示) -->+ <!-- ReRank 模型(当配置了知识库时显示) --><div v-if="needsRerankModel" class="setting-row"><div class="setting-info"><label>{{ $t('agent.editor.rerankModel') }} <span class="required">*</span></label><p class="desc">{{ $t('agent.editor.rerankModelDesc') }}</p></div><div class="setting-control">- <t-select- v-model="formData.config.rerank_model_id"+ <ModelSelector+ model-type="Rerank"+ :selected-model-id="formData.config.rerank_model_id"+ :all-models="allModels"+ @update:selected-model-id="(val: string) => formData.config.rerank_model_id = val"+ @add-model="handleAddModel('rerank')":placeholder="$t('agent.editor.rerankModelPlaceholder')"- filterable- >- <t-option- v-for="model in rerankModelOptions"- :key="model.value"- :value="model.value"- :label="model.label"- />- </t-select>+ /></div></div></div>@@ -695,13 +820,31 @@<div class="setting-info"><label>{{ $t('agent.editor.fallbackPrompt') || '兜底提示词' }}</label><p class="desc">当无法从知识库找到答案时,引导模型生成回复的提示词</p>+ <div class="placeholder-tags" v-if="fallbackPlaceholders.length > 0">+ <span class="placeholder-label">可用变量:</span>+ <t-tooltip+ v-for="placeholder in fallbackPlaceholders"+ :key="placeholder.name"+ :content="placeholder.description + '(点击插入)'"+ placement="top"+ >+ <span+ class="placeholder-tag"+ @click="handlePlaceholderClick('fallback', placeholder.name)"+ v-text="'{{' + placeholder.name + '}}'"+ ></span>+ </t-tooltip>+ <span class="placeholder-hint" v-text="'(点击插入,或输入 {{ 唤起列表)'"></span>+ </div></div>- <div class="setting-control setting-control-full">+ <div class="setting-control setting-control-full" style="position: relative;"><div class="textarea-with-template"><t-textarea+ ref="fallbackPromptTextareaRef"v-model="formData.config.fallback_prompt":placeholder="defaultFallbackPrompt || $t('agent.editor.fallbackPromptPlaceholder') || '留空使用系统默认提示词'":autosize="{ minRows: 4, maxRows: 10 }"+ @input="handleFallbackPromptInput"/><PromptTemplateSelectortype="fallback"@@ -709,6 +852,29 @@@select="handleFallbackPromptTemplateSelect"/></div>+ <Teleport to="body">+ <div+ v-if="fallbackPromptPopup.show && filteredFallbackPlaceholders.length > 0"+ class="placeholder-popup-wrapper"+ :style="fallbackPromptPopup.style"+ >+ <div class="placeholder-popup">+ <div+ v-for="(placeholder, index) in filteredFallbackPlaceholders"+ :key="placeholder.name"+ class="placeholder-item"+ :class="{ active: fallbackPromptPopup.selectedIndex === index }"+ @mousedown.prevent="insertGenericPlaceholder('fallback', placeholder.name, true)"+ @mouseenter="fallbackPromptPopup.selectedIndex = index"+ >+ <div class="placeholder-name">+ <code v-html="`{{${placeholder.name}}}`"></code>+ </div>+ <div class="placeholder-desc">{{ placeholder.description }}</div>+ </div>+ </div>+ </div>+ </Teleport></div></div></div>@@ -732,12 +898,17 @@import { ref, computed, watch, nextTick } from 'vue';import { useI18n } from 'vue-i18n';import { MessagePlugin } from 'tdesign-vue-next';-import { createAgent, updateAgent, type CustomAgent } from '@/api/agent';-import { listModels } from '@/api/model';+import { createAgent, updateAgent, getPlaceholders, type CustomAgent, type PlaceholderDefinition } from '@/api/agent';+import { listModels, type ModelConfig } from '@/api/model';import { listKnowledgeBases } from '@/api/knowledge-base';-import { getAgentConfig, getConversationConfig, type PlaceholderDefinition } from '@/api/system';+import { listMCPServices, type MCPService } from '@/api/mcp-service';+import { getAgentConfig, getConversationConfig } from '@/api/system';+import { useUIStore } from '@/stores/ui';import AgentAvatar from '@/components/AgentAvatar.vue';import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue';+import ModelSelector from '@/components/ModelSelector.vue';++const uiStore = useUIStore();const { t } = useI18n();@@ -745,6 +916,7 @@ const props = defineProps<{visible: boolean;mode: 'create' | 'edit';agent?: CustomAgent | null;+ initialSection?: string;}>();const emit = defineEmits<{@@ -752,14 +924,16 @@ const emit = defineEmits<{(e: 'success'): void;}>();-const currentSection = ref('basic');+const currentSection = ref(props.initialSection || 'basic');const saving = ref(false);-const modelOptions = ref<{ label: string; value: string }[]>([]);-const rerankModelOptions = ref<{ label: string; value: string }[]>([]);+const allModels = ref<ModelConfig[]>([]);const kbOptions = ref<{ label: string; value: string }[]>([]);+const mcpOptions = ref<{ label: string; value: string }[]>([]);// 系统默认配置(用于内置智能体显示默认提示词)-const defaultSystemPrompt = ref('');+const defaultSystemPrompt = ref(''); // 普通模式默认提示词+const defaultSystemPromptWebEnabled = ref(''); // Agent模式 Web开启时默认提示词+const defaultSystemPromptWebDisabled = ref(''); // Agent模式 Web关闭时默认提示词const defaultContextTemplate = ref('');const defaultRewritePromptSystem = ref('');const defaultRewritePromptUser = ref('');@@ -780,6 +954,9 @@ const knowledgeBaseTools = ['grep_chunks', 'knowledge_search', 'list_knowledge_c// 知识库选择模式:all=全部, selected=指定, none=不使用const kbSelectionMode = ref<'all' | 'selected' | 'none'>('none');+// MCP 服务选择模式:all=全部, selected=指定, none=不使用+const mcpSelectionMode = ref<'all' | 'selected' | 'none'>('none');+// 可用工具列表 (与后台 definitions.go 保持一致)const allTools = [{ value: 'thinking', label: '思考', description: '动态和反思性的问题解决思考工具', requiresKB: false },@@ -797,14 +974,6 @@ const hasKnowledgeBase = computed(() => {return kbSelectionMode.value !== 'none';});-// 允许用户选择知识库的描述-const allowUserKBSelectionDesc = computed(() => {- if (kbSelectionMode.value === 'all') {- return t('agent.editor.allowUserKBSelectionDescAll');- }- return t('agent.editor.allowUserKBSelectionDescSelected');-});-const availableTools = computed(() => {return allTools.map(tool => ({...tool,@@ -812,8 +981,40 @@ const availableTools = computed(() => {}));});-// 占位符相关-const availablePlaceholders = ref<PlaceholderDefinition[]>([]);+// 占位符相关 - 从 API 获取+const placeholderData = ref<{+ system_prompt: PlaceholderDefinition[];+ agent_system_prompt: PlaceholderDefinition[];+ context_template: PlaceholderDefinition[];+ rewrite_system_prompt: PlaceholderDefinition[];+ rewrite_prompt: PlaceholderDefinition[];+ fallback_prompt: PlaceholderDefinition[];+}>({+ system_prompt: [],+ agent_system_prompt: [],+ context_template: [],+ rewrite_system_prompt: [],+ rewrite_prompt: [],+ fallback_prompt: [],+});++// 系统提示词占位符(根据模式动态选择)+const availablePlaceholders = computed(() => {+ return isAgentMode.value ? placeholderData.value.agent_system_prompt : placeholderData.value.system_prompt;+});++// 上下文模板占位符+const contextTemplatePlaceholders = computed(() => placeholderData.value.context_template);++// 改写系统提示词占位符+const rewriteSystemPlaceholders = computed(() => placeholderData.value.rewrite_system_prompt);++// 改写用户提示词占位符+const rewritePlaceholders = computed(() => placeholderData.value.rewrite_prompt);++// 兜底提示词占位符+const fallbackPlaceholders = computed(() => placeholderData.value.fallback_prompt);+const promptTextareaRef = ref<any>(null);const showPlaceholderPopup = ref(false);const selectedPlaceholderIndex = ref(0);@@ -829,13 +1030,30 @@ const contextPlaceholderPrefix = ref('');const contextPopupStyle = ref({ top: '0px', left: '0px' });let contextPlaceholderPopupTimer: any = null;-// 上下文模板可用的占位符-const contextTemplatePlaceholders = computed(() => [- { name: 'query', description: t('agent.editor.placeholderQuery') || '用户的问题' },- { name: 'contexts', description: t('agent.editor.placeholderContexts') || '检索到的内容列表' },- { name: 'current_time', description: t('agent.editor.placeholderCurrentTime') || '当前时间(格式:2006-01-02 15:04:05)' },- { name: 'current_week', description: t('agent.editor.placeholderCurrentWeek') || '当前星期(如:星期一)' },-]);+// 通用占位符弹出相关(用于改写提示词和兜底提示词)+interface PlaceholderPopupState {+ show: boolean;+ selectedIndex: number;+ prefix: string;+ style: { top: string; left: string };+ timer: any;+ fieldKey: string;+ placeholders: PlaceholderDefinition[];+}++const rewriteSystemPopup = ref<PlaceholderPopupState>({+ show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'rewrite_prompt_system', placeholders: []+});+const rewriteUserPopup = ref<PlaceholderPopupState>({+ show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'rewrite_prompt_user', placeholders: []+});+const fallbackPromptPopup = ref<PlaceholderPopupState>({+ show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'fallback_prompt', placeholders: []+});++const rewriteSystemTextareaRef = ref<any>(null);+const rewriteUserTextareaRef = ref<any>(null);+const fallbackPromptTextareaRef = ref<any>(null);const navItems = computed(() => {const items: { key: string; icon: string; label: string }[] = [@@ -869,11 +1087,10 @@ const navItems = computed(() => {const defaultFormData = {name: '',description: '',- type: 'custom' as const,is_builtin: false,config: {// 基础设置- agent_mode: 'normal' as 'normal' | 'agent',+ agent_mode: 'quick-answer' as 'quick-answer' | 'smart-reasoning',system_prompt: '',system_prompt_web_enabled: '',context_template: '{{query}}',@@ -886,10 +1103,12 @@ const defaultFormData = {max_iterations: 10,allowed_tools: [] as string[],reflection_enabled: false,+ // MCP 服务设置+ mcp_selection_mode: 'none' as 'all' | 'selected' | 'none',+ mcp_services: [] as string[],// 知识库设置kb_selection_mode: 'none' as 'all' | 'selected' | 'none',knowledge_bases: [] as string[],- allow_user_kb_selection: false,// 网络搜索设置web_search_enabled: false,web_search_max_results: 5,@@ -919,29 +1138,33 @@ const defaultFormData = {const formData = ref(JSON.parse(JSON.stringify(defaultFormData)));const agentMode = computed({get: () => formData.value.config.agent_mode,- set: (val: 'normal' | 'agent') => { formData.value.config.agent_mode = val; }+ set: (val: 'quick-answer' | 'smart-reasoning') => { formData.value.config.agent_mode = val; }});-const isAgentMode = computed(() => agentMode.value === 'agent');+const isAgentMode = computed(() => agentMode.value === 'smart-reasoning');// 是否为内置智能体const isBuiltinAgent = computed(() => {return formData.value.is_builtin === true;});-// 系统提示词的 placeholder(内置智能体显示默认提示词,自定义智能体显示普通提示)+// 系统提示词的 placeholderconst systemPromptPlaceholder = computed(() => {- if (isBuiltinAgent.value && defaultSystemPrompt.value) {- return t('agent.editor.defaultPromptHint') + '\n\n' + defaultSystemPrompt.value;- }return t('agent.editor.systemPromptPlaceholder');});-// 上下文模板的 placeholder(内置智能体显示默认模板,自定义智能体显示普通提示)+// Agent模式 Web关闭时的 placeholder+const systemPromptWebDisabledPlaceholder = computed(() => {+ return t('agent.editor.systemPromptPlaceholder');+});++// Agent模式 Web开启时的 placeholder+const systemPromptWebEnabledPlaceholder = computed(() => {+ return t('agent.editor.systemPromptWebEnabledPlaceholder') || '网络搜索开启时使用的系统提示词';+});++// 上下文模板的 placeholderconst contextTemplatePlaceholder = computed(() => {- if (isBuiltinAgent.value && defaultContextTemplate.value) {- return t('agent.editor.defaultContextTemplateHint') + '\n\n' + defaultContextTemplate.value;- }return t('agent.editor.contextTemplatePlaceholder');});@@ -956,7 +1179,7 @@ const needsRerankModel = computed(() => {// 监听可见性变化,重置表单watch(() => props.visible, async (val) => {if (val) {- currentSection.value = 'basic';+ currentSection.value = props.initialSection || 'basic';// 先加载依赖数据(包括默认配置)await loadDependencies();@@ -976,16 +1199,22 @@ watch(() => props.visible, async (val) => {if (!agentData.config.suggested_prompts) agentData.config.suggested_prompts = [];if (!agentData.config.knowledge_bases) agentData.config.knowledge_bases = [];if (!agentData.config.allowed_tools) agentData.config.allowed_tools = [];+ if (!agentData.config.mcp_services) agentData.config.mcp_services = [];// 兼容旧数据:如果没有 agent_mode 字段,根据 allowed_tools 推断if (!agentData.config.agent_mode) {const isAgent = agentData.config.max_iterations > 1 || (agentData.config.allowed_tools && agentData.config.allowed_tools.length > 0);- agentData.config.agent_mode = isAgent ? 'agent' : 'normal';+ agentData.config.agent_mode = isAgent ? 'smart-reasoning' : 'quick-answer';}formData.value = agentData;// 初始化知识库选择模式initKbSelectionMode();+ initMcpSelectionMode();+ // 内置智能体:如果提示词为空,填入系统默认值+ if (agentData.is_builtin) {+ fillBuiltinAgentDefaults();+ }} else {// 创建新智能体,使用系统默认值const newFormData = JSON.parse(JSON.stringify(defaultFormData));@@ -1003,6 +1232,7 @@ watch(() => props.visible, async (val) => {}formData.value = newFormData;kbSelectionMode.value = 'none';+ mcpSelectionMode.value = 'none';}}});@@ -1015,21 +1245,68 @@ const initKbSelectionMode = () => {} else if (formData.value.config.knowledge_bases?.length > 0) {// 有指定知识库kbSelectionMode.value = 'selected';- } else if (formData.value.config.allow_user_kb_selection) {- // 允许用户选择(旧数据兼容:没有指定知识库但允许选择 = 全部)- kbSelectionMode.value = 'all';} else {kbSelectionMode.value = 'none';}};+// 初始化 MCP 选择模式+const initMcpSelectionMode = () => {+ if (formData.value.config.mcp_selection_mode) {+ // 如果有保存的模式,直接使用+ mcpSelectionMode.value = formData.value.config.mcp_selection_mode;+ } else if (formData.value.config.mcp_services?.length > 0) {+ // 有指定 MCP 服务+ mcpSelectionMode.value = 'selected';+ } else {+ mcpSelectionMode.value = 'none';+ }+};++// 内置智能体:填入系统默认值+const fillBuiltinAgentDefaults = () => {+ const config = formData.value.config;+ const isAgent = config.agent_mode === 'smart-reasoning';++ if (isAgent) {+ // Agent 模式:填入 Web 开启/关闭的默认提示词+ if (!config.system_prompt && defaultSystemPromptWebDisabled.value) {+ config.system_prompt = defaultSystemPromptWebDisabled.value;+ }+ if (!config.system_prompt_web_enabled && defaultSystemPromptWebEnabled.value) {+ config.system_prompt_web_enabled = defaultSystemPromptWebEnabled.value;+ }+ } else {+ // 普通模式:填入默认系统提示词和上下文模板+ if (!config.system_prompt && defaultSystemPrompt.value) {+ config.system_prompt = defaultSystemPrompt.value;+ }+ if (!config.context_template && defaultContextTemplate.value) {+ config.context_template = defaultContextTemplate.value;+ }+ }++ // 通用默认值+ if (!config.rewrite_prompt_system && defaultRewritePromptSystem.value) {+ config.rewrite_prompt_system = defaultRewritePromptSystem.value;+ }+ if (!config.rewrite_prompt_user && defaultRewritePromptUser.value) {+ config.rewrite_prompt_user = defaultRewritePromptUser.value;+ }+ if (!config.fallback_prompt && defaultFallbackPrompt.value) {+ config.fallback_prompt = defaultFallbackPrompt.value;+ }+ if (!config.fallback_response && defaultFallbackResponse.value) {+ config.fallback_response = defaultFallbackResponse.value;+ }+};+// 监听知识库选择模式变化watch(kbSelectionMode, (mode) => {formData.value.config.kb_selection_mode = mode;if (mode === 'none') {// 不使用知识库,清空相关配置formData.value.config.knowledge_bases = [];- formData.value.config.allow_user_kb_selection = false;} else if (mode === 'all') {// 全部知识库,清空指定列表formData.value.config.knowledge_bases = [];@@ -1037,9 +1314,22 @@ watch(kbSelectionMode, (mode) => {// selected 模式保持 knowledge_bases 不变});+// 监听 MCP 选择模式变化+watch(mcpSelectionMode, (mode) => {+ formData.value.config.mcp_selection_mode = mode;+ if (mode === 'none') {+ // 不使用 MCP,清空相关配置+ formData.value.config.mcp_services = [];+ } else if (mode === 'all') {+ // 全部 MCP,清空指定列表+ formData.value.config.mcp_services = [];+ }+ // selected 模式保持 mcp_services 不变+});+// 监听模式变化,自动调整配置watch(agentMode, (val) => {- if (val === 'agent') {+ if (val === 'smart-reasoning') {// 切换到 Agent 模式,根据知识库配置启用工具if (formData.value.config.allowed_tools.length === 0) {if (hasKnowledgeBase.value) {@@ -1106,16 +1396,10 @@ watch(isAgentMode, (isAgent) => {// 加载依赖数据const loadDependencies = async () => {try {- // 加载模型列表 (只加载 KnowledgeQA 类型的模型)- const models = await listModels('KnowledgeQA');+ // 加载所有模型列表(ModelSelector 组件会自动按类型过滤)+ const models = await listModels();if (models && models.length > 0) {- modelOptions.value = models.map((m: any) => ({ label: m.name || m.id, value: m.id }));- }-- // 加载 ReRank 模型列表- const rerankModels = await listModels('Rerank');- if (rerankModels && rerankModels.length > 0) {- rerankModelOptions.value = rerankModels.map((m: any) => ({ label: m.name || m.id, value: m.id }));+ allModels.value = models;}// 加载知识库列表@@ -1124,10 +1408,35 @@ const loadDependencies = async () => {kbOptions.value = kbRes.data.map((kb: any) => ({ label: kb.name, value: kb.id }));}- // 加载可用占位符+ // 加载 MCP 服务列表(只加载启用的)+ try {+ const mcpList = await listMCPServices();+ if (mcpList && mcpList.length > 0) {+ mcpOptions.value = mcpList+ .filter((mcp: MCPService) => mcp.enabled)+ .map((mcp: MCPService) => ({ label: mcp.name, value: mcp.id }));+ }+ } catch (e) {+ console.warn('Failed to load MCP services', e);+ }++ // 加载占位符定义(从统一 API)+ try {+ const placeholdersRes = await getPlaceholders();+ if (placeholdersRes.data) {+ placeholderData.value = placeholdersRes.data;+ }+ } catch (e) {+ console.warn('Failed to load placeholders', e);+ }++ // 加载 Agent 模式默认提示词const agentConfig = await getAgentConfig();- if (agentConfig.data?.available_placeholders) {- availablePlaceholders.value = agentConfig.data.available_placeholders;+ if (agentConfig.data?.system_prompt_web_enabled) {+ defaultSystemPromptWebEnabled.value = agentConfig.data.system_prompt_web_enabled;+ }+ if (agentConfig.data?.system_prompt_web_disabled) {+ defaultSystemPromptWebDisabled.value = agentConfig.data.system_prompt_web_disabled;}// 加载系统默认配置(用于内置智能体显示默认提示词)@@ -1177,9 +1486,17 @@ const loadDependencies = async () => {}};+// 跳转到模型管理页面添加模型+const handleAddModel = (subSection: string) => {+ uiStore.openSettings('models', subSection);+};+const handleClose = () => {showPlaceholderPopup.value = false;showContextPlaceholderPopup.value = false;+ rewriteSystemPopup.value.show = false;+ rewriteUserPopup.value.show = false;+ fallbackPromptPopup.value.show = false;emit('update:visible', false);};@@ -1205,6 +1522,39 @@ const filteredContextPlaceholders = computed(() => {);});+// 过滤后的改写系统提示词占位符列表+const filteredRewriteSystemPlaceholders = computed(() => {+ if (!rewriteSystemPopup.value.prefix) {+ return rewriteSystemPlaceholders.value;+ }+ const prefix = rewriteSystemPopup.value.prefix.toLowerCase();+ return rewriteSystemPlaceholders.value.filter(p =>+ p.name.toLowerCase().startsWith(prefix)+ );+});++// 过滤后的改写用户提示词占位符列表+const filteredRewriteUserPlaceholders = computed(() => {+ if (!rewriteUserPopup.value.prefix) {+ return rewritePlaceholders.value;+ }+ const prefix = rewriteUserPopup.value.prefix.toLowerCase();+ return rewritePlaceholders.value.filter(p =>+ p.name.toLowerCase().startsWith(prefix)+ );+});++// 过滤后的兜底提示词占位符列表+const filteredFallbackPlaceholders = computed(() => {+ if (!fallbackPromptPopup.value.prefix) {+ return fallbackPlaceholders.value;+ }+ const prefix = fallbackPromptPopup.value.prefix.toLowerCase();+ return fallbackPlaceholders.value.filter(p =>+ p.name.toLowerCase().startsWith(prefix)+ );+});+// 获取 textarea 元素const getTextareaElement = (): HTMLTextAreaElement | null => {if (promptTextareaRef.value) {@@ -1310,7 +1660,7 @@ const handlePromptInput = () => {};// 插入占位符-const insertPlaceholder = (placeholderName: string) => {+const insertPlaceholder = (placeholderName: string, fromPopup: boolean = false) => {const textarea = getTextareaElement();if (!textarea) return;@@ -1320,30 +1670,43 @@ const insertPlaceholder = (placeholderName: string) => {nextTick(() => {const cursorPos = textarea.selectionStart;- const currentValue = formData.value.config.system_prompt;+ const currentValue = formData.value.config.system_prompt || '';const textBeforeCursor = currentValue.substring(0, cursorPos);const textAfterCursor = currentValue.substring(cursorPos);- // 找到 {{ 的位置- let lastOpenPos = -1;- for (let i = textBeforeCursor.length - 1; i >= 1; i--) {- if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {- lastOpenPos = i - 1;- break;+ // 只有从下拉列表选择时才查找 {{ 并替换+ if (fromPopup) {+ let lastOpenPos = -1;+ for (let i = textBeforeCursor.length - 1; i >= 1; i--) {+ if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {+ lastOpenPos = i - 1;+ break;+ }}- }-- if (lastOpenPos !== -1) {- const textBeforeOpen = currentValue.substring(0, lastOpenPos);- const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;- formData.value.config.system_prompt = newValue;- nextTick(() => {- const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;- textarea.setSelectionRange(newCursorPos, newCursorPos);- textarea.focus();- });+ if (lastOpenPos !== -1) {+ const textBeforeOpen = currentValue.substring(0, lastOpenPos);+ const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;+ formData.value.config.system_prompt = newValue;++ nextTick(() => {+ const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;+ textarea.setSelectionRange(newCursorPos, newCursorPos);+ textarea.focus();+ });+ return;+ }}++ // 直接在光标位置插入完整占位符+ const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;+ formData.value.config.system_prompt = newValue;++ nextTick(() => {+ const newCursorPos = cursorPos + placeholderName.length + 4;+ textarea.setSelectionRange(newCursorPos, newCursorPos);+ textarea.focus();+ });});};@@ -1449,7 +1812,7 @@ const handleContextTemplateInput = () => {};// 插入上下文模板占位符-const insertContextPlaceholder = (placeholderName: string) => {+const insertContextPlaceholder = (placeholderName: string, fromPopup: boolean = false) => {const textarea = getContextTemplateTextareaElement();if (!textarea) return;@@ -1459,29 +1822,238 @@ const insertContextPlaceholder = (placeholderName: string) => {nextTick(() => {const cursorPos = textarea.selectionStart;- const currentValue = formData.value.config.context_template;+ const currentValue = formData.value.config.context_template || '';const textBeforeCursor = currentValue.substring(0, cursorPos);const textAfterCursor = currentValue.substring(cursorPos);- let lastOpenPos = -1;- for (let i = textBeforeCursor.length - 1; i >= 1; i--) {- if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {+ // 只有从下拉列表选择时才查找 {{ 并替换+ if (fromPopup) {+ let lastOpenPos = -1;+ for (let i = textBeforeCursor.length - 1; i >= 1; i--) {+ if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {+ lastOpenPos = i - 1;+ break;+ }+ }++ if (lastOpenPos !== -1) {+ const textBeforeOpen = currentValue.substring(0, lastOpenPos);+ const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;+ formData.value.config.context_template = newValue;++ nextTick(() => {+ const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;+ textarea.setSelectionRange(newCursorPos, newCursorPos);+ textarea.focus();+ });+ return;+ }+ }++ // 直接在光标位置插入完整占位符+ const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;+ formData.value.config.context_template = newValue;++ nextTick(() => {+ const newCursorPos = cursorPos + placeholderName.length + 4;+ textarea.setSelectionRange(newCursorPos, newCursorPos);+ textarea.focus();+ });+ });+};++// 通用获取 textarea 元素+const getGenericTextareaElement = (type: 'rewriteSystem' | 'rewriteUser' | 'fallback'): HTMLTextAreaElement | null => {+ const refMap = {+ rewriteSystem: rewriteSystemTextareaRef,+ rewriteUser: rewriteUserTextareaRef,+ fallback: fallbackPromptTextareaRef,+ };+ const ref = refMap[type];+ if (ref.value) {+ if (ref.value.$el) {+ return ref.value.$el.querySelector('textarea');+ }+ if (ref.value instanceof HTMLTextAreaElement) {+ return ref.value;+ }+ }+ return null;+};++// 通用计算光标位置+const calculateGenericCursorPosition = (textarea: HTMLTextAreaElement, fieldValue: string) => {+ const cursorPos = textarea.selectionStart;+ const textBeforeCursor = fieldValue.substring(0, cursorPos);+ const lines = textBeforeCursor.split('\n');+ const currentLine = lines.length - 1;+ const currentLineText = lines[currentLine];++ const textareaRect = textarea.getBoundingClientRect();+ const style = window.getComputedStyle(textarea);+ const lineHeight = parseFloat(style.lineHeight) || 20;+ const paddingTop = parseFloat(style.paddingTop) || 0;+ const paddingLeft = parseFloat(style.paddingLeft) || 0;++ const span = document.createElement('span');+ span.style.font = style.font;+ span.style.visibility = 'hidden';+ span.style.position = 'absolute';+ span.style.whiteSpace = 'pre';+ span.textContent = currentLineText;+ document.body.appendChild(span);+ const textWidth = span.offsetWidth;+ document.body.removeChild(span);++ const scrollTop = textarea.scrollTop;+ const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4;+ const scrollLeft = textarea.scrollLeft;+ const left = textareaRect.left + paddingLeft + textWidth - scrollLeft;++ return { top, left };+};++// 通用检查并显示占位符弹出+const checkAndShowGenericPlaceholderPopup = (+ type: 'rewriteSystem' | 'rewriteUser' | 'fallback',+ popup: typeof rewriteSystemPopup,+ fieldKey: keyof typeof formData.value.config,+ filteredPlaceholders: PlaceholderDefinition[]+) => {+ const textarea = getGenericTextareaElement(type);+ if (!textarea) return;++ const cursorPos = textarea.selectionStart;+ const fieldValue = String(formData.value.config[fieldKey] || '');+ const textBeforeCursor = fieldValue.substring(0, cursorPos);++ let lastOpenPos = -1;+ for (let i = textBeforeCursor.length - 1; i >= 1; i--) {+ if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {+ const textAfterOpen = textBeforeCursor.substring(i + 1);+ if (!textAfterOpen.includes('}}')) {lastOpenPos = i - 1;break;}}+ }++ if (lastOpenPos === -1) {+ popup.value.show = false;+ popup.value.prefix = '';+ return;+ }++ const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2);+ popup.value.prefix = textAfterOpen;++ if (filteredPlaceholders.length > 0) {+ nextTick(() => {+ const position = calculateGenericCursorPosition(textarea, fieldValue);+ popup.value.style = {+ top: `${position.top}px`,+ left: `${position.left}px`+ };+ popup.value.show = true;+ popup.value.selectedIndex = 0;+ });+ } else {+ popup.value.show = false;+ }+};++// 处理改写系统提示词输入+const handleRewriteSystemInput = () => {+ if (rewriteSystemPopup.value.timer) {+ clearTimeout(rewriteSystemPopup.value.timer);+ }+ rewriteSystemPopup.value.timer = setTimeout(() => {+ checkAndShowGenericPlaceholderPopup('rewriteSystem', rewriteSystemPopup, 'rewrite_prompt_system', filteredRewriteSystemPlaceholders.value);+ }, 50);+};++// 处理改写用户提示词输入+const handleRewriteUserInput = () => {+ if (rewriteUserPopup.value.timer) {+ clearTimeout(rewriteUserPopup.value.timer);+ }+ rewriteUserPopup.value.timer = setTimeout(() => {+ checkAndShowGenericPlaceholderPopup('rewriteUser', rewriteUserPopup, 'rewrite_prompt_user', filteredRewriteUserPlaceholders.value);+ }, 50);+};++// 处理兜底提示词输入+const handleFallbackPromptInput = () => {+ if (fallbackPromptPopup.value.timer) {+ clearTimeout(fallbackPromptPopup.value.timer);+ }+ fallbackPromptPopup.value.timer = setTimeout(() => {+ checkAndShowGenericPlaceholderPopup('fallback', fallbackPromptPopup, 'fallback_prompt', filteredFallbackPlaceholders.value);+ }, 50);+};++// 通用插入占位符+const insertGenericPlaceholder = (type: 'rewriteSystem' | 'rewriteUser' | 'fallback', placeholderName: string, fromPopup: boolean = false) => {+ const textarea = getGenericTextareaElement(type);+ if (!textarea) return;++ const popupMap = {+ rewriteSystem: rewriteSystemPopup,+ rewriteUser: rewriteUserPopup,+ fallback: fallbackPromptPopup,+ };+ const fieldKeyMap: Record<string, keyof typeof formData.value.config> = {+ rewriteSystem: 'rewrite_prompt_system',+ rewriteUser: 'rewrite_prompt_user',+ fallback: 'fallback_prompt',+ };++ const popup = popupMap[type];+ const fieldKey = fieldKeyMap[type];++ popup.value.show = false;+ popup.value.prefix = '';+ popup.value.selectedIndex = 0;++ nextTick(() => {+ const cursorPos = textarea.selectionStart;+ const currentValue = String(formData.value.config[fieldKey] || '');+ const textBeforeCursor = currentValue.substring(0, cursorPos);+ const textAfterCursor = currentValue.substring(cursorPos);- if (lastOpenPos !== -1) {- const textBeforeOpen = currentValue.substring(0, lastOpenPos);- const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;- formData.value.config.context_template = newValue;+ // 只有从下拉列表选择时才查找 {{ 并替换+ if (fromPopup) {+ let lastOpenPos = -1;+ for (let i = textBeforeCursor.length - 1; i >= 1; i--) {+ if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {+ lastOpenPos = i - 1;+ break;+ }+ }- nextTick(() => {- const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;- textarea.setSelectionRange(newCursorPos, newCursorPos);- textarea.focus();- });+ if (lastOpenPos !== -1) {+ const textBeforeOpen = currentValue.substring(0, lastOpenPos);+ const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;+ (formData.value.config as any)[fieldKey] = newValue;++ nextTick(() => {+ const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;+ textarea.setSelectionRange(newCursorPos, newCursorPos);+ textarea.focus();+ });+ return;+ }}++ // 直接在光标位置插入完整占位符+ const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;+ (formData.value.config as any)[fieldKey] = newValue;++ nextTick(() => {+ const newCursorPos = cursorPos + placeholderName.length + 4;+ textarea.setSelectionRange(newCursorPos, newCursorPos);+ textarea.focus();+ });});};@@ -1513,7 +2085,7 @@ const setupContextTemplateEventListeners = () => {e.stopPropagation();const selected = filteredContextPlaceholders.value[selectedContextPlaceholderIndex.value];if (selected) {- insertContextPlaceholder(selected.name);+ insertContextPlaceholder(selected.name, true);}} else if (e.key === 'Escape') {e.preventDefault();@@ -1555,7 +2127,7 @@ const setupTextareaEventListeners = () => {e.stopPropagation();const selected = filteredPlaceholders.value[selectedPlaceholderIndex.value];if (selected) {- insertPlaceholder(selected.name);+ insertPlaceholder(selected.name, true);}} else if (e.key === 'Escape') {e.preventDefault();@@ -1569,12 +2141,73 @@ const setupTextareaEventListeners = () => {});};+// 通用设置 textarea 事件监听+const setupGenericTextareaEventListeners = (+ type: 'rewriteSystem' | 'rewriteUser' | 'fallback',+ popup: typeof rewriteSystemPopup,+ filteredPlaceholders: () => PlaceholderDefinition[]+) => {+ nextTick(() => {+ const textarea = getGenericTextareaElement(type);+ if (textarea) {+ textarea.addEventListener('keydown', (e: KeyboardEvent) => {+ const filtered = filteredPlaceholders();+ if (popup.value.show && filtered.length > 0) {+ if (e.key === 'ArrowDown') {+ e.preventDefault();+ e.stopPropagation();+ if (popup.value.selectedIndex < filtered.length - 1) {+ popup.value.selectedIndex++;+ } else {+ popup.value.selectedIndex = 0;+ }+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ e.stopPropagation();+ if (popup.value.selectedIndex > 0) {+ popup.value.selectedIndex--;+ } else {+ popup.value.selectedIndex = filtered.length - 1;+ }+ } else if (e.key === 'Enter' || e.key === 'Tab') {+ e.preventDefault();+ e.stopPropagation();+ const selected = filtered[popup.value.selectedIndex];+ if (selected) {+ insertGenericPlaceholder(type, selected.name, true);+ }+ } else if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ popup.value.show = false;+ popup.value.prefix = '';+ }+ }+ }, true);+ }+ });+};++// 处理点击占位符标签+const handlePlaceholderClick = (type: 'system' | 'context' | 'rewriteSystem' | 'rewriteUser' | 'fallback', placeholderName: string) => {+ if (type === 'system') {+ insertPlaceholder(placeholderName);+ } else if (type === 'context') {+ insertContextPlaceholder(placeholderName);+ } else {+ insertGenericPlaceholder(type, placeholderName);+ }+};+// 监听 visible 变化设置事件监听watch(() => props.visible, (val) => {if (val) {nextTick(() => {setupTextareaEventListeners();setupContextTemplateEventListeners();+ setupGenericTextareaEventListeners('rewriteSystem', rewriteSystemPopup, () => filteredRewriteSystemPlaceholders.value);+ setupGenericTextareaEventListeners('rewriteUser', rewriteUserPopup, () => filteredRewriteUserPlaceholders.value);+ setupGenericTextareaEventListeners('fallback', fallbackPromptPopup, () => filteredFallbackPlaceholders.value);});}});@@ -1650,11 +2283,6 @@ const handleSave = async () => {formData.value.config.suggested_prompts = formData.value.config.suggested_prompts.filter((p: string) => p.trim() !== '');}- // 确保类型设置正确(内置智能体保持原类型)- if (!isBuiltinAgent.value) {- formData.value.type = 'custom';- }-saving.value = true;try {if (props.mode === 'create') {@@ -1854,6 +2482,11 @@ const handleSave = async () => {&.setting-row-vertical {flex-direction: column;gap: 12px;++ .setting-info {+ max-width: 100%;+ padding-right: 0;+ }}}@@ -2194,46 +2827,64 @@ const handleSave = async () => {}}-// 占位符提示样式-.placeholder-hint {- margin-top: 12px;- padding: 12px;- background: #f8fafc;- border-radius: 6px;- border: 1px solid #e1e8ed;+// 占位符标签组样式+.placeholder-tags {+ margin-top: 6px;+ display: flex;+ align-items: center;+ gap: 5px;font-size: 12px;- max-width: 480px;+ line-height: 1.4;+ overflow-x: auto;+ white-space: nowrap;+ padding-bottom: 4px;++ // 隐藏滚动条但保持可滚动+ scrollbar-width: thin;+ &::-webkit-scrollbar {+ height: 4px;+ }+ &::-webkit-scrollbar-thumb {+ background: rgba(0, 0, 0, 0.1);+ border-radius: 2px;+ }- .hint-title {- font-weight: 500;- color: #333;- margin: 0 0 8px 0;+ .placeholder-label {+ color: var(--td-text-color-secondary, #666);+ flex-shrink: 0;}- .placeholder-list {- margin: 8px 0;- padding-left: 20px;- color: #666;+ .placeholder-hint {+ color: var(--td-text-color-placeholder, #999);+ font-size: 11px;+ user-select: none;+ flex-shrink: 0;+ }- li {- margin: 4px 0;-- code {- background: #fff;- padding: 2px 6px;- border-radius: 3px;- font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;- font-size: 11px;- color: #e83e8c;- border: 1px solid #e1e8ed;- }+ .placeholder-tag {+ display: inline-flex;+ align-items: center;+ padding: 1px 5px;+ border-radius: 3px;+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;+ font-size: 11px;+ color: var(--td-text-color-primary, #333);+ background-color: var(--td-bg-color-secondarycontainer, #f3f3f3);+ cursor: pointer;+ transition: all 0.2s;+ user-select: none;+ border: 1px solid transparent;+ flex-shrink: 0;++ &:hover {+ color: var(--td-brand-color, #0052d9);+ background-color: var(--td-brand-color-light, #ecf2fe);+ border-color: var(--td-brand-color-focus, #d0e0fd);}- }- .hint-tip {- margin: 8px 0 0 0;- color: #999;- font-style: italic;+ &:active {+ background-color: var(--td-brand-color-focus, #d0e0fd);+ }}}@@ -2244,43 +2895,43 @@ const handleSave = async () => {}.placeholder-popup {- background: #fff;- border: 1px solid #e5e7eb;- border-radius: 4px;- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);- max-width: 400px;- max-height: 300px;+ background: var(--td-bg-color-container, #fff);+ border: 1px solid var(--td-component-stroke, #e5e7eb);+ border-radius: 6px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);+ max-width: 320px;+ max-height: 240px;overflow-y: auto;- padding: 4px 0;+ padding: 4px;}.placeholder-item {- padding: 8px 12px;+ padding: 6px 10px;cursor: pointer;- transition: background-color 0.2s;+ transition: background-color 0.15s;+ border-radius: 4px;&:hover,&.active {- background-color: #f5f7fa;+ background-color: var(--td-bg-color-container-hover, #f5f7fa);}.placeholder-name {- font-weight: 500;- margin-bottom: 4px;+ margin-bottom: 2px;code {- background: #f5f7fa;- padding: 2px 6px;+ background: var(--td-bg-color-container-hover, #f5f7fa);+ padding: 2px 5px;border-radius: 3px;font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;- font-size: 12px;- color: #e83e8c;+ font-size: 11px;+ color: var(--td-brand-color, #0052d9);}}.placeholder-desc {- font-size: 12px;- color: #666;+ font-size: 11px;+ color: var(--td-text-color-secondary, #666);}}@@ -2303,6 +2954,27 @@ const handleSave = async () => {}}+// 内置智能体头像+.builtin-avatar {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 48px;+ height: 48px;+ border-radius: 12px;+ flex-shrink: 0;++ &.normal {+ background: linear-gradient(135deg, rgba(7, 192, 95, 0.15) 0%, rgba(7, 192, 95, 0.08) 100%);+ color: #059669;+ }++ &.agent {+ background: linear-gradient(135deg, rgba(124, 77, 255, 0.15) 0%, rgba(124, 77, 255, 0.08) 100%);+ color: #7c4dff;+ }+}+// 提示词开关.prompt-toggle {display: flex;diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vueindex f218a83d5..f373d49c7 100644--- a/frontend/src/views/agent/AgentList.vue+++ b/frontend/src/views/agent/AgentList.vue@@ -17,8 +17,8 @@class="agent-card":class="{'is-builtin': agent.is_builtin,- 'agent-mode-normal': agent.config?.agent_mode === 'normal',- 'agent-mode-agent': agent.config?.agent_mode === 'agent'+ 'agent-mode-normal': agent.config?.agent_mode === 'quick-answer',+ 'agent-mode-agent': agent.config?.agent_mode === 'smart-reasoning'}"@click="handleCardClick(agent)">@@ -35,15 +35,15 @@<!-- 卡片头部 --><div class="card-header"><div class="card-header-left">- <AgentAvatar :name="agent.name" size="medium" />- <span class="card-title" :title="agent.name">{{ agent.name }}</span>- <div v-if="agent.is_builtin" class="builtin-badge">- <t-icon name="lock-on" size="12px" />- <span>{{ $t('agent.builtin') }}</span>+ <!-- 内置智能体使用简洁图标 -->+ <div v-if="agent.is_builtin" class="builtin-avatar" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">+ <t-icon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="18px" /></div>+ <!-- 自定义智能体使用 AgentAvatar -->+ <AgentAvatar v-else :name="agent.name" size="medium" />+ <span class="card-title" :title="agent.name">{{ agent.name }}</span></div><t-popup- v-if="!agent.is_builtin"v-model="agent.showMore"overlayClassName="card-more-popup":on-visible-change="(visible: boolean) => onVisibleChange(visible, agent)"@@ -64,17 +64,17 @@<t-icon class="menu-icon" name="edit" /><span>{{ $t('common.edit') }}</span></div>- <div class="popup-menu-item delete" @click="handleDelete(agent)">+ <div class="popup-menu-item" @click="handleCopy(agent)">+ <t-icon class="menu-icon" name="file-copy" />+ <span>{{ $t('common.copy') }}</span>+ </div>+ <div v-if="!agent.is_builtin" class="popup-menu-item delete" @click="handleDelete(agent)"><t-icon class="menu-icon" name="delete" /><span>{{ $t('common.delete') }}</span></div></div></template></t-popup>- <!-- 内置智能体显示编辑按钮 -->- <div v-else class="edit-btn" @click.stop="handleEdit(agent)">- <t-icon name="edit" size="16px" />- </div></div><!-- 卡片内容 -->@@ -87,11 +87,12 @@<!-- 卡片底部 --><div class="card-bottom"><div class="bottom-left">- <div class="type-badge" :class="{ 'normal': agent.config?.agent_mode === 'normal', 'agent': agent.config?.agent_mode === 'agent' }">- <t-icon :name="agent.config?.agent_mode === 'agent' ? 'control-platform' : 'chat'" size="14px" />- <span>{{ agent.config?.agent_mode === 'agent' ? $t('agent.mode.agent') : $t('agent.mode.normal') }}</span>- </div><div class="feature-badges">+ <t-tooltip :content="agent.config?.agent_mode === 'smart-reasoning' ? $t('agent.mode.agent') : $t('agent.mode.normal')" placement="top">+ <div class="feature-badge" :class="{ 'mode-normal': agent.config?.agent_mode === 'quick-answer', 'mode-agent': agent.config?.agent_mode === 'smart-reasoning' }">+ <t-icon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" />+ </div>+ </t-tooltip><t-tooltip v-if="agent.config?.web_search_enabled" :content="$t('agent.features.webSearch')" placement="top"><div class="feature-badge web-search"><t-icon name="search" size="14px" />@@ -109,7 +110,11 @@</t-tooltip></div></div>- <span v-if="agent.updated_at" class="card-time">{{ formatDate(agent.updated_at) }}</span>+ <div v-if="agent.is_builtin" class="builtin-badge">+ <t-icon name="lock-on" size="12px" />+ <span>{{ $t('agent.builtin') }}</span>+ </div>+ <span v-else-if="agent.updated_at" class="card-time">{{ formatDate(agent.updated_at) }}</span></div></div></div>@@ -149,6 +154,7 @@:visible="editorVisible":mode="editorMode":agent="editingAgent"+ :initialSection="editorInitialSection"@update:visible="editorVisible = $event"@success="handleEditorSuccess"/>@@ -157,14 +163,17 @@<script setup lang="ts">import { onMounted, onUnmounted, ref } from 'vue'+import { useRoute, useRouter } from 'vue-router'import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'-import { listAgents, deleteAgent, type CustomAgent } from '@/api/agent'+import { listAgents, deleteAgent, copyAgent, type CustomAgent } from '@/api/agent'import { formatStringDate } from '@/utils/index'import { useI18n } from 'vue-i18n'import AgentEditorModal from './AgentEditorModal.vue'import AgentAvatar from '@/components/AgentAvatar.vue'const { t } = useI18n()+const route = useRoute()+const router = useRouter()interface AgentWithUI extends CustomAgent {showMore?: boolean@@ -177,6 +186,7 @@ const deletingAgent = ref<AgentWithUI | null>(null)const editorVisible = ref(false)const editorMode = ref<'create' | 'edit'>('create')const editingAgent = ref<CustomAgent | null>(null)+const editorInitialSection = ref<string>('basic')const fetchList = () => {loading.value = true@@ -187,9 +197,29 @@ const fetchList = () => {...agent,showMore: false}))++ // 检查 URL 中是否有 edit 参数,如果有则打开对应智能体的编辑模态框+ checkAndOpenEditModal()}).finally(() => loading.value = false)}+// 检查 URL 参数并打开编辑模态框+const checkAndOpenEditModal = () => {+ const editId = route.query.edit as string+ const section = route.query.section as string+ if (editId) {+ const agent = agents.value.find(a => a.id === editId)+ if (agent) {+ editingAgent.value = agent+ editorMode.value = 'edit'+ editorInitialSection.value = section || 'basic'+ editorVisible.value = true+ }+ // 清除 URL 中的参数+ router.replace({ path: route.path, query: {} })+ }+}+// 监听菜单创建智能体事件const handleOpenAgentEditor = (event: CustomEvent) => {if (event.detail?.mode === 'create') {@@ -234,6 +264,20 @@ const handleDelete = (agent: AgentWithUI) => {deleteVisible.value = true}+const handleCopy = (agent: AgentWithUI) => {+ agent.showMore = false+ copyAgent(agent.id).then((res: any) => {+ if (res.data) {+ MessagePlugin.success(t('agent.messages.copied'))+ fetchList()+ } else {+ MessagePlugin.error(res.message || t('agent.messages.copyFailed'))+ }+ }).catch((e: any) => {+ MessagePlugin.error(e?.message || t('agent.messages.copyFailed'))+ })+}+const confirmDelete = () => {if (!deletingAgent.value) return@@ -323,43 +367,44 @@ defineExpose({.agent-card-wrap {display: grid;- gap: 20px;+ gap: 16px;grid-template-columns: 1fr;}.agent-card {- border: 2px solid #fbfbfb;- border-radius: 6px;+ border: 1px solid #f0f0f0;+ border-radius: 12px;overflow: hidden;box-sizing: border-box;- box-shadow: 0 0 8px 0 #00000005;+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);background: #fff;position: relative;cursor: pointer;- transition: all 0.2s ease;- padding: 12px 16px 14px;+ transition: all 0.25s ease;+ padding: 16px 18px;display: flex;flex-direction: column;- min-height: 150px;+ height: 160px;&:hover {border-color: #07c05f;+ box-shadow: 0 4px 12px rgba(7, 192, 95, 0.12);}// 普通模式样式&.agent-mode-normal {background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);border-color: #e8f5ed;-+&:hover {border-color: #07c05f;background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);}-+.card-decoration {color: rgba(7, 192, 95, 0.35);}-+&:hover .card-decoration {color: rgba(7, 192, 95, 0.5);}@@ -369,16 +414,17 @@ defineExpose({&.agent-mode-agent {background: linear-gradient(135deg, #ffffff 0%, #f8f5ff 100%);border-color: #ede8ff;-+&:hover {border-color: #7c4dff;+ box-shadow: 0 4px 12px rgba(124, 77, 255, 0.12);background: linear-gradient(135deg, #ffffff 0%, #f3efff 100%);}-+.card-decoration {color: rgba(124, 77, 255, 0.35);}-+&:hover .card-decoration {color: rgba(124, 77, 255, 0.5);}@@ -395,21 +441,21 @@ defineExpose({.card-decoration {position: absolute;- top: 8px;- right: 8px;+ top: 12px;+ right: 50px;display: flex;align-items: flex-start;- gap: 2px;+ gap: 4px;pointer-events: none;z-index: 0;- transition: color 0.2s ease;+ transition: color 0.25s ease;.star-icon {- opacity: 0.8;+ opacity: 0.9;&.small {- margin-top: 12px;- opacity: 0.6;+ margin-top: 14px;+ opacity: 0.7;}}}@@ -418,7 +464,7 @@ defineExpose({display: flex;justify-content: space-between;align-items: center;- margin-bottom: 8px;+ margin-bottom: 10px;}.card-header-left {@@ -430,9 +476,9 @@ defineExpose({}.card-title {- color: #000000e6;+ color: #1a1a1a;font-family: "PingFang SC";- font-size: 14px;+ font-size: 15px;font-weight: 600;line-height: 22px;overflow: hidden;@@ -445,15 +491,35 @@ defineExpose({.builtin-badge {display: inline-flex;align-items: center;- gap: 4px;+ gap: 3px;padding: 2px 8px;- border-radius: 4px;- background: rgba(0, 0, 0, 0.05);- color: #00000066;+ border-radius: 10px;+ background: rgba(0, 0, 0, 0.04);+ color: #666;font-family: "PingFang SC";- font-size: 12px;- font-weight: 400;+ font-size: 11px;+ font-weight: 500;+ flex-shrink: 0;+}++.builtin-avatar {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ border-radius: 8px;flex-shrink: 0;++ &.normal {+ background: linear-gradient(135deg, rgba(7, 192, 95, 0.15) 0%, rgba(7, 192, 95, 0.08) 100%);+ color: #059669;+ }++ &.agent {+ background: linear-gradient(135deg, rgba(124, 77, 255, 0.15) 0%, rgba(124, 77, 255, 0.08) 100%);+ color: #7c4dff;+ }}.edit-btn {@@ -476,24 +542,28 @@ defineExpose({.more-wrap {display: flex;- width: 32px;- height: 32px;+ width: 28px;+ height: 28px;justify-content: center;align-items: center;border-radius: 6px;cursor: pointer;flex-shrink: 0;transition: all 0.2s ease;- opacity: 0.7;+ opacity: 0;++ .agent-card:hover & {+ opacity: 0.6;+ }&:hover {- background: rgba(0, 0, 0, 0.06);- opacity: 1;+ background: rgba(0, 0, 0, 0.05);+ opacity: 1 !important;}&.active-more {- background: rgba(0, 0, 0, 0.08);- opacity: 1;+ background: rgba(0, 0, 0, 0.06);+ opacity: 1 !important;}.more-icon {@@ -504,7 +574,8 @@ defineExpose({.card-content {flex: 1;- margin-bottom: 10px;+ margin-bottom: 12px;+ overflow: hidden;}.card-description {@@ -513,21 +584,20 @@ defineExpose({-webkit-line-clamp: 2;line-clamp: 2;overflow: hidden;- color: #00000066;+ color: #666;font-family: "PingFang SC";- font-size: 12px;+ font-size: 13px;font-weight: 400;line-height: 20px;- min-height: 40px;}.card-bottom {display: flex;align-items: center;justify-content: space-between;- padding: 8px 0 0;- border-top: 1px solid #f0f0f0;margin-top: auto;+ padding-top: 12px;+ border-top: 1px solid #f0f0f0;}.bottom-left {@@ -536,78 +606,70 @@ defineExpose({gap: 8px;}-.type-badge {- display: inline-flex;- align-items: center;- gap: 4px;- padding: 3px 10px;- border-radius: 4px;- font-family: "PingFang SC";- font-size: 12px;- font-weight: 500;- line-height: 18px;-- &.normal {- background: rgba(7, 192, 95, 0.1);- color: #059669;- border: 1px solid rgba(7, 192, 95, 0.2);- }-- &.agent {- background: rgba(124, 77, 255, 0.1);- color: #7c4dff;- border: 1px solid rgba(124, 77, 255, 0.2);- }-}-.feature-badges {display: flex;align-items: center;- gap: 6px;+ gap: 4px;}.feature-badge {display: flex;align-items: center;justify-content: center;- width: 24px;- height: 24px;- border-radius: 4px;- cursor: pointer;+ width: 26px;+ height: 26px;+ border-radius: 6px;+ cursor: default;+ transition: background 0.2s ease;++ &.mode-normal {+ background: rgba(7, 192, 95, 0.08);+ color: #059669;++ &:hover {+ background: rgba(7, 192, 95, 0.12);+ }+ }++ &.mode-agent {+ background: rgba(124, 77, 255, 0.08);+ color: #7c4dff;++ &:hover {+ background: rgba(124, 77, 255, 0.12);+ }+ }&.web-search {- background: rgba(255, 152, 0, 0.1);- color: #ff9800;- border: 1px solid rgba(255, 152, 0, 0.2);+ background: rgba(255, 152, 0, 0.08);+ color: #f59e0b;&:hover {- background: rgba(255, 152, 0, 0.15);+ background: rgba(255, 152, 0, 0.12);}}&.knowledge {- background: rgba(7, 192, 95, 0.1);+ background: rgba(7, 192, 95, 0.08);color: #059669;- border: 1px solid rgba(7, 192, 95, 0.2);&:hover {- background: rgba(7, 192, 95, 0.15);+ background: rgba(7, 192, 95, 0.12);}}&.multi-turn {- background: rgba(0, 82, 217, 0.1);- color: #0052d9;- border: 1px solid rgba(0, 82, 217, 0.2);+ background: rgba(59, 130, 246, 0.08);+ color: #3b82f6;&:hover {- background: rgba(0, 82, 217, 0.15);+ background: rgba(59, 130, 246, 0.12);}}}.card-time {- color: #00000066;+ color: #999;font-family: "PingFang SC";font-size: 12px;font-weight: 400;diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vueindex 785c70307..d59a25939 100644--- a/frontend/src/views/knowledge/KnowledgeBaseList.vue+++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue@@ -116,23 +116,14 @@<!-- 卡片底部 --><div class="card-bottom"><div class="bottom-left">- <div class="type-badge" :class="{ 'document': (kb.type || 'document') === 'document', 'faq': kb.type === 'faq' }">- <t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" size="14px" />- <span>- {{ kb.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument') }}- ({{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }})- </span>- <t-tooltip- v-if="kb.isProcessing"- :content="kb.type === 'document' && (kb.processing_count || 0) > 0- ? $t('knowledgeList.processingDocuments', { count: kb.processing_count || 0 })- : $t('knowledgeList.processing')"- placement="top"- >- <t-icon name="loading" size="14px" class="processing-icon" />- </t-tooltip>- </div><div class="feature-badges">+ <t-tooltip :content="kb.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument')" placement="top">+ <div class="feature-badge" :class="{ 'type-document': (kb.type || 'document') === 'document', 'type-faq': kb.type === 'faq' }">+ <t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" size="14px" />+ <span class="badge-count">{{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }}</span>+ <t-icon v-if="kb.isProcessing" name="loading" size="12px" class="processing-icon" />+ </div>+ </t-tooltip><t-tooltip v-if="kb.extract_config?.enabled" :content="$t('knowledgeList.features.knowledgeGraph')" placement="top"><div class="feature-badge kg"><t-icon name="relation" size="14px" />@@ -700,27 +691,28 @@ const handleUploadFinishedEvent = (event: Event) => {.kb-card-wrap {display: grid;- gap: 20px;+ gap: 16px;grid-template-columns: 1fr;}.kb-card {- border: 2px solid #fbfbfb;- border-radius: 6px;+ border: 1px solid #f0f0f0;+ border-radius: 12px;overflow: hidden;box-sizing: border-box;- box-shadow: 0 0 8px 0 #00000005;+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);background: #fff;position: relative;cursor: pointer;- transition: all 0.2s ease;- padding: 12px 16px 14px;+ transition: all 0.25s ease;+ padding: 16px 18px;display: flex;flex-direction: column;- min-height: 150px;+ height: 160px;&:hover {border-color: #07c05f;+ box-shadow: 0 4px 12px rgba(7, 192, 95, 0.12);}&.uninitialized {@@ -731,12 +723,12 @@ const handleUploadFinishedEvent = (event: Event) => {&.kb-type-document {background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);border-color: #e8f5ed;-+&:hover {border-color: #07c05f;background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);}-+// 右上角装饰&::after {content: '';@@ -746,7 +738,7 @@ const handleUploadFinishedEvent = (event: Event) => {width: 60px;height: 60px;background: linear-gradient(135deg, rgba(7, 192, 95, 0.08) 0%, transparent 100%);- border-radius: 0 6px 0 100%;+ border-radius: 0 12px 0 100%;pointer-events: none;z-index: 0;}@@ -756,12 +748,13 @@ const handleUploadFinishedEvent = (event: Event) => {&.kb-type-faq {background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);border-color: #e6f0ff;-+&:hover {border-color: #0052d9;+ box-shadow: 0 4px 12px rgba(0, 82, 217, 0.12);background: linear-gradient(135deg, #ffffff 0%, #eff6ff 100%);}-+// 右上角装饰&::after {content: '';@@ -771,7 +764,7 @@ const handleUploadFinishedEvent = (event: Event) => {width: 60px;height: 60px;background: linear-gradient(135deg, rgba(0, 82, 217, 0.08) 0%, transparent 100%);- border-radius: 0 6px 0 100%;+ border-radius: 0 12px 0 100%;pointer-events: none;z-index: 0;}@@ -790,42 +783,46 @@ const handleUploadFinishedEvent = (event: Event) => {display: flex;justify-content: space-between;align-items: center;- margin-bottom: 8px;+ margin-bottom: 10px;}.card-title {- color: #000000e6;+ color: #1a1a1a;font-family: "PingFang SC";- font-size: 14px;+ font-size: 15px;font-weight: 600;line-height: 22px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;flex: 1;- margin-right: 8px;+ min-width: 0;}.more-wrap {display: flex;- width: 32px;- height: 32px;+ width: 28px;+ height: 28px;justify-content: center;align-items: center;border-radius: 6px;cursor: pointer;flex-shrink: 0;transition: all 0.2s ease;- opacity: 0.7;+ opacity: 0;++ .kb-card:hover & {+ opacity: 0.6;+ }&:hover {- background: rgba(0, 0, 0, 0.06);- opacity: 1;+ background: rgba(0, 0, 0, 0.05);+ opacity: 1 !important;}&.active-more {- background: rgba(0, 0, 0, 0.08);- opacity: 1;+ background: rgba(0, 0, 0, 0.06);+ opacity: 1 !important;}.more-icon {@@ -836,7 +833,8 @@ const handleUploadFinishedEvent = (event: Event) => {.card-content {flex: 1;- margin-bottom: 10px;+ margin-bottom: 12px;+ overflow: hidden;}.card-description {@@ -845,21 +843,20 @@ const handleUploadFinishedEvent = (event: Event) => {-webkit-line-clamp: 2;line-clamp: 2;overflow: hidden;- color: #00000066;+ color: #666;font-family: "PingFang SC";- font-size: 12px;+ font-size: 13px;font-weight: 400;line-height: 20px;- min-height: 40px;}.card-bottom {display: flex;align-items: center;justify-content: space-between;- padding: 8px 0 0;- border-top: 1px solid #f0f0f0;margin-top: auto;+ padding-top: 12px;+ border-top: 1px solid #f0f0f0;}.bottom-left {@@ -868,88 +865,90 @@ const handleUploadFinishedEvent = (event: Event) => {gap: 8px;}-.type-badge {- display: inline-flex;+.feature-badges {+ display: flex;align-items: center;gap: 4px;- padding: 3px 10px;- border-radius: 4px;- font-family: "PingFang SC";- font-size: 12px;- font-weight: 500;- line-height: 18px;+}- &.document {- background: rgba(7, 192, 95, 0.1);+.feature-badge {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 26px;+ height: 26px;+ border-radius: 6px;+ cursor: default;+ transition: background 0.2s ease;++ &.type-document {+ background: rgba(7, 192, 95, 0.08);color: #059669;- border: 1px solid rgba(7, 192, 95, 0.2);- }+ width: auto;+ padding: 0 8px;+ gap: 4px;- &.faq {- background: rgba(0, 82, 217, 0.1);- color: #0052d9;- border: 1px solid rgba(0, 82, 217, 0.2);- }+ &:hover {+ background: rgba(7, 192, 95, 0.12);+ }- .processing-icon {- animation: spin 1s linear infinite;- margin-left: 4px;- }+ .badge-count {+ font-size: 12px;+ font-weight: 500;+ }- &.document .processing-icon {- color: #059669;+ .processing-icon {+ animation: spin 1s linear infinite;+ }}- &.faq .processing-icon {+ &.type-faq {+ background: rgba(0, 82, 217, 0.08);color: #0052d9;- }-}+ width: auto;+ padding: 0 8px;+ gap: 4px;-.feature-badges {- display: flex;- align-items: center;- gap: 6px;-}+ &:hover {+ background: rgba(0, 82, 217, 0.12);+ }-.feature-badge {- display: flex;- align-items: center;- justify-content: center;- width: 24px;- height: 24px;- border-radius: 4px;- cursor: pointer;+ .badge-count {+ font-size: 12px;+ font-weight: 500;+ }++ .processing-icon {+ animation: spin 1s linear infinite;+ }+ }&.kg {- background: rgba(124, 77, 255, 0.1);+ background: rgba(124, 77, 255, 0.08);color: #7c4dff;- border: 1px solid rgba(124, 77, 255, 0.2);&:hover {- background: rgba(124, 77, 255, 0.15);+ background: rgba(124, 77, 255, 0.12);}}&.multimodal {- background: rgba(255, 152, 0, 0.1);- color: #ff9800;- border: 1px solid rgba(255, 152, 0, 0.2);+ background: rgba(255, 152, 0, 0.08);+ color: #f59e0b;&:hover {- background: rgba(255, 152, 0, 0.15);+ background: rgba(255, 152, 0, 0.12);}}&.question {- background: rgba(0, 150, 136, 0.1);+ background: rgba(0, 150, 136, 0.08);color: #009688;- border: 1px solid rgba(0, 150, 136, 0.2);&:hover {- background: rgba(0, 150, 136, 0.15);+ background: rgba(0, 150, 136, 0.12);}}-}@keyframes spin {@@ -986,7 +985,7 @@ const handleUploadFinishedEvent = (event: Event) => {}.card-time {- color: #00000066;+ color: #999;font-family: "PingFang SC";font-size: 12px;font-weight: 400;diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vueindex d941db074..f6f7d2536 100644--- a/frontend/src/views/settings/Settings.vue+++ b/frontend/src/views/settings/Settings.vue@@ -89,11 +89,6 @@<OllamaSettings /></div>- <!-- Agent 配置 -->- <div v-if="currentSection === 'agent'" class="section">- <AgentSettings :active-sub-section="currentSubSection || 'modes'" />- </div>-<!-- 网络搜索配置 --><div v-if="currentSection === 'websearch'" class="section"><WebSearchSettings />@@ -132,7 +127,6 @@ import { ref, computed, watch, onMounted, onUnmounted } from 'vue'import { useRoute, useRouter } from 'vue-router'import { useUIStore } from '@/stores/ui'import { useI18n } from 'vue-i18n'-import AgentSettings from './AgentSettings.vue'import SystemInfo from './SystemInfo.vue'import TenantInfo from './TenantInfo.vue'import ApiInfo from './ApiInfo.vue'@@ -165,17 +159,6 @@ const navItems = computed(() => []},{ key: 'ollama', icon: 'server', label: 'Ollama' },- {- key: 'agent',- icon: 'chat',- label: t('settings.conversationStrategy'),- children: [- { key: 'modes', label: t('conversationSettings.menus.modes') },- { key: 'models', label: t('conversationSettings.menus.models') },- { key: 'thresholds', label: t('conversationSettings.menus.thresholds') },- { key: 'advanced', label: t('conversationSettings.menus.advanced') },- ]- },{ key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },{ key: 'system', icon: 'info-circle', label: t('settings.systemSettings') },diff --git a/internal/agent/prompts.go b/internal/agent/prompts.goindex ea60f3930..8db881d60 100644--- a/internal/agent/prompts.go+++ b/internal/agent/prompts.go@@ -4,6 +4,8 @@ import ("fmt""strings""time"++ "github.com/Tencent/WeKnora/internal/types")// formatFileSize formats file size in human-readable format@@ -78,6 +80,7 @@ type KnowledgeBaseInfo struct {}// PlaceholderDefinition defines a placeholder exposed to UI/configuration+// Deprecated: Use types.PromptPlaceholder insteadtype PlaceholderDefinition struct {Name string `json:"name"`Label string `json:"label"`@@ -85,24 +88,19 @@ type PlaceholderDefinition struct {}// AvailablePlaceholders lists all supported prompt placeholders for UI hints+// This returns agent mode specific placeholdersfunc AvailablePlaceholders() []PlaceholderDefinition {- return []PlaceholderDefinition{- {- Name: "knowledge_bases",- Label: "知识库列表",- Description: "自动格式化为表格形式的知识库列表,包含知识库名称、描述、文档数量、最近添加的文档等信息",- },- {- Name: "web_search_status",- Label: "网络检索模式开关状态",- Description: "网络检索(web_search)工具是否启用的状态说明,值为 Enabled 或 Disabled",- },- {- Name: "current_time",- Label: "当前系统时间",- Description: "格式为 RFC3339 的当前系统时间,用于帮助模型感知实时性",- },+ // Use centralized placeholder definitions from types package+ placeholders := types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt)+ result := make([]PlaceholderDefinition, len(placeholders))+ for i, p := range placeholders {+ result[i] = PlaceholderDefinition{+ Name: p.Name,+ Label: p.Label,+ Description: p.Description,+ }}+ return result}// formatKnowledgeBaseList formats knowledge base information for the promptdiff --git a/internal/application/repository/custom_agent.go b/internal/application/repository/custom_agent.goindex 5a8a339f6..02a41c5ba 100644--- a/internal/application/repository/custom_agent.go+++ b/internal/application/repository/custom_agent.go@@ -57,6 +57,6 @@ func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.Cu}// DeleteAgent deletes an agent (soft delete)-func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string) error {- return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.CustomAgent{}).Error+func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string, tenantID uint64) error {+ return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.CustomAgent{}).Error}diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 1c707c136..1e3f42a0a 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -101,25 +101,51 @@ func (s *agentService) CreateAgentEngine(tenantID = tid}if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil {- // Get enabled MCP services for this tenant- mcpServices, err := s.mcpServiceService.ListMCPServices(ctx, tenantID)- if err != nil {- logger.Warnf(ctx, "Failed to list MCP services: %v", err)+ // Check MCP selection mode from agent config+ mcpMode := config.MCPSelectionMode+ if mcpMode == "" {+ mcpMode = "all" // Default to all enabled MCP services+ }++ // Skip MCP registration if mode is "none"+ if mcpMode == "none" {+ logger.Infof(ctx, "MCP services disabled by agent config (mode: none)")} else {- // Filter enabled services- enabledServices := make([]*types.MCPService, 0)- for _, svc := range mcpServices {- if svc != nil && svc.Enabled {- enabledServices = append(enabledServices, svc)+ var mcpServices []*types.MCPService+ var err error++ if mcpMode == "selected" && len(config.MCPServices) > 0 {+ // Get only selected MCP services+ mcpServices, err = s.mcpServiceService.ListMCPServicesByIDs(ctx, tenantID, config.MCPServices)+ if err != nil {+ logger.Warnf(ctx, "Failed to list selected MCP services: %v", err)+ } else {+ logger.Infof(ctx, "Using %d selected MCP services from agent config", len(mcpServices))+ }+ } else {+ // Get all MCP services for this tenant+ mcpServices, err = s.mcpServiceService.ListMCPServices(ctx, tenantID)+ if err != nil {+ logger.Warnf(ctx, "Failed to list MCP services: %v", err)}}- // Register MCP tools- if len(enabledServices) > 0 {- if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {- logger.Warnf(ctx, "Failed to register MCP tools: %v", err)- } else {- logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))+ if err == nil && len(mcpServices) > 0 {+ // Filter enabled services+ enabledServices := make([]*types.MCPService, 0)+ for _, svc := range mcpServices {+ if svc != nil && svc.Enabled {+ enabledServices = append(enabledServices, svc)+ }+ }++ // Register MCP tools+ if len(enabledServices) > 0 {+ if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {+ logger.Warnf(ctx, "Failed to register MCP tools: %v", err)+ } else {+ logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))+ }}}}diff --git a/internal/application/service/chat_pipline/common.go b/internal/application/service/chat_pipline/common.goindex dcda8d305..5e2e4e46b 100644--- a/internal/application/service/chat_pipline/common.go+++ b/internal/application/service/chat_pipline/common.go@@ -60,13 +60,8 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {{Role: "system", Content: systemPrompt},}- chatHistory := chatManage.History- if len(chatHistory) > 2 {- chatHistory = chatHistory[len(chatHistory)-2:]- }-- // Add conversation history- for _, history := range chatHistory {+ // Add conversation history (already limited by maxRounds in load_history/rewrite plugins)+ for _, history := range chatManage.History {chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query})chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer})}diff --git a/internal/application/service/chat_pipline/load_history.go b/internal/application/service/chat_pipline/load_history.gonew file mode 100644index 000000000..4c3563c2c--- /dev/null+++ b/internal/application/service/chat_pipline/load_history.go@@ -0,0 +1,126 @@+// Package chatpipline provides chat pipeline processing capabilities+package chatpipline++import (+ "context"+ "regexp"+ "slices"+ "sort"++ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)++// PluginLoadHistory is a plugin for loading conversation history without query rewriting+// It loads historical dialog context for multi-turn conversations+type PluginLoadHistory struct {+ messageService interfaces.MessageService // Message service for retrieving historical messages+ config *config.Config // System configuration+}++// regThink is a regular expression used to match and remove content between <think></think> tags+var regThink = regexp.MustCompile(`(?s)<think>.*?</think>`)++// NewPluginLoadHistory creates a new history loading plugin instance+// Also registers the plugin with the event manager+func NewPluginLoadHistory(eventManager *EventManager,+ messageService interfaces.MessageService,+ config *config.Config,+) *PluginLoadHistory {+ res := &PluginLoadHistory{+ messageService: messageService,+ config: config,+ }+ eventManager.Register(res)+ return res+}++// ActivationEvents returns the list of event types this plugin responds to+// This plugin only responds to LOAD_HISTORY events+func (p *PluginLoadHistory) ActivationEvents() []types.EventType {+ return []types.EventType{types.LOAD_HISTORY}+}++// OnEvent processes triggered events+// When receiving a LOAD_HISTORY event, it loads conversation history without rewriting the query+func (p *PluginLoadHistory) OnEvent(ctx context.Context,+ eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,+) *PluginError {+ // Determine max rounds from config or request+ maxRounds := p.config.Conversation.MaxRounds+ if chatManage.MaxRounds > 0 {+ maxRounds = chatManage.MaxRounds+ }++ pipelineInfo(ctx, "LoadHistory", "input", map[string]interface{}{+ "session_id": chatManage.SessionID,+ "max_rounds": maxRounds,+ })++ // Get conversation history (fetch more to account for incomplete pairs)+ history, err := p.messageService.GetRecentMessagesBySession(ctx, chatManage.SessionID, maxRounds*2+10)+ if err != nil {+ pipelineWarn(ctx, "LoadHistory", "history_fetch", map[string]interface{}{+ "session_id": chatManage.SessionID,+ "error": err.Error(),+ })+ return next()+ }++ pipelineInfo(ctx, "LoadHistory", "fetched", map[string]interface{}{+ "session_id": chatManage.SessionID,+ "message_count": len(history),+ })++ // Convert historical messages to conversation history structure+ historyMap := make(map[string]*types.History)++ // Process historical messages, grouped by requestID+ for _, message := range history {+ h, ok := historyMap[message.RequestID]+ if !ok {+ h = &types.History{}+ }+ if message.Role == "user" {+ // User message as query+ h.Query = message.Content+ h.CreateAt = message.CreatedAt+ } else {+ // System message as answer, while removing thinking process+ h.Answer = regThink.ReplaceAllString(message.Content, "")+ h.KnowledgeReferences = message.KnowledgeReferences+ }+ historyMap[message.RequestID] = h+ }++ // Convert to list and filter incomplete conversations+ historyList := make([]*types.History, 0)+ for _, h := range historyMap {+ if h.Answer != "" && h.Query != "" {+ historyList = append(historyList, h)+ }+ }++ // Sort by time, keep the most recent conversations+ sort.Slice(historyList, func(i, j int) bool {+ return historyList[i].CreateAt.After(historyList[j].CreateAt)+ })++ // Limit the number of historical records+ if len(historyList) > maxRounds {+ historyList = historyList[:maxRounds]+ }++ // Reverse to chronological order+ slices.Reverse(historyList)+ chatManage.History = historyList++ pipelineInfo(ctx, "LoadHistory", "output", map[string]interface{}{+ "session_id": chatManage.SessionID,+ "history_rounds": len(historyList),+ "max_rounds": maxRounds,+ })++ return next()+}diff --git a/internal/application/service/chat_pipline/rewrite.go b/internal/application/service/chat_pipline/rewrite.goindex fbb82b6e7..16e6b5d9d 100644--- a/internal/application/service/chat_pipline/rewrite.go+++ b/internal/application/service/chat_pipline/rewrite.go@@ -3,12 +3,11 @@package chatpiplineimport (- "bytes""context"- "html/template""regexp""slices""sort"+ "strings""time""github.com/Tencent/WeKnora/internal/config"@@ -144,54 +143,27 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,if chatManage.RewritePromptUser != "" {userPrompt = chatManage.RewritePromptUser}- userTmpl, err := template.New("rewriteContent").Parse(userPrompt)- if err != nil {- pipelineError(ctx, "Rewrite", "parse_user_template", map[string]interface{}{- "session_id": chatManage.SessionID,- "error": err.Error(),- })- return next()- }systemPrompt := p.config.Conversation.RewritePromptSystemif chatManage.RewritePromptSystem != "" {systemPrompt = chatManage.RewritePromptSystem}- systemTmpl, err := template.New("rewriteContent").Parse(systemPrompt)- if err != nil {- pipelineError(ctx, "Rewrite", "parse_system_template", map[string]interface{}{- "session_id": chatManage.SessionID,- "error": err.Error(),- })- return next()- }++ // Format conversation history for template+ conversationText := formatConversationHistory(historyList)currentTime := time.Now().Format("2006-01-02 15:04:05")- var userContent, systemContent bytes.Buffer- err = userTmpl.Execute(&userContent, map[string]interface{}{- "Query": chatManage.Query,- "CurrentTime": currentTime,- "Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),- "Conversation": historyList,- })- if err != nil {- pipelineError(ctx, "Rewrite", "render_user_template", map[string]interface{}{- "session_id": chatManage.SessionID,- "error": err.Error(),- })- return next()- }- err = systemTmpl.Execute(&systemContent, map[string]interface{}{- "Query": chatManage.Query,- "CurrentTime": currentTime,- "Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),- "Conversation": historyList,- })- if err != nil {- pipelineError(ctx, "Rewrite", "render_system_template", map[string]interface{}{- "session_id": chatManage.SessionID,- "error": err.Error(),- })- return next()- }+ yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")++ // Replace placeholders in prompts+ userContent := strings.ReplaceAll(userPrompt, "{{conversation}}", conversationText)+ userContent = strings.ReplaceAll(userContent, "{{query}}", chatManage.Query)+ userContent = strings.ReplaceAll(userContent, "{{current_time}}", currentTime)+ userContent = strings.ReplaceAll(userContent, "{{yesterday}}", yesterday)++ systemContent := strings.ReplaceAll(systemPrompt, "{{conversation}}", conversationText)+ systemContent = strings.ReplaceAll(systemContent, "{{query}}", chatManage.Query)+ systemContent = strings.ReplaceAll(systemContent, "{{current_time}}", currentTime)+ systemContent = strings.ReplaceAll(systemContent, "{{yesterday}}", yesterday)+rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)if err != nil {pipelineError(ctx, "Rewrite", "get_model", map[string]interface{}{@@ -207,11 +179,11 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,response, err := rewriteModel.Chat(ctx, []chat.Message{{Role: "system",- Content: systemContent.String(),+ Content: systemContent,},{Role: "user",- Content: userContent.String(),+ Content: userContent,},}, &chat.ChatOptions{Temperature: 0.3,@@ -236,3 +208,21 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,})return next()}++// formatConversationHistory formats conversation history for prompt template+func formatConversationHistory(historyList []*types.History) string {+ if len(historyList) == 0 {+ return ""+ }++ var builder strings.Builder+ for _, h := range historyList {+ builder.WriteString("------BEGIN------\n")+ builder.WriteString("用户的问题是:")+ builder.WriteString(h.Query)+ builder.WriteString("\n助手的回答是:")+ builder.WriteString(h.Answer)+ builder.WriteString("\n------END------\n")+ }+ return builder.String()+}diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.goindex f375037cf..722a0479e 100644--- a/internal/application/service/custom_agent.go+++ b/internal/application/service/custom_agent.go@@ -56,9 +56,9 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custoagent.CreatedAt = time.Now()agent.UpdatedAt = time.Now()- // Ensure custom type for user-created agents- if agent.Type == "" {- agent.Type = types.CustomAgentTypeCustom+ // Ensure agent mode is set for user-created agents+ if agent.Config.AgentMode == "" {+ agent.Config.AgentMode = types.AgentModeQuickAnswer}// Cannot create built-in agents@@ -67,8 +67,8 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo// Set defaultsagent.EnsureDefaults()- logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, type: %s",- agent.ID, agent.TenantID, agent.Name, agent.Type)+ logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s",+ agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode)if err := s.repo.CreateAgent(ctx, agent); err != nil {logger.ErrorWithFields(ctx, err, map[string]interface{}{@@ -95,19 +95,18 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*typereturn nil, ErrInvalidTenantID}- // Check if it's a built-in agent- if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID {+ // Check if it's a built-in agent using the registry+ if types.IsBuiltinAgentID(id) {// Try to get from database first (for customized config)agent, err := s.repo.GetAgentByID(ctx, id, tenantID)if err == nil {// Found in database, return with customized configreturn agent, nil}- // Not in database, return default built-in agent- if id == types.BuiltinAgentNormalID {- return types.GetBuiltinNormalAgent(tenantID), nil+ // Not in database, return default built-in agent from registry+ if builtinAgent := types.GetBuiltinAgent(id, tenantID); builtinAgent != nil {+ return builtinAgent, nil}- return types.GetBuiltinAgentAgent(tenantID), nil}// Query from database@@ -141,48 +140,39 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAgereturn nil, err}- // Check if built-in agents exist in database- hasNormalBuiltin := false- hasAgentBuiltin := false+ // Track which built-in agents exist in database+ builtinInDB := make(map[string]bool)for _, agent := range allAgents {- if agent.ID == types.BuiltinAgentNormalID {- hasNormalBuiltin = true- }- if agent.ID == types.BuiltinAgentAgentID {- hasAgentBuiltin = true+ if types.IsBuiltinAgentID(agent.ID) {+ builtinInDB[agent.ID] = true}}// Build result: built-in agents first, then custom agents- result := make([]*types.CustomAgent, 0, len(allAgents)+2)-- // Add built-in normal agent- if hasNormalBuiltin {- for _, agent := range allAgents {- if agent.ID == types.BuiltinAgentNormalID {- result = append(result, agent)- break+ builtinIDs := types.GetBuiltinAgentIDs()+ result := make([]*types.CustomAgent, 0, len(allAgents)+len(builtinIDs))++ // Add built-in agents in order+ for _, builtinID := range builtinIDs {+ if builtinInDB[builtinID] {+ // Use customized config from database+ for _, agent := range allAgents {+ if agent.ID == builtinID {+ result = append(result, agent)+ break+ }}- }- } else {- result = append(result, types.GetBuiltinNormalAgent(tenantID))- }-- // Add built-in agent mode agent- if hasAgentBuiltin {- for _, agent := range allAgents {- if agent.ID == types.BuiltinAgentAgentID {+ } else {+ // Use default built-in agent+ if agent := types.GetBuiltinAgent(builtinID, tenantID); agent != nil {result = append(result, agent)- break}}- } else {- result = append(result, types.GetBuiltinAgentAgent(tenantID))}// Add custom agentsfor _, agent := range allAgents {- if agent.ID != types.BuiltinAgentNormalID && agent.ID != types.BuiltinAgentAgentID {+ if !types.IsBuiltinAgentID(agent.ID) {result = append(result, agent)}}@@ -203,9 +193,8 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custoreturn nil, ErrInvalidTenantID}- // Handle built-in agents specially- isBuiltinAgent := agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID- if isBuiltinAgent {+ // Handle built-in agents specially using registry+ if types.IsBuiltinAgentID(agent.ID) {return s.updateBuiltinAgent(ctx, agent, tenantID)}@@ -232,7 +221,6 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.CustoexistingAgent.Name = agent.NameexistingAgent.Description = agent.DescriptionexistingAgent.Avatar = agent.Avatar- existingAgent.Type = agent.TypeexistingAgent.Config = agent.ConfigexistingAgent.UpdatedAt = time.Now()@@ -254,12 +242,10 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo// updateBuiltinAgent updates a built-in agent's configuration (but not basic info)func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) {- // Get the default built-in agent- var defaultAgent *types.CustomAgent- if agent.ID == types.BuiltinAgentNormalID {- defaultAgent = types.GetBuiltinNormalAgent(tenantID)- } else {- defaultAgent = types.GetBuiltinAgentAgent(tenantID)+ // Get the default built-in agent from registry+ defaultAgent := types.GetBuiltinAgent(agent.ID, tenantID)+ if defaultAgent == nil {+ return nil, ErrAgentNotFound}// Try to get existing customized config from database@@ -294,7 +280,6 @@ func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *typeDescription: defaultAgent.Description,Avatar: defaultAgent.Avatar,IsBuiltin: true,- Type: defaultAgent.Type,TenantID: tenantID,Config: agent.Config,CreatedAt: time.Now(),@@ -323,8 +308,8 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {return errors.New("agent ID cannot be empty")}- // Cannot delete built-in agents- if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID {+ // Cannot delete built-in agents using registry check+ if types.IsBuiltinAgentID(id) {return ErrCannotDeleteBuiltin}@@ -350,7 +335,7 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {logger.Infof(ctx, "Deleting custom agent, ID: %s", id)- if err := s.repo.DeleteAgent(ctx, id); err != nil {+ if err := s.repo.DeleteAgent(ctx, id, tenantID); err != nil {logger.ErrorWithFields(ctx, err, map[string]interface{}{"agent_id": id,})@@ -360,3 +345,52 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id)return nil}++// CopyAgent creates a copy of an existing agent+func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error) {+ if id == "" {+ logger.Error(ctx, "Agent ID is empty")+ return nil, errors.New("agent ID cannot be empty")+ }++ // Get tenant ID from context+ tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)+ if !ok {+ return nil, ErrInvalidTenantID+ }++ // Get the source agent+ sourceAgent, err := s.GetAgentByID(ctx, id)+ if err != nil {+ return nil, err+ }++ // Create a new agent with copied data+ newAgent := &types.CustomAgent{+ ID: uuid.New().String(),+ Name: sourceAgent.Name + " (副本)",+ Description: sourceAgent.Description,+ Avatar: sourceAgent.Avatar,+ IsBuiltin: false, // Copied agents are never built-in+ TenantID: tenantID,+ Config: sourceAgent.Config,+ CreatedAt: time.Now(),+ UpdatedAt: time.Now(),+ }++ // Ensure defaults+ newAgent.EnsureDefaults()++ logger.Infof(ctx, "Copying agent, source ID: %s, new ID: %s", id, newAgent.ID)++ if err := s.repo.CreateAgent(ctx, newAgent); err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{+ "source_agent_id": id,+ "new_agent_id": newAgent.ID,+ })+ return nil, err+ }++ logger.Infof(ctx, "Agent copied successfully, source ID: %s, new ID: %s", id, newAgent.ID)+ return newAgent, nil+}diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.goindex 9ca706bba..096e098f4 100644--- a/internal/application/service/knowledge.go+++ b/internal/application/service/knowledge.go@@ -1956,10 +1956,10 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,}// Replace placeholders- prompt = strings.ReplaceAll(prompt, "{{.QuestionCount}}", fmt.Sprintf("%d", questionCount))- prompt = strings.ReplaceAll(prompt, "{{.Content}}", content)- prompt = strings.ReplaceAll(prompt, "{{.Context}}", contextSection)- prompt = strings.ReplaceAll(prompt, "{{.DocName}}", docName)+ prompt = strings.ReplaceAll(prompt, "{{question_count}}", fmt.Sprintf("%d", questionCount))+ prompt = strings.ReplaceAll(prompt, "{{content}}", content)+ prompt = strings.ReplaceAll(prompt, "{{context}}", contextSection)+ prompt = strings.ReplaceAll(prompt, "{{doc_name}}", docName)thinking := falseresponse, err := chatModel.Chat(ctx, []chat.Message{@@ -2000,11 +2000,11 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,// Default prompt for question generation with context supportconst defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。-{{.Context}}+{{context}}## 主要内容(请基于此内容生成问题)-文档名称:{{.DocName}}+文档名称:{{doc_name}}文档内容:-{{.Content}}+{{content}}## 核心要求- 生成的问题必须与【主要内容】直接相关@@ -2013,7 +2013,7 @@ const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手- 问题应该是用户在实际场景中可能会提出的自然问题- 问题应该多样化,覆盖内容的不同方面- 每个问题应该简洁明了,长度控制在30字以内-- 生成的问题数量为 {{.QuestionCount}} 个+- 生成的问题数量为 {{question_count}} 个## 问题类型建议- 定义类:什么是...?...是什么?diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex c6386f927..c0f311cfb 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -1,13 +1,11 @@package serviceimport (- "bytes""context""encoding/json""errors""fmt""strings"- "text/template""github.com/Tencent/WeKnora/internal/agent""github.com/Tencent/WeKnora/internal/agent/tools"@@ -271,7 +269,7 @@ func (s *sessionService) GenerateTitle(ctx context.Context,if model == nil {continue}- if model.Type == types.ModelTypeKnowledgeQA {+ if model.Type == types.ModelTypeKnowledgeQA {modelID = model.IDlogger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID)break@@ -469,6 +467,11 @@ func (s *sessionService) KnowledgeQA(// Ensure defaults are setcustomAgent.EnsureDefaults()+ // Override model ID+ if customAgent.Config.ModelID != "" {+ chatModelID = customAgent.Config.ModelID+ logger.Infof(ctx, "Using custom agent's model_id: %s", chatModelID)+ }// Override system promptif customAgent.Config.SystemPrompt != "" {summaryConfig.Prompt = customAgent.Config.SystemPrompt@@ -588,10 +591,18 @@ func (s *sessionService) KnowledgeQA(// Otherwise use rag_stream pipeline (which handles both KB search and web search)var pipeline []types.EventTypeif len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && !webSearchEnabled {- logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat_stream pipeline")- pipeline = types.Pipline["chat_stream"]+ logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat pipeline")// For pure chat, UserContent is the Query (since INTO_CHAT_MESSAGE is skipped)chatManage.UserContent = query++ // Use chat_history_stream if multi-turn is enabled, otherwise use chat_stream+ if maxRounds > 0 {+ logger.Infof(ctx, "Multi-turn enabled with maxRounds=%d, using chat_history_stream pipeline", maxRounds)+ pipeline = types.Pipline["chat_history_stream"]+ } else {+ logger.Info(ctx, "Multi-turn disabled, using chat_stream pipeline")+ pipeline = types.Pipline["chat_stream"]+ }} else {if webSearchEnabled && len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 {logger.Info(ctx, "Web search enabled without knowledge bases, using rag_stream pipeline for web search only")@@ -1057,6 +1068,8 @@ func (s *sessionService) AgentQA(MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,HistoryTurns: customAgent.Config.HistoryTurns,KnowledgeBases: customAgent.Config.KnowledgeBases,+ MCPSelectionMode: customAgent.Config.MCPSelectionMode,+ MCPServices: customAgent.Config.MCPServices,}// Use custom agent's allowed tools if specified, otherwise use defaults@@ -1442,20 +1455,9 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty// renderFallbackPrompt renders the fallback prompt template with Query variablefunc (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *types.ChatManage) (string, error) {- tmpl, err := template.New("fallbackPrompt").Parse(chatManage.FallbackPrompt)- if err != nil {- return "", fmt.Errorf("failed to parse template: %w", err)- }-- var promptContent bytes.Buffer- err = tmpl.Execute(&promptContent, map[string]interface{}{- "Query": chatManage.Query,- })- if err != nil {- return "", fmt.Errorf("failed to execute template: %w", err)- }-- return promptContent.String(), nil+ // Use simple string replacement instead of Go template+ result := strings.ReplaceAll(chatManage.FallbackPrompt, "{{query}}", chatManage.Query)+ return result, nil}// consumeFallbackStream consumes the streaming response and emits eventsdiff --git a/internal/container/container.go b/internal/container/container.goindex 45d7720ec..d99204329 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -145,6 +145,7 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Invoke(chatpipline.NewPluginStreamFilter))must(container.Invoke(chatpipline.NewPluginFilterTopK))must(container.Invoke(chatpipline.NewPluginRewrite))+ must(container.Invoke(chatpipline.NewPluginLoadHistory))must(container.Invoke(chatpipline.NewPluginExtractEntity))must(container.Invoke(chatpipline.NewPluginSearchEntity))must(container.Invoke(chatpipline.NewPluginSearchParallel))diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.goindex 1eb2f39df..ce6cae98a 100644--- a/internal/handler/custom_agent.go+++ b/internal/handler/custom_agent.go@@ -29,7 +29,6 @@ type CreateAgentRequest struct {Name string `json:"name" binding:"required"`Description string `json:"description"`Avatar string `json:"avatar"`- Type types.CustomAgentType `json:"type"`Config types.CustomAgentConfig `json:"config"`}@@ -38,7 +37,6 @@ type UpdateAgentRequest struct {Name string `json:"name"`Description string `json:"description"`Avatar string `json:"avatar"`- Type types.CustomAgentType `json:"type"`Config types.CustomAgentConfig `json:"config"`}@@ -72,12 +70,11 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {Name: req.Name,Description: req.Description,Avatar: req.Avatar,- Type: req.Type,Config: req.Config,}- logger.Infof(ctx, "Creating custom agent, name: %s, type: %s",- secutils.SanitizeForLog(req.Name), req.Type)+ logger.Infof(ctx, "Creating custom agent, name: %s, agent_mode: %s",+ secutils.SanitizeForLog(req.Name), req.Config.AgentMode)// Create agent using the servicecreatedAgent, err := h.service.CreateAgent(ctx, agent)@@ -211,7 +208,6 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {Name: req.Name,Description: req.Description,Avatar: req.Avatar,- Type: req.Type,Config: req.Config,}@@ -296,3 +292,80 @@ func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) {"message": "Agent deleted successfully",})}++// CopyAgent godoc+// @Summary 复制智能体+// @Description 复制指定的智能体+// @Tags 智能体+// @Accept json+// @Produce json+// @Param id path string true "智能体ID"+// @Success 201 {object} map[string]interface{} "复制成功"+// @Failure 400 {object} errors.AppError "请求参数错误"+// @Failure 404 {object} errors.AppError "智能体不存在"+// @Security Bearer+// @Security ApiKeyAuth+// @Router /agents/{id}/copy [post]+func (h *CustomAgentHandler) CopyAgent(c *gin.Context) {+ ctx := c.Request.Context()++ logger.Info(ctx, "Start copying custom agent")++ // Get agent ID from URL parameter+ id := secutils.SanitizeForLog(c.Param("id"))+ if id == "" {+ logger.Error(ctx, "Agent ID is empty")+ c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))+ return+ }++ logger.Infof(ctx, "Copying custom agent, ID: %s", secutils.SanitizeForLog(id))++ // Copy the agent+ copiedAgent, err := h.service.CopyAgent(ctx, id)+ if err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{+ "agent_id": id,+ })+ switch err {+ case service.ErrAgentNotFound:+ c.Error(errors.NewNotFoundError("Agent not found"))+ default:+ c.Error(errors.NewInternalServerError(err.Error()))+ }+ return+ }++ logger.Infof(ctx, "Custom agent copied successfully, source ID: %s, new ID: %s",+ secutils.SanitizeForLog(id), secutils.SanitizeForLog(copiedAgent.ID))+ c.JSON(http.StatusCreated, gin.H{+ "success": true,+ "data": copiedAgent,+ })+}++// GetPlaceholders godoc+// @Summary 获取占位符定义+// @Description 获取所有可用的提示词占位符定义,按字段类型分组+// @Tags 智能体+// @Accept json+// @Produce json+// @Success 200 {object} map[string]interface{} "占位符定义"+// @Security Bearer+// @Security ApiKeyAuth+// @Router /agents/placeholders [get]+func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {+ // Return all placeholder definitions grouped by field type+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": gin.H{+ "all": types.AllPlaceholders(),+ "system_prompt": types.PlaceholdersByField(types.PromptFieldSystemPrompt),+ "agent_system_prompt": types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt),+ "context_template": types.PlaceholdersByField(types.PromptFieldContextTemplate),+ "rewrite_system_prompt": types.PlaceholdersByField(types.PromptFieldRewriteSystemPrompt),+ "rewrite_prompt": types.PlaceholdersByField(types.PromptFieldRewritePrompt),+ "fallback_prompt": types.PlaceholdersByField(types.PromptFieldFallbackPrompt),+ },+ })+}diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.goindex d5254c546..ef0ad37d3 100644--- a/internal/handler/session/qa.go+++ b/internal/handler/session/qa.go@@ -81,8 +81,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCosecutils.SanitizeForLog(request.AgentID), err)} else {customAgent = agent- logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, Type=%s, AgentMode=%s",- customAgent.ID, customAgent.Name, customAgent.Type, customAgent.Config.AgentMode)+ logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s",+ customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode)}}diff --git a/internal/router/router.go b/internal/router/router.goindex 40d53704e..14f6bcb82 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -417,6 +417,8 @@ func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSefunc RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) {agents := r.Group("/agents"){+ // Get placeholder definitions (must be before /:id to avoid conflict)+ agents.GET("/placeholders", agentHandler.GetPlaceholders)// Create custom agentagents.POST("", agentHandler.CreateAgent)// List all agents (including built-in)@@ -427,5 +429,7 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAagents.PUT("/:id", agentHandler.UpdateAgent)// Delete agentagents.DELETE("/:id", agentHandler.DeleteAgent)+ // Copy agent+ agents.POST("/:id/copy", agentHandler.CopyAgent)}}diff --git a/internal/types/agent.go b/internal/types/agent.goindex e9b1c0202..c6c118d48 100644--- a/internal/types/agent.go+++ b/internal/types/agent.go@@ -24,6 +24,9 @@ type AgentConfig struct {MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabledHistoryTurns int `json:"history_turns"` // Number of history turns to keep in contextSearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)+ // MCP service selection+ MCPSelectionMode string `json:"mcp_selection_mode"` // MCP selection mode: "all", "selected", "none"+ MCPServices []string `json:"mcp_services"` // Selected MCP service IDs (when mode is "selected")}// SessionAgentConfig represents session-level agent configurationdiff --git a/internal/types/chat_manage.go b/internal/types/chat_manage.goindex 22bf529a4..fc8dc128d 100644--- a/internal/types/chat_manage.go+++ b/internal/types/chat_manage.go@@ -124,6 +124,7 @@ func (c *ChatManage) Clone() *ChatManage {type EventType stringconst (+ LOAD_HISTORY EventType = "load_history" // Load conversation history without rewritingREWRITE_QUERY EventType = "rewrite_query" // Query rewriting for better retrievalCHUNK_SEARCH EventType = "chunk_search" // Search for relevant chunksCHUNK_SEARCH_PARALLEL EventType = "chunk_search_parallel" // Parallel search: chunks + entities@@ -142,7 +143,12 @@ var Pipline = map[string][]EventType{"chat": { // Simple chat without retrievalCHAT_COMPLETION,},- "chat_stream": { // Streaming chat without retrieval+ "chat_stream": { // Streaming chat without retrieval (no history)+ CHAT_COMPLETION_STREAM,+ STREAM_FILTER,+ },+ "chat_history_stream": { // Streaming chat with conversation history+ LOAD_HISTORY,CHAT_COMPLETION_STREAM,STREAM_FILTER,},diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.goindex b3d0b4463..52ff65797 100644--- a/internal/types/custom_agent.go+++ b/internal/types/custom_agent.go@@ -8,27 +8,27 @@ import ("gorm.io/gorm")-// CustomAgentType represents the type of the custom agent-type CustomAgentType string-+// BuiltinAgentID constants for built-in agentsconst (- // CustomAgentTypeNormal represents the normal RAG-based chat mode- CustomAgentTypeNormal CustomAgentType = "normal"- // CustomAgentTypeAgent represents the ReAct agent mode with tool calling- CustomAgentTypeAgent CustomAgentType = "agent"- // CustomAgentTypeCustom represents user-defined custom agents- CustomAgentTypeCustom CustomAgentType = "custom"+ // BuiltinQuickAnswerID is the ID for the built-in quick answer (RAG) agent+ BuiltinQuickAnswerID = "builtin-quick-answer"+ // BuiltinSmartReasoningID is the ID for the built-in smart reasoning (ReAct) agent+ BuiltinSmartReasoningID = "builtin-smart-reasoning")-// BuiltinAgentID constants for built-in agents+// AgentMode constants for agent running modeconst (- BuiltinAgentNormalID = "builtin-normal"- BuiltinAgentAgentID = "builtin-agent"+ // AgentModeQuickAnswer is the RAG mode for quick Q&A+ AgentModeQuickAnswer = "quick-answer"+ // AgentModeSmartReasoning is the ReAct mode for multi-step reasoning+ AgentModeSmartReasoning = "smart-reasoning")// CustomAgent represents a configurable AI agent (similar to GPTs)type CustomAgent struct {- // Unique identifier of the agent+ // Unique identifier of the agent (composite primary key with TenantID)+ // For built-in agents, this is 'builtin-quick-answer' or 'builtin-smart-reasoning'+ // For custom agents, this is a UUIDID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`// Name of the agentName string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`@@ -38,10 +38,8 @@ type CustomAgent struct {Avatar string `yaml:"avatar" json:"avatar" gorm:"type:varchar(64)"`// Whether this is a built-in agent (normal mode / agent mode)IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"`- // Type of the agent: normal, agent, custom- Type CustomAgentType `yaml:"type" json:"type" gorm:"type:varchar(32);default:'custom'"`- // Tenant ID- TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"index"`+ // Tenant ID (composite primary key with ID)+ TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"primaryKey"`// Created by user IDCreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"`@@ -57,7 +55,7 @@ type CustomAgent struct {// CustomAgentConfig represents the configuration of a custom agenttype CustomAgentConfig struct {// ===== Basic Settings =====- // Agent mode: "normal" for RAG mode, "agent" for ReAct agent mode+ // Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent modeAgentMode string `yaml:"agent_mode" json:"agent_mode"`// System prompt for the agent (for normal mode, or agent mode when web search is disabled)SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`@@ -83,16 +81,16 @@ type CustomAgentConfig struct {AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"`// Whether reflection is enabled (only for agent type)ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`+ // MCP service selection mode: "all" = all enabled MCP services, "selected" = specific services, "none" = no MCP+ MCPSelectionMode string `yaml:"mcp_selection_mode" json:"mcp_selection_mode"`+ // Selected MCP service IDs (only used when MCPSelectionMode is "selected")+ MCPServices []string `yaml:"mcp_services" json:"mcp_services"`// ===== Knowledge Base Settings =====// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KBKBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`// Associated knowledge base IDs (only used when KBSelectionMode is "selected")KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"`- // Whether to allow user to select knowledge bases during conversation- // If true, user can select from available KBs (all or selected based on KBSelectionMode)- // If false, the configured KBs are used automatically without user selection- AllowUserKBSelection *bool `yaml:"allow_user_kb_selection" json:"allow_user_kb_selection"`// ===== Web Search Settings =====// Whether web search is enabled@@ -162,9 +160,6 @@ func (a *CustomAgent) EnsureDefaults() {if a == nil {return}- if a.Type == "" {- a.Type = CustomAgentTypeCustom- }if a.Config.Temperature == 0 {a.Config.Temperature = 0.7}@@ -204,33 +199,33 @@ func (a *CustomAgent) EnsureDefaults() {// IsAgentMode returns true if this agent uses ReAct agent modefunc (a *CustomAgent) IsAgentMode() bool {- return a.Config.AgentMode == "agent"+ return a.Config.AgentMode == AgentModeSmartReasoning}-// GetBuiltinNormalAgent returns the built-in normal mode agent-func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {+// GetBuiltinQuickAnswerAgent returns the built-in quick answer (RAG) mode agent+func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {return &CustomAgent{- ID: BuiltinAgentNormalID,- Name: "普通模式",+ ID: BuiltinQuickAnswerID,+ Name: "快速问答",Description: "基于知识库的 RAG 问答,快速准确地回答问题",- Avatar: "💬",IsBuiltin: true,- Type: CustomAgentTypeNormal,TenantID: tenantID,Config: CustomAgentConfig{- AgentMode: "normal",- SystemPrompt: "",- Temperature: 0.7,- MaxCompletionTokens: 2048,- WebSearchEnabled: false,- MultiTurnEnabled: true,- HistoryTurns: 5,+ AgentMode: AgentModeQuickAnswer,+ SystemPrompt: "",+ Temperature: 0.7,+ MaxCompletionTokens: 2048,+ WebSearchEnabled: true,+ WebSearchMaxResults: 5,+ MultiTurnEnabled: true,+ HistoryTurns: 5,+ KBSelectionMode: "all",// Retrieval strategy- EmbeddingTopK: 10,- KeywordThreshold: 0.3,- VectorThreshold: 0.5,- RerankTopK: 5,- RerankThreshold: 0.5,+ EmbeddingTopK: 10,+ KeywordThreshold: 0.3,+ VectorThreshold: 0.5,+ RerankTopK: 10,+ RerankThreshold: 0.3,// Advanced settingsEnableQueryExpansion: true,EnableRewrite: true,@@ -239,21 +234,21 @@ func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {}}-// GetBuiltinAgentAgent returns the built-in agent mode agent-func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {+// GetBuiltinSmartReasoningAgent returns the built-in smart reasoning (ReAct) mode agent+func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {return &CustomAgent{- ID: BuiltinAgentAgentID,- Name: "Agent 模式",+ ID: BuiltinSmartReasoningID,+ Name: "智能推理",Description: "ReAct 推理框架,支持多步思考和工具调用",- Avatar: "🤖",IsBuiltin: true,- Type: CustomAgentTypeAgent,TenantID: tenantID,Config: CustomAgentConfig{- AgentMode: "agent",+ AgentMode: AgentModeSmartReasoning,SystemPrompt: "",Temperature: 0.7,- MaxIterations: 10,+ MaxCompletionTokens: 2048,+ MaxIterations: 50,+ KBSelectionMode: "all",AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},WebSearchEnabled: true,WebSearchMaxResults: 5,@@ -261,19 +256,50 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {MultiTurnEnabled: true,HistoryTurns: 5,// Retrieval strategy- EmbeddingTopK: 10,- KeywordThreshold: 0.3,- VectorThreshold: 0.5,- RerankTopK: 5,- RerankThreshold: 0.5,+ EmbeddingTopK: 10,+ KeywordThreshold: 0.3,+ VectorThreshold: 0.5,+ RerankTopK: 10,+ RerankThreshold: 0.3,},}}-// GetBuiltinAgents returns all built-in agents for a tenant-func GetBuiltinAgents(tenantID uint64) []*CustomAgent {- return []*CustomAgent{- GetBuiltinNormalAgent(tenantID),- GetBuiltinAgentAgent(tenantID),+// Deprecated: Use GetBuiltinQuickAnswerAgent instead+func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {+ return GetBuiltinQuickAnswerAgent(tenantID)+}++// Deprecated: Use GetBuiltinSmartReasoningAgent instead+func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {+ return GetBuiltinSmartReasoningAgent(tenantID)+}++// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension+var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{+ BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,+ BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,+}++// GetBuiltinAgentIDs returns all built-in agent IDs+func GetBuiltinAgentIDs() []string {+ ids := make([]string, 0, len(BuiltinAgentRegistry))+ for id := range BuiltinAgentRegistry {+ ids = append(ids, id)+ }+ return ids+}++// IsBuiltinAgentID checks if the given ID is a built-in agent ID+func IsBuiltinAgentID(id string) bool {+ _, exists := BuiltinAgentRegistry[id]+ return exists+}++// GetBuiltinAgent returns a built-in agent by ID, or nil if not found+func GetBuiltinAgent(id string, tenantID uint64) *CustomAgent {+ if factory, exists := BuiltinAgentRegistry[id]; exists {+ return factory(tenantID)}+ return nil}diff --git a/internal/types/interfaces/custom_agent.go b/internal/types/interfaces/custom_agent.goindex bf9a8c220..06c1c1a18 100644--- a/internal/types/interfaces/custom_agent.go+++ b/internal/types/interfaces/custom_agent.go@@ -52,6 +52,15 @@ type CustomAgentService interface {// Returns:// - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc.DeleteAgent(ctx context.Context, id string) error++ // CopyAgent creates a copy of an existing agent+ // Parameters:+ // - ctx: Context information+ // - id: Unique identifier of the agent to copy+ // Returns:+ // - The newly created agent copy+ // - Possible errors such as not existing, insufficient permissions, etc.+ CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error)}// CustomAgentRepository defines the custom agent repository interface@@ -96,7 +105,8 @@ type CustomAgentRepository interface {// Parameters:// - ctx: Context information// - id: Agent ID+ // - tenantID: Tenant ID for isolation (required for composite primary key)// Returns:// - Possible errors such as record not existing, database errors, etc.- DeleteAgent(ctx context.Context, id string) error+ DeleteAgent(ctx context.Context, id string, tenantID uint64) error}diff --git a/internal/types/placeholder.go b/internal/types/placeholder.gonew file mode 100644index 000000000..466c71b03--- /dev/null+++ b/internal/types/placeholder.go@@ -0,0 +1,165 @@+package types++// PromptPlaceholder represents a placeholder that can be used in prompt templates+type PromptPlaceholder struct {+ // Name is the placeholder name (without braces), e.g., "query"+ Name string `json:"name"`+ // Label is a short label for the placeholder+ Label string `json:"label"`+ // Description explains what this placeholder represents+ Description string `json:"description"`+}++// PromptFieldType represents the type of prompt field+type PromptFieldType string++const (+ // PromptFieldSystemPrompt is for system prompts (normal mode)+ PromptFieldSystemPrompt PromptFieldType = "system_prompt"+ // PromptFieldAgentSystemPrompt is for agent mode system prompts+ PromptFieldAgentSystemPrompt PromptFieldType = "agent_system_prompt"+ // PromptFieldContextTemplate is for context templates+ PromptFieldContextTemplate PromptFieldType = "context_template"+ // PromptFieldRewriteSystemPrompt is for rewrite system prompts+ PromptFieldRewriteSystemPrompt PromptFieldType = "rewrite_system_prompt"+ // PromptFieldRewritePrompt is for rewrite user prompts+ PromptFieldRewritePrompt PromptFieldType = "rewrite_prompt"+ // PromptFieldFallbackPrompt is for fallback prompts+ PromptFieldFallbackPrompt PromptFieldType = "fallback_prompt"+)++// All available placeholders in the system+var (+ // Common placeholders+ PlaceholderQuery = PromptPlaceholder{+ Name: "query",+ Label: "用户问题",+ Description: "用户当前的问题或查询内容",+ }++ PlaceholderContexts = PromptPlaceholder{+ Name: "contexts",+ Label: "检索内容",+ Description: "从知识库检索到的相关内容列表",+ }++ PlaceholderCurrentTime = PromptPlaceholder{+ Name: "current_time",+ Label: "当前时间",+ Description: "当前系统时间(格式:2006-01-02 15:04:05)",+ }++ PlaceholderCurrentWeek = PromptPlaceholder{+ Name: "current_week",+ Label: "当前星期",+ Description: "当前星期几(如:星期一、Monday)",+ }++ // Rewrite prompt placeholders+ PlaceholderConversation = PromptPlaceholder{+ Name: "conversation",+ Label: "历史对话",+ Description: "格式化的历史对话内容,用于多轮对话改写",+ }++ PlaceholderYesterday = PromptPlaceholder{+ Name: "yesterday",+ Label: "昨天日期",+ Description: "昨天的日期(格式:2006-01-02)",+ }++ PlaceholderAnswer = PromptPlaceholder{+ Name: "answer",+ Label: "助手回答",+ Description: "助手的回答内容(用于对话历史格式化)",+ }++ // Agent mode specific placeholders+ PlaceholderKnowledgeBases = PromptPlaceholder{+ Name: "knowledge_bases",+ Label: "知识库列表",+ Description: "自动格式化的知识库列表,包含名称、描述、文档数量等信息",+ }++ PlaceholderWebSearchStatus = PromptPlaceholder{+ Name: "web_search_status",+ Label: "网络搜索状态",+ Description: "网络搜索工具是否启用的状态(Enabled 或 Disabled)",+ }+)++// PlaceholdersByField returns the available placeholders for a specific prompt field type+func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {+ switch fieldType {+ case PromptFieldSystemPrompt:+ // Normal mode system prompt+ return []PromptPlaceholder{+ PlaceholderQuery,+ PlaceholderContexts,+ PlaceholderCurrentTime,+ PlaceholderCurrentWeek,+ }+ case PromptFieldAgentSystemPrompt:+ // Agent mode system prompt+ return []PromptPlaceholder{+ PlaceholderKnowledgeBases,+ PlaceholderWebSearchStatus,+ PlaceholderCurrentTime,+ }+ case PromptFieldContextTemplate:+ return []PromptPlaceholder{+ PlaceholderQuery,+ PlaceholderContexts,+ PlaceholderCurrentTime,+ PlaceholderCurrentWeek,+ }+ case PromptFieldRewriteSystemPrompt:+ // Rewrite system prompt supports same placeholders as rewrite user prompt+ return []PromptPlaceholder{+ PlaceholderQuery,+ PlaceholderConversation,+ PlaceholderCurrentTime,+ PlaceholderYesterday,+ }+ case PromptFieldRewritePrompt:+ return []PromptPlaceholder{+ PlaceholderQuery,+ PlaceholderConversation,+ PlaceholderCurrentTime,+ PlaceholderYesterday,+ }+ case PromptFieldFallbackPrompt:+ return []PromptPlaceholder{+ PlaceholderQuery,+ }+ default:+ return []PromptPlaceholder{}+ }+}++// AllPlaceholders returns all available placeholders in the system+func AllPlaceholders() []PromptPlaceholder {+ return []PromptPlaceholder{+ PlaceholderQuery,+ PlaceholderContexts,+ PlaceholderCurrentTime,+ PlaceholderCurrentWeek,+ PlaceholderConversation,+ PlaceholderYesterday,+ PlaceholderAnswer,+ PlaceholderKnowledgeBases,+ PlaceholderWebSearchStatus,+ }+}++// PlaceholderMap returns a map of field types to their available placeholders+func PlaceholderMap() map[PromptFieldType][]PromptPlaceholder {+ return map[PromptFieldType][]PromptPlaceholder{+ PromptFieldSystemPrompt: PlaceholdersByField(PromptFieldSystemPrompt),+ PromptFieldAgentSystemPrompt: PlaceholdersByField(PromptFieldAgentSystemPrompt),+ PromptFieldContextTemplate: PlaceholdersByField(PromptFieldContextTemplate),+ PromptFieldRewriteSystemPrompt: PlaceholdersByField(PromptFieldRewriteSystemPrompt),+ PromptFieldRewritePrompt: PlaceholdersByField(PromptFieldRewritePrompt),+ PromptFieldFallbackPrompt: PlaceholdersByField(PromptFieldFallbackPrompt),+ }+}diff --git a/internal/types/tenant.go b/internal/types/tenant.goindex ebafea3a4..67ce9502b 100644--- a/internal/types/tenant.go+++ b/internal/types/tenant.go@@ -69,13 +69,15 @@ type Tenant struct {StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`// Storage used (Bytes)StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`- // Global Agent configuration for this tenant (default for all sessions)+ // Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.+ // This field is kept for backward compatibility and will be removed in future versions.AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`// Global Context configuration for this tenant (default for all sessions)ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`// Global WebSearch configuration for this tenantWebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`- // Global Conversation configuration for this tenant (default for normal mode sessions)+ // Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.+ // This field is kept for backward compatibility and will be removed in future versions.ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`// Creation timeCreatedAt time.Time `yaml:"created_at" json:"created_at"`diff --git a/migrations/versioned/000006_custom_agents.down.sql b/migrations/versioned/000006_custom_agents.down.sqlindex 3e4a0dd5f..38c87f60f 100644--- a/migrations/versioned/000006_custom_agents.down.sql+++ b/migrations/versioned/000006_custom_agents.down.sql@@ -8,10 +8,9 @@ DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Removing agent_id column fromDROP INDEX IF EXISTS idx_sessions_agent_id;ALTER TABLE sessions DROP COLUMN IF EXISTS agent_id;--- Drop custom_agents table+-- Drop custom_agents table (includes built-in agents created during migration)DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Dropping table: custom_agents'; END $$;DROP INDEX IF EXISTS idx_custom_agents_tenant_id;-DROP INDEX IF EXISTS idx_custom_agents_type;DROP INDEX IF EXISTS idx_custom_agents_is_builtin;DROP INDEX IF EXISTS idx_custom_agents_deleted_at;DROP TABLE IF EXISTS custom_agents;diff --git a/migrations/versioned/000006_custom_agents.up.sql b/migrations/versioned/000006_custom_agents.up.sqlindex 80ba03b0c..915207ca2 100644--- a/migrations/versioned/000006_custom_agents.up.sql+++ b/migrations/versioned/000006_custom_agents.up.sql@@ -1,27 +1,27 @@-- Migration: 000006_custom_agents--- Description: Add custom agents table for GPTs-like agent configuration+-- Description: Add custom agents table for GPTs-like agent configuration and migrate tenant config to built-in agentsDO $$ BEGIN RAISE NOTICE '[Migration 000006] Starting custom agents setup...'; END $$;--- Create custom_agents table+-- Create custom_agents table with composite primary key (id, tenant_id)+-- This allows the same agent ID to exist for different tenants (e.g., 'builtin-normal' for each tenant)DO $$ BEGIN RAISE NOTICE '[Migration 000006] Creating table: custom_agents'; END $$;CREATE TABLE IF NOT EXISTS custom_agents (- id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),+ id VARCHAR(36) NOT NULL DEFAULT uuid_generate_v4(),name VARCHAR(255) NOT NULL,description TEXT,avatar VARCHAR(64),is_builtin BOOLEAN NOT NULL DEFAULT false,- type VARCHAR(32) NOT NULL DEFAULT 'custom',tenant_id INTEGER NOT NULL,created_by VARCHAR(36),config JSONB NOT NULL DEFAULT '{}',created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- deleted_at TIMESTAMP WITH TIME ZONE+ deleted_at TIMESTAMP WITH TIME ZONE,+ PRIMARY KEY (id, tenant_id));-- Add indexes for custom_agentsCREATE INDEX IF NOT EXISTS idx_custom_agents_tenant_id ON custom_agents(tenant_id);-CREATE INDEX IF NOT EXISTS idx_custom_agents_type ON custom_agents(type);CREATE INDEX IF NOT EXISTS idx_custom_agents_is_builtin ON custom_agents(is_builtin);CREATE INDEX IF NOT EXISTS idx_custom_agents_deleted_at ON custom_agents(deleted_at);@@ -30,4 +30,147 @@ DO $$ BEGIN RAISE NOTICE '[Migration 000006] Adding agent_id column to sessionsALTER TABLE sessions ADD COLUMN IF NOT EXISTS agent_id VARCHAR(36);CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id);-DO $$ BEGIN RAISE NOTICE '[Migration 000006] Custom agents setup completed successfully!'; END $$;+-- Helper function to unify prompt placeholders from Go template format to simple format+CREATE OR REPLACE FUNCTION unify_prompt_placeholder(input TEXT) RETURNS TEXT AS $$+DECLARE+ result TEXT := COALESCE(input, '');+ replacements TEXT[][] := ARRAY[+ -- Go template variables -> simple placeholders+ ['{{.Query}}', '{{query}}'],+ ['{{.Answer}}', '{{answer}}'],+ ['{{.CurrentTime}}', '{{current_time}}'],+ ['{{.CurrentWeek}}', '{{current_week}}'],+ ['{{.Yesterday}}', '{{yesterday}}'],+ ['{{.Contexts}}', '{{contexts}}'],+ -- Go template control structures -> simple placeholders or remove+ ['{{range .Contexts}}', '{{contexts}}'],+ -- Remove Go template syntax+ ['{{if .Contexts}}', ''],+ ['{{else}}', ''],+ ['{{.}}', '']+ ];+ r TEXT[];+BEGIN+ FOREACH r SLICE 1 IN ARRAY replacements LOOP+ result := REPLACE(result, r[1], r[2]);+ END LOOP;++ -- Handle {{range .Conversation}}...{{end}} block specially+ -- Replace the entire block with just {{conversation}}+ -- The pattern matches: {{range .Conversation}} followed by any content until {{end}}+ result := regexp_replace(+ result,+ '\{\{range \.Conversation\}\}[\s\S]*?\{\{end\}\}',+ '{{conversation}}',+ 'g'+ );++ -- Clean up any remaining {{end}} tags+ result := REPLACE(result, '{{end}}', '');++ RETURN result;+END;+$$ LANGUAGE plpgsql;++-- Migrate tenant AgentConfig and ConversationConfig to built-in custom agents+DO $$ BEGIN RAISE NOTICE '[Migration 000006] Migrating tenant config to built-in agents...'; END $$;++-- Insert builtin-quick-answer agent for tenants with ConversationConfig+INSERT INTO custom_agents (id, name, description, avatar, is_builtin, tenant_id, config, created_at, updated_at)+SELECT+ 'builtin-quick-answer',+ '快速问答',+ '基于知识库的 RAG 问答,快速准确地回答问题',+ '💬',+ true,+ t.id,+ jsonb_build_object(+ 'agent_mode', 'quick-answer',+ 'system_prompt', unify_prompt_placeholder(t.conversation_config->>'prompt'),+ 'context_template', unify_prompt_placeholder(t.conversation_config->>'context_template'),+ 'model_id', COALESCE(t.conversation_config->>'summary_model_id', ''),+ 'rerank_model_id', COALESCE(t.conversation_config->>'rerank_model_id', ''),+ 'temperature', COALESCE((t.conversation_config->>'temperature')::float, 0.7),+ 'max_completion_tokens', COALESCE((t.conversation_config->>'max_completion_tokens')::int, 2048),+ 'max_iterations', 10,+ 'allowed_tools', '[]'::jsonb,+ 'reflection_enabled', false,+ 'kb_selection_mode', 'all',+ 'knowledge_bases', '[]'::jsonb,+ 'web_search_enabled', false,+ 'web_search_max_results', COALESCE((t.web_search_config->>'max_results')::int, 5),+ 'multi_turn_enabled', COALESCE((t.conversation_config->>'multi_turn_enabled')::bool, true),+ 'history_turns', COALESCE((t.conversation_config->>'max_rounds')::int, 5),+ 'embedding_top_k', COALESCE((t.conversation_config->>'embedding_top_k')::int, 10),+ 'keyword_threshold', COALESCE((t.conversation_config->>'keyword_threshold')::float, 0.3),+ 'vector_threshold', COALESCE((t.conversation_config->>'vector_threshold')::float, 0.5),+ 'rerank_top_k', COALESCE((t.conversation_config->>'rerank_top_k')::int, 5),+ 'rerank_threshold', COALESCE((t.conversation_config->>'rerank_threshold')::float, 0.5),+ 'enable_query_expansion', COALESCE((t.conversation_config->>'enable_query_expansion')::bool, true),+ 'enable_rewrite', COALESCE((t.conversation_config->>'enable_rewrite')::bool, true),+ 'rewrite_prompt_system', unify_prompt_placeholder(t.conversation_config->>'rewrite_prompt_system'),+ 'rewrite_prompt_user', unify_prompt_placeholder(t.conversation_config->>'rewrite_prompt_user'),+ 'fallback_strategy', COALESCE(t.conversation_config->>'fallback_strategy', 'model'),+ 'fallback_response', unify_prompt_placeholder(t.conversation_config->>'fallback_response'),+ 'fallback_prompt', unify_prompt_placeholder(t.conversation_config->>'fallback_prompt')+ ),+ NOW(),+ NOW()+FROM tenants t+WHERE t.conversation_config IS NOT NULL+ AND t.deleted_at IS NULL+ON CONFLICT (id, tenant_id) DO UPDATE SET+ config = EXCLUDED.config,+ updated_at = NOW();++-- Insert builtin-smart-reasoning agent for tenants with AgentConfig+INSERT INTO custom_agents (id, name, description, avatar, is_builtin, tenant_id, config, created_at, updated_at)+SELECT+ 'builtin-smart-reasoning',+ '智能推理',+ 'ReAct 推理框架,支持多步思考和工具调用',+ '🤖',+ true,+ t.id,+ jsonb_build_object(+ 'agent_mode', 'smart-reasoning',+ 'system_prompt', unify_prompt_placeholder(t.agent_config->>'system_prompt_web_disabled'),+ 'system_prompt_web_enabled', unify_prompt_placeholder(t.agent_config->>'system_prompt_web_enabled'),+ 'context_template', '',+ 'model_id', COALESCE(t.conversation_config->>'summary_model_id', ''),+ 'rerank_model_id', COALESCE(t.conversation_config->>'rerank_model_id', ''),+ 'temperature', COALESCE((t.agent_config->>'temperature')::float, 0.7),+ 'max_completion_tokens', 2048,+ 'max_iterations', COALESCE((t.agent_config->>'max_iterations')::int, 50),+ 'allowed_tools', COALESCE(t.agent_config->'allowed_tools', '["thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"]'::jsonb),+ 'reflection_enabled', COALESCE((t.agent_config->>'reflection_enabled')::bool, false),+ 'mcp_selection_mode', 'all',+ 'mcp_services', '[]'::jsonb,+ 'kb_selection_mode', 'all',+ 'knowledge_bases', COALESCE(t.agent_config->'knowledge_bases', '[]'::jsonb),+ 'web_search_enabled', COALESCE((t.agent_config->>'web_search_enabled')::bool, true),+ 'web_search_max_results', COALESCE((t.agent_config->>'web_search_max_results')::int, COALESCE((t.web_search_config->>'max_results')::int, 5)),+ 'multi_turn_enabled', COALESCE((t.agent_config->>'multi_turn_enabled')::bool, true),+ 'history_turns', COALESCE((t.agent_config->>'history_turns')::int, 5),+ 'embedding_top_k', 10,+ 'keyword_threshold', 0.3,+ 'vector_threshold', 0.5,+ 'rerank_top_k', 5,+ 'rerank_threshold', 0.5,+ 'enable_query_expansion', false,+ 'enable_rewrite', false,+ 'rewrite_prompt_system', '',+ 'rewrite_prompt_user', '',+ 'fallback_strategy', 'model',+ 'fallback_response', '',+ 'fallback_prompt', ''+ ),+ NOW(),+ NOW()+FROM tenants t+WHERE t.agent_config IS NOT NULL+ AND t.deleted_at IS NULL+ON CONFLICT (id, tenant_id) DO UPDATE SET+ config = EXCLUDED.config,+ updated_at = NOW();+