feat: 重构提示词模板系统,新增多场景模板配置支持;优化智能体知识库选择模式,支持全部/指定/禁用三种模式

This commit is contained in:
wizardchen
2025-12-25 18:22:36 +08:00
parent dc1ab5b81d
commit abfe87eaed
32 changed files with 2755 additions and 1102 deletions
+1 -13
View File
@@ -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: |
## 任务
用户提供的文本中,提取所有符合以下实体类型的实体:
@@ -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}}
请基于以上资料回答问题。回答要求:
- 直接回答问题,不要重复问题
- 如果资料中没有相关信息,请说明
- 保持回答简洁准确
+47
View File
@@ -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}}
@@ -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. 改写结果必须是一个问句
直接输出改写后的问题,不要有任何解释。
+39
View File
@@ -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}}
## 任务要求
请根据以上对话历史,将当前问题改写为一个独立、完整、可以脱离上下文理解的问题。
## 改写后的问题
+113
View File
@@ -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}}
+41 -7
View File
@@ -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; // 保留历史轮数
}
// 智能体
+21 -3
View File
@@ -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')
}
+75 -29
View File
@@ -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;
@@ -0,0 +1,261 @@
<template>
<div class="prompt-template-selector" :class="{ 'position-corner': position === 'corner' }">
<t-popup
trigger="click"
placement="top-right"
:visible="popupVisible"
@visible-change="handleVisibleChange"
>
<template #content>
<div class="template-popup">
<div class="template-header">
<span class="template-title">{{ $t('promptTemplate.selectTemplate') }}</span>
</div>
<div v-if="loading" class="template-loading">
<t-loading size="small" />
</div>
<div v-else-if="templates.length === 0" class="template-empty">
{{ $t('promptTemplate.noTemplates') || '暂无模板' }}
</div>
<div v-else class="template-list">
<div
v-for="template in templates"
:key="template.id"
class="template-item"
@click="selectTemplate(template)"
>
<div class="template-item-header">
<span class="template-name">{{ template.name }}</span>
<span v-if="template.has_knowledge_base" class="template-tag kb-tag">
<t-icon name="folder" size="12px" />
{{ $t('promptTemplate.withKnowledgeBase') }}
</span>
<span v-if="template.has_web_search" class="template-tag web-tag">
<t-icon name="internet" size="12px" />
{{ $t('promptTemplate.withWebSearch') }}
</span>
</div>
<p class="template-desc">{{ template.description }}</p>
</div>
</div>
</div>
</template>
<t-button
variant="outline"
size="small"
class="template-trigger-btn"
:loading="loading"
>
<t-icon name="view-module" />
<span>{{ $t('promptTemplate.useTemplate') }}</span>
</t-button>
</t-popup>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getPromptTemplates, type PromptTemplate, type PromptTemplatesConfig } from '@/api/system';
const props = defineProps<{
type: 'systemPrompt' | 'contextTemplate' | 'rewriteSystem' | 'rewriteUser' | 'fallback';
hasKnowledgeBase?: boolean;
position?: 'inline' | 'corner'; // inline: 行内显示, corner: 输入框右下角
}>();
const emit = defineEmits<{
(e: 'select', content: string): void;
}>();
const popupVisible = ref(false);
const loading = ref(false);
const templatesConfig = ref<PromptTemplatesConfig | null>(null);
const handleVisibleChange = async (visible: boolean) => {
popupVisible.value = visible;
// 首次打开时加载模板
if (visible && !templatesConfig.value) {
await loadTemplates();
}
};
const loadTemplates = async () => {
if (loading.value) return;
loading.value = true;
try {
const response = await getPromptTemplates();
templatesConfig.value = response.data;
} catch (error) {
console.error('Failed to load prompt templates:', error);
} finally {
loading.value = false;
}
};
// 根据类型获取对应的模板列表
const templates = computed<PromptTemplate[]>(() => {
if (!templatesConfig.value) return [];
switch (props.type) {
case 'systemPrompt':
return templatesConfig.value.system_prompt || [];
case 'contextTemplate':
return templatesConfig.value.context_template || [];
case 'rewriteSystem':
return templatesConfig.value.rewrite_system || [];
case 'rewriteUser':
return templatesConfig.value.rewrite_user || [];
case 'fallback':
return templatesConfig.value.fallback || [];
default:
return [];
}
});
const selectTemplate = (template: PromptTemplate) => {
emit('select', template.content);
popupVisible.value = false;
};
// 预加载模板(可选)
onMounted(() => {
// 可以在这里预加载,也可以等用户点击时再加载
// loadTemplates();
});
</script>
<style scoped lang="less">
.prompt-template-selector {
display: inline-flex;
&.position-corner {
position: absolute;
right: 8px;
bottom: 8px;
z-index: 10;
}
}
.template-trigger-btn {
display: inline-flex;
align-items: center;
gap: 4px;
color: #666;
border-color: #d9d9d9;
font-size: 12px;
height: 26px;
padding: 0 8px;
background: rgba(255, 255, 255, 0.95);
&:hover {
color: #07c05f;
border-color: #07c05f;
background: #fff;
}
:deep(.t-button__text) {
display: inline-flex;
align-items: center;
gap: 4px;
}
:deep(.t-icon) {
vertical-align: middle;
line-height: 1;
}
}
.template-popup {
width: 420px;
max-height: 400px;
overflow: hidden;
display: flex;
flex-direction: column;
}
.template-header {
padding: 12px 16px;
border-bottom: 1px solid #e5e7eb;
flex-shrink: 0;
}
.template-title {
font-size: 14px;
font-weight: 500;
color: #333;
}
.template-loading,
.template-empty {
padding: 40px 16px;
text-align: center;
color: #999;
font-size: 13px;
}
.template-list {
overflow-y: auto;
padding: 8px;
flex: 1;
}
.template-item {
padding: 12px;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
margin-bottom: 4px;
&:last-child {
margin-bottom: 0;
}
&:hover {
background: #f5f7fa;
}
}
.template-item-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
flex-wrap: wrap;
}
.template-name {
font-size: 14px;
font-weight: 500;
color: #333;
}
.template-tag {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 2px 6px;
border-radius: 4px;
font-size: 11px;
&.kb-tag {
background: #e6f7ff;
color: #1890ff;
}
&.web-tag {
background: #f0faf5;
color: #07c05f;
}
}
.template-desc {
font-size: 12px;
color: #666;
margin: 0;
line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
+138 -6
View File
@@ -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',
},
},
},
}
+137 -5
View File
@@ -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: "引导模型基于通用知识回答的提示词",
},
},
},
};
-2
View File
@@ -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: [], // 默认为空数组
File diff suppressed because it is too large Load Diff
+33 -17
View File
@@ -37,6 +37,10 @@
<div class="card-header-left">
<AgentAvatar :name="agent.name" size="medium" />
<span class="card-title" :title="agent.name">{{ agent.name }}</span>
<div v-if="agent.is_builtin" class="builtin-badge">
<t-icon name="lock-on" size="12px" />
<span>{{ $t('agent.builtin') }}</span>
</div>
</div>
<t-popup
v-if="!agent.is_builtin"
@@ -67,9 +71,9 @@
</div>
</template>
</t-popup>
<div v-else class="builtin-badge">
<t-icon name="lock-on" size="12px" />
<span>{{ $t('agent.builtin') }}</span>
<!-- 内置智能体显示编辑按钮 -->
<div v-else class="edit-btn" @click.stop="handleEdit(agent)">
<t-icon name="edit" size="16px" />
</div>
</div>
@@ -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 {
+158 -179
View File
@@ -4,6 +4,10 @@
<div class="section-header">
<h2>{{ $t('settings.conversationStrategy') }}</h2>
<p class="section-description">{{ $t('conversationSettings.description') }}</p>
<div class="global-config-notice">
<t-icon name="info-circle" />
<span>这些是全局默认配置,新建智能体时会继承这些设置。您也可以在智能体列表中单独配置每个智能体。</span>
</div>
</div>
<t-tabs v-model="activeTab" class="conversation-tabs">
@@ -146,17 +150,7 @@
</div>
<div class="setting-control full-width" style="position: relative;">
<div class="prompt-header">
<div class="prompt-toggle">
<span class="prompt-toggle-label">{{ $t('agentSettings.systemPrompt.custom') }}</span>
<t-switch
v-model="localUseCustomSystemPrompt"
:label="[$t('common.off'), $t('common.on')]"
size="large"
@change="handleUseCustomPromptToggle"
/>
</div>
<t-button
v-if="localUseCustomSystemPrompt"
theme="default"
variant="outline"
size="small"
@@ -167,18 +161,15 @@
</t-button>
</div>
<p class="prompt-tab-hint">
{{ $t('agentSettings.systemPrompt.tabHint') }}
{{ $t('agentSettings.systemPrompt.tabHint') }}(留空则使用系统默认)
</p>
<p v-if="!localUseCustomSystemPrompt" class="prompt-disabled-hint">
{{ $t('agentSettings.systemPrompt.disabledHint') }}
</p>
<div v-if="localUseCustomSystemPrompt" class="system-prompt-tabs">
<div class="system-prompt-tabs">
<t-tabs
v-model="activeSystemPromptTab"
class="system-prompt-variant-tabs"
>
<t-tab-panel value="web-enabled" :label="$t('agentSettings.systemPrompt.tabWebOn')">
<div v-if="activeSystemPromptTab === 'web-enabled'" class="prompt-textarea-wrapper">
<div v-if="activeSystemPromptTab === 'web-enabled'" class="prompt-textarea-wrapper textarea-with-template">
<t-textarea
ref="promptTextareaRef"
v-model="localSystemPromptWebEnabled"
@@ -187,14 +178,18 @@
@blur="handleSystemPromptChange('web-enabled', $event)"
@input="handlePromptInput"
@keydown="handlePromptKeydown"
:readonly="!localUseCustomSystemPrompt"
:class="{ 'prompt-textarea-readonly': !localUseCustomSystemPrompt }"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
<PromptTemplateSelector
type="systemPrompt"
position="corner"
:hasKnowledgeBase="true"
@select="handleAgentSystemPromptTemplateSelect"
/>
</div>
</t-tab-panel>
<t-tab-panel value="web-disabled" :label="$t('agentSettings.systemPrompt.tabWebOff')">
<div v-if="activeSystemPromptTab === 'web-disabled'" class="prompt-textarea-wrapper">
<div v-if="activeSystemPromptTab === 'web-disabled'" class="prompt-textarea-wrapper textarea-with-template">
<t-textarea
ref="promptTextareaRef"
v-model="localSystemPromptWebDisabled"
@@ -203,10 +198,14 @@
@blur="handleSystemPromptChange('web-disabled', $event)"
@input="handlePromptInput"
@keydown="handlePromptKeydown"
:readonly="!localUseCustomSystemPrompt"
:class="{ 'prompt-textarea-readonly': !localUseCustomSystemPrompt }"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
<PromptTemplateSelector
type="systemPrompt"
position="corner"
:hasKnowledgeBase="true"
@select="handleAgentSystemPromptTemplateSelect"
/>
</div>
</t-tab-panel>
</t-tabs>
@@ -214,7 +213,7 @@
<!-- 占位符提示下拉框 -->
<teleport to="body">
<div
v-if="localUseCustomSystemPrompt && showPlaceholderPopup && filteredPlaceholders.length > 0"
v-if="showPlaceholderPopup && filteredPlaceholders.length > 0"
class="placeholder-popup-wrapper"
:style="popupStyle"
>
@@ -249,24 +248,10 @@
<div class="setting-row vertical">
<div class="setting-info">
<label>{{ $t('conversationSettings.systemPrompt.label') }}</label>
<p class="desc">{{ $t('conversationSettings.systemPrompt.desc') }}</p>
<p class="desc">{{ $t('conversationSettings.systemPrompt.desc') }}(留空则使用系统默认)</p>
</div>
<div class="setting-control full-width">
<div class="prompt-header">
<div class="prompt-toggle">
<span class="prompt-toggle-label">{{ $t('conversationSettings.systemPrompt.custom') }}</span>
<t-switch
v-model="localUseCustomSystemPromptNormal"
:label="[$t('common.off'), $t('common.on')]"
size="large"
@change="handleUseCustomSystemPromptNormalToggle"
/>
</div>
</div>
<p v-if="!localUseCustomSystemPromptNormal" class="prompt-disabled-hint">
{{ $t('conversationSettings.systemPrompt.disabledHint') }}
</p>
<div v-if="localUseCustomSystemPromptNormal" class="prompt-textarea-wrapper">
<div class="prompt-textarea-wrapper textarea-with-template">
<t-textarea
v-model="localSystemPromptNormal"
:autosize="{ minRows: 10, maxRows: 20 }"
@@ -274,32 +259,24 @@
@blur="handleSystemPromptNormalChange"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
<PromptTemplateSelector
type="systemPrompt"
position="corner"
:hasKnowledgeBase="true"
@select="handleNormalSystemPromptTemplateSelect"
/>
</div>
</div>
</div>
<!-- Context Template(普通模式,自定义开关) -->
<!-- Context Template(普通模式) -->
<div class="setting-row vertical">
<div class="setting-info">
<label>{{ $t('conversationSettings.contextTemplate.label') }}</label>
<p class="desc">{{ $t('conversationSettings.contextTemplate.desc') }}</p>
<p class="desc">{{ $t('conversationSettings.contextTemplate.desc') }}(留空则使用系统默认)</p>
</div>
<div class="setting-control full-width">
<div class="prompt-header">
<div class="prompt-toggle">
<span class="prompt-toggle-label">{{ $t('conversationSettings.contextTemplate.custom') }}</span>
<t-switch
v-model="localUseCustomContextTemplate"
:label="[$t('common.off'), $t('common.on')]"
size="large"
@change="handleUseCustomContextTemplateToggle"
/>
</div>
</div>
<p v-if="!localUseCustomContextTemplate" class="prompt-disabled-hint">
{{ $t('conversationSettings.contextTemplate.disabledHint') }}
</p>
<div v-if="localUseCustomContextTemplate" class="prompt-textarea-wrapper">
<div class="prompt-textarea-wrapper textarea-with-template">
<t-textarea
v-model="localContextTemplate"
:autosize="{ minRows: 15, maxRows: 30 }"
@@ -307,6 +284,12 @@
@blur="handleContextTemplateChange"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
<PromptTemplateSelector
type="contextTemplate"
position="corner"
:hasKnowledgeBase="true"
@select="handleContextTemplateTemplateSelect"
/>
</div>
</div>
</div>
@@ -540,11 +523,18 @@
<p class="desc">{{ $t('conversationSettings.rewritePrompt.desc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localRewritePromptSystem"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptSystemChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localRewritePromptSystem"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptSystemChange"
/>
<PromptTemplateSelector
type="rewriteSystem"
position="corner"
@select="handleRewriteSystemTemplateSelect"
/>
</div>
</div>
</div>
@@ -554,11 +544,18 @@
<p class="desc">{{ $t('conversationSettings.rewritePrompt.userDesc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localRewritePromptUser"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptUserChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localRewritePromptUser"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptUserChange"
/>
<PromptTemplateSelector
type="rewriteUser"
position="corner"
@select="handleRewriteUserTemplateSelect"
/>
</div>
</div>
</div>
@@ -583,26 +580,40 @@
<p class="desc">{{ $t('conversationSettings.fallbackResponse.desc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localFallbackResponse"
:autosize="{ minRows: 3, maxRows: 6 }"
@blur="handleFallbackResponseChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localFallbackResponse"
:autosize="{ minRows: 3, maxRows: 6 }"
@blur="handleFallbackResponseChange"
/>
<PromptTemplateSelector
type="fallback"
position="corner"
@select="handleFallbackResponseTemplateSelect"
/>
</div>
</div>
</div>
<!-- 兜底 Prompt:仅在选择“交给模型继续生成”时展示 -->
<!-- 兜底 Prompt:仅在选择"交给模型继续生成"时展示 -->
<div v-else-if="localFallbackStrategy === 'model'" class="setting-row vertical">
<div class="setting-info">
<label>{{ $t('conversationSettings.fallbackPrompt.label') }}</label>
<p class="desc">{{ $t('conversationSettings.fallbackPrompt.desc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localFallbackPrompt"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleFallbackPromptChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localFallbackPrompt"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleFallbackPromptChange"
/>
<PromptTemplateSelector
type="fallback"
position="corner"
@select="handleFallbackPromptTemplateSelect"
/>
</div>
</div>
</div>
@@ -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<SystemPromptTab, string> = {
}
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<AgentConfig> = {}): 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;
@@ -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
}
@@ -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
}
@@ -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),
+132 -37
View File
@@ -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
-42
View File
@@ -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)
}
+155 -242
View File
@@ -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)
+91 -10
View File
@@ -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"`
+1 -1
View File
@@ -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"`
+4 -102
View File
@@ -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获取会话详情
+8 -15
View File
@@ -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
+1 -125
View File
@@ -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)
}
}
+48 -115
View File
@@ -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,
})
}
+106 -13
View File
@@ -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,
},
}
}
+3 -2
View File
@@ -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:
+16 -16
View File
@@ -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"`
+1 -3
View File
@@ -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