refactor: 调整智能体配置,增强智能体选择与状态管理

This commit is contained in:
wizardchen
2025-12-26 21:31:02 +08:00
parent abfe87eaed
commit 0ca947981a
36 changed files with 2421 additions and 916 deletions
+8 -13
View File
@@ -23,7 +23,7 @@ conversation:
- 使用礼貌、专业的语气 - 使用礼貌、专业的语气
## 用户的问题是: ## 用户的问题是:
{{.Query}} {{query}}
enable_rewrite: true enable_rewrite: true
enable_query_expansion: true enable_query_expansion: true
enable_rerank: true enable_rerank: true
@@ -82,15 +82,10 @@ conversation:
改写后: 国外手机号是否可以注册微信账号 改写后: 国外手机号是否可以注册微信账号
rewrite_prompt_user: | rewrite_prompt_user: |
## 历史对话背景 ## 历史对话背景
{{range .Conversation}} {{conversation}}
------BEGIN------
用户的问题是:{{.Query}}
助手的回答是:{{.Answer}}
------END------
{{end}}
## 需要改写的用户问题 ## 需要改写的用户问题
{{.Query}} {{query}}
## 改写后的问题 ## 改写后的问题
keywords_extraction_prompt: | keywords_extraction_prompt: |
@@ -134,7 +129,7 @@ conversation:
Output: iPhone, 连接WiFi, 使用iPhone连接WiFi Output: iPhone, 连接WiFi, 使用iPhone连接WiFi
# Real Data # Real Data
USER: {{.Query}} USER: {{query}}
keywords_extraction_prompt_user: | keywords_extraction_prompt_user: |
Output: Output:
@@ -483,11 +478,11 @@ conversation:
generate_questions_prompt: | generate_questions_prompt: |
你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。 你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
{{.Context}} {{context}}
## 主要内容(请基于此内容生成问题) ## 主要内容(请基于此内容生成问题)
文档名称:{{.DocName}} 文档名称:{{doc_name}}
文档内容: 文档内容:
{{.Content}} {{content}}
## 核心要求 ## 核心要求
- 生成的问题必须与【主要内容】直接相关 - 生成的问题必须与【主要内容】直接相关
@@ -496,7 +491,7 @@ conversation:
- 问题应该是用户在实际场景中可能会提出的自然问题 - 问题应该是用户在实际场景中可能会提出的自然问题
- 问题应该多样化,覆盖内容的不同方面 - 问题应该多样化,覆盖内容的不同方面
- 每个问题应该简洁明了,长度控制在30字以内 - 每个问题应该简洁明了,长度控制在30字以内
- 生成的问题数量为 {{.QuestionCount}} 个 - 生成的问题数量为 {{question_count}} 个
## 问题类型建议 ## 问题类型建议
- 定义类:什么是...?...是什么? - 定义类:什么是...?...是什么?
+1 -1
View File
@@ -44,4 +44,4 @@ templates:
2. 如果问题涉及特定领域或需要最新信息,建议用户查阅官方资料 2. 如果问题涉及特定领域或需要最新信息,建议用户查阅官方资料
3. 保持回答的准确性和客观性 3. 保持回答的准确性和客观性
用户问题:{{.Query}} 用户问题:{{query}}
+4 -13
View File
@@ -5,15 +5,10 @@ templates:
description: "标准的改写用户提示词格式" description: "标准的改写用户提示词格式"
content: | content: |
## 历史对话背景 ## 历史对话背景
{{range .Conversation}} {{conversation}}
------BEGIN------
用户的问题是:{{.Query}}
助手的回答是:{{.Answer}}
------END------
{{end}}
## 需要改写的用户问题 ## 需要改写的用户问题
{{.Query}} {{query}}
## 改写后的问题 ## 改写后的问题
@@ -24,14 +19,10 @@ templates:
## 历史对话背景 ## 历史对话背景
以下是用户与助手的对话历史,请仔细阅读以理解上下文: 以下是用户与助手的对话历史,请仔细阅读以理解上下文:
{{range .Conversation}} {{conversation}}
【用户】{{.Query}}
【助手】{{.Answer}}
{{end}}
## 当前用户问题 ## 当前用户问题
{{.Query}} {{query}}
## 任务要求 ## 任务要求
请根据以上对话历史,将当前问题改写为一个独立、完整、可以脱离上下文理解的问题。 请根据以上对话历史,将当前问题改写为一个独立、完整、可以脱离上下文理解的问题。
+50 -14
View File
@@ -1,12 +1,9 @@
import { get, post, put, del } from "../../utils/request"; import { get, post, put, del } from "../../utils/request";
// 智能体类型
export type CustomAgentType = 'normal' | 'agent' | 'custom';
// 智能体配置 // 智能体配置
export interface CustomAgentConfig { export interface CustomAgentConfig {
// ===== 基础设置 ===== // ===== 基础设置 =====
agent_mode?: 'normal' | 'agent'; // 运行模式:normal=RAG模式, agent=ReAct Agent模式 agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式
system_prompt?: string; // 系统提示词(普通模式,或Agent模式网络搜索关闭时) system_prompt?: string; // 系统提示词(普通模式,或Agent模式网络搜索关闭时)
system_prompt_web_enabled?: string; // Agent模式网络搜索开启时的系统提示词 system_prompt_web_enabled?: string; // Agent模式网络搜索开启时的系统提示词
context_template?: string; // 上下文模板(普通模式) context_template?: string; // 上下文模板(普通模式)
@@ -21,15 +18,14 @@ export interface CustomAgentConfig {
max_iterations?: number; // 最大迭代次数 max_iterations?: number; // 最大迭代次数
allowed_tools?: string[]; // 允许的工具 allowed_tools?: string[]; // 允许的工具
reflection_enabled?: boolean; // 是否启用反思 reflection_enabled?: boolean; // 是否启用反思
// MCP服务选择模式:all=全部启用的MCP服务, selected=指定服务, none=不使用MCP
mcp_selection_mode?: 'all' | 'selected' | 'none';
mcp_services?: string[]; // 选择的MCP服务ID列表
// ===== 知识库设置 ===== // ===== 知识库设置 =====
// 知识库选择模式:all=全部知识库, selected=指定知识库, none=不使用知识库 // 知识库选择模式:all=全部知识库, selected=指定知识库, none=不使用知识库
kb_selection_mode?: 'all' | 'selected' | 'none'; kb_selection_mode?: 'all' | 'selected' | 'none';
knowledge_bases?: string[]; knowledge_bases?: string[];
// 当没有配置知识库时,是否允许用户自由选择知识库
// true (默认): 用户可以自由选择任意知识库
// false: 禁用知识库选择功能
allow_user_kb_selection?: boolean;
// ===== 网络搜索设置 ===== // ===== 网络搜索设置 =====
web_search_enabled?: boolean; web_search_enabled?: boolean;
@@ -67,7 +63,6 @@ export interface CustomAgent {
description?: string; description?: string;
avatar?: string; avatar?: string;
is_builtin: boolean; is_builtin: boolean;
type: CustomAgentType;
tenant_id?: number; tenant_id?: number;
created_by?: string; created_by?: string;
config: CustomAgentConfig; config: CustomAgentConfig;
@@ -80,7 +75,6 @@ export interface CreateAgentRequest {
name: string; name: string;
description?: string; description?: string;
avatar?: string; avatar?: string;
type?: CustomAgentType;
config?: CustomAgentConfig; config?: CustomAgentConfig;
} }
@@ -89,13 +83,27 @@ export interface UpdateAgentRequest {
name: string; name: string;
description?: string; description?: string;
avatar?: string; avatar?: string;
type?: CustomAgentType;
config?: CustomAgentConfig; config?: CustomAgentConfig;
} }
// 内置智能体 ID // 内置智能体 ID
export const BUILTIN_AGENT_NORMAL_ID = 'builtin-normal'; export const BUILTIN_QUICK_ANSWER_ID = 'builtin-quick-answer';
export const BUILTIN_AGENT_AGENT_ID = 'builtin-agent'; export const BUILTIN_SMART_REASONING_ID = 'builtin-smart-reasoning';
// AgentMode 常量
export const AGENT_MODE_QUICK_ANSWER = 'quick-answer';
export const AGENT_MODE_SMART_REASONING = 'smart-reasoning';
// Deprecated: Use BUILTIN_QUICK_ANSWER_ID instead
export const BUILTIN_AGENT_NORMAL_ID = BUILTIN_QUICK_ANSWER_ID;
// Deprecated: Use BUILTIN_SMART_REASONING_ID instead
export const BUILTIN_AGENT_AGENT_ID = BUILTIN_SMART_REASONING_ID;
// 所有内置智能体 ID 列表(便于扩展)
export const BUILTIN_AGENT_IDS = [
BUILTIN_QUICK_ANSWER_ID,
BUILTIN_SMART_REASONING_ID,
] as const;
// 获取智能体列表(包括内置智能体) // 获取智能体列表(包括内置智能体)
export function listAgents() { export function listAgents() {
@@ -122,7 +130,35 @@ export function deleteAgent(id: string) {
return del<{ success: boolean }>(`/api/v1/agents/${id}`); return del<{ success: boolean }>(`/api/v1/agents/${id}`);
} }
// 复制智能体
export function copyAgent(id: string) {
return post<{ data: CustomAgent }>(`/api/v1/agents/${id}/copy`);
}
// 判断是否为内置智能体 // 判断是否为内置智能体
export function isBuiltinAgent(agentId: string): boolean { export function isBuiltinAgent(agentId: string): boolean {
return agentId === BUILTIN_AGENT_NORMAL_ID || agentId === BUILTIN_AGENT_AGENT_ID; return (BUILTIN_AGENT_IDS as readonly string[]).includes(agentId);
}
// 占位符定义
export interface PlaceholderDefinition {
name: string;
label: string;
description: string;
}
// 占位符响应
export interface PlaceholdersResponse {
all: PlaceholderDefinition[];
system_prompt: PlaceholderDefinition[];
agent_system_prompt: PlaceholderDefinition[];
context_template: PlaceholderDefinition[];
rewrite_system_prompt: PlaceholderDefinition[];
rewrite_prompt: PlaceholderDefinition[];
fallback_prompt: PlaceholderDefinition[];
}
// 获取占位符定义
export function getPlaceholders() {
return get<{ data: PlaceholdersResponse }>('/api/v1/agents/placeholders');
} }
+9 -4
View File
@@ -110,12 +110,17 @@ const letterStyle = computed(() => {
overflow: hidden; overflow: hidden;
&.agent-avatar-small { &.agent-avatar-small {
width: 24px; width: 22px;
height: 24px; height: 22px;
border-radius: 6px; border-radius: 5px;
box-shadow: none;
.agent-avatar-letter { .agent-avatar-letter {
font-size: 12px; font-size: 11px;
}
.agent-sparkles {
display: none;
} }
} }
+16 -14
View File
@@ -32,8 +32,8 @@
:class="{ 'selected': currentAgentId === agent.id }" :class="{ 'selected': currentAgentId === agent.id }"
@click="selectAgent(agent)" @click="selectAgent(agent)"
> >
<div class="builtin-icon" :class="agent.type"> <div class="builtin-icon" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">
<TIcon :name="agent.type === 'agent' ? 'control-platform' : 'chat'" size="14px" /> <TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" />
</div> </div>
<span class="agent-option-name">{{ agent.name }}</span> <span class="agent-option-name">{{ agent.name }}</span>
<svg <svg
@@ -95,7 +95,7 @@
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 } from 'tdesign-vue-next';
import { listAgents, type CustomAgent } from '@/api/agent'; import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';
import AgentAvatar from '@/components/AgentAvatar.vue'; import AgentAvatar from '@/components/AgentAvatar.vue';
const { t } = useI18n(); const { t } = useI18n();
@@ -118,18 +118,18 @@ const dropdownStyle = ref<Record<string, string>>({});
const builtinAgents = computed(() => { const builtinAgents = computed(() => {
return [ return [
{ {
id: 'builtin-normal', id: BUILTIN_QUICK_ANSWER_ID,
name: t('input.normalMode'), name: t('input.normalMode'),
description: t('input.normalModeDesc'), description: t('input.normalModeDesc'),
type: 'normal', is_builtin: true,
is_builtin: true config: { agent_mode: 'quick-answer' as const }
}, },
{ {
id: 'builtin-agent', id: BUILTIN_SMART_REASONING_ID,
name: t('input.agentMode'), name: t('input.agentMode'),
description: t('input.agentModeDesc'), description: t('input.agentModeDesc'),
type: 'agent', is_builtin: true,
is_builtin: true config: { agent_mode: 'smart-reasoning' as const }
} }
] as CustomAgent[]; ] as CustomAgent[];
}); });
@@ -143,9 +143,9 @@ const customAgents = computed(() => {
const getAgentCapabilities = (agent: CustomAgent): string => { const getAgentCapabilities = (agent: CustomAgent): string => {
// 内置智能体 // 内置智能体
if (agent.is_builtin) { if (agent.is_builtin) {
if (agent.type === 'normal') { if (agent.config?.agent_mode === 'quick-answer') {
return t('agent.capabilities.normal'); return t('agent.capabilities.normal');
} else if (agent.type === 'agent') { } else if (agent.config?.agent_mode === 'smart-reasoning') {
return t('agent.capabilities.agent'); return t('agent.capabilities.agent');
} }
return ''; return '';
@@ -158,10 +158,12 @@ const getAgentCapabilities = (agent: CustomAgent): string => {
if (config.model_id) { if (config.model_id) {
capabilities.push(t('agent.capabilities.modelSpecified')); capabilities.push(t('agent.capabilities.modelSpecified'));
} }
if (config.knowledge_bases && config.knowledge_bases.length > 0) { if (config.kb_selection_mode === 'none') {
capabilities.push(t('agent.capabilities.kbCount', { count: config.knowledge_bases.length }));
} else if (config.allow_user_kb_selection === false) {
capabilities.push(t('agent.capabilities.kbDisabled')); capabilities.push(t('agent.capabilities.kbDisabled'));
} else if (config.knowledge_bases && config.knowledge_bases.length > 0) {
capabilities.push(t('agent.capabilities.kbCount', { count: config.knowledge_bases.length }));
} else if (config.kb_selection_mode === 'all') {
capabilities.push(t('agent.capabilities.kbAll'));
} }
if (config.rerank_model_id) { if (config.rerank_model_id) {
capabilities.push(t('agent.capabilities.rerankSpecified')); capabilities.push(t('agent.capabilities.rerankSpecified'));
+285 -155
View File
@@ -12,7 +12,7 @@ import MentionSelector from './MentionSelector.vue';
import AgentSelector from './AgentSelector.vue'; import AgentSelector from './AgentSelector.vue';
import { getCaretCoordinates } from '@/utils/caret'; import { getCaretCoordinates } from '@/utils/caret';
import { listModels, type ModelConfig } from '@/api/model'; import { listModels, type ModelConfig } from '@/api/model';
import { listAgents, type CustomAgent } from '@/api/agent'; import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';
import { getTenantWebSearchConfig } from '@/api/web-search'; import { getTenantWebSearchConfig } from '@/api/web-search';
import { getConversationConfig, updateConversationConfig, type ConversationConfig } from '@/api/system'; import { getConversationConfig, updateConversationConfig, type ConversationConfig } from '@/api/system';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@@ -31,80 +31,92 @@ const agentModeDropdownStyle = ref<Record<string, string>>({});
// 智能体相关状态 // 智能体相关状态
const agents = ref<CustomAgent[]>([]); const agents = ref<CustomAgent[]>([]);
const selectedAgentId = computed({ const selectedAgentId = computed({
get: () => settingsStore.selectedAgentId || 'builtin-normal', get: () => settingsStore.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,
set: (val: string) => settingsStore.selectAgent(val) set: (val: string) => settingsStore.selectAgent(val)
}); });
const selectedAgent = computed(() => { const selectedAgent = computed(() => {
return agents.value.find(a => a.id === selectedAgentId.value) || { return agents.value.find(a => a.id === selectedAgentId.value) || {
id: 'builtin-normal', id: BUILTIN_QUICK_ANSWER_ID,
name: t('input.normalMode'), name: t('input.normalMode'),
type: 'normal', is_builtin: true,
is_builtin: true config: { agent_mode: 'quick-answer' as const }
} as CustomAgent; } as CustomAgent;
}); });
// 判断是否为自定义智能体(非内置) // 判断是否为自定义智能体(非内置)
const isCustomAgent = computed(() => { const isCustomAgent = computed(() => {
const agent = selectedAgent.value; const agent = selectedAgent.value;
return agent && !agent.is_builtin && agent.type === 'custom'; return agent && !agent.is_builtin;
});
// 判断是否有智能体配置(包括内置智能体)
const hasAgentConfig = computed(() => {
const agent = selectedAgent.value;
// 内置智能体需要从 agents 列表中获取实际配置
if (agent?.is_builtin) {
const builtinAgent = agents.value.find(a => a.id === agent.id);
return !!builtinAgent?.config;
}
return !!agent?.config;
});
// 获取当前智能体的实际配置(内置智能体从 agents 列表获取)
const currentAgentConfig = computed(() => {
const agent = selectedAgent.value;
if (agent?.is_builtin) {
const builtinAgent = agents.value.find(a => a.id === agent.id);
return builtinAgent?.config || {};
}
return agent?.config || {};
}); });
// 智能体预配置的知识库 IDs // 智能体预配置的知识库 IDs
const agentKnowledgeBases = computed(() => { const agentKnowledgeBases = computed(() => {
if (!isCustomAgent.value) return []; if (!hasAgentConfig.value) return [];
return selectedAgent.value?.config?.knowledge_bases || []; return currentAgentConfig.value?.knowledge_bases || [];
}); });
// 智能体的知识库选择模式 // 智能体的知识库选择模式
const agentKBSelectionMode = computed(() => { const agentKBSelectionMode = computed(() => {
if (!isCustomAgent.value) return null; // null 表示不受智能体控制 if (!hasAgentConfig.value) return null; // null 表示不受智能体控制
return selectedAgent.value?.config?.kb_selection_mode || 'none'; return currentAgentConfig.value?.kb_selection_mode || 'all';
}); });
// 智能体是否启用了网络搜索 // 智能体是否启用了网络搜索
const agentWebSearchEnabled = computed(() => { const agentWebSearchEnabled = computed(() => {
if (!isCustomAgent.value) return null; // null 表示不受智能体控制 if (!hasAgentConfig.value) return null; // null 表示不受智能体控制
return selectedAgent.value?.config?.web_search_enabled ?? false; return currentAgentConfig.value?.web_search_enabled ?? true;
}); });
// 网络搜索是否被智能体禁用(只读状态) // 网络搜索是否被智能体禁用(只读状态)- 只有明确设置为 false 时才禁用
const isWebSearchDisabledByAgent = computed(() => { const isWebSearchDisabledByAgent = computed(() => {
return isCustomAgent.value && agentWebSearchEnabled.value === false; return hasAgentConfig.value && agentWebSearchEnabled.value === false;
});
// 网络搜索是否被智能体强制启用
const isWebSearchForcedByAgent = computed(() => {
return isCustomAgent.value && agentWebSearchEnabled.value === true;
}); });
// 知识库选择是否被智能体锁定 // 知识库选择是否被智能体锁定
// 1. 如果智能体配置了 kb_selection_mode = 'none' → 完全禁用知识库 // 1. 如果智能体配置了 kb_selection_mode = 'none' → 完全禁用知识库
// 2. 如果智能体配置了 kb_selection_mode = 'selected' 且 allow_user_kb_selection=false → 锁定到指定知识库 // 其他情况用户都可以在允许的范围内通过 @ 选择知识库
// 3. 如果智能体配置了 kb_selection_mode = 'all' 且 allow_user_kb_selection=false → 锁定到全部知识库(但不允许用户选择)
const isKnowledgeBaseLockedByAgent = computed(() => { const isKnowledgeBaseLockedByAgent = computed(() => {
if (!isCustomAgent.value) return false; if (!hasAgentConfig.value) return false;
// 如果禁用了知识库,返回 true(锁定状态) // 只有禁用了知识库才锁定
if (agentKBSelectionMode.value === 'none') return true; return agentKBSelectionMode.value === 'none';
// 如果不允许用户选择知识库,返回 true
const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection;
return allowUserKBSelection === false;
}); });
// 知识库是否被智能体完全禁用(kb_selection_mode = 'none') // 知识库是否被智能体完全禁用(kb_selection_mode = 'none')
const isKnowledgeBaseDisabledByAgent = computed(() => { const isKnowledgeBaseDisabledByAgent = computed(() => {
if (!isCustomAgent.value) return false; if (!hasAgentConfig.value) return false;
return agentKBSelectionMode.value === 'none'; return agentKBSelectionMode.value === 'none';
}); });
// 智能体配置的模型 ID // 智能体配置的模型 ID
const agentModelId = computed(() => { const agentModelId = computed(() => {
if (!isCustomAgent.value) return null; if (!hasAgentConfig.value) return null;
return selectedAgent.value?.config?.model_id || null; return currentAgentConfig.value?.model_id || null;
}); });
// 模型选择是否被智能体锁定 // 模型选择是否被智能体锁定
const isModelLockedByAgent = computed(() => { const isModelLockedByAgent = computed(() => {
return isCustomAgent.value && !!agentModelId.value; return hasAgentConfig.value && !!agentModelId.value;
}); });
// Mention related state // Mention related state
@@ -566,8 +578,8 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
// 获取可选的知识库列表 // 获取可选的知识库列表
let availableKbs = knowledgeBases.value; let availableKbs = knowledgeBases.value;
// 如果是自定义智能体,根据 kb_selection_mode 过滤 // 如果智能体有配置,根据 kb_selection_mode 过滤
if (isCustomAgent.value) { if (hasAgentConfig.value) {
const kbMode = agentKBSelectionMode.value; const kbMode = agentKBSelectionMode.value;
if (kbMode === 'none') { if (kbMode === 'none') {
// 不使用知识库,不显示任何知识库 // 不使用知识库,不显示任何知识库
@@ -596,7 +608,7 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
// Fetch Files from API // Fetch Files from API
// 如果智能体禁用了知识库,也不显示文件 // 如果智能体禁用了知识库,也不显示文件
let fileItems: any[] = []; let fileItems: any[] = [];
const shouldLoadFiles = !isCustomAgent.value || agentKBSelectionMode.value !== 'none'; const shouldLoadFiles = !hasAgentConfig.value || agentKBSelectionMode.value !== 'none';
if (shouldLoadFiles) { if (shouldLoadFiles) {
mentionLoading.value = true; mentionLoading.value = true;
@@ -606,8 +618,8 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
if (res.data && Array.isArray(res.data)) { if (res.data && Array.isArray(res.data)) {
let files = res.data; let files = res.data;
// 如果是自定义智能体且 kb_selection_mode === 'selected',只显示指定知识库中的文件 // 如果智能体配置了 kb_selection_mode === 'selected',只显示指定知识库中的文件
if (isCustomAgent.value && agentKBSelectionMode.value === 'selected') { if (hasAgentConfig.value && agentKBSelectionMode.value === 'selected') {
const configuredKbIds = agentKnowledgeBases.value; const configuredKbIds = agentKnowledgeBases.value;
files = files.filter((f: any) => configuredKbIds.includes(f.knowledge_base_id)); files = files.filter((f: any) => configuredKbIds.includes(f.knowledge_base_id));
} }
@@ -1136,18 +1148,24 @@ const toggleAgentModeSelector = () => {
} }
} }
const selectAgentMode = (mode: 'normal' | 'agent') => { const selectAgentMode = (mode: 'quick-answer' | 'smart-reasoning') => {
if (mode === 'agent' && !settingsStore.isAgentReady) { const builtinAgentId = mode === 'smart-reasoning' ? BUILTIN_SMART_REASONING_ID : BUILTIN_QUICK_ANSWER_ID;
toggleAgentMode(); const builtinAgent = agents.value.find(a => a.id === builtinAgentId);
showAgentModeSelector.value = false;
return; if (builtinAgent) {
const notReadyReasons = getBuiltinAgentNotReadyReasons(builtinAgent, mode === 'smart-reasoning');
if (notReadyReasons.length > 0) {
showBuiltinAgentNotReadyMessage(mode, notReadyReasons);
showAgentModeSelector.value = false;
return;
}
} }
const shouldEnableAgent = mode === 'agent'; const shouldEnableAgent = mode === 'smart-reasoning';
if (shouldEnableAgent !== isAgentEnabled.value) { if (shouldEnableAgent !== isAgentEnabled.value) {
settingsStore.toggleAgent(shouldEnableAgent); settingsStore.toggleAgent(shouldEnableAgent);
// 同时更新选中的智能体 // 同时更新选中的智能体
settingsStore.selectAgent(shouldEnableAgent ? 'builtin-agent' : 'builtin-normal'); settingsStore.selectAgent(shouldEnableAgent ? BUILTIN_SMART_REASONING_ID : BUILTIN_QUICK_ANSWER_ID);
MessagePlugin.success(shouldEnableAgent ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff')); MessagePlugin.success(shouldEnableAgent ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff'));
} }
showAgentModeSelector.value = false; showAgentModeSelector.value = false;
@@ -1155,21 +1173,36 @@ const selectAgentMode = (mode: 'normal' | 'agent') => {
// 选择智能体(新版) // 选择智能体(新版)
const handleSelectAgent = (agent: CustomAgent) => { const handleSelectAgent = (agent: CustomAgent) => {
selectedAgentId.value = agent.id; // 根据智能体的 agent_mode 判断是否为 Agent 模式
const isAgentType = agent.config?.agent_mode === 'smart-reasoning';
// 根据智能体类型切换 Agent 模式 // 内置智能体检查 - 从实际的智能体配置来判断
const isAgentType = agent.type === 'agent' || (agent.type === 'custom' && (agent.config?.max_iterations ?? 0) > 1); if (agent.is_builtin) {
// 从 agents 列表中获取实际的内置智能体数据
if (isAgentType && !settingsStore.isAgentReady) { const builtinAgent = agents.value.find(a => a.id === agent.id);
// Agent 模式未就绪,显示提示 if (builtinAgent) {
toggleAgentMode(); const notReadyReasons = getBuiltinAgentNotReadyReasons(builtinAgent, isAgentType);
return; if (notReadyReasons.length > 0) {
showBuiltinAgentNotReadyMessage(isAgentType ? 'smart-reasoning' : 'quick-answer', notReadyReasons);
return;
}
}
} }
// 自定义智能体检查
if (!agent.is_builtin) {
const notReadyReasons = getCustomAgentNotReadyReasons(agent);
if (notReadyReasons.length > 0) {
showCustomAgentNotReadyMessage(agent, notReadyReasons);
return;
}
}
selectedAgentId.value = agent.id;
settingsStore.toggleAgent(!!isAgentType); settingsStore.toggleAgent(!!isAgentType);
// 如果是自定义智能体,同步网络搜索状态和模型 // 如果是自定义智能体,同步网络搜索状态和模型
if (!agent.is_builtin && agent.type === 'custom') { if (!agent.is_builtin) {
const agentWebSearch = agent.config?.web_search_enabled; const agentWebSearch = agent.config?.web_search_enabled;
if (agentWebSearch !== undefined) { if (agentWebSearch !== undefined) {
// 智能体配置了网络搜索设置,同步到 store // 智能体配置了网络搜索设置,同步到 store
@@ -1250,75 +1283,125 @@ const handleGoToWebSearchSettings = () => {
} }
}; };
const handleGoToAgentSettings = () => { const handleGoToAgentSettings = (section?: string) => {
// 使用 uiStore 打开设置并跳转到 agent 部分 // 跳转到智能体列表页并打开编辑弹窗
uiStore.openSettings('agent'); if (selectedAgent.value && !selectedAgent.value.is_builtin) {
// 如果当前不在设置页面,导航到设置页面 const query: Record<string, string> = { edit: selectedAgent.value.id };
if (route.path !== '/platform/settings') { if (section) {
router.push('/platform/settings'); query.section = section;
}
router.push({ path: '/platform/agents', query });
} else {
router.push('/platform/agents');
} }
} };
// 获取 Agent 不就绪的原因 // 获取内置智能体不就绪的原因
const getAgentNotReadyReasons = (): string[] => { const getBuiltinAgentNotReadyReasons = (agent: CustomAgent, isAgentMode: boolean): string[] => {
const reasons: string[] = [] const reasons: string[] = []
const config = settingsStore.agentConfig || { allowedTools: [] } const config = agent.config || {}
const models = settingsStore.conversationModels || { summaryModelId: '', rerankModelId: '' }
if (!config.allowedTools || config.allowedTools.length === 0) { // 检查对话模型(Summary Model)
reasons.push(t('input.agentMissingAllowedTools')) if (!config.model_id || config.model_id.trim() === '') {
reasons.push(t('input.customAgentMissingSummaryModel'))
} }
if (!models.summaryModelId || models.summaryModelId.trim() === '') {
reasons.push(t('input.agentMissingSummaryModel')) // 检查重排模型(Rerank Model)- 如果使用知识库则需要
if (config.kb_selection_mode !== 'none') {
if (!config.rerank_model_id || config.rerank_model_id.trim() === '') {
reasons.push(t('input.customAgentMissingRerankModel'))
}
} }
if (!models.rerankModelId || models.rerankModelId.trim() === '') {
reasons.push(t('input.agentMissingRerankModel')) // Agent 模式还需要检查允许的工具
if (isAgentMode) {
if (!config.allowed_tools || config.allowed_tools.length === 0) {
reasons.push(t('input.agentMissingAllowedTools'))
}
} }
return reasons return reasons
} }
const toggleAgentMode = () => { // 获取自定义智能体不就绪的原因(非 Agent 模式,快速回答)
// 如果要启用 Agent,先检查是否就绪 const getCustomAgentNotReadyReasons = (agent: CustomAgent): string[] => {
// 注意:isAgentReady 是从 store 中计算的,需要确保 store 中的配置是最新的 const reasons: string[] = []
if (!isAgentEnabled.value) { const config = agent.config || {}
// 尝试启用 Agent,先检查是否就绪
const agentReady = settingsStore.isAgentReady // 检查对话模型(Summary Model)
if (!agentReady) { if (!config.model_id || config.model_id.trim() === '') {
const reasons = getAgentNotReadyReasons() reasons.push(t('input.customAgentMissingSummaryModel'))
const reasonsText = reasons.join('、') }
// 检查重排模型(Rerank Model)- 如果使用知识库则需要
// 创建带跳转链接的自定义消息 if (config.kb_selection_mode !== 'none') {
const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 8px; max-width: 320px;' }, [ if (!config.rerank_model_id || config.rerank_model_id.trim() === '') {
h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.messages.agentNotReadyDetail', { reasons: reasonsText })), reasons.push(t('input.customAgentMissingRerankModel'))
h('a', {
href: '#',
onClick: (e: Event) => {
e.preventDefault();
handleGoToAgentSettings();
},
style: 'color: #07C05F; text-decoration: none; font-weight: 500; cursor: pointer; align-self: flex-start;',
onMouseenter: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'underline';
},
onMouseleave: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'none';
}
}, t('input.goToSettings'))
]);
MessagePlugin.warning({
content: () => messageContent,
duration: 5000
});
return
} }
} }
// 正常切换 Agent 状态 return reasons
settingsStore.toggleAgent(!isAgentEnabled.value); }
const message = isAgentEnabled.value ? t('input.messages.agentEnabled') : t('input.messages.agentDisabled');
MessagePlugin.success(message); // 显示自定义智能体未就绪的消息
const showCustomAgentNotReadyMessage = (agent: CustomAgent, reasons: string[]) => {
const reasonsText = reasons.join('、')
const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 8px; max-width: 320px;' }, [
h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.customAgentNotReadyDetail', { reasons: reasonsText })),
h('a', {
href: '#',
onClick: (e: Event) => {
e.preventDefault();
// 跳转到智能体编辑页面
router.push(`/platform/agents?edit=${agent.id}`);
},
style: 'color: #07C05F; text-decoration: none; font-weight: 500; cursor: pointer; align-self: flex-start;',
onMouseenter: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'underline';
},
onMouseleave: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'none';
}
}, t('input.goToAgentEditor'))
]);
MessagePlugin.warning({
content: () => messageContent,
duration: 5000
});
}
// 显示内置智能体未就绪的消息
const showBuiltinAgentNotReadyMessage = (mode: 'smart-reasoning' | 'quick-answer', reasons: string[]) => {
const agentName = mode === 'smart-reasoning'
? t('input.builtinAgentSettingName')
: t('input.builtinNormalSettingName');
const builtinAgentId = mode === 'smart-reasoning' ? BUILTIN_SMART_REASONING_ID : BUILTIN_QUICK_ANSWER_ID;
const reasonsText = reasons.join('、')
const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 8px; max-width: 320px;' }, [
h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.builtinAgentNotReadyDetail', { agentName, reasons: reasonsText })),
h('a', {
href: '#',
onClick: (e: Event) => {
e.preventDefault();
// 跳转到内置智能体编辑页面
router.push(`/platform/agents?edit=${builtinAgentId}`);
},
style: 'color: #07C05F; text-decoration: none; font-weight: 500; cursor: pointer; align-self: flex-start;',
onMouseenter: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'underline';
},
onMouseleave: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'none';
}
}, t('input.goToAgentEditor'))
]);
MessagePlugin.warning({
content: () => messageContent,
duration: 5000
});
} }
const toggleWebSearch = () => { const toggleWebSearch = () => {
@@ -1332,12 +1415,6 @@ const toggleWebSearch = () => {
MessagePlugin.warning(t('input.webSearchDisabledByAgent')); MessagePlugin.warning(t('input.webSearchDisabledByAgent'));
return; return;
} }
// 如果智能体强制启用了网络搜索,不允许关闭
if (isWebSearchForcedByAgent.value) {
MessagePlugin.warning(t('input.webSearchForcedByAgent'));
return;
}
if (!isWebSearchConfigured.value) { if (!isWebSearchConfigured.value) {
const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 6px; max-width: 280px;' }, [ const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 6px; max-width: 280px;' }, [
@@ -1472,8 +1549,9 @@ onBeforeRouteUpdate((to, from, next) => {
ref="agentModeButtonRef" ref="agentModeButtonRef"
class="control-btn agent-mode-btn" class="control-btn agent-mode-btn"
:class="{ :class="{
'active': isAgentEnabled, 'is-normal': !isCustomAgent && !isAgentEnabled,
'agent-active': isAgentEnabled 'is-agent': !isCustomAgent && isAgentEnabled,
'is-custom': isCustomAgent
}" }"
@click.stop="toggleAgentModeSelector" @click.stop="toggleAgentModeSelector"
> >
@@ -1502,12 +1580,14 @@ onBeforeRouteUpdate((to, from, next) => {
/> />
<!-- WebSearch 开关按钮 --> <!-- WebSearch 开关按钮 -->
<t-tooltip placement="top"> <t-tooltip placement="top" theme="light" :popupProps="{ overlayClassName: 'input-field-tooltip' }">
<template #content> <template #content>
<span v-if="isWebSearchDisabledByAgent">{{ $t('input.webSearchDisabledByAgent') }}</span> <div v-if="isWebSearchDisabledByAgent" class="tooltip-with-link">
<span v-else-if="isWebSearchForcedByAgent">{{ $t('input.webSearchForcedByAgent') }}</span> <span>{{ $t('input.webSearchDisabledByAgent') }}</span>
<a href="#" @click.prevent="handleGoToAgentSettings('websearch')">{{ $t('input.goToAgentSettings') }}</a>
</div>
<span v-else-if="isWebSearchConfigured">{{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }}</span> <span v-else-if="isWebSearchConfigured">{{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }}</span>
<div v-else class="websearch-tooltip-disabled"> <div v-else class="tooltip-with-link">
<span>{{ $t('input.webSearch.notConfigured') }}</span> <span>{{ $t('input.webSearch.notConfigured') }}</span>
<a href="#" @click.prevent="handleGoToWebSearchSettings">{{ $t('input.goToSettings') }}</a> <a href="#" @click.prevent="handleGoToWebSearchSettings">{{ $t('input.goToSettings') }}</a>
</div> </div>
@@ -1515,9 +1595,8 @@ onBeforeRouteUpdate((to, from, next) => {
<div <div
class="control-btn websearch-btn" class="control-btn websearch-btn"
:class="{ :class="{
'active': (isWebSearchEnabled && isWebSearchConfigured) || isWebSearchForcedByAgent, 'active': isWebSearchEnabled && isWebSearchConfigured,
'disabled': !isWebSearchConfigured, 'disabled': !isWebSearchConfigured || isWebSearchDisabledByAgent
'agent-controlled': isWebSearchDisabledByAgent || isWebSearchForcedByAgent
}" }"
@click.stop="toggleWebSearch" @click.stop="toggleWebSearch"
> >
@@ -1528,7 +1607,7 @@ onBeforeRouteUpdate((to, from, next) => {
fill="none" fill="none"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
class="control-icon websearch-icon" class="control-icon websearch-icon"
:class="{ 'active': (isWebSearchEnabled && isWebSearchConfigured) || isWebSearchForcedByAgent }" :class="{ 'active': isWebSearchEnabled && isWebSearchConfigured }"
> >
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none"/> <circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none"/>
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/> <path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
@@ -1540,13 +1619,20 @@ onBeforeRouteUpdate((to, from, next) => {
</t-tooltip> </t-tooltip>
<!-- @ 知识库/文件选择按钮 --> <!-- @ 知识库/文件选择按钮 -->
<t-tooltip :content="isKnowledgeBaseDisabledByAgent ? $t('input.kbDisabledByAgent') : (isKnowledgeBaseLockedByAgent ? $t('input.kbLockedByAgent') : (allSelectedItems.length > 0 ? $t('input.knowledgeBaseWithCount', { count: allSelectedItems.length }) : $t('input.knowledgeBase')))"> <t-tooltip placement="top" theme="light" :popupProps="{ overlayClassName: 'input-field-tooltip' }">
<template #content>
<div v-if="isKnowledgeBaseDisabledByAgent" class="tooltip-with-link">
<span>{{ $t('input.kbDisabledByAgent') }}</span>
<a href="#" @click.prevent="handleGoToAgentSettings('knowledge')">{{ $t('input.goToAgentSettings') }}</a>
</div>
<span v-else>{{ allSelectedItems.length > 0 ? $t('input.knowledgeBaseWithCount', { count: allSelectedItems.length }) : $t('input.knowledgeBase') }}</span>
</template>
<div <div
ref="atButtonRef" ref="atButtonRef"
class="control-btn kb-btn" class="control-btn kb-btn"
:class="{ :class="{
'active': allSelectedItems.length > 0, 'active': allSelectedItems.length > 0,
'agent-controlled': isKnowledgeBaseLockedByAgent 'disabled': isKnowledgeBaseDisabledByAgent
}" }"
@click.stop @click.stop
@mousedown.prevent="triggerMention" @mousedown.prevent="triggerMention"
@@ -1882,46 +1968,63 @@ const getImgSrc = (url: string) => {
transition: background 0.12s, border-color 0.12s; transition: background 0.12s, border-color 0.12s;
position: relative; position: relative;
&.active, // 内置普通模式 - 绿色
&.agent-active { &.is-normal {
background: linear-gradient(135deg, rgba(16, 185, 129, 0.15) 0%, rgba(16, 185, 129, 0.1) 100%); background: linear-gradient(135deg, rgba(16, 185, 129, 0.12) 0%, rgba(16, 185, 129, 0.08) 100%);
border-color: rgba(16, 185, 129, 0.4); border-color: rgba(16, 185, 129, 0.35);
box-shadow: 0 2px 6px rgba(16, 185, 129, 0.12);
.agent-mode-text { .agent-mode-text {
color: #07C05F; color: #059669;
font-weight: 600; font-weight: 600;
} }
.agent-icon {
filter: brightness(0) saturate(100%) invert(58%) sepia(87%) saturate(1234%) hue-rotate(95deg) brightness(98%) contrast(89%);
}
.dropdown-arrow { .dropdown-arrow {
color: #07C05F; color: #059669;
} }
&:hover { &:hover {
background: linear-gradient(135deg, rgba(16, 185, 129, 0.2) 0%, rgba(16, 185, 129, 0.15) 100%); background: linear-gradient(135deg, rgba(16, 185, 129, 0.18) 0%, rgba(16, 185, 129, 0.12) 100%);
border-color: rgba(16, 185, 129, 0.6); border-color: rgba(16, 185, 129, 0.5);
} }
} }
&:not(.agent-active) { // 内置 Agent 模式 - 紫色
background: var(--td-bg-color-container, #fff); &.is-agent {
border-color: var(--td-component-border, #e0e0e0); background: linear-gradient(135deg, rgba(124, 77, 255, 0.12) 0%, rgba(124, 77, 255, 0.08) 100%);
border-color: rgba(124, 77, 255, 0.35);
.agent-mode-text { .agent-mode-text {
color: var(--td-text-color-secondary, #666); color: #7c4dff;
font-weight: 600;
} }
.normal-mode-icon { .dropdown-arrow {
color: var(--td-text-color-secondary, #666); color: #7c4dff;
} }
&:hover { &:hover {
background: var(--td-bg-color-container-hover, #fff); background: linear-gradient(135deg, rgba(124, 77, 255, 0.18) 0%, rgba(124, 77, 255, 0.12) 100%);
border-color: var(--td-component-stroke, #b0b0b0); border-color: rgba(124, 77, 255, 0.5);
}
}
// 自定义智能体 - 蓝色
&.is-custom {
background: linear-gradient(135deg, rgba(59, 130, 246, 0.12) 0%, rgba(59, 130, 246, 0.08) 100%);
border-color: rgba(59, 130, 246, 0.35);
.agent-mode-text {
color: #3b82f6;
font-weight: 600;
}
.dropdown-arrow {
color: #3b82f6;
}
&:hover {
background: linear-gradient(135deg, rgba(59, 130, 246, 0.18) 0%, rgba(59, 130, 246, 0.12) 100%);
border-color: rgba(59, 130, 246, 0.5);
} }
} }
} }
@@ -1932,6 +2035,26 @@ const getImgSrc = (url: string) => {
flex-shrink: 0; flex-shrink: 0;
} }
.agent-btn-icon {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 5px;
flex-shrink: 0;
&.normal {
background: rgba(7, 192, 95, 0.12);
color: #059669;
}
&.agent {
background: rgba(124, 77, 255, 0.12);
color: #7c4dff;
}
}
.agent-mode-text { .agent-mode-text {
font-size: 13px; font-size: 13px;
color: var(--td-text-color-secondary, #666); color: var(--td-text-color-secondary, #666);
@@ -2052,22 +2175,29 @@ const getImgSrc = (url: string) => {
} }
} }
:global(.websearch-tooltip-disabled) { :global(.input-field-tooltip) {
display: flex; .t-popup__content {
flex-direction: column; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
gap: 4px; border: 1px solid var(--td-component-border, #e7e7e7);
max-width: 220px; }
font-size: 12px;
color: var(--td-text-color-secondary, #666);
} }
:global(.websearch-tooltip-disabled a) { :global(.tooltip-with-link) {
display: flex;
flex-direction: column;
gap: 6px;
max-width: 220px;
font-size: 12px;
color: var(--td-text-color-primary, #333);
}
:global(.tooltip-with-link a) {
color: #07C05F; color: #07C05F;
font-weight: 500; font-weight: 500;
text-decoration: none; text-decoration: none;
} }
:global(.websearch-tooltip-disabled a:hover) { :global(.tooltip-with-link a:hover) {
text-decoration: underline; text-decoration: underline;
} }
-4
View File
@@ -24,10 +24,6 @@
<t-icon name="server" class="menu-icon" /> <t-icon name="server" class="menu-icon" />
<span>Ollama</span> <span>Ollama</span>
</div> </div>
<div class="menu-item" @click="handleQuickNav('agent')">
<t-icon name="chat" class="menu-icon" />
<span>{{ $t('settings.conversationStrategy') }}</span>
</div>
<div class="menu-item" @click="handleQuickNav('websearch')"> <div class="menu-item" @click="handleQuickNav('websearch')">
<svg <svg
width="16" width="16"
+16 -6
View File
@@ -221,6 +221,7 @@ export default {
agent: 'Multi-step thinking, deep analysis for complex questions', agent: 'Multi-step thinking, deep analysis for complex questions',
modelSpecified: 'Model specified', modelSpecified: 'Model specified',
kbCount: '{count} knowledge base(s) specified', kbCount: '{count} knowledge base(s) specified',
kbAll: 'Access to all knowledge bases',
kbDisabled: 'Knowledge base disabled', kbDisabled: 'Knowledge base disabled',
rerankSpecified: 'ReRank model specified', rerankSpecified: 'ReRank model specified',
webSearchOn: 'Web search enabled', webSearchOn: 'Web search enabled',
@@ -258,6 +259,8 @@ export default {
deleteFailed: 'Delete failed', deleteFailed: 'Delete failed',
saveFailed: 'Save failed', saveFailed: 'Save failed',
builtinReadonly: 'Built-in agents cannot be edited', builtinReadonly: 'Built-in agents cannot be edited',
copied: 'Agent copied successfully',
copyFailed: 'Copy failed',
}, },
editor: { editor: {
createTitle: 'Create Agent', createTitle: 'Create Agent',
@@ -313,9 +316,6 @@ export default {
noKnowledgeBase: 'No Knowledge Base', noKnowledgeBase: 'No Knowledge Base',
noKnowledgeBaseDesc: 'Pure model conversation, no knowledge retrieval', noKnowledgeBaseDesc: 'Pure model conversation, no knowledge retrieval',
selectKnowledgeBases: 'Select Knowledge Bases', selectKnowledgeBases: 'Select Knowledge Bases',
allowUserKBSelection: 'Allow User KB Selection',
allowUserKBSelectionDescAll: 'When enabled, users can select from all knowledge bases during conversation; when disabled, all knowledge bases will be used automatically',
allowUserKBSelectionDescSelected: 'When enabled, users can select from associated knowledge bases during conversation; when disabled, all associated knowledge bases will be used automatically',
rerankModel: 'ReRank Model', rerankModel: 'ReRank Model',
rerankModelDesc: 'Used to rerank knowledge base retrieval results for better accuracy', rerankModelDesc: 'Used to rerank knowledge base retrieval results for better accuracy',
rerankModelPlaceholder: 'Select ReRank Model', rerankModelPlaceholder: 'Select ReRank Model',
@@ -759,6 +759,7 @@ export default {
save: 'Save', save: 'Save',
delete: 'Delete', delete: 'Delete',
edit: 'Edit', edit: 'Edit',
copy: 'Copy',
default: 'Default', default: 'Default',
create: 'Create', create: 'Create',
search: 'Search', search: 'Search',
@@ -918,6 +919,14 @@ export default {
agentMissingSummaryModel: 'Chat Model (Summary Model)', agentMissingSummaryModel: 'Chat Model (Summary Model)',
agentMissingRerankModel: 'Rerank Model', agentMissingRerankModel: 'Rerank Model',
goToSettings: 'Go to settings →', goToSettings: 'Go to settings →',
customAgentNotReadyTooltip: 'Agent is not ready. Please finish configuration first.',
customAgentNotReadyDetail: 'Agent is not ready. Please configure the following: {reasons}',
customAgentMissingSummaryModel: 'Chat Model (Summary Model)',
customAgentMissingRerankModel: 'Rerank Model',
goToAgentEditor: 'Go to configure →',
builtinAgentNotReadyDetail: 'Built-in agent "{agentName}" is not ready. Please configure: {reasons}',
builtinAgentSettingName: 'Intelligent Reasoning',
builtinNormalSettingName: 'Quick Q&A',
webSearch: { webSearch: {
toggleOn: 'Enable Web Search', toggleOn: 'Enable Web Search',
toggleOff: 'Disable Web Search', toggleOff: 'Disable Web Search',
@@ -936,8 +945,8 @@ export default {
enterContent: 'Please enter content first!', enterContent: 'Please enter content first!',
selectKnowledge: 'Please select a knowledge base first!', selectKnowledge: 'Please select a knowledge base first!',
replying: 'Currently replying, please try again later!', replying: 'Currently replying, please try again later!',
agentSwitchedOn: 'Switched to Agent Mode', agentSwitchedOn: 'Switched to Intelligent Reasoning',
agentSwitchedOff: 'Switched to Normal Mode', agentSwitchedOff: 'Switched to Quick Q&A',
agentSelected: 'Selected agent "{name}"', agentSelected: 'Selected agent "{name}"',
agentEnabled: 'Agent Mode enabled', agentEnabled: 'Agent Mode enabled',
agentDisabled: 'Agent Mode disabled', agentDisabled: 'Agent Mode disabled',
@@ -959,7 +968,8 @@ export default {
kbDisabledByAgent: 'Knowledge base is disabled by the current agent', kbDisabledByAgent: 'Knowledge base is disabled by the current agent',
cannotRemoveAgentKb: 'Cannot remove knowledge base configured by agent', cannotRemoveAgentKb: 'Cannot remove knowledge base configured by agent',
agentConfiguredKb: 'Configured by agent, cannot be removed', agentConfiguredKb: 'Configured by agent, cannot be removed',
modelLockedByAgent: 'Model selection is locked by the current agent' modelLockedByAgent: 'Model selection is locked by the current agent',
goToAgentSettings: 'Go to agent settings'
}, },
createChat: { createChat: {
title: 'Knowledge-base Q&A - AI Assistant', title: 'Knowledge-base Q&A - AI Assistant',
+15 -5
View File
@@ -689,6 +689,7 @@ export default {
save: "保存", save: "保存",
delete: "删除", delete: "删除",
edit: "编辑", edit: "编辑",
copy: "复制",
default: "默认", default: "默认",
create: "创建", create: "创建",
search: "搜索", search: "搜索",
@@ -750,6 +751,7 @@ export default {
agent: "多步思考,深度分析复杂问题", agent: "多步思考,深度分析复杂问题",
modelSpecified: "指定模型", modelSpecified: "指定模型",
kbCount: "指定 {count} 个知识库", kbCount: "指定 {count} 个知识库",
kbAll: "可访问全部知识库",
kbDisabled: "禁用知识库", kbDisabled: "禁用知识库",
rerankSpecified: "指定 ReRank 模型", rerankSpecified: "指定 ReRank 模型",
webSearchOn: "启用网络搜索", webSearchOn: "启用网络搜索",
@@ -787,6 +789,8 @@ export default {
deleteFailed: "删除失败", deleteFailed: "删除失败",
saveFailed: "保存失败", saveFailed: "保存失败",
builtinReadonly: "内置智能体不可编辑", builtinReadonly: "内置智能体不可编辑",
copied: "智能体复制成功",
copyFailed: "复制失败",
}, },
editor: { editor: {
createTitle: "创建智能体", createTitle: "创建智能体",
@@ -842,9 +846,6 @@ export default {
noKnowledgeBase: "不使用知识库", noKnowledgeBase: "不使用知识库",
noKnowledgeBaseDesc: "纯模型对话,不检索知识库", noKnowledgeBaseDesc: "纯模型对话,不检索知识库",
selectKnowledgeBases: "选择知识库", selectKnowledgeBases: "选择知识库",
allowUserKBSelection: "允许用户选择知识库",
allowUserKBSelectionDescAll: "开启后,用户可以在对话时从全部知识库中选择;关闭后,将自动使用全部知识库",
allowUserKBSelectionDescSelected: "开启后,用户可以在对话时从关联的知识库中选择;关闭后,将自动使用全部关联的知识库",
rerankModel: "ReRank 模型", rerankModel: "ReRank 模型",
rerankModelDesc: "用于对知识库检索结果进行重排序,提高回答准确性", rerankModelDesc: "用于对知识库检索结果进行重排序,提高回答准确性",
rerankModelPlaceholder: "请选择 ReRank 模型", rerankModelPlaceholder: "请选择 ReRank 模型",
@@ -1598,6 +1599,14 @@ export default {
agentMissingSummaryModel: "对话模型(Summary Model)", agentMissingSummaryModel: "对话模型(Summary Model)",
agentMissingRerankModel: "重排模型(Rerank Model)", agentMissingRerankModel: "重排模型(Rerank Model)",
goToSettings: "前往设置 →", goToSettings: "前往设置 →",
customAgentNotReadyTooltip: "智能体未就绪,请先完成配置",
customAgentNotReadyDetail: "智能体未就绪,需要配置以下内容:{reasons}",
customAgentMissingSummaryModel: "对话模型(Summary Model)",
customAgentMissingRerankModel: "重排模型(Rerank Model)",
goToAgentEditor: "前往配置 →",
builtinAgentNotReadyDetail: "内置智能体「{agentName}」未就绪,需要配置以下内容:{reasons}",
builtinAgentSettingName: "智能推理",
builtinNormalSettingName: "快速问答",
webSearch: { webSearch: {
toggleOn: "开启网络搜索", toggleOn: "开启网络搜索",
toggleOff: "关闭网络搜索", toggleOff: "关闭网络搜索",
@@ -1616,8 +1625,8 @@ export default {
enterContent: "请先输入内容!", enterContent: "请先输入内容!",
selectKnowledge: "请先选择知识库!", selectKnowledge: "请先选择知识库!",
replying: "正在回复中,请稍后再试!", replying: "正在回复中,请稍后再试!",
agentSwitchedOn: "已切换到 Agent 模式", agentSwitchedOn: "已切换到智能推理",
agentSwitchedOff: "已切换到普通模式", agentSwitchedOff: "已切换到快速问答",
agentSelected: "已选择智能体「{name}」", agentSelected: "已选择智能体「{name}」",
agentEnabled: "Agent 模式已启用", agentEnabled: "Agent 模式已启用",
agentDisabled: "Agent 模式已禁用", agentDisabled: "Agent 模式已禁用",
@@ -1639,6 +1648,7 @@ export default {
cannotRemoveAgentKb: "智能体配置的知识库无法移除", cannotRemoveAgentKb: "智能体配置的知识库无法移除",
agentConfiguredKb: "由智能体配置,不可删除", agentConfiguredKb: "由智能体配置,不可删除",
modelLockedByAgent: "当前智能体已锁定模型配置", modelLockedByAgent: "当前智能体已锁定模型配置",
goToAgentSettings: "去设置智能体",
}, },
agentSettings: { agentSettings: {
title: "Agent 配置", title: "Agent 配置",
+16 -5
View File
@@ -1,4 +1,5 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent";
// 定义设置接口 // 定义设置接口
interface Settings { interface Settings {
@@ -89,7 +90,7 @@ const defaultSettings: Settings = {
rerankModelId: "", rerankModelId: "",
selectedChatModelId: "", // 用户当前选择的对话模型ID selectedChatModelId: "", // 用户当前选择的对话模型ID
}, },
selectedAgentId: "builtin-normal", // 默认选中普通模式 selectedAgentId: BUILTIN_QUICK_ANSWER_ID, // 默认选中快速问答模式
}; };
export const useSettingsStore = defineStore("settings", { export const useSettingsStore = defineStore("settings", {
@@ -114,6 +115,16 @@ export const useSettingsStore = defineStore("settings", {
) )
}, },
// 普通模式(快速回答)是否就绪
// 需要满足:1) 设置了对话模型 2) 设置了重排模型
isNormalModeReady: (state) => {
const models = state.settings.conversationModels || defaultSettings.conversationModels
return Boolean(
models.summaryModelId && models.summaryModelId.trim() !== '' &&
models.rerankModelId && models.rerankModelId.trim() !== ''
)
},
// 获取 Agent 配置 // 获取 Agent 配置
agentConfig: (state) => state.settings.agentConfig || defaultSettings.agentConfig, agentConfig: (state) => state.settings.agentConfig || defaultSettings.agentConfig,
@@ -126,7 +137,7 @@ export const useSettingsStore = defineStore("settings", {
isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false, isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,
// 当前选中的智能体ID // 当前选中的智能体ID
selectedAgentId: (state) => state.settings.selectedAgentId || "builtin-normal", selectedAgentId: (state) => state.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,
}, },
actions: { actions: {
@@ -309,9 +320,9 @@ export const useSettingsStore = defineStore("settings", {
selectAgent(agentId: string) { selectAgent(agentId: string) {
this.settings.selectedAgentId = agentId; this.settings.selectedAgentId = agentId;
// 根据智能体类型自动切换 Agent 模式 // 根据智能体类型自动切换 Agent 模式
if (agentId === "builtin-normal") { if (agentId === BUILTIN_QUICK_ANSWER_ID) {
this.settings.isAgentEnabled = false; this.settings.isAgentEnabled = false;
} else if (agentId === "builtin-agent") { } else if (agentId === BUILTIN_SMART_REASONING_ID) {
this.settings.isAgentEnabled = true; this.settings.isAgentEnabled = true;
} }
// 自定义智能体需要根据其配置来决定 // 自定义智能体需要根据其配置来决定
@@ -320,7 +331,7 @@ export const useSettingsStore = defineStore("settings", {
// 获取选中的智能体ID // 获取选中的智能体ID
getSelectedAgentId(): string { getSelectedAgentId(): string {
return this.settings.selectedAgentId || "builtin-normal"; return this.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID;
}, },
}, },
}); });
File diff suppressed because it is too large Load Diff
+165 -103
View File
@@ -17,8 +17,8 @@
class="agent-card" class="agent-card"
:class="{ :class="{
'is-builtin': agent.is_builtin, 'is-builtin': agent.is_builtin,
'agent-mode-normal': agent.config?.agent_mode === 'normal', 'agent-mode-normal': agent.config?.agent_mode === 'quick-answer',
'agent-mode-agent': agent.config?.agent_mode === 'agent' 'agent-mode-agent': agent.config?.agent_mode === 'smart-reasoning'
}" }"
@click="handleCardClick(agent)" @click="handleCardClick(agent)"
> >
@@ -35,15 +35,15 @@
<!-- 卡片头部 --> <!-- 卡片头部 -->
<div class="card-header"> <div class="card-header">
<div class="card-header-left"> <div class="card-header-left">
<AgentAvatar :name="agent.name" size="medium" /> <!-- 内置智能体使用简洁图标 -->
<span class="card-title" :title="agent.name">{{ agent.name }}</span> <div v-if="agent.is_builtin" class="builtin-avatar" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">
<div v-if="agent.is_builtin" class="builtin-badge"> <t-icon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="18px" />
<t-icon name="lock-on" size="12px" />
<span>{{ $t('agent.builtin') }}</span>
</div> </div>
<!-- 自定义智能体使用 AgentAvatar -->
<AgentAvatar v-else :name="agent.name" size="medium" />
<span class="card-title" :title="agent.name">{{ agent.name }}</span>
</div> </div>
<t-popup <t-popup
v-if="!agent.is_builtin"
v-model="agent.showMore" v-model="agent.showMore"
overlayClassName="card-more-popup" overlayClassName="card-more-popup"
:on-visible-change="(visible: boolean) => onVisibleChange(visible, agent)" :on-visible-change="(visible: boolean) => onVisibleChange(visible, agent)"
@@ -64,17 +64,17 @@
<t-icon class="menu-icon" name="edit" /> <t-icon class="menu-icon" name="edit" />
<span>{{ $t('common.edit') }}</span> <span>{{ $t('common.edit') }}</span>
</div> </div>
<div class="popup-menu-item delete" @click="handleDelete(agent)"> <div class="popup-menu-item" @click="handleCopy(agent)">
<t-icon class="menu-icon" name="file-copy" />
<span>{{ $t('common.copy') }}</span>
</div>
<div v-if="!agent.is_builtin" class="popup-menu-item delete" @click="handleDelete(agent)">
<t-icon class="menu-icon" name="delete" /> <t-icon class="menu-icon" name="delete" />
<span>{{ $t('common.delete') }}</span> <span>{{ $t('common.delete') }}</span>
</div> </div>
</div> </div>
</template> </template>
</t-popup> </t-popup>
<!-- 内置智能体显示编辑按钮 -->
<div v-else class="edit-btn" @click.stop="handleEdit(agent)">
<t-icon name="edit" size="16px" />
</div>
</div> </div>
<!-- 卡片内容 --> <!-- 卡片内容 -->
@@ -87,11 +87,12 @@
<!-- 卡片底部 --> <!-- 卡片底部 -->
<div class="card-bottom"> <div class="card-bottom">
<div class="bottom-left"> <div class="bottom-left">
<div class="type-badge" :class="{ 'normal': agent.config?.agent_mode === 'normal', 'agent': agent.config?.agent_mode === 'agent' }">
<t-icon :name="agent.config?.agent_mode === 'agent' ? 'control-platform' : 'chat'" size="14px" />
<span>{{ agent.config?.agent_mode === 'agent' ? $t('agent.mode.agent') : $t('agent.mode.normal') }}</span>
</div>
<div class="feature-badges"> <div class="feature-badges">
<t-tooltip :content="agent.config?.agent_mode === 'smart-reasoning' ? $t('agent.mode.agent') : $t('agent.mode.normal')" placement="top">
<div class="feature-badge" :class="{ 'mode-normal': agent.config?.agent_mode === 'quick-answer', 'mode-agent': agent.config?.agent_mode === 'smart-reasoning' }">
<t-icon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" />
</div>
</t-tooltip>
<t-tooltip v-if="agent.config?.web_search_enabled" :content="$t('agent.features.webSearch')" placement="top"> <t-tooltip v-if="agent.config?.web_search_enabled" :content="$t('agent.features.webSearch')" placement="top">
<div class="feature-badge web-search"> <div class="feature-badge web-search">
<t-icon name="search" size="14px" /> <t-icon name="search" size="14px" />
@@ -109,7 +110,11 @@
</t-tooltip> </t-tooltip>
</div> </div>
</div> </div>
<span v-if="agent.updated_at" class="card-time">{{ formatDate(agent.updated_at) }}</span> <div v-if="agent.is_builtin" class="builtin-badge">
<t-icon name="lock-on" size="12px" />
<span>{{ $t('agent.builtin') }}</span>
</div>
<span v-else-if="agent.updated_at" class="card-time">{{ formatDate(agent.updated_at) }}</span>
</div> </div>
</div> </div>
</div> </div>
@@ -149,6 +154,7 @@
:visible="editorVisible" :visible="editorVisible"
:mode="editorMode" :mode="editorMode"
:agent="editingAgent" :agent="editingAgent"
:initialSection="editorInitialSection"
@update:visible="editorVisible = $event" @update:visible="editorVisible = $event"
@success="handleEditorSuccess" @success="handleEditorSuccess"
/> />
@@ -157,14 +163,17 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue' import { onMounted, onUnmounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next' import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { listAgents, deleteAgent, type CustomAgent } from '@/api/agent' import { listAgents, deleteAgent, copyAgent, type CustomAgent } from '@/api/agent'
import { formatStringDate } from '@/utils/index' import { formatStringDate } from '@/utils/index'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import AgentEditorModal from './AgentEditorModal.vue' import AgentEditorModal from './AgentEditorModal.vue'
import AgentAvatar from '@/components/AgentAvatar.vue' import AgentAvatar from '@/components/AgentAvatar.vue'
const { t } = useI18n() const { t } = useI18n()
const route = useRoute()
const router = useRouter()
interface AgentWithUI extends CustomAgent { interface AgentWithUI extends CustomAgent {
showMore?: boolean showMore?: boolean
@@ -177,6 +186,7 @@ const deletingAgent = ref<AgentWithUI | null>(null)
const editorVisible = ref(false) const editorVisible = ref(false)
const editorMode = ref<'create' | 'edit'>('create') const editorMode = ref<'create' | 'edit'>('create')
const editingAgent = ref<CustomAgent | null>(null) const editingAgent = ref<CustomAgent | null>(null)
const editorInitialSection = ref<string>('basic')
const fetchList = () => { const fetchList = () => {
loading.value = true loading.value = true
@@ -187,9 +197,29 @@ const fetchList = () => {
...agent, ...agent,
showMore: false showMore: false
})) }))
// 检查 URL 中是否有 edit 参数,如果有则打开对应智能体的编辑模态框
checkAndOpenEditModal()
}).finally(() => loading.value = false) }).finally(() => loading.value = false)
} }
// 检查 URL 参数并打开编辑模态框
const checkAndOpenEditModal = () => {
const editId = route.query.edit as string
const section = route.query.section as string
if (editId) {
const agent = agents.value.find(a => a.id === editId)
if (agent) {
editingAgent.value = agent
editorMode.value = 'edit'
editorInitialSection.value = section || 'basic'
editorVisible.value = true
}
// 清除 URL 中的参数
router.replace({ path: route.path, query: {} })
}
}
// 监听菜单创建智能体事件 // 监听菜单创建智能体事件
const handleOpenAgentEditor = (event: CustomEvent) => { const handleOpenAgentEditor = (event: CustomEvent) => {
if (event.detail?.mode === 'create') { if (event.detail?.mode === 'create') {
@@ -234,6 +264,20 @@ const handleDelete = (agent: AgentWithUI) => {
deleteVisible.value = true deleteVisible.value = true
} }
const handleCopy = (agent: AgentWithUI) => {
agent.showMore = false
copyAgent(agent.id).then((res: any) => {
if (res.data) {
MessagePlugin.success(t('agent.messages.copied'))
fetchList()
} else {
MessagePlugin.error(res.message || t('agent.messages.copyFailed'))
}
}).catch((e: any) => {
MessagePlugin.error(e?.message || t('agent.messages.copyFailed'))
})
}
const confirmDelete = () => { const confirmDelete = () => {
if (!deletingAgent.value) return if (!deletingAgent.value) return
@@ -323,43 +367,44 @@ defineExpose({
.agent-card-wrap { .agent-card-wrap {
display: grid; display: grid;
gap: 20px; gap: 16px;
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
.agent-card { .agent-card {
border: 2px solid #fbfbfb; border: 1px solid #f0f0f0;
border-radius: 6px; border-radius: 12px;
overflow: hidden; overflow: hidden;
box-sizing: border-box; box-sizing: border-box;
box-shadow: 0 0 8px 0 #00000005; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
background: #fff; background: #fff;
position: relative; position: relative;
cursor: pointer; cursor: pointer;
transition: all 0.2s ease; transition: all 0.25s ease;
padding: 12px 16px 14px; padding: 16px 18px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-height: 150px; height: 160px;
&:hover { &:hover {
border-color: #07c05f; border-color: #07c05f;
box-shadow: 0 4px 12px rgba(7, 192, 95, 0.12);
} }
// 普通模式样式 // 普通模式样式
&.agent-mode-normal { &.agent-mode-normal {
background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%); background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);
border-color: #e8f5ed; border-color: #e8f5ed;
&:hover { &:hover {
border-color: #07c05f; border-color: #07c05f;
background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%); background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
} }
.card-decoration { .card-decoration {
color: rgba(7, 192, 95, 0.35); color: rgba(7, 192, 95, 0.35);
} }
&:hover .card-decoration { &:hover .card-decoration {
color: rgba(7, 192, 95, 0.5); color: rgba(7, 192, 95, 0.5);
} }
@@ -369,16 +414,17 @@ defineExpose({
&.agent-mode-agent { &.agent-mode-agent {
background: linear-gradient(135deg, #ffffff 0%, #f8f5ff 100%); background: linear-gradient(135deg, #ffffff 0%, #f8f5ff 100%);
border-color: #ede8ff; border-color: #ede8ff;
&:hover { &:hover {
border-color: #7c4dff; border-color: #7c4dff;
box-shadow: 0 4px 12px rgba(124, 77, 255, 0.12);
background: linear-gradient(135deg, #ffffff 0%, #f3efff 100%); background: linear-gradient(135deg, #ffffff 0%, #f3efff 100%);
} }
.card-decoration { .card-decoration {
color: rgba(124, 77, 255, 0.35); color: rgba(124, 77, 255, 0.35);
} }
&:hover .card-decoration { &:hover .card-decoration {
color: rgba(124, 77, 255, 0.5); color: rgba(124, 77, 255, 0.5);
} }
@@ -395,21 +441,21 @@ defineExpose({
.card-decoration { .card-decoration {
position: absolute; position: absolute;
top: 8px; top: 12px;
right: 8px; right: 50px;
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
gap: 2px; gap: 4px;
pointer-events: none; pointer-events: none;
z-index: 0; z-index: 0;
transition: color 0.2s ease; transition: color 0.25s ease;
.star-icon { .star-icon {
opacity: 0.8; opacity: 0.9;
&.small { &.small {
margin-top: 12px; margin-top: 14px;
opacity: 0.6; opacity: 0.7;
} }
} }
} }
@@ -418,7 +464,7 @@ defineExpose({
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 8px; margin-bottom: 10px;
} }
.card-header-left { .card-header-left {
@@ -430,9 +476,9 @@ defineExpose({
} }
.card-title { .card-title {
color: #000000e6; color: #1a1a1a;
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 14px; font-size: 15px;
font-weight: 600; font-weight: 600;
line-height: 22px; line-height: 22px;
overflow: hidden; overflow: hidden;
@@ -445,17 +491,37 @@ defineExpose({
.builtin-badge { .builtin-badge {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 4px; gap: 3px;
padding: 2px 8px; padding: 2px 8px;
border-radius: 4px; border-radius: 10px;
background: rgba(0, 0, 0, 0.05); background: rgba(0, 0, 0, 0.04);
color: #00000066; color: #666;
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 12px; font-size: 11px;
font-weight: 400; font-weight: 500;
flex-shrink: 0; flex-shrink: 0;
} }
.builtin-avatar {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
flex-shrink: 0;
&.normal {
background: linear-gradient(135deg, rgba(7, 192, 95, 0.15) 0%, rgba(7, 192, 95, 0.08) 100%);
color: #059669;
}
&.agent {
background: linear-gradient(135deg, rgba(124, 77, 255, 0.15) 0%, rgba(124, 77, 255, 0.08) 100%);
color: #7c4dff;
}
}
.edit-btn { .edit-btn {
display: flex; display: flex;
width: 32px; width: 32px;
@@ -476,24 +542,28 @@ defineExpose({
.more-wrap { .more-wrap {
display: flex; display: flex;
width: 32px; width: 28px;
height: 32px; height: 28px;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
border-radius: 6px; border-radius: 6px;
cursor: pointer; cursor: pointer;
flex-shrink: 0; flex-shrink: 0;
transition: all 0.2s ease; transition: all 0.2s ease;
opacity: 0.7; opacity: 0;
.agent-card:hover & {
opacity: 0.6;
}
&:hover { &:hover {
background: rgba(0, 0, 0, 0.06); background: rgba(0, 0, 0, 0.05);
opacity: 1; opacity: 1 !important;
} }
&.active-more { &.active-more {
background: rgba(0, 0, 0, 0.08); background: rgba(0, 0, 0, 0.06);
opacity: 1; opacity: 1 !important;
} }
.more-icon { .more-icon {
@@ -504,7 +574,8 @@ defineExpose({
.card-content { .card-content {
flex: 1; flex: 1;
margin-bottom: 10px; margin-bottom: 12px;
overflow: hidden;
} }
.card-description { .card-description {
@@ -513,21 +584,20 @@ defineExpose({
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
line-clamp: 2; line-clamp: 2;
overflow: hidden; overflow: hidden;
color: #00000066; color: #666;
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 12px; font-size: 13px;
font-weight: 400; font-weight: 400;
line-height: 20px; line-height: 20px;
min-height: 40px;
} }
.card-bottom { .card-bottom {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 8px 0 0;
border-top: 1px solid #f0f0f0;
margin-top: auto; margin-top: auto;
padding-top: 12px;
border-top: 1px solid #f0f0f0;
} }
.bottom-left { .bottom-left {
@@ -536,78 +606,70 @@ defineExpose({
gap: 8px; gap: 8px;
} }
.type-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 10px;
border-radius: 4px;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 500;
line-height: 18px;
&.normal {
background: rgba(7, 192, 95, 0.1);
color: #059669;
border: 1px solid rgba(7, 192, 95, 0.2);
}
&.agent {
background: rgba(124, 77, 255, 0.1);
color: #7c4dff;
border: 1px solid rgba(124, 77, 255, 0.2);
}
}
.feature-badges { .feature-badges {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 6px; gap: 4px;
} }
.feature-badge { .feature-badge {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 24px; width: 26px;
height: 24px; height: 26px;
border-radius: 4px; border-radius: 6px;
cursor: pointer; cursor: default;
transition: background 0.2s ease;
&.web-search { &.mode-normal {
background: rgba(255, 152, 0, 0.1); background: rgba(7, 192, 95, 0.08);
color: #ff9800; color: #059669;
border: 1px solid rgba(255, 152, 0, 0.2);
&:hover { &:hover {
background: rgba(255, 152, 0, 0.15); background: rgba(7, 192, 95, 0.12);
}
}
&.mode-agent {
background: rgba(124, 77, 255, 0.08);
color: #7c4dff;
&:hover {
background: rgba(124, 77, 255, 0.12);
}
}
&.web-search {
background: rgba(255, 152, 0, 0.08);
color: #f59e0b;
&:hover {
background: rgba(255, 152, 0, 0.12);
} }
} }
&.knowledge { &.knowledge {
background: rgba(7, 192, 95, 0.1); background: rgba(7, 192, 95, 0.08);
color: #059669; color: #059669;
border: 1px solid rgba(7, 192, 95, 0.2);
&:hover { &:hover {
background: rgba(7, 192, 95, 0.15); background: rgba(7, 192, 95, 0.12);
} }
} }
&.multi-turn { &.multi-turn {
background: rgba(0, 82, 217, 0.1); background: rgba(59, 130, 246, 0.08);
color: #0052d9; color: #3b82f6;
border: 1px solid rgba(0, 82, 217, 0.2);
&:hover { &:hover {
background: rgba(0, 82, 217, 0.15); background: rgba(59, 130, 246, 0.12);
} }
} }
} }
.card-time { .card-time {
color: #00000066; color: #999;
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 12px; font-size: 12px;
font-weight: 400; font-weight: 400;
+101 -102
View File
@@ -116,23 +116,14 @@
<!-- 卡片底部 --> <!-- 卡片底部 -->
<div class="card-bottom"> <div class="card-bottom">
<div class="bottom-left"> <div class="bottom-left">
<div class="type-badge" :class="{ 'document': (kb.type || 'document') === 'document', 'faq': kb.type === 'faq' }">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" size="14px" />
<span>
{{ kb.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument') }}
({{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }})
</span>
<t-tooltip
v-if="kb.isProcessing"
:content="kb.type === 'document' && (kb.processing_count || 0) > 0
? $t('knowledgeList.processingDocuments', { count: kb.processing_count || 0 })
: $t('knowledgeList.processing')"
placement="top"
>
<t-icon name="loading" size="14px" class="processing-icon" />
</t-tooltip>
</div>
<div class="feature-badges"> <div class="feature-badges">
<t-tooltip :content="kb.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument')" placement="top">
<div class="feature-badge" :class="{ 'type-document': (kb.type || 'document') === 'document', 'type-faq': kb.type === 'faq' }">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" size="14px" />
<span class="badge-count">{{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }}</span>
<t-icon v-if="kb.isProcessing" name="loading" size="12px" class="processing-icon" />
</div>
</t-tooltip>
<t-tooltip v-if="kb.extract_config?.enabled" :content="$t('knowledgeList.features.knowledgeGraph')" placement="top"> <t-tooltip v-if="kb.extract_config?.enabled" :content="$t('knowledgeList.features.knowledgeGraph')" placement="top">
<div class="feature-badge kg"> <div class="feature-badge kg">
<t-icon name="relation" size="14px" /> <t-icon name="relation" size="14px" />
@@ -700,27 +691,28 @@ const handleUploadFinishedEvent = (event: Event) => {
.kb-card-wrap { .kb-card-wrap {
display: grid; display: grid;
gap: 20px; gap: 16px;
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
.kb-card { .kb-card {
border: 2px solid #fbfbfb; border: 1px solid #f0f0f0;
border-radius: 6px; border-radius: 12px;
overflow: hidden; overflow: hidden;
box-sizing: border-box; box-sizing: border-box;
box-shadow: 0 0 8px 0 #00000005; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
background: #fff; background: #fff;
position: relative; position: relative;
cursor: pointer; cursor: pointer;
transition: all 0.2s ease; transition: all 0.25s ease;
padding: 12px 16px 14px; padding: 16px 18px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-height: 150px; height: 160px;
&:hover { &:hover {
border-color: #07c05f; border-color: #07c05f;
box-shadow: 0 4px 12px rgba(7, 192, 95, 0.12);
} }
&.uninitialized { &.uninitialized {
@@ -731,12 +723,12 @@ const handleUploadFinishedEvent = (event: Event) => {
&.kb-type-document { &.kb-type-document {
background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%); background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);
border-color: #e8f5ed; border-color: #e8f5ed;
&:hover { &:hover {
border-color: #07c05f; border-color: #07c05f;
background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%); background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
} }
// 右上角装饰 // 右上角装饰
&::after { &::after {
content: ''; content: '';
@@ -746,7 +738,7 @@ const handleUploadFinishedEvent = (event: Event) => {
width: 60px; width: 60px;
height: 60px; height: 60px;
background: linear-gradient(135deg, rgba(7, 192, 95, 0.08) 0%, transparent 100%); background: linear-gradient(135deg, rgba(7, 192, 95, 0.08) 0%, transparent 100%);
border-radius: 0 6px 0 100%; border-radius: 0 12px 0 100%;
pointer-events: none; pointer-events: none;
z-index: 0; z-index: 0;
} }
@@ -756,12 +748,13 @@ const handleUploadFinishedEvent = (event: Event) => {
&.kb-type-faq { &.kb-type-faq {
background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%); background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
border-color: #e6f0ff; border-color: #e6f0ff;
&:hover { &:hover {
border-color: #0052d9; border-color: #0052d9;
box-shadow: 0 4px 12px rgba(0, 82, 217, 0.12);
background: linear-gradient(135deg, #ffffff 0%, #eff6ff 100%); background: linear-gradient(135deg, #ffffff 0%, #eff6ff 100%);
} }
// 右上角装饰 // 右上角装饰
&::after { &::after {
content: ''; content: '';
@@ -771,7 +764,7 @@ const handleUploadFinishedEvent = (event: Event) => {
width: 60px; width: 60px;
height: 60px; height: 60px;
background: linear-gradient(135deg, rgba(0, 82, 217, 0.08) 0%, transparent 100%); background: linear-gradient(135deg, rgba(0, 82, 217, 0.08) 0%, transparent 100%);
border-radius: 0 6px 0 100%; border-radius: 0 12px 0 100%;
pointer-events: none; pointer-events: none;
z-index: 0; z-index: 0;
} }
@@ -790,42 +783,46 @@ const handleUploadFinishedEvent = (event: Event) => {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 8px; margin-bottom: 10px;
} }
.card-title { .card-title {
color: #000000e6; color: #1a1a1a;
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 14px; font-size: 15px;
font-weight: 600; font-weight: 600;
line-height: 22px; line-height: 22px;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
flex: 1; flex: 1;
margin-right: 8px; min-width: 0;
} }
.more-wrap { .more-wrap {
display: flex; display: flex;
width: 32px; width: 28px;
height: 32px; height: 28px;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
border-radius: 6px; border-radius: 6px;
cursor: pointer; cursor: pointer;
flex-shrink: 0; flex-shrink: 0;
transition: all 0.2s ease; transition: all 0.2s ease;
opacity: 0.7; opacity: 0;
.kb-card:hover & {
opacity: 0.6;
}
&:hover { &:hover {
background: rgba(0, 0, 0, 0.06); background: rgba(0, 0, 0, 0.05);
opacity: 1; opacity: 1 !important;
} }
&.active-more { &.active-more {
background: rgba(0, 0, 0, 0.08); background: rgba(0, 0, 0, 0.06);
opacity: 1; opacity: 1 !important;
} }
.more-icon { .more-icon {
@@ -836,7 +833,8 @@ const handleUploadFinishedEvent = (event: Event) => {
.card-content { .card-content {
flex: 1; flex: 1;
margin-bottom: 10px; margin-bottom: 12px;
overflow: hidden;
} }
.card-description { .card-description {
@@ -845,21 +843,20 @@ const handleUploadFinishedEvent = (event: Event) => {
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
line-clamp: 2; line-clamp: 2;
overflow: hidden; overflow: hidden;
color: #00000066; color: #666;
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 12px; font-size: 13px;
font-weight: 400; font-weight: 400;
line-height: 20px; line-height: 20px;
min-height: 40px;
} }
.card-bottom { .card-bottom {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 8px 0 0;
border-top: 1px solid #f0f0f0;
margin-top: auto; margin-top: auto;
padding-top: 12px;
border-top: 1px solid #f0f0f0;
} }
.bottom-left { .bottom-left {
@@ -868,88 +865,90 @@ const handleUploadFinishedEvent = (event: Event) => {
gap: 8px; gap: 8px;
} }
.type-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 10px;
border-radius: 4px;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 500;
line-height: 18px;
&.document {
background: rgba(7, 192, 95, 0.1);
color: #059669;
border: 1px solid rgba(7, 192, 95, 0.2);
}
&.faq {
background: rgba(0, 82, 217, 0.1);
color: #0052d9;
border: 1px solid rgba(0, 82, 217, 0.2);
}
.processing-icon {
animation: spin 1s linear infinite;
margin-left: 4px;
}
&.document .processing-icon {
color: #059669;
}
&.faq .processing-icon {
color: #0052d9;
}
}
.feature-badges { .feature-badges {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 6px; gap: 4px;
} }
.feature-badge { .feature-badge {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 24px; width: 26px;
height: 24px; height: 26px;
border-radius: 4px; border-radius: 6px;
cursor: pointer; cursor: default;
transition: background 0.2s ease;
&.kg { &.type-document {
background: rgba(124, 77, 255, 0.1); background: rgba(7, 192, 95, 0.08);
color: #7c4dff; color: #059669;
border: 1px solid rgba(124, 77, 255, 0.2); width: auto;
padding: 0 8px;
gap: 4px;
&:hover { &:hover {
background: rgba(124, 77, 255, 0.15); background: rgba(7, 192, 95, 0.12);
}
.badge-count {
font-size: 12px;
font-weight: 500;
}
.processing-icon {
animation: spin 1s linear infinite;
}
}
&.type-faq {
background: rgba(0, 82, 217, 0.08);
color: #0052d9;
width: auto;
padding: 0 8px;
gap: 4px;
&:hover {
background: rgba(0, 82, 217, 0.12);
}
.badge-count {
font-size: 12px;
font-weight: 500;
}
.processing-icon {
animation: spin 1s linear infinite;
}
}
&.kg {
background: rgba(124, 77, 255, 0.08);
color: #7c4dff;
&:hover {
background: rgba(124, 77, 255, 0.12);
} }
} }
&.multimodal { &.multimodal {
background: rgba(255, 152, 0, 0.1); background: rgba(255, 152, 0, 0.08);
color: #ff9800; color: #f59e0b;
border: 1px solid rgba(255, 152, 0, 0.2);
&:hover { &:hover {
background: rgba(255, 152, 0, 0.15); background: rgba(255, 152, 0, 0.12);
} }
} }
&.question { &.question {
background: rgba(0, 150, 136, 0.1); background: rgba(0, 150, 136, 0.08);
color: #009688; color: #009688;
border: 1px solid rgba(0, 150, 136, 0.2);
&:hover { &:hover {
background: rgba(0, 150, 136, 0.15); background: rgba(0, 150, 136, 0.12);
} }
} }
} }
@keyframes spin { @keyframes spin {
@@ -986,7 +985,7 @@ const handleUploadFinishedEvent = (event: Event) => {
} }
.card-time { .card-time {
color: #00000066; color: #999;
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 12px; font-size: 12px;
font-weight: 400; font-weight: 400;
-17
View File
@@ -89,11 +89,6 @@
<OllamaSettings /> <OllamaSettings />
</div> </div>
<!-- Agent 配置 -->
<div v-if="currentSection === 'agent'" class="section">
<AgentSettings :active-sub-section="currentSubSection || 'modes'" />
</div>
<!-- 网络搜索配置 --> <!-- 网络搜索配置 -->
<div v-if="currentSection === 'websearch'" class="section"> <div v-if="currentSection === 'websearch'" class="section">
<WebSearchSettings /> <WebSearchSettings />
@@ -132,7 +127,6 @@ import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { useUIStore } from '@/stores/ui' import { useUIStore } from '@/stores/ui'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import AgentSettings from './AgentSettings.vue'
import SystemInfo from './SystemInfo.vue' import SystemInfo from './SystemInfo.vue'
import TenantInfo from './TenantInfo.vue' import TenantInfo from './TenantInfo.vue'
import ApiInfo from './ApiInfo.vue' import ApiInfo from './ApiInfo.vue'
@@ -165,17 +159,6 @@ const navItems = computed(() => [
] ]
}, },
{ key: 'ollama', icon: 'server', label: 'Ollama' }, { key: 'ollama', icon: 'server', label: 'Ollama' },
{
key: 'agent',
icon: 'chat',
label: t('settings.conversationStrategy'),
children: [
{ key: 'modes', label: t('conversationSettings.menus.modes') },
{ key: 'models', label: t('conversationSettings.menus.models') },
{ key: 'thresholds', label: t('conversationSettings.menus.thresholds') },
{ key: 'advanced', label: t('conversationSettings.menus.advanced') },
]
},
{ key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') }, { key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },
{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') }, { key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
{ key: 'system', icon: 'info-circle', label: t('settings.systemSettings') }, { key: 'system', icon: 'info-circle', label: t('settings.systemSettings') },
+14 -16
View File
@@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"time" "time"
"github.com/Tencent/WeKnora/internal/types"
) )
// formatFileSize formats file size in human-readable format // formatFileSize formats file size in human-readable format
@@ -78,6 +80,7 @@ type KnowledgeBaseInfo struct {
} }
// PlaceholderDefinition defines a placeholder exposed to UI/configuration // PlaceholderDefinition defines a placeholder exposed to UI/configuration
// Deprecated: Use types.PromptPlaceholder instead
type PlaceholderDefinition struct { type PlaceholderDefinition struct {
Name string `json:"name"` Name string `json:"name"`
Label string `json:"label"` Label string `json:"label"`
@@ -85,24 +88,19 @@ type PlaceholderDefinition struct {
} }
// AvailablePlaceholders lists all supported prompt placeholders for UI hints // AvailablePlaceholders lists all supported prompt placeholders for UI hints
// This returns agent mode specific placeholders
func AvailablePlaceholders() []PlaceholderDefinition { func AvailablePlaceholders() []PlaceholderDefinition {
return []PlaceholderDefinition{ // Use centralized placeholder definitions from types package
{ placeholders := types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt)
Name: "knowledge_bases", result := make([]PlaceholderDefinition, len(placeholders))
Label: "知识库列表", for i, p := range placeholders {
Description: "自动格式化为表格形式的知识库列表,包含知识库名称、描述、文档数量、最近添加的文档等信息", result[i] = PlaceholderDefinition{
}, Name: p.Name,
{ Label: p.Label,
Name: "web_search_status", Description: p.Description,
Label: "网络检索模式开关状态", }
Description: "网络检索(web_search)工具是否启用的状态说明,值为 Enabled 或 Disabled",
},
{
Name: "current_time",
Label: "当前系统时间",
Description: "格式为 RFC3339 的当前系统时间,用于帮助模型感知实时性",
},
} }
return result
} }
// formatKnowledgeBaseList formats knowledge base information for the prompt // formatKnowledgeBaseList formats knowledge base information for the prompt
@@ -57,6 +57,6 @@ func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.Cu
} }
// DeleteAgent deletes an agent (soft delete) // DeleteAgent deletes an agent (soft delete)
func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string) error { func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string, tenantID uint64) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.CustomAgent{}).Error return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.CustomAgent{}).Error
} }
+41 -15
View File
@@ -101,25 +101,51 @@ func (s *agentService) CreateAgentEngine(
tenantID = tid tenantID = tid
} }
if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil { if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil {
// Get enabled MCP services for this tenant // Check MCP selection mode from agent config
mcpServices, err := s.mcpServiceService.ListMCPServices(ctx, tenantID) mcpMode := config.MCPSelectionMode
if err != nil { if mcpMode == "" {
logger.Warnf(ctx, "Failed to list MCP services: %v", err) mcpMode = "all" // Default to all enabled MCP services
}
// Skip MCP registration if mode is "none"
if mcpMode == "none" {
logger.Infof(ctx, "MCP services disabled by agent config (mode: none)")
} else { } else {
// Filter enabled services var mcpServices []*types.MCPService
enabledServices := make([]*types.MCPService, 0) var err error
for _, svc := range mcpServices {
if svc != nil && svc.Enabled { if mcpMode == "selected" && len(config.MCPServices) > 0 {
enabledServices = append(enabledServices, svc) // Get only selected MCP services
mcpServices, err = s.mcpServiceService.ListMCPServicesByIDs(ctx, tenantID, config.MCPServices)
if err != nil {
logger.Warnf(ctx, "Failed to list selected MCP services: %v", err)
} else {
logger.Infof(ctx, "Using %d selected MCP services from agent config", len(mcpServices))
}
} else {
// Get all MCP services for this tenant
mcpServices, err = s.mcpServiceService.ListMCPServices(ctx, tenantID)
if err != nil {
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
} }
} }
// Register MCP tools if err == nil && len(mcpServices) > 0 {
if len(enabledServices) > 0 { // Filter enabled services
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil { enabledServices := make([]*types.MCPService, 0)
logger.Warnf(ctx, "Failed to register MCP tools: %v", err) for _, svc := range mcpServices {
} else { if svc != nil && svc.Enabled {
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices)) enabledServices = append(enabledServices, svc)
}
}
// Register MCP tools
if len(enabledServices) > 0 {
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
} else {
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
}
} }
} }
} }
@@ -60,13 +60,8 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
{Role: "system", Content: systemPrompt}, {Role: "system", Content: systemPrompt},
} }
chatHistory := chatManage.History // Add conversation history (already limited by maxRounds in load_history/rewrite plugins)
if len(chatHistory) > 2 { for _, history := range chatManage.History {
chatHistory = chatHistory[len(chatHistory)-2:]
}
// Add conversation history
for _, history := range chatHistory {
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query}) chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query})
chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer}) chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer})
} }
@@ -0,0 +1,126 @@
// Package chatpipline provides chat pipeline processing capabilities
package chatpipline
import (
"context"
"regexp"
"slices"
"sort"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginLoadHistory is a plugin for loading conversation history without query rewriting
// It loads historical dialog context for multi-turn conversations
type PluginLoadHistory struct {
messageService interfaces.MessageService // Message service for retrieving historical messages
config *config.Config // System configuration
}
// regThink is a regular expression used to match and remove content between <think></think> tags
var regThink = regexp.MustCompile(`(?s)<think>.*?</think>`)
// NewPluginLoadHistory creates a new history loading plugin instance
// Also registers the plugin with the event manager
func NewPluginLoadHistory(eventManager *EventManager,
messageService interfaces.MessageService,
config *config.Config,
) *PluginLoadHistory {
res := &PluginLoadHistory{
messageService: messageService,
config: config,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the list of event types this plugin responds to
// This plugin only responds to LOAD_HISTORY events
func (p *PluginLoadHistory) ActivationEvents() []types.EventType {
return []types.EventType{types.LOAD_HISTORY}
}
// OnEvent processes triggered events
// When receiving a LOAD_HISTORY event, it loads conversation history without rewriting the query
func (p *PluginLoadHistory) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Determine max rounds from config or request
maxRounds := p.config.Conversation.MaxRounds
if chatManage.MaxRounds > 0 {
maxRounds = chatManage.MaxRounds
}
pipelineInfo(ctx, "LoadHistory", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"max_rounds": maxRounds,
})
// Get conversation history (fetch more to account for incomplete pairs)
history, err := p.messageService.GetRecentMessagesBySession(ctx, chatManage.SessionID, maxRounds*2+10)
if err != nil {
pipelineWarn(ctx, "LoadHistory", "history_fetch", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
pipelineInfo(ctx, "LoadHistory", "fetched", map[string]interface{}{
"session_id": chatManage.SessionID,
"message_count": len(history),
})
// Convert historical messages to conversation history structure
historyMap := make(map[string]*types.History)
// Process historical messages, grouped by requestID
for _, message := range history {
h, ok := historyMap[message.RequestID]
if !ok {
h = &types.History{}
}
if message.Role == "user" {
// User message as query
h.Query = message.Content
h.CreateAt = message.CreatedAt
} else {
// System message as answer, while removing thinking process
h.Answer = regThink.ReplaceAllString(message.Content, "")
h.KnowledgeReferences = message.KnowledgeReferences
}
historyMap[message.RequestID] = h
}
// Convert to list and filter incomplete conversations
historyList := make([]*types.History, 0)
for _, h := range historyMap {
if h.Answer != "" && h.Query != "" {
historyList = append(historyList, h)
}
}
// Sort by time, keep the most recent conversations
sort.Slice(historyList, func(i, j int) bool {
return historyList[i].CreateAt.After(historyList[j].CreateAt)
})
// Limit the number of historical records
if len(historyList) > maxRounds {
historyList = historyList[:maxRounds]
}
// Reverse to chronological order
slices.Reverse(historyList)
chatManage.History = historyList
pipelineInfo(ctx, "LoadHistory", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"history_rounds": len(historyList),
"max_rounds": maxRounds,
})
return next()
}
@@ -3,12 +3,11 @@
package chatpipline package chatpipline
import ( import (
"bytes"
"context" "context"
"html/template"
"regexp" "regexp"
"slices" "slices"
"sort" "sort"
"strings"
"time" "time"
"github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/config"
@@ -144,54 +143,27 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
if chatManage.RewritePromptUser != "" { if chatManage.RewritePromptUser != "" {
userPrompt = chatManage.RewritePromptUser userPrompt = chatManage.RewritePromptUser
} }
userTmpl, err := template.New("rewriteContent").Parse(userPrompt)
if err != nil {
pipelineError(ctx, "Rewrite", "parse_user_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
systemPrompt := p.config.Conversation.RewritePromptSystem systemPrompt := p.config.Conversation.RewritePromptSystem
if chatManage.RewritePromptSystem != "" { if chatManage.RewritePromptSystem != "" {
systemPrompt = chatManage.RewritePromptSystem systemPrompt = chatManage.RewritePromptSystem
} }
systemTmpl, err := template.New("rewriteContent").Parse(systemPrompt)
if err != nil { // Format conversation history for template
pipelineError(ctx, "Rewrite", "parse_system_template", map[string]interface{}{ conversationText := formatConversationHistory(historyList)
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
currentTime := time.Now().Format("2006-01-02 15:04:05") currentTime := time.Now().Format("2006-01-02 15:04:05")
var userContent, systemContent bytes.Buffer yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
err = userTmpl.Execute(&userContent, map[string]interface{}{
"Query": chatManage.Query, // Replace placeholders in prompts
"CurrentTime": currentTime, userContent := strings.ReplaceAll(userPrompt, "{{conversation}}", conversationText)
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"), userContent = strings.ReplaceAll(userContent, "{{query}}", chatManage.Query)
"Conversation": historyList, userContent = strings.ReplaceAll(userContent, "{{current_time}}", currentTime)
}) userContent = strings.ReplaceAll(userContent, "{{yesterday}}", yesterday)
if err != nil {
pipelineError(ctx, "Rewrite", "render_user_template", map[string]interface{}{ systemContent := strings.ReplaceAll(systemPrompt, "{{conversation}}", conversationText)
"session_id": chatManage.SessionID, systemContent = strings.ReplaceAll(systemContent, "{{query}}", chatManage.Query)
"error": err.Error(), systemContent = strings.ReplaceAll(systemContent, "{{current_time}}", currentTime)
}) systemContent = strings.ReplaceAll(systemContent, "{{yesterday}}", yesterday)
return next()
}
err = systemTmpl.Execute(&systemContent, map[string]interface{}{
"Query": chatManage.Query,
"CurrentTime": currentTime,
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
"Conversation": historyList,
})
if err != nil {
pipelineError(ctx, "Rewrite", "render_system_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID) rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil { if err != nil {
pipelineError(ctx, "Rewrite", "get_model", map[string]interface{}{ pipelineError(ctx, "Rewrite", "get_model", map[string]interface{}{
@@ -207,11 +179,11 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
response, err := rewriteModel.Chat(ctx, []chat.Message{ response, err := rewriteModel.Chat(ctx, []chat.Message{
{ {
Role: "system", Role: "system",
Content: systemContent.String(), Content: systemContent,
}, },
{ {
Role: "user", Role: "user",
Content: userContent.String(), Content: userContent,
}, },
}, &chat.ChatOptions{ }, &chat.ChatOptions{
Temperature: 0.3, Temperature: 0.3,
@@ -236,3 +208,21 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
}) })
return next() return next()
} }
// formatConversationHistory formats conversation history for prompt template
func formatConversationHistory(historyList []*types.History) string {
if len(historyList) == 0 {
return ""
}
var builder strings.Builder
for _, h := range historyList {
builder.WriteString("------BEGIN------\n")
builder.WriteString("用户的问题是:")
builder.WriteString(h.Query)
builder.WriteString("\n助手的回答是:")
builder.WriteString(h.Answer)
builder.WriteString("\n------END------\n")
}
return builder.String()
}
+88 -54
View File
@@ -56,9 +56,9 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
agent.CreatedAt = time.Now() agent.CreatedAt = time.Now()
agent.UpdatedAt = time.Now() agent.UpdatedAt = time.Now()
// Ensure custom type for user-created agents // Ensure agent mode is set for user-created agents
if agent.Type == "" { if agent.Config.AgentMode == "" {
agent.Type = types.CustomAgentTypeCustom agent.Config.AgentMode = types.AgentModeQuickAnswer
} }
// Cannot create built-in agents // Cannot create built-in agents
@@ -67,8 +67,8 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
// Set defaults // Set defaults
agent.EnsureDefaults() agent.EnsureDefaults()
logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, type: %s", logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s",
agent.ID, agent.TenantID, agent.Name, agent.Type) agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode)
if err := s.repo.CreateAgent(ctx, agent); err != nil { if err := s.repo.CreateAgent(ctx, agent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{ logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -95,19 +95,18 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
return nil, ErrInvalidTenantID return nil, ErrInvalidTenantID
} }
// Check if it's a built-in agent // Check if it's a built-in agent using the registry
if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID { if types.IsBuiltinAgentID(id) {
// Try to get from database first (for customized config) // Try to get from database first (for customized config)
agent, err := s.repo.GetAgentByID(ctx, id, tenantID) agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err == nil { if err == nil {
// Found in database, return with customized config // Found in database, return with customized config
return agent, nil return agent, nil
} }
// Not in database, return default built-in agent // Not in database, return default built-in agent from registry
if id == types.BuiltinAgentNormalID { if builtinAgent := types.GetBuiltinAgent(id, tenantID); builtinAgent != nil {
return types.GetBuiltinNormalAgent(tenantID), nil return builtinAgent, nil
} }
return types.GetBuiltinAgentAgent(tenantID), nil
} }
// Query from database // Query from database
@@ -141,48 +140,39 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge
return nil, err return nil, err
} }
// Check if built-in agents exist in database // Track which built-in agents exist in database
hasNormalBuiltin := false builtinInDB := make(map[string]bool)
hasAgentBuiltin := false
for _, agent := range allAgents { for _, agent := range allAgents {
if agent.ID == types.BuiltinAgentNormalID { if types.IsBuiltinAgentID(agent.ID) {
hasNormalBuiltin = true builtinInDB[agent.ID] = true
}
if agent.ID == types.BuiltinAgentAgentID {
hasAgentBuiltin = true
} }
} }
// Build result: built-in agents first, then custom agents // Build result: built-in agents first, then custom agents
result := make([]*types.CustomAgent, 0, len(allAgents)+2) builtinIDs := types.GetBuiltinAgentIDs()
result := make([]*types.CustomAgent, 0, len(allAgents)+len(builtinIDs))
// Add built-in normal agent // Add built-in agents in order
if hasNormalBuiltin { for _, builtinID := range builtinIDs {
for _, agent := range allAgents { if builtinInDB[builtinID] {
if agent.ID == types.BuiltinAgentNormalID { // Use customized config from database
for _, agent := range allAgents {
if agent.ID == builtinID {
result = append(result, agent)
break
}
}
} else {
// Use default built-in agent
if agent := types.GetBuiltinAgent(builtinID, tenantID); agent != nil {
result = append(result, agent) result = append(result, agent)
break
} }
} }
} else {
result = append(result, types.GetBuiltinNormalAgent(tenantID))
}
// Add built-in agent mode agent
if hasAgentBuiltin {
for _, agent := range allAgents {
if agent.ID == types.BuiltinAgentAgentID {
result = append(result, agent)
break
}
}
} else {
result = append(result, types.GetBuiltinAgentAgent(tenantID))
} }
// Add custom agents // Add custom agents
for _, agent := range allAgents { for _, agent := range allAgents {
if agent.ID != types.BuiltinAgentNormalID && agent.ID != types.BuiltinAgentAgentID { if !types.IsBuiltinAgentID(agent.ID) {
result = append(result, agent) result = append(result, agent)
} }
} }
@@ -203,9 +193,8 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
return nil, ErrInvalidTenantID return nil, ErrInvalidTenantID
} }
// Handle built-in agents specially // Handle built-in agents specially using registry
isBuiltinAgent := agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID if types.IsBuiltinAgentID(agent.ID) {
if isBuiltinAgent {
return s.updateBuiltinAgent(ctx, agent, tenantID) return s.updateBuiltinAgent(ctx, agent, tenantID)
} }
@@ -232,7 +221,6 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
existingAgent.Name = agent.Name existingAgent.Name = agent.Name
existingAgent.Description = agent.Description existingAgent.Description = agent.Description
existingAgent.Avatar = agent.Avatar existingAgent.Avatar = agent.Avatar
existingAgent.Type = agent.Type
existingAgent.Config = agent.Config existingAgent.Config = agent.Config
existingAgent.UpdatedAt = time.Now() existingAgent.UpdatedAt = time.Now()
@@ -254,12 +242,10 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
// updateBuiltinAgent updates a built-in agent's configuration (but not basic info) // updateBuiltinAgent updates a built-in agent's configuration (but not basic info)
func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) { func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) {
// Get the default built-in agent // Get the default built-in agent from registry
var defaultAgent *types.CustomAgent defaultAgent := types.GetBuiltinAgent(agent.ID, tenantID)
if agent.ID == types.BuiltinAgentNormalID { if defaultAgent == nil {
defaultAgent = types.GetBuiltinNormalAgent(tenantID) return nil, ErrAgentNotFound
} else {
defaultAgent = types.GetBuiltinAgentAgent(tenantID)
} }
// Try to get existing customized config from database // Try to get existing customized config from database
@@ -294,7 +280,6 @@ func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *type
Description: defaultAgent.Description, Description: defaultAgent.Description,
Avatar: defaultAgent.Avatar, Avatar: defaultAgent.Avatar,
IsBuiltin: true, IsBuiltin: true,
Type: defaultAgent.Type,
TenantID: tenantID, TenantID: tenantID,
Config: agent.Config, Config: agent.Config,
CreatedAt: time.Now(), CreatedAt: time.Now(),
@@ -323,8 +308,8 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
return errors.New("agent ID cannot be empty") return errors.New("agent ID cannot be empty")
} }
// Cannot delete built-in agents // Cannot delete built-in agents using registry check
if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID { if types.IsBuiltinAgentID(id) {
return ErrCannotDeleteBuiltin return ErrCannotDeleteBuiltin
} }
@@ -350,7 +335,7 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
logger.Infof(ctx, "Deleting custom agent, ID: %s", id) logger.Infof(ctx, "Deleting custom agent, ID: %s", id)
if err := s.repo.DeleteAgent(ctx, id); err != nil { if err := s.repo.DeleteAgent(ctx, id, tenantID); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{ logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id, "agent_id": id,
}) })
@@ -360,3 +345,52 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id) logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id)
return nil return nil
} }
// CopyAgent creates a copy of an existing agent
func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error) {
if id == "" {
logger.Error(ctx, "Agent ID is empty")
return nil, errors.New("agent ID cannot be empty")
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Get the source agent
sourceAgent, err := s.GetAgentByID(ctx, id)
if err != nil {
return nil, err
}
// Create a new agent with copied data
newAgent := &types.CustomAgent{
ID: uuid.New().String(),
Name: sourceAgent.Name + " (副本)",
Description: sourceAgent.Description,
Avatar: sourceAgent.Avatar,
IsBuiltin: false, // Copied agents are never built-in
TenantID: tenantID,
Config: sourceAgent.Config,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// Ensure defaults
newAgent.EnsureDefaults()
logger.Infof(ctx, "Copying agent, source ID: %s, new ID: %s", id, newAgent.ID)
if err := s.repo.CreateAgent(ctx, newAgent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"source_agent_id": id,
"new_agent_id": newAgent.ID,
})
return nil, err
}
logger.Infof(ctx, "Agent copied successfully, source ID: %s, new ID: %s", id, newAgent.ID)
return newAgent, nil
}
+8 -8
View File
@@ -1956,10 +1956,10 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
} }
// Replace placeholders // Replace placeholders
prompt = strings.ReplaceAll(prompt, "{{.QuestionCount}}", fmt.Sprintf("%d", questionCount)) prompt = strings.ReplaceAll(prompt, "{{question_count}}", fmt.Sprintf("%d", questionCount))
prompt = strings.ReplaceAll(prompt, "{{.Content}}", content) prompt = strings.ReplaceAll(prompt, "{{content}}", content)
prompt = strings.ReplaceAll(prompt, "{{.Context}}", contextSection) prompt = strings.ReplaceAll(prompt, "{{context}}", contextSection)
prompt = strings.ReplaceAll(prompt, "{{.DocName}}", docName) prompt = strings.ReplaceAll(prompt, "{{doc_name}}", docName)
thinking := false thinking := false
response, err := chatModel.Chat(ctx, []chat.Message{ response, err := chatModel.Chat(ctx, []chat.Message{
@@ -2000,11 +2000,11 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
// Default prompt for question generation with context support // Default prompt for question generation with context support
const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。 const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
{{.Context}} {{context}}
## 主要内容(请基于此内容生成问题) ## 主要内容(请基于此内容生成问题)
文档名称:{{.DocName}} 文档名称:{{doc_name}}
文档内容: 文档内容:
{{.Content}} {{content}}
## 核心要求 ## 核心要求
- 生成的问题必须与【主要内容】直接相关 - 生成的问题必须与【主要内容】直接相关
@@ -2013,7 +2013,7 @@ const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手
- 问题应该是用户在实际场景中可能会提出的自然问题 - 问题应该是用户在实际场景中可能会提出的自然问题
- 问题应该多样化,覆盖内容的不同方面 - 问题应该多样化,覆盖内容的不同方面
- 每个问题应该简洁明了,长度控制在30字以内 - 每个问题应该简洁明了,长度控制在30字以内
- 生成的问题数量为 {{.QuestionCount}} 个 - 生成的问题数量为 {{question_count}} 个
## 问题类型建议 ## 问题类型建议
- 定义类:什么是...?...是什么? - 定义类:什么是...?...是什么?
+21 -19
View File
@@ -1,13 +1,11 @@
package service package service
import ( import (
"bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
"text/template"
"github.com/Tencent/WeKnora/internal/agent" "github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/tools" "github.com/Tencent/WeKnora/internal/agent/tools"
@@ -271,7 +269,7 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
if model == nil { if model == nil {
continue continue
} }
if model.Type == types.ModelTypeKnowledgeQA { if model.Type == types.ModelTypeKnowledgeQA {
modelID = model.ID modelID = model.ID
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID) logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID)
break break
@@ -469,6 +467,11 @@ func (s *sessionService) KnowledgeQA(
// Ensure defaults are set // Ensure defaults are set
customAgent.EnsureDefaults() customAgent.EnsureDefaults()
// Override model ID
if customAgent.Config.ModelID != "" {
chatModelID = customAgent.Config.ModelID
logger.Infof(ctx, "Using custom agent's model_id: %s", chatModelID)
}
// Override system prompt // Override system prompt
if customAgent.Config.SystemPrompt != "" { if customAgent.Config.SystemPrompt != "" {
summaryConfig.Prompt = customAgent.Config.SystemPrompt summaryConfig.Prompt = customAgent.Config.SystemPrompt
@@ -588,10 +591,18 @@ func (s *sessionService) KnowledgeQA(
// Otherwise use rag_stream pipeline (which handles both KB search and web search) // Otherwise use rag_stream pipeline (which handles both KB search and web search)
var pipeline []types.EventType var pipeline []types.EventType
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && !webSearchEnabled { if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && !webSearchEnabled {
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat_stream pipeline") logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat pipeline")
pipeline = types.Pipline["chat_stream"]
// For pure chat, UserContent is the Query (since INTO_CHAT_MESSAGE is skipped) // For pure chat, UserContent is the Query (since INTO_CHAT_MESSAGE is skipped)
chatManage.UserContent = query chatManage.UserContent = query
// Use chat_history_stream if multi-turn is enabled, otherwise use chat_stream
if maxRounds > 0 {
logger.Infof(ctx, "Multi-turn enabled with maxRounds=%d, using chat_history_stream pipeline", maxRounds)
pipeline = types.Pipline["chat_history_stream"]
} else {
logger.Info(ctx, "Multi-turn disabled, using chat_stream pipeline")
pipeline = types.Pipline["chat_stream"]
}
} else { } else {
if webSearchEnabled && len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 { if webSearchEnabled && len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 {
logger.Info(ctx, "Web search enabled without knowledge bases, using rag_stream pipeline for web search only") logger.Info(ctx, "Web search enabled without knowledge bases, using rag_stream pipeline for web search only")
@@ -1057,6 +1068,8 @@ func (s *sessionService) AgentQA(
MultiTurnEnabled: customAgent.Config.MultiTurnEnabled, MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,
HistoryTurns: customAgent.Config.HistoryTurns, HistoryTurns: customAgent.Config.HistoryTurns,
KnowledgeBases: customAgent.Config.KnowledgeBases, KnowledgeBases: customAgent.Config.KnowledgeBases,
MCPSelectionMode: customAgent.Config.MCPSelectionMode,
MCPServices: customAgent.Config.MCPServices,
} }
// Use custom agent's allowed tools if specified, otherwise use defaults // Use custom agent's allowed tools if specified, otherwise use defaults
@@ -1442,20 +1455,9 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty
// renderFallbackPrompt renders the fallback prompt template with Query variable // renderFallbackPrompt renders the fallback prompt template with Query variable
func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *types.ChatManage) (string, error) { func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *types.ChatManage) (string, error) {
tmpl, err := template.New("fallbackPrompt").Parse(chatManage.FallbackPrompt) // Use simple string replacement instead of Go template
if err != nil { result := strings.ReplaceAll(chatManage.FallbackPrompt, "{{query}}", chatManage.Query)
return "", fmt.Errorf("failed to parse template: %w", err) return result, nil
}
var promptContent bytes.Buffer
err = tmpl.Execute(&promptContent, map[string]interface{}{
"Query": chatManage.Query,
})
if err != nil {
return "", fmt.Errorf("failed to execute template: %w", err)
}
return promptContent.String(), nil
} }
// consumeFallbackStream consumes the streaming response and emits events // consumeFallbackStream consumes the streaming response and emits events
+1
View File
@@ -145,6 +145,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(chatpipline.NewPluginStreamFilter)) must(container.Invoke(chatpipline.NewPluginStreamFilter))
must(container.Invoke(chatpipline.NewPluginFilterTopK)) must(container.Invoke(chatpipline.NewPluginFilterTopK))
must(container.Invoke(chatpipline.NewPluginRewrite)) must(container.Invoke(chatpipline.NewPluginRewrite))
must(container.Invoke(chatpipline.NewPluginLoadHistory))
must(container.Invoke(chatpipline.NewPluginExtractEntity)) must(container.Invoke(chatpipline.NewPluginExtractEntity))
must(container.Invoke(chatpipline.NewPluginSearchEntity)) must(container.Invoke(chatpipline.NewPluginSearchEntity))
must(container.Invoke(chatpipline.NewPluginSearchParallel)) must(container.Invoke(chatpipline.NewPluginSearchParallel))
+79 -6
View File
@@ -29,7 +29,6 @@ type CreateAgentRequest struct {
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
Description string `json:"description"` Description string `json:"description"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
Type types.CustomAgentType `json:"type"`
Config types.CustomAgentConfig `json:"config"` Config types.CustomAgentConfig `json:"config"`
} }
@@ -38,7 +37,6 @@ type UpdateAgentRequest struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
Type types.CustomAgentType `json:"type"`
Config types.CustomAgentConfig `json:"config"` Config types.CustomAgentConfig `json:"config"`
} }
@@ -72,12 +70,11 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
Name: req.Name, Name: req.Name,
Description: req.Description, Description: req.Description,
Avatar: req.Avatar, Avatar: req.Avatar,
Type: req.Type,
Config: req.Config, Config: req.Config,
} }
logger.Infof(ctx, "Creating custom agent, name: %s, type: %s", logger.Infof(ctx, "Creating custom agent, name: %s, agent_mode: %s",
secutils.SanitizeForLog(req.Name), req.Type) secutils.SanitizeForLog(req.Name), req.Config.AgentMode)
// Create agent using the service // Create agent using the service
createdAgent, err := h.service.CreateAgent(ctx, agent) createdAgent, err := h.service.CreateAgent(ctx, agent)
@@ -211,7 +208,6 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
Name: req.Name, Name: req.Name,
Description: req.Description, Description: req.Description,
Avatar: req.Avatar, Avatar: req.Avatar,
Type: req.Type,
Config: req.Config, Config: req.Config,
} }
@@ -296,3 +292,80 @@ func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) {
"message": "Agent deleted successfully", "message": "Agent deleted successfully",
}) })
} }
// CopyAgent godoc
// @Summary 复制智能体
// @Description 复制指定的智能体
// @Tags 智能体
// @Accept json
// @Produce json
// @Param id path string true "智能体ID"
// @Success 201 {object} map[string]interface{} "复制成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "智能体不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/{id}/copy [post]
func (h *CustomAgentHandler) CopyAgent(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start copying custom agent")
// Get agent ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Agent ID is empty")
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
return
}
logger.Infof(ctx, "Copying custom agent, ID: %s", secutils.SanitizeForLog(id))
// Copy the agent
copiedAgent, err := h.service.CopyAgent(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
switch err {
case service.ErrAgentNotFound:
c.Error(errors.NewNotFoundError("Agent not found"))
default:
c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
logger.Infof(ctx, "Custom agent copied successfully, source ID: %s, new ID: %s",
secutils.SanitizeForLog(id), secutils.SanitizeForLog(copiedAgent.ID))
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": copiedAgent,
})
}
// GetPlaceholders godoc
// @Summary 获取占位符定义
// @Description 获取所有可用的提示词占位符定义,按字段类型分组
// @Tags 智能体
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "占位符定义"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/placeholders [get]
func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
// Return all placeholder definitions grouped by field type
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"all": types.AllPlaceholders(),
"system_prompt": types.PlaceholdersByField(types.PromptFieldSystemPrompt),
"agent_system_prompt": types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt),
"context_template": types.PlaceholdersByField(types.PromptFieldContextTemplate),
"rewrite_system_prompt": types.PlaceholdersByField(types.PromptFieldRewriteSystemPrompt),
"rewrite_prompt": types.PlaceholdersByField(types.PromptFieldRewritePrompt),
"fallback_prompt": types.PlaceholdersByField(types.PromptFieldFallbackPrompt),
},
})
}
+2 -2
View File
@@ -81,8 +81,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
secutils.SanitizeForLog(request.AgentID), err) secutils.SanitizeForLog(request.AgentID), err)
} else { } else {
customAgent = agent customAgent = agent
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, Type=%s, AgentMode=%s", logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s",
customAgent.ID, customAgent.Name, customAgent.Type, customAgent.Config.AgentMode) customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode)
} }
} }
+4
View File
@@ -417,6 +417,8 @@ func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSe
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) { func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) {
agents := r.Group("/agents") agents := r.Group("/agents")
{ {
// Get placeholder definitions (must be before /:id to avoid conflict)
agents.GET("/placeholders", agentHandler.GetPlaceholders)
// Create custom agent // Create custom agent
agents.POST("", agentHandler.CreateAgent) agents.POST("", agentHandler.CreateAgent)
// List all agents (including built-in) // List all agents (including built-in)
@@ -427,5 +429,7 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
agents.PUT("/:id", agentHandler.UpdateAgent) agents.PUT("/:id", agentHandler.UpdateAgent)
// Delete agent // Delete agent
agents.DELETE("/:id", agentHandler.DeleteAgent) agents.DELETE("/:id", agentHandler.DeleteAgent)
// Copy agent
agents.POST("/:id/copy", agentHandler.CopyAgent)
} }
} }
+3
View File
@@ -24,6 +24,9 @@ type AgentConfig struct {
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled 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 HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only) SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
// MCP service selection
MCPSelectionMode string `json:"mcp_selection_mode"` // MCP selection mode: "all", "selected", "none"
MCPServices []string `json:"mcp_services"` // Selected MCP service IDs (when mode is "selected")
} }
// SessionAgentConfig represents session-level agent configuration // SessionAgentConfig represents session-level agent configuration
+7 -1
View File
@@ -124,6 +124,7 @@ func (c *ChatManage) Clone() *ChatManage {
type EventType string type EventType string
const ( const (
LOAD_HISTORY EventType = "load_history" // Load conversation history without rewriting
REWRITE_QUERY EventType = "rewrite_query" // Query rewriting for better retrieval REWRITE_QUERY EventType = "rewrite_query" // Query rewriting for better retrieval
CHUNK_SEARCH EventType = "chunk_search" // Search for relevant chunks CHUNK_SEARCH EventType = "chunk_search" // Search for relevant chunks
CHUNK_SEARCH_PARALLEL EventType = "chunk_search_parallel" // Parallel search: chunks + entities CHUNK_SEARCH_PARALLEL EventType = "chunk_search_parallel" // Parallel search: chunks + entities
@@ -142,7 +143,12 @@ var Pipline = map[string][]EventType{
"chat": { // Simple chat without retrieval "chat": { // Simple chat without retrieval
CHAT_COMPLETION, CHAT_COMPLETION,
}, },
"chat_stream": { // Streaming chat without retrieval "chat_stream": { // Streaming chat without retrieval (no history)
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
},
"chat_history_stream": { // Streaming chat with conversation history
LOAD_HISTORY,
CHAT_COMPLETION_STREAM, CHAT_COMPLETION_STREAM,
STREAM_FILTER, STREAM_FILTER,
}, },
+91 -65
View File
@@ -8,27 +8,27 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// CustomAgentType represents the type of the custom agent
type CustomAgentType string
const (
// CustomAgentTypeNormal represents the normal RAG-based chat mode
CustomAgentTypeNormal CustomAgentType = "normal"
// CustomAgentTypeAgent represents the ReAct agent mode with tool calling
CustomAgentTypeAgent CustomAgentType = "agent"
// CustomAgentTypeCustom represents user-defined custom agents
CustomAgentTypeCustom CustomAgentType = "custom"
)
// BuiltinAgentID constants for built-in agents // BuiltinAgentID constants for built-in agents
const ( const (
BuiltinAgentNormalID = "builtin-normal" // BuiltinQuickAnswerID is the ID for the built-in quick answer (RAG) agent
BuiltinAgentAgentID = "builtin-agent" BuiltinQuickAnswerID = "builtin-quick-answer"
// BuiltinSmartReasoningID is the ID for the built-in smart reasoning (ReAct) agent
BuiltinSmartReasoningID = "builtin-smart-reasoning"
)
// AgentMode constants for agent running mode
const (
// AgentModeQuickAnswer is the RAG mode for quick Q&A
AgentModeQuickAnswer = "quick-answer"
// AgentModeSmartReasoning is the ReAct mode for multi-step reasoning
AgentModeSmartReasoning = "smart-reasoning"
) )
// CustomAgent represents a configurable AI agent (similar to GPTs) // CustomAgent represents a configurable AI agent (similar to GPTs)
type CustomAgent struct { type CustomAgent struct {
// Unique identifier of the agent // Unique identifier of the agent (composite primary key with TenantID)
// For built-in agents, this is 'builtin-quick-answer' or 'builtin-smart-reasoning'
// For custom agents, this is a UUID
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"` ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Name of the agent // Name of the agent
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"` Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
@@ -38,10 +38,8 @@ type CustomAgent struct {
Avatar string `yaml:"avatar" json:"avatar" gorm:"type:varchar(64)"` Avatar string `yaml:"avatar" json:"avatar" gorm:"type:varchar(64)"`
// Whether this is a built-in agent (normal mode / agent mode) // Whether this is a built-in agent (normal mode / agent mode)
IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"` IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"`
// Type of the agent: normal, agent, custom // Tenant ID (composite primary key with ID)
Type CustomAgentType `yaml:"type" json:"type" gorm:"type:varchar(32);default:'custom'"` TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"primaryKey"`
// Tenant ID
TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"index"`
// Created by user ID // Created by user ID
CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"` CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"`
@@ -57,7 +55,7 @@ type CustomAgent struct {
// CustomAgentConfig represents the configuration of a custom agent // CustomAgentConfig represents the configuration of a custom agent
type CustomAgentConfig struct { type CustomAgentConfig struct {
// ===== Basic Settings ===== // ===== Basic Settings =====
// Agent mode: "normal" for RAG mode, "agent" for ReAct agent mode // Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent 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 (for normal mode, or agent mode when web search is disabled)
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"` SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
@@ -83,16 +81,16 @@ type CustomAgentConfig struct {
AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"` AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"`
// Whether reflection is enabled (only for agent type) // Whether reflection is enabled (only for agent type)
ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"` ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`
// MCP service selection mode: "all" = all enabled MCP services, "selected" = specific services, "none" = no MCP
MCPSelectionMode string `yaml:"mcp_selection_mode" json:"mcp_selection_mode"`
// Selected MCP service IDs (only used when MCPSelectionMode is "selected")
MCPServices []string `yaml:"mcp_services" json:"mcp_services"`
// ===== Knowledge Base Settings ===== // ===== Knowledge Base Settings =====
// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB // Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"` KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`
// 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"`
// Whether to allow user to select knowledge bases during conversation
// If true, user can select from available KBs (all or selected based on KBSelectionMode)
// If false, the configured KBs are used automatically without user selection
AllowUserKBSelection *bool `yaml:"allow_user_kb_selection" json:"allow_user_kb_selection"`
// ===== Web Search Settings ===== // ===== Web Search Settings =====
// Whether web search is enabled // Whether web search is enabled
@@ -162,9 +160,6 @@ func (a *CustomAgent) EnsureDefaults() {
if a == nil { if a == nil {
return return
} }
if a.Type == "" {
a.Type = CustomAgentTypeCustom
}
if a.Config.Temperature == 0 { if a.Config.Temperature == 0 {
a.Config.Temperature = 0.7 a.Config.Temperature = 0.7
} }
@@ -204,33 +199,33 @@ func (a *CustomAgent) EnsureDefaults() {
// IsAgentMode returns true if this agent uses ReAct agent mode // IsAgentMode returns true if this agent uses ReAct agent mode
func (a *CustomAgent) IsAgentMode() bool { func (a *CustomAgent) IsAgentMode() bool {
return a.Config.AgentMode == "agent" return a.Config.AgentMode == AgentModeSmartReasoning
} }
// GetBuiltinNormalAgent returns the built-in normal mode agent // GetBuiltinQuickAnswerAgent returns the built-in quick answer (RAG) mode agent
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent { func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{ return &CustomAgent{
ID: BuiltinAgentNormalID, ID: BuiltinQuickAnswerID,
Name: "普通模式", Name: "快速问答",
Description: "基于知识库的 RAG 问答,快速准确地回答问题", Description: "基于知识库的 RAG 问答,快速准确地回答问题",
Avatar: "💬",
IsBuiltin: true, IsBuiltin: true,
Type: CustomAgentTypeNormal,
TenantID: tenantID, TenantID: tenantID,
Config: CustomAgentConfig{ Config: CustomAgentConfig{
AgentMode: "normal", AgentMode: AgentModeQuickAnswer,
SystemPrompt: "", SystemPrompt: "",
Temperature: 0.7, Temperature: 0.7,
MaxCompletionTokens: 2048, MaxCompletionTokens: 2048,
WebSearchEnabled: false, WebSearchEnabled: true,
MultiTurnEnabled: true, WebSearchMaxResults: 5,
HistoryTurns: 5, MultiTurnEnabled: true,
HistoryTurns: 5,
KBSelectionMode: "all",
// Retrieval strategy // Retrieval strategy
EmbeddingTopK: 10, EmbeddingTopK: 10,
KeywordThreshold: 0.3, KeywordThreshold: 0.3,
VectorThreshold: 0.5, VectorThreshold: 0.5,
RerankTopK: 5, RerankTopK: 10,
RerankThreshold: 0.5, RerankThreshold: 0.3,
// Advanced settings // Advanced settings
EnableQueryExpansion: true, EnableQueryExpansion: true,
EnableRewrite: true, EnableRewrite: true,
@@ -239,21 +234,21 @@ func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
} }
} }
// GetBuiltinAgentAgent returns the built-in agent mode agent // GetBuiltinSmartReasoningAgent returns the built-in smart reasoning (ReAct) mode agent
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent { func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{ return &CustomAgent{
ID: BuiltinAgentAgentID, ID: BuiltinSmartReasoningID,
Name: "Agent 模式", Name: "智能推理",
Description: "ReAct 推理框架,支持多步思考和工具调用", Description: "ReAct 推理框架,支持多步思考和工具调用",
Avatar: "🤖",
IsBuiltin: true, IsBuiltin: true,
Type: CustomAgentTypeAgent,
TenantID: tenantID, TenantID: tenantID,
Config: CustomAgentConfig{ Config: CustomAgentConfig{
AgentMode: "agent", AgentMode: AgentModeSmartReasoning,
SystemPrompt: "", SystemPrompt: "",
Temperature: 0.7, Temperature: 0.7,
MaxIterations: 10, MaxCompletionTokens: 2048,
MaxIterations: 50,
KBSelectionMode: "all",
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"}, AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
WebSearchEnabled: true, WebSearchEnabled: true,
WebSearchMaxResults: 5, WebSearchMaxResults: 5,
@@ -261,19 +256,50 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
MultiTurnEnabled: true, MultiTurnEnabled: true,
HistoryTurns: 5, HistoryTurns: 5,
// Retrieval strategy // Retrieval strategy
EmbeddingTopK: 10, EmbeddingTopK: 10,
KeywordThreshold: 0.3, KeywordThreshold: 0.3,
VectorThreshold: 0.5, VectorThreshold: 0.5,
RerankTopK: 5, RerankTopK: 10,
RerankThreshold: 0.5, RerankThreshold: 0.3,
}, },
} }
} }
// GetBuiltinAgents returns all built-in agents for a tenant // Deprecated: Use GetBuiltinQuickAnswerAgent instead
func GetBuiltinAgents(tenantID uint64) []*CustomAgent { func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
return []*CustomAgent{ return GetBuiltinQuickAnswerAgent(tenantID)
GetBuiltinNormalAgent(tenantID), }
GetBuiltinAgentAgent(tenantID),
} // Deprecated: Use GetBuiltinSmartReasoningAgent instead
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
return GetBuiltinSmartReasoningAgent(tenantID)
}
// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
}
// GetBuiltinAgentIDs returns all built-in agent IDs
func GetBuiltinAgentIDs() []string {
ids := make([]string, 0, len(BuiltinAgentRegistry))
for id := range BuiltinAgentRegistry {
ids = append(ids, id)
}
return ids
}
// IsBuiltinAgentID checks if the given ID is a built-in agent ID
func IsBuiltinAgentID(id string) bool {
_, exists := BuiltinAgentRegistry[id]
return exists
}
// GetBuiltinAgent returns a built-in agent by ID, or nil if not found
func GetBuiltinAgent(id string, tenantID uint64) *CustomAgent {
if factory, exists := BuiltinAgentRegistry[id]; exists {
return factory(tenantID)
}
return nil
} }
+11 -1
View File
@@ -52,6 +52,15 @@ type CustomAgentService interface {
// Returns: // Returns:
// - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc. // - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc.
DeleteAgent(ctx context.Context, id string) error DeleteAgent(ctx context.Context, id string) error
// CopyAgent creates a copy of an existing agent
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the agent to copy
// Returns:
// - The newly created agent copy
// - Possible errors such as not existing, insufficient permissions, etc.
CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error)
} }
// CustomAgentRepository defines the custom agent repository interface // CustomAgentRepository defines the custom agent repository interface
@@ -96,7 +105,8 @@ type CustomAgentRepository interface {
// Parameters: // Parameters:
// - ctx: Context information // - ctx: Context information
// - id: Agent ID // - id: Agent ID
// - tenantID: Tenant ID for isolation (required for composite primary key)
// Returns: // Returns:
// - Possible errors such as record not existing, database errors, etc. // - Possible errors such as record not existing, database errors, etc.
DeleteAgent(ctx context.Context, id string) error DeleteAgent(ctx context.Context, id string, tenantID uint64) error
} }
+165
View File
@@ -0,0 +1,165 @@
package types
// PromptPlaceholder represents a placeholder that can be used in prompt templates
type PromptPlaceholder struct {
// Name is the placeholder name (without braces), e.g., "query"
Name string `json:"name"`
// Label is a short label for the placeholder
Label string `json:"label"`
// Description explains what this placeholder represents
Description string `json:"description"`
}
// PromptFieldType represents the type of prompt field
type PromptFieldType string
const (
// PromptFieldSystemPrompt is for system prompts (normal mode)
PromptFieldSystemPrompt PromptFieldType = "system_prompt"
// PromptFieldAgentSystemPrompt is for agent mode system prompts
PromptFieldAgentSystemPrompt PromptFieldType = "agent_system_prompt"
// PromptFieldContextTemplate is for context templates
PromptFieldContextTemplate PromptFieldType = "context_template"
// PromptFieldRewriteSystemPrompt is for rewrite system prompts
PromptFieldRewriteSystemPrompt PromptFieldType = "rewrite_system_prompt"
// PromptFieldRewritePrompt is for rewrite user prompts
PromptFieldRewritePrompt PromptFieldType = "rewrite_prompt"
// PromptFieldFallbackPrompt is for fallback prompts
PromptFieldFallbackPrompt PromptFieldType = "fallback_prompt"
)
// All available placeholders in the system
var (
// Common placeholders
PlaceholderQuery = PromptPlaceholder{
Name: "query",
Label: "用户问题",
Description: "用户当前的问题或查询内容",
}
PlaceholderContexts = PromptPlaceholder{
Name: "contexts",
Label: "检索内容",
Description: "从知识库检索到的相关内容列表",
}
PlaceholderCurrentTime = PromptPlaceholder{
Name: "current_time",
Label: "当前时间",
Description: "当前系统时间(格式:2006-01-02 15:04:05)",
}
PlaceholderCurrentWeek = PromptPlaceholder{
Name: "current_week",
Label: "当前星期",
Description: "当前星期几(如:星期一、Monday)",
}
// Rewrite prompt placeholders
PlaceholderConversation = PromptPlaceholder{
Name: "conversation",
Label: "历史对话",
Description: "格式化的历史对话内容,用于多轮对话改写",
}
PlaceholderYesterday = PromptPlaceholder{
Name: "yesterday",
Label: "昨天日期",
Description: "昨天的日期(格式:2006-01-02)",
}
PlaceholderAnswer = PromptPlaceholder{
Name: "answer",
Label: "助手回答",
Description: "助手的回答内容(用于对话历史格式化)",
}
// Agent mode specific placeholders
PlaceholderKnowledgeBases = PromptPlaceholder{
Name: "knowledge_bases",
Label: "知识库列表",
Description: "自动格式化的知识库列表,包含名称、描述、文档数量等信息",
}
PlaceholderWebSearchStatus = PromptPlaceholder{
Name: "web_search_status",
Label: "网络搜索状态",
Description: "网络搜索工具是否启用的状态(Enabled 或 Disabled)",
}
)
// PlaceholdersByField returns the available placeholders for a specific prompt field type
func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
switch fieldType {
case PromptFieldSystemPrompt:
// Normal mode system prompt
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
}
case PromptFieldAgentSystemPrompt:
// Agent mode system prompt
return []PromptPlaceholder{
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
PlaceholderCurrentTime,
}
case PromptFieldContextTemplate:
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
}
case PromptFieldRewriteSystemPrompt:
// Rewrite system prompt supports same placeholders as rewrite user prompt
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
}
case PromptFieldRewritePrompt:
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
}
case PromptFieldFallbackPrompt:
return []PromptPlaceholder{
PlaceholderQuery,
}
default:
return []PromptPlaceholder{}
}
}
// AllPlaceholders returns all available placeholders in the system
func AllPlaceholders() []PromptPlaceholder {
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
PlaceholderConversation,
PlaceholderYesterday,
PlaceholderAnswer,
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
}
}
// PlaceholderMap returns a map of field types to their available placeholders
func PlaceholderMap() map[PromptFieldType][]PromptPlaceholder {
return map[PromptFieldType][]PromptPlaceholder{
PromptFieldSystemPrompt: PlaceholdersByField(PromptFieldSystemPrompt),
PromptFieldAgentSystemPrompt: PlaceholdersByField(PromptFieldAgentSystemPrompt),
PromptFieldContextTemplate: PlaceholdersByField(PromptFieldContextTemplate),
PromptFieldRewriteSystemPrompt: PlaceholdersByField(PromptFieldRewriteSystemPrompt),
PromptFieldRewritePrompt: PlaceholdersByField(PromptFieldRewritePrompt),
PromptFieldFallbackPrompt: PlaceholdersByField(PromptFieldFallbackPrompt),
}
}
+4 -2
View File
@@ -69,13 +69,15 @@ type Tenant struct {
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"` StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes) // Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"` StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// Global Agent configuration for this tenant (default for all sessions) // Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.
// This field is kept for backward compatibility and will be removed in future versions.
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"` AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`
// Global Context configuration for this tenant (default for all sessions) // Global Context configuration for this tenant (default for all sessions)
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"` ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
// Global WebSearch configuration for this tenant // Global WebSearch configuration for this tenant
WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"` WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`
// Global Conversation configuration for this tenant (default for normal mode sessions) // Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.
// This field is kept for backward compatibility and will be removed in future versions.
ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"` ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`
// Creation time // Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"` CreatedAt time.Time `yaml:"created_at" json:"created_at"`
@@ -8,10 +8,9 @@ DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Removing agent_id column from
DROP INDEX IF EXISTS idx_sessions_agent_id; DROP INDEX IF EXISTS idx_sessions_agent_id;
ALTER TABLE sessions DROP COLUMN IF EXISTS agent_id; ALTER TABLE sessions DROP COLUMN IF EXISTS agent_id;
-- Drop custom_agents table -- Drop custom_agents table (includes built-in agents created during migration)
DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Dropping table: custom_agents'; END $$; DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Dropping table: custom_agents'; END $$;
DROP INDEX IF EXISTS idx_custom_agents_tenant_id; DROP INDEX IF EXISTS idx_custom_agents_tenant_id;
DROP INDEX IF EXISTS idx_custom_agents_type;
DROP INDEX IF EXISTS idx_custom_agents_is_builtin; DROP INDEX IF EXISTS idx_custom_agents_is_builtin;
DROP INDEX IF EXISTS idx_custom_agents_deleted_at; DROP INDEX IF EXISTS idx_custom_agents_deleted_at;
DROP TABLE IF EXISTS custom_agents; DROP TABLE IF EXISTS custom_agents;
@@ -1,27 +1,27 @@
-- Migration: 000006_custom_agents -- Migration: 000006_custom_agents
-- Description: Add custom agents table for GPTs-like agent configuration -- Description: Add custom agents table for GPTs-like agent configuration and migrate tenant config to built-in agents
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Starting custom agents setup...'; END $$; DO $$ BEGIN RAISE NOTICE '[Migration 000006] Starting custom agents setup...'; END $$;
-- Create custom_agents table -- Create custom_agents table with composite primary key (id, tenant_id)
-- This allows the same agent ID to exist for different tenants (e.g., 'builtin-normal' for each tenant)
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Creating table: custom_agents'; END $$; DO $$ BEGIN RAISE NOTICE '[Migration 000006] Creating table: custom_agents'; END $$;
CREATE TABLE IF NOT EXISTS custom_agents ( CREATE TABLE IF NOT EXISTS custom_agents (
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(), id VARCHAR(36) NOT NULL DEFAULT uuid_generate_v4(),
name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL,
description TEXT, description TEXT,
avatar VARCHAR(64), avatar VARCHAR(64),
is_builtin BOOLEAN NOT NULL DEFAULT false, is_builtin BOOLEAN NOT NULL DEFAULT false,
type VARCHAR(32) NOT NULL DEFAULT 'custom',
tenant_id INTEGER NOT NULL, tenant_id INTEGER NOT NULL,
created_by VARCHAR(36), created_by VARCHAR(36),
config JSONB NOT NULL DEFAULT '{}', config JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
deleted_at TIMESTAMP WITH TIME ZONE deleted_at TIMESTAMP WITH TIME ZONE,
PRIMARY KEY (id, tenant_id)
); );
-- Add indexes for custom_agents -- Add indexes for custom_agents
CREATE INDEX IF NOT EXISTS idx_custom_agents_tenant_id ON custom_agents(tenant_id); CREATE INDEX IF NOT EXISTS idx_custom_agents_tenant_id ON custom_agents(tenant_id);
CREATE INDEX IF NOT EXISTS idx_custom_agents_type ON custom_agents(type);
CREATE INDEX IF NOT EXISTS idx_custom_agents_is_builtin ON custom_agents(is_builtin); CREATE INDEX IF NOT EXISTS idx_custom_agents_is_builtin ON custom_agents(is_builtin);
CREATE INDEX IF NOT EXISTS idx_custom_agents_deleted_at ON custom_agents(deleted_at); CREATE INDEX IF NOT EXISTS idx_custom_agents_deleted_at ON custom_agents(deleted_at);
@@ -30,4 +30,147 @@ DO $$ BEGIN RAISE NOTICE '[Migration 000006] Adding agent_id column to sessions
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS agent_id VARCHAR(36); ALTER TABLE sessions ADD COLUMN IF NOT EXISTS agent_id VARCHAR(36);
CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id); CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id);
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Custom agents setup completed successfully!'; END $$; -- Helper function to unify prompt placeholders from Go template format to simple format
CREATE OR REPLACE FUNCTION unify_prompt_placeholder(input TEXT) RETURNS TEXT AS $$
DECLARE
result TEXT := COALESCE(input, '');
replacements TEXT[][] := ARRAY[
-- Go template variables -> simple placeholders
['{{.Query}}', '{{query}}'],
['{{.Answer}}', '{{answer}}'],
['{{.CurrentTime}}', '{{current_time}}'],
['{{.CurrentWeek}}', '{{current_week}}'],
['{{.Yesterday}}', '{{yesterday}}'],
['{{.Contexts}}', '{{contexts}}'],
-- Go template control structures -> simple placeholders or remove
['{{range .Contexts}}', '{{contexts}}'],
-- Remove Go template syntax
['{{if .Contexts}}', ''],
['{{else}}', ''],
['{{.}}', '']
];
r TEXT[];
BEGIN
FOREACH r SLICE 1 IN ARRAY replacements LOOP
result := REPLACE(result, r[1], r[2]);
END LOOP;
-- Handle {{range .Conversation}}...{{end}} block specially
-- Replace the entire block with just {{conversation}}
-- The pattern matches: {{range .Conversation}} followed by any content until {{end}}
result := regexp_replace(
result,
'\{\{range \.Conversation\}\}[\s\S]*?\{\{end\}\}',
'{{conversation}}',
'g'
);
-- Clean up any remaining {{end}} tags
result := REPLACE(result, '{{end}}', '');
RETURN result;
END;
$$ LANGUAGE plpgsql;
-- Migrate tenant AgentConfig and ConversationConfig to built-in custom agents
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Migrating tenant config to built-in agents...'; END $$;
-- Insert builtin-quick-answer agent for tenants with ConversationConfig
INSERT INTO custom_agents (id, name, description, avatar, is_builtin, tenant_id, config, created_at, updated_at)
SELECT
'builtin-quick-answer',
'快速问答',
'基于知识库的 RAG 问答,快速准确地回答问题',
'💬',
true,
t.id,
jsonb_build_object(
'agent_mode', 'quick-answer',
'system_prompt', unify_prompt_placeholder(t.conversation_config->>'prompt'),
'context_template', unify_prompt_placeholder(t.conversation_config->>'context_template'),
'model_id', COALESCE(t.conversation_config->>'summary_model_id', ''),
'rerank_model_id', COALESCE(t.conversation_config->>'rerank_model_id', ''),
'temperature', COALESCE((t.conversation_config->>'temperature')::float, 0.7),
'max_completion_tokens', COALESCE((t.conversation_config->>'max_completion_tokens')::int, 2048),
'max_iterations', 10,
'allowed_tools', '[]'::jsonb,
'reflection_enabled', false,
'kb_selection_mode', 'all',
'knowledge_bases', '[]'::jsonb,
'web_search_enabled', false,
'web_search_max_results', COALESCE((t.web_search_config->>'max_results')::int, 5),
'multi_turn_enabled', COALESCE((t.conversation_config->>'multi_turn_enabled')::bool, true),
'history_turns', COALESCE((t.conversation_config->>'max_rounds')::int, 5),
'embedding_top_k', COALESCE((t.conversation_config->>'embedding_top_k')::int, 10),
'keyword_threshold', COALESCE((t.conversation_config->>'keyword_threshold')::float, 0.3),
'vector_threshold', COALESCE((t.conversation_config->>'vector_threshold')::float, 0.5),
'rerank_top_k', COALESCE((t.conversation_config->>'rerank_top_k')::int, 5),
'rerank_threshold', COALESCE((t.conversation_config->>'rerank_threshold')::float, 0.5),
'enable_query_expansion', COALESCE((t.conversation_config->>'enable_query_expansion')::bool, true),
'enable_rewrite', COALESCE((t.conversation_config->>'enable_rewrite')::bool, true),
'rewrite_prompt_system', unify_prompt_placeholder(t.conversation_config->>'rewrite_prompt_system'),
'rewrite_prompt_user', unify_prompt_placeholder(t.conversation_config->>'rewrite_prompt_user'),
'fallback_strategy', COALESCE(t.conversation_config->>'fallback_strategy', 'model'),
'fallback_response', unify_prompt_placeholder(t.conversation_config->>'fallback_response'),
'fallback_prompt', unify_prompt_placeholder(t.conversation_config->>'fallback_prompt')
),
NOW(),
NOW()
FROM tenants t
WHERE t.conversation_config IS NOT NULL
AND t.deleted_at IS NULL
ON CONFLICT (id, tenant_id) DO UPDATE SET
config = EXCLUDED.config,
updated_at = NOW();
-- Insert builtin-smart-reasoning agent for tenants with AgentConfig
INSERT INTO custom_agents (id, name, description, avatar, is_builtin, tenant_id, config, created_at, updated_at)
SELECT
'builtin-smart-reasoning',
'智能推理',
'ReAct 推理框架,支持多步思考和工具调用',
'🤖',
true,
t.id,
jsonb_build_object(
'agent_mode', 'smart-reasoning',
'system_prompt', unify_prompt_placeholder(t.agent_config->>'system_prompt_web_disabled'),
'system_prompt_web_enabled', unify_prompt_placeholder(t.agent_config->>'system_prompt_web_enabled'),
'context_template', '',
'model_id', COALESCE(t.conversation_config->>'summary_model_id', ''),
'rerank_model_id', COALESCE(t.conversation_config->>'rerank_model_id', ''),
'temperature', COALESCE((t.agent_config->>'temperature')::float, 0.7),
'max_completion_tokens', 2048,
'max_iterations', COALESCE((t.agent_config->>'max_iterations')::int, 50),
'allowed_tools', COALESCE(t.agent_config->'allowed_tools', '["thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"]'::jsonb),
'reflection_enabled', COALESCE((t.agent_config->>'reflection_enabled')::bool, false),
'mcp_selection_mode', 'all',
'mcp_services', '[]'::jsonb,
'kb_selection_mode', 'all',
'knowledge_bases', COALESCE(t.agent_config->'knowledge_bases', '[]'::jsonb),
'web_search_enabled', COALESCE((t.agent_config->>'web_search_enabled')::bool, true),
'web_search_max_results', COALESCE((t.agent_config->>'web_search_max_results')::int, COALESCE((t.web_search_config->>'max_results')::int, 5)),
'multi_turn_enabled', COALESCE((t.agent_config->>'multi_turn_enabled')::bool, true),
'history_turns', COALESCE((t.agent_config->>'history_turns')::int, 5),
'embedding_top_k', 10,
'keyword_threshold', 0.3,
'vector_threshold', 0.5,
'rerank_top_k', 5,
'rerank_threshold', 0.5,
'enable_query_expansion', false,
'enable_rewrite', false,
'rewrite_prompt_system', '',
'rewrite_prompt_user', '',
'fallback_strategy', 'model',
'fallback_response', '',
'fallback_prompt', ''
),
NOW(),
NOW()
FROM tenants t
WHERE t.agent_config IS NOT NULL
AND t.deleted_at IS NULL
ON CONFLICT (id, tenant_id) DO UPDATE SET
config = EXCLUDED.config,
updated_at = NOW();