From abfe87eaedf3a2b1d023bff605f365fe101c023b Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 25 Dec 2025 18:22:36 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=87=8D=E6=9E=84=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E8=AF=8D=E6=A8=A1=E6=9D=BF=E7=B3=BB=E7=BB=9F=EF=BC=8C=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E5=A4=9A=E5=9C=BA=E6=99=AF=E6=A8=A1=E6=9D=BF=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E6=94=AF=E6=8C=81=EF=BC=9B=E4=BC=98=E5=8C=96=E6=99=BA?= =?UTF-8?q?=E8=83=BD=E4=BD=93=E7=9F=A5=E8=AF=86=E5=BA=93=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=EF=BC=8C=E6=94=AF=E6=8C=81=E5=85=A8=E9=83=A8?= =?UTF-8?q?/=E6=8C=87=E5=AE=9A/=E7=A6=81=E7=94=A8=E4=B8=89=E7=A7=8D?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.yaml | 14 +- config/prompt_templates/context_template.yaml | 65 + config/prompt_templates/fallback.yaml | 47 + config/prompt_templates/rewrite_system.yaml | 30 + config/prompt_templates/rewrite_user.yaml | 39 + config/prompt_templates/system_prompt.yaml | 113 ++ frontend/src/api/agent/index.ts | 48 +- frontend/src/api/system/index.ts | 24 +- frontend/src/components/Input-field.vue | 104 +- .../src/components/PromptTemplateSelector.vue | 261 ++++ frontend/src/i18n/locales/en-US.ts | 144 ++- frontend/src/i18n/locales/zh-CN.ts | 142 ++- frontend/src/stores/settings.ts | 2 - frontend/src/views/agent/AgentEditorModal.vue | 1072 +++++++++++++++-- frontend/src/views/agent/AgentList.vue | 50 +- frontend/src/views/settings/AgentSettings.vue | 337 +++--- .../application/repository/custom_agent.go | 6 +- .../service/chat_pipline/common.go | 22 +- .../service/chat_pipline/into_chat_message.go | 48 +- internal/application/service/custom_agent.go | 169 ++- internal/application/service/knowledge.go | 42 - internal/application/service/session.go | 397 +++--- internal/config/config.go | 101 +- internal/handler/custom_agent.go | 2 +- internal/handler/session/handler.go | 106 +- internal/handler/session/helpers.go | 23 +- internal/handler/session/qa.go | 126 +- internal/handler/tenant.go | 163 +-- internal/types/custom_agent.go | 119 +- internal/types/interfaces/custom_agent.go | 5 +- internal/types/session.go | 32 +- internal/types/tenant.go | 4 +- 32 files changed, 2755 insertions(+), 1102 deletions(-) create mode 100644 config/prompt_templates/context_template.yaml create mode 100644 config/prompt_templates/fallback.yaml create mode 100644 config/prompt_templates/rewrite_system.yaml create mode 100644 config/prompt_templates/rewrite_user.yaml create mode 100644 config/prompt_templates/system_prompt.yaml create mode 100644 frontend/src/components/PromptTemplateSelector.vue diff --git a/config/config.yaml b/config/config.yaml index 5f8a19e2..693a7064 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -182,7 +182,6 @@ conversation: prompt: | 你是一个专业的智能信息检索助手,名为WeKnora。你犹如专业的高级秘书,依据检索到的信息回答用户问题,不能利用任何先验知识。 当用户提出问题时,助手会基于特定的信息进行解答。助手首先在心中思考推理过程,然后向用户提供答案。 - context_template: | ## 回答问题规则 - 仅根据检索到的信息中的事实进行回复,不得运用任何先验知识,保持回应的客观性和准确性。 - 复杂问题和答案的按Markdown分结构展示,总述部分不需要拆分 @@ -195,18 +194,7 @@ conversation: - 以Markdown图文格式输出你的最终结果 - 输出内容要保证简短且全面,条理清晰,信息明确,不重复。 - ## 当前时间是: - {{.CurrentTime}} {{.CurrentWeek}} - - ## 检索到的信息如下: - ------BEGIN------ - {{range .Contexts}} - {{.}} - {{end}} - ------END------ - - ## 用户当前的问题是: - {{.Query}} + context_template: "{{query}}" extract_entities_prompt: | ## 任务 用户提供的文本中,提取所有符合以下实体类型的实体: diff --git a/config/prompt_templates/context_template.yaml b/config/prompt_templates/context_template.yaml new file mode 100644 index 00000000..4965fed1 --- /dev/null +++ b/config/prompt_templates/context_template.yaml @@ -0,0 +1,65 @@ +# 上下文模板 +templates: + - id: "default_context" + name: "标准模板" + description: "标准的上下文格式化模板" + has_knowledge_base: true + content: | + 请根据以下参考资料回答用户问题。 + + 参考资料: + {{contexts}} + + 用户问题:{{query}} + + 请基于上述参考资料进行回答。如果参考资料不足以回答问题,请明确告知。 + + - id: "detailed_context" + name: "详细模板" + description: "包含详细说明的上下文模板" + has_knowledge_base: true + content: | + ## 任务说明 + 请根据提供的参考资料,准确、全面地回答用户问题。 + + ## 参考资料 + {{contexts}} + + ## 用户问题 + {{query}} + + ## 回答要求 + 1. 仅基于参考资料回答,不要编造信息 + 2. 如果多个资料有冲突,请综合分析 + 3. 适当引用来源,增强可信度 + 4. 如果资料不足,请明确说明 + + 当前时间:{{current_time}} {{current_week}} + + - id: "simple_context" + name: "简洁模板" + description: "简洁的上下文模板" + has_knowledge_base: true + content: | + 参考资料: + {{contexts}} + + 问题:{{query}} + + 请回答上述问题。 + + - id: "qa_context" + name: "问答模板" + description: "问答场景专用模板" + has_knowledge_base: true + content: | + 你需要回答一个问题。以下是可能相关的资料: + + {{contexts}} + + 用户的问题是:{{query}} + + 请基于以上资料回答问题。回答要求: + - 直接回答问题,不要重复问题 + - 如果资料中没有相关信息,请说明 + - 保持回答简洁准确 diff --git a/config/prompt_templates/fallback.yaml b/config/prompt_templates/fallback.yaml new file mode 100644 index 00000000..e1902d11 --- /dev/null +++ b/config/prompt_templates/fallback.yaml @@ -0,0 +1,47 @@ +# 兜底提示词模板 +templates: + - id: "default_fallback" + name: "标准兜底" + description: "标准的兜底回复模板" + content: | + 抱歉,我在知识库中没有找到与您问题直接相关的内容。 + + 您可以尝试: + 1. 换一种方式描述您的问题 + 2. 提供更多具体信息 + 3. 咨询相关领域的专业人员 + + 如果您有其他问题,我很乐意继续为您服务。 + + - id: "polite_fallback" + name: "礼貌兜底" + description: "更加礼貌友好的兜底回复" + content: | + 非常抱歉,目前我无法为您提供这个问题的准确答案。这可能是因为: + - 该问题超出了我的知识范围 + - 知识库中暂无相关内容 + + 建议您: + 1. 尝试用不同的关键词重新提问 + 2. 将问题拆分为更具体的小问题 + 3. 联系人工客服获取帮助 + + 感谢您的理解,期待能在其他问题上帮助到您! + + - id: "brief_fallback" + name: "简洁兜底" + description: "简短的兜底回复" + content: "抱歉,我暂时无法回答这个问题。请尝试换一种方式提问,或联系人工客服。" + + - id: "model_fallback" + name: "模型兜底" + description: "交给模型继续生成的兜底提示词" + content: | + 知识库中没有找到与用户问题直接相关的内容。请根据你的通用知识,尽可能帮助用户解答问题。 + + 注意事项: + 1. 明确告知用户这是基于通用知识的回答,而非知识库内容 + 2. 如果问题涉及特定领域或需要最新信息,建议用户查阅官方资料 + 3. 保持回答的准确性和客观性 + + 用户问题:{{.Query}} diff --git a/config/prompt_templates/rewrite_system.yaml b/config/prompt_templates/rewrite_system.yaml new file mode 100644 index 00000000..1c74e82e --- /dev/null +++ b/config/prompt_templates/rewrite_system.yaml @@ -0,0 +1,30 @@ +# 改写系统提示词模板 +templates: + - id: "default_rewrite_system" + name: "标准改写" + description: "标准的问题改写系统提示词" + content: | + 你是一个专业的问题改写助手。你的任务是将用户的后续问题改写为独立、完整的问题,使其可以脱离对话上下文独立理解。 + + 改写规则: + 1. 消解代词指代(如"它"、"这个"、"他们"等) + 2. 补全省略的主语或宾语 + 3. 保持原问题的核心意图不变 + 4. 改写后的问题应该简洁清晰 + + 只输出改写后的问题,不要输出其他内容。 + + - id: "strict_rewrite_system" + name: "严格改写" + description: "严格要求的问题改写模板" + content: | + 你是问题改写专家。请将用户问题改写为完整、独立的问题。 + + 严格要求: + 1. 必须消解所有代词和指代 + 2. 必须补全所有省略内容 + 3. 不得改变原问题意图 + 4. 不得添加原问题没有的内容 + 5. 改写结果必须是一个问句 + + 直接输出改写后的问题,不要有任何解释。 diff --git a/config/prompt_templates/rewrite_user.yaml b/config/prompt_templates/rewrite_user.yaml new file mode 100644 index 00000000..54e0f994 --- /dev/null +++ b/config/prompt_templates/rewrite_user.yaml @@ -0,0 +1,39 @@ +# 改写用户提示词模板 +templates: + - id: "default_rewrite_user" + name: "标准格式" + description: "标准的改写用户提示词格式" + content: | + ## 历史对话背景 + {{range .Conversation}} + ------BEGIN------ + 用户的问题是:{{.Query}} + 助手的回答是:{{.Answer}} + ------END------ + {{end}} + + ## 需要改写的用户问题 + {{.Query}} + + ## 改写后的问题 + + - id: "detailed_rewrite_user" + name: "详细格式" + description: "详细的改写用户提示词格式" + content: | + ## 历史对话背景 + 以下是用户与助手的对话历史,请仔细阅读以理解上下文: + + {{range .Conversation}} + 【用户】{{.Query}} + 【助手】{{.Answer}} + + {{end}} + + ## 当前用户问题 + {{.Query}} + + ## 任务要求 + 请根据以上对话历史,将当前问题改写为一个独立、完整、可以脱离上下文理解的问题。 + + ## 改写后的问题 diff --git a/config/prompt_templates/system_prompt.yaml b/config/prompt_templates/system_prompt.yaml new file mode 100644 index 00000000..3e3afded --- /dev/null +++ b/config/prompt_templates/system_prompt.yaml @@ -0,0 +1,113 @@ +# 系统提示词模板 +templates: + - id: "default_kb" + name: "知识库问答" + description: "基于知识库内容回答问题的标准模板" + has_knowledge_base: true + content: | + 你是一个专业的知识库问答助手。请根据提供的参考资料回答用户问题。 + + 要求: + 1. 仅基于参考资料回答,不要编造信息 + 2. 如果参考资料不足以回答问题,请明确告知用户 + 3. 回答要准确、简洁、专业 + 4. 适当引用来源,增强可信度 + + 当前时间:{{current_time}} + + - id: "expert_assistant" + name: "领域专家" + description: "专业领域深度解答的专家模板" + has_knowledge_base: true + content: | + 你是一位资深的领域专家助手,拥有丰富的专业知识和实践经验。 + + 核心职责: + 1. 深入分析用户问题,提供专业、全面的解答 + 2. 结合知识库内容,给出有据可依的建议 + 3. 必要时提供多角度分析和权衡利弊 + 4. 用通俗易懂的语言解释专业概念 + + 回答风格: + - 条理清晰,逻辑严谨 + - 重点突出,层次分明 + - 实用性强,可操作性高 + + 当前时间:{{current_time}} + + - id: "customer_service" + name: "客服助手" + description: "友善专业的客服对话模板" + has_knowledge_base: true + content: | + 你是一位专业、友善的客服助手,致力于为用户提供优质的服务体验。 + + 服务准则: + 1. 态度热情友好,用语礼貌得体 + 2. 准确理解用户需求,提供针对性解答 + 3. 基于知识库内容回答,确保信息准确 + 4. 遇到无法解答的问题,引导用户寻求其他帮助渠道 + + 回答要求: + - 语气亲切自然,避免机械生硬 + - 回答简洁明了,重点突出 + - 必要时主动提供相关信息 + + 当前时间:{{current_time}} + + - id: "technical_support" + name: "技术支持" + description: "技术问题诊断与解决方案模板" + has_knowledge_base: true + content: | + 你是一位专业的技术支持工程师,负责解答技术相关问题。 + + 工作职责: + 1. 准确诊断用户遇到的技术问题 + 2. 提供清晰、可执行的解决方案 + 3. 必要时提供代码示例或操作步骤 + 4. 解释技术原理,帮助用户理解 + + 回答规范: + - 技术术语准确,解释清晰 + - 步骤详细,便于操作 + - 代码示例规范,注释完整 + - 考虑不同场景和边界情况 + + 当前时间:{{current_time}} + + - id: "pure_chat" + name: "通用对话" + description: "无知识库的通用对话模板" + has_knowledge_base: false + content: | + 你是一个智能对话助手,可以与用户进行自然流畅的对话。 + + 特点: + 1. 理解用户意图,提供有帮助的回答 + 2. 知识广泛,可以讨论多种话题 + 3. 回答准确、客观、有见地 + 4. 语言自然,富有亲和力 + + 当前时间:{{current_time}} + + - id: "web_search_assistant" + name: "网络搜索助手" + description: "结合网络搜索的智能助手模板" + has_knowledge_base: true + has_web_search: true + content: | + 你是一个具备网络搜索能力的智能助手,可以获取最新信息来回答问题。 + + 工作方式: + 1. 结合网络搜索结果和知识库内容回答问题 + 2. 优先使用最新、最权威的信息来源 + 3. 明确标注信息来源,便于用户验证 + 4. 对于时效性强的问题,优先参考搜索结果 + + 注意事项: + - 区分事实和观点 + - 对比多个来源,提供全面视角 + - 标注信息的时效性 + + 当前时间:{{current_time}} diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index b41e9566..43987153 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -5,25 +5,59 @@ export type CustomAgentType = 'normal' | 'agent' | 'custom'; // 智能体配置 export interface CustomAgentConfig { + // ===== 基础设置 ===== agent_mode?: 'normal' | 'agent'; // 运行模式:normal=RAG模式, agent=ReAct Agent模式 - system_prompt?: string; + system_prompt?: string; // 系统提示词(普通模式,或Agent模式网络搜索关闭时) + system_prompt_web_enabled?: string; // Agent模式网络搜索开启时的系统提示词 + context_template?: string; // 上下文模板(普通模式) + + // ===== 模型设置 ===== model_id?: string; - rerank_model_id?: string; // ReRank 模型 ID(当使用知识库时需要) + rerank_model_id?: string; // ReRank 模型 ID temperature?: number; - max_iterations?: number; - allowed_tools?: string[]; + max_completion_tokens?: number; // 最大生成token数(普通模式) + + // ===== Agent模式设置 ===== + max_iterations?: number; // 最大迭代次数 + allowed_tools?: string[]; // 允许的工具 + reflection_enabled?: boolean; // 是否启用反思 + + // ===== 知识库设置 ===== + // 知识库选择模式:all=全部知识库, selected=指定知识库, none=不使用知识库 + kb_selection_mode?: 'all' | 'selected' | 'none'; knowledge_bases?: string[]; // 当没有配置知识库时,是否允许用户自由选择知识库 // true (默认): 用户可以自由选择任意知识库 // false: 禁用知识库选择功能 allow_user_kb_selection?: boolean; + + // ===== 网络搜索设置 ===== web_search_enabled?: boolean; web_search_max_results?: number; - reflection_enabled?: boolean; + + // ===== 多轮对话设置 ===== + multi_turn_enabled?: boolean; // 是否启用多轮对话 + history_turns?: number; // 保留历史轮数 + + // ===== 检索策略设置 ===== + embedding_top_k?: number; // 向量召回TopK + keyword_threshold?: number; // 关键词召回阈值 + vector_threshold?: number; // 向量召回阈值 + rerank_top_k?: number; // 重排TopK + rerank_threshold?: number; // 重排阈值 + + // ===== 高级设置(主要用于普通模式)===== + enable_query_expansion?: boolean; // 是否启用查询扩展 + enable_rewrite?: boolean; // 是否启用问题改写 + rewrite_prompt_system?: string; // 改写系统提示词 + rewrite_prompt_user?: string; // 改写用户提示词模板 + fallback_strategy?: 'fixed' | 'model'; // 兜底策略 + fallback_response?: string; // 固定兜底回复 + fallback_prompt?: string; // 兜底提示词(模型生成时) + + // ===== 已废弃字段(保留兼容)===== welcome_message?: string; suggested_prompts?: string[]; - multi_turn_enabled?: boolean; // 是否启用多轮对话 - history_turns?: number; // 保留历史轮数 } // 智能体 diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 134d18e5..934cc8f5 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -31,7 +31,6 @@ export interface AgentConfig { knowledge_bases?: string[] system_prompt_web_enabled?: string // Custom system prompt when web search is enabled system_prompt_web_disabled?: string // Custom system prompt when web search is disabled - use_custom_system_prompt?: boolean available_tools?: ToolDefinition[] // GET 响应中包含,POST/PUT 不需要 available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要 } @@ -41,8 +40,6 @@ export interface ConversationConfig { context_template: string temperature: number max_completion_tokens: number - use_custom_system_prompt?: boolean - use_custom_context_template?: boolean max_rounds: number embedding_top_k: number keyword_threshold: number @@ -60,6 +57,23 @@ export interface ConversationConfig { enable_query_expansion?: boolean } +export interface PromptTemplate { + id: string + name: string + description: string + content: string + has_knowledge_base?: boolean + has_web_search?: boolean +} + +export interface PromptTemplatesConfig { + system_prompt: PromptTemplate[] + context_template: PromptTemplate[] + rewrite_system: PromptTemplate[] + rewrite_user: PromptTemplate[] + fallback: PromptTemplate[] +} + export function getSystemInfo(): Promise<{ data: SystemInfo }> { return get('/api/v1/system/info') } @@ -79,3 +93,7 @@ export function getConversationConfig(): Promise<{ data: ConversationConfig }> { export function updateConversationConfig(config: ConversationConfig): Promise<{ data: ConversationConfig }> { return put('/api/v1/tenants/kv/conversation-config', config) } + +export function getPromptTemplates(): Promise<{ data: PromptTemplatesConfig }> { + return get('/api/v1/tenants/kv/prompt-templates') +} diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 8499351c..739b9027 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -55,6 +55,12 @@ const agentKnowledgeBases = computed(() => { return selectedAgent.value?.config?.knowledge_bases || []; }); +// 智能体的知识库选择模式 +const agentKBSelectionMode = computed(() => { + if (!isCustomAgent.value) return null; // null 表示不受智能体控制 + return selectedAgent.value?.config?.kb_selection_mode || 'none'; +}); + // 智能体是否启用了网络搜索 const agentWebSearchEnabled = computed(() => { if (!isCustomAgent.value) return null; // null 表示不受智能体控制 @@ -72,24 +78,22 @@ const isWebSearchForcedByAgent = computed(() => { }); // 知识库选择是否被智能体锁定 -// 1. 如果智能体配置了知识库 → 锁定到这些知识库 -// 2. 如果智能体没配置知识库,但 allow_user_kb_selection=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; - // 有预配置知识库时,锁定到这些知识库 - if (agentKnowledgeBases.value.length > 0) return true; - // 没有预配置知识库,但禁止用户选择 + // 如果禁用了知识库,返回 true(锁定状态) + if (agentKBSelectionMode.value === 'none') return true; + // 如果不允许用户选择知识库,返回 true const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection; - // 默认为 true(允许用户选择),只有明确设置为 false 时才禁用 return allowUserKBSelection === false; }); -// 知识库是否被智能体完全禁用(没有预配置且不允许用户选择) +// 知识库是否被智能体完全禁用(kb_selection_mode = 'none') const isKnowledgeBaseDisabledByAgent = computed(() => { if (!isCustomAgent.value) return false; - if (agentKnowledgeBases.value.length > 0) return false; // 有预配置的不算禁用 - const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection; - return allowUserKBSelection === false; + return agentKBSelectionMode.value === 'none'; }); // 智能体配置的模型 ID @@ -556,10 +560,28 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) => mentionOffset.value = 0; } - // Fetch KBs (always show, filter by query) - only on first load + // 根据智能体的 kb_selection_mode 过滤知识库 let kbItems: any[] = []; if (!append) { - const kbs = knowledgeBases.value.filter(kb => + // 获取可选的知识库列表 + let availableKbs = knowledgeBases.value; + + // 如果是自定义智能体,根据 kb_selection_mode 过滤 + if (isCustomAgent.value) { + const kbMode = agentKBSelectionMode.value; + if (kbMode === 'none') { + // 不使用知识库,不显示任何知识库 + availableKbs = []; + } else if (kbMode === 'selected') { + // 仅显示智能体配置的知识库 + const configuredKbIds = agentKnowledgeBases.value; + availableKbs = knowledgeBases.value.filter(kb => configuredKbIds.includes(kb.id)); + } + // kbMode === 'all' 时显示全部知识库 + } + + // 按查询过滤 + const kbs = availableKbs.filter(kb => !q || kb.name.toLowerCase().includes(q.toLowerCase()) ); kbItems = kbs.map(kb => ({ @@ -572,26 +594,41 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) => } // Fetch Files from API + // 如果智能体禁用了知识库,也不显示文件 let fileItems: any[] = []; - mentionLoading.value = true; - try { - const res: any = await searchKnowledge(q || '', mentionOffset.value, MENTION_PAGE_SIZE); - console.log('[Mention] searchKnowledge response:', res); - if (res.data && Array.isArray(res.data)) { - fileItems = res.data.map((f: any) => ({ - id: f.id, - name: f.title || f.file_name, - type: 'file' as const, - kbName: f.knowledge_base_name || '' - })); + const shouldLoadFiles = !isCustomAgent.value || agentKBSelectionMode.value !== 'none'; + + if (shouldLoadFiles) { + mentionLoading.value = true; + try { + const res: any = await searchKnowledge(q || '', mentionOffset.value, MENTION_PAGE_SIZE); + console.log('[Mention] searchKnowledge response:', res); + if (res.data && Array.isArray(res.data)) { + let files = res.data; + + // 如果是自定义智能体且 kb_selection_mode === 'selected',只显示指定知识库中的文件 + if (isCustomAgent.value && agentKBSelectionMode.value === 'selected') { + const configuredKbIds = agentKnowledgeBases.value; + files = files.filter((f: any) => configuredKbIds.includes(f.knowledge_base_id)); + } + + fileItems = files.map((f: any) => ({ + id: f.id, + name: f.title || f.file_name, + type: 'file' as const, + kbName: f.knowledge_base_name || '' + })); + } + mentionHasMore.value = res.has_more || false; + mentionOffset.value += fileItems.length; + } catch (e) { + console.error('[Mention] searchKnowledge error:', e); + mentionHasMore.value = false; + } finally { + mentionLoading.value = false; } - mentionHasMore.value = res.has_more || false; - mentionOffset.value += fileItems.length; - } catch (e) { - console.error('[Mention] searchKnowledge error:', e); + } else { mentionHasMore.value = false; - } finally { - mentionLoading.value = false; } if (append) { @@ -680,6 +717,15 @@ const onInput = (val: string | InputEvent) => { } } else { if (textBeforeCursor.endsWith('@')) { + // 如果智能体禁用了知识库,不触发 @ 菜单 + if (isKnowledgeBaseDisabledByAgent.value) { + return; + } + // 如果智能体锁定了知识库且不允许用户选择,也不触发 @ 菜单 + if (isKnowledgeBaseLockedByAgent.value) { + return; + } + console.log('[Mention] @ detected, opening menu'); isMentionTriggeredByButton.value = false; mentionStartPos.value = cursor - 1; diff --git a/frontend/src/components/PromptTemplateSelector.vue b/frontend/src/components/PromptTemplateSelector.vue new file mode 100644 index 00000000..99b202f4 --- /dev/null +++ b/frontend/src/components/PromptTemplateSelector.vue @@ -0,0 +1,261 @@ + + + + + diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 706c41ef..fb116d5e 100644 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -268,6 +268,12 @@ export default { modelConfigDesc: 'Configure agent model parameters', capabilities: 'Capabilities', capabilitiesDesc: 'Configure agent capabilities and tools', + toolsConfig: 'Tools', + toolsConfigDesc: 'Configure tools available to the Agent', + knowledgeConfig: 'Knowledge Base', + knowledgeConfigDesc: 'Configure knowledge bases for the agent', + webSearchConfig: 'Web Search', + webSearchConfigDesc: 'Configure web search capabilities for the agent', configuration: 'Configuration', name: 'Name', namePlaceholder: 'Enter agent name', @@ -286,6 +292,10 @@ export default { modelPlaceholder: 'Select Model', systemPrompt: 'System Prompt', systemPromptPlaceholder: 'Custom system prompt to define agent behavior and role', + systemPromptWebEnabledPlaceholder: 'System prompt used when web search is enabled', + defaultPromptHint: 'Leave empty to use the following default system prompt:', + defaultContextTemplateHint: 'Leave empty to use the following default context template:', + contextTemplateRequired: 'Context template is required', availablePlaceholders: 'Available Placeholders', placeholderHint: 'Type {{ to trigger autocomplete', temperature: 'Temperature', @@ -296,9 +306,16 @@ export default { webSearch: 'Web Search', webSearchMaxResults: 'Max Search Results', knowledgeBases: 'Knowledge Bases', - selectKnowledgeBases: 'Select knowledge bases', + allKnowledgeBases: 'All Knowledge Bases', + allKnowledgeBasesDesc: 'Agent can access all knowledge bases', + selectedKnowledgeBases: 'Selected Knowledge Bases', + selectedKnowledgeBasesDesc: 'Only access selected knowledge bases', + noKnowledgeBase: 'No Knowledge Base', + noKnowledgeBaseDesc: 'Pure model conversation, no knowledge retrieval', + selectKnowledgeBases: 'Select Knowledge Bases', allowUserKBSelection: 'Allow User KB Selection', - allowUserKBSelectionDesc: 'When disabled, users cannot select knowledge bases during conversation', + 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', @@ -306,6 +323,36 @@ export default { allowedTools: 'Allowed Tools', multiTurn: 'Multi-turn Conversation', historyTurns: 'History Turns', + // Retrieval Strategy + retrievalStrategy: 'Retrieval Strategy', + embeddingTopK: 'Embedding Top K', + keywordThreshold: 'Keyword Threshold', + vectorThreshold: 'Vector Threshold', + rerankTopK: 'Rerank Top K', + rerankThreshold: 'Rerank Threshold', + // Conversation Settings + conversationSettings: 'Conversation', + // Advanced Settings + advancedSettings: 'Advanced Settings', + contextTemplate: 'Context Template', + contextTemplatePlaceholder: 'Custom context template...', + availableContextPlaceholders: 'Available Placeholders', + placeholderQuery: 'User query', + placeholderContexts: 'Retrieved content list', + placeholderCurrentTime: 'Current time (format: 2006-01-02 15:04:05)', + placeholderCurrentWeek: 'Current weekday (e.g., Monday)', + enableQueryExpansion: 'Query Expansion', + enableRewrite: 'Query Rewrite', + rewritePromptSystem: 'Rewrite System Prompt', + rewritePromptSystemPlaceholder: 'Leave empty to use default prompt', + rewritePromptUser: 'Rewrite User Prompt', + rewritePromptUserPlaceholder: 'Leave empty to use default prompt', + maxCompletionTokens: 'Max Completion Tokens', + fallbackStrategy: 'Fallback Strategy', + fallbackResponse: 'Fixed Response', + fallbackResponsePlaceholder: 'Sorry, I cannot answer this question.', + fallbackPrompt: 'Fallback Prompt', + fallbackPromptPlaceholder: 'Leave empty to use default prompt', }, selector: { title: 'Select Agent', @@ -313,9 +360,6 @@ export default { customSection: 'My Agents', addNew: 'Add New Agent', }, - builtinAgents: 'Built-in Agents', - customAgents: 'Custom Agents', - manageAgents: 'Manage Agents', }, settings: { title: 'Settings', @@ -1993,5 +2037,93 @@ export default { createFailed: 'Failed to create MCP service', updateFailed: 'Failed to update MCP service' } - } + }, + promptTemplate: { + selectTemplate: 'Select Template', + useTemplate: 'Use Template', + withKnowledgeBase: 'KB', + withWebSearch: 'Web Search', + systemPrompt: { + defaultKB: { + name: 'Knowledge Base Assistant', + desc: 'Basic knowledge base Q&A template for most scenarios', + }, + expert: { + name: 'Domain Expert', + desc: 'Professional and in-depth answers for technical domains', + }, + customerService: { + name: 'Customer Service', + desc: 'Friendly and warm service style for customer support', + }, + techSupport: { + name: 'Technical Support', + desc: 'Professional technical problem solving with code examples', + }, + pureChat: { + name: 'General Chat', + desc: 'General conversation assistant without knowledge base', + }, + webSearch: { + name: 'Web Search Assistant', + desc: 'Combines web search for up-to-date information', + }, + }, + contextTemplate: { + default: { + name: 'Standard Template', + desc: 'Basic context template with clear references and questions', + }, + detailed: { + name: 'Detailed Template', + desc: 'Complete template with detailed instructions and requirements', + }, + simple: { + name: 'Simple Template', + desc: 'Minimal template format for simple Q&A scenarios', + }, + qa: { + name: 'Q&A Template', + desc: 'Optimized template for Q&A scenarios', + }, + }, + rewriteSystem: { + default: { + name: 'Standard Rewrite', + desc: 'Standard rules for resolving references and completing omissions', + }, + strict: { + name: 'Strict Rewrite', + desc: 'Stricter requirements for complete and independent questions', + }, + }, + rewriteUser: { + default: { + name: 'Standard Format', + desc: 'Standard format with conversation history and current question', + }, + detailed: { + name: 'Detailed Format', + desc: 'Detailed format with task instructions', + }, + }, + fallback: { + default: { + name: 'Standard Fallback', + desc: 'Friendly message with suggestions when unable to answer', + }, + polite: { + name: 'Polite Fallback', + desc: 'More polite and detailed unable-to-answer message', + }, + brief: { + name: 'Brief Fallback', + desc: 'Short unable-to-answer message', + }, + model: { + name: 'Model Fallback Prompt', + desc: 'Prompt to guide model to answer with general knowledge', + }, + }, + }, } \ No newline at end of file diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index d5ee38ec..fe6b30ea 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -797,6 +797,12 @@ export default { modelConfigDesc: "配置智能体的模型参数", capabilities: "能力与工具", capabilitiesDesc: "配置智能体的能力和工具", + toolsConfig: "工具配置", + toolsConfigDesc: "配置 Agent 可以使用的工具", + knowledgeConfig: "知识库", + knowledgeConfigDesc: "配置智能体可访问的知识库", + webSearchConfig: "网络搜索", + webSearchConfigDesc: "配置智能体的网络搜索能力", configuration: "配置项", name: "名称", namePlaceholder: "请输入智能体名称", @@ -815,6 +821,10 @@ export default { modelPlaceholder: "请选择模型", systemPrompt: "系统提示词", systemPromptPlaceholder: "自定义系统提示词,定义智能体的行为和角色", + systemPromptWebEnabledPlaceholder: "网络搜索开启时使用的系统提示词", + defaultPromptHint: "留空将使用以下系统默认提示词:", + defaultContextTemplateHint: "留空将使用以下系统默认上下文模板:", + contextTemplateRequired: "请输入上下文模板", availablePlaceholders: "可用占位符", placeholderHint: "输入 {{ 触发自动补全", temperature: "温度", @@ -825,9 +835,16 @@ export default { webSearch: "网络搜索", webSearchMaxResults: "最大搜索结果数", knowledgeBases: "关联知识库", - selectKnowledgeBases: "请选择知识库", + allKnowledgeBases: "全部知识库", + allKnowledgeBasesDesc: "智能体可访问所有知识库", + selectedKnowledgeBases: "指定知识库", + selectedKnowledgeBasesDesc: "仅访问选定的知识库", + noKnowledgeBase: "不使用知识库", + noKnowledgeBaseDesc: "纯模型对话,不检索知识库", + selectKnowledgeBases: "选择知识库", allowUserKBSelection: "允许用户选择知识库", - allowUserKBSelectionDesc: "关闭后,用户将无法在对话时选择知识库", + allowUserKBSelectionDescAll: "开启后,用户可以在对话时从全部知识库中选择;关闭后,将自动使用全部知识库", + allowUserKBSelectionDescSelected: "开启后,用户可以在对话时从关联的知识库中选择;关闭后,将自动使用全部关联的知识库", rerankModel: "ReRank 模型", rerankModelDesc: "用于对知识库检索结果进行重排序,提高回答准确性", rerankModelPlaceholder: "请选择 ReRank 模型", @@ -835,6 +852,36 @@ export default { allowedTools: "允许的工具", multiTurn: "多轮对话", historyTurns: "保留轮数", + // 检索策略 + retrievalStrategy: "检索策略", + embeddingTopK: "向量召回数量", + keywordThreshold: "关键词阈值", + vectorThreshold: "向量阈值", + rerankTopK: "重排数量", + rerankThreshold: "重排阈值", + // 多轮对话 + conversationSettings: "多轮对话", + // 高级设置 + advancedSettings: "高级设置", + contextTemplate: "上下文模板", + contextTemplatePlaceholder: "自定义上下文模板...", + availableContextPlaceholders: "可用占位符", + placeholderQuery: "用户的问题", + placeholderContexts: "检索到的内容列表", + placeholderCurrentTime: "当前时间(格式:2006-01-02 15:04:05)", + placeholderCurrentWeek: "当前星期(如:星期一)", + enableQueryExpansion: "查询扩展", + enableRewrite: "问题改写", + rewritePromptSystem: "改写系统提示词", + rewritePromptSystemPlaceholder: "留空使用系统默认提示词", + rewritePromptUser: "改写用户提示词", + rewritePromptUserPlaceholder: "留空使用系统默认提示词", + maxCompletionTokens: "最大生成Token数", + fallbackStrategy: "兜底策略", + fallbackResponse: "固定回复内容", + fallbackResponsePlaceholder: "抱歉,我无法回答这个问题。", + fallbackPrompt: "兜底提示词", + fallbackPromptPlaceholder: "留空使用系统默认提示词", }, selector: { title: "选择智能体", @@ -842,9 +889,6 @@ export default { customSection: "我的智能体", addNew: "添加新智能体", }, - builtinAgents: "内置智能体", - customAgents: "自定义智能体", - manageAgents: "管理智能体", }, file: { upload: "上传文件", @@ -1999,4 +2043,92 @@ export default { updateFailed: "更新 MCP 服务失败", }, }, + promptTemplate: { + selectTemplate: "选择模板", + useTemplate: "使用模板", + withKnowledgeBase: "知识库", + withWebSearch: "网络搜索", + systemPrompt: { + defaultKB: { + name: "知识库问答助手", + desc: "基础的知识库问答模板,适用于大多数场景", + }, + expert: { + name: "领域专家助手", + desc: "专业深入的解答风格,适合技术或专业领域", + }, + customerService: { + name: "客服助手", + desc: "友善热情的服务风格,适合客户服务场景", + }, + techSupport: { + name: "技术支持", + desc: "专业的技术问题解答,包含代码示例", + }, + pureChat: { + name: "通用对话", + desc: "不依赖知识库的通用对话助手", + }, + webSearch: { + name: "网络搜索助手", + desc: "结合网络搜索获取最新信息", + }, + }, + contextTemplate: { + default: { + name: "标准模板", + desc: "基础的上下文模板,清晰展示参考资料和问题", + }, + detailed: { + name: "详细模板", + desc: "包含详细说明和回答要求的完整模板", + }, + simple: { + name: "简洁模板", + desc: "精简的模板格式,适合简单问答场景", + }, + qa: { + name: "问答模板", + desc: "针对问答场景优化的模板", + }, + }, + rewriteSystem: { + default: { + name: "标准改写", + desc: "消解指代、补全省略的标准改写规则", + }, + strict: { + name: "严格改写", + desc: "更严格的改写要求,确保问题完整独立", + }, + }, + rewriteUser: { + default: { + name: "标准格式", + desc: "包含对话历史和当前问题的标准格式", + }, + detailed: { + name: "详细格式", + desc: "带有任务说明的详细格式", + }, + }, + fallback: { + default: { + name: "标准兜底", + desc: "友好告知无法回答并提供建议", + }, + polite: { + name: "礼貌兜底", + desc: "更加礼貌详细的无法回答提示", + }, + brief: { + name: "简洁兜底", + desc: "简短的无法回答提示", + }, + model: { + name: "模型兜底提示", + desc: "引导模型基于通用知识回答的提示词", + }, + }, + }, }; diff --git a/frontend/src/stores/settings.ts b/frontend/src/stores/settings.ts index 7913e3bc..5cae4a06 100644 --- a/frontend/src/stores/settings.ts +++ b/frontend/src/stores/settings.ts @@ -23,7 +23,6 @@ interface AgentConfig { allowedTools: string[]; system_prompt_web_enabled?: string; system_prompt_web_disabled?: string; - use_custom_system_prompt?: boolean; } interface ConversationModels { @@ -71,7 +70,6 @@ const defaultSettings: Settings = { allowedTools: [], // 默认为空,需要通过 API 从后端加载 system_prompt_web_enabled: "", system_prompt_web_disabled: "", - use_custom_system_prompt: false }, selectedKnowledgeBases: [], // 默认为空数组 selectedFiles: [], // 默认为空数组 diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue index 7e4156ab..286c3778 100644 --- a/frontend/src/views/agent/AgentEditorModal.vue +++ b/frontend/src/views/agent/AgentEditorModal.vue @@ -40,16 +40,45 @@
+ +
+ + 这是内置智能体,名称和描述不可修改,但可以调整配置参数 +
+ + +
+
+ +

