feat: 统一系统提示词并优化智能体选择器界面

- 将系统提示词从分离的网络搜索开/关状态合并为统一提示词,使用 {{web_search_status}} 占位符动态控制行为
- 重构智能体选择器,从简单tooltip升级为内容丰富的popup,显示智能体详细信息、类型和能力
- 新增FAQ优先策略配置,支持FAQ答案优先于普通文档
- 优化知识库选择逻辑,智能体切换时自动同步配置的知识库
- 更新相关接口类型定义和国际化文本
This commit is contained in:
wizardchen
2025-12-28 21:46:42 +08:00
parent c9e482eb79
commit 6bc19ab082
21 changed files with 1198 additions and 609 deletions
+1 -2
View File
@@ -4,8 +4,7 @@ import { get, post, put, del } from "../../utils/request";
export interface CustomAgentConfig { export interface CustomAgentConfig {
// ===== 基础设置 ===== // ===== 基础设置 =====
agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式 agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式
system_prompt?: string; // 系统提示词(普通模式,或Agent模式网络搜索关闭时) system_prompt?: string; // 统一系统提示词(使用 {{web_search_status}} 占位符动态控制行为)
system_prompt_web_enabled?: string; // Agent模式网络搜索开启时的系统提示词
context_template?: string; // 上下文模板(普通模式) context_template?: string; // 上下文模板(普通模式)
// ===== 模型设置 ===== // ===== 模型设置 =====
+1 -2
View File
@@ -29,8 +29,7 @@ export interface AgentConfig {
allowed_tools: string[] allowed_tools: string[]
temperature: number temperature: number
knowledge_bases?: string[] knowledge_bases?: string[]
system_prompt_web_enabled?: string // Custom system prompt when web search is enabled system_prompt?: string // Unified system prompt (uses {{web_search_status}} placeholder)
system_prompt_web_disabled?: string // Custom system prompt when web search is disabled
available_tools?: ToolDefinition[] // GET 响应中包含,POST/PUT 不需要 available_tools?: ToolDefinition[] // GET 响应中包含,POST/PUT 不需要
available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要 available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要
} }
+167 -43
View File
@@ -20,12 +20,13 @@
<!-- 内置智能体分组 --> <!-- 内置智能体分组 -->
<div class="agent-group"> <div class="agent-group">
<div class="agent-group-title">{{ $t('agent.builtinAgents') }}</div> <div class="agent-group-title">{{ $t('agent.builtinAgents') }}</div>
<t-tooltip <t-popup
v-for="agent in builtinAgents" v-for="agent in builtinAgents"
:key="agent.id" :key="agent.id"
:content="getAgentCapabilities(agent)"
:disabled="currentAgentId === agent.id"
placement="right" placement="right"
trigger="hover"
:show-arrow="true"
:overlay-inner-class-name="'agent-tooltip-popup'"
> >
<div <div
class="agent-option" class="agent-option"
@@ -47,18 +48,39 @@
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/> <path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg> </svg>
</div> </div>
</t-tooltip> <template #content>
<div class="agent-tooltip-content">
<div class="agent-tooltip-header">
<div class="builtin-icon" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">
<TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" />
</div>
<div class="agent-tooltip-title">
<span class="agent-tooltip-name">{{ agent.name }}</span>
<span v-if="currentAgentId === agent.id" class="agent-tooltip-selected">{{ $t('agent.selector.current') }}</span>
</div>
</div>
<p class="agent-tooltip-desc">{{ agent.description || $t('agent.noDescription') }}</p>
<div class="agent-tooltip-capabilities">
<div class="capability-item">
<TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="12px" />
<span>{{ agent.config?.agent_mode === 'smart-reasoning' ? $t('agent.type.agent') : $t('agent.type.normal') }}</span>
</div>
</div>
</div>
</template>
</t-popup>
</div> </div>
<!-- 自定义智能体分组 --> <!-- 自定义智能体分组 -->
<div v-if="customAgents.length > 0" class="agent-group"> <div v-if="customAgents.length > 0" class="agent-group">
<div class="agent-group-title">{{ $t('agent.customAgents') }}</div> <div class="agent-group-title">{{ $t('agent.customAgents') }}</div>
<t-tooltip <t-popup
v-for="agent in customAgents" v-for="agent in customAgents"
:key="agent.id" :key="agent.id"
:content="getAgentCapabilities(agent)"
:disabled="currentAgentId === agent.id"
placement="right" placement="right"
trigger="hover"
:show-arrow="true"
:overlay-inner-class-name="'agent-tooltip-popup'"
> >
<div <div
class="agent-option" class="agent-option"
@@ -78,7 +100,41 @@
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/> <path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg> </svg>
</div> </div>
</t-tooltip> <template #content>
<div class="agent-tooltip-content">
<div class="agent-tooltip-header">
<AgentAvatar :name="agent.name" size="small" />
<div class="agent-tooltip-title">
<span class="agent-tooltip-name">{{ agent.name }}</span>
<span v-if="currentAgentId === agent.id" class="agent-tooltip-selected">{{ $t('agent.selector.current') }}</span>
</div>
</div>
<p class="agent-tooltip-desc">{{ agent.description || $t('agent.noDescription') }}</p>
<div class="agent-tooltip-capabilities">
<div class="capability-item">
<TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="12px" />
<span>{{ agent.config?.agent_mode === 'smart-reasoning' ? $t('agent.type.agent') : $t('agent.type.normal') }}</span>
</div>
<div v-if="getKbCapability(agent)" class="capability-item">
<TIcon name="folder" size="12px" />
<span>{{ getKbCapability(agent) }}</span>
</div>
<div v-if="agent.config?.web_search_enabled" class="capability-item">
<TIcon name="internet" size="12px" />
<span>{{ $t('agent.capabilities.webSearchOn') }}</span>
</div>
<div v-if="agent.config?.mcp_services?.length || agent.config?.mcp_selection_mode === 'all'" class="capability-item">
<TIcon name="extension" size="12px" />
<span>{{ $t('agent.capabilities.mcpEnabled') }}</span>
</div>
<div v-if="agent.config?.multi_turn_enabled" class="capability-item">
<TIcon name="chat-bubble" size="12px" />
<span>{{ $t('agent.capabilities.multiTurn') }}</span>
</div>
</div>
</div>
</template>
</t-popup>
</div> </div>
<!-- 空状态 --> <!-- 空状态 -->
@@ -94,7 +150,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue'; import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Icon as TIcon } from 'tdesign-vue-next'; import { Icon as TIcon, Popup as TPopup } from 'tdesign-vue-next';
import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent'; import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';
import AgentAvatar from '@/components/AgentAvatar.vue'; import AgentAvatar from '@/components/AgentAvatar.vue';
@@ -139,45 +195,17 @@ const customAgents = computed(() => {
return agents.value.filter(a => !a.is_builtin); return agents.value.filter(a => !a.is_builtin);
}); });
// 获取智能体能力描述(用于 tooltip) // 获取知识库能力描述
const getAgentCapabilities = (agent: CustomAgent): string => { const getKbCapability = (agent: CustomAgent): string => {
// 内置智能体
if (agent.is_builtin) {
if (agent.config?.agent_mode === 'quick-answer') {
return t('agent.capabilities.normal');
} else if (agent.config?.agent_mode === 'smart-reasoning') {
return t('agent.capabilities.agent');
}
return '';
}
// 自定义智能体
const capabilities: string[] = [];
const config = agent.config || {}; const config = agent.config || {};
if (config.model_id) {
capabilities.push(t('agent.capabilities.modelSpecified'));
}
if (config.kb_selection_mode === 'none') { if (config.kb_selection_mode === 'none') {
capabilities.push(t('agent.capabilities.kbDisabled')); return '';
} else if (config.knowledge_bases && config.knowledge_bases.length > 0) { } else if (config.knowledge_bases && config.knowledge_bases.length > 0) {
capabilities.push(t('agent.capabilities.kbCount', { count: config.knowledge_bases.length })); return t('agent.capabilities.kbCount', { count: config.knowledge_bases.length });
} else if (config.kb_selection_mode === 'all') { } else if (config.kb_selection_mode === 'all') {
capabilities.push(t('agent.capabilities.kbAll')); return t('agent.capabilities.kbAll');
} }
if (config.rerank_model_id) { return '';
capabilities.push(t('agent.capabilities.rerankSpecified'));
}
if (config.web_search_enabled === true) {
capabilities.push(t('agent.capabilities.webSearchOn'));
} else if (config.web_search_enabled === false) {
capabilities.push(t('agent.capabilities.webSearchOff'));
}
if (config.system_prompt) {
capabilities.push(t('agent.capabilities.hasPrompt'));
}
return capabilities.length > 0 ? capabilities.join('、') : t('agent.capabilities.default');
}; };
// 加载智能体列表 // 加载智能体列表
@@ -429,4 +457,100 @@ onMounted(() => {
flex-shrink: 0; flex-shrink: 0;
margin-left: 6px; margin-left: 6px;
} }
// Tooltip 内容样式
.agent-tooltip-content {
padding: 4px 0;
min-width: 200px;
max-width: 280px;
}
.agent-tooltip-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
.builtin-icon {
width: 28px;
height: 28px;
}
}
.agent-tooltip-title {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.agent-tooltip-name {
font-size: 13px;
font-weight: 600;
color: var(--td-text-color-primary, #222);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.agent-tooltip-selected {
font-size: 10px;
color: #10b981;
font-weight: 500;
}
.agent-tooltip-desc {
font-size: 12px;
color: var(--td-text-color-secondary, #666);
line-height: 1.5;
margin: 0 0 10px 0;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.agent-tooltip-capabilities {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding-top: 8px;
border-top: 1px solid var(--td-component-stroke, #f0f0f0);
}
.capability-item {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
border-radius: 4px;
font-size: 11px;
color: var(--td-text-color-secondary, #666);
:deep(.t-icon) {
color: var(--td-text-color-placeholder, #999);
}
}
</style>
<!-- 全局样式覆盖 TDesign Popup -->
<style lang="less">
.agent-tooltip-popup {
&.t-popup__content {
background: var(--td-bg-color-container, #fff) !important;
border: 1px solid var(--td-component-border, #e7e9eb) !important;
border-radius: 8px !important;
box-shadow: var(--td-shadow-2, 0 6px 28px rgba(15, 23, 42, 0.08)) !important;
padding: 10px 12px !important;
}
.t-popup__arrow {
&::before {
background: var(--td-bg-color-container, #fff) !important;
border-color: var(--td-component-border, #e7e9eb) !important;
}
}
}
</style> </style>
+29 -31
View File
@@ -21,6 +21,8 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
const settingsStore = useSettingsStore(); const settingsStore = useSettingsStore();
const uiStore = useUIStore(); const uiStore = useUIStore();
const { t } = useI18n();
let query = ref(""); let query = ref("");
const showKbSelector = ref(false); const showKbSelector = ref(false);
const atButtonRef = ref<HTMLElement>(); const atButtonRef = ref<HTMLElement>();
@@ -76,6 +78,19 @@ const agentKnowledgeBases = computed(() => {
return currentAgentConfig.value?.knowledge_bases || []; return currentAgentConfig.value?.knowledge_bases || [];
}); });
// 当智能体改变时,将智能体配置的知识库同步到 store
// 这样用户可以移除这些知识库
watch([selectedAgentId, agentKnowledgeBases], ([newAgentId, newAgentKbs], [oldAgentId]) => {
if (newAgentId !== oldAgentId && newAgentKbs && newAgentKbs.length > 0) {
// 智能体切换了,将新智能体配置的知识库添加到 store
const currentSelected = settingsStore.settings.selectedKnowledgeBases || [];
const toAdd = newAgentKbs.filter((id: string) => !currentSelected.includes(id));
if (toAdd.length > 0) {
settingsStore.selectKnowledgeBases([...currentSelected, ...toAdd]);
}
}
}, { immediate: true });
// 智能体的知识库选择模式 // 智能体的知识库选择模式
const agentKBSelectionMode = computed(() => { const agentKBSelectionMode = computed(() => {
if (!hasAgentConfig.value) return null; // null 表示不受智能体控制 if (!hasAgentConfig.value) return null; // null 表示不受智能体控制
@@ -173,30 +188,18 @@ const selectedFiles = computed(() => {
}); });
// 合并所有选中项(用于输入框内显示) // 合并所有选中项(用于输入框内显示)
// 包括用户选择的和智能体预配置的知识库 // 现在智能体配置的知识库也在 store 中,统一从 selectedKbs 获取
const allSelectedItems = computed(() => { const allSelectedItems = computed(() => {
// 获取智能体预配置的知识库 IDs // 获取智能体预配置的知识库 IDs(用于标记和排序)
const agentKbIds = agentKnowledgeBases.value; const agentKbIds = agentKnowledgeBases.value;
// 用户选择的知识库(排除智能体已配置的) // 所有选中的知识库,标记是否为智能体配置
const userSelectedKbs = selectedKbs.value const allKbs = selectedKbs.value.map(kb => ({
.filter(kb => !agentKbIds.includes(kb.id)) ...kb,
.map(kb => ({ type: 'kb' as const,
...kb, kbType: kb.type,
type: 'kb' as const, isAgentConfigured: agentKbIds.includes(kb.id)
kbType: kb.type, }));
isAgentConfigured: false
}));
// 智能体预配置的知识库
const agentConfiguredKbs = knowledgeBases.value
.filter(kb => agentKbIds.includes(kb.id))
.map(kb => ({
...kb,
type: 'kb' as const,
kbType: kb.type,
isAgentConfigured: true // 标记为智能体配置,不可删除
}));
// 用户选择的文件 // 用户选择的文件
const files = selectedFiles.value.map((f: { id: string; name: string }) => ({ const files = selectedFiles.value.map((f: { id: string; name: string }) => ({
@@ -206,16 +209,14 @@ const selectedFiles = computed(() => {
})); }));
// 智能体配置的放在前面 // 智能体配置的放在前面
const agentConfiguredKbs = allKbs.filter(kb => kb.isAgentConfigured);
const userSelectedKbs = allKbs.filter(kb => !kb.isAgentConfigured);
return [...agentConfiguredKbs, ...userSelectedKbs, ...files]; return [...agentConfiguredKbs, ...userSelectedKbs, ...files];
}); });
// 移除选中项(智能体配置的项不可移除) // 移除选中项(智能体配置的项也可以移除)
const removeSelectedItem = (item: { id: string; type: 'kb' | 'file'; isAgentConfigured?: boolean }) => { const removeSelectedItem = (item: { id: string; type: 'kb' | 'file'; isAgentConfigured?: boolean }) => {
// 如果是智能体配置的,不允许删除
if (item.isAgentConfigured) {
MessagePlugin.warning(t('input.cannotRemoveAgentKb'));
return;
}
if (item.type === 'kb') { if (item.type === 'kb') {
settingsStore.removeKnowledgeBase(item.id); settingsStore.removeKnowledgeBase(item.id);
} else { } else {
@@ -236,8 +237,6 @@ const showModelSelector = ref(false);
const modelButtonRef = ref<HTMLElement>(); const modelButtonRef = ref<HTMLElement>();
const modelDropdownStyle = ref<Record<string, string>>({}); const modelDropdownStyle = ref<Record<string, string>>({});
const { t } = useI18n();
// 显示的知识库标签(最多显示2个) // 显示的知识库标签(最多显示2个)
const displayedKbs = computed(() => selectedKbs.value.slice(0, 2)); const displayedKbs = computed(() => selectedKbs.value.slice(0, 2));
const remainingCount = computed(() => Math.max(0, selectedKbs.value.length - 2)); const remainingCount = computed(() => Math.max(0, selectedKbs.value.length - 2));
@@ -1507,8 +1506,7 @@ onBeforeRouteUpdate((to, from, next) => {
<t-icon v-else name="file" /> <t-icon v-else name="file" />
</span> </span>
<span class="tag-name">{{ item.name }}</span> <span class="tag-name">{{ item.name }}</span>
<!-- 智能体配置的项不显示删除按钮 --> <span class="tag-remove" @click="removeSelectedItem(item)">×</span>
<span v-if="!item.isAgentConfigured" class="tag-remove" @click="removeSelectedItem(item)">×</span>
</span> </span>
</div> </div>
+38 -5
View File
@@ -228,6 +228,8 @@ export default {
webSearchOff: 'Web search disabled', webSearchOff: 'Web search disabled',
hasPrompt: 'Custom prompt', hasPrompt: 'Custom prompt',
default: 'Default configuration', default: 'Default configuration',
mcpEnabled: 'MCP services enabled',
multiTurn: 'Multi-turn conversation',
}, },
type: { type: {
normal: 'Quick Answer', normal: 'Quick Answer',
@@ -285,6 +287,12 @@ export default {
systemPromptRequired: 'System prompt is required', systemPromptRequired: 'System prompt is required',
modelRequired: 'Please select a model', modelRequired: 'Please select a model',
rerankModelRequired: 'ReRank model is required when using knowledge bases', rerankModelRequired: 'ReRank model is required when using knowledge bases',
contextsMissing: 'Context template must contain {{contexts}} placeholder when knowledge base is enabled',
queryMissingInContext: 'Context template must contain {{query}} placeholder',
knowledgeBasesMissing: 'It is recommended to include {{knowledge_bases}} placeholder in system prompt so the model knows available knowledge bases',
queryMissingInRewrite: 'Rewrite user prompt must contain {{query}} placeholder',
conversationMissing: 'Rewrite user prompt must contain {{conversation}} placeholder',
queryMissingInFallback: 'Fallback prompt must contain {{query}} placeholder',
avatar: 'Avatar', avatar: 'Avatar',
avatarPlaceholder: 'Enter Emoji or select', avatarPlaceholder: 'Enter Emoji or select',
description: 'Description', description: 'Description',
@@ -295,8 +303,7 @@ export default {
model: 'Model', model: 'Model',
modelPlaceholder: 'Select Model', modelPlaceholder: 'Select Model',
systemPrompt: 'System Prompt', systemPrompt: 'System Prompt',
systemPromptPlaceholder: 'Custom system prompt to define agent behavior and role', systemPromptPlaceholder: 'Custom system prompt to define agent behavior and role (use {{web_search_status}} placeholder for dynamic web search behavior)',
systemPromptWebEnabledPlaceholder: 'System prompt used when web search is enabled',
defaultPromptHint: 'Leave empty to use the following default system prompt:', defaultPromptHint: 'Leave empty to use the following default system prompt:',
defaultContextTemplateHint: 'Leave empty to use the following default context template:', defaultContextTemplateHint: 'Leave empty to use the following default context template:',
contextTemplateRequired: 'Context template is required', contextTemplateRequired: 'Context template is required',
@@ -360,6 +367,34 @@ export default {
builtinSection: 'Built-in Agents', builtinSection: 'Built-in Agents',
customSection: 'My Agents', customSection: 'My Agents',
addNew: 'Add New Agent', addNew: 'Add New Agent',
current: 'Current',
},
// Built-in agent information
builtinInfo: {
quickAnswer: {
name: 'Quick Answer',
description: 'Knowledge base RAG Q&A for fast and accurate answers',
},
smartReasoning: {
name: 'Smart Reasoning',
description: 'ReAct reasoning framework with multi-step thinking and tool calling',
},
deepResearcher: {
name: 'Deep Researcher',
description: 'Focused on in-depth research and comprehensive analysis, capable of creating research plans, multi-dimensional information retrieval, deep thinking and providing thorough analysis reports',
},
dataAnalyst: {
name: 'Data Analyst',
description: 'Focused on database queries and data analysis, capable of understanding business needs, building SQL queries, analyzing data and providing insights',
},
knowledgeGraphExpert: {
name: 'Knowledge Graph Expert',
description: 'Focused on knowledge graph queries and relationship analysis, capable of exploring entity relationships, discovering hidden connections and building knowledge networks',
},
documentAssistant: {
name: 'Document Assistant',
description: 'Focused on document retrieval and content organization, capable of quickly locating documents, extracting key information and generating summaries',
},
}, },
}, },
settings: { settings: {
@@ -1706,9 +1741,7 @@ export default {
custom: 'Custom Prompt', custom: 'Custom Prompt',
disabledHint: 'Currently using the default prompt. Enable custom to apply the content below.', disabledHint: 'Currently using the default prompt. Enable custom to apply the content below.',
placeholder: 'Enter the system prompt, or leave blank to use the default...', placeholder: 'Enter the system prompt, or leave blank to use the default...',
tabHint: 'Configure separate prompts for sessions with web search on or off.', tabHint: 'Unified system prompt using {{web_search_status}} placeholder for dynamic web search behavior'
tabWebOn: 'Web search enabled',
tabWebOff: 'Web search disabled'
}, },
reset: { reset: {
header: 'Reset to Default Prompt', header: 'Reset to Default Prompt',
+38 -5
View File
@@ -758,6 +758,8 @@ export default {
webSearchOff: "禁用网络搜索", webSearchOff: "禁用网络搜索",
hasPrompt: "自定义提示词", hasPrompt: "自定义提示词",
default: "默认配置", default: "默认配置",
mcpEnabled: "启用 MCP 服务",
multiTurn: "多轮对话",
}, },
type: { type: {
normal: "快速问答", normal: "快速问答",
@@ -815,6 +817,12 @@ export default {
systemPromptRequired: "请输入系统提示词", systemPromptRequired: "请输入系统提示词",
modelRequired: "请选择模型", modelRequired: "请选择模型",
rerankModelRequired: "使用知识库时请选择 ReRank 模型", rerankModelRequired: "使用知识库时请选择 ReRank 模型",
contextsMissing: "开启知识库时,上下文模板必须包含 {{contexts}} 占位符",
queryMissingInContext: "上下文模板必须包含 {{query}} 占位符",
knowledgeBasesMissing: "建议在系统提示词中包含 {{knowledge_bases}} 占位符,以便模型了解可用的知识库",
queryMissingInRewrite: "改写用户提示词必须包含 {{query}} 占位符",
conversationMissing: "改写用户提示词必须包含 {{conversation}} 占位符",
queryMissingInFallback: "兜底提示词必须包含 {{query}} 占位符",
avatar: "图标", avatar: "图标",
avatarPlaceholder: "输入 Emoji 或点击选择", avatarPlaceholder: "输入 Emoji 或点击选择",
description: "描述", description: "描述",
@@ -825,8 +833,7 @@ export default {
model: "模型", model: "模型",
modelPlaceholder: "请选择模型", modelPlaceholder: "请选择模型",
systemPrompt: "系统提示词", systemPrompt: "系统提示词",
systemPromptPlaceholder: "自定义系统提示词,定义智能体的行为和角色", systemPromptPlaceholder: "自定义系统提示词,定义智能体的行为和角色(使用 {{web_search_status}} 占位符动态控制网络搜索行为)",
systemPromptWebEnabledPlaceholder: "网络搜索开启时使用的系统提示词",
defaultPromptHint: "留空将使用以下系统默认提示词:", defaultPromptHint: "留空将使用以下系统默认提示词:",
defaultContextTemplateHint: "留空将使用以下系统默认上下文模板:", defaultContextTemplateHint: "留空将使用以下系统默认上下文模板:",
contextTemplateRequired: "请输入上下文模板", contextTemplateRequired: "请输入上下文模板",
@@ -890,6 +897,34 @@ export default {
builtinSection: "内置智能体", builtinSection: "内置智能体",
customSection: "我的智能体", customSection: "我的智能体",
addNew: "添加新智能体", addNew: "添加新智能体",
current: "当前",
},
// 内置智能体信息
builtinInfo: {
quickAnswer: {
name: "快速问答",
description: "基于知识库的 RAG 问答,快速准确地回答问题",
},
smartReasoning: {
name: "智能推理",
description: "ReAct 推理框架,支持多步思考和工具调用",
},
deepResearcher: {
name: "深度研究员",
description: "专注于深度研究和综合分析,能够制定研究计划、多维度检索信息、深入思考并给出全面的分析报告",
},
dataAnalyst: {
name: "数据分析师",
description: "专注于数据库查询和数据分析,能够理解业务需求、构建SQL查询、分析数据并提供洞察",
},
knowledgeGraphExpert: {
name: "知识图谱专家",
description: "专注于知识图谱查询和关系分析,能够探索实体关系、发现隐藏联系并构建知识网络",
},
documentAssistant: {
name: "文档助手",
description: "专注于文档检索和内容整理,能够快速定位文档、提取关键信息并生成摘要",
},
}, },
}, },
file: { file: {
@@ -1709,9 +1744,7 @@ export default {
custom: "自定义 Prompt", custom: "自定义 Prompt",
disabledHint: "当前使用系统默认 Prompt,开启自定义后才会应用下方内容。", disabledHint: "当前使用系统默认 Prompt,开启自定义后才会应用下方内容。",
placeholder: "请输入系统 Prompt,或留空使用默认 Prompt...", placeholder: "请输入系统 Prompt,或留空使用默认 Prompt...",
tabHint: "根据是否启用网络搜索分别配置系统 Prompt。", tabHint: "统一的系统提示词,使用 {{web_search_status}} 占位符动态控制网络搜索行为",
tabWebOn: "网络搜索已启用",
tabWebOff: "网络搜索未启用",
}, },
reset: { reset: {
header: "恢复默认 Prompt", header: "恢复默认 Prompt",
+8 -4
View File
@@ -22,8 +22,7 @@ interface AgentConfig {
maxIterations: number; maxIterations: number;
temperature: number; temperature: number;
allowedTools: string[]; allowedTools: string[];
system_prompt_web_enabled?: string; system_prompt?: string; // Unified system prompt (uses {{web_search_status}} placeholder)
system_prompt_web_disabled?: string;
} }
interface ConversationModels { interface ConversationModels {
@@ -69,8 +68,7 @@ const defaultSettings: Settings = {
maxIterations: 5, maxIterations: 5,
temperature: 0.7, temperature: 0.7,
allowedTools: [], // 默认为空,需要通过 API 从后端加载 allowedTools: [], // 默认为空,需要通过 API 从后端加载
system_prompt_web_enabled: "", system_prompt: "",
system_prompt_web_disabled: "",
}, },
selectedKnowledgeBases: [], // 默认为空数组 selectedKnowledgeBases: [], // 默认为空数组
selectedFiles: [], // 默认为空数组 selectedFiles: [], // 默认为空数组
@@ -326,6 +324,12 @@ export const useSettingsStore = defineStore("settings", {
this.settings.isAgentEnabled = true; this.settings.isAgentEnabled = true;
} }
// 自定义智能体需要根据其配置来决定 // 自定义智能体需要根据其配置来决定
// 切换智能体时重置知识库和文件选择状态
// 因为不同智能体关联的知识库不同,需要清空用户之前的选择
this.settings.selectedKnowledgeBases = [];
this.settings.selectedFiles = [];
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings)); localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
}, },
+338 -179
View File
@@ -127,44 +127,22 @@
</div> </div>
</div> </div>
<div class="setting-control setting-control-full" style="position: relative;"> <div class="setting-control setting-control-full" style="position: relative;">
<!-- Agent模式:网络搜索开/关两个提示词 --> <!-- Agent模式:统一提示词(使用 {{web_search_status}} 占位符动态控制行为) -->
<div v-if="isAgentMode" class="system-prompt-tabs"> <div v-if="isAgentMode" class="textarea-with-template">
<t-tabs v-model="activePromptTab" class="prompt-variant-tabs"> <t-textarea
<t-tab-panel value="web-disabled" label="网络搜索关闭"> ref="promptTextareaRef"
<div class="textarea-with-template"> v-model="formData.config.system_prompt"
<t-textarea :placeholder="systemPromptPlaceholder"
ref="promptTextareaRef" :autosize="{ minRows: 10, maxRows: 25 }"
v-model="formData.config.system_prompt" @input="handlePromptInput"
:placeholder="systemPromptWebDisabledPlaceholder" class="system-prompt-textarea"
:autosize="{ minRows: 10, maxRows: 25 }" />
@input="handlePromptInput" <PromptTemplateSelector
class="system-prompt-textarea" type="systemPrompt"
/> position="corner"
<PromptTemplateSelector :hasKnowledgeBase="hasKnowledgeBase"
type="systemPrompt" @select="handleSystemPromptTemplateSelect"
position="corner" />
:hasKnowledgeBase="hasKnowledgeBase"
@select="handleSystemPromptTemplateSelect"
/>
</div>
</t-tab-panel>
<t-tab-panel value="web-enabled" label="网络搜索开启">
<div class="textarea-with-template">
<t-textarea
v-model="formData.config.system_prompt_web_enabled"
:placeholder="systemPromptWebEnabledPlaceholder"
:autosize="{ minRows: 10, maxRows: 25 }"
class="system-prompt-textarea"
/>
<PromptTemplateSelector
type="systemPrompt"
position="corner"
:hasKnowledgeBase="hasKnowledgeBase"
@select="handleSystemPromptTemplateSelect"
/>
</div>
</t-tab-panel>
</t-tabs>
</div> </div>
<!-- 普通模式:单个提示词 --> <!-- 普通模式:单个提示词 -->
<div v-else class="textarea-with-template"> <div v-else class="textarea-with-template">
@@ -626,7 +604,15 @@
:key="kb.value" :key="kb.value"
:value="kb.value" :value="kb.value"
:label="kb.label" :label="kb.label"
/> >
<div class="kb-option-item">
<span class="kb-option-icon" :class="kb.type === 'faq' ? 'faq-icon' : 'doc-icon'">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" />
</span>
<span class="kb-option-label">{{ kb.label }}</span>
<span class="kb-option-count">({{ kb.count || 0 }})</span>
</div>
</t-option>
</t-select> </t-select>
</div> </div>
</div> </div>
@@ -648,6 +634,56 @@
/> />
</div> </div>
</div> </div>
<!-- FAQ 策略设置(仅当选择了 FAQ 类型知识库时显示) -->
<div v-if="hasFaqKnowledgeBase" class="faq-strategy-section">
<div class="faq-strategy-header">
<t-icon name="chat-bubble-help" class="faq-icon" />
<span>FAQ 优先策略</span>
<t-tooltip content="当知识库中包含 FAQ(问答对)时,可以启用此策略让 FAQ 答案优先于普通文档">
<t-icon name="help-circle" class="help-icon" />
</t-tooltip>
</div>
<!-- FAQ 优先开关 -->
<div class="setting-row">
<div class="setting-info">
<label>启用 FAQ 优先</label>
<p class="desc">FAQ 答案将优先于普通文档被引用,提高回答准确性</p>
</div>
<div class="setting-control">
<t-switch v-model="formData.config.faq_priority_enabled" />
</div>
</div>
<!-- FAQ 直接回答阈值 -->
<div v-if="formData.config.faq_priority_enabled" class="setting-row">
<div class="setting-info">
<label>直接回答阈值</label>
<p class="desc">当问题与 FAQ 相似度超过此值时,直接使用 FAQ 答案</p>
</div>
<div class="setting-control">
<div class="slider-wrapper">
<t-slider v-model="formData.config.faq_direct_answer_threshold" :min="0.7" :max="1" :step="0.05" />
<span class="slider-value">{{ formData.config.faq_direct_answer_threshold?.toFixed(2) }}</span>
</div>
</div>
</div>
<!-- FAQ 分数加权 -->
<div v-if="formData.config.faq_priority_enabled" class="setting-row">
<div class="setting-info">
<label>FAQ 分数加权</label>
<p class="desc">FAQ 结果的相关性分数乘以此系数,使其排序更靠前</p>
</div>
<div class="setting-control">
<div class="slider-wrapper">
<t-slider v-model="formData.config.faq_score_boost" :min="1" :max="2" :step="0.1" />
<span class="slider-value">{{ formData.config.faq_score_boost?.toFixed(1) }}x</span>
</div>
</div>
</div>
</div>
</div> </div>
</div> </div>
@@ -768,115 +804,107 @@
</div> </div>
</div> </div>
</div> </div>
</div>
</div>
<!-- 高级设置(仅普通模式) --> <!-- 兜底策略(仅普通模式) -->
<div v-show="currentSection === 'advanced' && !isAgentMode" class="section"> <template v-if="!isAgentMode">
<div class="section-header"> <div class="setting-row">
<h2>{{ $t('agent.editor.advancedSettings') || '高级设置' }}</h2> <div class="setting-info">
<p class="section-description">配置兜底策略</p> <label>{{ $t('agent.editor.fallbackStrategy') || '兜底策略' }}</label>
</div> <p class="desc">当无法从知识库找到相关内容时的处理方式</p>
</div>
<div class="settings-group"> <div class="setting-control">
<!-- 兜底策略 --> <t-radio-group v-model="formData.config.fallback_strategy">
<div class="setting-row"> <t-radio-button value="fixed">固定回复</t-radio-button>
<div class="setting-info"> <t-radio-button value="model">模型生成</t-radio-button>
<label>{{ $t('agent.editor.fallbackStrategy') || '兜底策略' }}</label> </t-radio-group>
<p class="desc">当无法从知识库找到相关内容时的处理方式</p>
</div>
<div class="setting-control">
<t-radio-group v-model="formData.config.fallback_strategy">
<t-radio-button value="fixed">固定回复</t-radio-button>
<t-radio-button value="model">模型生成</t-radio-button>
</t-radio-group>
</div>
</div>
<!-- 固定兜底回复 -->
<div v-if="formData.config.fallback_strategy === 'fixed'" class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agent.editor.fallbackResponse') || '固定回复内容' }}</label>
<p class="desc">当无法回答时返回的固定文本</p>
</div>
<div class="setting-control setting-control-full">
<div class="textarea-with-template">
<t-textarea
v-model="formData.config.fallback_response"
:placeholder="defaultFallbackResponse || $t('agent.editor.fallbackResponsePlaceholder') || '抱歉,我无法回答这个问题。'"
:autosize="{ minRows: 2, maxRows: 6 }"
/>
<PromptTemplateSelector
type="fallback"
position="corner"
@select="handleFallbackResponseTemplateSelect"
/>
</div> </div>
</div> </div>
</div>
<!-- 兜底提示词 --> <!-- 固定兜底回复 -->
<div v-if="formData.config.fallback_strategy === 'model'" class="setting-row setting-row-vertical"> <div v-if="formData.config.fallback_strategy === 'fixed'" class="setting-row setting-row-vertical">
<div class="setting-info"> <div class="setting-info">
<label>{{ $t('agent.editor.fallbackPrompt') || '兜底提示词' }}</label> <label>{{ $t('agent.editor.fallbackResponse') || '固定回复内容' }}</label>
<p class="desc">当无法从知识库找到答案时,引导模型生成回复的提示词</p> <p class="desc">当无法回答时返回的固定文本</p>
<div class="placeholder-tags" v-if="fallbackPlaceholders.length > 0"> </div>
<span class="placeholder-label">可用变量:</span> <div class="setting-control setting-control-full">
<t-tooltip <div class="textarea-with-template">
v-for="placeholder in fallbackPlaceholders" <t-textarea
:key="placeholder.name" v-model="formData.config.fallback_response"
:content="placeholder.description + '(点击插入)'" :placeholder="defaultFallbackResponse || $t('agent.editor.fallbackResponsePlaceholder') || '抱歉,我无法回答这个问题。'"
placement="top" :autosize="{ minRows: 2, maxRows: 6 }"
> />
<span <PromptTemplateSelector
class="placeholder-tag" type="fallback"
@click="handlePlaceholderClick('fallback', placeholder.name)" position="corner"
v-text="'{{' + placeholder.name + '}}'" @select="handleFallbackResponseTemplateSelect"
></span> />
</t-tooltip> </div>
<span class="placeholder-hint" v-text="'(点击插入,或输入 {{ 唤起列表)'"></span>
</div> </div>
</div> </div>
<div class="setting-control setting-control-full" style="position: relative;">
<div class="textarea-with-template"> <!-- 兜底提示词 -->
<t-textarea <div v-if="formData.config.fallback_strategy === 'model'" class="setting-row setting-row-vertical">
ref="fallbackPromptTextareaRef" <div class="setting-info">
v-model="formData.config.fallback_prompt" <label>{{ $t('agent.editor.fallbackPrompt') || '兜底提示词' }}</label>
:placeholder="defaultFallbackPrompt || $t('agent.editor.fallbackPromptPlaceholder') || '留空使用系统默认提示词'" <p class="desc">当无法从知识库找到答案时,引导模型生成回复的提示词</p>
:autosize="{ minRows: 4, maxRows: 10 }" <div class="placeholder-tags" v-if="fallbackPlaceholders.length > 0">
@input="handleFallbackPromptInput" <span class="placeholder-label">可用变量:</span>
/> <t-tooltip
<PromptTemplateSelector v-for="placeholder in fallbackPlaceholders"
type="fallback" :key="placeholder.name"
position="corner" :content="placeholder.description + '(点击插入)'"
@select="handleFallbackPromptTemplateSelect" placement="top"
/> >
<span
class="placeholder-tag"
@click="handlePlaceholderClick('fallback', placeholder.name)"
v-text="'{{' + placeholder.name + '}}'"
></span>
</t-tooltip>
<span class="placeholder-hint" v-text="'(点击插入,或输入 {{ 唤起列表)'"></span>
</div>
</div> </div>
<Teleport to="body"> <div class="setting-control setting-control-full" style="position: relative;">
<div <div class="textarea-with-template">
v-if="fallbackPromptPopup.show && filteredFallbackPlaceholders.length > 0" <t-textarea
class="placeholder-popup-wrapper" ref="fallbackPromptTextareaRef"
:style="fallbackPromptPopup.style" v-model="formData.config.fallback_prompt"
> :placeholder="defaultFallbackPrompt || $t('agent.editor.fallbackPromptPlaceholder') || '留空使用系统默认提示词'"
<div class="placeholder-popup"> :autosize="{ minRows: 4, maxRows: 10 }"
<div @input="handleFallbackPromptInput"
v-for="(placeholder, index) in filteredFallbackPlaceholders" />
:key="placeholder.name" <PromptTemplateSelector
class="placeholder-item" type="fallback"
:class="{ active: fallbackPromptPopup.selectedIndex === index }" position="corner"
@mousedown.prevent="insertGenericPlaceholder('fallback', placeholder.name, true)" @select="handleFallbackPromptTemplateSelect"
@mouseenter="fallbackPromptPopup.selectedIndex = index" />
> </div>
<div class="placeholder-name"> <Teleport to="body">
<code v-html="`{{${placeholder.name}}}`"></code> <div
v-if="fallbackPromptPopup.show && filteredFallbackPlaceholders.length > 0"
class="placeholder-popup-wrapper"
:style="fallbackPromptPopup.style"
>
<div class="placeholder-popup">
<div
v-for="(placeholder, index) in filteredFallbackPlaceholders"
:key="placeholder.name"
class="placeholder-item"
:class="{ active: fallbackPromptPopup.selectedIndex === index }"
@mousedown.prevent="insertGenericPlaceholder('fallback', placeholder.name, true)"
@mouseenter="fallbackPromptPopup.selectedIndex = index"
>
<div class="placeholder-name">
<code v-html="`{{${placeholder.name}}}`"></code>
</div>
<div class="placeholder-desc">{{ placeholder.description }}</div>
</div> </div>
<div class="placeholder-desc">{{ placeholder.description }}</div>
</div> </div>
</div> </div>
</div> </Teleport>
</Teleport> </div>
</div> </div>
</div> </template>
</div> </div>
</div> </div>
</div> </div>
@@ -927,13 +955,11 @@ const emit = defineEmits<{
const currentSection = ref(props.initialSection || 'basic'); const currentSection = ref(props.initialSection || 'basic');
const saving = ref(false); const saving = ref(false);
const allModels = ref<ModelConfig[]>([]); const allModels = ref<ModelConfig[]>([]);
const kbOptions = ref<{ label: string; value: string }[]>([]); const kbOptions = ref<{ label: string; value: string; type?: 'document' | 'faq'; count?: number }[]>([]);
const mcpOptions = ref<{ label: string; value: string }[]>([]); const mcpOptions = ref<{ label: string; value: string }[]>([]);
// 系统默认配置(用于内置智能体显示默认提示词) // 系统默认配置(用于内置智能体显示默认提示词)
const defaultSystemPrompt = ref(''); // 普通模式默认提示词 const defaultSystemPrompt = ref(''); // 统一的默认系统提示词
const defaultSystemPromptWebEnabled = ref(''); // Agent模式 Web开启时默认提示词
const defaultSystemPromptWebDisabled = ref(''); // Agent模式 Web关闭时默认提示词
const defaultContextTemplate = ref(''); const defaultContextTemplate = ref('');
const defaultRewritePromptSystem = ref(''); const defaultRewritePromptSystem = ref('');
const defaultRewritePromptUser = ref(''); const defaultRewritePromptUser = ref('');
@@ -974,6 +1000,18 @@ const hasKnowledgeBase = computed(() => {
return kbSelectionMode.value !== 'none'; return kbSelectionMode.value !== 'none';
}); });
// 检测选择的知识库中是否包含 FAQ 类型
const hasFaqKnowledgeBase = computed(() => {
if (kbSelectionMode.value === 'none') return false;
if (kbSelectionMode.value === 'all') {
// 全部知识库模式,检查是否有任何 FAQ 类型的知识库
return kbOptions.value.some(kb => kb.type === 'faq');
}
// 指定知识库模式,检查选中的知识库中是否有 FAQ 类型
const selectedKbIds = formData.value.config.knowledge_bases || [];
return kbOptions.value.some(kb => selectedKbIds.includes(kb.value) && kb.type === 'faq');
});
const availableTools = computed(() => { const availableTools = computed(() => {
return allTools.map(tool => ({ return allTools.map(tool => ({
...tool, ...tool,
@@ -1076,10 +1114,6 @@ const navItems = computed(() => {
if (!isAgentMode.value) { if (!isAgentMode.value) {
items.push({ key: 'conversation', icon: 'chat', label: t('agent.editor.conversationSettings') || '多轮对话' }); items.push({ key: 'conversation', icon: 'chat', label: t('agent.editor.conversationSettings') || '多轮对话' });
} }
// 普通模式才显示高级设置
if (!isAgentMode.value) {
items.push({ key: 'advanced', icon: 'setting', label: t('agent.editor.advancedSettings') || '高级设置' });
}
return items; return items;
}); });
@@ -1092,7 +1126,6 @@ const defaultFormData = {
// 基础设置 // 基础设置
agent_mode: 'quick-answer' as 'quick-answer' | 'smart-reasoning', agent_mode: 'quick-answer' as 'quick-answer' | 'smart-reasoning',
system_prompt: '', system_prompt: '',
system_prompt_web_enabled: '',
context_template: '{{query}}', context_template: '{{query}}',
// 模型设置 // 模型设置
model_id: '', model_id: '',
@@ -1109,6 +1142,10 @@ const defaultFormData = {
// 知识库设置 // 知识库设置
kb_selection_mode: 'none' as 'all' | 'selected' | 'none', kb_selection_mode: 'none' as 'all' | 'selected' | 'none',
knowledge_bases: [] as string[], knowledge_bases: [] as string[],
// FAQ 策略设置
faq_priority_enabled: true, // 是否启用 FAQ 优先策略
faq_direct_answer_threshold: 0.9, // FAQ 直接回答阈值(相似度高于此值直接使用 FAQ 答案)
faq_score_boost: 1.2, // FAQ 分数加权系数
// 网络搜索设置 // 网络搜索设置
web_search_enabled: false, web_search_enabled: false,
web_search_max_results: 5, web_search_max_results: 5,
@@ -1153,24 +1190,11 @@ const systemPromptPlaceholder = computed(() => {
return t('agent.editor.systemPromptPlaceholder'); return t('agent.editor.systemPromptPlaceholder');
}); });
// Agent模式 Web关闭时的 placeholder
const systemPromptWebDisabledPlaceholder = computed(() => {
return t('agent.editor.systemPromptPlaceholder');
});
// Agent模式 Web开启时的 placeholder
const systemPromptWebEnabledPlaceholder = computed(() => {
return t('agent.editor.systemPromptWebEnabledPlaceholder') || '网络搜索开启时使用的系统提示词';
});
// 上下文模板的 placeholder // 上下文模板的 placeholder
const contextTemplatePlaceholder = computed(() => { const contextTemplatePlaceholder = computed(() => {
return t('agent.editor.contextTemplatePlaceholder'); return t('agent.editor.contextTemplatePlaceholder');
}); });
// Agent模式系统提示词Tab
const activePromptTab = ref<'web-disabled' | 'web-enabled'>('web-disabled');
// 是否需要配置 ReRank 模型(有知识库能力时需要) // 是否需要配置 ReRank 模型(有知识库能力时需要)
const needsRerankModel = computed(() => { const needsRerankModel = computed(() => {
return hasKnowledgeBase.value; return hasKnowledgeBase.value;
@@ -1269,12 +1293,9 @@ const fillBuiltinAgentDefaults = () => {
const isAgent = config.agent_mode === 'smart-reasoning'; const isAgent = config.agent_mode === 'smart-reasoning';
if (isAgent) { if (isAgent) {
// Agent 模式:填入 Web 开启/关闭的默认提示词 // Agent 模式:填入统一的默认提示词
if (!config.system_prompt && defaultSystemPromptWebDisabled.value) { if (!config.system_prompt && defaultSystemPrompt.value) {
config.system_prompt = defaultSystemPromptWebDisabled.value; config.system_prompt = defaultSystemPrompt.value;
}
if (!config.system_prompt_web_enabled && defaultSystemPromptWebEnabled.value) {
config.system_prompt_web_enabled = defaultSystemPromptWebEnabled.value;
} }
} else { } else {
// 普通模式:填入默认系统提示词和上下文模板 // 普通模式:填入默认系统提示词和上下文模板
@@ -1405,7 +1426,12 @@ const loadDependencies = async () => {
// 加载知识库列表 // 加载知识库列表
const kbRes: any = await listKnowledgeBases(); const kbRes: any = await listKnowledgeBases();
if (kbRes.data) { if (kbRes.data) {
kbOptions.value = kbRes.data.map((kb: any) => ({ label: kb.name, value: kb.id })); kbOptions.value = kbRes.data.map((kb: any) => ({
label: kb.name,
value: kb.id,
type: kb.type || 'document',
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0)
}));
} }
// 加载 MCP 服务列表(只加载启用的) // 加载 MCP 服务列表(只加载启用的)
@@ -1430,18 +1456,16 @@ const loadDependencies = async () => {
console.warn('Failed to load placeholders', e); console.warn('Failed to load placeholders', e);
} }
// 加载 Agent 模式默认提示词 // 加载 Agent 模式默认提示词(统一提示词)
const agentConfig = await getAgentConfig(); const agentConfig = await getAgentConfig();
if (agentConfig.data?.system_prompt_web_enabled) { if (agentConfig.data?.system_prompt) {
defaultSystemPromptWebEnabled.value = agentConfig.data.system_prompt_web_enabled; defaultSystemPrompt.value = agentConfig.data.system_prompt;
}
if (agentConfig.data?.system_prompt_web_disabled) {
defaultSystemPromptWebDisabled.value = agentConfig.data.system_prompt_web_disabled;
} }
// 加载系统默认配置(用于内置智能体显示默认提示词) // 加载系统默认配置(用于普通模式)
const conversationConfig = await getConversationConfig(); const conversationConfig = await getConversationConfig();
if (conversationConfig.data?.prompt) { if (conversationConfig.data?.prompt && !defaultSystemPrompt.value) {
// 如果 Agent 配置没有提供默认提示词,则使用普通模式的
defaultSystemPrompt.value = conversationConfig.data.prompt; defaultSystemPrompt.value = conversationConfig.data.prompt;
} }
if (conversationConfig.data?.context_template) { if (conversationConfig.data?.context_template) {
@@ -2214,11 +2238,7 @@ watch(() => props.visible, (val) => {
// 模板选择处理函数 // 模板选择处理函数
const handleSystemPromptTemplateSelect = (template: string) => { const handleSystemPromptTemplateSelect = (template: string) => {
if (activePromptTab.value === 'web-enabled') { formData.value.config.system_prompt = template;
formData.value.config.system_prompt_web_enabled = template;
} else {
formData.value.config.system_prompt = template;
}
}; };
const handleContextTemplateSelect = (template: string) => { const handleContextTemplateSelect = (template: string) => {
@@ -2241,6 +2261,12 @@ const handleFallbackPromptTemplateSelect = (template: string) => {
formData.value.config.fallback_prompt = template; formData.value.config.fallback_prompt = template;
}; };
// 辅助函数:检查提示词是否包含指定占位符
const hasPlaceholder = (text: string | undefined, placeholder: string): boolean => {
if (!text) return false;
return text.includes(`{{${placeholder}}}`);
};
const handleSave = async () => { const handleSave = async () => {
// 验证必填项(内置智能体不验证名称和系统提示词) // 验证必填项(内置智能体不验证名称和系统提示词)
if (!isBuiltinAgent.value) { if (!isBuiltinAgent.value) {
@@ -2265,6 +2291,58 @@ const handleSave = async () => {
} }
} }
// 校验占位符(普通模式 + 开启知识库)
if (!isAgentMode.value && hasKnowledgeBase.value) {
const contextTemplate = formData.value.config.context_template || '';
if (!hasPlaceholder(contextTemplate, 'contexts')) {
MessagePlugin.error(t('agent.editor.contextsMissing') || '开启知识库时,上下文模板必须包含 {{contexts}} 占位符');
currentSection.value = 'basic';
return;
}
if (!hasPlaceholder(contextTemplate, 'query')) {
MessagePlugin.error(t('agent.editor.queryMissingInContext') || '上下文模板必须包含 {{query}} 占位符');
currentSection.value = 'basic';
return;
}
}
// 校验占位符(Agent 模式 + 开启知识库)
if (isAgentMode.value && hasKnowledgeBase.value) {
const systemPrompt = formData.value.config.system_prompt || '';
if (!hasPlaceholder(systemPrompt, 'knowledge_bases')) {
MessagePlugin.warning(t('agent.editor.knowledgeBasesMissing') || '建议在系统提示词中包含 {{knowledge_bases}} 占位符,以便模型了解可用的知识库');
}
}
// 校验占位符(普通模式 + 开启多轮对话改写)
if (!isAgentMode.value && formData.value.config.multi_turn_enabled && formData.value.config.enable_rewrite) {
const rewritePrompt = formData.value.config.rewrite_prompt_user || '';
// 只有用户自定义了改写提示词时才校验
if (rewritePrompt.trim()) {
if (!hasPlaceholder(rewritePrompt, 'query')) {
MessagePlugin.error(t('agent.editor.queryMissingInRewrite') || '改写用户提示词必须包含 {{query}} 占位符');
currentSection.value = 'conversation';
return;
}
if (!hasPlaceholder(rewritePrompt, 'conversation')) {
MessagePlugin.error(t('agent.editor.conversationMissing') || '改写用户提示词必须包含 {{conversation}} 占位符');
currentSection.value = 'conversation';
return;
}
}
}
// 校验占位符(兜底策略为模型生成时)
if (!isAgentMode.value && formData.value.config.fallback_strategy === 'model') {
const fallbackPrompt = formData.value.config.fallback_prompt || '';
// 只有用户自定义了兜底提示词时才校验
if (fallbackPrompt.trim() && !hasPlaceholder(fallbackPrompt, 'query')) {
MessagePlugin.error(t('agent.editor.queryMissingInFallback') || '兜底提示词必须包含 {{query}} 占位符');
currentSection.value = 'retrieval';
return;
}
}
if (!formData.value.config.model_id) { if (!formData.value.config.model_id) {
MessagePlugin.error(t('agent.editor.modelRequired')); MessagePlugin.error(t('agent.editor.modelRequired'));
currentSection.value = 'model'; currentSection.value = 'model';
@@ -3008,4 +3086,85 @@ const handleSave = async () => {
} }
} }
} }
// 知识库选项样式
.kb-option-item {
display: flex;
align-items: center;
gap: 6px;
}
.kb-option-icon {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
font-size: 16px;
// Document KB - Greenish
&.doc-icon {
color: #10b981;
}
// FAQ KB - Blueish
&.faq-icon {
color: #0052d9;
}
}
.kb-option-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kb-option-count {
flex-shrink: 0;
font-size: 12px;
color: #999;
}
// FAQ 策略区域样式
.faq-strategy-section {
margin-top: 24px;
padding: 16px;
background: rgba(0, 82, 217, 0.04);
border: 1px solid rgba(0, 82, 217, 0.15);
border-radius: 8px;
}
.faq-strategy-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 16px;
font-size: 14px;
font-weight: 600;
color: #0052d9;
.faq-icon {
font-size: 18px;
}
.help-icon {
font-size: 14px;
color: #999;
cursor: help;
}
}
.faq-strategy-section .setting-row {
padding: 12px 0;
border-bottom: 1px solid rgba(0, 82, 217, 0.1);
&:last-child {
border-bottom: none;
padding-bottom: 0;
}
&:first-of-type {
padding-top: 0;
}
}
</style> </style>
+36 -96
View File
@@ -161,54 +161,27 @@
</t-button> </t-button>
</div> </div>
<p class="prompt-tab-hint"> <p class="prompt-tab-hint">
{{ $t('agentSettings.systemPrompt.tabHint') }}(留空则使用系统默认) {{ $t('agentSettings.systemPrompt.tabHint') }}(留空则使用系统默认,使用 {{web_search_status}} 占位符动态控制网络搜索行为)
</p> </p>
<div class="system-prompt-tabs"> <div class="system-prompt-tabs">
<t-tabs <div class="prompt-textarea-wrapper textarea-with-template">
v-model="activeSystemPromptTab" <t-textarea
class="system-prompt-variant-tabs" ref="promptTextareaRef"
> v-model="localSystemPrompt"
<t-tab-panel value="web-enabled" :label="$t('agentSettings.systemPrompt.tabWebOn')"> :autosize="{ minRows: 15, maxRows: 30 }"
<div v-if="activeSystemPromptTab === 'web-enabled'" class="prompt-textarea-wrapper textarea-with-template"> :placeholder="$t('agentSettings.systemPrompt.placeholder')"
<t-textarea @blur="handleSystemPromptChange"
ref="promptTextareaRef" @input="handlePromptInput"
v-model="localSystemPromptWebEnabled" @keydown="handlePromptKeydown"
:autosize="{ minRows: 15, maxRows: 30 }" style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
:placeholder="$t('agentSettings.systemPrompt.placeholder')" />
@blur="handleSystemPromptChange('web-enabled', $event)" <PromptTemplateSelector
@input="handlePromptInput" type="systemPrompt"
@keydown="handlePromptKeydown" position="corner"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;" :hasKnowledgeBase="true"
/> @select="handleAgentSystemPromptTemplateSelect"
<PromptTemplateSelector />
type="systemPrompt" </div>
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 textarea-with-template">
<t-textarea
ref="promptTextareaRef"
v-model="localSystemPromptWebDisabled"
:autosize="{ minRows: 15, maxRows: 30 }"
:placeholder="$t('agentSettings.systemPrompt.placeholder')"
@blur="handleSystemPromptChange('web-disabled', $event)"
@input="handlePromptInput"
@keydown="handlePromptKeydown"
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>
</div> </div>
<!-- 占位符提示下拉框 --> <!-- 占位符提示下拉框 -->
<teleport to="body"> <teleport to="body">
@@ -723,20 +696,9 @@ const localMaxIterations = ref(5)
const localTemperature = ref(0.7) const localTemperature = ref(0.7)
const localAllowedTools = ref<string[]>([]) const localAllowedTools = ref<string[]>([])
type SystemPromptTab = 'web-enabled' | 'web-disabled' // 统一系统提示词
const activeSystemPromptTab = ref<SystemPromptTab>('web-enabled') const localSystemPrompt = ref('')
const localSystemPromptWebEnabled = ref('') let savedSystemPrompt = ''
const localSystemPromptWebDisabled = ref('')
const systemPromptRefs: Record<SystemPromptTab, Ref<string>> = {
'web-enabled': localSystemPromptWebEnabled,
'web-disabled': localSystemPromptWebDisabled,
}
const savedSystemPromptMap: Record<SystemPromptTab, string> = {
'web-enabled': '',
'web-disabled': '',
}
const getPromptRefByTab = (tab: SystemPromptTab) => systemPromptRefs[tab]
const getActivePromptRef = () => getPromptRefByTab(activeSystemPromptTab.value)
// 普通模式本地状态 // 普通模式本地状态
const localContextTemplate = ref('') const localContextTemplate = ref('')
@@ -838,8 +800,7 @@ const buildAgentConfigPayload = (overrides: Partial<AgentConfig> = {}): AgentCon
reflection_enabled: false, reflection_enabled: false,
allowed_tools: localAllowedTools.value, allowed_tools: localAllowedTools.value,
temperature: localTemperature.value, temperature: localTemperature.value,
system_prompt_web_enabled: localSystemPromptWebEnabled.value, system_prompt: localSystemPrompt.value,
system_prompt_web_disabled: localSystemPromptWebDisabled.value,
...overrides, ...overrides,
}) })
@@ -929,12 +890,6 @@ let placeholderPopupTimer: any = null
const placeholderPrefix = ref('') // 当前输入的前缀,用于过滤 const placeholderPrefix = ref('') // 当前输入的前缀,用于过滤
const popupStyle = ref({ top: '0px', left: '0px' }) // 提示框位置 const popupStyle = ref({ top: '0px', left: '0px' }) // 提示框位置
watch(activeSystemPromptTab, () => {
showPlaceholderPopup.value = false
placeholderPrefix.value = ''
selectedPlaceholderIndex.value = 0
})
// 设置 textarea 原生事件监听器 // 设置 textarea 原生事件监听器
const setupTextareaEventListeners = () => { const setupTextareaEventListeners = () => {
nextTick(() => { nextTick(() => {
@@ -1048,12 +1003,9 @@ onMounted(async () => {
lastSavedValue = config.max_iterations // 初始化时记录已保存的值 lastSavedValue = config.max_iterations // 初始化时记录已保存的值
localTemperature.value = config.temperature localTemperature.value = config.temperature
localAllowedTools.value = config.allowed_tools || [] localAllowedTools.value = config.allowed_tools || []
const promptWebEnabled = config.system_prompt_web_enabled || '' const systemPrompt = config.system_prompt || ''
const promptWebDisabled = config.system_prompt_web_disabled || '' localSystemPrompt.value = systemPrompt
localSystemPromptWebEnabled.value = promptWebEnabled savedSystemPrompt = systemPrompt
localSystemPromptWebDisabled.value = promptWebDisabled
savedSystemPromptMap['web-enabled'] = promptWebEnabled
savedSystemPromptMap['web-disabled'] = promptWebDisabled
availableTools.value = config.available_tools || [] availableTools.value = config.available_tools || []
availablePlaceholders.value = config.available_placeholders || [] availablePlaceholders.value = config.available_placeholders || []
@@ -1070,8 +1022,7 @@ onMounted(async () => {
maxIterations: config.max_iterations, maxIterations: config.max_iterations,
temperature: config.temperature, temperature: config.temperature,
allowedTools: config.allowed_tools || [], allowedTools: config.allowed_tools || [],
system_prompt_web_enabled: promptWebEnabled, system_prompt: systemPrompt,
system_prompt_web_disabled: promptWebDisabled,
}) })
// 加载普通模式配置 // 加载普通模式配置
@@ -1432,25 +1383,21 @@ const handleResetToDefault = async () => {
try { try {
isResettingPrompt.value = true isResettingPrompt.value = true
// 通过设置 system_prompt_web_* 为空字符串来获取默认值 // 通过设置 system_prompt 为空字符串来获取默认值
// 后端在字段为空时会返回默认值 // 后端在字段为空时会返回默认值
const tempConfig = buildAgentConfigPayload({ const tempConfig = buildAgentConfigPayload({
system_prompt_web_enabled: '', system_prompt: '',
system_prompt_web_disabled: '',
}) })
await updateAgentConfig(tempConfig) await updateAgentConfig(tempConfig)
// 重新加载配置以获取默认 Prompt 的完整内容 // 重新加载配置以获取默认 Prompt 的完整内容
const res = await getAgentConfig() const res = await getAgentConfig()
const defaultPromptWebEnabled = res.data.system_prompt_web_enabled || '' const defaultPrompt = res.data.system_prompt || ''
const defaultPromptWebDisabled = res.data.system_prompt_web_disabled || ''
// 设置为默认 Prompt 的内容 // 设置为默认 Prompt 的内容
localSystemPromptWebEnabled.value = defaultPromptWebEnabled localSystemPrompt.value = defaultPrompt
localSystemPromptWebDisabled.value = defaultPromptWebDisabled savedSystemPrompt = defaultPrompt
savedSystemPromptMap['web-enabled'] = defaultPromptWebEnabled
savedSystemPromptMap['web-disabled'] = defaultPromptWebDisabled
MessagePlugin.success(t('agentSettings.toasts.resetToDefault')) MessagePlugin.success(t('agentSettings.toasts.resetToDefault'))
confirmDialog.hide() confirmDialog.hide()
@@ -1465,7 +1412,7 @@ const handleResetToDefault = async () => {
} }
// 处理系统 Prompt 变化 // 处理系统 Prompt 变化
const handleSystemPromptChange = async (tab: SystemPromptTab, e?: FocusEvent) => { const handleSystemPromptChange = async (e?: FocusEvent) => {
// 如果点击的是占位符提示框,不触发保存 // 如果点击的是占位符提示框,不触发保存
if (e?.relatedTarget) { if (e?.relatedTarget) {
const target = e.relatedTarget as HTMLElement const target = e.relatedTarget as HTMLElement
@@ -1488,18 +1435,15 @@ const handleSystemPromptChange = async (tab: SystemPromptTab, e?: FocusEvent) =>
// 如果正在初始化,不触发保存 // 如果正在初始化,不触发保存
if (isInitializing.value) return if (isInitializing.value) return
const promptRef = getPromptRefByTab(tab)
const savedValue = savedSystemPromptMap[tab]
// 检查内容是否变化 // 检查内容是否变化
if (promptRef.value === savedValue) { if (localSystemPrompt.value === savedSystemPrompt) {
return // 内容没变,不调用接口 return // 内容没变,不调用接口
} }
try { try {
const config = buildAgentConfigPayload() const config = buildAgentConfigPayload()
await updateAgentConfig(config) await updateAgentConfig(config)
savedSystemPromptMap[tab] = promptRef.value // 更新已保存的值 savedSystemPrompt = localSystemPrompt.value // 更新已保存的值
MessagePlugin.success(t('agentSettings.toasts.systemPromptSaved')) MessagePlugin.success(t('agentSettings.toasts.systemPromptSaved'))
} catch (error) { } catch (error) {
console.error('保存系统 Prompt 失败:', error) console.error('保存系统 Prompt 失败:', error)
@@ -1725,11 +1669,7 @@ const handleFallbackPromptChange = async () => {
// 模板选择处理函数 // 模板选择处理函数
const handleAgentSystemPromptTemplateSelect = (template: string) => { const handleAgentSystemPromptTemplateSelect = (template: string) => {
if (activeSystemPromptTab.value === 'web-enabled') { localSystemPrompt.value = template
localSystemPromptWebEnabled.value = template
} else {
localSystemPromptWebDisabled.value = template
}
} }
const handleNormalSystemPromptTemplateSelect = (template: string) => { const handleNormalSystemPromptTemplateSelect = (template: string) => {
+34 -103
View File
@@ -250,7 +250,8 @@ func renderPromptPlaceholdersWithStatus(
return result return result
} }
// BuildSystemPromptWithWeb builds the progressive RAG system prompt with web search enabled // BuildSystemPromptWithKB builds the progressive RAG system prompt with knowledge bases
// Deprecated: Use BuildSystemPrompt instead
func BuildSystemPromptWithWeb( func BuildSystemPromptWithWeb(
knowledgeBases []*KnowledgeBaseInfo, knowledgeBases []*KnowledgeBaseInfo,
systemPromptTemplate ...string, systemPromptTemplate ...string,
@@ -259,13 +260,14 @@ func BuildSystemPromptWithWeb(
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" { if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
template = systemPromptTemplate[0] template = systemPromptTemplate[0]
} else { } else {
template = ProgressiveRAGSystemPromptWithWeb template = ProgressiveRAGSystemPrompt
} }
currentTime := time.Now().Format(time.RFC3339) currentTime := time.Now().Format(time.RFC3339)
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, true, currentTime) return renderPromptPlaceholdersWithStatus(template, knowledgeBases, true, currentTime)
} }
// BuildSystemPromptWithoutWeb builds the progressive RAG system prompt without web search // BuildSystemPromptWithoutWeb builds the progressive RAG system prompt without web search
// Deprecated: Use BuildSystemPrompt instead
func BuildSystemPromptWithoutWeb( func BuildSystemPromptWithoutWeb(
knowledgeBases []*KnowledgeBaseInfo, knowledgeBases []*KnowledgeBaseInfo,
systemPromptTemplate ...string, systemPromptTemplate ...string,
@@ -274,7 +276,7 @@ func BuildSystemPromptWithoutWeb(
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" { if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
template = systemPromptTemplate[0] template = systemPromptTemplate[0]
} else { } else {
template = ProgressiveRAGSystemPromptWithoutWeb template = ProgressiveRAGSystemPrompt
} }
currentTime := time.Now().Format(time.RFC3339) currentTime := time.Now().Format(time.RFC3339)
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, false, currentTime) return renderPromptPlaceholdersWithStatus(template, knowledgeBases, false, currentTime)
@@ -296,8 +298,8 @@ func BuildPureAgentSystemPrompt(
return renderPromptPlaceholdersWithStatus(template, []*KnowledgeBaseInfo{}, webSearchEnabled, currentTime) return renderPromptPlaceholdersWithStatus(template, []*KnowledgeBaseInfo{}, webSearchEnabled, currentTime)
} }
// BuildProgressiveRAGSystemPrompt builds the progressive RAG system prompt based on web search status // BuildSystemPrompt builds the progressive RAG system prompt
// This is the main function to use - it automatically selects the appropriate version // This is the main function to use - it uses a unified template with dynamic web search status
func BuildSystemPrompt( func BuildSystemPrompt(
knowledgeBases []*KnowledgeBaseInfo, knowledgeBases []*KnowledgeBaseInfo,
webSearchEnabled bool, webSearchEnabled bool,
@@ -305,16 +307,20 @@ func BuildSystemPrompt(
systemPromptTemplate ...string, systemPromptTemplate ...string,
) string { ) string {
var basePrompt string var basePrompt string
var template string
// If no knowledge bases, use Pure Agent prompt // Determine template to use
if len(knowledgeBases) == 0 { if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
basePrompt = BuildPureAgentSystemPrompt(webSearchEnabled, systemPromptTemplate...) template = systemPromptTemplate[0]
} else if webSearchEnabled { } else if len(knowledgeBases) == 0 {
basePrompt = BuildSystemPromptWithWeb(knowledgeBases, systemPromptTemplate...) template = PureAgentSystemPrompt
} else { } else {
basePrompt = BuildSystemPromptWithoutWeb(knowledgeBases, systemPromptTemplate...) template = ProgressiveRAGSystemPrompt
} }
currentTime := time.Now().Format(time.RFC3339)
basePrompt = renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime)
// Append selected documents section if any // Append selected documents section if any
if len(selectedDocs) > 0 { if len(selectedDocs) > 0 {
basePrompt += formatSelectedDocuments(selectedDocs) basePrompt += formatSelectedDocuments(selectedDocs)
@@ -346,10 +352,10 @@ Current Time: {{current_time}}
Web Search: {{web_search_status}} Web Search: {{web_search_status}}
` `
// ProgressiveRAGSystemPromptWithWeb is the progressive RAG system prompt template with web search enabled // ProgressiveRAGSystemPrompt is the unified progressive RAG system prompt template
// This version emphasizes hybrid retrieval strategy: KB-first with web supplementation // This template dynamically adapts based on web search status via {{web_search_status}} placeholder
var ProgressiveRAGSystemPromptWithWeb = `### Role var ProgressiveRAGSystemPrompt = `### Role
You are WeKnora, an intelligent retrieval assistant powered by Progressive Agentic RAG. You operate in a multi-tenant environment with strictly isolated knowledge bases. Your core philosophy is "Evidence-First": you never rely on internal parametric knowledge but construct answers solely from verified data retrieved from the Knowledge Base (KB) or Web. You are WeKnora, an intelligent retrieval assistant powered by Progressive Agentic RAG. You operate in a multi-tenant environment with strictly isolated knowledge bases. Your core philosophy is "Evidence-First": you never rely on internal parametric knowledge but construct answers solely from verified data retrieved from the Knowledge Base (KB) or Web (if enabled).
### Mission ### Mission
To deliver accurate, traceable, and verifiable answers by orchestrating a dynamic retrieval process. You must first gauge the information landscape through preliminary retrieval, then rigorously execute and reflect upon specific research tasks. **You prioritize "Deep Reading" over superficial scanning.** To deliver accurate, traceable, and verifiable answers by orchestrating a dynamic retrieval process. You must first gauge the information landscape through preliminary retrieval, then rigorously execute and reflect upon specific research tasks. **You prioritize "Deep Reading" over superficial scanning.**
@@ -357,7 +363,7 @@ To deliver accurate, traceable, and verifiable answers by orchestrating a dynami
### Critical Constraints (ABSOLUTE RULES) ### Critical Constraints (ABSOLUTE RULES)
1. **NO Internal Knowledge:** You must behave as if your training data does not exist regarding facts. 1. **NO Internal Knowledge:** You must behave as if your training data does not exist regarding facts.
2. **Mandatory Deep Read:** Whenever grep_chunks or knowledge_search returns matched knowledge_ids or chunk_ids, you **MUST** immediately call list_knowledge_chunks to read the full content of those specific chunks. Do not rely on search snippets alone. 2. **Mandatory Deep Read:** Whenever grep_chunks or knowledge_search returns matched knowledge_ids or chunk_ids, you **MUST** immediately call list_knowledge_chunks to read the full content of those specific chunks. Do not rely on search snippets alone.
3. **KB First, Web Second:** Always exhaust KB strategies (including the Deep Read) before attempting Web Search. 3. **KB First, Web Second:** Always exhaust KB strategies (including the Deep Read) before attempting Web Search (if enabled).
4. **Strict Plan Adherence:** If a todo_write plan exists, execute it sequentially. No skipping. 4. **Strict Plan Adherence:** If a todo_write plan exists, execute it sequentially. No skipping.
5. **Tool Privacy:** Never expose tool names to the user. 5. **Tool Privacy:** Never expose tool names to the user.
@@ -384,7 +390,7 @@ If in **Path B**, execute tasks in todo_write sequentially. For **EACH** task:
3. **MANDATORY Deep Reflection (in think):** Pause and evaluate the full text: 3. **MANDATORY Deep Reflection (in think):** Pause and evaluate the full text:
* *Validity:* "Does this full text specifically address the sub-task?" * *Validity:* "Does this full text specifically address the sub-task?"
* *Gap Analysis:* "Is anything missing? Is the information outdated? Is the information irrelevant?" * *Gap Analysis:* "Is anything missing? Is the information outdated? Is the information irrelevant?"
* *Correction:* If insufficient, formulate a remedial action (e.g., "Search for synonym X", "Web Search") immediately. * *Correction:* If insufficient, formulate a remedial action (e.g., "Search for synonym X", "Web Search if enabled") immediately.
* *Completion:* Mark task as "completed" ONLY when evidence is secured. * *Completion:* Mark task as "completed" ONLY when evidence is secured.
#### Phase 4: Final Synthesis #### Phase 4: Final Synthesis
@@ -401,109 +407,34 @@ For every retrieval attempt (Phase 1 or Phase 3), follow this exact chain:
* Rule: After Step 1 or 2 returns knowledge_ids, you MUST call this tool. * Rule: After Step 1 or 2 returns knowledge_ids, you MUST call this tool.
* Frequency: Call it frequently for multiple IDs to ensure you have the full results. **Do not be lazy; fetch the content.** * Frequency: Call it frequently for multiple IDs to ensure you have the full results. **Do not be lazy; fetch the content.**
4. **Graph Exploration (query_knowledge_graph):** Optional for relationships. 4. **Graph Exploration (query_knowledge_graph):** Optional for relationships.
5. **Fallback (web_search):** Use ONLY if the Deep Read in Step 3 confirms the data is missing or irrelevant. 5. **Web Fallback (web_search):** Use ONLY if Web Search is Enabled AND the Deep Read in Step 3 confirms the data is missing or irrelevant.
### Tool Selection Guidelines ### Tool Selection Guidelines
* **grep_chunks / knowledge_search:** Your "Index". Use these to find *where* the information might be. * **grep_chunks / knowledge_search:** Your "Index". Use these to find *where* the information might be.
* **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is. * **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is.
* **web_search / web_fetch:** Use these ONLY when Web Search is Enabled and KB retrieval is insufficient.
* **todo_write:** Your "Manager". Tracks multi-step research. * **todo_write:** Your "Manager". Tracks multi-step research.
* **think:** Your "Conscience". Use to plan and relect the content returned by list_knowledge_chunks. * **think:** Your "Conscience". Use to plan and reflect the content returned by list_knowledge_chunks.
### Final Output Standards ### Final Output Standards
* **Definitive:** Based strictly on the "Deep Read" content. * **Definitive:** Based strictly on the "Deep Read" content.
* **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." /> or <web url="..." title="..." />. * **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." /> or <web url="..." title="..." /> (if from web).
Citations may not be placed at the end of the answer. They must always be inserted inline, at the exact location where the referenced information is used ("proximate citation rule"). Citations may not be placed at the end of the answer. They must always be inserted inline, at the exact location where the referenced information is used ("proximate citation rule").
* **Structured:** Clear hierarchy and logic. * **Structured:** Clear hierarchy and logic.
* **Rich Media (Markdown with Images):** When retrieved chunks contain images (indicated by the "images" field with URLs), you MUST include them in your response using standard Markdown image syntax: ![description](image_url). Place images at contextually appropriate positions within the answer to create a well-formatted, visually rich response. Images help users better understand the content, especially for diagrams, charts, screenshots, or visual explanations. * **Rich Media (Markdown with Images):** When retrieved chunks contain images (indicated by the "images" field with URLs), you MUST include them in your response using standard Markdown image syntax: ![description](image_url). Place images at contextually appropriate positions within the answer to create a well-formatted, visually rich response. Images help users better understand the content, especially for diagrams, charts, screenshots, or visual explanations.
### System Status ### System Status
Current Time: {{current_time}} Current Time: {{current_time}}
Web Search: {{web_search_status}}
### User Selected Knowledge Bases (via @ mention) ### User Selected Knowledge Bases (via @ mention)
{{knowledge_bases}} {{knowledge_bases}}
` `
// ProgressiveRAGSystemPromptWithoutWeb is the progressive RAG system prompt template without web search // ProgressiveRAGSystemPromptWithWeb is deprecated, use ProgressiveRAGSystemPrompt instead
// This version emphasizes deep KB-only retrieval with advanced techniques // Kept for backward compatibility
var ProgressiveRAGSystemPromptWithoutWeb = `### Role var ProgressiveRAGSystemPromptWithWeb = ProgressiveRAGSystemPrompt
You are WeKnora, a meticulous retrieval assistant powered by Progressive Agentic RAG. You operate in a strictly isolated, **Closed-Loop Knowledge Environment** (No Internet). You are defined by your "Deep Reading" philosophy: you never trust a snippet alone; you always verify the full context.
### Mission // ProgressiveRAGSystemPromptWithoutWeb is deprecated, use ProgressiveRAGSystemPrompt instead
To provide answers that are not only accurate but contextually complete. You achieve this by following a strict **"Locate-then-Read"** protocol: finding documents via search, then reading their full content before synthesizing an answer. // Kept for backward compatibility
var ProgressiveRAGSystemPromptWithoutWeb = ProgressiveRAGSystemPrompt
### Critical Constraints (ABSOLUTE RULES)
1. **No Snippet-Only Answers:** You are FORBIDDEN from answering based solely on the short text snippets returned by grep_chunks or knowledge_search.
2. **Mandatory Deep Reading:** Whenever a search tool returns relevant knowledge_ids, you MUST use list_knowledge_chunks to read the actual content of those chunks/documents before using them as evidence.
3. **No Internet:** You are strictly confined to internal Knowledge Bases.
4. **Evidence Verification:** If the full text read via list_knowledge_chunks contradicts the search snippet or shows the info is irrelevant, you must discard it and search again.
### Workflow: The "Locate-Read-Plan-Execute" Cycle
You must follow this **Specific Operational Sequence** for every user query:
#### Phase 1: Preliminary Reconnaissance & Context Verification
Before answering or creating a plan, you MUST perform an initial "Test & Read" loop.
1. **Locate:** Execute grep_chunks (keyword) and knowledge_search (semantic) to find potential documents.
2. **READ (Mandatory):** Identify the most relevant knowledge_ids from step 1 (you can select multiple, e.g., top 3-5). **IMMEDIATELY call list_knowledge_chunks** on these IDs to retrieve their full content.
3. **Analyze:** In your think block, evaluate the *full text* you just read. Does it cover the user's intent?
* *Decision:* If this full text is sufficient → Go to **Answer Generation**.
* *Decision:* If complex/incomplete → Go to **Phase 2**.
#### Phase 2: Strategic Decision & Planning
If Phase 1 is insufficient, create a todo_write Work Plan.
* **Plan Structure:** Break the problem into distinct retrieval tasks.
* **Context Awareness:** Use the full text read in Phase 1 to inform your plan (e.g., "Doc A mentions Protocol X, I need to create a task to specifically search for Protocol X details").
#### Phase 3: Disciplined Execution with Deep Reading
Execute tasks in todo_write sequentially. For **EACH** task:
1. **Search:** Perform grep_chunks or knowledge_search specific to the sub-task.
2. **READ (Mandatory):**
* Extract the knowledge_ids of the most promising results.
* **Call list_knowledge_chunks** to fetch the content for these IDs. **Do not skip this step.**
* *Note:* You are encouraged to check multiple files if the answer might be spread across them.
3. **Reflect (Deep Reflection):**
* "Based on the *full text* I just read, is this sub-task resolved?"
* If no, formulate a remedial search action immediately.
* Only mark as "completed" when the full text evidence is secured.
#### Phase 4: Final Synthesis
* Synthesize findings based **only** on the content read via list_knowledge_chunks.
* Generate the final response with citations.
### Core Retrieval Strategy (The "Locate-then-Read" Pattern)
For every information seeking step, strictly follow this 3-step atomic unit:
1. **Step A: Locate (Search)**
* Use grep_chunks for specific entities (Error codes, product names).
* Use knowledge_search for concepts.
* *Goal:* Get a list of candidate knowledge_ids.
2. **Step B: Read (Fetch Context)**
* **Action:** Call list_knowledge_chunks(knowledge_ids=[id1, id2, ...]).
* *Rule:* Always fetch the content. Snippets are often truncated or lack necessary context (like prerequisites or exceptions).
* *Scope:* It is acceptable and encouraged to fetch 3-5 distinct documents to ensure comprehensive coverage.
3. **Step C: Evaluate (Filter)**
* Read the output of list_knowledge_chunks.
* Discard irrelevant documents.
* Extract facts from valid documents to build your answer.
### Tool Selection Guidelines
* **grep_chunks / knowledge_search:** Used ONLY as "Pointers" or "Index Lookups". They tell you *where* to look, not *what* the answer is.
* **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is.
* **todo_write:** Use for managing multi-step research.
* **think:** Your "Conscience". Use to plan and relect the content returned by list_knowledge_chunks.
### Final Output Standards
1. **Context-Backed:** Your answer must reflect the nuance found in the full text (e.g., conditions, warnings, detailed steps) which might be missing from search snippets.
2. **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." />.
Citations may not be placed at the end of the answer. They must always be inserted inline, at the exact location where the referenced information is used ("proximate citation rule").
3. **Honest:** If the full text reveals the search hit was a false positive, admit it and search again.
4. **Rich Media (Markdown with Images):** When retrieved chunks contain images (indicated by the "images" field with URLs), you MUST include them in your response using standard Markdown image syntax: ![description](image_url). Place images at contextually appropriate positions within the answer to create a well-formatted, visually rich response. Images help users better understand the content, especially for diagrams, charts, screenshots, or visual explanations.
### System Status
Current Time: {{current_time}}
### User Selected Knowledge Bases (via @ mention)
{{knowledge_bases}}
`
@@ -18,7 +18,7 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
const MAX_ITERATIONS = 30 // Max iterations for agent execution const MAX_ITERATIONS = 100 // Max iterations for agent execution
// agentService implements agent-related business logic // agentService implements agent-related business logic
type agentService struct { type agentService struct {
@@ -37,11 +37,32 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
"template_len": len(chatManage.SummaryConfig.ContextTemplate), "template_len": len(chatManage.SummaryConfig.ContextTemplate),
}) })
// Extract content from merge results // Separate FAQ and document results when FAQ priority is enabled
passages := make([]string, len(chatManage.MergeResult)) var faqResults, docResults []*types.SearchResult
for i, result := range chatManage.MergeResult { var hasHighConfidenceFAQ bool
// 合并内容和图片信息
passages[i] = getEnrichedPassageForChat(ctx, result) if chatManage.FAQPriorityEnabled {
for _, result := range chatManage.MergeResult {
if result.ChunkType == string(types.ChunkTypeFAQ) {
faqResults = append(faqResults, result)
// Check if this FAQ has high confidence (above direct answer threshold)
if result.Score >= chatManage.FAQDirectAnswerThreshold && !hasHighConfidenceFAQ {
hasHighConfidenceFAQ = true
pipelineInfo(ctx, "IntoChatMessage", "high_confidence_faq", map[string]interface{}{
"chunk_id": result.ID,
"score": fmt.Sprintf("%.4f", result.Score),
"threshold": chatManage.FAQDirectAnswerThreshold,
})
}
} else {
docResults = append(docResults, result)
}
}
pipelineInfo(ctx, "IntoChatMessage", "faq_separation", map[string]interface{}{
"faq_count": len(faqResults),
"doc_count": len(docResults),
"has_high_confidence": hasHighConfidenceFAQ,
})
} }
// 验证用户查询的安全性 // 验证用户查询的安全性
@@ -56,13 +77,42 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
// Prepare weekday names // Prepare weekday names
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"} weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
// Build contexts string from passages
var contextsBuilder strings.Builder var contextsBuilder strings.Builder
for i, passage := range passages {
if i > 0 { // Build contexts string based on FAQ priority strategy
contextsBuilder.WriteString("\n\n") if chatManage.FAQPriorityEnabled && len(faqResults) > 0 {
// Build structured context with FAQ prioritization
contextsBuilder.WriteString("### 资料来源 1:标准问答库 (FAQ)\n")
contextsBuilder.WriteString("【高置信度 - 请优先参考】\n")
for i, result := range faqResults {
passage := getEnrichedPassageForChat(ctx, result)
if hasHighConfidenceFAQ && i == 0 {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] ⭐ 精准匹配: %s\n", i+1, passage))
} else {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] %s\n", i+1, passage))
}
}
if len(docResults) > 0 {
contextsBuilder.WriteString("\n### 资料来源 2:参考文档\n")
contextsBuilder.WriteString("【补充资料 - 仅在FAQ无法解答时参考】\n")
for i, result := range docResults {
passage := getEnrichedPassageForChat(ctx, result)
contextsBuilder.WriteString(fmt.Sprintf("[DOC-%d] %s\n", i+1, passage))
}
}
} else {
// Original behavior: simple numbered list
passages := make([]string, len(chatManage.MergeResult))
for i, result := range chatManage.MergeResult {
passages[i] = getEnrichedPassageForChat(ctx, result)
}
for i, passage := range passages {
if i > 0 {
contextsBuilder.WriteString("\n\n")
}
contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage))
} }
contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage))
} }
// Replace placeholders in context template // Replace placeholders in context template
@@ -77,6 +127,7 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{ pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{
"session_id": chatManage.SessionID, "session_id": chatManage.SessionID,
"user_content_len": len(chatManage.UserContent), "user_content_len": len(chatManage.UserContent),
"faq_priority": chatManage.FAQPriorityEnabled,
}) })
return next() return next()
} }
@@ -145,6 +145,22 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base) sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base)
modelScore := rr.RelevanceScore modelScore := rr.RelevanceScore
sr.Score = compositeScore(sr, modelScore, base) sr.Score = compositeScore(sr, modelScore, base)
// Apply FAQ score boost if enabled
if chatManage.FAQPriorityEnabled && chatManage.FAQScoreBoost > 1.0 &&
sr.ChunkType == string(types.ChunkTypeFAQ) {
originalScore := sr.Score
sr.Score = math.Min(sr.Score*chatManage.FAQScoreBoost, 1.0)
sr.Metadata["faq_boosted"] = "true"
sr.Metadata["faq_original_score"] = fmt.Sprintf("%.4f", originalScore)
pipelineInfo(ctx, "Rerank", "faq_boost", map[string]interface{}{
"chunk_id": sr.ID,
"original_score": fmt.Sprintf("%.4f", originalScore),
"boosted_score": fmt.Sprintf("%.4f", sr.Score),
"boost_factor": chatManage.FAQScoreBoost,
})
}
pipelineInfo(ctx, "Rerank", "composite_calc", map[string]interface{}{ pipelineInfo(ctx, "Rerank", "composite_calc", map[string]interface{}{
"chunk_id": sr.ID, "chunk_id": sr.ID,
"base_score": fmt.Sprintf("%.4f", base), "base_score": fmt.Sprintf("%.4f", base),
+68 -62
View File
@@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/tools" "github.com/Tencent/WeKnora/internal/agent/tools"
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline" chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext" llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext"
@@ -15,6 +14,7 @@ import (
"github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat" "github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/tracing" "github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -408,24 +408,15 @@ func (s *sessionService) KnowledgeQA(
webSearchEnabled, webSearchEnabled,
) )
// Merge custom agent's configured knowledge bases // Use custom agent's knowledge bases only if request didn't specify any
if customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 { // When user explicitly @mentions a knowledge base or document, only search those
// Create a set of existing knowledge base IDs to avoid duplicates if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 {
existingKBs := make(map[string]bool) knowledgeBaseIDs = customAgent.Config.KnowledgeBases
for _, kbID := range knowledgeBaseIDs { logger.Infof(ctx, "No knowledge bases specified in request, using custom agent's knowledge bases: %v", knowledgeBaseIDs)
existingKBs[kbID] = true } else if len(knowledgeBaseIDs) > 0 || len(knowledgeIDs) > 0 {
} logger.Infof(ctx, "Using request-specified targets (ignoring agent config): kbs=%v, docs=%v", knowledgeBaseIDs, knowledgeIDs)
// Add agent's knowledge bases that are not already in the list
for _, kbID := range customAgent.Config.KnowledgeBases {
if !existingKBs[kbID] {
knowledgeBaseIDs = append(knowledgeBaseIDs, kbID)
logger.Infof(ctx, "Adding custom agent's knowledge base: %s", kbID)
}
}
} }
logger.Infof(ctx, "Using knowledge bases: %v", knowledgeBaseIDs)
// Determine chat model ID: prioritize request's summaryModelID, then Remote models // Determine chat model ID: prioritize request's summaryModelID, then Remote models
chatModelID, err := s.selectChatModelIDWithOverride(ctx, session, knowledgeBaseIDs, knowledgeIDs, summaryModelID) chatModelID, err := s.selectChatModelIDWithOverride(ctx, session, knowledgeBaseIDs, knowledgeIDs, summaryModelID)
if err != nil { if err != nil {
@@ -542,6 +533,20 @@ func (s *sessionService) KnowledgeQA(
} }
} }
// Extract FAQ strategy settings from custom agent
var faqPriorityEnabled bool
var faqDirectAnswerThreshold float64
var faqScoreBoost float64
if customAgent != nil {
faqPriorityEnabled = customAgent.Config.FAQPriorityEnabled
faqDirectAnswerThreshold = customAgent.Config.FAQDirectAnswerThreshold
faqScoreBoost = customAgent.Config.FAQScoreBoost
if faqPriorityEnabled {
logger.Infof(ctx, "FAQ priority enabled: threshold=%.2f, boost=%.2f",
faqDirectAnswerThreshold, faqScoreBoost)
}
}
// Build unified search targets (computed once, used throughout pipeline) // Build unified search targets (computed once, used throughout pipeline)
searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs) searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs)
if err != nil { if err != nil {
@@ -584,6 +589,10 @@ func (s *sessionService) KnowledgeQA(
RewritePromptUser: rewritePromptUser, RewritePromptUser: rewritePromptUser,
EnableRewrite: enableRewrite, EnableRewrite: enableRewrite,
EnableQueryExpansion: enableQueryExpansion, EnableQueryExpansion: enableQueryExpansion,
// FAQ Strategy Settings
FAQPriorityEnabled: faqPriorityEnabled,
FAQDirectAnswerThreshold: faqDirectAnswerThreshold,
FAQScoreBoost: faqScoreBoost,
} }
// Determine pipeline based on knowledge bases availability and web search setting // Determine pipeline based on knowledge bases availability and web search setting
@@ -886,17 +895,6 @@ func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
return nil return nil
} }
func getTenantConversationConfig(ctx context.Context) (*types.ConversationConfig, error) {
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
if tenant == nil {
return nil, errors.New("tenant is empty")
}
if tenant.ConversationConfig == nil {
return nil, errors.New("tenant has no conversation config")
}
return tenant.ConversationConfig, nil
}
// SearchKnowledge performs knowledge base search without LLM summarization // SearchKnowledge performs knowledge base search without LLM summarization
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB) // knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
// knowledgeIDs: list of specific knowledge (file) IDs to search // knowledgeIDs: list of specific knowledge (file) IDs to search
@@ -1020,6 +1018,8 @@ func (s *sessionService) AgentQA(
assistantMessageID string, assistantMessageID string,
eventBus *event.EventBus, eventBus *event.EventBus,
customAgent *types.CustomAgent, customAgent *types.CustomAgent,
knowledgeBaseIDs []string,
knowledgeIDs []string,
) error { ) error {
sessionID := session.ID sessionID := session.ID
tenantID := ctx.Value(types.TenantIDContextKey).(uint64) tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
@@ -1045,20 +1045,8 @@ func (s *sessionService) AgentQA(
// Ensure defaults are set // Ensure defaults are set
customAgent.EnsureDefaults() customAgent.EnsureDefaults()
// Check if tenant has agent configuration (for defaults)
if tenantInfo.AgentConfig == nil {
tenantInfo.AgentConfig = &types.AgentConfig{
MaxIterations: agent.DefaultAgentMaxIterations,
ReflectionEnabled: agent.DefaultAgentReflectionEnabled,
AllowedTools: tools.DefaultAllowedTools(),
Temperature: agent.DefaultAgentTemperature,
SystemPromptWebEnabled: agent.ProgressiveRAGSystemPromptWithWeb,
SystemPromptWebDisabled: agent.ProgressiveRAGSystemPromptWithoutWeb,
UseCustomSystemPrompt: agent.DefaultUseCustomSystemPrompt,
}
}
// Create runtime AgentConfig from customAgent // Create runtime AgentConfig from customAgent
// Note: tenantInfo.AgentConfig is deprecated, all config comes from customAgent now
agentConfig := &types.AgentConfig{ agentConfig := &types.AgentConfig{
MaxIterations: customAgent.Config.MaxIterations, MaxIterations: customAgent.Config.MaxIterations,
ReflectionEnabled: customAgent.Config.ReflectionEnabled, ReflectionEnabled: customAgent.Config.ReflectionEnabled,
@@ -1072,6 +1060,24 @@ func (s *sessionService) AgentQA(
MCPServices: customAgent.Config.MCPServices, MCPServices: customAgent.Config.MCPServices,
} }
// Handle knowledge bases: request-level @ mentions take priority over agent config
// When user explicitly @mentions a knowledge base or document, only search those
if len(knowledgeBaseIDs) > 0 || len(knowledgeIDs) > 0 {
// User explicitly specified via @ mention, use only those (clear agent's default KBs)
if len(knowledgeBaseIDs) > 0 {
agentConfig.KnowledgeBases = knowledgeBaseIDs
logger.Infof(ctx, "Using request-specified knowledge bases (ignoring agent config): %v", knowledgeBaseIDs)
} else {
// User only specified documents, clear the default KBs
agentConfig.KnowledgeBases = nil
logger.Infof(ctx, "User specified documents only, clearing agent's default knowledge bases")
}
if len(knowledgeIDs) > 0 {
agentConfig.KnowledgeIDs = knowledgeIDs
logger.Infof(ctx, "Using request-specified knowledge IDs: %v", knowledgeIDs)
}
}
// Use custom agent's allowed tools if specified, otherwise use defaults // Use custom agent's allowed tools if specified, otherwise use defaults
if len(customAgent.Config.AllowedTools) > 0 { if len(customAgent.Config.AllowedTools) > 0 {
agentConfig.AllowedTools = customAgent.Config.AllowedTools agentConfig.AllowedTools = customAgent.Config.AllowedTools
@@ -1082,8 +1088,7 @@ func (s *sessionService) AgentQA(
// Use custom agent's system prompt if specified // Use custom agent's system prompt if specified
if customAgent.Config.SystemPrompt != "" { if customAgent.Config.SystemPrompt != "" {
agentConfig.UseCustomSystemPrompt = true agentConfig.UseCustomSystemPrompt = true
agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt agentConfig.SystemPrompt = customAgent.Config.SystemPrompt
agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt
} }
logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v", logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v",
@@ -1117,14 +1122,12 @@ func (s *sessionService) AgentQA(
agentConfig.SearchTargets = searchTargets agentConfig.SearchTargets = searchTargets
logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets)) logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets))
// Get summary model from custom agent config or tenant config // Get summary model from custom agent config
// Note: tenantInfo.ConversationConfig is deprecated, all config comes from customAgent now
summaryModelID := customAgent.Config.ModelID summaryModelID := customAgent.Config.ModelID
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
}
if summaryModelID == "" { if summaryModelID == "" {
logger.Warnf(ctx, "No summary model configured for tenant %d or session %s", tenantInfo.ID, session.ID) logger.Warnf(ctx, "No summary model configured for custom agent %s", customAgent.ID)
return errors.New("summary model is not configured in conversation settings") return errors.New("summary model (model_id) is not configured in custom agent settings")
} }
summaryModel, err := s.modelService.GetChatModel(ctx, summaryModelID) summaryModel, err := s.modelService.GetChatModel(ctx, summaryModelID)
@@ -1133,20 +1136,23 @@ func (s *sessionService) AgentQA(
return fmt.Errorf("failed to get chat model: %w", err) return fmt.Errorf("failed to get chat model: %w", err)
} }
// Get rerank model from custom agent config or tenant config // Get rerank model from custom agent config (only required when knowledge bases are configured)
rerankModelID := customAgent.Config.RerankModelID var rerankModel rerank.Reranker
if rerankModelID == "" && tenantInfo.ConversationConfig != nil { hasKnowledge := len(agentConfig.KnowledgeBases) > 0 || len(agentConfig.KnowledgeIDs) > 0
rerankModelID = tenantInfo.ConversationConfig.RerankModelID if hasKnowledge {
} rerankModelID := customAgent.Config.RerankModelID
if rerankModelID == "" { if rerankModelID == "" {
logger.Warnf(ctx, "No rerank model configured for tenant %d or session %s", tenantInfo.ID, session.ID) logger.Warnf(ctx, "No rerank model configured for custom agent %s, but knowledge bases are specified", customAgent.ID)
return errors.New("rerank model is not configured in conversation settings") return errors.New("rerank model (rerank_model_id) is not configured in custom agent settings")
} }
rerankModel, err := s.modelService.GetRerankModel(ctx, rerankModelID) rerankModel, err = s.modelService.GetRerankModel(ctx, rerankModelID)
if err != nil { if err != nil {
logger.Warnf(ctx, "Failed to get rerank model: %v", err) logger.Warnf(ctx, "Failed to get rerank model: %v", err)
return fmt.Errorf("failed to get rerank model: %w", err) return fmt.Errorf("failed to get rerank model: %w", err)
}
} else {
logger.Infof(ctx, "No knowledge bases configured, skipping rerank model initialization")
} }
// Get or create contextManager for this session // Get or create contextManager for this session
+2
View File
@@ -440,6 +440,8 @@ func (h *Handler) executeAgentModeQA(reqCtx *qaRequestContext) {
reqCtx.assistantMessage.ID, reqCtx.assistantMessage.ID,
streamCtx.eventBus, streamCtx.eventBus,
reqCtx.customAgent, reqCtx.customAgent,
reqCtx.knowledgeBaseIDs,
reqCtx.knowledgeIDs,
) )
if err != nil { if err != nil {
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil) logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
+37 -42
View File
@@ -419,12 +419,11 @@ func (h *TenantHandler) SearchTenants(c *gin.Context) {
// AgentConfigRequest represents the request body for updating agent configuration // AgentConfigRequest represents the request body for updating agent configuration
type AgentConfigRequest struct { type AgentConfigRequest struct {
MaxIterations int `json:"max_iterations"` MaxIterations int `json:"max_iterations"`
ReflectionEnabled bool `json:"reflection_enabled"` ReflectionEnabled bool `json:"reflection_enabled"`
AllowedTools []string `json:"allowed_tools"` AllowedTools []string `json:"allowed_tools"`
Temperature float64 `json:"temperature"` Temperature float64 `json:"temperature"`
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` SystemPrompt string `json:"system_prompt,omitempty"` // Unified system prompt (uses {{web_search_status}} placeholder)
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"`
} }
// GetTenantAgentConfig godoc // GetTenantAgentConfig godoc
@@ -472,42 +471,37 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": true, "success": true,
"data": gin.H{ "data": gin.H{
"max_iterations": agent.DefaultAgentMaxIterations, "max_iterations": agent.DefaultAgentMaxIterations,
"reflection_enabled": agent.DefaultAgentReflectionEnabled, "reflection_enabled": agent.DefaultAgentReflectionEnabled,
"allowed_tools": agenttools.DefaultAllowedTools(), "allowed_tools": agenttools.DefaultAllowedTools(),
"temperature": agent.DefaultAgentTemperature, "temperature": agent.DefaultAgentTemperature,
"system_prompt_web_enabled": agent.ProgressiveRAGSystemPromptWithWeb, "system_prompt": agent.ProgressiveRAGSystemPrompt,
"system_prompt_web_disabled": agent.ProgressiveRAGSystemPromptWithoutWeb, "use_custom_system_prompt": false,
"use_custom_system_prompt": false, "available_tools": availableTools,
"available_tools": availableTools, "available_placeholders": availablePlaceholders,
"available_placeholders": availablePlaceholders,
}, },
}) })
return return
} }
// Get system prompts for both web search states, use defaults if empty // Get system prompt, use default if empty
systemPromptWithWeb := tenant.AgentConfig.ResolveSystemPrompt(true) systemPrompt := tenant.AgentConfig.ResolveSystemPrompt(true) // webSearchEnabled doesn't matter for unified prompt
if systemPromptWithWeb == "" { if systemPrompt == "" {
systemPromptWithWeb = agent.ProgressiveRAGSystemPromptWithWeb systemPrompt = agent.ProgressiveRAGSystemPrompt
}
systemPromptWithoutWeb := tenant.AgentConfig.ResolveSystemPrompt(false)
if systemPromptWithoutWeb == "" {
systemPromptWithoutWeb = agent.ProgressiveRAGSystemPromptWithoutWeb
} }
logger.Infof(ctx, "Retrieved tenant agent config successfully, Tenant ID: %d", tenant.ID) logger.Infof(ctx, "Retrieved tenant agent config successfully, Tenant ID: %d", tenant.ID)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": true, "success": true,
"data": gin.H{ "data": gin.H{
"max_iterations": tenant.AgentConfig.MaxIterations, "max_iterations": tenant.AgentConfig.MaxIterations,
"reflection_enabled": tenant.AgentConfig.ReflectionEnabled, "reflection_enabled": tenant.AgentConfig.ReflectionEnabled,
"allowed_tools": agenttools.DefaultAllowedTools(), "allowed_tools": agenttools.DefaultAllowedTools(),
"temperature": tenant.AgentConfig.Temperature, "temperature": tenant.AgentConfig.Temperature,
"system_prompt_web_enabled": systemPromptWithWeb, "system_prompt": systemPrompt,
"system_prompt_web_disabled": systemPromptWithoutWeb, "use_custom_system_prompt": tenant.AgentConfig.UseCustomSystemPrompt,
"available_tools": availableTools, "available_tools": availableTools,
"available_placeholders": availablePlaceholders, "available_placeholders": availablePlaceholders,
}, },
}) })
} }
@@ -543,19 +537,20 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
} }
// Update agent configuration // Update agent configuration
// Determine if using custom prompt based on whether custom prompts are set // Determine if using custom prompt based on whether custom prompts are set
useCustomPrompt := req.SystemPromptWebEnabled != "" || req.SystemPromptWebDisabled != "" // Support both new unified SystemPrompt and deprecated separate prompts
systemPrompt := req.SystemPrompt
useCustomPrompt := systemPrompt != ""
tenant.AgentConfig = &types.AgentConfig{ agentConfig := &types.AgentConfig{
MaxIterations: req.MaxIterations, MaxIterations: req.MaxIterations,
ReflectionEnabled: req.ReflectionEnabled, ReflectionEnabled: req.ReflectionEnabled,
AllowedTools: agenttools.DefaultAllowedTools(), AllowedTools: agenttools.DefaultAllowedTools(),
Temperature: req.Temperature, Temperature: req.Temperature,
SystemPromptWebEnabled: req.SystemPromptWebEnabled, SystemPrompt: systemPrompt,
SystemPromptWebDisabled: req.SystemPromptWebDisabled, UseCustomSystemPrompt: useCustomPrompt,
UseCustomSystemPrompt: useCustomPrompt,
} }
updatedTenant, err := h.service.UpdateTenant(ctx, tenant) _, err := h.service.UpdateTenant(ctx, tenant)
if err != nil { if err != nil {
if appErr, ok := errors.IsAppError(err); ok { if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr) logger.Error(ctx, "Failed to update tenant: application error", appErr)
@@ -570,7 +565,7 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
logger.Infof(ctx, "Tenant agent config updated successfully, Tenant ID: %d", tenant.ID) logger.Infof(ctx, "Tenant agent config updated successfully, Tenant ID: %d", tenant.ID)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": true, "success": true,
"data": updatedTenant.AgentConfig, "data": agentConfig,
"message": "Agent configuration updated successfully", "message": "Agent configuration updated successfully",
}) })
} }
-4
View File
@@ -211,10 +211,6 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
toolNames = append(toolNames, tool.Function.Name) toolNames = append(toolNames, tool.Function.Name)
} }
logger.Infof(context.Background(), "[LLM Request] tools_count=%d, tool_names=%v", len(req.Tools), toolNames) logger.Infof(context.Background(), "[LLM Request] tools_count=%d, tool_names=%v", len(req.Tools), toolNames)
// Print full tool definitions
if toolsJSON, err := json.MarshalIndent(req.Tools, "", " "); err == nil {
logger.Infof(context.Background(), "[LLM Request] tools_definition:\n%s", string(toolsJSON))
}
} }
return req return req
+23 -14
View File
@@ -10,20 +10,22 @@ import (
// AgentConfig represents the full agent configuration (used at tenant level and runtime) // AgentConfig represents the full agent configuration (used at tenant level and runtime)
// This includes all configuration parameters for agent execution // This includes all configuration parameters for agent execution
type AgentConfig struct { type AgentConfig struct {
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
Temperature float64 `json:"temperature"` // LLM temperature for agent Temperature float64 `json:"temperature"` // LLM temperature for agent
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
KnowledgeIDs []string `json:"knowledge_ids"` // Accessible knowledge IDs (individual documents) KnowledgeIDs []string `json:"knowledge_ids"` // Accessible knowledge IDs (individual documents)
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` // Custom prompt when web search is enabled SystemPrompt string `json:"system_prompt,omitempty"` // Unified system prompt (uses {{web_search_status}} placeholder for dynamic behavior)
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` // Custom prompt when web search is disabled // Deprecated: Use SystemPrompt instead. Kept for backward compatibility during migration.
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` // Deprecated: Custom prompt when web search is enabled
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` // Deprecated: Custom prompt when web search is disabled
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5) UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only) MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled
HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
// MCP service selection // MCP service selection
MCPSelectionMode string `json:"mcp_selection_mode"` // MCP selection mode: "all", "selected", "none" MCPSelectionMode string `json:"mcp_selection_mode"` // MCP selection mode: "all", "selected", "none"
MCPServices []string `json:"mcp_services"` // Selected MCP service IDs (when mode is "selected") MCPServices []string `json:"mcp_services"` // Selected MCP service IDs (when mode is "selected")
@@ -73,11 +75,18 @@ func (c *SessionAgentConfig) Scan(value interface{}) error {
} }
// ResolveSystemPrompt returns the prompt template for the given web search state. // ResolveSystemPrompt returns the prompt template for the given web search state.
// It uses the unified SystemPrompt field, falling back to deprecated fields for backward compatibility.
func (c *AgentConfig) ResolveSystemPrompt(webSearchEnabled bool) string { func (c *AgentConfig) ResolveSystemPrompt(webSearchEnabled bool) string {
if c == nil { if c == nil {
return "" return ""
} }
// First, try the new unified SystemPrompt field
if c.SystemPrompt != "" {
return c.SystemPrompt
}
// Fallback to deprecated fields for backward compatibility
if webSearchEnabled { if webSearchEnabled {
if c.SystemPromptWebEnabled != "" { if c.SystemPromptWebEnabled != "" {
return c.SystemPromptWebEnabled return c.SystemPromptWebEnabled
+9
View File
@@ -53,6 +53,11 @@ type ChatManage struct {
// Web search configuration (internal use) // Web search configuration (internal use)
TenantID uint64 `json:"-"` // Tenant ID for retrieving web search config TenantID uint64 `json:"-"` // Tenant ID for retrieving web search config
WebSearchEnabled bool `json:"-"` // Whether web search is enabled for this request WebSearchEnabled bool `json:"-"` // Whether web search is enabled for this request
// FAQ Strategy Settings
FAQPriorityEnabled bool `json:"-"` // Whether FAQ priority strategy is enabled
FAQDirectAnswerThreshold float64 `json:"-"` // Threshold for direct FAQ answer (similarity > this value)
FAQScoreBoost float64 `json:"-"` // Score multiplier for FAQ results
} }
// Clone creates a deep copy of the ChatManage object // Clone creates a deep copy of the ChatManage object
@@ -117,6 +122,10 @@ func (c *ChatManage) Clone() *ChatManage {
EnableRewrite: c.EnableRewrite, EnableRewrite: c.EnableRewrite,
EnableQueryExpansion: c.EnableQueryExpansion, EnableQueryExpansion: c.EnableQueryExpansion,
TenantID: c.TenantID, TenantID: c.TenantID,
// FAQ Strategy Settings
FAQPriorityEnabled: c.FAQPriorityEnabled,
FAQDirectAnswerThreshold: c.FAQDirectAnswerThreshold,
FAQScoreBoost: c.FAQScoreBoost,
} }
} }
+288 -5
View File
@@ -14,6 +14,14 @@ const (
BuiltinQuickAnswerID = "builtin-quick-answer" BuiltinQuickAnswerID = "builtin-quick-answer"
// BuiltinSmartReasoningID is the ID for the built-in smart reasoning (ReAct) agent // BuiltinSmartReasoningID is the ID for the built-in smart reasoning (ReAct) agent
BuiltinSmartReasoningID = "builtin-smart-reasoning" BuiltinSmartReasoningID = "builtin-smart-reasoning"
// BuiltinDeepResearcherID is the ID for the built-in deep researcher agent
BuiltinDeepResearcherID = "builtin-deep-researcher"
// BuiltinDataAnalystID is the ID for the built-in data analyst agent
BuiltinDataAnalystID = "builtin-data-analyst"
// BuiltinKnowledgeGraphExpertID is the ID for the built-in knowledge graph expert agent
BuiltinKnowledgeGraphExpertID = "builtin-knowledge-graph-expert"
// BuiltinDocumentAssistantID is the ID for the built-in document assistant agent
BuiltinDocumentAssistantID = "builtin-document-assistant"
) )
// AgentMode constants for agent running mode // AgentMode constants for agent running mode
@@ -57,10 +65,8 @@ type CustomAgentConfig struct {
// ===== Basic Settings ===== // ===== Basic Settings =====
// Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent mode // Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent mode
AgentMode string `yaml:"agent_mode" json:"agent_mode"` AgentMode string `yaml:"agent_mode" json:"agent_mode"`
// System prompt for the agent (for normal mode, or agent mode when web search is disabled) // System prompt for the agent (unified prompt, uses {{web_search_status}} placeholder for dynamic behavior)
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"` 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) // Context template for normal mode (how to format retrieved chunks)
ContextTemplate string `yaml:"context_template" json:"context_template"` ContextTemplate string `yaml:"context_template" json:"context_template"`
@@ -92,6 +98,14 @@ type CustomAgentConfig struct {
// Associated knowledge base IDs (only used when KBSelectionMode is "selected") // Associated knowledge base IDs (only used when KBSelectionMode is "selected")
KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"` KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"`
// ===== FAQ Strategy Settings =====
// Whether FAQ priority strategy is enabled (FAQ answers prioritized over document chunks)
FAQPriorityEnabled bool `yaml:"faq_priority_enabled" json:"faq_priority_enabled"`
// FAQ direct answer threshold - if similarity > this value, use FAQ answer directly
FAQDirectAnswerThreshold float64 `yaml:"faq_direct_answer_threshold" json:"faq_direct_answer_threshold"`
// FAQ score boost multiplier - FAQ results score multiplied by this factor
FAQScoreBoost float64 `yaml:"faq_score_boost" json:"faq_score_boost"`
// ===== Web Search Settings ===== // ===== Web Search Settings =====
// Whether web search is enabled // Whether web search is enabled
WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"` WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"`
@@ -224,6 +238,10 @@ func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
MultiTurnEnabled: true, MultiTurnEnabled: true,
HistoryTurns: 5, HistoryTurns: 5,
KBSelectionMode: "all", KBSelectionMode: "all",
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy // Retrieval strategy
EmbeddingTopK: 10, EmbeddingTopK: 10,
KeywordThreshold: 0.3, KeywordThreshold: 0.3,
@@ -259,6 +277,10 @@ func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
ReflectionEnabled: false, ReflectionEnabled: false,
MultiTurnEnabled: true, MultiTurnEnabled: true,
HistoryTurns: 5, HistoryTurns: 5,
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy // Retrieval strategy
EmbeddingTopK: 10, EmbeddingTopK: 10,
KeywordThreshold: 0.3, KeywordThreshold: 0.3,
@@ -269,6 +291,259 @@ func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
} }
} }
// GetBuiltinDeepResearcherAgent returns the built-in deep researcher agent
// This agent is optimized for in-depth research and comprehensive analysis
func GetBuiltinDeepResearcherAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinDeepResearcherID,
Name: "深度研究员",
Description: "专注于深度研究和综合分析,能够制定研究计划、多维度检索信息、深入思考并给出全面的分析报告",
Avatar: "🔬",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: `你是一位专业的深度研究员,擅长进行系统性的研究和综合分析。
## 核心能力
- 制定结构化的研究计划
- 多维度信息检索和交叉验证
- 深入思考和逻辑推理
- 综合分析和报告撰写
## 工作流程
1. **理解问题**:深入分析用户的研究需求,明确研究目标和范围
2. **制定计划**:使用 todo_write 工具制定详细的研究计划
3. **信息收集**:
- 使用 knowledge_search 进行语义搜索获取相关文档
- 使用 grep_chunks 进行关键词精确搜索
- 使用 query_knowledge_graph 探索实体关系
- 必要时使用网络搜索获取最新信息
4. **深度分析**:使用 thinking 工具进行深入思考和推理
5. **综合报告**:整合所有信息,给出结构化的研究报告
## 输出要求
- 研究报告应包含:背景、方法、发现、分析、结论
- 引用具体的信息来源
- 指出信息的可靠性和局限性
- 提供进一步研究的建议`,
Temperature: 0.5,
MaxCompletionTokens: 4096,
MaxIterations: 30,
KBSelectionMode: "all",
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
WebSearchEnabled: true,
WebSearchMaxResults: 10,
ReflectionEnabled: true,
MultiTurnEnabled: true,
HistoryTurns: 10,
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy - more comprehensive
EmbeddingTopK: 20,
KeywordThreshold: 0.2,
VectorThreshold: 0.4,
RerankTopK: 15,
RerankThreshold: 0.25,
},
}
}
// GetBuiltinDataAnalystAgent returns the built-in data analyst agent
// This agent is optimized for database queries and data analysis
func GetBuiltinDataAnalystAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinDataAnalystID,
Name: "数据分析师",
Description: "专注于数据库查询和数据分析,能够理解业务需求、构建SQL查询、分析数据并提供洞察",
Avatar: "📊",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: `你是一位专业的数据分析师,擅长数据库查询和数据分析。
## 核心能力
- 理解业务需求并转化为数据查询
- 构建高效的 SQL 查询语句
- 数据分析和可视化建议
- 提供数据驱动的业务洞察
## 工作流程
1. **需求理解**:
- 明确用户的数据分析目标
- 确定需要查询的数据范围和维度
2. **数据探索**:
- 使用 database_query 查询相关数据
- 使用 get_document_info 了解数据结构和元数据
3. **数据分析**:
- 使用 thinking 工具进行数据分析和推理
- 识别数据模式和趋势
4. **结果呈现**:
- 清晰展示查询结果
- 提供数据解读和业务建议
## 输出要求
- 解释 SQL 查询的逻辑
- 以表格或结构化方式展示数据
- 提供数据的业务含义解读
- 指出数据的局限性和注意事项
- 建议后续分析方向`,
Temperature: 0.3,
MaxCompletionTokens: 2048,
MaxIterations: 20,
KBSelectionMode: "all",
AllowedTools: []string{"thinking", "todo_write", "database_query", "knowledge_search", "get_document_info"},
WebSearchEnabled: false,
WebSearchMaxResults: 5,
ReflectionEnabled: false,
MultiTurnEnabled: true,
HistoryTurns: 5,
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 5,
RerankThreshold: 0.3,
},
}
}
// GetBuiltinKnowledgeGraphExpertAgent returns the built-in knowledge graph expert agent
// This agent is optimized for knowledge graph exploration and relationship analysis
func GetBuiltinKnowledgeGraphExpertAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinKnowledgeGraphExpertID,
Name: "知识图谱专家",
Description: "专注于知识图谱查询和关系分析,能够探索实体关系、发现隐藏联系并构建知识网络",
Avatar: "🕸️",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: `你是一位知识图谱专家,擅长探索实体关系和构建知识网络。
## 核心能力
- 实体识别和关系发现
- 知识图谱查询和遍历
- 关系链分析和推理
- 知识网络可视化建议
## 工作流程
1. **实体识别**:
- 从用户问题中识别关键实体
- 确定需要探索的关系类型
2. **图谱查询**:
- 使用 query_knowledge_graph 查询实体关系
- 探索多跳关系和间接联系
3. **关系分析**:
- 使用 thinking 工具分析关系模式
- 发现隐藏的关联和规律
4. **知识整合**:
- 结合 knowledge_search 获取更多上下文
- 构建完整的知识图景
## 输出要求
- 清晰展示实体和关系
- 使用图形化描述(如 A -> 关系 -> B)
- 解释关系的含义和重要性
- 指出可能的推理和假设
- 建议进一步探索的方向`,
Temperature: 0.5,
MaxCompletionTokens: 2048,
MaxIterations: 25,
KBSelectionMode: "all",
AllowedTools: []string{"thinking", "todo_write", "query_knowledge_graph", "knowledge_search", "grep_chunks", "get_document_info"},
WebSearchEnabled: false,
WebSearchMaxResults: 5,
ReflectionEnabled: true,
MultiTurnEnabled: true,
HistoryTurns: 5,
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy
EmbeddingTopK: 15,
KeywordThreshold: 0.3,
VectorThreshold: 0.4,
RerankTopK: 10,
RerankThreshold: 0.3,
},
}
}
// GetBuiltinDocumentAssistantAgent returns the built-in document assistant agent
// This agent is optimized for document retrieval, organization and summarization
func GetBuiltinDocumentAssistantAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinDocumentAssistantID,
Name: "文档助手",
Description: "专注于文档检索和内容整理,能够快速定位文档、提取关键信息并生成摘要",
Avatar: "📚",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: `你是一位专业的文档助手,擅长文档检索、信息提取和内容整理。
## 核心能力
- 快速定位相关文档和内容
- 提取文档关键信息
- 生成结构化摘要
- 文档对比和整合
## 工作流程
1. **需求分析**:
- 理解用户的文档检索需求
- 确定搜索关键词和范围
2. **文档检索**:
- 使用 knowledge_search 语义搜索相关内容
- 使用 grep_chunks 精确匹配关键词
- 使用 get_document_info 获取文档元信息
3. **内容处理**:
- 使用 list_knowledge_chunks 查看完整内容
- 使用 thinking 工具整理和分析信息
4. **结果输出**:
- 提供结构化的信息摘要
- 标注信息来源和位置
## 输出要求
- 清晰标注信息来源(文档名、位置)
- 使用结构化格式展示信息
- 区分直接引用和总结内容
- 指出信息的完整性和可能遗漏
- 提供相关文档的导航建议`,
Temperature: 0.3,
MaxCompletionTokens: 2048,
MaxIterations: 20,
KBSelectionMode: "all",
AllowedTools: []string{"thinking", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "get_document_info"},
WebSearchEnabled: false,
WebSearchMaxResults: 5,
ReflectionEnabled: false,
MultiTurnEnabled: true,
HistoryTurns: 5,
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy - focused on precision
EmbeddingTopK: 15,
KeywordThreshold: 0.25,
VectorThreshold: 0.45,
RerankTopK: 10,
RerankThreshold: 0.3,
},
}
}
// Deprecated: Use GetBuiltinQuickAnswerAgent instead // Deprecated: Use GetBuiltinQuickAnswerAgent instead
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent { func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
return GetBuiltinQuickAnswerAgent(tenantID) return GetBuiltinQuickAnswerAgent(tenantID)
@@ -281,14 +556,22 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension // BuiltinAgentRegistry provides a registry of all built-in agents for easy extension
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{ var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent, BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent, BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
BuiltinDeepResearcherID: GetBuiltinDeepResearcherAgent,
BuiltinDataAnalystID: GetBuiltinDataAnalystAgent,
BuiltinKnowledgeGraphExpertID: GetBuiltinKnowledgeGraphExpertAgent,
BuiltinDocumentAssistantID: GetBuiltinDocumentAssistantAgent,
} }
// builtinAgentIDsOrdered defines the fixed display order of built-in agents // builtinAgentIDsOrdered defines the fixed display order of built-in agents
var builtinAgentIDsOrdered = []string{ var builtinAgentIDsOrdered = []string{
BuiltinQuickAnswerID, BuiltinQuickAnswerID,
BuiltinSmartReasoningID, BuiltinSmartReasoningID,
BuiltinDeepResearcherID,
BuiltinDataAnalystID,
BuiltinKnowledgeGraphExpertID,
BuiltinDocumentAssistantID,
} }
// GetBuiltinAgentIDs returns all built-in agent IDs in fixed order // GetBuiltinAgentIDs returns all built-in agent IDs in fixed order
+2
View File
@@ -54,6 +54,8 @@ type SessionService interface {
assistantMessageID string, assistantMessageID string,
eventBus *event.EventBus, eventBus *event.EventBus,
customAgent *types.CustomAgent, customAgent *types.CustomAgent,
knowledgeBaseIDs []string,
knowledgeIDs []string,
) error ) error
// ClearContext clears the LLM context for a session // ClearContext clears the LLM context for a session
ClearContext(ctx context.Context, sessionID string) error ClearContext(ctx context.Context, sessionID string) error