diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts new file mode 100644 index 00000000..b41e9566 --- /dev/null +++ b/frontend/src/api/agent/index.ts @@ -0,0 +1,94 @@ +import { get, post, put, del } from "../../utils/request"; + +// 智能体类型 +export type CustomAgentType = 'normal' | 'agent' | 'custom'; + +// 智能体配置 +export interface CustomAgentConfig { + agent_mode?: 'normal' | 'agent'; // 运行模式:normal=RAG模式, agent=ReAct Agent模式 + system_prompt?: string; + model_id?: string; + rerank_model_id?: string; // ReRank 模型 ID(当使用知识库时需要) + temperature?: number; + max_iterations?: number; + allowed_tools?: string[]; + knowledge_bases?: string[]; + // 当没有配置知识库时,是否允许用户自由选择知识库 + // true (默认): 用户可以自由选择任意知识库 + // false: 禁用知识库选择功能 + allow_user_kb_selection?: boolean; + web_search_enabled?: boolean; + web_search_max_results?: number; + reflection_enabled?: boolean; + welcome_message?: string; + suggested_prompts?: string[]; + multi_turn_enabled?: boolean; // 是否启用多轮对话 + history_turns?: number; // 保留历史轮数 +} + +// 智能体 +export interface CustomAgent { + id: string; + name: string; + description?: string; + avatar?: string; + is_builtin: boolean; + type: CustomAgentType; + tenant_id?: number; + created_by?: string; + config: CustomAgentConfig; + created_at?: string; + updated_at?: string; +} + +// 创建智能体请求 +export interface CreateAgentRequest { + name: string; + description?: string; + avatar?: string; + type?: CustomAgentType; + config?: CustomAgentConfig; +} + +// 更新智能体请求 +export interface UpdateAgentRequest { + name: string; + description?: string; + avatar?: string; + type?: CustomAgentType; + config?: CustomAgentConfig; +} + +// 内置智能体 ID +export const BUILTIN_AGENT_NORMAL_ID = 'builtin-normal'; +export const BUILTIN_AGENT_AGENT_ID = 'builtin-agent'; + +// 获取智能体列表(包括内置智能体) +export function listAgents() { + return get<{ data: CustomAgent[] }>('/api/v1/agents'); +} + +// 获取智能体详情 +export function getAgentById(id: string) { + return get<{ data: CustomAgent }>(`/api/v1/agents/${id}`); +} + +// 创建智能体 +export function createAgent(data: CreateAgentRequest) { + return post<{ data: CustomAgent }>('/api/v1/agents', data); +} + +// 更新智能体 +export function updateAgent(id: string, data: UpdateAgentRequest) { + return put<{ data: CustomAgent }>(`/api/v1/agents/${id}`, data); +} + +// 删除智能体 +export function deleteAgent(id: string) { + return del<{ success: boolean }>(`/api/v1/agents/${id}`); +} + +// 判断是否为内置智能体 +export function isBuiltinAgent(agentId: string): boolean { + return agentId === BUILTIN_AGENT_NORMAL_ID || agentId === BUILTIN_AGENT_AGENT_ID; +} diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts index 4b0ae712..f7dd5628 100644 --- a/frontend/src/api/chat/streame.ts +++ b/frontend/src/api/chat/streame.ts @@ -28,7 +28,7 @@ export function useStream() { let renderTimer: number | null = null // 启动流式请求 - const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => { + const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => { // 重置状态 output.value = ''; error.value = null; @@ -89,6 +89,10 @@ export function useStream() { if (params.knowledge_ids !== undefined && params.knowledge_ids.length > 0) { postBody.knowledge_ids = params.knowledge_ids; } + // Include agent_id if provided (for custom agent configuration) + if (params.agent_id) { + postBody.agent_id = params.agent_id; + } // Include web_search_enabled if provided if (params.web_search_enabled !== undefined) { postBody.web_search_enabled = params.web_search_enabled; diff --git a/frontend/src/assets/img/agent-green.svg b/frontend/src/assets/img/agent-green.svg new file mode 100644 index 00000000..96b5b46c --- /dev/null +++ b/frontend/src/assets/img/agent-green.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/assets/img/agent.svg b/frontend/src/assets/img/agent.svg index 458f55da..3b94a604 100644 --- a/frontend/src/assets/img/agent.svg +++ b/frontend/src/assets/img/agent.svg @@ -1,5 +1,5 @@ - - - - \ No newline at end of file + + + + diff --git a/frontend/src/components/AgentAvatar.vue b/frontend/src/components/AgentAvatar.vue new file mode 100644 index 00000000..570e5181 --- /dev/null +++ b/frontend/src/components/AgentAvatar.vue @@ -0,0 +1,155 @@ + + + + + + + + + + {{ letter }} + + + + + + diff --git a/frontend/src/components/AgentSelector.vue b/frontend/src/components/AgentSelector.vue new file mode 100644 index 00000000..e8d6701f --- /dev/null +++ b/frontend/src/components/AgentSelector.vue @@ -0,0 +1,430 @@ + + + + + + + {{ $t('agent.selectAgent') }} + + + + {{ $t('agent.manageAgents') }} + + + + + + + + {{ $t('agent.builtinAgents') }} + + + + + + {{ agent.name }} + + + + + + + + + + {{ $t('agent.customAgents') }} + + + + {{ agent.name }} + + + + + + + + + + {{ $t('agent.noAgents') }} + + + + + + + + + + diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 28077bac..8499351c 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -9,8 +9,10 @@ import { listKnowledgeBases, searchKnowledge, batchQueryKnowledge } from '@/api/ import { stopSession } from '@/api/chat'; import KnowledgeBaseSelector from './KnowledgeBaseSelector.vue'; import MentionSelector from './MentionSelector.vue'; +import AgentSelector from './AgentSelector.vue'; import { getCaretCoordinates } from '@/utils/caret'; import { listModels, type ModelConfig } from '@/api/model'; +import { listAgents, type CustomAgent } from '@/api/agent'; import { getTenantWebSearchConfig } from '@/api/web-search'; import { getConversationConfig, updateConversationConfig, type ConversationConfig } from '@/api/system'; import { useI18n } from 'vue-i18n'; @@ -26,6 +28,81 @@ const showAgentModeSelector = ref(false); const agentModeButtonRef = ref(); const agentModeDropdownStyle = ref>({}); +// 智能体相关状态 +const agents = ref([]); +const selectedAgentId = computed({ + get: () => settingsStore.selectedAgentId || 'builtin-normal', + set: (val: string) => settingsStore.selectAgent(val) +}); +const selectedAgent = computed(() => { + return agents.value.find(a => a.id === selectedAgentId.value) || { + id: 'builtin-normal', + name: t('input.normalMode'), + type: 'normal', + is_builtin: true + } as CustomAgent; +}); + +// 判断是否为自定义智能体(非内置) +const isCustomAgent = computed(() => { + const agent = selectedAgent.value; + return agent && !agent.is_builtin && agent.type === 'custom'; +}); + +// 智能体预配置的知识库 IDs +const agentKnowledgeBases = computed(() => { + if (!isCustomAgent.value) return []; + return selectedAgent.value?.config?.knowledge_bases || []; +}); + +// 智能体是否启用了网络搜索 +const agentWebSearchEnabled = computed(() => { + if (!isCustomAgent.value) return null; // null 表示不受智能体控制 + return selectedAgent.value?.config?.web_search_enabled ?? false; +}); + +// 网络搜索是否被智能体禁用(只读状态) +const isWebSearchDisabledByAgent = computed(() => { + return isCustomAgent.value && agentWebSearchEnabled.value === false; +}); + +// 网络搜索是否被智能体强制启用 +const isWebSearchForcedByAgent = computed(() => { + return isCustomAgent.value && agentWebSearchEnabled.value === true; +}); + +// 知识库选择是否被智能体锁定 +// 1. 如果智能体配置了知识库 → 锁定到这些知识库 +// 2. 如果智能体没配置知识库,但 allow_user_kb_selection=false → 禁用知识库选择 +const isKnowledgeBaseLockedByAgent = computed(() => { + if (!isCustomAgent.value) return false; + // 有预配置知识库时,锁定到这些知识库 + if (agentKnowledgeBases.value.length > 0) return true; + // 没有预配置知识库,但禁止用户选择 + const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection; + // 默认为 true(允许用户选择),只有明确设置为 false 时才禁用 + return allowUserKBSelection === false; +}); + +// 知识库是否被智能体完全禁用(没有预配置且不允许用户选择) +const isKnowledgeBaseDisabledByAgent = computed(() => { + if (!isCustomAgent.value) return false; + if (agentKnowledgeBases.value.length > 0) return false; // 有预配置的不算禁用 + const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection; + return allowUserKBSelection === false; +}); + +// 智能体配置的模型 ID +const agentModelId = computed(() => { + if (!isCustomAgent.value) return null; + return selectedAgent.value?.config?.model_id || null; +}); + +// 模型选择是否被智能体锁定 +const isModelLockedByAgent = computed(() => { + return isCustomAgent.value && !!agentModelId.value; +}); + // Mention related state const showMention = ref(false); const mentionQuery = ref(""); @@ -80,21 +157,49 @@ const selectedFiles = computed(() => { }); // 合并所有选中项(用于输入框内显示) + // 包括用户选择的和智能体预配置的知识库 const allSelectedItems = computed(() => { - const kbs = selectedKbs.value.map(kb => ({ - ...kb, - type: 'kb' as const, - kbType: kb.type // 保留原始类型用于显示区分 - })); + // 获取智能体预配置的知识库 IDs + const agentKbIds = agentKnowledgeBases.value; + + // 用户选择的知识库(排除智能体已配置的) + const userSelectedKbs = selectedKbs.value + .filter(kb => !agentKbIds.includes(kb.id)) + .map(kb => ({ + ...kb, + type: 'kb' as const, + kbType: kb.type, + isAgentConfigured: false + })); + + // 智能体预配置的知识库 + const agentConfiguredKbs = knowledgeBases.value + .filter(kb => agentKbIds.includes(kb.id)) + .map(kb => ({ + ...kb, + type: 'kb' as const, + kbType: kb.type, + isAgentConfigured: true // 标记为智能体配置,不可删除 + })); + + // 用户选择的文件 const files = selectedFiles.value.map((f: { id: string; name: string }) => ({ ...f, - type: 'file' as const + type: 'file' as const, + isAgentConfigured: false })); - return [...kbs, ...files]; + + // 智能体配置的放在前面 + return [...agentConfiguredKbs, ...userSelectedKbs, ...files]; }); -// 移除选中项 -const removeSelectedItem = (item: { id: string; type: 'kb' | 'file' }) => { +// 移除选中项(智能体配置的项不可移除) +const removeSelectedItem = (item: { id: string; type: 'kb' | 'file'; isAgentConfigured?: boolean }) => { + // 如果是智能体配置的,不允许删除 + if (item.isAgentConfigured) { + MessagePlugin.warning(t('input.cannotRemoveAgentKb')); + return; + } if (item.type === 'kb') { settingsStore.removeKnowledgeBase(item.id); } else { @@ -123,6 +228,15 @@ const remainingCount = computed(() => Math.max(0, selectedKbs.value.length - 2)) // 根据不同状态组合计算输入框的 placeholder const inputPlaceholder = computed(() => { + // 如果选择了自定义智能体 + if (isCustomAgent.value && selectedAgent.value) { + // 有描述时显示描述,否则显示"向 [名称] 提问" + if (selectedAgent.value.description) { + return selectedAgent.value.description; + } + return t('input.placeholderAgent', { name: selectedAgent.value.name }); + } + const hasKnowledge = allSelectedItems.value.length > 0; const hasWebSearch = isWebSearchEnabled.value && isWebSearchConfigured.value; @@ -211,6 +325,16 @@ const loadWebSearchConfig = async () => { } }; +// 加载智能体列表 +const loadAgents = async () => { + try { + const response = await listAgents(); + agents.value = response.data || []; + } catch (error) { + console.error('Failed to load agents:', error); + } +}; + const loadConversationConfig = async () => { try { const response = await getConversationConfig(); @@ -619,6 +743,13 @@ const onCompositionEnd = (e: CompositionEvent) => { }; const triggerMention = () => { + // 如果智能体锁定或禁用了知识库,不允许打开选择器 + if (isKnowledgeBaseLockedByAgent.value) { + const msgKey = isKnowledgeBaseDisabledByAgent.value ? 'input.kbDisabledByAgent' : 'input.kbLockedByAgent'; + MessagePlugin.warning(t(msgKey)); + return; + } + const textarea = getTextareaEl(); if (!textarea) return; @@ -712,6 +843,12 @@ const removeFile = (id: string) => { }; const toggleModelSelector = () => { + // 如果智能体锁定了模型,不允许打开选择器 + if (isModelLockedByAgent.value) { + MessagePlugin.warning(t('input.modelLockedByAgent')); + return; + } + // 互斥:关闭其他 showMention.value = false; showAgentModeSelector.value = false; @@ -761,6 +898,7 @@ onMounted(() => { loadWebSearchConfig(); loadConversationConfig(); loadChatModels(); + loadAgents(); // 如果从知识库内部进入,自动选中该知识库 const kbId = (route.params as any)?.kbId as string; @@ -931,18 +1069,14 @@ const updateAgentModeDropdownPosition = () => { }; const toggleAgentModeSelector = () => { - // 如果 Agent 未就绪,显示提示 - if (!settingsStore.isAgentReady && !isAgentEnabled.value) { - toggleAgentMode(); - return; - } - // 互斥 showMention.value = false; showModelSelector.value = false; showAgentModeSelector.value = !showAgentModeSelector.value; if (showAgentModeSelector.value) { + // 重新加载智能体列表 + loadAgents(); // 多次更新位置确保准确 nextTick(() => { updateAgentModeDropdownPosition(); @@ -966,11 +1100,51 @@ const selectAgentMode = (mode: 'normal' | 'agent') => { const shouldEnableAgent = mode === 'agent'; if (shouldEnableAgent !== isAgentEnabled.value) { settingsStore.toggleAgent(shouldEnableAgent); + // 同时更新选中的智能体 + settingsStore.selectAgent(shouldEnableAgent ? 'builtin-agent' : 'builtin-normal'); MessagePlugin.success(shouldEnableAgent ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff')); } showAgentModeSelector.value = false; } +// 选择智能体(新版) +const handleSelectAgent = (agent: CustomAgent) => { + selectedAgentId.value = agent.id; + + // 根据智能体类型切换 Agent 模式 + const isAgentType = agent.type === 'agent' || (agent.type === 'custom' && (agent.config?.max_iterations ?? 0) > 1); + + if (isAgentType && !settingsStore.isAgentReady) { + // Agent 模式未就绪,显示提示 + toggleAgentMode(); + return; + } + + settingsStore.toggleAgent(!!isAgentType); + + // 如果是自定义智能体,同步网络搜索状态和模型 + if (!agent.is_builtin && agent.type === 'custom') { + const agentWebSearch = agent.config?.web_search_enabled; + if (agentWebSearch !== undefined) { + // 智能体配置了网络搜索设置,同步到 store + settingsStore.toggleWebSearch(agentWebSearch); + } + + // 如果智能体配置了模型,同步到 store + const agentModel = agent.config?.model_id; + if (agentModel) { + selectedModelId.value = agentModel; + } + } + + showAgentModeSelector.value = false; + + const message = agent.is_builtin + ? (isAgentType ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff')) + : t('input.messages.agentSelected', { name: agent.name }); + MessagePlugin.success(message); +} + const clearvalue = () => { query.value = ""; } @@ -1107,6 +1281,18 @@ const toggleWebSearch = () => { showModelSelector.value = false; showAgentModeSelector.value = false; + // 如果智能体禁用了网络搜索,不允许开启 + if (isWebSearchDisabledByAgent.value) { + MessagePlugin.warning(t('input.webSearchDisabledByAgent')); + return; + } + + // 如果智能体强制启用了网络搜索,不允许关闭 + if (isWebSearchForcedByAgent.value) { + MessagePlugin.warning(t('input.webSearchForcedByAgent')); + return; + } + if (!isWebSearchConfigured.value) { const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 6px; max-width: 280px;' }, [ h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.messages.webSearchNotConfigured')), @@ -1182,14 +1368,15 @@ onBeforeRouteUpdate((to, from, next) => { - + @@ -1197,7 +1384,8 @@ onBeforeRouteUpdate((to, from, next) => { {{ item.name }} - × + + × @@ -1243,28 +1431,8 @@ onBeforeRouteUpdate((to, from, next) => { }" @click.stop="toggleAgentModeSelector" > - - - - - {{ isAgentEnabled ? $t('input.agentMode') : $t('input.normalMode') }} + {{ selectedAgent.name || (isAgentEnabled ? $t('input.agentMode') : $t('input.normalMode')) }} { - - - - - - - {{ $t('input.normalMode') }} - {{ $t('input.normalModeDesc') }} - - - - - - - - {{ $t('input.agentMode') }} - {{ $t('input.agentModeDesc') }} - - - - - - - - - - - - - - + + - {{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }} + {{ $t('input.webSearchDisabledByAgent') }} + {{ $t('input.webSearchForcedByAgent') }} + {{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }} {{ $t('input.webSearch.notConfigured') }} {{ $t('input.goToSettings') }} @@ -1358,7 +1468,11 @@ onBeforeRouteUpdate((to, from, next) => { { fill="none" xmlns="http://www.w3.org/2000/svg" class="control-icon websearch-icon" - :class="{ 'active': isWebSearchEnabled && isWebSearchConfigured }" + :class="{ 'active': (isWebSearchEnabled && isWebSearchConfigured) || isWebSearchForcedByAgent }" > @@ -1380,11 +1494,14 @@ onBeforeRouteUpdate((to, from, next) => { - + @@ -1394,27 +1511,29 @@ onBeforeRouteUpdate((to, from, next) => { - - - - {{ selectedModel?.name || $t('input.notConfigured') }} - - + + - - + + {{ selectedModel?.name || $t('input.notConfigured') }} + + + + + - + @@ -1609,6 +1728,12 @@ const getImgSrc = (url: string) => { background: rgba(0, 0, 0, 0.1); } } + + // 智能体配置的标签样式(用虚线边框区分,不显示锁图标) + &.agent-configured { + border-style: dashed; + opacity: 0.9; + } } :deep(.t-textarea__inner) { @@ -1788,6 +1913,19 @@ const getImgSrc = (url: string) => { background: rgba(16, 185, 129, 0.15); } } + + &.agent-controlled { + cursor: not-allowed; + opacity: 0.85; + + &:hover { + background: var(--td-bg-color-secondarycontainer, #f5f5f5); + } + + &.active:hover { + background: rgba(16, 185, 129, 0.1); + } + } } .kb-count { @@ -1826,6 +1964,7 @@ const getImgSrc = (url: string) => { display: flex; align-items: center; justify-content: center; + position: relative; &.active { background: rgba(16, 185, 129, 0.1); @@ -1852,6 +1991,19 @@ const getImgSrc = (url: string) => { } } } + + &.agent-controlled { + cursor: not-allowed; + opacity: 0.85; + + &:hover { + background: var(--td-bg-color-secondarycontainer, #f5f5f5); + } + + &.active:hover { + background: rgba(16, 185, 129, 0.1); + } + } } :global(.websearch-tooltip-disabled) { @@ -1956,6 +2108,18 @@ const getImgSrc = (url: string) => { align-items: center; margin-left: auto; flex-shrink: 0; + + &.agent-controlled { + .model-selector-trigger { + cursor: not-allowed; + opacity: 0.85; + + &:hover { + background: rgba(16, 185, 129, 0.1); + border-color: rgba(16, 185, 129, 0.3); + } + } + } } .model-selector-trigger { @@ -2040,12 +2204,12 @@ const getImgSrc = (url: string) => { display: flex; align-items: center; justify-content: space-between; - padding: 8px 10px; - border-bottom: 1px solid var(--td-component-border, #f2f4f5); - background: var(--td-bg-color-secondarycontainer, #fafcfc); + padding: 8px 12px; + border-bottom: 1px solid var(--td-component-stroke, #f0f0f0); + background: var(--td-bg-color-container, #fff); font-size: 12px; - font-weight: 600; - color: var(--td-text-color-primary, #222); + font-weight: 500; + color: var(--td-text-color-secondary, #666); } .model-selector-content { @@ -2061,26 +2225,26 @@ const getImgSrc = (url: string) => { display: inline-flex; align-items: center; gap: 4px; - padding: 3px 8px; - border-radius: 6px; - border: 1px solid var(--td-component-border, #e1e5e6); - background: var(--td-bg-color-container, #fff); - color: var(--td-text-color-secondary, #52575a); - font-size: 11px; + padding: 2px 8px; + border-radius: 4px; + border: 1px solid transparent; + background: transparent; + color: var(--td-brand-color, #07c05f); + font-size: 12px; font-weight: 500; cursor: pointer; - transition: all 0.12s; -} - -.model-selector-add .add-icon { - font-size: 12px; - line-height: 1; -} - -.model-selector-add:hover { - border-color: #10b981; - color: #10b981; - background: #f0fdf6; + transition: all 0.2s; + + .add-icon { + font-size: 14px; + line-height: 1; + font-weight: 400; + } + + &:hover { + color: var(--td-brand-color-hover, #05a04f); + background: var(--td-bg-color-secondarycontainer, #f3f3f3); + } } .model-option { diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index c6e7ad24..da2c6057 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -24,6 +24,18 @@ + + + + + + + + + {{ t('agent.createAgent') }} + + + @@ -138,7 +150,7 @@ :class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : isMenuItemActive(item.path) ? 'menu_item_active' : '']"> - + {{ item.title }} @@ -253,6 +265,9 @@ const isInCreatChat = computed(() => { // 是否在对话详情页 const isInChatDetail = computed(() => route.name === 'chat'); +// 是否在智能体列表页面 +const isInAgentList = computed(() => route.name === 'agentList'); + // 统一的菜单项激活状态判断 const isMenuItemActive = (itemPath: string): boolean => { const currentRoute = route.name; @@ -262,6 +277,8 @@ const isMenuItemActive = (itemPath: string): boolean => { return currentRoute === 'knowledgeBaseList' || currentRoute === 'knowledgeBaseDetail' || currentRoute === 'knowledgeBaseSettings'; + case 'agents': + return currentRoute === 'agentList'; case 'creatChat': return currentRoute === 'kbCreatChat' || currentRoute === 'globalCreatChat'; case 'settings': @@ -290,13 +307,13 @@ const getIconActiveState = (itemPath: string) => { // 分离上下两部分菜单 const topMenuItems = computed(() => { return (menuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => - item.path === 'knowledge-bases' || item.path === 'creatChat' + item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'creatChat' ); }); const bottomMenuItems = computed(() => { return (menuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => { - if (item.path === 'knowledge-bases' || item.path === 'creatChat') { + if (item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'creatChat') { return false; } return true; @@ -325,12 +342,14 @@ const showKbActions = computed(() => (isInKnowledgeBase.value && !!currentKbInfo.value) || isInKnowledgeBaseList.value || isInCreatChat.value || - isInChatDetail.value + isInChatDetail.value || + isInAgentList.value ) const currentKbType = computed(() => currentKbInfo.value?.type || 'document') const showDocActions = computed(() => showKbActions.value && isInKnowledgeBase.value && currentKbType.value !== 'faq') const showFaqActions = computed(() => showKbActions.value && isInKnowledgeBase.value && currentKbType.value === 'faq') const showCreateKbAction = computed(() => showKbActions.value && (isInKnowledgeBaseList.value || isInCreatChat.value || isInChatDetail.value)) +const showCreateAgentAction = computed(() => showKbActions.value && isInAgentList.value) // 时间分组函数 const getTimeCategory = (dateStr: string): string => { @@ -570,16 +589,21 @@ let knowledgeIcon = ref('zhishiku-green.svg'); let prefixIcon = ref('prefixIcon.svg'); let logoutIcon = ref('logout.svg'); let settingIcon = ref('setting.svg'); // 设置图标 +let agentIcon = ref('agent.svg'); // 智能体图标 let pathPrefix = ref(route.name) const getIcon = (path: string) => { // 根据当前路由状态更新所有图标 const kbActiveState = getIconActiveState('knowledge-bases'); const creatChatActiveState = getIconActiveState('creatChat'); const settingsActiveState = getIconActiveState('settings'); + const agentsActiveState = route.name === 'agentList'; // 知识库图标:只在知识库页面显示绿色 knowledgeIcon.value = kbActiveState.isKbActive ? 'zhishiku-green.svg' : 'zhishiku.svg'; + // 智能体图标:只在智能体页面显示绿色 + agentIcon.value = agentsActiveState ? 'agent-green.svg' : 'agent.svg'; + // 对话图标:只在对话创建页面显示绿色,在知识库页面显示灰色,其他情况显示默认 prefixIcon.value = creatChatActiveState.isCreatChatActive ? 'prefixIcon-green.svg' : kbActiveState.isKbActive ? 'prefixIcon-grey.svg' : @@ -601,6 +625,9 @@ const handleMenuClick = async (path: string) => { } else { router.push('/platform/knowledge-bases') } + } else if (path === 'agents') { + // 智能体菜单项:跳转到智能体列表 + router.push('/platform/agents') } else if (path === 'settings') { // 设置菜单项:打开设置弹窗并跳转路由 uiStore.openSettings() @@ -1238,6 +1265,13 @@ const handleCreateKnowledgeBase = () => { uiStore.openCreateKB() } +const handleCreateAgent = () => { + // 触发创建智能体事件,由 AgentList 页面监听处理 + window.dispatchEvent(new CustomEvent('openAgentEditor', { + detail: { mode: 'create' } + })) +} + diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue new file mode 100644 index 00000000..b286b5a2 --- /dev/null +++ b/frontend/src/views/agent/AgentList.vue @@ -0,0 +1,797 @@ + + + + + + {{ $t('agent.title') }} + {{ $t('agent.subtitle') }} + + + + + + + + + + + + + + + + + + + + + + {{ agent.name }} + + + + + + + + + + {{ $t('common.edit') }} + + + + {{ $t('common.delete') }} + + + + + + + {{ $t('agent.builtin') }} + + + + + + + {{ agent.description || $t('agent.noDescription') }} + + + + + + + + + {{ agent.config?.agent_mode === 'agent' ? $t('agent.mode.agent') : $t('agent.mode.normal') }} + + + + + + + + + + + + + + + + + + + + {{ formatDate(agent.updated_at) }} + + + + + + + + {{ $t('agent.empty.title') }} + {{ $t('agent.empty.description') }} + + + + + + + + {{ $t('agent.delete.confirmTitle') }} + + + {{ $t('agent.delete.confirmMessage', { name: deletingAgent?.name ?? '' }) }} + + + {{ $t('common.cancel') }} + {{ $t('agent.delete.confirmButton') }} + + + + + + + + + + + + + + diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 53e7e643..88e60b41 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -314,6 +314,8 @@ const sendMsg = async (value, modelId = '', mentionedItems = []) => { const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || []; const knowledgeIds = useSettingsStoreInstance.settings.selectedFiles || []; + // Get selected agent ID + const selectedAgentId = useSettingsStoreInstance.selectedAgentId || ''; // Use agent-chat endpoint when agent is enabled, otherwise use knowledge-chat @@ -327,6 +329,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = []) => { knowledge_base_ids: kbIds, knowledge_ids: knowledgeIds, agent_enabled: agentEnabled, + agent_id: selectedAgentId, // 传递选中的智能体 ID web_search_enabled: webSearchEnabled, summary_model_id: modelId, mcp_service_ids: mcpServiceIds, diff --git a/internal/application/repository/custom_agent.go b/internal/application/repository/custom_agent.go new file mode 100644 index 00000000..70a10612 --- /dev/null +++ b/internal/application/repository/custom_agent.go @@ -0,0 +1,62 @@ +package repository + +import ( + "context" + "errors" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "gorm.io/gorm" +) + +// ErrCustomAgentNotFound is returned when a custom agent is not found +var ErrCustomAgentNotFound = errors.New("custom agent not found") + +// customAgentRepository implements the CustomAgentRepository interface +type customAgentRepository struct { + db *gorm.DB +} + +// NewCustomAgentRepository creates a new custom agent repository +func NewCustomAgentRepository(db *gorm.DB) interfaces.CustomAgentRepository { + return &customAgentRepository{db: db} +} + +// CreateAgent creates a new custom agent +func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.CustomAgent) error { + return r.db.WithContext(ctx).Create(agent).Error +} + +// GetAgentByID gets an agent by id +func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) { + var agent types.CustomAgent + if err := r.db.WithContext(ctx).Where("id = ?", id).First(&agent).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, ErrCustomAgentNotFound + } + return nil, err + } + return &agent, nil +} + +// ListAgentsByTenantID lists all agents for a specific tenant +func (r *customAgentRepository) ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error) { + var agents []*types.CustomAgent + if err := r.db.WithContext(ctx). + Where("tenant_id = ?", tenantID). + Order("created_at DESC"). + Find(&agents).Error; err != nil { + return nil, err + } + return agents, nil +} + +// UpdateAgent updates an agent +func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.CustomAgent) error { + return r.db.WithContext(ctx).Save(agent).Error +} + +// DeleteAgent deletes an agent (soft delete) +func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string) error { + return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.CustomAgent{}).Error +} diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index deb44579..f4e6bace 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -179,8 +179,16 @@ func (s *agentService) registerTools( sessionID string, sessionService interfaces.SessionService, ) error { - // If no specific tools allowed, register default tools - allowedTools := tools.DefaultAllowedTools() + // Use config's allowed tools if specified, otherwise use defaults + var allowedTools []string + if len(config.AllowedTools) > 0 { + allowedTools = make([]string, len(config.AllowedTools)) + copy(allowedTools, config.AllowedTools) + logger.Infof(ctx, "Using custom allowed tools from config: %v", allowedTools) + } else { + allowedTools = tools.DefaultAllowedTools() + logger.Infof(ctx, "Using default allowed tools: %v", allowedTools) + } // Filter out knowledge base tools if no knowledge bases or knowledge IDs are configured hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0 @@ -206,7 +214,7 @@ func (s *agentService) registerTools( } } allowedTools = filteredTools - logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools disabled due to empty configuration") + logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools filtered out, remaining: %v", allowedTools) } // If web search is enabled, add web_search to allowedTools diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go new file mode 100644 index 00000000..c4ad9c6e --- /dev/null +++ b/internal/application/service/custom_agent.go @@ -0,0 +1,267 @@ +package service + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/google/uuid" +) + +// Custom agent related errors +var ( + ErrAgentNotFound = errors.New("agent not found") + ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent") + ErrCannotDeleteBuiltin = errors.New("cannot delete built-in agent") + ErrAgentNameRequired = errors.New("agent name is required") +) + +// customAgentService implements the CustomAgentService interface +type customAgentService struct { + repo interfaces.CustomAgentRepository +} + +// NewCustomAgentService creates a new custom agent service +func NewCustomAgentService(repo interfaces.CustomAgentRepository) interfaces.CustomAgentService { + return &customAgentService{ + repo: repo, + } +} + +// CreateAgent creates a new custom agent +func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) { + // Validate required fields + if strings.TrimSpace(agent.Name) == "" { + return nil, ErrAgentNameRequired + } + + // Generate UUID and set creation timestamps + if agent.ID == "" { + agent.ID = uuid.New().String() + } + + // Get tenant ID from context + tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64) + if !ok { + return nil, ErrInvalidTenantID + } + agent.TenantID = tenantID + + // Set timestamps + agent.CreatedAt = time.Now() + agent.UpdatedAt = time.Now() + + // Ensure custom type for user-created agents + if agent.Type == "" { + agent.Type = types.CustomAgentTypeCustom + } + + // Cannot create built-in agents + agent.IsBuiltin = false + + // Set defaults + agent.EnsureDefaults() + + logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, type: %s", + agent.ID, agent.TenantID, agent.Name, agent.Type) + + if err := s.repo.CreateAgent(ctx, agent); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": agent.ID, + "tenant_id": agent.TenantID, + }) + return nil, err + } + + logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s", agent.ID, agent.Name) + return agent, nil +} + +// GetAgentByID retrieves an agent by its ID (including built-in agents) +func (s *customAgentService) GetAgentByID(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 + } + + // Check if it's a built-in agent + if id == types.BuiltinAgentNormalID { + return types.GetBuiltinNormalAgent(tenantID), nil + } + if id == types.BuiltinAgentAgentID { + return types.GetBuiltinAgentAgent(tenantID), nil + } + + // Query from database + agent, err := s.repo.GetAgentByID(ctx, id) + if err != nil { + if errors.Is(err, repository.ErrCustomAgentNotFound) { + return nil, ErrAgentNotFound + } + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": id, + }) + return nil, err + } + + // Verify tenant ownership + if agent.TenantID != tenantID { + return nil, ErrAgentNotFound + } + + return agent, nil +} + +// ListAgents lists all agents for the current tenant (including built-in agents) +func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAgent, error) { + tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64) + if !ok { + return nil, ErrInvalidTenantID + } + + // Get built-in agents first + builtinAgents := types.GetBuiltinAgents(tenantID) + + // Get custom agents from database + customAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID) + if err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "tenant_id": tenantID, + }) + return nil, err + } + + // Combine: built-in agents first, then custom agents + result := make([]*types.CustomAgent, 0, len(builtinAgents)+len(customAgents)) + result = append(result, builtinAgents...) + result = append(result, customAgents...) + + return result, nil +} + +// UpdateAgent updates an agent's information +func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) { + if agent.ID == "" { + logger.Error(ctx, "Agent ID is empty") + return nil, errors.New("agent ID cannot be empty") + } + + // Cannot modify built-in agents + if agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID { + return nil, ErrCannotModifyBuiltin + } + + // Get tenant ID from context + tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64) + if !ok { + return nil, ErrInvalidTenantID + } + + // Get existing agent + existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID) + if err != nil { + if errors.Is(err, repository.ErrCustomAgentNotFound) { + return nil, ErrAgentNotFound + } + return nil, err + } + + // Verify tenant ownership + if existingAgent.TenantID != tenantID { + return nil, ErrAgentNotFound + } + + // Cannot modify built-in status + if existingAgent.IsBuiltin { + return nil, ErrCannotModifyBuiltin + } + + // Validate name + if strings.TrimSpace(agent.Name) == "" { + return nil, ErrAgentNameRequired + } + + // Update fields + existingAgent.Name = agent.Name + existingAgent.Description = agent.Description + existingAgent.Avatar = agent.Avatar + existingAgent.Type = agent.Type + existingAgent.Config = agent.Config + existingAgent.UpdatedAt = time.Now() + + // Ensure defaults + existingAgent.EnsureDefaults() + + logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s", agent.ID, agent.Name) + + if err := s.repo.UpdateAgent(ctx, existingAgent); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": agent.ID, + }) + return nil, err + } + + logger.Infof(ctx, "Custom agent updated successfully, ID: %s", agent.ID) + return existingAgent, nil +} + +// DeleteAgent deletes an agent +func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error { + if id == "" { + logger.Error(ctx, "Agent ID is empty") + return errors.New("agent ID cannot be empty") + } + + // Cannot delete built-in agents + if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID { + return ErrCannotDeleteBuiltin + } + + // Get tenant ID from context + tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64) + if !ok { + return ErrInvalidTenantID + } + + // Get existing agent to verify ownership + existingAgent, err := s.repo.GetAgentByID(ctx, id) + if err != nil { + if errors.Is(err, repository.ErrCustomAgentNotFound) { + return ErrAgentNotFound + } + return err + } + + // Verify tenant ownership + if existingAgent.TenantID != tenantID { + return ErrAgentNotFound + } + + // Cannot delete built-in agents + if existingAgent.IsBuiltin { + return ErrCannotDeleteBuiltin + } + + logger.Infof(ctx, "Deleting custom agent, ID: %s", id) + + if err := s.repo.DeleteAgent(ctx, id); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": id, + }) + return err + } + + logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id) + return nil +} diff --git a/internal/application/service/llmcontext/context_manager.go b/internal/application/service/llmcontext/context_manager.go index 08fbb228..3bd3afe5 100644 --- a/internal/application/service/llmcontext/context_manager.go +++ b/internal/application/service/llmcontext/context_manager.go @@ -166,3 +166,42 @@ func (cm *contextManager) GetContextStats(ctx context.Context, sessionID string) return stats, nil } + +// SetSystemPrompt sets or updates the system prompt for a session +// If a system message exists, it will be replaced; otherwise, a new one will be added at the beginning +func (cm *contextManager) SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error { + logger.Infof(ctx, "[ContextManager][Session-%s] Setting system prompt, length=%d", sessionID, len(systemPrompt)) + + // Load existing messages from storage + messages, err := cm.storage.Load(ctx, sessionID) + if err != nil { + logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to load context: %v", sessionID, err) + return fmt.Errorf("failed to load context: %w", err) + } + + // Create new system message + systemMessage := chat.Message{ + Role: "system", + Content: systemPrompt, + } + + // Check if first message is a system message + if len(messages) > 0 && messages[0].Role == "system" { + // Replace existing system message + logger.Debugf(ctx, "[ContextManager][Session-%s] Replacing existing system prompt", sessionID) + messages[0] = systemMessage + } else { + // Insert system message at the beginning + logger.Debugf(ctx, "[ContextManager][Session-%s] Inserting new system prompt at beginning", sessionID) + messages = append([]chat.Message{systemMessage}, messages...) + } + + // Save updated messages to storage + if err := cm.storage.Save(ctx, sessionID, messages); err != nil { + logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to save context: %v", sessionID, err) + return fmt.Errorf("failed to save context: %w", err) + } + + logger.Infof(ctx, "[ContextManager][Session-%s] System prompt set successfully", sessionID) + return nil +} diff --git a/internal/application/service/session.go b/internal/application/service/session.go index 9aac121f..49b8274d 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -392,6 +392,7 @@ func (s *sessionService) GenerateTitleAsync( // KnowledgeQA performs knowledge base question answering with LLM summarization // Events are emitted through eventBus (references, answer chunks, completion) +// customAgent is optional - if provided, uses custom agent configuration for multiTurnEnabled and historyTurns func (s *sessionService) KnowledgeQA( ctx context.Context, session *types.Session, @@ -402,6 +403,7 @@ func (s *sessionService) KnowledgeQA( summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus, + customAgent *types.CustomAgent, ) error { logger.Infof( ctx, @@ -421,6 +423,22 @@ func (s *sessionService) KnowledgeQA( } } + // Merge custom agent's configured knowledge bases + if customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 { + // Create a set of existing knowledge base IDs to avoid duplicates + existingKBs := make(map[string]bool) + for _, kbID := range knowledgeBaseIDs { + existingKBs[kbID] = true + } + // Add agent's knowledge bases that are not already in the list + for _, kbID := range customAgent.Config.KnowledgeBases { + if !existingKBs[kbID] { + knowledgeBaseIDs = append(knowledgeBaseIDs, kbID) + logger.Infof(ctx, "Adding custom agent's knowledge base: %s", kbID) + } + } + } + logger.Infof(ctx, "Using knowledge bases: %v", knowledgeBaseIDs) // Determine chat model ID: prioritize request's summaryModelID, then Remote models @@ -514,6 +532,32 @@ func (s *sessionService) KnowledgeQA( logger.Infof(ctx, "Fallback strategy not set, using default: %v", fallbackStrategy) } + // Apply custom agent configuration if provided + multiTurnEnabled := true // Default: enable multi-turn + if customAgent != nil { + // Override system prompt with customAgent's SystemPrompt + if customAgent.Config.SystemPrompt != "" { + summaryConfig.Prompt = customAgent.Config.SystemPrompt + logger.Infof(ctx, "Using custom agent's system_prompt") + } + // Override temperature with customAgent's Temperature + if customAgent.Config.Temperature > 0 { + summaryConfig.Temperature = customAgent.Config.Temperature + logger.Infof(ctx, "Using custom agent's temperature: %f", customAgent.Config.Temperature) + } + // Override maxRounds with customAgent's HistoryTurns + if customAgent.Config.HistoryTurns > 0 { + maxRounds = customAgent.Config.HistoryTurns + logger.Infof(ctx, "Using custom agent's history_turns: %d", maxRounds) + } + // Check if multi-turn is disabled + multiTurnEnabled = customAgent.Config.MultiTurnEnabled + if !multiTurnEnabled { + maxRounds = 0 // Disable history + logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history") + } + } + // Build unified search targets (computed once, used throughout pipeline) searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs) if err != nil { @@ -962,12 +1006,14 @@ func (s *sessionService) SearchKnowledge(ctx context.Context, } // AgentQA performs agent-based question answering with conversation history and streaming support +// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults func (s *sessionService) AgentQA( ctx context.Context, session *types.Session, query string, assistantMessageID string, eventBus *event.EventBus, + customAgent *types.CustomAgent, ) error { sessionID := session.ID tenantID := ctx.Value(types.TenantIDContextKey).(uint64) @@ -1004,29 +1050,82 @@ func (s *sessionService) AgentQA( } } - // Create runtime AgentConfig by merging session and tenant configs - // Tenant config provides the runtime parameters (MaxIterations, Temperature, Tools, Models) + // Create runtime AgentConfig + // Priority: CustomAgent config > Tenant config > Defaults // Session config provides KnowledgeBases and KnowledgeIDs - agentConfig := &types.AgentConfig{ - MaxIterations: tenantInfo.AgentConfig.MaxIterations, - ReflectionEnabled: tenantInfo.AgentConfig.ReflectionEnabled, - AllowedTools: tools.DefaultAllowedTools(), - Temperature: tenantInfo.AgentConfig.Temperature, - KnowledgeBases: session.AgentConfig.KnowledgeBases, // Use session's knowledge bases - KnowledgeIDs: session.AgentConfig.KnowledgeIDs, // Use session's knowledge IDs (individual documents) - WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config + var agentConfig *types.AgentConfig + + if customAgent != nil && customAgent.ID != types.BuiltinAgentNormalID && customAgent.ID != types.BuiltinAgentAgentID { + // Use custom agent configuration + logger.Infof(ctx, "Using custom agent configuration, agent ID: %s, name: %s", customAgent.ID, customAgent.Name) + customAgent.EnsureDefaults() + + agentConfig = &types.AgentConfig{ + MaxIterations: customAgent.Config.MaxIterations, + ReflectionEnabled: customAgent.Config.ReflectionEnabled, + Temperature: customAgent.Config.Temperature, + WebSearchEnabled: customAgent.Config.WebSearchEnabled, + WebSearchMaxResults: customAgent.Config.WebSearchMaxResults, + MultiTurnEnabled: customAgent.Config.MultiTurnEnabled, + HistoryTurns: customAgent.Config.HistoryTurns, + } + + // Use custom agent's allowed tools if specified, otherwise use defaults + if len(customAgent.Config.AllowedTools) > 0 { + agentConfig.AllowedTools = customAgent.Config.AllowedTools + } else { + agentConfig.AllowedTools = tools.DefaultAllowedTools() + } + + // Use custom agent's system prompt if specified + if customAgent.Config.SystemPrompt != "" { + agentConfig.UseCustomSystemPrompt = true + agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt + agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt + } + + // Use custom agent's knowledge bases if specified, otherwise use session's + if len(customAgent.Config.KnowledgeBases) > 0 { + agentConfig.KnowledgeBases = customAgent.Config.KnowledgeBases + } else { + agentConfig.KnowledgeBases = session.AgentConfig.KnowledgeBases + } + agentConfig.KnowledgeIDs = session.AgentConfig.KnowledgeIDs + + // Override summary model if custom agent specifies one + if customAgent.Config.ModelID != "" { + session.SummaryModelID = customAgent.Config.ModelID + } + + logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v", + agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled) + } else { + // Use tenant configuration (default behavior) + agentConfig = &types.AgentConfig{ + MaxIterations: tenantInfo.AgentConfig.MaxIterations, + ReflectionEnabled: tenantInfo.AgentConfig.ReflectionEnabled, + AllowedTools: tools.DefaultAllowedTools(), + Temperature: tenantInfo.AgentConfig.Temperature, + KnowledgeBases: session.AgentConfig.KnowledgeBases, // Use session's knowledge bases + KnowledgeIDs: session.AgentConfig.KnowledgeIDs, // Use session's knowledge IDs (individual documents) + WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config + MultiTurnEnabled: true, // Default: enable multi-turn + HistoryTurns: 5, // Default: keep 5 turns + } + + agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt + if agentConfig.UseCustomSystemPrompt { + agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true) + agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false) + } } - agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt - if agentConfig.UseCustomSystemPrompt { - agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true) - agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false) - } - - // Set web search max results from tenant config (default: 5) - agentConfig.WebSearchMaxResults = 5 - if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 { - agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults + // Set web search max results from tenant config if not set (default: 5) + if agentConfig.WebSearchMaxResults == 0 { + agentConfig.WebSearchMaxResults = 5 + if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 { + agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults + } } logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, sessionID) @@ -1099,6 +1198,18 @@ func (s *sessionService) AgentQA( // Get or create contextManager for this session contextManager := s.getContextManagerForSession(ctx, session, summaryModel) + + // Set system prompt for the current agent in context manager + // This ensures the context uses the correct system prompt when switching agents + systemPrompt := agentConfig.ResolveSystemPrompt(agentConfig.WebSearchEnabled) + if systemPrompt != "" { + if err := contextManager.SetSystemPrompt(ctx, sessionID, systemPrompt); err != nil { + logger.Warnf(ctx, "Failed to set system prompt in context manager: %v", err) + } else { + logger.Infof(ctx, "System prompt updated in context manager for agent") + } + } + // Get LLM context from context manager llmContext, err := s.getContextForSession(ctx, contextManager, sessionID) if err != nil { @@ -1107,6 +1218,15 @@ func (s *sessionService) AgentQA( } logger.Infof(ctx, "Loaded %d messages from LLM context manager", len(llmContext)) + // Apply multi-turn configuration for Agent mode + // Note: In Agent mode, context is managed by contextManager with compression strategies, + // so we don't apply HistoryTurns limit here. HistoryTurns is used in normal (KnowledgeQA) mode. + if !agentConfig.MultiTurnEnabled { + // Multi-turn disabled, clear history + logger.Infof(ctx, "Multi-turn disabled for this agent, clearing history context") + llmContext = []chat.Message{} + } + // Create agent engine with EventBus and ContextManager logger.Info(ctx, "Creating agent engine") engine, err := s.agentService.CreateAgentEngine( diff --git a/internal/container/container.go b/internal/container/container.go index 0df1e411..45d7720e 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -97,6 +97,7 @@ func BuildContainer(container *dig.Container) *dig.Container { must(container.Provide(repository.NewAuthTokenRepository)) must(container.Provide(neo4jRepo.NewNeo4jRepository)) must(container.Provide(repository.NewMCPServiceRepository)) + must(container.Provide(repository.NewCustomAgentRepository)) // MCP manager for managing MCP client connections must(container.Provide(mcp.NewMCPManager)) @@ -115,6 +116,7 @@ func BuildContainer(container *dig.Container) *dig.Container { must(container.Provide(service.NewChunkExtractService)) must(container.Provide(service.NewMessageService)) must(container.Provide(service.NewMCPServiceService)) + must(container.Provide(service.NewCustomAgentService)) // Web search service (needed by AgentService) must(container.Provide(service.NewWebSearchService)) @@ -163,6 +165,7 @@ func BuildContainer(container *dig.Container) *dig.Container { must(container.Provide(handler.NewSystemHandler)) must(container.Provide(handler.NewMCPServiceHandler)) must(container.Provide(handler.NewWebSearchHandler)) + must(container.Provide(handler.NewCustomAgentHandler)) // Router configuration must(container.Provide(router.NewRouter)) diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go new file mode 100644 index 00000000..b147fcb8 --- /dev/null +++ b/internal/handler/custom_agent.go @@ -0,0 +1,298 @@ +package handler + +import ( + "net/http" + + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + secutils "github.com/Tencent/WeKnora/internal/utils" + "github.com/gin-gonic/gin" +) + +// CustomAgentHandler defines the HTTP handler for custom agent operations +type CustomAgentHandler struct { + service interfaces.CustomAgentService +} + +// NewCustomAgentHandler creates a new custom agent handler instance +func NewCustomAgentHandler(service interfaces.CustomAgentService) *CustomAgentHandler { + return &CustomAgentHandler{ + service: service, + } +} + +// CreateAgentRequest defines the request body for creating an agent +type CreateAgentRequest struct { + Name string `json:"name" binding:"required"` + Description string `json:"description"` + Avatar string `json:"avatar"` + Type types.CustomAgentType `json:"type"` + Config types.CustomAgentConfig `json:"config"` +} + +// UpdateAgentRequest defines the request body for updating an agent +type UpdateAgentRequest struct { + Name string `json:"name" binding:"required"` + Description string `json:"description"` + Avatar string `json:"avatar"` + Type types.CustomAgentType `json:"type"` + Config types.CustomAgentConfig `json:"config"` +} + +// CreateAgent godoc +// @Summary 创建智能体 +// @Description 创建新的自定义智能体 +// @Tags 智能体 +// @Accept json +// @Produce json +// @Param request body CreateAgentRequest true "智能体信息" +// @Success 201 {object} map[string]interface{} "创建的智能体" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /agents [post] +func (h *CustomAgentHandler) CreateAgent(c *gin.Context) { + ctx := c.Request.Context() + + logger.Info(ctx, "Start creating custom agent") + + // Parse request body + var req CreateAgentRequest + if err := c.ShouldBindJSON(&req); err != nil { + logger.Error(ctx, "Failed to parse request parameters", err) + c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error())) + return + } + + // Build agent object + agent := &types.CustomAgent{ + Name: req.Name, + Description: req.Description, + Avatar: req.Avatar, + Type: req.Type, + Config: req.Config, + } + + logger.Infof(ctx, "Creating custom agent, name: %s, type: %s", + secutils.SanitizeForLog(req.Name), req.Type) + + // Create agent using the service + createdAgent, err := h.service.CreateAgent(ctx, agent) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + if err == service.ErrAgentNameRequired { + c.Error(errors.NewBadRequestError(err.Error())) + return + } + c.Error(errors.NewInternalServerError(err.Error())) + return + } + + logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s", + secutils.SanitizeForLog(createdAgent.ID), secutils.SanitizeForLog(createdAgent.Name)) + c.JSON(http.StatusCreated, gin.H{ + "success": true, + "data": createdAgent, + }) +} + +// GetAgent godoc +// @Summary 获取智能体详情 +// @Description 根据ID获取智能体详情 +// @Tags 智能体 +// @Accept json +// @Produce json +// @Param id path string true "智能体ID" +// @Success 200 {object} map[string]interface{} "智能体详情" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Failure 404 {object} errors.AppError "智能体不存在" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /agents/{id} [get] +func (h *CustomAgentHandler) GetAgent(c *gin.Context) { + ctx := c.Request.Context() + + // 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 + } + + agent, err := h.service.GetAgentByID(ctx, id) + if err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": id, + }) + if err == service.ErrAgentNotFound { + c.Error(errors.NewNotFoundError("Agent not found")) + return + } + c.Error(errors.NewInternalServerError(err.Error())) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": agent, + }) +} + +// ListAgents godoc +// @Summary 获取智能体列表 +// @Description 获取当前租户的所有智能体(包括内置智能体) +// @Tags 智能体 +// @Accept json +// @Produce json +// @Success 200 {object} map[string]interface{} "智能体列表" +// @Failure 500 {object} errors.AppError "服务器错误" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /agents [get] +func (h *CustomAgentHandler) ListAgents(c *gin.Context) { + ctx := c.Request.Context() + + // Get all agents for this tenant + agents, err := h.service.ListAgents(ctx) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + c.Error(errors.NewInternalServerError(err.Error())) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": agents, + }) +} + +// UpdateAgent godoc +// @Summary 更新智能体 +// @Description 更新智能体的名称、描述和配置 +// @Tags 智能体 +// @Accept json +// @Produce json +// @Param id path string true "智能体ID" +// @Param request body UpdateAgentRequest true "更新请求" +// @Success 200 {object} map[string]interface{} "更新后的智能体" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Failure 403 {object} errors.AppError "无法修改内置智能体" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /agents/{id} [put] +func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) { + ctx := c.Request.Context() + + logger.Info(ctx, "Start updating 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 + } + + // Parse request body + var req UpdateAgentRequest + if err := c.ShouldBindJSON(&req); err != nil { + logger.Error(ctx, "Failed to parse request parameters", err) + c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error())) + return + } + + // Build agent object + agent := &types.CustomAgent{ + ID: id, + Name: req.Name, + Description: req.Description, + Avatar: req.Avatar, + Type: req.Type, + Config: req.Config, + } + + logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s", + secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.Name)) + + // Update the agent + updatedAgent, err := h.service.UpdateAgent(ctx, agent) + 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")) + case service.ErrCannotModifyBuiltin: + c.Error(errors.NewForbiddenError("Cannot modify built-in agent")) + case service.ErrAgentNameRequired: + c.Error(errors.NewBadRequestError(err.Error())) + default: + c.Error(errors.NewInternalServerError(err.Error())) + } + return + } + + logger.Infof(ctx, "Custom agent updated successfully, ID: %s", secutils.SanitizeForLog(id)) + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": updatedAgent, + }) +} + +// DeleteAgent godoc +// @Summary 删除智能体 +// @Description 删除指定的智能体 +// @Tags 智能体 +// @Accept json +// @Produce json +// @Param id path string true "智能体ID" +// @Success 200 {object} map[string]interface{} "删除成功" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Failure 403 {object} errors.AppError "无法删除内置智能体" +// @Failure 404 {object} errors.AppError "智能体不存在" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /agents/{id} [delete] +func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) { + ctx := c.Request.Context() + + logger.Info(ctx, "Start deleting 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, "Deleting custom agent, ID: %s", secutils.SanitizeForLog(id)) + + // Delete the agent + err := h.service.DeleteAgent(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")) + case service.ErrCannotDeleteBuiltin: + c.Error(errors.NewForbiddenError("Cannot delete built-in agent")) + default: + c.Error(errors.NewInternalServerError(err.Error())) + } + return + } + + logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", secutils.SanitizeForLog(id)) + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": "Agent deleted successfully", + }) +} diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index 0ed065e6..ee3e0cb7 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -20,6 +20,7 @@ type Handler struct { streamManager interfaces.StreamManager // Manager for handling streaming responses config *config.Config // Application configuration knowledgebaseService interfaces.KnowledgeBaseService // Service for managing knowledge bases + customAgentService interfaces.CustomAgentService // Service for managing custom agents } // NewHandler creates a new instance of Handler with all necessary dependencies @@ -29,6 +30,7 @@ func NewHandler( streamManager interfaces.StreamManager, config *config.Config, knowledgebaseService interfaces.KnowledgeBaseService, + customAgentService interfaces.CustomAgentService, ) *Handler { return &Handler{ sessionService: sessionService, @@ -36,6 +38,7 @@ func NewHandler( streamManager: streamManager, config: config, knowledgebaseService: knowledgebaseService, + customAgentService: customAgentService, } } diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 7c7ad8a6..ea993233 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -16,6 +16,256 @@ import ( "github.com/gin-gonic/gin" ) +// qaRequestContext holds all the common data needed for QA requests +type qaRequestContext struct { + ctx context.Context + c *gin.Context + sessionID string + requestID string + query string + session *types.Session + customAgent *types.CustomAgent + assistantMessage *types.Message + knowledgeBaseIDs []string + knowledgeIDs []string + summaryModelID string + webSearchEnabled bool + mentionedItems types.MentionedItems +} + +// parseQARequest parses and validates a QA request, returns the request context +func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) { + ctx := logger.CloneContext(c.Request.Context()) + logger.Infof(ctx, "[%s] Start processing request", logPrefix) + + // Get session ID from URL parameter + sessionID := secutils.SanitizeForLog(c.Param("session_id")) + if sessionID == "" { + logger.Error(ctx, "Session ID is empty") + return nil, nil, errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()) + } + + // Parse request body + var request CreateKnowledgeQARequest + if err := c.ShouldBindJSON(&request); err != nil { + logger.Error(ctx, "Failed to parse request data", err) + return nil, nil, errors.NewBadRequestError(err.Error()) + } + + // Validate query content + if request.Query == "" { + logger.Error(ctx, "Query content is empty") + return nil, nil, errors.NewBadRequestError("Query content cannot be empty") + } + + // Log request details + if requestJSON, err := json.Marshal(request); err == nil { + logger.Infof(ctx, "[%s] Request: session_id=%s, request=%s", + logPrefix, sessionID, secutils.SanitizeForLog(string(requestJSON))) + } + + // Get session + session, err := h.sessionService.GetSession(ctx, sessionID) + if err != nil { + logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err) + return nil, nil, errors.NewNotFoundError("Session not found") + } + + // Get custom agent if agent_id is provided + var customAgent *types.CustomAgent + if request.AgentID != "" { + logger.Infof(ctx, "Fetching custom agent, agent ID: %s", secutils.SanitizeForLog(request.AgentID)) + agent, err := h.customAgentService.GetAgentByID(ctx, request.AgentID) + if err != nil { + logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config", + secutils.SanitizeForLog(request.AgentID), err) + } else { + customAgent = agent + logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, Type=%s, AgentMode=%s", + customAgent.ID, customAgent.Name, customAgent.Type, customAgent.Config.AgentMode) + } + } + + // Build request context + reqCtx := &qaRequestContext{ + ctx: ctx, + c: c, + sessionID: sessionID, + requestID: secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String())), + query: secutils.SanitizeForLog(request.Query), + session: session, + customAgent: customAgent, + assistantMessage: &types.Message{ + SessionID: sessionID, + Role: "assistant", + RequestID: c.GetString(types.RequestIDContextKey.String()), + IsCompleted: false, + }, + knowledgeBaseIDs: secutils.SanitizeForLogArray(request.KnowledgeBaseIDs), + knowledgeIDs: secutils.SanitizeForLogArray(request.KnowledgeIds), + summaryModelID: secutils.SanitizeForLog(request.SummaryModelID), + webSearchEnabled: request.WebSearchEnabled, + mentionedItems: convertMentionedItems(request.MentionedItems), + } + + return reqCtx, &request, nil +} + +// detectAndApplyConfigChanges detects configuration changes and updates session if needed +// Returns true if any configuration changed +func (h *Handler) detectAndApplyConfigChanges( + reqCtx *qaRequestContext, + request *CreateKnowledgeQARequest, +) (bool, error) { + ctx := reqCtx.ctx + session := reqCtx.session + sessionID := reqCtx.sessionID + + // Initialize AgentConfig if it doesn't exist + if session.AgentConfig == nil { + session.AgentConfig = &types.SessionAgentConfig{} + } + + configChanged := false + + // Check knowledge bases change + if hasArrayChanged(session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs) { + logger.Infof(ctx, "Knowledge bases changed from %v to %v", + session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs) + configChanged = true + } + + // Check knowledge IDs change + if hasArrayChanged(session.AgentConfig.KnowledgeIDs, request.KnowledgeIds) { + logger.Infof(ctx, "Knowledge IDs changed from %v to %v", + session.AgentConfig.KnowledgeIDs, request.KnowledgeIds) + configChanged = true + } + + // Check agent mode change + if request.AgentEnabled != session.AgentConfig.AgentModeEnabled { + logger.Infof(ctx, "Agent mode changed from %v to %v", + session.AgentConfig.AgentModeEnabled, request.AgentEnabled) + configChanged = true + } + + // Check web search change + if request.WebSearchEnabled != session.AgentConfig.WebSearchEnabled { + logger.Infof(ctx, "Web search mode changed from %v to %v", + session.AgentConfig.WebSearchEnabled, request.WebSearchEnabled) + configChanged = true + } + + // Resolve summary model ID + summaryModelID := reqCtx.summaryModelID + if summaryModelID == "" { + summaryModelID = session.SummaryModelID + } + if summaryModelID == "" { + if tenantInfo, ok := ctx.Value(types.TenantInfoContextKey).(*types.Tenant); ok && tenantInfo.ConversationConfig != nil { + summaryModelID = tenantInfo.ConversationConfig.SummaryModelID + } + } + if summaryModelID != session.SummaryModelID { + configChanged = true + } + + // Apply changes if any + if configChanged { + logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID) + + // Clear LLM context + if err := h.sessionService.ClearContext(ctx, sessionID); err != nil { + logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err) + } + + // Delete temp KB state + if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil { + logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err) + } + + // Update session config + session.AgentConfig.KnowledgeBases = secutils.SanitizeForLogArray(request.KnowledgeBaseIDs) + session.AgentConfig.KnowledgeIDs = secutils.SanitizeForLogArray(request.KnowledgeIds) + session.AgentConfig.AgentModeEnabled = request.AgentEnabled + session.AgentConfig.WebSearchEnabled = request.WebSearchEnabled + session.SummaryModelID = summaryModelID + + // Persist changes + if err := h.sessionService.UpdateSession(ctx, session); err != nil { + logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err) + return false, errors.NewInternalServerError("Failed to update session configuration") + } + logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID) + } + + return configChanged, nil +} + +// hasArrayChanged checks if two string arrays are different +func hasArrayChanged(current, new []string) bool { + if len(current) != len(new) { + return true + } + if len(current) == 0 && len(new) == 0 { + return false + } + + currentMap := make(map[string]bool) + for _, v := range current { + currentMap[v] = true + } + for _, v := range new { + if !currentMap[v] { + return true + } + } + return false +} + +// sseStreamContext holds the context for SSE streaming +type sseStreamContext struct { + eventBus *event.EventBus + asyncCtx context.Context + cancel context.CancelFunc + assistantMessage *types.Message +} + +// setupSSEStream sets up the SSE streaming context +func (h *Handler) setupSSEStream(reqCtx *qaRequestContext) *sseStreamContext { + // Set SSE headers + setSSEHeaders(reqCtx.c) + + // Write initial agent_query event + h.writeAgentQueryEvent(reqCtx.ctx, reqCtx.sessionID, reqCtx.assistantMessage.ID) + + // Create EventBus and cancellable context + eventBus := event.NewEventBus() + asyncCtx, cancel := context.WithCancel(logger.CloneContext(reqCtx.ctx)) + + streamCtx := &sseStreamContext{ + eventBus: eventBus, + asyncCtx: asyncCtx, + cancel: cancel, + assistantMessage: reqCtx.assistantMessage, + } + + // Setup stop event handler + h.setupStopEventHandler(eventBus, reqCtx.sessionID, reqCtx.assistantMessage, cancel) + + // Setup stream handler + h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID, + reqCtx.requestID, reqCtx.assistantMessage, eventBus) + + // Generate title if needed + if reqCtx.session.Title == "" { + logger.Infof(reqCtx.ctx, "Session has no title, starting async title generation, session ID: %s", reqCtx.sessionID) + h.sessionService.GenerateTitleAsync(asyncCtx, reqCtx.session, reqCtx.query, eventBus) + } + + return streamCtx +} + // SearchKnowledge godoc // @Summary 知识搜索 // @Description 在知识库中搜索(不使用LLM总结) @@ -30,7 +280,6 @@ import ( // @Router /sessions/search [post] func (h *Handler) SearchKnowledge(c *gin.Context) { ctx := logger.CloneContext(c.Request.Context()) - logger.Info(ctx, "Start processing knowledge search request") // Parse request body @@ -54,14 +303,11 @@ func (h *Handler) SearchKnowledge(c *gin.Context) { return } - logger.Infof( - ctx, - "Knowledge search request, knowledge base ID: %s, query: %s", + logger.Infof(ctx, "Knowledge search request, knowledge base ID: %s, query: %s", secutils.SanitizeForLog(request.KnowledgeBaseID), - secutils.SanitizeForLog(request.Query), - ) + secutils.SanitizeForLog(request.Query)) - // Directly call knowledge retrieval service without LLM summarization + // Perform search searchResults, err := h.sessionService.SearchKnowledge(ctx, request.KnowledgeBaseID, request.Query) if err != nil { logger.ErrorWithFields(ctx, err, nil) @@ -70,8 +316,6 @@ func (h *Handler) SearchKnowledge(c *gin.Context) { } logger.Infof(ctx, "Knowledge search completed, found %d results", len(searchResults)) - - // Return search results c.JSON(http.StatusOK, gin.H{ "success": true, "data": searchResults, @@ -92,73 +336,15 @@ func (h *Handler) SearchKnowledge(c *gin.Context) { // @Security ApiKeyAuth // @Router /sessions/{session_id}/knowledge-qa [post] func (h *Handler) KnowledgeQA(c *gin.Context) { - ctx := logger.CloneContext(c.Request.Context()) - - logger.Info(ctx, "Start processing knowledge QA request") - - // Get session ID from URL parameter - sessionID := secutils.SanitizeForLog(c.Param("session_id")) - if sessionID == "" { - logger.Error(ctx, "Session ID is empty") - c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error())) - return - } - - // Parse request body - var request CreateKnowledgeQARequest - if err := c.ShouldBindJSON(&request); err != nil { - logger.Error(ctx, "Failed to parse request data", err) - c.Error(errors.NewBadRequestError(err.Error())) - return - } - - // Create assistant message - assistantMessage := &types.Message{ - SessionID: sessionID, - Role: "assistant", - RequestID: c.GetString(types.RequestIDContextKey.String()), - IsCompleted: false, - } - - // Validate query content - if request.Query == "" { - logger.Error(ctx, "Query content is empty") - c.Error(errors.NewBadRequestError("Query content cannot be empty")) - return - } - - logger.Infof( - ctx, - "Knowledge QA request, session ID: %s, query: %s", - sessionID, - secutils.SanitizeForLog(request.Query), - ) - - // Get session to prepare knowledge base IDs - session, err := h.sessionService.GetSession(ctx, sessionID) + // Parse and validate request + reqCtx, _, err := h.parseQARequest(c, "KnowledgeQA") if err != nil { - logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err) - c.Error(errors.NewInternalServerError(err.Error())) + c.Error(err) return } - // Prepare knowledge base IDs - knowledgeBaseIDs := request.KnowledgeBaseIDs - // if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" { - // knowledgeBaseIDs = []string{session.KnowledgeBaseID} - // logger.Infof( - // ctx, - // "No knowledge base IDs in request, using session default: %s", - // secutils.SanitizeForLog(session.KnowledgeBaseID), - // ) - // } - - // Use shared function to handle KnowledgeQA request - h.handleKnowledgeQARequest(ctx, c, session, secutils.SanitizeForLog(request.Query), - secutils.SanitizeForLogArray(knowledgeBaseIDs), - secutils.SanitizeForLogArray(request.KnowledgeIds), - assistantMessage, true, secutils.SanitizeForLog(request.SummaryModelID), request.WebSearchEnabled, - convertMentionedItems(request.MentionedItems)) + // Execute normal mode QA + h.executeNormalModeQA(reqCtx, true) } // AgentQA godoc @@ -175,427 +361,112 @@ func (h *Handler) KnowledgeQA(c *gin.Context) { // @Security ApiKeyAuth // @Router /sessions/{session_id}/agent-qa [post] func (h *Handler) AgentQA(c *gin.Context) { - ctx := logger.CloneContext(c.Request.Context()) - logger.Info(ctx, "Start processing agent QA request") - - // Get session ID from URL parameter - sessionID := secutils.SanitizeForLog(c.Param("session_id")) - if sessionID == "" { - logger.Error(ctx, "Session ID is empty") - c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error())) + // Parse and validate request + reqCtx, request, err := h.parseQARequest(c, "AgentQA") + if err != nil { + c.Error(err) return } - // Parse request body - var request CreateKnowledgeQARequest - if err := c.ShouldBindJSON(&request); err != nil { - logger.Error(ctx, "Failed to parse request data", err) - c.Error(errors.NewBadRequestError(err.Error())) + // Detect and apply configuration changes + if _, err := h.detectAndApplyConfigChanges(reqCtx, request); err != nil { + c.Error(err) return } - if requestJSON, err := json.Marshal(request); err == nil { - logger.Infof(ctx, "Agent QA request, request: %s", secutils.SanitizeForLog(string(requestJSON))) + + // Determine if agent mode should be enabled + // Priority: customAgent.IsAgentMode() > request.AgentEnabled + agentModeEnabled := request.AgentEnabled + if reqCtx.customAgent != nil { + agentModeEnabled = reqCtx.customAgent.IsAgentMode() + logger.Infof(reqCtx.ctx, "Agent mode determined by custom agent: %v (config.agent_mode=%s)", + agentModeEnabled, reqCtx.customAgent.Config.AgentMode) + } + + // Route to appropriate handler based on agent mode + if agentModeEnabled { + h.executeAgentModeQA(reqCtx) } else { - logger.Warnf(ctx, "failed to marshal for logging: %s", secutils.SanitizeForLog(err.Error())) - } - - // Validate query content - if request.Query == "" { - logger.Error(ctx, "Query content is empty") - c.Error(errors.NewBadRequestError("Query content cannot be empty")) - return - } - - tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - - // Get session information first - session, err := h.sessionService.GetSession(ctx, sessionID) - if err != nil { - logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err) - c.Error(errors.NewNotFoundError("Session not found")) - return - } - sessionJSON, err := json.Marshal(session) - if err != nil { - logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err) - c.Error(errors.NewInternalServerError(err.Error())) - return - } - logger.Infof(ctx, "Before AgentQA, Session: %s", secutils.SanitizeForLog(string(sessionJSON))) - - // Create assistant message - assistantMessage := &types.Message{ - SessionID: sessionID, - Role: "assistant", - RequestID: c.GetString(types.RequestIDContextKey.String()), - IsCompleted: false, - } - - // Initialize AgentConfig if it doesn't exist - if session.AgentConfig == nil { - session.AgentConfig = &types.SessionAgentConfig{} - } - - // Detect if knowledge bases or agent mode has changed - knowledgeBasesChanged := false - knowledgeIdsChanged := false - configChanged := false - - // Check if knowledge bases array has changed - if len(request.KnowledgeBaseIDs) > 0 || len(session.AgentConfig.KnowledgeBases) > 0 { - // Compare arrays to detect changes - currentKBs := session.AgentConfig.KnowledgeBases - if len(currentKBs) != len(request.KnowledgeBaseIDs) { - knowledgeBasesChanged = true - configChanged = true - } else { - // Check if contents are different - kbMap := make(map[string]bool) - for _, kb := range currentKBs { - kbMap[kb] = true - } - for _, kb := range request.KnowledgeBaseIDs { - if !kbMap[kb] { - knowledgeBasesChanged = true - configChanged = true - break - } - } + logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID) + // Fallback to session's knowledge bases if not specified in request + if len(reqCtx.knowledgeBaseIDs) == 0 { + reqCtx.knowledgeBaseIDs = reqCtx.session.AgentConfig.KnowledgeBases } - if knowledgeBasesChanged { - logger.Infof(ctx, "Knowledge bases changed from %s to %s", - secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeBases)), - secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeBaseIDs)), - ) + if len(reqCtx.knowledgeBaseIDs) == 0 && reqCtx.session.KnowledgeBaseID != "" { + reqCtx.knowledgeBaseIDs = []string{reqCtx.session.KnowledgeBaseID} } + h.executeNormalModeQA(reqCtx, false) } - - // Check if knowledge IDs array has changed - if len(request.KnowledgeIds) > 0 || len(session.AgentConfig.KnowledgeIDs) > 0 { - // Compare arrays to detect changes - currentKIDs := session.AgentConfig.KnowledgeIDs - if len(currentKIDs) != len(request.KnowledgeIds) { - knowledgeIdsChanged = true - configChanged = true - } else { - // Check if contents are different - kidMap := make(map[string]bool) - for _, kid := range currentKIDs { - kidMap[kid] = true - } - for _, kid := range request.KnowledgeIds { - if !kidMap[kid] { - knowledgeIdsChanged = true - configChanged = true - break - } - } - } - if knowledgeIdsChanged { - logger.Infof(ctx, "Knowledge IDs changed from %s to %s", - secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeIDs)), - secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeIds)), - ) - } - } - - // Check if agent mode has changed - currentAgentEnabled := session.AgentConfig.AgentModeEnabled - if request.AgentEnabled != currentAgentEnabled { - logger.Infof(ctx, "Agent mode changed from %v to %v", currentAgentEnabled, request.AgentEnabled) - configChanged = true - } - currentWebSearchEnabled := session.AgentConfig.WebSearchEnabled - if request.WebSearchEnabled != currentWebSearchEnabled { - logger.Infof(ctx, "Web search mode changed from %v to %v", currentWebSearchEnabled, request.WebSearchEnabled) - configChanged = true - } - summaryModelID := secutils.SanitizeForLog(request.SummaryModelID) - if summaryModelID == "" { - summaryModelID = session.SummaryModelID - } - if summaryModelID == "" && tenantInfo.ConversationConfig != nil { - summaryModelID = tenantInfo.ConversationConfig.SummaryModelID - } - if summaryModelID != session.SummaryModelID { - configChanged = true - session.SummaryModelID = summaryModelID - } - - // If configuration changed, clear context and update session - if configChanged { - logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID) - // Clear the LLM context to prevent contamination - if err := h.sessionService.ClearContext(ctx, sessionID); err != nil { - logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err) - // Continue anyway - this is not a fatal error - } - if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil { - logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err) - // Continue anyway - this is not a fatal error - } - session.AgentConfig.KnowledgeBases = secutils.SanitizeForLogArray(request.KnowledgeBaseIDs) - session.AgentConfig.KnowledgeIDs = secutils.SanitizeForLogArray(request.KnowledgeIds) - session.AgentConfig.AgentModeEnabled = request.AgentEnabled - session.AgentConfig.WebSearchEnabled = request.WebSearchEnabled - session.SummaryModelID = secutils.SanitizeForLog(summaryModelID) - // Persist the session changes - if err := h.sessionService.UpdateSession(ctx, session); err != nil { - logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err) - c.Error(errors.NewInternalServerError("Failed to update session configuration")) - return - } - logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID) - } - - // If Agent mode is disabled, delegate to KnowledgeQA - if !request.AgentEnabled { - logger.Infof(ctx, "Agent mode disabled, delegating to KnowledgeQA for session: %s", sessionID) - - // Use knowledge bases from request or session config - knowledgeBaseIDs := secutils.SanitizeForLogArray(request.KnowledgeBaseIDs) - if len(knowledgeBaseIDs) == 0 { - knowledgeBaseIDs = session.AgentConfig.KnowledgeBases - } - - // If still empty, use session default knowledge base - if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" { - knowledgeBaseIDs = []string{session.KnowledgeBaseID} - logger.Infof( - ctx, - "Using session default knowledge base: %s", - secutils.SanitizeForLog(session.KnowledgeBaseID), - ) - } - - logger.Infof( - ctx, - "Delegating to KnowledgeQA with knowledge bases: %s", - secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs)), - ) - - // Use shared function to handle KnowledgeQA request (no title generation for AgentQA fallback) - h.handleKnowledgeQARequest( - ctx, - c, - session, - secutils.SanitizeForLog(request.Query), - secutils.SanitizeForLogArray( - knowledgeBaseIDs, - ), - secutils.SanitizeForLogArray( - request.KnowledgeIds, - ), - assistantMessage, - false, - secutils.SanitizeForLog(request.SummaryModelID), - request.WebSearchEnabled, - convertMentionedItems(request.MentionedItems), - ) - return - } - - // Emit agent query event to create user message - requestID := secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String())) - if err := event.Emit(ctx, event.Event{ - Type: event.EventAgentQuery, - SessionID: sessionID, - RequestID: requestID, - Data: event.AgentQueryData{ - SessionID: sessionID, - Query: secutils.SanitizeForLog(request.Query), - RequestID: requestID, - }, - }); err != nil { - logger.Errorf(ctx, "Failed to emit agent query event: %v", err) - return - } - - // Set headers for SSE immediately - setSSEHeaders(c) - - // Create user message - if err := h.createUserMessage(ctx, sessionID, secutils.SanitizeForLog(request.Query), requestID, convertMentionedItems(request.MentionedItems)); err != nil { - c.Error(errors.NewInternalServerError(err.Error())) - return - } - - // Create assistant message (response) - assistantMessagePtr, err := h.createAssistantMessage(ctx, assistantMessage) - if err != nil { - c.Error(errors.NewInternalServerError(err.Error())) - return - } - assistantMessage = assistantMessagePtr - - logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID) - - // Write initial agent_query event to StreamManager - h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID) - - eventBus := event.NewEventBus() - // Create cancellable context for async operations - asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx)) - // Create and subscribe stream handler - h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus) - - // Start async title generation if session has no title - if session.Title == "" { - logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID) - h.sessionService.GenerateTitleAsync(asyncCtx, session, secutils.SanitizeForLog(request.Query), eventBus) - } - - // Register stop event handler to cancel the context - h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel) - - go func() { - defer func() { - if r := recover(); r != nil { - buf := make([]byte, 1024) - runtime.Stack(buf, true) - logger.ErrorWithFields(asyncCtx, - errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))), - map[string]interface{}{ - "session_id": sessionID, - }) - } - h.completeAssistantMessage(asyncCtx, assistantMessage) - logger.Infof(asyncCtx, "Agent QA service completed for session: %s", sessionID) - }() - err := h.sessionService.AgentQA( - asyncCtx, - session, - secutils.SanitizeForLog(request.Query), - assistantMessage.ID, - eventBus, - ) - if err != nil { - logger.ErrorWithFields(asyncCtx, err, nil) - // Emit error event to dedicated EventBus - eventBus.Emit(asyncCtx, event.Event{ - Type: event.EventError, - SessionID: sessionID, - Data: event.ErrorData{ - Error: err.Error(), - Stage: "agent_execution", - SessionID: sessionID, - }, - }) - return - } - }() - - // Handle events for SSE (blocking until connection is done) - // Wait for title only if session has no title (first message in session) - h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "") } -// handleKnowledgeQARequest handles a KnowledgeQA request with the given parameters -// This is a shared function used by both KnowledgeQA endpoint and AgentQA fallback -func (h *Handler) handleKnowledgeQARequest( - ctx context.Context, - c *gin.Context, - session *types.Session, - query string, - knowledgeBaseIDs []string, - knowledgeIDs []string, - assistantMessage *types.Message, - generateTitle bool, // Whether to generate title if session has no title - summaryModelID string, // Optional summary model ID (overrides session default) - webSearchEnabled bool, // Whether web search is enabled - mentionedItems types.MentionedItems, // @mentioned knowledge bases and files -) { - sessionID := session.ID - requestID := getRequestID(c) +// executeNormalModeQA executes the normal (KnowledgeQA) mode +func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle bool) { + ctx := reqCtx.ctx + sessionID := reqCtx.sessionID // Create user message - if err := h.createUserMessage(ctx, sessionID, query, requestID, mentionedItems); err != nil { - c.Error(errors.NewInternalServerError(err.Error())) + if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil { + reqCtx.c.Error(errors.NewInternalServerError(err.Error())) return } - // Create assistant message (response) - if _, err := h.createAssistantMessage(ctx, assistantMessage); err != nil { - c.Error(errors.NewInternalServerError(err.Error())) + // Create assistant message + if _, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage); err != nil { + reqCtx.c.Error(errors.NewInternalServerError(err.Error())) return } - logger.Infof(ctx, "Using knowledge bases: %s", secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs))) + logger.Infof(ctx, "Using knowledge bases: %v", reqCtx.knowledgeBaseIDs) - // Set headers for SSE - setSSEHeaders(c) + // Setup SSE stream + streamCtx := h.setupSSEStream(reqCtx) - // Write initial agent_query event to StreamManager - h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID) - - // Create dedicated EventBus for this request - eventBus := event.NewEventBus() - // Create cancellable context for async operations - asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx)) - - // Register stop event handler and setup stream handler - h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel) - h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus) - - // Generate title if needed - if generateTitle && session.Title == "" { - logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID) - h.sessionService.GenerateTitleAsync(asyncCtx, session, query, eventBus) - } - - eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error { + // Setup completion handler for normal mode + streamCtx.eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error { data, ok := evt.Data.(event.AgentFinalAnswerData) if !ok { return nil } - assistantMessage.Content += data.Content + streamCtx.assistantMessage.Content += data.Content if data.Done { - logger.Infof(asyncCtx, "Knowledge QA service completed for session: %s", sessionID) - h.completeAssistantMessage(asyncCtx, assistantMessage) - // Emit completion event when stream finishes - if err := eventBus.Emit(asyncCtx, event.Event{ + logger.Infof(streamCtx.asyncCtx, "Knowledge QA service completed for session: %s", sessionID) + h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage) + streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{ Type: event.EventAgentComplete, SessionID: sessionID, - Data: event.AgentCompleteData{ - FinalAnswer: assistantMessage.Content, - }, - }); err != nil { - logger.Errorf(asyncCtx, "Failed to emit completion event: %v", err) - } - cancel() // Clean up context - return nil + Data: event.AgentCompleteData{FinalAnswer: streamCtx.assistantMessage.Content}, + }) + streamCtx.cancel() } return nil }) - // Call service to perform knowledge QA (async, emits events) + // Execute KnowledgeQA asynchronously go func() { defer func() { if r := recover(); r != nil { buf := make([]byte, 10240) runtime.Stack(buf, true) - logger.ErrorWithFields( - asyncCtx, - errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))), - nil, - ) + logger.ErrorWithFields(streamCtx.asyncCtx, + errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))), nil) } }() + err := h.sessionService.KnowledgeQA( - asyncCtx, - session, - query, - knowledgeBaseIDs, - knowledgeIDs, - assistantMessage.ID, - summaryModelID, - webSearchEnabled, - eventBus, + streamCtx.asyncCtx, + reqCtx.session, + reqCtx.query, + reqCtx.knowledgeBaseIDs, + reqCtx.knowledgeIDs, + reqCtx.assistantMessage.ID, + reqCtx.summaryModelID, + reqCtx.webSearchEnabled, + streamCtx.eventBus, + reqCtx.customAgent, ) if err != nil { - logger.ErrorWithFields(asyncCtx, err, nil) - // Emit error event to dedicated EventBus - eventBus.Emit(asyncCtx, event.Event{ + logger.ErrorWithFields(streamCtx.asyncCtx, err, nil) + streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{ Type: event.EventError, SessionID: sessionID, Data: event.ErrorData{ @@ -604,13 +475,93 @@ func (h *Handler) handleKnowledgeQARequest( SessionID: sessionID, }, }) - return } }() - // Handle events for SSE (blocking until connection is done) - // Wait for title only if session has no title (first message in session) - h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "") + // Handle SSE events (blocking) + shouldWaitForTitle := generateTitle && reqCtx.session.Title == "" + h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID, + reqCtx.requestID, streamCtx.eventBus, shouldWaitForTitle) +} + +// executeAgentModeQA executes the agent mode +func (h *Handler) executeAgentModeQA(reqCtx *qaRequestContext) { + ctx := reqCtx.ctx + sessionID := reqCtx.sessionID + + // Emit agent query event + if err := event.Emit(ctx, event.Event{ + Type: event.EventAgentQuery, + SessionID: sessionID, + RequestID: reqCtx.requestID, + Data: event.AgentQueryData{ + SessionID: sessionID, + Query: reqCtx.query, + RequestID: reqCtx.requestID, + }, + }); err != nil { + logger.Errorf(ctx, "Failed to emit agent query event: %v", err) + return + } + + // Create user message + if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil { + reqCtx.c.Error(errors.NewInternalServerError(err.Error())) + return + } + + // Create assistant message + assistantMessagePtr, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage) + if err != nil { + reqCtx.c.Error(errors.NewInternalServerError(err.Error())) + return + } + reqCtx.assistantMessage = assistantMessagePtr + + logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID) + + // Setup SSE stream + streamCtx := h.setupSSEStream(reqCtx) + + // Execute AgentQA asynchronously + go func() { + defer func() { + if r := recover(); r != nil { + buf := make([]byte, 1024) + runtime.Stack(buf, true) + logger.ErrorWithFields(streamCtx.asyncCtx, + errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))), + map[string]interface{}{"session_id": sessionID}) + } + h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage) + logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID) + }() + + err := h.sessionService.AgentQA( + streamCtx.asyncCtx, + reqCtx.session, + reqCtx.query, + reqCtx.assistantMessage.ID, + streamCtx.eventBus, + reqCtx.customAgent, + ) + if err != nil { + logger.ErrorWithFields(streamCtx.asyncCtx, err, nil) + streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{ + Type: event.EventError, + SessionID: sessionID, + Data: event.ErrorData{ + Error: err.Error(), + Stage: "agent_execution", + SessionID: sessionID, + }, + }) + } + }() + + // Handle SSE events (blocking) + h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID, + reqCtx.requestID, streamCtx.eventBus, reqCtx.session.Title == "") } // completeAssistantMessage marks an assistant message as complete and updates it diff --git a/internal/handler/session/types.go b/internal/handler/session/types.go index fce15fc8..a3e4a956 100644 --- a/internal/handler/session/types.go +++ b/internal/handler/session/types.go @@ -65,6 +65,7 @@ type CreateKnowledgeQARequest struct { KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request + AgentID string `json:"agent_id"` // Selected custom agent ID for this request WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default) MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files diff --git a/internal/models/chat/remote_api.go b/internal/models/chat/remote_api.go index fc21ddf0..75041f72 100644 --- a/internal/models/chat/remote_api.go +++ b/internal/models/chat/remote_api.go @@ -199,12 +199,23 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message, "enable_thinking": thinking, } - // print req - // jsonData, err := json.Marshal(req) - // if err != nil { - // logger.Error(context.Background(), "marshal request: %w", err) - // } - // logger.Infof(context.Background(), "llm request: %s", string(jsonData)) + // Log LLM request for debugging + if jsonData, err := json.MarshalIndent(req, "", " "); err == nil { + logger.Infof(context.Background(), "[LLM Request] model=%s, stream=%v, request:\n%s", c.modelName, isStream, string(jsonData)) + } + + // Log tools/functions separately for clarity + if len(req.Tools) > 0 { + toolNames := make([]string, 0, len(req.Tools)) + for _, tool := range req.Tools { + toolNames = append(toolNames, tool.Function.Name) + } + logger.Infof(context.Background(), "[LLM Request] tools_count=%d, tool_names=%v", len(req.Tools), toolNames) + // Print full tool definitions + if toolsJSON, err := json.MarshalIndent(req.Tools, "", " "); err == nil { + logger.Infof(context.Background(), "[LLM Request] tools_definition:\n%s", string(toolsJSON)) + } + } return req } diff --git a/internal/router/router.go b/internal/router/router.go index fcf6219b..40d53704 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -47,6 +47,7 @@ type RouterParams struct { WebSearchHandler *handler.WebSearchHandler FAQHandler *handler.FAQHandler TagHandler *handler.TagHandler + CustomAgentHandler *handler.CustomAgentHandler } // NewRouter 创建新的路由 @@ -110,6 +111,7 @@ func NewRouter(params RouterParams) *gin.Engine { RegisterSystemRoutes(v1, params.SystemHandler) RegisterMCPServiceRoutes(v1, params.MCPServiceHandler) RegisterWebSearchRoutes(v1, params.WebSearchHandler) + RegisterCustomAgentRoutes(v1, params.CustomAgentHandler) } return r @@ -410,3 +412,20 @@ func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSe webSearch.GET("/providers", webSearchHandler.GetProviders) } } + +// RegisterCustomAgentRoutes registers custom agent routes +func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) { + agents := r.Group("/agents") + { + // Create custom agent + agents.POST("", agentHandler.CreateAgent) + // List all agents (including built-in) + agents.GET("", agentHandler.ListAgents) + // Get agent by ID + agents.GET("/:id", agentHandler.GetAgent) + // Update agent + agents.PUT("/:id", agentHandler.UpdateAgent) + // Delete agent + agents.DELETE("/:id", agentHandler.DeleteAgent) + } +} diff --git a/internal/types/agent.go b/internal/types/agent.go index f4529249..e9b1c020 100644 --- a/internal/types/agent.go +++ b/internal/types/agent.go @@ -21,6 +21,8 @@ type AgentConfig struct { UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5) + MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled + HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only) } diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go new file mode 100644 index 00000000..4f00e8d3 --- /dev/null +++ b/internal/types/custom_agent.go @@ -0,0 +1,186 @@ +package types + +import ( + "database/sql/driver" + "encoding/json" + "time" + + "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 +const ( + BuiltinAgentNormalID = "builtin-normal" + BuiltinAgentAgentID = "builtin-agent" +) + +// CustomAgent represents a configurable AI agent (similar to GPTs) +type CustomAgent struct { + // Unique identifier of the agent + ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"` + // Name of the agent + Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"` + // Description of the agent + Description string `yaml:"description" json:"description" gorm:"type:text"` + // Avatar/Icon of the agent (emoji or icon name) + Avatar string `yaml:"avatar" json:"avatar" gorm:"type:varchar(64)"` + // Whether this is a built-in agent (normal mode / agent mode) + IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"` + // Type of the agent: normal, agent, custom + Type CustomAgentType `yaml:"type" json:"type" gorm:"type:varchar(32);default:'custom'"` + // Tenant ID + TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"index"` + // Created by user ID + CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"` + + // Agent configuration + Config CustomAgentConfig `yaml:"config" json:"config" gorm:"type:json"` + + // Timestamps + CreatedAt time.Time `yaml:"created_at" json:"created_at"` + UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"` + DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"` +} + +// CustomAgentConfig represents the configuration of a custom agent +type CustomAgentConfig struct { + // Agent mode: "normal" for RAG mode, "agent" for ReAct agent mode + AgentMode string `yaml:"agent_mode" json:"agent_mode"` + // System prompt for the agent + SystemPrompt string `yaml:"system_prompt" json:"system_prompt"` + // Model ID to use for conversations + ModelID string `yaml:"model_id" json:"model_id"` + // Temperature for LLM (0-1) + Temperature float64 `yaml:"temperature" json:"temperature"` + // Maximum iterations for ReAct loop (only for agent type) + MaxIterations int `yaml:"max_iterations" json:"max_iterations"` + // Allowed tools (only for agent type) + AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"` + // Associated knowledge base IDs + KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"` + // Whether to allow user to select knowledge bases when no KnowledgeBases are configured + // If true (default), user can freely select any knowledge base + // If false, knowledge base selection is disabled for this agent + AllowUserKBSelection *bool `yaml:"allow_user_kb_selection" json:"allow_user_kb_selection"` + // Whether web search is enabled + WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"` + // Maximum web search results + WebSearchMaxResults int `yaml:"web_search_max_results" json:"web_search_max_results"` + // Whether reflection is enabled (only for agent type) + ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"` + // Welcome message displayed when agent is selected + MultiTurnEnabled bool `yaml:"multi_turn_enabled" json:"multi_turn_enabled"` + // Number of history turns to keep in context + HistoryTurns int `yaml:"history_turns" json:"history_turns"` +} + +// Value implements driver.Valuer interface for CustomAgentConfig +func (c CustomAgentConfig) Value() (driver.Value, error) { + return json.Marshal(c) +} + +// Scan implements sql.Scanner interface for CustomAgentConfig +func (c *CustomAgentConfig) Scan(value interface{}) error { + if value == nil { + return nil + } + b, ok := value.([]byte) + if !ok { + return nil + } + return json.Unmarshal(b, c) +} + +// TableName returns the table name for CustomAgent +func (CustomAgent) TableName() string { + return "custom_agents" +} + +// EnsureDefaults sets default values for the agent +func (a *CustomAgent) EnsureDefaults() { + if a == nil { + return + } + if a.Type == "" { + a.Type = CustomAgentTypeCustom + } + if a.Config.Temperature == 0 { + a.Config.Temperature = 0.7 + } + if a.Config.MaxIterations == 0 { + a.Config.MaxIterations = 10 + } + if a.Config.WebSearchMaxResults == 0 { + a.Config.WebSearchMaxResults = 5 + } + if a.Config.HistoryTurns == 0 { + a.Config.HistoryTurns = 5 + } +} + +// IsAgentMode returns true if this agent uses ReAct agent mode +func (a *CustomAgent) IsAgentMode() bool { + return a.Config.AgentMode == "agent" +} + +// GetBuiltinNormalAgent returns the built-in normal mode agent +func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent { + return &CustomAgent{ + ID: BuiltinAgentNormalID, + Name: "普通模式", + Description: "基于知识库的 RAG 问答,快速准确地回答问题", + Avatar: "💬", + IsBuiltin: true, + Type: CustomAgentTypeNormal, + TenantID: tenantID, + Config: CustomAgentConfig{ + AgentMode: "normal", + SystemPrompt: "", + Temperature: 0.7, + WebSearchEnabled: false, + }, + } +} + +// GetBuiltinAgentAgent returns the built-in agent mode agent +func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent { + return &CustomAgent{ + ID: BuiltinAgentAgentID, + Name: "Agent 模式", + Description: "ReAct 推理框架,支持多步思考和工具调用", + Avatar: "🤖", + IsBuiltin: true, + Type: CustomAgentTypeAgent, + TenantID: tenantID, + Config: CustomAgentConfig{ + AgentMode: "agent", + SystemPrompt: "", + Temperature: 0.7, + MaxIterations: 10, + AllowedTools: []string{"knowledge_search", "web_search"}, + WebSearchEnabled: true, + WebSearchMaxResults: 5, + ReflectionEnabled: false, + }, + } +} + +// GetBuiltinAgents returns all built-in agents for a tenant +func GetBuiltinAgents(tenantID uint64) []*CustomAgent { + return []*CustomAgent{ + GetBuiltinNormalAgent(tenantID), + GetBuiltinAgentAgent(tenantID), + } +} diff --git a/internal/types/interfaces/context_manager.go b/internal/types/interfaces/context_manager.go index 5d57b9b5..349a1ffd 100644 --- a/internal/types/interfaces/context_manager.go +++ b/internal/types/interfaces/context_manager.go @@ -24,6 +24,10 @@ type ContextManager interface { // GetContextStats returns statistics about the context GetContextStats(ctx context.Context, sessionID string) (*ContextStats, error) + + // SetSystemPrompt sets or updates the system prompt for a session + // If a system message exists, it will be replaced; otherwise, a new one will be added at the beginning + SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error } // ContextStats contains statistics about session context diff --git a/internal/types/interfaces/custom_agent.go b/internal/types/interfaces/custom_agent.go new file mode 100644 index 00000000..fde98379 --- /dev/null +++ b/internal/types/interfaces/custom_agent.go @@ -0,0 +1,101 @@ +// Package interfaces defines the interface contracts for custom agent management +package interfaces + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/types" +) + +// CustomAgentService defines the custom agent service interface +// Provides high-level operations for agent creation, querying, updating, and deletion +type CustomAgentService interface { + // CreateAgent creates a new custom agent + // Parameters: + // - ctx: Context information, carrying request tracking, user identity, etc. + // - agent: Agent object containing basic information and configuration + // Returns: + // - Created agent object (including automatically generated ID) + // - Possible errors such as insufficient permissions, validation errors, etc. + CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) + + // GetAgentByID retrieves agent information by ID + // Parameters: + // - ctx: Context information + // - id: Unique identifier of the agent + // Returns: + // - Agent object, if found (including built-in agents) + // - Possible errors such as not existing, insufficient permissions, etc. + GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) + + // ListAgents lists all agents under the current tenant (including built-in agents) + // Parameters: + // - ctx: Context information, containing tenant information + // Returns: + // - List of agent objects (built-in agents first, then custom agents sorted by creation time) + // - Possible errors such as insufficient permissions, etc. + ListAgents(ctx context.Context) ([]*types.CustomAgent, error) + + // UpdateAgent updates agent information + // Parameters: + // - ctx: Context information + // - agent: Agent object containing update information + // Returns: + // - Updated agent object + // - Possible errors such as not existing, insufficient permissions, cannot modify built-in, etc. + UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) + + // DeleteAgent deletes an agent + // Parameters: + // - ctx: Context information + // - id: Unique identifier of the agent + // Returns: + // - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc. + DeleteAgent(ctx context.Context, id string) error +} + +// CustomAgentRepository defines the custom agent repository interface +// Responsible for agent data persistence and retrieval +type CustomAgentRepository interface { + // CreateAgent creates an agent record + // Parameters: + // - ctx: Context information + // - agent: Agent object + // Returns: + // - Possible errors such as database connection failure, unique constraint conflicts, etc. + CreateAgent(ctx context.Context, agent *types.CustomAgent) error + + // GetAgentByID queries an agent by ID + // Parameters: + // - ctx: Context information + // - id: Agent ID + // Returns: + // - Agent object, if found + // - Possible errors such as record not existing, database errors, etc. + GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) + + // ListAgentsByTenantID lists all agents for a specific tenant + // Parameters: + // - ctx: Context information + // - tenantID: Tenant ID + // Returns: + // - List of agent objects + // - Possible errors such as database errors, etc. + ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error) + + // UpdateAgent updates an agent record + // Parameters: + // - ctx: Context information + // - agent: Agent object containing update information + // Returns: + // - Possible errors such as record not existing, database errors, etc. + UpdateAgent(ctx context.Context, agent *types.CustomAgent) error + + // DeleteAgent deletes an agent record + // Parameters: + // - ctx: Context information + // - id: Agent ID + // Returns: + // - Possible errors such as record not existing, database errors, etc. + DeleteAgent(ctx context.Context, id string) error +} diff --git a/internal/types/interfaces/session.go b/internal/types/interfaces/session.go index b82623ff..b47d224d 100644 --- a/internal/types/interfaces/session.go +++ b/internal/types/interfaces/session.go @@ -31,10 +31,12 @@ type SessionService interface { // knowledgeIDs: list of specific knowledge (file) IDs to search // summaryModelID: optional summary model ID override (if empty, uses session/KB default) // webSearchEnabled: whether to enable web search to supplement knowledge base results + // customAgent: optional custom agent for config override (multiTurnEnabled, historyTurns) // Events are emitted through eventBus (references, answer chunks, completion) KnowledgeQA(ctx context.Context, session *types.Session, query string, knowledgeBaseIDs []string, knowledgeIDs []string, assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus, + customAgent *types.CustomAgent, ) error // KnowledgeQAByEvent performs knowledge-based question answering by event KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error @@ -42,12 +44,14 @@ type SessionService interface { SearchKnowledge(ctx context.Context, knowledgeBaseID, query string) ([]*types.SearchResult, error) // AgentQA performs agent-based question answering with conversation history and streaming support // eventBus is optional - if nil, uses service's default EventBus + // customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults AgentQA( ctx context.Context, session *types.Session, query string, assistantMessageID string, eventBus *event.EventBus, + customAgent *types.CustomAgent, ) error // ClearContext clears the LLM context for a session ClearContext(ctx context.Context, sessionID string) error diff --git a/migrations/versioned/000006_custom_agents.down.sql b/migrations/versioned/000006_custom_agents.down.sql new file mode 100644 index 00000000..3e4a0dd5 --- /dev/null +++ b/migrations/versioned/000006_custom_agents.down.sql @@ -0,0 +1,19 @@ +-- Migration: 000006_custom_agents (rollback) +-- Description: Remove custom agents table and related changes + +DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Starting custom agents rollback...'; END $$; + +-- Remove agent_id column from sessions table +DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Removing agent_id column from sessions table'; END $$; +DROP INDEX IF EXISTS idx_sessions_agent_id; +ALTER TABLE sessions DROP COLUMN IF EXISTS agent_id; + +-- Drop custom_agents table +DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Dropping table: custom_agents'; END $$; +DROP INDEX IF EXISTS idx_custom_agents_tenant_id; +DROP INDEX IF EXISTS idx_custom_agents_type; +DROP INDEX IF EXISTS idx_custom_agents_is_builtin; +DROP INDEX IF EXISTS idx_custom_agents_deleted_at; +DROP TABLE IF EXISTS custom_agents; + +DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Custom agents rollback completed!'; END $$; diff --git a/migrations/versioned/000006_custom_agents.up.sql b/migrations/versioned/000006_custom_agents.up.sql new file mode 100644 index 00000000..80ba03b0 --- /dev/null +++ b/migrations/versioned/000006_custom_agents.up.sql @@ -0,0 +1,33 @@ +-- Migration: 000006_custom_agents +-- Description: Add custom agents table for GPTs-like agent configuration +DO $$ BEGIN RAISE NOTICE '[Migration 000006] Starting custom agents setup...'; END $$; + +-- Create custom_agents table +DO $$ BEGIN RAISE NOTICE '[Migration 000006] Creating table: custom_agents'; END $$; +CREATE TABLE IF NOT EXISTS custom_agents ( + id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(), + name VARCHAR(255) NOT NULL, + description TEXT, + avatar VARCHAR(64), + is_builtin BOOLEAN NOT NULL DEFAULT false, + type VARCHAR(32) NOT NULL DEFAULT 'custom', + tenant_id INTEGER NOT NULL, + created_by VARCHAR(36), + config JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + deleted_at TIMESTAMP WITH TIME ZONE +); + +-- 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_type ON custom_agents(type); +CREATE INDEX IF NOT EXISTS idx_custom_agents_is_builtin ON custom_agents(is_builtin); +CREATE INDEX IF NOT EXISTS idx_custom_agents_deleted_at ON custom_agents(deleted_at); + +-- Add agent_id column to sessions table to track which agent was used +DO $$ BEGIN RAISE NOTICE '[Migration 000006] Adding agent_id column to sessions table'; END $$; +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); + +DO $$ BEGIN RAISE NOTICE '[Migration 000006] Custom agents setup completed successfully!'; END $$;
{{ $t('agent.subtitle') }}