{{ agentMode === 'agent' ? $t('agent.editor.agentDesc') : $t('agent.editor.normalDesc') }}

+
+
+ + + {{ $t('agent.type.normal') }} + + + {{ $t('agent.type.agent') }} + + +
+
+
- +

为智能体设置一个易于识别的名称

- +
@@ -65,15 +94,16 @@ v-model="formData.description" :placeholder="$t('agent.editor.descriptionPlaceholder')" :autosize="{ minRows: 2, maxRows: 4 }" + :disabled="isBuiltinAgent" />
- +
- -

自定义系统提示词,定义智能体的行为和角色

+ +

自定义系统提示词,定义智能体的行为和角色{{ isBuiltinAgent ? '(留空则使用系统默认)' : '' }}

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

    @@ -85,14 +115,62 @@
- + +
+ + +
+ + +
+
+ +
+ + +
+
+
+
+ +
+ + +
+ +
+
+ +

定义如何将检索到的内容格式化后传递给模型{{ isBuiltinAgent ? '(留空则使用系统默认)' : '' }}

+
+

{{ $t('agent.editor.availableContextPlaceholders') || '可用占位符' }}

+
    +
  • + - {{ placeholder.description }} +
  • +
+
+
+
+
+ + +
+ + +
+
+
+
+ +
+
{{ placeholder.description }}
+
+
+
+
+
+
+
@@ -163,6 +299,27 @@ + +
+
+ +

模型生成回复的最大Token数量

+
+
+ +
+
+ + + + +
+
+

{{ $t('agent.editor.conversationSettings') || '多轮对话' }}

+

配置多轮对话和问题改写相关参数

+
+ +
@@ -184,46 +341,74 @@
-
-
- -
-
-

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

-

{{ $t('agent.editor.capabilitiesDesc') || '配置智能体的能力和工具' }}

-
- -
- -
+ +
- -

选择智能体的运行模式

+ +

多轮对话时自动改写用户问题,消解指代和补全省略

- - - {{ $t('agent.type.normal') }} - - - {{ $t('agent.type.agent') }} - - +
- -
-
-
- {{ agentMode === 'agent' ? $t('agent.editor.agentDesc') : $t('agent.editor.normalDesc') }} + +
+
+ +

用于问题改写的系统提示词(留空使用默认)

+
+
+
+ +
- -
+ +
+
+ +

用于问题改写的用户提示词模板(留空使用默认)

+
+
+
+ + +
+
+
+
+
+ + +
+
+

{{ $t('agent.editor.toolsConfig') || '工具配置' }}

+

{{ $t('agent.editor.toolsConfigDesc') || '配置 Agent 可以使用的工具' }}

+
+ +
+ +

选择 Agent 可以使用的工具

@@ -247,8 +432,8 @@
- -
+ +

Agent 执行任务时的最大推理步骤数

@@ -257,12 +442,37 @@
+
+
+ +
+
+

{{ $t('agent.editor.knowledgeConfig') || '知识库' }}

+

{{ $t('agent.editor.knowledgeConfigDesc') || '配置智能体可访问的知识库' }}

+
+ +
-

选择智能体可访问的知识库

+

选择智能体可访问的知识库范围

+
+
+ + {{ $t('agent.editor.allKnowledgeBases') || '全部' }} + {{ $t('agent.editor.selectedKnowledgeBases') || '指定' }} + {{ $t('agent.editor.noKnowledgeBase') || '禁用' }} + +
+
+ + +
+
+ +

选择要关联的知识库

- -
+ +
-

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

+

{{ allowUserKBSelectionDesc }}

@@ -313,7 +523,17 @@
+
+
+ +
+
+

{{ $t('agent.editor.webSearchConfig') || '网络搜索' }}

+

{{ $t('agent.editor.webSearchConfigDesc') || '配置智能体的网络搜索能力' }}

+
+ +
@@ -340,6 +560,159 @@
+ + +
+
+

{{ $t('agent.editor.retrievalStrategy') || '检索策略' }}

+

配置知识库检索和排序的参数

+
+ +
+ +
+
+ +

自动扩展查询词以提高召回率

+
+
+ +
+
+ + +
+
+ +

向量检索返回的最大结果数量

+
+
+ +
+
+ + +
+
+ +

关键词检索的最低相关性分数

+
+
+
+ + {{ formData.config.keyword_threshold?.toFixed(2) }} +
+
+
+ + +
+
+ +

向量检索的最低相似度分数

+
+
+
+ + {{ formData.config.vector_threshold?.toFixed(2) }} +
+
+
+ + +
+
+ +

重排序后保留的最大结果数量

+
+
+ +
+
+ + +
+
+ +

重排序的最低相关性分数

+
+
+
+ + {{ formData.config.rerank_threshold?.toFixed(2) }} +
+
+
+
+
+ + +
+
+

{{ $t('agent.editor.advancedSettings') || '高级设置' }}

+

配置兜底策略

+
+ +
+ +
+
+ +

当无法从知识库找到相关内容时的处理方式

+
+
+ + 固定回复 + 模型生成 + +
+
+ + +
+
+ +

当无法回答时返回的固定文本

+
+
+
+ + +
+
+
+ + +
+
+ +

当无法从知识库找到答案时,引导模型生成回复的提示词

+
+
+
+ + +
+
+
+
+
@@ -362,8 +735,9 @@ import { MessagePlugin } from 'tdesign-vue-next'; import { createAgent, updateAgent, type CustomAgent } from '@/api/agent'; import { listModels } from '@/api/model'; import { listKnowledgeBases } from '@/api/knowledge-base'; -import { getAgentConfig, type PlaceholderDefinition } from '@/api/system'; +import { getAgentConfig, getConversationConfig, type PlaceholderDefinition } from '@/api/system'; import AgentAvatar from '@/components/AgentAvatar.vue'; +import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue'; const { t } = useI18n(); @@ -384,9 +758,28 @@ const modelOptions = ref<{ label: string; value: string }[]>([]); const rerankModelOptions = ref<{ label: string; value: string }[]>([]); const kbOptions = ref<{ label: string; value: string }[]>([]); +// 系统默认配置(用于内置智能体显示默认提示词) +const defaultSystemPrompt = ref(''); +const defaultContextTemplate = ref(''); +const defaultRewritePromptSystem = ref(''); +const defaultRewritePromptUser = ref(''); +const defaultFallbackPrompt = ref(''); +const defaultFallbackResponse = ref(''); +// 默认检索参数 +const defaultEmbeddingTopK = ref(10); +const defaultKeywordThreshold = ref(0.3); +const defaultVectorThreshold = ref(0.5); +const defaultRerankTopK = ref(5); +const defaultRerankThreshold = ref(0.5); +const defaultMaxCompletionTokens = ref(2048); +const defaultTemperature = ref(0.7); + // 知识库相关工具列表 const knowledgeBaseTools = ['grep_chunks', 'knowledge_search', 'list_knowledge_chunks', 'query_knowledge_graph', 'get_document_info', 'database_query']; +// 知识库选择模式:all=全部, selected=指定, none=不使用 +const kbSelectionMode = ref<'all' | 'selected' | 'none'>('none'); + // 可用工具列表 (与后台 definitions.go 保持一致) const allTools = [ { value: 'thinking', label: '思考', description: '动态和反思性的问题解决思考工具', requiresKB: false }, @@ -399,9 +792,17 @@ const allTools = [ { value: 'database_query', label: '查询数据库', description: '查询数据库中的信息', requiresKB: true }, ]; -// 根据知识库配置动态计算可用工具 +// 根据知识库配置动态计算是否有知识库能力 const hasKnowledgeBase = computed(() => { - return (formData.value.config.knowledge_bases?.length > 0) || formData.value.config.allow_user_kb_selection; + return kbSelectionMode.value !== 'none'; +}); + +// 允许用户选择知识库的描述 +const allowUserKBSelectionDesc = computed(() => { + if (kbSelectionMode.value === 'all') { + return t('agent.editor.allowUserKBSelectionDescAll'); + } + return t('agent.editor.allowUserKBSelectionDescSelected'); }); const availableTools = computed(() => { @@ -420,33 +821,98 @@ const placeholderPrefix = ref(''); const popupStyle = ref({ top: '0px', left: '0px' }); let placeholderPopupTimer: any = null; -const navItems = computed(() => [ - { key: 'basic', icon: 'info-circle', label: t('agent.editor.basicInfo') }, - { key: 'capabilities', icon: 'app', label: t('agent.editor.capabilities') }, - { key: 'model', icon: 'control-platform', label: t('agent.editor.modelConfig') }, +// 上下文模板占位符相关 +const contextTemplateTextareaRef = ref(null); +const showContextPlaceholderPopup = ref(false); +const selectedContextPlaceholderIndex = ref(0); +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') || '当前星期(如:星期一)' }, ]); +const navItems = computed(() => { + const items: { key: string; icon: string; label: string }[] = [ + { key: 'basic', icon: 'info-circle', label: t('agent.editor.basicInfo') }, + { key: 'model', icon: 'control-platform', label: t('agent.editor.modelConfig') }, + ]; + // 知识库配置(放在工具上面) + items.push({ key: 'knowledge', icon: 'folder', label: t('agent.editor.knowledgeConfig') || '知识库' }); + // Agent模式才显示工具配置 + if (isAgentMode.value) { + items.push({ key: 'tools', icon: 'tools', label: t('agent.editor.toolsConfig') || '工具配置' }); + } + // 有知识库能力时才显示检索策略 + if (hasKnowledgeBase.value) { + items.push({ key: 'retrieval', icon: 'search', label: t('agent.editor.retrievalStrategy') || '检索策略' }); + } + // 网络搜索(独立菜单) + items.push({ key: 'websearch', icon: 'internet', label: t('agent.editor.webSearchConfig') || '网络搜索' }); + // 多轮对话(仅普通模式显示,Agent模式内部自动控制) + if (!isAgentMode.value) { + items.push({ key: 'conversation', icon: 'chat', label: t('agent.editor.conversationSettings') || '多轮对话' }); + } + // 普通模式才显示高级设置 + if (!isAgentMode.value) { + items.push({ key: 'advanced', icon: 'setting', label: t('agent.editor.advancedSettings') || '高级设置' }); + } + return items; +}); + // 初始数据 const defaultFormData = { name: '', description: '', type: 'custom' as const, + is_builtin: false, config: { - agent_mode: 'normal' as 'normal' | 'agent', // 运行模式 + // 基础设置 + agent_mode: 'normal' as 'normal' | 'agent', system_prompt: '', + system_prompt_web_enabled: '', + context_template: '{{query}}', + // 模型设置 model_id: '', rerank_model_id: '', temperature: 0.7, + max_completion_tokens: 2048, + // Agent模式设置 max_iterations: 10, allowed_tools: [] as string[], + reflection_enabled: false, + // 知识库设置 + kb_selection_mode: 'none' as 'all' | 'selected' | 'none', knowledge_bases: [] as string[], - allow_user_kb_selection: false, // 默认不允许用户选择知识库 + allow_user_kb_selection: false, + // 网络搜索设置 web_search_enabled: false, web_search_max_results: 5, + // 多轮对话设置 + multi_turn_enabled: false, + history_turns: 5, + // 检索策略设置 + embedding_top_k: 10, + keyword_threshold: 0.3, + vector_threshold: 0.5, + rerank_top_k: 5, + rerank_threshold: 0.5, + // 高级设置(普通模式) + enable_query_expansion: true, + enable_rewrite: true, + rewrite_prompt_system: '', + rewrite_prompt_user: '', + fallback_strategy: 'model' as 'fixed' | 'model', + fallback_response: '', + fallback_prompt: '', + // 已废弃字段(保留兼容) welcome_message: '', suggested_prompts: [] as string[], - multi_turn_enabled: false, // 默认关闭多轮对话 - history_turns: 5 } }; @@ -458,16 +924,42 @@ const agentMode = computed({ const isAgentMode = computed(() => agentMode.value === 'agent'); -// 是否需要配置 ReRank 模型(当配置了知识库或允许用户选择知识库时) +// 是否为内置智能体 +const isBuiltinAgent = computed(() => { + return formData.value.is_builtin === true; +}); + +// 系统提示词的 placeholder(内置智能体显示默认提示词,自定义智能体显示普通提示) +const systemPromptPlaceholder = computed(() => { + if (isBuiltinAgent.value && defaultSystemPrompt.value) { + return t('agent.editor.defaultPromptHint') + '\n\n' + defaultSystemPrompt.value; + } + return t('agent.editor.systemPromptPlaceholder'); +}); + +// 上下文模板的 placeholder(内置智能体显示默认模板,自定义智能体显示普通提示) +const contextTemplatePlaceholder = computed(() => { + if (isBuiltinAgent.value && defaultContextTemplate.value) { + return t('agent.editor.defaultContextTemplateHint') + '\n\n' + defaultContextTemplate.value; + } + return t('agent.editor.contextTemplatePlaceholder'); +}); + +// Agent模式系统提示词Tab +const activePromptTab = ref<'web-disabled' | 'web-enabled'>('web-disabled'); + +// 是否需要配置 ReRank 模型(有知识库能力时需要) const needsRerankModel = computed(() => { - const hasKnowledgeBases = formData.value.config.knowledge_bases?.length > 0; - const allowUserKBSelection = formData.value.config.allow_user_kb_selection !== false; - return hasKnowledgeBases || allowUserKBSelection; + return hasKnowledgeBase.value; }); // 监听可见性变化,重置表单 -watch(() => props.visible, (val) => { +watch(() => props.visible, async (val) => { if (val) { + currentSection.value = 'basic'; + // 先加载依赖数据(包括默认配置) + await loadDependencies(); + if (props.mode === 'edit' && props.agent) { // 深度复制对象以避免引用问题 const agentData = JSON.parse(JSON.stringify(props.agent)); @@ -492,14 +984,59 @@ watch(() => props.visible, (val) => { } formData.value = agentData; + // 初始化知识库选择模式 + initKbSelectionMode(); } else { - formData.value = JSON.parse(JSON.stringify(defaultFormData)); + // 创建新智能体,使用系统默认值 + const newFormData = JSON.parse(JSON.stringify(defaultFormData)); + // 应用系统默认检索参数 + newFormData.config.embedding_top_k = defaultEmbeddingTopK.value; + newFormData.config.keyword_threshold = defaultKeywordThreshold.value; + newFormData.config.vector_threshold = defaultVectorThreshold.value; + newFormData.config.rerank_top_k = defaultRerankTopK.value; + newFormData.config.rerank_threshold = defaultRerankThreshold.value; + newFormData.config.max_completion_tokens = defaultMaxCompletionTokens.value; + newFormData.config.temperature = defaultTemperature.value; + // 应用系统默认上下文模板 + if (defaultContextTemplate.value) { + newFormData.config.context_template = defaultContextTemplate.value; + } + formData.value = newFormData; + kbSelectionMode.value = 'none'; } - currentSection.value = 'basic'; - loadDependencies(); } }); +// 初始化知识库选择模式 +const initKbSelectionMode = () => { + if (formData.value.config.kb_selection_mode) { + // 如果有保存的模式,直接使用 + kbSelectionMode.value = formData.value.config.kb_selection_mode; + } 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'; + } +}; + +// 监听知识库选择模式变化 +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 = []; + } + // selected 模式保持 knowledge_bases 不变 +}); + // 监听模式变化,自动调整配置 watch(agentMode, (val) => { if (val === 'agent') { @@ -534,9 +1071,19 @@ watch(agentMode, (val) => { // 监听知识库配置变化,自动移除/添加知识库相关工具 watch(hasKnowledgeBase, (hasKB, oldHasKB) => { - if (!isAgentMode.value) return; // 只在Agent模式下处理 + // 如果当前在检索策略页面但没有知识库能力了,切换到基础设置 + if (!hasKB && currentSection.value === 'retrieval') { + currentSection.value = 'basic'; + } - if (!hasKB && oldHasKB) { + if (!isAgentMode.value) return; // 只在Agent模式下处理工具 + + if (hasKB && !oldHasKB) { + // 从无知识库变为有知识库,自动添加知识库相关工具 + const currentTools = formData.value.config.allowed_tools || []; + const toolsToAdd = knowledgeBaseTools.filter((tool: string) => !currentTools.includes(tool)); + formData.value.config.allowed_tools = [...currentTools, ...toolsToAdd]; + } else if (!hasKB && oldHasKB) { // 从有知识库变为无知识库,移除知识库相关工具 formData.value.config.allowed_tools = formData.value.config.allowed_tools.filter( (tool: string) => !knowledgeBaseTools.includes(tool) @@ -544,6 +1091,18 @@ watch(hasKnowledgeBase, (hasKB, oldHasKB) => { } }); +// 监听运行模式变化,自动切换页面 +watch(isAgentMode, (isAgent) => { + // 如果当前在高级设置页面但切换到了Agent模式,切换到基础设置 + if (isAgent && currentSection.value === 'advanced') { + currentSection.value = 'basic'; + } + // 如果当前在多轮对话页面但切换到了Agent模式,切换到基础设置(Agent模式下多轮对话由内部控制) + if (isAgent && currentSection.value === 'conversation') { + currentSection.value = 'basic'; + } +}); + // 加载依赖数据 const loadDependencies = async () => { try { @@ -570,6 +1129,49 @@ const loadDependencies = async () => { if (agentConfig.data?.available_placeholders) { availablePlaceholders.value = agentConfig.data.available_placeholders; } + + // 加载系统默认配置(用于内置智能体显示默认提示词) + const conversationConfig = await getConversationConfig(); + if (conversationConfig.data?.prompt) { + defaultSystemPrompt.value = conversationConfig.data.prompt; + } + if (conversationConfig.data?.context_template) { + defaultContextTemplate.value = conversationConfig.data.context_template; + } + if (conversationConfig.data?.rewrite_prompt_system) { + defaultRewritePromptSystem.value = conversationConfig.data.rewrite_prompt_system; + } + if (conversationConfig.data?.rewrite_prompt_user) { + defaultRewritePromptUser.value = conversationConfig.data.rewrite_prompt_user; + } + if (conversationConfig.data?.fallback_prompt) { + defaultFallbackPrompt.value = conversationConfig.data.fallback_prompt; + } + if (conversationConfig.data?.fallback_response) { + defaultFallbackResponse.value = conversationConfig.data.fallback_response; + } + // 加载默认检索参数 + if (conversationConfig.data?.embedding_top_k) { + defaultEmbeddingTopK.value = conversationConfig.data.embedding_top_k; + } + if (conversationConfig.data?.keyword_threshold !== undefined) { + defaultKeywordThreshold.value = conversationConfig.data.keyword_threshold; + } + if (conversationConfig.data?.vector_threshold !== undefined) { + defaultVectorThreshold.value = conversationConfig.data.vector_threshold; + } + if (conversationConfig.data?.rerank_top_k) { + defaultRerankTopK.value = conversationConfig.data.rerank_top_k; + } + if (conversationConfig.data?.rerank_threshold !== undefined) { + defaultRerankThreshold.value = conversationConfig.data.rerank_threshold; + } + if (conversationConfig.data?.max_completion_tokens) { + defaultMaxCompletionTokens.value = conversationConfig.data.max_completion_tokens; + } + if (conversationConfig.data?.temperature !== undefined) { + defaultTemperature.value = conversationConfig.data.temperature; + } } catch (e) { console.error('Failed to load dependencies', e); } @@ -577,6 +1179,7 @@ const loadDependencies = async () => { const handleClose = () => { showPlaceholderPopup.value = false; + showContextPlaceholderPopup.value = false; emit('update:visible', false); }; @@ -591,6 +1194,17 @@ const filteredPlaceholders = computed(() => { ); }); +// 过滤后的上下文模板占位符列表 +const filteredContextPlaceholders = computed(() => { + if (!contextPlaceholderPrefix.value) { + return contextTemplatePlaceholders.value; + } + const prefix = contextPlaceholderPrefix.value.toLowerCase(); + return contextTemplatePlaceholders.value.filter(p => + p.name.toLowerCase().startsWith(prefix) + ); +}); + // 获取 textarea 元素 const getTextareaElement = (): HTMLTextAreaElement | null => { if (promptTextareaRef.value) { @@ -733,6 +1347,186 @@ const insertPlaceholder = (placeholderName: string) => { }); }; +// 获取上下文模板 textarea 元素 +const getContextTemplateTextareaElement = (): HTMLTextAreaElement | null => { + if (contextTemplateTextareaRef.value) { + if (contextTemplateTextareaRef.value.$el) { + return contextTemplateTextareaRef.value.$el.querySelector('textarea'); + } + if (contextTemplateTextareaRef.value instanceof HTMLTextAreaElement) { + return contextTemplateTextareaRef.value; + } + } + return null; +}; + +// 计算上下文模板光标位置 +const calculateContextCursorPosition = (textarea: HTMLTextAreaElement) => { + const cursorPos = textarea.selectionStart; + const textBeforeCursor = formData.value.config.context_template.substring(0, cursorPos); + + const style = window.getComputedStyle(textarea); + const textareaRect = textarea.getBoundingClientRect(); + + const lineHeight = parseFloat(style.lineHeight) || 20; + const paddingTop = parseFloat(style.paddingTop) || 0; + const paddingLeft = parseFloat(style.paddingLeft) || 0; + + const lines = textBeforeCursor.split('\n'); + const currentLine = lines.length - 1; + const currentLineText = lines[currentLine]; + + 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 checkAndShowContextPlaceholderPopup = () => { + const textarea = getContextTemplateTextareaElement(); + if (!textarea) return; + + const cursorPos = textarea.selectionStart; + const textBeforeCursor = formData.value.config.context_template.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) { + showContextPlaceholderPopup.value = false; + contextPlaceholderPrefix.value = ''; + return; + } + + const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2); + contextPlaceholderPrefix.value = textAfterOpen; + + const filtered = filteredContextPlaceholders.value; + if (filtered.length > 0) { + nextTick(() => { + const position = calculateContextCursorPosition(textarea); + contextPopupStyle.value = { + top: `${position.top}px`, + left: `${position.left}px` + }; + showContextPlaceholderPopup.value = true; + selectedContextPlaceholderIndex.value = 0; + }); + } else { + showContextPlaceholderPopup.value = false; + } +}; + +// 处理上下文模板输入 +const handleContextTemplateInput = () => { + if (contextPlaceholderPopupTimer) { + clearTimeout(contextPlaceholderPopupTimer); + } + contextPlaceholderPopupTimer = setTimeout(() => { + checkAndShowContextPlaceholderPopup(); + }, 50); +}; + +// 插入上下文模板占位符 +const insertContextPlaceholder = (placeholderName: string) => { + const textarea = getContextTemplateTextareaElement(); + if (!textarea) return; + + showContextPlaceholderPopup.value = false; + contextPlaceholderPrefix.value = ''; + selectedContextPlaceholderIndex.value = 0; + + nextTick(() => { + const cursorPos = textarea.selectionStart; + 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] === '{') { + 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(); + }); + } + }); +}; + +// 设置上下文模板 textarea 事件监听 +const setupContextTemplateEventListeners = () => { + nextTick(() => { + const textarea = getContextTemplateTextareaElement(); + if (textarea) { + textarea.addEventListener('keydown', (e: KeyboardEvent) => { + if (showContextPlaceholderPopup.value && filteredContextPlaceholders.value.length > 0) { + if (e.key === 'ArrowDown') { + e.preventDefault(); + e.stopPropagation(); + if (selectedContextPlaceholderIndex.value < filteredContextPlaceholders.value.length - 1) { + selectedContextPlaceholderIndex.value++; + } else { + selectedContextPlaceholderIndex.value = 0; + } + } else if (e.key === 'ArrowUp') { + e.preventDefault(); + e.stopPropagation(); + if (selectedContextPlaceholderIndex.value > 0) { + selectedContextPlaceholderIndex.value--; + } else { + selectedContextPlaceholderIndex.value = filteredContextPlaceholders.value.length - 1; + } + } else if (e.key === 'Enter' || e.key === 'Tab') { + e.preventDefault(); + e.stopPropagation(); + const selected = filteredContextPlaceholders.value[selectedContextPlaceholderIndex.value]; + if (selected) { + insertContextPlaceholder(selected.name); + } + } else if (e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + showContextPlaceholderPopup.value = false; + contextPlaceholderPrefix.value = ''; + } + } + }, true); + } + }); +}; + // 设置 textarea 事件监听 const setupTextareaEventListeners = () => { nextTick(() => { @@ -780,22 +1574,62 @@ watch(() => props.visible, (val) => { if (val) { nextTick(() => { setupTextareaEventListeners(); + setupContextTemplateEventListeners(); }); } }); -const handleSave = async () => { - // 验证必填项 - if (!formData.value.name || !formData.value.name.trim()) { - MessagePlugin.error(t('agent.editor.nameRequired')); - currentSection.value = 'basic'; - return; +// 模板选择处理函数 +const handleSystemPromptTemplateSelect = (template: string) => { + if (activePromptTab.value === 'web-enabled') { + formData.value.config.system_prompt_web_enabled = template; + } else { + formData.value.config.system_prompt = template; } +}; - if (!formData.value.config.system_prompt || !formData.value.config.system_prompt.trim()) { - MessagePlugin.error(t('agent.editor.systemPromptRequired')); - currentSection.value = 'basic'; - return; +const handleContextTemplateSelect = (template: string) => { + formData.value.config.context_template = template; +}; + +const handleRewriteSystemTemplateSelect = (template: string) => { + formData.value.config.rewrite_prompt_system = template; +}; + +const handleRewriteUserTemplateSelect = (template: string) => { + formData.value.config.rewrite_prompt_user = template; +}; + +const handleFallbackResponseTemplateSelect = (template: string) => { + formData.value.config.fallback_response = template; +}; + +const handleFallbackPromptTemplateSelect = (template: string) => { + formData.value.config.fallback_prompt = template; +}; + +const handleSave = async () => { + // 验证必填项(内置智能体不验证名称和系统提示词) + if (!isBuiltinAgent.value) { + if (!formData.value.name || !formData.value.name.trim()) { + MessagePlugin.error(t('agent.editor.nameRequired')); + currentSection.value = 'basic'; + return; + } + + // 自定义智能体必须填写系统提示词 + if (!formData.value.config.system_prompt || !formData.value.config.system_prompt.trim()) { + MessagePlugin.error(t('agent.editor.systemPromptRequired')); + currentSection.value = 'basic'; + return; + } + + // 自定义智能体普通模式必须填写上下文模板 + if (!isAgentMode.value && (!formData.value.config.context_template || !formData.value.config.context_template.trim())) { + MessagePlugin.error(t('agent.editor.contextTemplateRequired')); + currentSection.value = 'basic'; + return; + } } if (!formData.value.config.model_id) { @@ -807,7 +1641,7 @@ const handleSave = async () => { // 校验 ReRank 模型(当需要时必填) if (needsRerankModel.value && !formData.value.config.rerank_model_id) { MessagePlugin.error(t('agent.editor.rerankModelRequired')); - currentSection.value = 'capabilities'; + currentSection.value = 'knowledge'; return; } @@ -816,10 +1650,10 @@ const handleSave = async () => { formData.value.config.suggested_prompts = formData.value.config.suggested_prompts.filter((p: string) => p.trim() !== ''); } - // 确保类型设置正确 - // 注意:我们始终保持 type 为 'custom',通过 config 来区分行为 - // 如果需要后端严格区分 type 字段,可以在这里修改 - formData.value.type = 'custom'; + // 确保类型设置正确(内置智能体保持原类型) + if (!isBuiltinAgent.value) { + formData.value.type = 'custom'; + } saving.value = true; try { @@ -1033,6 +1867,17 @@ const handleSave = async () => { padding-right: 0; } + .setting-info-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 4px; + + label { + margin-bottom: 0; + } + } + label { font-size: 15px; font-weight: 500; @@ -1331,6 +2176,12 @@ const handleSave = async () => { } } +// textarea 与模板选择器容器 +.textarea-with-template { + position: relative; + width: 100%; +} + // 系统提示词输入框样式 .system-prompt-textarea { width: 100%; @@ -1432,4 +2283,57 @@ const handleSave = async () => { color: #666; } } + +// 内置智能体提示 +.builtin-agent-notice { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 16px; + background: #fff7e6; + border: 1px solid #ffd591; + border-radius: 8px; + margin-bottom: 16px; + color: #d46b08; + font-size: 14px; + + .t-icon { + font-size: 16px; + flex-shrink: 0; + } +} + +// 提示词开关 +.prompt-toggle { + display: flex; + align-items: center; + gap: 12px; + margin-top: 12px; + + .prompt-toggle-label { + font-size: 13px; + color: #666; + } +} + +// 提示词禁用提示 +.prompt-disabled-hint { + color: #999; + font-size: 13px; + font-style: italic; + padding: 12px 16px; + background: #f5f5f5; + border-radius: 6px; +} + +// 系统提示词Tabs +.system-prompt-tabs { + width: 100%; + + .prompt-variant-tabs { + :deep(.t-tabs__nav) { + margin-bottom: 12px; + } + } +} diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue index b286b5a2..f218a83d 100644 --- a/frontend/src/views/agent/AgentList.vue +++ b/frontend/src/views/agent/AgentList.vue @@ -37,6 +37,10 @@
{{ agent.name }} +
+ + {{ $t('agent.builtin') }} +
-
- - {{ $t('agent.builtin') }} + +
+
@@ -178,13 +182,11 @@ const fetchList = () => { loading.value = true return listAgents().then((res: any) => { const data = res.data || [] - // 过滤掉内置智能体,只展示自定义智能体 - agents.value = data - .filter((agent: CustomAgent) => !agent.is_builtin) - .map((agent: CustomAgent) => ({ - ...agent, - showMore: false - })) + // 显示所有智能体(包括内置智能体) + agents.value = data.map((agent: CustomAgent) => ({ + ...agent, + showMore: false + })) }).finally(() => loading.value = false) } @@ -215,13 +217,8 @@ const handleCardClick = (agent: AgentWithUI) => { if (agent.showMore) { return } - // 点击卡片查看详情或编辑 - if (agent.is_builtin) { - // 内置智能体只能查看 - MessagePlugin.info(t('agent.messages.builtinReadonly')) - } else { - handleEdit(agent) - } + // 点击卡片编辑(包括内置智能体) + handleEdit(agent) } const handleEdit = (agent: AgentWithUI) => { @@ -456,6 +453,25 @@ defineExpose({ font-family: "PingFang SC"; font-size: 12px; font-weight: 400; + flex-shrink: 0; +} + +.edit-btn { + display: flex; + width: 32px; + height: 32px; + justify-content: center; + align-items: center; + border-radius: 6px; + cursor: pointer; + flex-shrink: 0; + transition: all 0.2s ease; + color: #00000066; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: #07c05f; + } } .more-wrap { diff --git a/frontend/src/views/settings/AgentSettings.vue b/frontend/src/views/settings/AgentSettings.vue index 2164da69..86cc9af7 100644 --- a/frontend/src/views/settings/AgentSettings.vue +++ b/frontend/src/views/settings/AgentSettings.vue @@ -4,6 +4,10 @@

{{ $t('settings.conversationStrategy') }}

{{ $t('conversationSettings.description') }}

+
+ + 这些是全局默认配置,新建智能体时会继承这些设置。您也可以在智能体列表中单独配置每个智能体。 +
@@ -146,17 +150,7 @@
-
- {{ $t('agentSettings.systemPrompt.custom') }} - -

- {{ $t('agentSettings.systemPrompt.tabHint') }} + {{ $t('agentSettings.systemPrompt.tabHint') }}(留空则使用系统默认)

-

- {{ $t('agentSettings.systemPrompt.disabledHint') }} -

-
+
-
+
+
-
+
+
@@ -214,7 +213,7 @@
@@ -249,24 +248,10 @@
-

{{ $t('conversationSettings.systemPrompt.desc') }}

+

{{ $t('conversationSettings.systemPrompt.desc') }}(留空则使用系统默认)

-
-
- {{ $t('conversationSettings.systemPrompt.custom') }} - -
-
-

- {{ $t('conversationSettings.systemPrompt.disabledHint') }} -

-
+
+
- +
-

{{ $t('conversationSettings.contextTemplate.desc') }}

+

{{ $t('conversationSettings.contextTemplate.desc') }}(留空则使用系统默认)

-
-
- {{ $t('conversationSettings.contextTemplate.custom') }} - -
-
-

- {{ $t('conversationSettings.contextTemplate.disabledHint') }} -

-
+
+
@@ -540,11 +523,18 @@

{{ $t('conversationSettings.rewritePrompt.desc') }}

- +
+ + +
@@ -554,11 +544,18 @@

{{ $t('conversationSettings.rewritePrompt.userDesc') }}

- +
+ + +
@@ -583,26 +580,40 @@

{{ $t('conversationSettings.fallbackResponse.desc') }}

- +
+ + +
- +

{{ $t('conversationSettings.fallbackPrompt.desc') }}

- +
+ + +
@@ -659,6 +670,7 @@ import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next' import { useI18n } from 'vue-i18n' import { listModels, type ModelConfig } from '@/api/model' import { getAgentConfig, updateAgentConfig, getConversationConfig, updateConversationConfig, type AgentConfig, type ConversationConfig, type ToolDefinition, type PlaceholderDefinition } from '@/api/system' +import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue' const props = defineProps<{ // 来自外部设置弹窗的子菜单 key: 'modes' | 'models' | 'thresholds' | 'advanced' @@ -680,8 +692,6 @@ const getDefaultConversationConfig = (): ConversationConfig => ({ context_template: '', temperature: 0.3, max_completion_tokens: 2048, - use_custom_system_prompt: true, - use_custom_context_template: true, max_rounds: 5, embedding_top_k: 10, keyword_threshold: 0.3, @@ -727,7 +737,6 @@ const savedSystemPromptMap: Record = { } const getPromptRefByTab = (tab: SystemPromptTab) => systemPromptRefs[tab] const getActivePromptRef = () => getPromptRefByTab(activeSystemPromptTab.value) -const localUseCustomSystemPrompt = ref(false) // 普通模式本地状态 const localContextTemplate = ref('') @@ -755,10 +764,6 @@ const localRewritePromptUser = ref('') const localSummaryModelId = ref('') const localConversationRerankModelId = ref('') -// 普通模式 Prompt 是否自定义(关闭时使用系统默认) -const localUseCustomSystemPromptNormal = ref(true) -const localUseCustomContextTemplate = ref(true) - const syncConversationLocals = () => { const cfg = conversationConfig.value localContextTemplate.value = cfg.context_template ?? '' @@ -785,8 +790,6 @@ const syncConversationLocals = () => { localRewritePromptUser.value = cfg.rewrite_prompt_user ?? '' localSummaryModelId.value = cfg.summary_model_id ?? '' localConversationRerankModelId.value = cfg.rerank_model_id ?? '' - localUseCustomSystemPromptNormal.value = cfg.use_custom_system_prompt ?? true - localUseCustomContextTemplate.value = cfg.use_custom_context_template ?? true settingsStore.updateConversationModels({ summaryModelId: localSummaryModelId.value || '', @@ -837,7 +840,6 @@ const buildAgentConfigPayload = (overrides: Partial = {}): AgentCon temperature: localTemperature.value, system_prompt_web_enabled: localSystemPromptWebEnabled.value, system_prompt_web_disabled: localSystemPromptWebDisabled.value, - use_custom_system_prompt: localUseCustomSystemPrompt.value, ...overrides, }) @@ -916,9 +918,6 @@ const loadingConfig = ref(false) const configLoaded = ref(false) // 防止重复加载 const isInitializing = ref(true) // 标记是否正在初始化,防止初始化时触发保存 -// 保存的 Prompt 值,用于比较是否变化 -let savedUseCustomSystemPrompt = false - // 恢复默认 Prompt 的加载状态 const isResettingPrompt = ref(false) @@ -1055,9 +1054,6 @@ onMounted(async () => { localSystemPromptWebDisabled.value = promptWebDisabled savedSystemPromptMap['web-enabled'] = promptWebEnabled savedSystemPromptMap['web-disabled'] = promptWebDisabled - const useCustomPrompt = config.use_custom_system_prompt ?? false - localUseCustomSystemPrompt.value = useCustomPrompt - savedUseCustomSystemPrompt = useCustomPrompt availableTools.value = config.available_tools || [] availablePlaceholders.value = config.available_placeholders || [] @@ -1076,7 +1072,6 @@ onMounted(async () => { allowedTools: config.allowed_tools || [], system_prompt_web_enabled: promptWebEnabled, system_prompt_web_disabled: promptWebDisabled, - use_custom_system_prompt: useCustomPrompt }) // 加载普通模式配置 @@ -1232,25 +1227,6 @@ const handleTemperatureChange = async (value: number) => { } } -// 切换是否启用自定义 Prompt -const handleUseCustomPromptToggle = async (value: boolean) => { - if (isInitializing.value) return - if (value === savedUseCustomSystemPrompt) return - - try { - const config = buildAgentConfigPayload({ use_custom_system_prompt: value }) - await updateAgentConfig(config) - savedUseCustomSystemPrompt = value - - MessagePlugin.success(value ? t('agentSettings.toasts.customPromptEnabled') : t('agentSettings.toasts.defaultPromptEnabled')) - } catch (error) { - console.error('切换自定义 Prompt 失败:', error) - MessagePlugin.error(getErrorMessage(error)) - // 回滚开关状态 - localUseCustomSystemPrompt.value = savedUseCustomSystemPrompt - } -} - // 处理系统 Prompt 键盘事件(作为备用,主要逻辑在原生事件监听器中) const handlePromptKeydown = (e: KeyboardEvent) => { // 如果正在显示占位符提示,且输入的是字母、数字或下划线,实时更新过滤 @@ -1461,7 +1437,6 @@ const handleResetToDefault = async () => { const tempConfig = buildAgentConfigPayload({ system_prompt_web_enabled: '', system_prompt_web_disabled: '', - use_custom_system_prompt: false, }) await updateAgentConfig(tempConfig) @@ -1470,15 +1445,12 @@ const handleResetToDefault = async () => { const res = await getAgentConfig() const defaultPromptWebEnabled = res.data.system_prompt_web_enabled || '' const defaultPromptWebDisabled = res.data.system_prompt_web_disabled || '' - const useCustom = res.data.use_custom_system_prompt ?? false // 设置为默认 Prompt 的内容 localSystemPromptWebEnabled.value = defaultPromptWebEnabled localSystemPromptWebDisabled.value = defaultPromptWebDisabled savedSystemPromptMap['web-enabled'] = defaultPromptWebEnabled savedSystemPromptMap['web-disabled'] = defaultPromptWebDisabled - localUseCustomSystemPrompt.value = useCustom - savedUseCustomSystemPrompt = useCustom MessagePlugin.success(t('agentSettings.toasts.resetToDefault')) confirmDialog.hide() @@ -1559,7 +1531,6 @@ const handleContextTemplateChange = async () => { await saveConversationConfig( { context_template: localContextTemplate.value, - use_custom_context_template: localUseCustomContextTemplate.value, }, t('conversationSettings.toasts.contextTemplateSaved') ) @@ -1576,66 +1547,6 @@ const reloadConversationConfig = async () => { syncConversationLocals() } -const handleUseCustomSystemPromptNormalToggle = async (value: boolean) => { - if (!conversationConfigLoaded.value) return - - try { - if (!value) { - await saveConversationConfig( - { - prompt: '', - use_custom_system_prompt: false, - }, - t('conversationSettings.toasts.defaultPromptEnabled') - ) - await reloadConversationConfig() - } else { - await saveConversationConfig( - { - prompt: localSystemPromptNormal.value, - use_custom_system_prompt: true, - }, - t('conversationSettings.toasts.customPromptEnabled') - ) - savedSystemPromptNormal = localSystemPromptNormal.value - } - } catch (error) { - console.error('切换普通模式 System Prompt 自定义失败:', error) - MessagePlugin.error(getErrorMessage(error)) - localUseCustomSystemPromptNormal.value = !value - } -} - -const handleUseCustomContextTemplateToggle = async (value: boolean) => { - if (!conversationConfigLoaded.value) return - - try { - if (!value) { - await saveConversationConfig( - { - context_template: '', - use_custom_context_template: false, - }, - t('conversationSettings.toasts.defaultContextTemplateEnabled') - ) - await reloadConversationConfig() - } else { - await saveConversationConfig( - { - context_template: localContextTemplate.value, - use_custom_context_template: true, - }, - t('conversationSettings.toasts.customContextTemplateEnabled') - ) - savedContextTemplate = localContextTemplate.value - } - } catch (error) { - console.error('切换普通模式 Context Template 自定义失败:', error) - MessagePlugin.error(getErrorMessage(error)) - localUseCustomContextTemplate.value = !value - } -} - const handleSystemPromptNormalChange = async () => { if (!conversationConfigLoaded.value) return @@ -1647,7 +1558,6 @@ const handleSystemPromptNormalChange = async () => { await saveConversationConfig( { prompt: localSystemPromptNormal.value, - use_custom_system_prompt: localUseCustomSystemPromptNormal.value, }, t('conversationSettings.toasts.systemPromptSaved') ) @@ -1813,6 +1723,39 @@ const handleFallbackPromptChange = async () => { } } +// 模板选择处理函数 +const handleAgentSystemPromptTemplateSelect = (template: string) => { + if (activeSystemPromptTab.value === 'web-enabled') { + localSystemPromptWebEnabled.value = template + } else { + localSystemPromptWebDisabled.value = template + } +} + +const handleNormalSystemPromptTemplateSelect = (template: string) => { + localSystemPromptNormal.value = template +} + +const handleContextTemplateTemplateSelect = (template: string) => { + localContextTemplate.value = template +} + +const handleRewriteSystemTemplateSelect = (template: string) => { + localRewritePromptSystem.value = template +} + +const handleRewriteUserTemplateSelect = (template: string) => { + localRewritePromptUser.value = template +} + +const handleFallbackResponseTemplateSelect = (template: string) => { + localFallbackResponse.value = template +} + +const handleFallbackPromptTemplateSelect = (template: string) => { + localFallbackPrompt.value = template +} + const navigateToModelSettings = (subsection: 'chat' | 'rerank') => { router.push('/platform/settings') @@ -1881,9 +1824,29 @@ const handleConversationRerankModelChange = async (value: string) => { .section-description { font-size: 14px; color: #666666; - margin: 0 0 20px 0; + margin: 0 0 12px 0; line-height: 1.5; } + + .global-config-notice { + display: flex; + align-items: flex-start; + gap: 8px; + padding: 12px 16px; + background: #f0f9ff; + border: 1px solid #bae0ff; + border-radius: 8px; + margin-bottom: 20px; + color: #0958d9; + font-size: 13px; + line-height: 1.5; + + .t-icon { + font-size: 16px; + flex-shrink: 0; + margin-top: 2px; + } + } } .agent-status-row { @@ -2056,6 +2019,17 @@ const handleConversationRerankModelChange = async (value: string) => { word-break: keep-all; white-space: normal; + .setting-info-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 4px; + + label { + margin-bottom: 0; + } + } + label { font-size: 15px; font-weight: 500; @@ -2263,6 +2237,11 @@ const handleConversationRerankModelChange = async (value: string) => { width: 100%; } +.textarea-with-template { + position: relative; + width: 100%; +} + .setting-control.full-width { display: flex; flex-direction: column; diff --git a/internal/application/repository/custom_agent.go b/internal/application/repository/custom_agent.go index 70a10612..5a8a339f 100644 --- a/internal/application/repository/custom_agent.go +++ b/internal/application/repository/custom_agent.go @@ -27,10 +27,10 @@ func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.Cu return r.db.WithContext(ctx).Create(agent).Error } -// GetAgentByID gets an agent by id -func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) { +// GetAgentByID gets an agent by id and tenant +func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) { var agent types.CustomAgent - if err := r.db.WithContext(ctx).Where("id = ?", id).First(&agent).Error; err != nil { + if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&agent).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrCustomAgentNotFound } diff --git a/internal/application/service/chat_pipline/common.go b/internal/application/service/chat_pipline/common.go index cf28ff6a..dcda8d30 100644 --- a/internal/application/service/chat_pipline/common.go +++ b/internal/application/service/chat_pipline/common.go @@ -2,6 +2,8 @@ package chatpipline import ( "context" + "strings" + "time" "github.com/Tencent/WeKnora/internal/common" "github.com/Tencent/WeKnora/internal/logger" @@ -51,8 +53,11 @@ func prepareChatModel(ctx context.Context, modelService interfaces.ModelService, // prepareMessagesWithHistory prepare complete messages including history func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message { + // Replace placeholders in system prompt + systemPrompt := renderSystemPromptPlaceholders(chatManage.SummaryConfig.Prompt) + chatMessages := []chat.Message{ - {Role: "system", Content: chatManage.SummaryConfig.Prompt}, + {Role: "system", Content: systemPrompt}, } chatHistory := chatManage.History @@ -71,3 +76,18 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message { return chatMessages } + +// renderSystemPromptPlaceholders replaces placeholders in system prompt +// Supported placeholders: +// - {{current_time}} -> current time in RFC3339 format +func renderSystemPromptPlaceholders(prompt string) string { + result := prompt + + // Replace {{current_time}} placeholder + if strings.Contains(result, "{{current_time}}") { + currentTime := time.Now().Format(time.RFC3339) + result = strings.ReplaceAll(result, "{{current_time}}", currentTime) + } + + return result +} diff --git a/internal/application/service/chat_pipline/into_chat_message.go b/internal/application/service/chat_pipline/into_chat_message.go index 4193345f..73d92b1e 100644 --- a/internal/application/service/chat_pipline/into_chat_message.go +++ b/internal/application/service/chat_pipline/into_chat_message.go @@ -1,11 +1,9 @@ package chatpipline import ( - "bytes" "context" "encoding/json" "fmt" - "html/template" "regexp" "strings" "time" @@ -46,20 +44,6 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context, passages[i] = getEnrichedPassageForChat(ctx, result) } - // Parse the context template - tmpl, err := template.New("searchContent").Parse(chatManage.SummaryConfig.ContextTemplate) - if err != nil { - pipelineError(ctx, "IntoChatMessage", "parse_template", map[string]interface{}{ - "session_id": chatManage.SessionID, - "error": err.Error(), - }) - return ErrTemplateParse.WithError(err) - } - - // Prepare weekday names for template - weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"} - var userContent bytes.Buffer - // 验证用户查询的安全性 safeQuery, isValid := secutils.ValidateInput(chatManage.Query) if !isValid { @@ -69,23 +53,27 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context, return ErrTemplateExecute.WithError(fmt.Errorf("用户查询包含非法内容")) } - // Execute template with context data - err = tmpl.Execute(&userContent, map[string]interface{}{ - "Query": safeQuery, // User's original query - "Contexts": passages, // Extracted passages from search results - "CurrentTime": time.Now().Format("2006-01-02 15:04:05"), // Formatted current time - "CurrentWeek": weekdayName[time.Now().Weekday()], // Current weekday in Chinese - }) - if err != nil { - pipelineError(ctx, "IntoChatMessage", "render_template", map[string]interface{}{ - "session_id": chatManage.SessionID, - "error": err.Error(), - }) - return ErrTemplateExecute.WithError(err) + // Prepare weekday names + weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"} + + // Build contexts string from passages + var contextsBuilder strings.Builder + for i, passage := range passages { + if i > 0 { + contextsBuilder.WriteString("\n\n") + } + contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage)) } + // Replace placeholders in context template + userContent := chatManage.SummaryConfig.ContextTemplate + userContent = strings.ReplaceAll(userContent, "{{query}}", safeQuery) + userContent = strings.ReplaceAll(userContent, "{{contexts}}", contextsBuilder.String()) + userContent = strings.ReplaceAll(userContent, "{{current_time}}", time.Now().Format("2006-01-02 15:04:05")) + userContent = strings.ReplaceAll(userContent, "{{current_week}}", weekdayName[time.Now().Weekday()]) + // Set formatted content back to chat management - chatManage.UserContent = userContent.String() + chatManage.UserContent = userContent pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{ "session_id": chatManage.SessionID, "user_content_len": len(chatManage.UserContent), diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index c4ad9c6e..f375037c 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -16,7 +16,7 @@ import ( // Custom agent related errors var ( ErrAgentNotFound = errors.New("agent not found") - ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent") + ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent basic info") ErrCannotDeleteBuiltin = errors.New("cannot delete built-in agent") ErrAgentNameRequired = errors.New("agent name is required") ) @@ -96,15 +96,22 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type } // Check if it's a built-in agent - if id == types.BuiltinAgentNormalID { - return types.GetBuiltinNormalAgent(tenantID), nil - } - if id == types.BuiltinAgentAgentID { + if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID { + // 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 config + return agent, nil + } + // Not in database, return default built-in agent + if id == types.BuiltinAgentNormalID { + return types.GetBuiltinNormalAgent(tenantID), nil + } return types.GetBuiltinAgentAgent(tenantID), nil } // Query from database - agent, err := s.repo.GetAgentByID(ctx, id) + agent, err := s.repo.GetAgentByID(ctx, id, tenantID) if err != nil { if errors.Is(err, repository.ErrCustomAgentNotFound) { return nil, ErrAgentNotFound @@ -115,11 +122,6 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type return nil, err } - // Verify tenant ownership - if agent.TenantID != tenantID { - return nil, ErrAgentNotFound - } - return agent, nil } @@ -130,11 +132,8 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge return nil, ErrInvalidTenantID } - // Get built-in agents first - builtinAgents := types.GetBuiltinAgents(tenantID) - - // Get custom agents from database - customAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID) + // Get all agents from database (including built-in agents with customized config) + allAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ "tenant_id": tenantID, @@ -142,10 +141,51 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge return nil, err } - // Combine: built-in agents first, then custom agents - result := make([]*types.CustomAgent, 0, len(builtinAgents)+len(customAgents)) - result = append(result, builtinAgents...) - result = append(result, customAgents...) + // Check if built-in agents exist in database + hasNormalBuiltin := false + hasAgentBuiltin := false + for _, agent := range allAgents { + if agent.ID == types.BuiltinAgentNormalID { + hasNormalBuiltin = true + } + if agent.ID == types.BuiltinAgentAgentID { + hasAgentBuiltin = 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 + } + } + } else { + result = append(result, types.GetBuiltinNormalAgent(tenantID)) + } + + // Add built-in agent mode agent + if hasAgentBuiltin { + for _, agent := range allAgents { + if agent.ID == types.BuiltinAgentAgentID { + result = append(result, agent) + break + } + } + } else { + result = append(result, types.GetBuiltinAgentAgent(tenantID)) + } + + // Add custom agents + for _, agent := range allAgents { + if agent.ID != types.BuiltinAgentNormalID && agent.ID != types.BuiltinAgentAgentID { + result = append(result, agent) + } + } return result, nil } @@ -157,19 +197,20 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo return nil, errors.New("agent ID cannot be empty") } - // Cannot modify built-in agents - if agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID { - return nil, ErrCannotModifyBuiltin - } - // Get tenant ID from context tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64) if !ok { return nil, ErrInvalidTenantID } + // Handle built-in agents specially + isBuiltinAgent := agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID + if isBuiltinAgent { + return s.updateBuiltinAgent(ctx, agent, tenantID) + } + // Get existing agent - existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID) + existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID) if err != nil { if errors.Is(err, repository.ErrCustomAgentNotFound) { return nil, ErrAgentNotFound @@ -177,11 +218,6 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo return nil, err } - // Verify tenant ownership - if existingAgent.TenantID != tenantID { - return nil, ErrAgentNotFound - } - // Cannot modify built-in status if existingAgent.IsBuiltin { return nil, ErrCannotModifyBuiltin @@ -216,6 +252,70 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo return existingAgent, nil } +// 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) + } + + // Try to get existing customized config from database + existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID) + if err != nil && !errors.Is(err, repository.ErrCustomAgentNotFound) { + return nil, err + } + + if existingAgent != nil { + // Update existing record - only update config, keep basic info unchanged + existingAgent.Config = agent.Config + existingAgent.UpdatedAt = time.Now() + existingAgent.EnsureDefaults() + + logger.Infof(ctx, "Updating built-in agent config, ID: %s", agent.ID) + + if err := s.repo.UpdateAgent(ctx, existingAgent); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": agent.ID, + }) + return nil, err + } + + logger.Infof(ctx, "Built-in agent config updated successfully, ID: %s", agent.ID) + return existingAgent, nil + } + + // Create new record for built-in agent with customized config + newAgent := &types.CustomAgent{ + ID: defaultAgent.ID, + Name: defaultAgent.Name, + Description: defaultAgent.Description, + Avatar: defaultAgent.Avatar, + IsBuiltin: true, + Type: defaultAgent.Type, + TenantID: tenantID, + Config: agent.Config, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + } + newAgent.EnsureDefaults() + + logger.Infof(ctx, "Creating built-in agent config record, ID: %s, tenant ID: %d", agent.ID, tenantID) + + if err := s.repo.CreateAgent(ctx, newAgent); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": agent.ID, + "tenant_id": tenantID, + }) + return nil, err + } + + logger.Infof(ctx, "Built-in agent config record created successfully, ID: %s", agent.ID) + return newAgent, nil +} + // DeleteAgent deletes an agent func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error { if id == "" { @@ -235,7 +335,7 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error { } // Get existing agent to verify ownership - existingAgent, err := s.repo.GetAgentByID(ctx, id) + existingAgent, err := s.repo.GetAgentByID(ctx, id, tenantID) if err != nil { if errors.Is(err, repository.ErrCustomAgentNotFound) { return ErrAgentNotFound @@ -243,11 +343,6 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error { return err } - // Verify tenant ownership - if existingAgent.TenantID != tenantID { - return ErrAgentNotFound - } - // Cannot delete built-in agents if existingAgent.IsBuiltin { return ErrCannotDeleteBuiltin diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index fe18c966..9ca706bb 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -3403,47 +3403,6 @@ func (s *knowledgeService) GetFAQEntry(ctx context.Context, return entry, nil } -// GetFAQEntry retrieves a single FAQ entry by ID. -func (s *knowledgeService) GetFAQEntry(ctx context.Context, - kbID string, entryID string, -) (*types.FAQEntry, error) { - if entryID == "" { - return nil, werrors.NewBadRequestError("条目ID不能为空") - } - - kb, err := s.validateFAQKnowledgeBase(ctx, kbID) - if err != nil { - return nil, err - } - kb.EnsureDefaults() - - tenantID := ctx.Value(types.TenantIDContextKey).(uint64) - - // 获取chunk - chunk, err := s.chunkService.GetChunkByID(ctx, entryID) - if err != nil { - return nil, err - } - - // 验证chunk属于当前知识库 - if chunk.KnowledgeBaseID != kb.ID || chunk.TenantID != tenantID { - return nil, werrors.NewNotFoundError("FAQ条目不存在") - } - - // 验证是FAQ类型 - if chunk.ChunkType != types.ChunkTypeFAQ { - return nil, werrors.NewNotFoundError("FAQ条目不存在") - } - - // 转换为FAQEntry返回 - entry, err := s.chunkToFAQEntry(chunk, kb) - if err != nil { - return nil, err - } - - return entry, nil -} - // UpdateFAQEntry updates a single FAQ entry. func (s *knowledgeService) UpdateFAQEntry(ctx context.Context, kbID string, entryID string, payload *types.FAQEntryPayload, @@ -5901,4 +5860,3 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, } return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit) } - diff --git a/internal/application/service/session.go b/internal/application/service/session.go index d27af700..c6386f92 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -87,8 +87,7 @@ func (s *sessionService) CreateSession(ctx context.Context, session *types.Sessi return nil, errors.New("tenant ID is required") } - logger.Infof(ctx, "Creating session, tenant ID: %d, model ID: %s, knowledge base ID: %s", - session.TenantID, session.SummaryModelID, session.KnowledgeBaseID) + logger.Infof(ctx, "Creating session, tenant ID: %d", session.TenantID) // Create session in repository createdSession, err := s.sessionRepo.Create(ctx, session) @@ -259,31 +258,29 @@ func (s *sessionService) GenerateTitle(ctx context.Context, return "", errors.New("no user message found") } - // Get chat model, use default if SummaryModelID is empty - modelID := session.SummaryModelID - if modelID == "" { - // Try to get an available KnowledgeQA model - models, err := s.modelService.ListModels(ctx) - if err != nil { - logger.ErrorWithFields(ctx, err, nil) - return "", fmt.Errorf("failed to list models: %w", err) + // Get chat model, find an available model + modelID := "" + // Try to get an available KnowledgeQA model + models, err := s.modelService.ListModels(ctx) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + return "", fmt.Errorf("failed to list models: %w", err) + } + // Find first available KnowledgeQA model + for _, model := range models { + if model == nil { + continue } - // Find first available KnowledgeQA model - for _, model := range models { - if model == nil { - continue - } if model.Type == types.ModelTypeKnowledgeQA { - modelID = model.ID - logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID) - break - } - } - if modelID == "" { - logger.Error(ctx, "No KnowledgeQA model found") - return "", errors.New("no KnowledgeQA model available for title generation") + modelID = model.ID + logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID) + break } } + if modelID == "" { + logger.Error(ctx, "No KnowledgeQA model found") + return "", errors.New("no KnowledgeQA model available for title generation") + } chatModel, err := s.modelService.GetChatModel(ctx, modelID) if err != nil { @@ -413,16 +410,6 @@ func (s *sessionService) KnowledgeQA( webSearchEnabled, ) - // If no knowledge base IDs provided, fall back to session's default - if len(knowledgeBaseIDs) == 0 { - if session.KnowledgeBaseID != "" { - knowledgeBaseIDs = []string{session.KnowledgeBaseID} - logger.Infof(ctx, "No knowledge base IDs provided, using session default: %s", session.KnowledgeBaseID) - } else { - logger.Warnf(ctx, "Session has no associated knowledge base, session ID: %s", session.ID) - } - } - // Merge custom agent's configured knowledge bases if customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 { // Create a set of existing knowledge base IDs to avoid duplicates @@ -447,83 +434,28 @@ func (s *sessionService) KnowledgeQA( return err } + // Initialize default values from config.yaml rewritePromptSystem := s.cfg.Conversation.RewritePromptSystem rewritePromptUser := s.cfg.Conversation.RewritePromptUser - var tenantConv *types.ConversationConfig - if tc, err := getTenantConversationConfig(ctx); err == nil { - tenantConv = tc - } else { - logger.Warnf(ctx, "Failed to load tenant conversation config, tenant ID: %d, error: %v", session.TenantID, err) - } + vectorThreshold := s.cfg.Conversation.VectorThreshold + keywordThreshold := s.cfg.Conversation.KeywordThreshold + embeddingTopK := s.cfg.Conversation.EmbeddingTopK + rerankTopK := s.cfg.Conversation.RerankTopK + rerankThreshold := s.cfg.Conversation.RerankThreshold + maxRounds := s.cfg.Conversation.MaxRounds + fallbackStrategy := types.FallbackStrategy(s.cfg.Conversation.FallbackStrategy) + fallbackResponse := s.cfg.Conversation.FallbackResponse + fallbackPrompt := s.cfg.Conversation.FallbackPrompt + enableRewrite := s.cfg.Conversation.EnableRewrite + enableQueryExpansion := s.cfg.Conversation.EnableQueryExpansion + rerankModelID := "" - vectorThreshold := session.VectorThreshold - keywordThreshold := session.KeywordThreshold - embeddingTopK := session.EmbeddingTopK - rerankModelID := session.RerankModelID - rerankTopK := session.RerankTopK - rerankThreshold := session.RerankThreshold - maxRounds := session.MaxRounds - fallbackStrategy := session.FallbackStrategy - fallbackResponse := session.FallbackResponse - fallbackPrompt := "" - enableRewrite := session.EnableRewrite - enableQueryExpansion := true - - summaryParams := session.SummaryParameters - if summaryParams == nil { - summaryParams = &types.SummaryConfig{} - } summaryConfig := types.SummaryConfig{ - MaxTokens: summaryParams.MaxTokens, - RepeatPenalty: summaryParams.RepeatPenalty, - TopK: summaryParams.TopK, - TopP: summaryParams.TopP, - FrequencyPenalty: summaryParams.FrequencyPenalty, - PresencePenalty: summaryParams.PresencePenalty, - Prompt: summaryParams.Prompt, - ContextTemplate: summaryParams.ContextTemplate, - Temperature: summaryParams.Temperature, - Seed: summaryParams.Seed, - NoMatchPrefix: summaryParams.NoMatchPrefix, - MaxCompletionTokens: summaryParams.MaxCompletionTokens, - } - - if tenantConv != nil { - vectorThreshold = tenantConv.VectorThreshold - keywordThreshold = tenantConv.KeywordThreshold - embeddingTopK = tenantConv.EmbeddingTopK - rerankModelID = tenantConv.RerankModelID - rerankTopK = tenantConv.RerankTopK - rerankThreshold = tenantConv.RerankThreshold - maxRounds = tenantConv.MaxRounds - if tenantConv.FallbackStrategy != "" { - fallbackStrategy = types.FallbackStrategy(tenantConv.FallbackStrategy) - } - fallbackResponse = tenantConv.FallbackResponse - if tenantConv.FallbackPrompt != "" { - fallbackPrompt = tenantConv.FallbackPrompt - } - enableRewrite = tenantConv.EnableRewrite - enableQueryExpansion = tenantConv.EnableQueryExpansion - - if tenantConv.MaxCompletionTokens != 0 { - summaryConfig.MaxCompletionTokens = tenantConv.MaxCompletionTokens - } - if tenantConv.Prompt != "" { - summaryConfig.Prompt = tenantConv.Prompt - } - if tenantConv.ContextTemplate != "" { - summaryConfig.ContextTemplate = tenantConv.ContextTemplate - } - if tenantConv.Temperature != 0 { - summaryConfig.Temperature = tenantConv.Temperature - } - if tenantConv.RewritePromptSystem != "" { - rewritePromptSystem = tenantConv.RewritePromptSystem - } - if tenantConv.RewritePromptUser != "" { - rewritePromptUser = tenantConv.RewritePromptUser - } + Prompt: s.cfg.Conversation.Summary.Prompt, + ContextTemplate: s.cfg.Conversation.Summary.ContextTemplate, + Temperature: s.cfg.Conversation.Summary.Temperature, + NoMatchPrefix: s.cfg.Conversation.Summary.NoMatchPrefix, + MaxCompletionTokens: s.cfg.Conversation.Summary.MaxCompletionTokens, } // Set default fallback strategy if not set @@ -533,26 +465,75 @@ func (s *sessionService) KnowledgeQA( } // Apply custom agent configuration if provided - multiTurnEnabled := true // Default: enable multi-turn if customAgent != nil { - // Override system prompt with customAgent's SystemPrompt + // Ensure defaults are set + customAgent.EnsureDefaults() + + // Override system prompt if customAgent.Config.SystemPrompt != "" { summaryConfig.Prompt = customAgent.Config.SystemPrompt logger.Infof(ctx, "Using custom agent's system_prompt") } - // Override temperature with customAgent's Temperature + // Override context template + if customAgent.Config.ContextTemplate != "" { + summaryConfig.ContextTemplate = customAgent.Config.ContextTemplate + logger.Infof(ctx, "Using custom agent's context_template") + } + // Override temperature if customAgent.Config.Temperature > 0 { summaryConfig.Temperature = customAgent.Config.Temperature logger.Infof(ctx, "Using custom agent's temperature: %f", customAgent.Config.Temperature) } - // Override maxRounds with customAgent's HistoryTurns + // Override max completion tokens + if customAgent.Config.MaxCompletionTokens > 0 { + summaryConfig.MaxCompletionTokens = customAgent.Config.MaxCompletionTokens + logger.Infof(ctx, "Using custom agent's max_completion_tokens: %d", customAgent.Config.MaxCompletionTokens) + } + // Override retrieval strategy settings + if customAgent.Config.EmbeddingTopK > 0 { + embeddingTopK = customAgent.Config.EmbeddingTopK + } + if customAgent.Config.KeywordThreshold > 0 { + keywordThreshold = customAgent.Config.KeywordThreshold + } + if customAgent.Config.VectorThreshold > 0 { + vectorThreshold = customAgent.Config.VectorThreshold + } + if customAgent.Config.RerankTopK > 0 { + rerankTopK = customAgent.Config.RerankTopK + } + if customAgent.Config.RerankThreshold > 0 { + rerankThreshold = customAgent.Config.RerankThreshold + } + if customAgent.Config.RerankModelID != "" { + rerankModelID = customAgent.Config.RerankModelID + } + // Override rewrite settings + enableRewrite = customAgent.Config.EnableRewrite + enableQueryExpansion = customAgent.Config.EnableQueryExpansion + if customAgent.Config.RewritePromptSystem != "" { + rewritePromptSystem = customAgent.Config.RewritePromptSystem + } + if customAgent.Config.RewritePromptUser != "" { + rewritePromptUser = customAgent.Config.RewritePromptUser + } + // Override fallback settings + if customAgent.Config.FallbackStrategy != "" { + fallbackStrategy = types.FallbackStrategy(customAgent.Config.FallbackStrategy) + } + if customAgent.Config.FallbackResponse != "" { + fallbackResponse = customAgent.Config.FallbackResponse + } + if customAgent.Config.FallbackPrompt != "" { + fallbackPrompt = customAgent.Config.FallbackPrompt + } + // Override history turns if customAgent.Config.HistoryTurns > 0 { maxRounds = customAgent.Config.HistoryTurns logger.Infof(ctx, "Using custom agent's history_turns: %d", maxRounds) } // Check if multi-turn is disabled - multiTurnEnabled = customAgent.Config.MultiTurnEnabled - if !multiTurnEnabled { + if !customAgent.Config.MultiTurnEnabled { maxRounds = 0 // Disable history logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history") } @@ -625,8 +606,7 @@ func (s *sessionService) KnowledgeQA( err = s.KnowledgeQAByEvent(ctx, chatManage, pipeline) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ - "session_id": session.ID, - "knowledge_base_id": session.KnowledgeBaseID, + "session_id": session.ID, }) return err } @@ -703,10 +683,6 @@ func (s *sessionService) selectChatModelID( knowledgeIDs []string, ) (string, error) { - // First, check if session has a SummaryModelID and if it's a Remote model - if session.SummaryModelID != "" { - return session.SummaryModelID, nil - } // If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) > 0 { tenantID := ctx.Value(types.TenantIDContextKey).(uint64) @@ -728,7 +704,7 @@ func (s *sessionService) selectChatModelID( len(knowledgeBaseIDs), len(knowledgeIDs)) } } - // If no Remote model found from session, check knowledge bases for Remote models + // Check knowledge bases for models if len(knowledgeBaseIDs) > 0 { // Try to find a knowledge base with Remote model for _, kbID := range knowledgeBaseIDs { @@ -746,13 +722,7 @@ func (s *sessionService) selectChatModelID( } } - // If still no Remote model found, use session's SummaryModelID if available - if session.SummaryModelID != "" { - logger.Infof(ctx, "No Remote model found, using session's summary model: %s", session.SummaryModelID) - return session.SummaryModelID, nil - } - - // If still empty, use first knowledge base's model + // If no Remote model found, use first knowledge base's model kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, knowledgeBaseIDs[0]) if err != nil { logger.Errorf(ctx, "Failed to get knowledge base for model ID: %v", err) @@ -766,22 +736,24 @@ func (s *sessionService) selectChatModelID( kb.SummaryModelID, ) return kb.SummaryModelID, nil - } else { - logger.Errorf(ctx, "Knowledge base %s has no summary model ID", knowledgeBaseIDs[0]) - return "", fmt.Errorf("knowledge base %s has no summary model configured", knowledgeBaseIDs[0]) } } - // No knowledge bases - use session's SummaryModelID if available - if session.SummaryModelID != "" { - logger.Infof(ctx, "No knowledge bases, using session's summary model: %s", session.SummaryModelID) - return session.SummaryModelID, nil + // No knowledge bases - try to find any available chat model + models, err := s.modelService.ListModels(ctx) + if err != nil { + logger.Errorf(ctx, "Failed to list models: %v", err) + return "", fmt.Errorf("failed to list models: %w", err) + } + for _, model := range models { + if model != nil && model.Type == types.ModelTypeKnowledgeQA { + logger.Infof(ctx, "Using first available KnowledgeQA model: %s", model.ID) + return model.ID, nil + } } logger.Error(ctx, "No chat model ID available") - return "", errors.New( - "no chat model ID available: session has no SummaryModelID and no knowledge bases configured", - ) + return "", errors.New("no chat model ID available: no knowledge bases configured and no available models") } // buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs @@ -1049,18 +1021,20 @@ func (s *sessionService) AgentQA( sessionID, tenantID, query, string(sessionJSON)) // Build effective agent configuration by merging session and tenant configs - // Session-level config: Enabled, KnowledgeBases (stored in session.AgentConfig) - // Tenant-level config: MaxIterations, Temperature, Models, Tools, etc. (from tenant.AgentConfig) + // All config now comes from customAgent parameter tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - // Check if agent is enabled at session level - if session.AgentConfig == nil { - logger.Warnf(ctx, "Agent config not found for session: %s", sessionID) - return errors.New("agent config not found for session") + // customAgent is required for AgentQA + if customAgent == nil { + logger.Warnf(ctx, "Custom agent not provided for session: %s", sessionID) + return errors.New("custom agent configuration is required for agent QA") } - // Check if tenant has agent configuration + // Ensure defaults are set + customAgent.EnsureDefaults() + + // Check if tenant has agent configuration (for defaults) if tenantInfo.AgentConfig == nil { tenantInfo.AgentConfig = &types.AgentConfig{ MaxIterations: agent.DefaultAgentMaxIterations, @@ -1073,76 +1047,35 @@ func (s *sessionService) AgentQA( } } - // Create runtime AgentConfig - // Priority: CustomAgent config > Tenant config > Defaults - // Session config provides KnowledgeBases and KnowledgeIDs - var agentConfig *types.AgentConfig - - if customAgent != nil && customAgent.ID != types.BuiltinAgentNormalID && customAgent.ID != types.BuiltinAgentAgentID { - // Use custom agent configuration - logger.Infof(ctx, "Using custom agent configuration, agent ID: %s, name: %s", customAgent.ID, customAgent.Name) - customAgent.EnsureDefaults() - - agentConfig = &types.AgentConfig{ - MaxIterations: customAgent.Config.MaxIterations, - ReflectionEnabled: customAgent.Config.ReflectionEnabled, - Temperature: customAgent.Config.Temperature, - WebSearchEnabled: customAgent.Config.WebSearchEnabled, - WebSearchMaxResults: customAgent.Config.WebSearchMaxResults, - MultiTurnEnabled: customAgent.Config.MultiTurnEnabled, - HistoryTurns: customAgent.Config.HistoryTurns, - } - - // Use custom agent's allowed tools if specified, otherwise use defaults - if len(customAgent.Config.AllowedTools) > 0 { - agentConfig.AllowedTools = customAgent.Config.AllowedTools - } else { - agentConfig.AllowedTools = tools.DefaultAllowedTools() - } - - // Use custom agent's system prompt if specified - if customAgent.Config.SystemPrompt != "" { - agentConfig.UseCustomSystemPrompt = true - agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt - agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt - } - - // Use custom agent's knowledge bases if specified, otherwise use session's - if len(customAgent.Config.KnowledgeBases) > 0 { - agentConfig.KnowledgeBases = customAgent.Config.KnowledgeBases - } else { - agentConfig.KnowledgeBases = session.AgentConfig.KnowledgeBases - } - agentConfig.KnowledgeIDs = session.AgentConfig.KnowledgeIDs - - // Override summary model if custom agent specifies one - if customAgent.Config.ModelID != "" { - session.SummaryModelID = customAgent.Config.ModelID - } - - logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v", - agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled) - } else { - // Use tenant configuration (default behavior) - agentConfig = &types.AgentConfig{ - MaxIterations: tenantInfo.AgentConfig.MaxIterations, - ReflectionEnabled: tenantInfo.AgentConfig.ReflectionEnabled, - AllowedTools: tools.DefaultAllowedTools(), - Temperature: tenantInfo.AgentConfig.Temperature, - KnowledgeBases: session.AgentConfig.KnowledgeBases, // Use session's knowledge bases - KnowledgeIDs: session.AgentConfig.KnowledgeIDs, // Use session's knowledge IDs (individual documents) - WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config - MultiTurnEnabled: true, // Default: enable multi-turn - HistoryTurns: 5, // Default: keep 5 turns - } - - agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt - if agentConfig.UseCustomSystemPrompt { - agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true) - agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false) - } + // Create runtime AgentConfig from customAgent + agentConfig := &types.AgentConfig{ + MaxIterations: customAgent.Config.MaxIterations, + ReflectionEnabled: customAgent.Config.ReflectionEnabled, + Temperature: customAgent.Config.Temperature, + WebSearchEnabled: customAgent.Config.WebSearchEnabled, + WebSearchMaxResults: customAgent.Config.WebSearchMaxResults, + MultiTurnEnabled: customAgent.Config.MultiTurnEnabled, + HistoryTurns: customAgent.Config.HistoryTurns, + KnowledgeBases: customAgent.Config.KnowledgeBases, } + // Use custom agent's allowed tools if specified, otherwise use defaults + if len(customAgent.Config.AllowedTools) > 0 { + agentConfig.AllowedTools = customAgent.Config.AllowedTools + } else { + agentConfig.AllowedTools = tools.DefaultAllowedTools() + } + + // Use custom agent's system prompt if specified + if customAgent.Config.SystemPrompt != "" { + agentConfig.UseCustomSystemPrompt = true + agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt + agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt + } + + logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v", + agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled) + // Set web search max results from tenant config if not set (default: 5) if agentConfig.WebSearchMaxResults == 0 { agentConfig.WebSearchMaxResults = 5 @@ -1153,31 +1086,13 @@ func (s *sessionService) AgentQA( logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, sessionID) - // Log knowledge IDs if present - if len(agentConfig.KnowledgeIDs) > 0 { - logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s): %v", - len(agentConfig.KnowledgeIDs), agentConfig.KnowledgeIDs) - } - - // Determine knowledge bases for agent - // Priority: Session.AgentConfig.KnowledgeBases > Session.KnowledgeBaseID > All tenant knowledge bases - // Exception: If KnowledgeIDs are specified, don't auto-add all KBs (let buildSearchTargets handle it) - if len(agentConfig.KnowledgeBases) == 0 && len(agentConfig.KnowledgeIDs) == 0 { - if session.KnowledgeBaseID != "" { - // Use session's knowledge base as fallback - agentConfig.KnowledgeBases = []string{session.KnowledgeBaseID} - logger.Infof(ctx, "Using session's knowledge base for agent: %s", session.KnowledgeBaseID) - } else { - // Allow running without knowledge bases (Pure Agent mode) - logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode") - } - } else if len(agentConfig.KnowledgeIDs) > 0 && len(agentConfig.KnowledgeBases) == 0 { - // User specified individual files but no KBs - don't auto-add all KBs - logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s), no KB auto-expansion", - len(agentConfig.KnowledgeIDs)) - } else { + // Log knowledge bases if present + if len(agentConfig.KnowledgeBases) > 0 { logger.Infof(ctx, "Agent configured with %d knowledge base(s): %v", len(agentConfig.KnowledgeBases), agentConfig.KnowledgeBases) + } else { + // Allow running without knowledge bases (Pure Agent mode) + logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode") } // Build search targets for agent (pre-compute once to avoid repeated queries) @@ -1189,7 +1104,8 @@ func (s *sessionService) AgentQA( agentConfig.SearchTargets = searchTargets logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets)) - summaryModelID := session.SummaryModelID + // Get summary model from custom agent config or tenant config + summaryModelID := customAgent.Config.ModelID if summaryModelID == "" && tenantInfo.ConversationConfig != nil { summaryModelID = tenantInfo.ConversationConfig.SummaryModelID } @@ -1204,7 +1120,8 @@ func (s *sessionService) AgentQA( return fmt.Errorf("failed to get chat model: %w", err) } - rerankModelID := session.RerankModelID + // Get rerank model from custom agent config or tenant config + rerankModelID := customAgent.Config.RerankModelID if rerankModelID == "" && tenantInfo.ConversationConfig != nil { rerankModelID = tenantInfo.ConversationConfig.RerankModelID } @@ -1296,13 +1213,9 @@ func (s *sessionService) getContextManagerForSession( ) interfaces.ContextManager { // Get tenant to access global context configuration tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - // Determine which context config to use: session-specific or tenant-level + // Determine which context config to use: tenant-level or default var contextConfig *types.ContextConfig - if session.ContextConfig != nil { - // Use session-specific configuration - contextConfig = session.ContextConfig - logger.Infof(ctx, "Using session-specific context config for session %s", session.ID) - } else if tenant.ContextConfig != nil { + if tenant != nil && tenant.ContextConfig != nil { // Use tenant-level configuration contextConfig = tenant.ContextConfig logger.Infof(ctx, "Using tenant-level context config for session %s", session.ID) diff --git a/internal/config/config.go b/internal/config/config.go index f70fe9e1..9a137a3b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( "fmt" "os" + "path/filepath" "regexp" "strings" "time" @@ -10,20 +11,22 @@ import ( "github.com/Tencent/WeKnora/internal/types" "github.com/go-viper/mapstructure/v2" "github.com/spf13/viper" + "gopkg.in/yaml.v3" ) // Config 应用程序总配置 type Config struct { - Conversation *ConversationConfig `yaml:"conversation" json:"conversation"` - Server *ServerConfig `yaml:"server" json:"server"` - KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"` - Tenant *TenantConfig `yaml:"tenant" json:"tenant"` - Models []ModelConfig `yaml:"models" json:"models"` - VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"` - DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"` - StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"` - ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"` - WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"` + Conversation *ConversationConfig `yaml:"conversation" json:"conversation"` + Server *ServerConfig `yaml:"server" json:"server"` + KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"` + Tenant *TenantConfig `yaml:"tenant" json:"tenant"` + Models []ModelConfig `yaml:"models" json:"models"` + VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"` + DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"` + StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"` + ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"` + WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"` + PromptTemplates *PromptTemplatesConfig `yaml:"prompt_templates" json:"prompt_templates"` } type DocReaderConfig struct { @@ -108,6 +111,25 @@ type TenantConfig struct { EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"` } +// PromptTemplate 提示词模板 +type PromptTemplate struct { + ID string `yaml:"id" json:"id"` + Name string `yaml:"name" json:"name"` + Description string `yaml:"description" json:"description"` + Content string `yaml:"content" json:"content"` + HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"` + HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"` +} + +// PromptTemplatesConfig 提示词模板配置 +type PromptTemplatesConfig struct { + SystemPrompt []PromptTemplate `yaml:"system_prompt" json:"system_prompt"` + ContextTemplate []PromptTemplate `yaml:"context_template" json:"context_template"` + RewriteSystem []PromptTemplate `yaml:"rewrite_system" json:"rewrite_system"` + RewriteUser []PromptTemplate `yaml:"rewrite_user" json:"rewrite_user"` + Fallback []PromptTemplate `yaml:"fallback" json:"fallback"` +} + // ModelConfig 模型配置 type ModelConfig struct { Type string `yaml:"type" json:"type"` @@ -192,9 +214,68 @@ func LoadConfig() (*Config, error) { return nil, fmt.Errorf("unable to decode config into struct: %w", err) } fmt.Printf("Using configuration file: %s\n", viper.ConfigFileUsed()) + + // 加载提示词模板(从目录或配置文件) + configDir := filepath.Dir(viper.ConfigFileUsed()) + promptTemplates, err := loadPromptTemplates(configDir) + if err != nil { + fmt.Printf("Warning: failed to load prompt templates from directory: %v\n", err) + // 如果目录加载失败,使用配置文件中的模板(如果有) + } else if promptTemplates != nil { + cfg.PromptTemplates = promptTemplates + } + return &cfg, nil } +// promptTemplateFile 用于解析模板文件 +type promptTemplateFile struct { + Templates []PromptTemplate `yaml:"templates"` +} + +// loadPromptTemplates 从目录加载提示词模板 +func loadPromptTemplates(configDir string) (*PromptTemplatesConfig, error) { + templatesDir := filepath.Join(configDir, "prompt_templates") + + // 检查目录是否存在 + if _, err := os.Stat(templatesDir); os.IsNotExist(err) { + return nil, nil // 目录不存在,返回nil让调用者使用配置文件中的模板 + } + + config := &PromptTemplatesConfig{} + + // 定义模板文件映射 + templateFiles := map[string]*[]PromptTemplate{ + "system_prompt.yaml": &config.SystemPrompt, + "context_template.yaml": &config.ContextTemplate, + "rewrite_system.yaml": &config.RewriteSystem, + "rewrite_user.yaml": &config.RewriteUser, + "fallback.yaml": &config.Fallback, + } + + // 加载每个模板文件 + for filename, target := range templateFiles { + filePath := filepath.Join(templatesDir, filename) + if _, err := os.Stat(filePath); os.IsNotExist(err) { + continue // 文件不存在,跳过 + } + + data, err := os.ReadFile(filePath) + if err != nil { + return nil, fmt.Errorf("failed to read %s: %w", filename, err) + } + + var file promptTemplateFile + if err := yaml.Unmarshal(data, &file); err != nil { + return nil, fmt.Errorf("failed to parse %s: %w", filename, err) + } + + *target = file.Templates + } + + return config, nil +} + // WebSearchConfig represents the web search configuration type WebSearchConfig struct { Providers []WebSearchProviderConfig `yaml:"providers" json:"providers"` diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go index b147fcb8..1eb2f39d 100644 --- a/internal/handler/custom_agent.go +++ b/internal/handler/custom_agent.go @@ -35,7 +35,7 @@ type CreateAgentRequest struct { // UpdateAgentRequest defines the request body for updating an agent type UpdateAgentRequest struct { - Name string `json:"name" binding:"required"` + Name string `json:"name"` Description string `json:"description"` Avatar string `json:"avatar"` Type types.CustomAgentType `json:"type"` diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index ee3e0cb7..39ba42e9 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -1,7 +1,6 @@ package session import ( - "context" "net/http" "github.com/Tencent/WeKnora/internal/config" @@ -74,75 +73,17 @@ func (h *Handler) CreateSession(c *gin.Context) { // Validate session creation request // Sessions are now knowledge-base-independent: - // - KnowledgeBaseID is optional during session creation - // - Knowledge base can be specified in each query request (AgentQA/KnowledgeQA) - // - Agent mode can access multiple knowledge bases via AgentConfig.KnowledgeBases - // - Knowledge base can be switched during conversation - isAgentMode := request.AgentConfig != nil && request.AgentConfig.AgentModeEnabled - hasAgentKnowledgeBases := request.AgentConfig != nil && len(request.AgentConfig.KnowledgeBases) > 0 - + // - All configuration comes from custom agent at query time + // - Session only stores basic info (tenant ID, title, etc.) logger.Infof( ctx, - "Processing session creation request, tenant ID: %d, knowledge base ID: %s, agent mode: %v, agent KBs: %v", + "Processing session creation request, tenant ID: %d", tenantID, - request.KnowledgeBaseID, - isAgentMode, - hasAgentKnowledgeBases, ) // Create session object with base properties createdSession := &types.Session{ - TenantID: tenantID.(uint64), - KnowledgeBaseID: request.KnowledgeBaseID, - AgentConfig: request.AgentConfig, // Set agent config if provided - } - - // If summary model parameters are empty, set defaults - if request.SessionStrategy != nil { - createdSession.RerankModelID = request.SessionStrategy.RerankModelID - createdSession.SummaryModelID = request.SessionStrategy.SummaryModelID - createdSession.MaxRounds = request.SessionStrategy.MaxRounds - createdSession.EnableRewrite = request.SessionStrategy.EnableRewrite - createdSession.FallbackStrategy = request.SessionStrategy.FallbackStrategy - createdSession.FallbackResponse = request.SessionStrategy.FallbackResponse - createdSession.EmbeddingTopK = request.SessionStrategy.EmbeddingTopK - createdSession.KeywordThreshold = request.SessionStrategy.KeywordThreshold - createdSession.VectorThreshold = request.SessionStrategy.VectorThreshold - createdSession.RerankTopK = request.SessionStrategy.RerankTopK - createdSession.RerankThreshold = request.SessionStrategy.RerankThreshold - if request.SessionStrategy.SummaryParameters != nil { - createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters - } else { - createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx) - } - h.fillSummaryConfigDefaults(ctx, createdSession.SummaryParameters) - - logger.Debug(ctx, "Custom session strategy set") - } else { - tenantInfo, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - h.applyConversationDefaults(ctx, createdSession, tenantInfo) - logger.Debug(ctx, "Using default session strategy") - } - - // Fetch knowledge base if KnowledgeBaseID is provided to inherit its model configurations - // If no KB is provided, models will be determined at query time or use tenant/system defaults - if request.KnowledgeBaseID != "" { - kb, err := h.knowledgebaseService.GetKnowledgeBaseByID(ctx, request.KnowledgeBaseID) - if err != nil { - logger.Error(ctx, "Failed to get knowledge base", err) - c.Error(errors.NewInternalServerError(err.Error())) - return - } - - // Use knowledge base's summary model if session doesn't specify it - if createdSession.SummaryModelID == "" { - createdSession.SummaryModelID = kb.SummaryModelID - } - - logger.Debugf(ctx, "Knowledge base fetched: %s, summary model: %s", - kb.ID, kb.SummaryModelID) - } else { - logger.Debug(ctx, "No knowledge base ID provided, models will use session strategy or be determined at query time") + TenantID: tenantID.(uint64), } // Call service to create session @@ -162,45 +103,6 @@ func (h *Handler) CreateSession(c *gin.Context) { }) } -func (h *Handler) applyConversationDefaults(ctx context.Context, session *types.Session, tenant *types.Tenant) { - session.MaxRounds = h.config.Conversation.MaxRounds - session.EnableRewrite = h.config.Conversation.EnableRewrite - session.FallbackStrategy = types.FallbackStrategy(h.config.Conversation.FallbackStrategy) - session.FallbackResponse = h.config.Conversation.FallbackResponse - session.EmbeddingTopK = h.config.Conversation.EmbeddingTopK - session.KeywordThreshold = h.config.Conversation.KeywordThreshold - session.VectorThreshold = h.config.Conversation.VectorThreshold - session.RerankThreshold = h.config.Conversation.RerankThreshold - session.RerankTopK = h.config.Conversation.RerankTopK - session.RerankModelID = "" - session.SummaryModelID = "" - - if tenant != nil && tenant.ConversationConfig != nil { - tc := tenant.ConversationConfig - session.MaxRounds = tc.MaxRounds - session.EnableRewrite = tc.EnableRewrite - if tc.FallbackStrategy != "" { - session.FallbackStrategy = types.FallbackStrategy(tc.FallbackStrategy) - } - if tc.FallbackResponse != "" { - session.FallbackResponse = tc.FallbackResponse - } - session.EmbeddingTopK = tc.EmbeddingTopK - session.KeywordThreshold = tc.KeywordThreshold - session.VectorThreshold = tc.VectorThreshold - session.RerankThreshold = tc.RerankThreshold - session.RerankTopK = tc.RerankTopK - if tc.RerankModelID != "" { - session.RerankModelID = tc.RerankModelID - } - if tc.SummaryModelID != "" { - session.SummaryModelID = tc.SummaryModelID - } - } - - session.SummaryParameters = h.createDefaultSummaryConfig(ctx) -} - // GetSession godoc // @Summary 获取会话详情 // @Description 根据ID获取会话详情 diff --git a/internal/handler/session/helpers.go b/internal/handler/session/helpers.go index f14ebc77..b1e76d77 100644 --- a/internal/handler/session/helpers.go +++ b/internal/handler/session/helpers.go @@ -203,20 +203,13 @@ func (h *Handler) createDefaultSummaryConfig(ctx context.Context) *types.Summary // Override with tenant-level conversation config if available if tenant != nil && tenant.ConversationConfig != nil { - useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt - if !useSystemPrompt && tenant.ConversationConfig.Prompt != "" { - // Backward compatibility: treat legacy configs without flag as custom - useSystemPrompt = true - } - if useSystemPrompt && tenant.ConversationConfig.Prompt != "" { + // Use custom prompt if provided + if tenant.ConversationConfig.Prompt != "" { cfg.Prompt = tenant.ConversationConfig.Prompt } - useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate - if !useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" { - useContextTemplate = true - } - if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" { + // Use custom context template if provided + if tenant.ConversationConfig.ContextTemplate != "" { cfg.ContextTemplate = tenant.ConversationConfig.ContextTemplate } if tenant.ConversationConfig.Temperature > 0 { @@ -242,13 +235,13 @@ func (h *Handler) fillSummaryConfigDefaults(ctx context.Context, config *types.S var defaultMaxCompletionTokens int if tenant != nil && tenant.ConversationConfig != nil { - useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt - if useSystemPrompt && tenant.ConversationConfig.Prompt != "" { + // Use custom prompt if provided + if tenant.ConversationConfig.Prompt != "" { defaultPrompt = tenant.ConversationConfig.Prompt } - useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate - if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" { + // Use custom context template if provided + if tenant.ConversationConfig.ContextTemplate != "" { defaultContextTemplate = tenant.ConversationConfig.ContextTemplate } defaultTemperature = tenant.ConversationConfig.Temperature diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 4a4ae8c0..d5254c54 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -111,118 +111,6 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo return reqCtx, &request, nil } -// detectAndApplyConfigChanges detects configuration changes and updates session if needed -// Returns true if any configuration changed -func (h *Handler) detectAndApplyConfigChanges( - reqCtx *qaRequestContext, - request *CreateKnowledgeQARequest, -) (bool, error) { - ctx := reqCtx.ctx - session := reqCtx.session - sessionID := reqCtx.sessionID - - // Initialize AgentConfig if it doesn't exist - if session.AgentConfig == nil { - session.AgentConfig = &types.SessionAgentConfig{} - } - - configChanged := false - - // Check knowledge bases change - if hasArrayChanged(session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs) { - logger.Infof(ctx, "Knowledge bases changed from %v to %v", - session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs) - configChanged = true - } - - // Check knowledge IDs change - if hasArrayChanged(session.AgentConfig.KnowledgeIDs, request.KnowledgeIds) { - logger.Infof(ctx, "Knowledge IDs changed from %v to %v", - session.AgentConfig.KnowledgeIDs, request.KnowledgeIds) - configChanged = true - } - - // Check agent mode change - if request.AgentEnabled != session.AgentConfig.AgentModeEnabled { - logger.Infof(ctx, "Agent mode changed from %v to %v", - session.AgentConfig.AgentModeEnabled, request.AgentEnabled) - configChanged = true - } - - // Check web search change - if request.WebSearchEnabled != session.AgentConfig.WebSearchEnabled { - logger.Infof(ctx, "Web search mode changed from %v to %v", - session.AgentConfig.WebSearchEnabled, request.WebSearchEnabled) - configChanged = true - } - - // Resolve summary model ID - summaryModelID := reqCtx.summaryModelID - if summaryModelID == "" { - summaryModelID = session.SummaryModelID - } - if summaryModelID == "" { - if tenantInfo, ok := ctx.Value(types.TenantInfoContextKey).(*types.Tenant); ok && tenantInfo.ConversationConfig != nil { - summaryModelID = tenantInfo.ConversationConfig.SummaryModelID - } - } - if summaryModelID != session.SummaryModelID { - configChanged = true - } - - // Apply changes if any - if configChanged { - logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID) - - // Clear LLM context - if err := h.sessionService.ClearContext(ctx, sessionID); err != nil { - logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err) - } - - // Delete temp KB state - if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil { - logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err) - } - - // Update session config - session.AgentConfig.KnowledgeBases = secutils.SanitizeForLogArray(request.KnowledgeBaseIDs) - session.AgentConfig.KnowledgeIDs = secutils.SanitizeForLogArray(request.KnowledgeIds) - session.AgentConfig.AgentModeEnabled = request.AgentEnabled - session.AgentConfig.WebSearchEnabled = request.WebSearchEnabled - session.SummaryModelID = summaryModelID - - // Persist changes - if err := h.sessionService.UpdateSession(ctx, session); err != nil { - logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err) - return false, errors.NewInternalServerError("Failed to update session configuration") - } - logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID) - } - - return configChanged, nil -} - -// hasArrayChanged checks if two string arrays are different -func hasArrayChanged(current, new []string) bool { - if len(current) != len(new) { - return true - } - if len(current) == 0 && len(new) == 0 { - return false - } - - currentMap := make(map[string]bool) - for _, v := range current { - currentMap[v] = true - } - for _, v := range new { - if !currentMap[v] { - return true - } - } - return false -} - // sseStreamContext holds the context for SSE streaming type sseStreamContext struct { eventBus *event.EventBus @@ -388,12 +276,6 @@ func (h *Handler) AgentQA(c *gin.Context) { return } - // Detect and apply configuration changes - if _, err := h.detectAndApplyConfigChanges(reqCtx, request); err != nil { - c.Error(err) - return - } - // Determine if agent mode should be enabled // Priority: customAgent.IsAgentMode() > request.AgentEnabled agentModeEnabled := request.AgentEnabled @@ -408,13 +290,7 @@ func (h *Handler) AgentQA(c *gin.Context) { h.executeAgentModeQA(reqCtx) } else { logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID) - // Fallback to session's knowledge bases if not specified in request - if len(reqCtx.knowledgeBaseIDs) == 0 { - reqCtx.knowledgeBaseIDs = reqCtx.session.AgentConfig.KnowledgeBases - } - if len(reqCtx.knowledgeBaseIDs) == 0 && reqCtx.session.KnowledgeBaseID != "" { - reqCtx.knowledgeBaseIDs = []string{reqCtx.session.KnowledgeBaseID} - } + // Knowledge bases should be specified in request or from custom agent h.executeNormalModeQA(reqCtx, false) } } diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go index eac5b405..b9bcd734 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -425,7 +425,6 @@ type AgentConfigRequest struct { Temperature float64 `json:"temperature"` SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` - UseCustomPrompt *bool `json:"use_custom_system_prompt"` } // GetTenantAgentConfig godoc @@ -497,8 +496,6 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) { systemPromptWithoutWeb = agent.ProgressiveRAGSystemPromptWithoutWeb } - useCustomPrompt := tenant.AgentConfig.UseCustomSystemPrompt - logger.Infof(ctx, "Retrieved tenant agent config successfully, Tenant ID: %d", tenant.ID) c.JSON(http.StatusOK, gin.H{ "success": true, @@ -509,7 +506,6 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) { "temperature": tenant.AgentConfig.Temperature, "system_prompt_web_enabled": systemPromptWithWeb, "system_prompt_web_disabled": systemPromptWithoutWeb, - "use_custom_system_prompt": useCustomPrompt, "available_tools": availableTools, "available_placeholders": availablePlaceholders, }, @@ -546,13 +542,8 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) { return } // Update agent configuration - useCustomPrompt := false - if tenant.AgentConfig != nil { - useCustomPrompt = tenant.AgentConfig.UseCustomSystemPrompt - } - if req.UseCustomPrompt != nil { - useCustomPrompt = *req.UseCustomPrompt - } + // Determine if using custom prompt based on whether custom prompts are set + useCustomPrompt := req.SystemPromptWebEnabled != "" || req.SystemPromptWebDisabled != "" tenant.AgentConfig = &types.AgentConfig{ MaxIterations: req.MaxIterations, @@ -610,6 +601,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) { case "conversation-config": h.GetTenantConversationConfig(c) return + case "prompt-templates": + h.GetPromptTemplates(c) + return default: logger.Info(ctx, "KV key not supported", "key", key) c.Error(errors.NewBadRequestError("unsupported key")) @@ -726,25 +720,23 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) { func (h *TenantHandler) buildDefaultConversationConfig() *types.ConversationConfig { return &types.ConversationConfig{ - Prompt: h.config.Conversation.Summary.Prompt, - ContextTemplate: h.config.Conversation.Summary.ContextTemplate, - UseCustomContextTemplate: true, - UseCustomSystemPrompt: true, - Temperature: h.config.Conversation.Summary.Temperature, - MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens, - MaxRounds: h.config.Conversation.MaxRounds, - EmbeddingTopK: h.config.Conversation.EmbeddingTopK, - KeywordThreshold: h.config.Conversation.KeywordThreshold, - VectorThreshold: h.config.Conversation.VectorThreshold, - RerankTopK: h.config.Conversation.RerankTopK, - RerankThreshold: h.config.Conversation.RerankThreshold, - EnableRewrite: h.config.Conversation.EnableRewrite, - EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion, - FallbackStrategy: h.config.Conversation.FallbackStrategy, - FallbackResponse: h.config.Conversation.FallbackResponse, - FallbackPrompt: h.config.Conversation.FallbackPrompt, - RewritePromptUser: h.config.Conversation.RewritePromptUser, - RewritePromptSystem: h.config.Conversation.RewritePromptSystem, + Prompt: h.config.Conversation.Summary.Prompt, + ContextTemplate: h.config.Conversation.Summary.ContextTemplate, + Temperature: h.config.Conversation.Summary.Temperature, + MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens, + MaxRounds: h.config.Conversation.MaxRounds, + EmbeddingTopK: h.config.Conversation.EmbeddingTopK, + KeywordThreshold: h.config.Conversation.KeywordThreshold, + VectorThreshold: h.config.Conversation.VectorThreshold, + RerankTopK: h.config.Conversation.RerankTopK, + RerankThreshold: h.config.Conversation.RerankThreshold, + EnableRewrite: h.config.Conversation.EnableRewrite, + EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion, + FallbackStrategy: h.config.Conversation.FallbackStrategy, + FallbackResponse: h.config.Conversation.FallbackResponse, + FallbackPrompt: h.config.Conversation.FallbackPrompt, + RewritePromptUser: h.config.Conversation.RewritePromptUser, + RewritePromptSystem: h.config.Conversation.RewritePromptSystem, } } @@ -803,91 +795,8 @@ func (h *TenantHandler) GetTenantConversationConfig(c *gin.Context) { // If tenant has no conversation config, return defaults from config.yaml var response *types.ConversationConfig - if tc := tenant.ConversationConfig; tc == nil { - logger.Info(ctx, "Tenant has no conversation config, returning defaults") - response = h.buildDefaultConversationConfig() - } else { - logger.Infof(ctx, "Tenant has conversation config, merging with defaults, Tenant ID: %d", tenant.ID) - // Merge tenant config with defaults, so that newly added fields always have valid values - defaultCfg := h.buildDefaultConversationConfig() - // Prompt related - defaultCfg.UseCustomSystemPrompt = tc.UseCustomSystemPrompt - if !defaultCfg.UseCustomSystemPrompt && tc.Prompt != "" { - // Legacy configs without explicit flag - defaultCfg.UseCustomSystemPrompt = true - } - defaultCfg.UseCustomContextTemplate = tc.UseCustomContextTemplate - if !defaultCfg.UseCustomContextTemplate && tc.ContextTemplate != "" { - defaultCfg.UseCustomContextTemplate = true - } - if tc.Prompt != "" { - defaultCfg.Prompt = tc.Prompt - } - if tc.ContextTemplate != "" { - defaultCfg.ContextTemplate = tc.ContextTemplate - } - if tc.Temperature > 0 { - defaultCfg.Temperature = tc.Temperature - } - if tc.MaxCompletionTokens > 0 { - defaultCfg.MaxCompletionTokens = tc.MaxCompletionTokens - } - - // Retrieval parameters - if tc.MaxRounds > 0 { - defaultCfg.MaxRounds = tc.MaxRounds - } - if tc.EmbeddingTopK > 0 { - defaultCfg.EmbeddingTopK = tc.EmbeddingTopK - } - if tc.KeywordThreshold > 0 { - defaultCfg.KeywordThreshold = tc.KeywordThreshold - } - if tc.VectorThreshold > 0 { - defaultCfg.VectorThreshold = tc.VectorThreshold - } - if tc.RerankTopK > 0 { - defaultCfg.RerankTopK = tc.RerankTopK - } - if tc.RerankThreshold > 0 { - defaultCfg.RerankThreshold = tc.RerankThreshold - } - // EnableRewrite 需要允许显式关闭,因此直接覆盖 - defaultCfg.EnableRewrite = tc.EnableRewrite - - // Query expansion toggle - defaultCfg.EnableQueryExpansion = tc.EnableQueryExpansion - - // Model IDs - if tc.SummaryModelID != "" { - defaultCfg.SummaryModelID = tc.SummaryModelID - } - if tc.RerankModelID != "" { - defaultCfg.RerankModelID = tc.RerankModelID - } - - // Fallback settings - if tc.FallbackStrategy != "" { - defaultCfg.FallbackStrategy = tc.FallbackStrategy - } - if tc.FallbackResponse != "" { - defaultCfg.FallbackResponse = tc.FallbackResponse - } - if tc.FallbackPrompt != "" { - defaultCfg.FallbackPrompt = tc.FallbackPrompt - } - - // Rewrite prompts - if tc.RewritePromptSystem != "" { - defaultCfg.RewritePromptSystem = tc.RewritePromptSystem - } - if tc.RewritePromptUser != "" { - defaultCfg.RewritePromptUser = tc.RewritePromptUser - } - - response = defaultCfg - } - + logger.Info(ctx, "Tenant has no conversation config, returning defaults") + response = h.buildDefaultConversationConfig() c.JSON(http.StatusOK, gin.H{ "success": true, "data": response, @@ -943,3 +852,27 @@ func (h *TenantHandler) updateTenantConversationInternal(c *gin.Context) { "message": "Conversation configuration updated successfully", }) } + +// GetPromptTemplates godoc +// @Summary 获取提示词模板 +// @Description 获取系统配置的提示词模板列表 +// @Tags 租户管理 +// @Accept json +// @Produce json +// @Success 200 {object} map[string]interface{} "提示词模板配置" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /tenants/kv/prompt-templates [get] +func (h *TenantHandler) GetPromptTemplates(c *gin.Context) { + // Return prompt templates from config.yaml + templates := h.config.PromptTemplates + if templates == nil { + templates = &config.PromptTemplatesConfig{} + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": templates, + }) +} diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go index 4f00e8d3..b3d0b446 100644 --- a/internal/types/custom_agent.go +++ b/internal/types/custom_agent.go @@ -56,34 +56,83 @@ type CustomAgent struct { // CustomAgentConfig represents the configuration of a custom agent type CustomAgentConfig struct { + // ===== Basic Settings ===== // Agent mode: "normal" for RAG mode, "agent" for ReAct agent mode AgentMode string `yaml:"agent_mode" json:"agent_mode"` - // System prompt for the agent + // System prompt for the agent (for normal mode, or agent mode when web search is disabled) SystemPrompt string `yaml:"system_prompt" json:"system_prompt"` + // System prompt for agent mode when web search is enabled + SystemPromptWebEnabled string `yaml:"system_prompt_web_enabled" json:"system_prompt_web_enabled"` + // Context template for normal mode (how to format retrieved chunks) + ContextTemplate string `yaml:"context_template" json:"context_template"` + + // ===== Model Settings ===== // Model ID to use for conversations ModelID string `yaml:"model_id" json:"model_id"` + // ReRank model ID for retrieval + RerankModelID string `yaml:"rerank_model_id" json:"rerank_model_id"` // Temperature for LLM (0-1) Temperature float64 `yaml:"temperature" json:"temperature"` + // Maximum completion tokens (only for normal mode) + MaxCompletionTokens int `yaml:"max_completion_tokens" json:"max_completion_tokens"` + + // ===== Agent Mode Settings ===== // Maximum iterations for ReAct loop (only for agent type) MaxIterations int `yaml:"max_iterations" json:"max_iterations"` // Allowed tools (only for agent type) AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"` - // Associated knowledge base IDs + // Whether reflection is enabled (only for agent type) + ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"` + + // ===== Knowledge Base Settings ===== + // Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB + KBSelectionMode 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 when no KnowledgeBases are configured - // If true (default), user can freely select any knowledge base - // If false, knowledge base selection is disabled for this agent + // 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 WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"` // Maximum web search results WebSearchMaxResults int `yaml:"web_search_max_results" json:"web_search_max_results"` - // Whether reflection is enabled (only for agent type) - ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"` - // Welcome message displayed when agent is selected + + // ===== Multi-turn Conversation Settings ===== + // Whether multi-turn conversation is enabled MultiTurnEnabled bool `yaml:"multi_turn_enabled" json:"multi_turn_enabled"` // Number of history turns to keep in context HistoryTurns int `yaml:"history_turns" json:"history_turns"` + + // ===== Retrieval Strategy Settings (for both modes) ===== + // Embedding/Vector retrieval top K + EmbeddingTopK int `yaml:"embedding_top_k" json:"embedding_top_k"` + // Keyword retrieval threshold + KeywordThreshold float64 `yaml:"keyword_threshold" json:"keyword_threshold"` + // Vector retrieval threshold + VectorThreshold float64 `yaml:"vector_threshold" json:"vector_threshold"` + // Rerank top K + RerankTopK int `yaml:"rerank_top_k" json:"rerank_top_k"` + // Rerank threshold + RerankThreshold float64 `yaml:"rerank_threshold" json:"rerank_threshold"` + + // ===== Advanced Settings (mainly for normal mode) ===== + // Whether to enable query expansion + EnableQueryExpansion bool `yaml:"enable_query_expansion" json:"enable_query_expansion"` + // Whether to enable query rewrite for multi-turn conversations + EnableRewrite bool `yaml:"enable_rewrite" json:"enable_rewrite"` + // Rewrite prompt system message + RewritePromptSystem string `yaml:"rewrite_prompt_system" json:"rewrite_prompt_system"` + // Rewrite prompt user message template + RewritePromptUser string `yaml:"rewrite_prompt_user" json:"rewrite_prompt_user"` + // Fallback strategy: "fixed" for fixed response, "model" for model generation + FallbackStrategy string `yaml:"fallback_strategy" json:"fallback_strategy"` + // Fixed fallback response (when FallbackStrategy is "fixed") + FallbackResponse string `yaml:"fallback_response" json:"fallback_response"` + // Fallback prompt (when FallbackStrategy is "model") + FallbackPrompt string `yaml:"fallback_prompt" json:"fallback_prompt"` } // Value implements driver.Valuer interface for CustomAgentConfig @@ -128,6 +177,29 @@ func (a *CustomAgent) EnsureDefaults() { if a.Config.HistoryTurns == 0 { a.Config.HistoryTurns = 5 } + // Retrieval strategy defaults + if a.Config.EmbeddingTopK == 0 { + a.Config.EmbeddingTopK = 10 + } + if a.Config.KeywordThreshold == 0 { + a.Config.KeywordThreshold = 0.3 + } + if a.Config.VectorThreshold == 0 { + a.Config.VectorThreshold = 0.5 + } + if a.Config.RerankTopK == 0 { + a.Config.RerankTopK = 5 + } + if a.Config.RerankThreshold == 0 { + a.Config.RerankThreshold = 0.5 + } + // Advanced settings defaults + if a.Config.FallbackStrategy == "" { + a.Config.FallbackStrategy = "model" + } + if a.Config.MaxCompletionTokens == 0 { + a.Config.MaxCompletionTokens = 2048 + } } // IsAgentMode returns true if this agent uses ReAct agent mode @@ -146,10 +218,23 @@ func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent { Type: CustomAgentTypeNormal, TenantID: tenantID, Config: CustomAgentConfig{ - AgentMode: "normal", - SystemPrompt: "", - Temperature: 0.7, - WebSearchEnabled: false, + AgentMode: "normal", + SystemPrompt: "", + Temperature: 0.7, + MaxCompletionTokens: 2048, + WebSearchEnabled: false, + MultiTurnEnabled: true, + HistoryTurns: 5, + // Retrieval strategy + EmbeddingTopK: 10, + KeywordThreshold: 0.3, + VectorThreshold: 0.5, + RerankTopK: 5, + RerankThreshold: 0.5, + // Advanced settings + EnableQueryExpansion: true, + EnableRewrite: true, + FallbackStrategy: "model", }, } } @@ -169,10 +254,18 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent { SystemPrompt: "", Temperature: 0.7, MaxIterations: 10, - AllowedTools: []string{"knowledge_search", "web_search"}, + AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"}, WebSearchEnabled: true, WebSearchMaxResults: 5, ReflectionEnabled: false, + MultiTurnEnabled: true, + HistoryTurns: 5, + // Retrieval strategy + EmbeddingTopK: 10, + KeywordThreshold: 0.3, + VectorThreshold: 0.5, + RerankTopK: 5, + RerankThreshold: 0.5, }, } } diff --git a/internal/types/interfaces/custom_agent.go b/internal/types/interfaces/custom_agent.go index fde98379..bf9a8c22 100644 --- a/internal/types/interfaces/custom_agent.go +++ b/internal/types/interfaces/custom_agent.go @@ -65,14 +65,15 @@ type CustomAgentRepository interface { // - Possible errors such as database connection failure, unique constraint conflicts, etc. CreateAgent(ctx context.Context, agent *types.CustomAgent) error - // GetAgentByID queries an agent by ID + // GetAgentByID queries an agent by ID and tenant // Parameters: // - ctx: Context information // - id: Agent ID + // - tenantID: Tenant ID for isolation // Returns: // - Agent object, if found // - Possible errors such as record not existing, database errors, etc. - GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) + GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) // ListAgentsByTenantID lists all agents for a specific tenant // Parameters: diff --git a/internal/types/session.go b/internal/types/session.go index d239563d..9d5cfd96 100644 --- a/internal/types/session.go +++ b/internal/types/session.go @@ -80,22 +80,22 @@ type Session struct { // Tenant ID TenantID uint64 `json:"tenant_id" gorm:"index"` - // Strategy configuration - KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID - MaxRounds int `json:"max_rounds"` // 多轮保持轮数 - EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关 - FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略 - FallbackResponse string `json:"fallback_response"` // 固定回复内容 - EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK - KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值 - VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值 - RerankModelID string `json:"rerank_model_id"` // 排序模型ID - RerankTopK int `json:"rerank_top_k"` // 排序TopK - RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值 - SummaryModelID string `json:"summary_model_id"` // 总结模型ID - SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数 - AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases) - ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选) + // // Strategy configuration + // KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID + // MaxRounds int `json:"max_rounds"` // 多轮保持轮数 + // EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关 + // FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略 + // FallbackResponse string `json:"fallback_response"` // 固定回复内容 + // EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK + // KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值 + // VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值 + // RerankModelID string `json:"rerank_model_id"` // 排序模型ID + // RerankTopK int `json:"rerank_top_k"` // 排序TopK + // RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值 + // SummaryModelID string `json:"summary_model_id"` // 总结模型ID + // SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数 + // AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases) + // ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选) CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` diff --git a/internal/types/tenant.go b/internal/types/tenant.go index 3430294e..ebafea3a 100644 --- a/internal/types/tenant.go +++ b/internal/types/tenant.go @@ -126,9 +126,7 @@ func (c *RetrieverEngines) Scan(value interface{}) error { // ConversationConfig represents the conversation configuration for normal mode type ConversationConfig struct { // Prompt is the system prompt for normal mode - UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` - Prompt string `json:"prompt"` - UseCustomContextTemplate bool `json:"use_custom_context_template"` + Prompt string `json:"prompt"` // ContextTemplate is the prompt template for summarizing retrieval results ContextTemplate string `json:"context_template"` // Temperature controls the randomness of the model output