feat: 新增智能体功能模块,支持自定义智能体创建、配置和选择

This commit is contained in:
wizardchen
2025-12-24 10:34:41 +08:00
parent 236b190b26
commit d0c5c4f6b0
36 changed files with 5195 additions and 672 deletions
+94
View File
@@ -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;
}
+5 -1
View File
@@ -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;
+5
View File
@@ -0,0 +1,5 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 996 B

+4 -4
View File
@@ -1,5 +1,5 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" fill="#000000" fill-opacity=".9" stroke="#000000" stroke-opacity=".9" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z" fill="#000000" fill-opacity=".9" stroke="#000000" stroke-opacity=".9" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z" fill="#000000" fill-opacity=".9" stroke="#000000" stroke-opacity=".9" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 995 B

After

Width:  |  Height:  |  Size: 1.1 KiB

+155
View File
@@ -0,0 +1,155 @@
<template>
<div
class="agent-avatar"
:style="avatarStyle"
:class="{ 'agent-avatar-small': size === 'small', 'agent-avatar-large': size === 'large' }"
>
<!-- 星星装饰 - 融入背景 -->
<svg class="agent-sparkles" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<!-- 右上角小星星 -->
<path d="M24 5L24.4 6.6C24.45 6.85 24.65 7.05 24.9 7.1L26.5 7.5L24.9 7.9C24.65 7.95 24.45 8.15 24.4 8.4L24 10L23.6 8.4C23.55 8.15 23.35 7.95 23.1 7.9L21.5 7.5L23.1 7.1C23.35 7.05 23.55 6.85 23.6 6.6L24 5Z" fill="rgba(255,255,255,0.6)"/>
<!-- 左下角小星星 -->
<path d="M7 22L7.4 23.6C7.45 23.85 7.65 24.05 7.9 24.1L9.5 24.5L7.9 24.9C7.65 24.95 7.45 25.15 7.4 25.4L7 27L6.6 25.4C6.55 25.15 6.35 24.95 6.1 24.9L4.5 24.5L6.1 24.1C6.35 24.05 6.55 23.85 6.6 23.6L7 22Z" fill="rgba(255,255,255,0.5)"/>
</svg>
<span class="agent-avatar-letter" :style="letterStyle">{{ letter }}</span>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = withDefaults(defineProps<{
name: string;
size?: 'small' | 'medium' | 'large';
}>(), {
size: 'medium'
});
// 预定义的渐变色方案 - 现代、柔和、专业
const gradients = [
{ from: '#667eea', to: '#764ba2' }, // 紫蓝渐变
{ from: '#4facfe', to: '#00f2fe' }, // 蓝青渐变
{ from: '#43e97b', to: '#38f9d7' }, // 绿青渐变
{ from: '#11998e', to: '#38ef7d' }, // 深绿渐变
{ from: '#5ee7df', to: '#b490ca' }, // 青紫渐变
{ from: '#48c6ef', to: '#6f86d6' }, // 蓝紫渐变
{ from: '#a8edea', to: '#fed6e3' }, // 青粉渐变(柔和)
{ from: '#667db6', to: '#0082c8' }, // 蓝色渐变
{ from: '#36d1dc', to: '#5b86e5' }, // 青蓝渐变
{ from: '#56ab2f', to: '#a8e063' }, // 草绿渐变
{ from: '#614385', to: '#516395' }, // 深紫蓝渐变
{ from: '#02aab0', to: '#00cdac' }, // 青绿渐变
{ from: '#6a82fb', to: '#fc5c7d' }, // 蓝粉渐变(柔和)
{ from: '#834d9b', to: '#d04ed6' }, // 紫色渐变
{ from: '#4776e6', to: '#8e54e9' }, // 蓝紫渐变
{ from: '#00b09b', to: '#96c93d' }, // 青绿渐变
];
// 根据名称生成一个稳定的哈希值
const hashCode = (str: string): number => {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return Math.abs(hash);
};
// 获取首字母(支持中文)
const letter = computed(() => {
const name = props.name?.trim() || '';
if (!name) return '?';
// 获取第一个字符
const firstChar = name.charAt(0);
// 如果是英文字母,转大写
if (/[a-zA-Z]/.test(firstChar)) {
return firstChar.toUpperCase();
}
// 中文或其他字符直接返回
return firstChar;
});
// 根据名称选择渐变色
const gradient = computed(() => {
const hash = hashCode(props.name || '');
return gradients[hash % gradients.length];
});
// 生成样式
const avatarStyle = computed(() => {
const g = gradient.value;
return {
background: `linear-gradient(135deg, ${g.from} 0%, ${g.to} 100%)`
};
});
// 字母样式 - 白色 + 背景色阴影增加层次感
const letterStyle = computed(() => {
const g = gradient.value;
return {
textShadow: `0 1px 2px ${g.to}80, 0 0 8px ${g.from}30`
};
});
</script>
<style scoped lang="less">
.agent-avatar {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
flex-shrink: 0;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
overflow: hidden;
&.agent-avatar-small {
width: 24px;
height: 24px;
border-radius: 6px;
.agent-avatar-letter {
font-size: 12px;
}
}
&.agent-avatar-large {
width: 48px;
height: 48px;
border-radius: 12px;
.agent-avatar-letter {
font-size: 20px;
}
.agent-sparkles {
opacity: 0.9;
}
}
}
.agent-sparkles {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
opacity: 0.85;
}
.agent-avatar-letter {
position: relative;
z-index: 1;
color: #fff;
font-size: 14px;
font-weight: 600;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
</style>
+430
View File
@@ -0,0 +1,430 @@
<template>
<Teleport to="body">
<div v-if="visible" class="agent-selector-overlay" @click="$emit('close')">
<div
class="agent-selector-dropdown"
:style="dropdownStyle"
@click.stop
>
<!-- 头部 -->
<div class="agent-selector-header">
<span>{{ $t('agent.selectAgent') }}</span>
<router-link to="/platform/agents" class="agent-selector-add" @click="$emit('close')">
<span class="add-icon">+</span>
<span class="add-text">{{ $t('agent.manageAgents') }}</span>
</router-link>
</div>
<!-- 内容区域 -->
<div class="agent-selector-content">
<!-- 内置智能体分组 -->
<div class="agent-group">
<div class="agent-group-title">{{ $t('agent.builtinAgents') }}</div>
<t-tooltip
v-for="agent in builtinAgents"
:key="agent.id"
:content="getAgentCapabilities(agent)"
:disabled="currentAgentId === agent.id"
placement="right"
>
<div
class="agent-option"
:class="{ 'selected': currentAgentId === agent.id }"
@click="selectAgent(agent)"
>
<div class="builtin-icon" :class="agent.type">
<TIcon :name="agent.type === 'agent' ? 'control-platform' : 'chat'" size="14px" />
</div>
<span class="agent-option-name">{{ agent.name }}</span>
<svg
v-if="currentAgentId === agent.id"
width="14"
height="14"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
</div>
</t-tooltip>
</div>
<!-- 自定义智能体分组 -->
<div v-if="customAgents.length > 0" class="agent-group">
<div class="agent-group-title">{{ $t('agent.customAgents') }}</div>
<t-tooltip
v-for="agent in customAgents"
:key="agent.id"
:content="getAgentCapabilities(agent)"
:disabled="currentAgentId === agent.id"
placement="right"
>
<div
class="agent-option"
:class="{ 'selected': currentAgentId === agent.id }"
@click="selectAgent(agent)"
>
<AgentAvatar :name="agent.name" size="small" />
<span class="agent-option-name">{{ agent.name }}</span>
<svg
v-if="currentAgentId === agent.id"
width="14"
height="14"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
</div>
</t-tooltip>
</div>
<!-- 空状态 -->
<div v-if="builtinAgents.length === 0 && customAgents.length === 0" class="agent-option empty">
{{ $t('agent.noAgents') }}
</div>
</div>
</div>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { Icon as TIcon } from 'tdesign-vue-next';
import { listAgents, type CustomAgent } from '@/api/agent';
import AgentAvatar from '@/components/AgentAvatar.vue';
const { t } = useI18n();
const props = defineProps<{
visible: boolean;
anchorEl?: HTMLElement;
currentAgentId: string;
}>();
const emit = defineEmits<{
(e: 'close'): void;
(e: 'select', agent: CustomAgent): void;
}>();
const agents = ref<CustomAgent[]>([]);
const dropdownStyle = ref<Record<string, string>>({});
// 内置智能体
const builtinAgents = computed(() => {
return [
{
id: 'builtin-normal',
name: t('input.normalMode'),
description: t('input.normalModeDesc'),
type: 'normal',
is_builtin: true
},
{
id: 'builtin-agent',
name: t('input.agentMode'),
description: t('input.agentModeDesc'),
type: 'agent',
is_builtin: true
}
] as CustomAgent[];
});
// 自定义智能体
const customAgents = computed(() => {
return agents.value.filter(a => !a.is_builtin);
});
// 获取智能体能力描述(用于 tooltip)
const getAgentCapabilities = (agent: CustomAgent): string => {
// 内置智能体
if (agent.is_builtin) {
if (agent.type === 'normal') {
return t('agent.capabilities.normal');
} else if (agent.type === 'agent') {
return t('agent.capabilities.agent');
}
return '';
}
// 自定义智能体
const capabilities: string[] = [];
const config = agent.config || {};
if (config.model_id) {
capabilities.push(t('agent.capabilities.modelSpecified'));
}
if (config.knowledge_bases && config.knowledge_bases.length > 0) {
capabilities.push(t('agent.capabilities.kbCount', { count: config.knowledge_bases.length }));
} else if (config.allow_user_kb_selection === false) {
capabilities.push(t('agent.capabilities.kbDisabled'));
}
if (config.rerank_model_id) {
capabilities.push(t('agent.capabilities.rerankSpecified'));
}
if (config.web_search_enabled === true) {
capabilities.push(t('agent.capabilities.webSearchOn'));
} else if (config.web_search_enabled === false) {
capabilities.push(t('agent.capabilities.webSearchOff'));
}
if (config.system_prompt) {
capabilities.push(t('agent.capabilities.hasPrompt'));
}
return capabilities.length > 0 ? capabilities.join('、') : t('agent.capabilities.default');
};
// 加载智能体列表
const loadAgents = async () => {
try {
const response = await listAgents();
agents.value = response.data || [];
} catch (error) {
console.error('Failed to load agents:', error);
}
};
// 选择智能体
const selectAgent = (agent: CustomAgent) => {
emit('select', agent);
};
// 更新下拉框位置(与模型选择器一致)
const updateDropdownPosition = () => {
if (!props.anchorEl) return;
const rect = props.anchorEl.getBoundingClientRect();
const dropdownWidth = 200;
const offsetY = 8;
const vh = window.innerHeight;
const vw = window.innerWidth;
// 水平位置:左对齐
let left = Math.floor(rect.left);
const minLeft = 16;
const maxLeft = Math.max(16, vw - dropdownWidth - 16);
left = Math.max(minLeft, Math.min(maxLeft, left));
// 垂直位置
const preferredDropdownHeight = 320;
const minDropdownHeight = 100;
const topMargin = 20;
const spaceBelow = vh - rect.bottom;
const spaceAbove = rect.top;
let actualHeight: number;
if (spaceBelow >= minDropdownHeight + offsetY) {
// 向下弹出
actualHeight = Math.min(preferredDropdownHeight, spaceBelow - offsetY - 16);
const top = Math.floor(rect.bottom + offsetY);
dropdownStyle.value = {
position: 'fixed',
width: `${dropdownWidth}px`,
left: `${left}px`,
top: `${top}px`,
maxHeight: `${actualHeight}px`,
zIndex: '9999'
};
} else {
// 向上弹出
const availableHeight = spaceAbove - offsetY - topMargin;
actualHeight = availableHeight >= preferredDropdownHeight
? preferredDropdownHeight
: Math.max(minDropdownHeight, availableHeight);
const bottom = vh - rect.top + offsetY;
dropdownStyle.value = {
position: 'fixed',
width: `${dropdownWidth}px`,
left: `${left}px`,
bottom: `${bottom}px`,
maxHeight: `${actualHeight}px`,
zIndex: '9999'
};
}
};
// 监听显示状态
watch(() => props.visible, (newVal) => {
if (newVal) {
loadAgents();
nextTick(() => {
updateDropdownPosition();
});
}
});
onMounted(() => {
if (props.visible) {
loadAgents();
}
});
</script>
<style scoped lang="less">
.agent-selector-overlay {
position: fixed;
inset: 0;
z-index: 9998;
background: transparent;
touch-action: none;
}
.agent-selector-dropdown {
position: fixed;
background: var(--td-bg-color-container, #fff);
border-radius: 10px;
box-shadow: var(--td-shadow-2, 0 6px 28px rgba(15, 23, 42, 0.08));
border: 1px solid var(--td-component-border, #e7e9eb);
overflow: hidden;
display: flex;
flex-direction: column;
}
.agent-selector-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
border-bottom: 1px solid var(--td-component-stroke, #f0f0f0);
background: var(--td-bg-color-container, #fff);
font-size: 12px;
font-weight: 500;
color: var(--td-text-color-secondary, #666);
}
.agent-selector-add {
display: inline-flex;
align-items: center;
gap: 4px;
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.2s;
text-decoration: none;
.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);
}
}
.agent-selector-content {
flex: 1;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
padding: 6px 8px;
}
.agent-group {
&:not(:last-child) {
margin-bottom: 8px;
padding-bottom: 8px;
border-bottom: 1px solid var(--td-component-stroke, #f0f0f0);
}
}
.agent-group-title {
font-size: 11px;
color: var(--td-text-color-placeholder, #999);
padding: 4px 8px 6px;
font-weight: 500;
}
.agent-option {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
cursor: pointer;
transition: background 0.12s;
border-radius: 6px;
margin-bottom: 4px;
&:last-child {
margin-bottom: 0;
}
&:hover {
background: var(--td-bg-color-container-hover, #f6f8f7);
}
&.selected {
background: var(--td-brand-color-light, #eefdf5);
.agent-option-name {
color: #10b981;
font-weight: 600;
}
}
&.empty {
color: var(--td-text-color-disabled, #9aa0a6);
cursor: default;
text-align: center;
padding: 20px 8px;
&:hover {
background: transparent;
}
}
}
.agent-option-name {
font-size: 12px;
color: var(--td-text-color-primary, #222);
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.4;
}
.builtin-icon {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 6px;
flex-shrink: 0;
&.normal {
background: rgba(7, 192, 95, 0.1);
color: #059669;
}
&.agent {
background: rgba(124, 77, 255, 0.1);
color: #7c4dff;
}
}
.check-icon {
width: 14px;
height: 14px;
color: #10b981;
flex-shrink: 0;
margin-left: 6px;
}
</style>
+318 -154
View File
@@ -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<HTMLElement>();
const agentModeDropdownStyle = ref<Record<string, string>>({});
// 智能体相关状态
const agents = ref<CustomAgent[]>([]);
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) => {
<div class="answers-input">
<!-- 富文本输入框容器 -->
<div class="rich-input-container">
<!-- 选中的知识库和文件标签(显示在输入框内顶部) -->
<!-- 选中的知识库和文件标签(显示在输入框内顶部) -->
<div v-if="allSelectedItems.length > 0" class="selected-tags-inline">
<span
v-for="item in allSelectedItems"
:key="item.id"
class="inline-tag"
:class="[
item.type === 'kb' ? (item.kbType === 'faq' ? 'faq-tag' : 'kb-tag') : 'file-tag'
item.type === 'kb' ? (item.kbType === 'faq' ? 'faq-tag' : 'kb-tag') : 'file-tag',
{ 'agent-configured': item.isAgentConfigured }
]"
>
<span class="tag-icon">
@@ -1197,7 +1384,8 @@ onBeforeRouteUpdate((to, from, next) => {
<t-icon v-else name="file" />
</span>
<span class="tag-name">{{ item.name }}</span>
<span class="tag-remove" @click="removeSelectedItem(item)">×</span>
<!-- 智能体配置的项不显示删除按钮 -->
<span v-if="!item.isAgentConfigured" class="tag-remove" @click="removeSelectedItem(item)">×</span>
</span>
</div>
@@ -1243,28 +1431,8 @@ onBeforeRouteUpdate((to, from, next) => {
}"
@click.stop="toggleAgentModeSelector"
>
<img
v-if="isAgentEnabled"
:src="getImgSrc('agent-active.svg')"
:alt="$t('input.agentMode')"
class="control-icon agent-icon"
/>
<svg
v-else
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="control-icon normal-mode-icon"
>
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
</svg>
<span class="agent-mode-text">
{{ isAgentEnabled ? $t('input.agentMode') : $t('input.normalMode') }}
{{ selectedAgent.name || (isAgentEnabled ? $t('input.agentMode') : $t('input.normalMode')) }}
</span>
<svg
width="12"
@@ -1278,79 +1446,21 @@ onBeforeRouteUpdate((to, from, next) => {
</svg>
</div>
<!-- Agent 模式选择下拉菜单 -->
<Teleport to="body">
<div v-if="showAgentModeSelector" class="agent-mode-selector-overlay" @click="closeAgentModeSelector">
<div
class="agent-mode-selector-dropdown"
:style="agentModeDropdownStyle"
@click.stop
>
<div
class="agent-mode-option"
:class="{ 'selected': !isAgentEnabled }"
@click="selectAgentMode('normal')"
>
<div class="agent-mode-option-main">
<span class="agent-mode-option-name">{{ $t('input.normalMode') }}</span>
<span class="agent-mode-option-desc">{{ $t('input.normalModeDesc') }}</span>
</div>
<svg
v-if="!isAgentEnabled"
width="16"
height="16"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
</div>
<div
class="agent-mode-option"
:class="{
'selected': isAgentEnabled,
'disabled': !settingsStore.isAgentReady && !isAgentEnabled
}"
@click="selectAgentMode('agent')"
>
<div class="agent-mode-option-main">
<span class="agent-mode-option-name">{{ $t('input.agentMode') }}</span>
<span class="agent-mode-option-desc">{{ $t('input.agentModeDesc') }}</span>
</div>
<svg
v-if="isAgentEnabled"
width="16"
height="16"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
<div v-if="!settingsStore.isAgentReady && !isAgentEnabled" class="agent-mode-warning">
<t-tooltip :content="$t('input.agentNotReadyTooltip')" placement="left">
<t-icon name="error-circle" class="warning-icon" />
</t-tooltip>
</div>
</div>
<div v-if="!settingsStore.isAgentReady && !isAgentEnabled" class="agent-mode-footer">
<a
href="#"
@click.prevent="handleGoToAgentSettings"
class="agent-mode-link"
>
{{ $t('input.goToSettings') }}
</a>
</div>
</div>
</div>
</Teleport>
<!-- Agent 选择器下拉菜单 -->
<AgentSelector
:visible="showAgentModeSelector"
:anchorEl="agentModeButtonRef"
:currentAgentId="selectedAgentId"
@close="closeAgentModeSelector"
@select="handleSelectAgent"
/>
<!-- WebSearch 开关按钮 -->
<t-tooltip placement="top">
<template #content>
<span v-if="isWebSearchConfigured">{{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }}</span>
<span v-if="isWebSearchDisabledByAgent">{{ $t('input.webSearchDisabledByAgent') }}</span>
<span v-else-if="isWebSearchForcedByAgent">{{ $t('input.webSearchForcedByAgent') }}</span>
<span v-else-if="isWebSearchConfigured">{{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }}</span>
<div v-else class="websearch-tooltip-disabled">
<span>{{ $t('input.webSearch.notConfigured') }}</span>
<a href="#" @click.prevent="handleGoToWebSearchSettings">{{ $t('input.goToSettings') }}</a>
@@ -1358,7 +1468,11 @@ onBeforeRouteUpdate((to, from, next) => {
</template>
<div
class="control-btn websearch-btn"
:class="{ 'active': isWebSearchEnabled && isWebSearchConfigured, 'disabled': !isWebSearchConfigured }"
:class="{
'active': (isWebSearchEnabled && isWebSearchConfigured) || isWebSearchForcedByAgent,
'disabled': !isWebSearchConfigured,
'agent-controlled': isWebSearchDisabledByAgent || isWebSearchForcedByAgent
}"
@click.stop="toggleWebSearch"
>
<svg
@@ -1368,7 +1482,7 @@ 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 }"
>
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none"/>
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
@@ -1380,11 +1494,14 @@ onBeforeRouteUpdate((to, from, next) => {
</t-tooltip>
<!-- @ 知识库/文件选择按钮 -->
<t-tooltip :content="allSelectedItems.length > 0 ? $t('input.knowledgeBaseWithCount', { count: allSelectedItems.length }) : $t('input.knowledgeBase')">
<t-tooltip :content="isKnowledgeBaseDisabledByAgent ? $t('input.kbDisabledByAgent') : (isKnowledgeBaseLockedByAgent ? $t('input.kbLockedByAgent') : (allSelectedItems.length > 0 ? $t('input.knowledgeBaseWithCount', { count: allSelectedItems.length }) : $t('input.knowledgeBase')))">
<div
ref="atButtonRef"
class="control-btn kb-btn"
:class="{ 'active': allSelectedItems.length > 0 }"
:class="{
'active': allSelectedItems.length > 0,
'agent-controlled': isKnowledgeBaseLockedByAgent
}"
@click.stop
@mousedown.prevent="triggerMention"
>
@@ -1394,27 +1511,29 @@ onBeforeRouteUpdate((to, from, next) => {
</t-tooltip>
<!-- 模型显示 -->
<div class="model-display">
<div
ref="modelButtonRef"
class="model-selector-trigger"
@click.stop="toggleModelSelector"
>
<span class="model-selector-name">
{{ selectedModel?.name || $t('input.notConfigured') }}
</span>
<svg
width="12"
height="12"
viewBox="0 0 12 12"
fill="currentColor"
class="model-dropdown-arrow"
:class="{ 'rotate': showModelSelector }"
<t-tooltip :content="isModelLockedByAgent ? $t('input.modelLockedByAgent') : ''" :disabled="!isModelLockedByAgent">
<div class="model-display" :class="{ 'agent-controlled': isModelLockedByAgent }">
<div
ref="modelButtonRef"
class="model-selector-trigger"
@click.stop="toggleModelSelector"
>
<path d="M2.5 4.5L6 8L9.5 4.5H2.5Z"/>
</svg>
<span class="model-selector-name">
{{ selectedModel?.name || $t('input.notConfigured') }}
</span>
<svg
width="12"
height="12"
viewBox="0 0 12 12"
fill="currentColor"
class="model-dropdown-arrow"
:class="{ 'rotate': showModelSelector }"
>
<path d="M2.5 4.5L6 8L9.5 4.5H2.5Z"/>
</svg>
</div>
</div>
</div>
</t-tooltip>
</div>
<Teleport to="body">
@@ -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 {
+38 -4
View File
@@ -24,6 +24,18 @@
</div>
</div>
</template>
<template v-else-if="showCreateAgentAction">
<div class="menu_item kb-action-item" @click.stop="handleCreateAgent">
<div class="kb-action-icon-wrapper">
<svg class="kb-action-icon" width="18" height="18" viewBox="0 0 18 18" fill="none">
<path d="M9 3.75V14.25M3.75 9H14.25" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</div>
<div class="kb-action-content">
<span class="kb-action-title">{{ t('agent.createAgent') }}</span>
</div>
</div>
</template>
<template v-else-if="showDocActions">
<div class="menu_item kb-action-item" @click.stop="handleDocUploadClick">
<div class="kb-action-icon-wrapper">
@@ -138,7 +150,7 @@
:class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : isMenuItemActive(item.path) ? 'menu_item_active' : '']">
<div class="menu_item-box">
<div class="menu_icon">
<img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
<img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'agent' ? agentIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
</div>
<span class="menu_title" :title="item.title">{{ item.title }}</span>
<t-icon v-if="item.path === 'creatChat'" name="add" class="menu-create-hint" />
@@ -253,6 +265,9 @@ const isInCreatChat = computed<boolean>(() => {
// 是否在对话详情页
const isInChatDetail = computed<boolean>(() => route.name === 'chat');
// 是否在智能体列表页面
const isInAgentList = computed<boolean>(() => 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<MenuItem[]>(() => {
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<MenuItem[]>(() => {
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' }
}))
}
</script>
<style lang="less" scoped>
.aside_box {
+125 -5
View File
@@ -1,6 +1,7 @@
export default {
menu: {
knowledgeBase: 'Knowledge Base',
agents: 'Agents',
chat: 'Chat',
createChat: 'Create Chat',
tenant: 'Account Info',
@@ -204,7 +205,117 @@ export default {
updatePlan: 'Update Plan',
webSearchFound: 'Found <strong>{count}</strong> web search result(s)',
argumentsLabel: 'Arguments',
toolFallback: 'Tool'
toolFallback: 'Tool',
title: 'Agents',
subtitle: 'Configure and manage your agents to customize conversation behavior and capabilities',
createAgent: 'Create Agent',
builtin: 'Built-in',
noDescription: 'No description',
selectAgent: 'Select Agent',
noAgents: 'No agents',
manageAgents: 'Manage',
builtinAgents: 'Built-in Agents',
customAgents: 'Custom Agents',
capabilities: {
normal: 'Quick response, direct answers',
agent: 'Multi-step thinking, deep analysis for complex questions',
modelSpecified: 'Model specified',
kbCount: '{count} knowledge base(s) specified',
kbDisabled: 'Knowledge base disabled',
rerankSpecified: 'ReRank model specified',
webSearchOn: 'Web search enabled',
webSearchOff: 'Web search disabled',
hasPrompt: 'Custom prompt',
default: 'Default configuration',
},
type: {
normal: 'Quick Answer',
agent: 'Smart Reasoning',
custom: 'Custom',
},
mode: {
normal: 'Quick Answer',
agent: 'Smart Reasoning',
},
features: {
webSearch: 'Web Search Enabled',
knowledgeBase: 'Knowledge Base Linked',
multiTurn: 'Multi-turn Conversation',
},
empty: {
title: 'No Custom Agents',
description: 'Click the button in the top right to create your first agent',
},
delete: {
confirmTitle: 'Delete Agent',
confirmMessage: 'Are you sure you want to delete agent "{name}"? This action cannot be undone.',
confirmButton: 'Confirm Delete',
},
messages: {
created: 'Agent created successfully',
updated: 'Agent updated successfully',
deleted: 'Agent deleted',
deleteFailed: 'Delete failed',
saveFailed: 'Save failed',
builtinReadonly: 'Built-in agents cannot be edited',
},
editor: {
createTitle: 'Create Agent',
editTitle: 'Edit Agent',
basicInfo: 'Basic Info',
basicInfoDesc: 'Configure agent basic information',
modelConfig: 'Model Config',
modelConfigDesc: 'Configure agent model parameters',
capabilities: 'Capabilities',
capabilitiesDesc: 'Configure agent capabilities and tools',
configuration: 'Configuration',
name: 'Name',
namePlaceholder: 'Enter agent name',
nameRequired: 'Agent name is required',
systemPromptRequired: 'System prompt is required',
modelRequired: 'Please select a model',
rerankModelRequired: 'ReRank model is required when using knowledge bases',
avatar: 'Avatar',
avatarPlaceholder: 'Enter Emoji or select',
description: 'Description',
descriptionPlaceholder: 'Enter agent description',
baseType: 'Base Type',
normalDesc: 'Quick response, direct answers',
agentDesc: 'Multi-step thinking, deep analysis for complex questions',
model: 'Model',
modelPlaceholder: 'Select Model',
systemPrompt: 'System Prompt',
systemPromptPlaceholder: 'Custom system prompt to define agent behavior and role',
availablePlaceholders: 'Available Placeholders',
placeholderHint: 'Type {{ to trigger autocomplete',
temperature: 'Temperature',
welcomeMessage: 'Welcome Message',
welcomeMessagePlaceholder: 'Message displayed when this agent is selected',
suggestedPrompts: 'Suggested Prompts',
mode: 'Running Mode',
webSearch: 'Web Search',
webSearchMaxResults: 'Max Search Results',
knowledgeBases: 'Knowledge Bases',
selectKnowledgeBases: 'Select knowledge bases',
allowUserKBSelection: 'Allow User KB Selection',
allowUserKBSelectionDesc: 'When disabled, users cannot select knowledge bases during conversation',
rerankModel: 'ReRank Model',
rerankModelDesc: 'Used to rerank knowledge base retrieval results for better accuracy',
rerankModelPlaceholder: 'Select ReRank Model',
maxIterations: 'Max Iterations',
allowedTools: 'Allowed Tools',
multiTurn: 'Multi-turn Conversation',
historyTurns: 'History Turns',
},
selector: {
title: 'Select Agent',
builtinSection: 'Built-in Agents',
customSection: 'My Agents',
addNew: 'Add New Agent',
},
builtinAgents: 'Built-in Agents',
customAgents: 'Custom Agents',
manageAgents: 'Manage Agents',
},
settings: {
title: 'Settings',
@@ -752,10 +863,11 @@ export default {
placeholderWithContext: 'Enter your question, will answer based on selected knowledge bases/files above',
placeholderWebOnly: 'Enter your question, will answer with web search',
placeholderKbAndWeb: 'Enter your question, will answer based on knowledge base and web search',
agentMode: 'Agent Mode',
normalMode: 'Normal Mode',
placeholderAgent: 'Ask {name}',
agentMode: 'Smart Reasoning',
normalMode: 'Quick Answer',
normalModeDesc: 'Knowledge base RAG Q&A',
agentModeDesc: 'ReAct reasoning framework with multi-step thinking',
agentModeDesc: 'Multi-step thinking, deep analysis',
agentNotReadyTooltip: 'Agent is not ready. Please finish configuration first.',
agentNotReadyDetail: 'Agent is not ready. Please configure the following: {reasons}',
agentMissingAllowedTools: 'Allowed tools',
@@ -782,6 +894,7 @@ export default {
replying: 'Currently replying, please try again later!',
agentSwitchedOn: 'Switched to Agent Mode',
agentSwitchedOff: 'Switched to Normal Mode',
agentSelected: 'Selected agent "{name}"',
agentEnabled: 'Agent Mode enabled',
agentDisabled: 'Agent Mode disabled',
agentNotReadyDetail: 'Agent is not ready. Please configure the following: {reasons}',
@@ -795,7 +908,14 @@ export default {
messageMissing: 'Unable to get message ID. Please refresh the page and try again.',
stopSuccess: 'Generation stopped',
stopFailed: 'Failed to stop. Please try again.'
}
},
webSearchDisabledByAgent: 'Web search is disabled by the current agent',
webSearchForcedByAgent: 'Web search is enabled by the current agent and cannot be turned off',
kbLockedByAgent: 'Knowledge base configuration is locked by the current agent',
kbDisabledByAgent: 'Knowledge base is disabled by the current agent',
cannotRemoveAgentKb: 'Cannot remove knowledge base configured by agent',
agentConfiguredKb: 'Configured by agent, cannot be removed',
modelLockedByAgent: 'Model selection is locked by the current agent'
},
createChat: {
title: 'Knowledge-base Q&A - AI Assistant',
+4 -3
View File
@@ -1675,10 +1675,11 @@ export default {
placeholderWithContext: 'Введите вопрос, ответ будет основан на выбранных выше базах знаний/файлах',
placeholderWebOnly: 'Введите вопрос, ответ будет основан на веб-поиске',
placeholderKbAndWeb: 'Введите вопрос, ответ будет основан на базе знаний и веб-поиске',
agentMode: 'Agent режим',
normalMode: 'Обычный режим',
placeholderAgent: 'Спросить {name}',
agentMode: 'Умный анализ',
normalMode: 'Быстрый ответ',
normalModeDesc: 'RAG-вопросы и ответы по базе знаний',
agentModeDesc: 'Шаблон рассуждений ReAct, многошаговое мышление',
agentModeDesc: 'Многошаговое мышление, глубокий анализ',
agentNotReadyTooltip: 'Agent не готов. Пожалуйста, завершите настройку.',
agentNotReadyDetail: 'Agent не готов. Пожалуйста, настройте следующее: {reasons}',
agentMissingAllowedTools: 'Разрешённые инструменты',
+132 -12
View File
@@ -1,6 +1,7 @@
export default {
menu: {
knowledgeBase: "知识库",
agents: "智能体",
chat: "对话",
createChat: "创建对话",
tenant: "账户信息",
@@ -297,15 +298,6 @@ export default {
selectKnowledgeBaseWarning: "请至少选择一个知识库",
processError: "处理出错",
},
agent: {
taskLabel: "任务:",
copy: "复制",
addToKnowledgeBase: "添加到知识库",
updatePlan: "更新计划",
webSearchFound: "找到 <strong>{count}</strong> 个网络搜索结果",
argumentsLabel: "参数",
toolFallback: "工具",
},
settings: {
title: "设置",
modelConfig: "模型配置",
@@ -735,6 +727,125 @@ export default {
knowledgeBase: "知识库",
noResult: "无结果",
},
agent: {
taskLabel: "任务:",
copy: "复制",
addToKnowledgeBase: "添加到知识库",
updatePlan: "更新计划",
webSearchFound: "找到 <strong>{count}</strong> 个网络搜索结果",
argumentsLabel: "参数",
toolFallback: "工具",
title: "智能体",
subtitle: "配置和管理您的智能体,自定义对话行为和能力",
createAgent: "创建智能体",
builtin: "内置",
noDescription: "暂无描述",
selectAgent: "选择智能体",
noAgents: "暂无智能体",
manageAgents: "管理",
builtinAgents: "内置智能体",
customAgents: "自定义智能体",
capabilities: {
normal: "快速响应,直接回答问题",
agent: "多步思考,深度分析复杂问题",
modelSpecified: "指定模型",
kbCount: "指定 {count} 个知识库",
kbDisabled: "禁用知识库",
rerankSpecified: "指定 ReRank 模型",
webSearchOn: "启用网络搜索",
webSearchOff: "禁用网络搜索",
hasPrompt: "自定义提示词",
default: "默认配置",
},
type: {
normal: "快速问答",
agent: "智能推理",
custom: "自定义",
},
mode: {
normal: "快速问答",
agent: "智能推理",
},
features: {
webSearch: "支持网络搜索",
knowledgeBase: "关联知识库",
multiTurn: "多轮对话",
},
empty: {
title: "暂无自定义智能体",
description: "点击右上角按钮创建您的第一个智能体",
},
delete: {
confirmTitle: "删除智能体",
confirmMessage: "确定要删除智能体「{name}」吗?此操作不可恢复。",
confirmButton: "确认删除",
},
messages: {
created: "智能体创建成功",
updated: "智能体更新成功",
deleted: "智能体已删除",
deleteFailed: "删除失败",
saveFailed: "保存失败",
builtinReadonly: "内置智能体不可编辑",
},
editor: {
createTitle: "创建智能体",
editTitle: "编辑智能体",
basicInfo: "基本信息",
basicInfoDesc: "配置智能体的基本信息",
modelConfig: "模型配置",
modelConfigDesc: "配置智能体的模型参数",
capabilities: "能力与工具",
capabilitiesDesc: "配置智能体的能力和工具",
configuration: "配置项",
name: "名称",
namePlaceholder: "请输入智能体名称",
nameRequired: "请输入智能体名称",
systemPromptRequired: "请输入系统提示词",
modelRequired: "请选择模型",
rerankModelRequired: "使用知识库时请选择 ReRank 模型",
avatar: "图标",
avatarPlaceholder: "输入 Emoji 或点击选择",
description: "描述",
descriptionPlaceholder: "请输入智能体描述",
baseType: "基础类型",
normalDesc: "快速响应,直接回答问题",
agentDesc: "多步思考,深度分析复杂问题",
model: "模型",
modelPlaceholder: "请选择模型",
systemPrompt: "系统提示词",
systemPromptPlaceholder: "自定义系统提示词,定义智能体的行为和角色",
availablePlaceholders: "可用占位符",
placeholderHint: "输入 {{ 触发自动补全",
temperature: "温度",
welcomeMessage: "欢迎消息",
welcomeMessagePlaceholder: "选择该智能体时显示的欢迎消息",
suggestedPrompts: "推荐问题",
mode: "运行模式",
webSearch: "网络搜索",
webSearchMaxResults: "最大搜索结果数",
knowledgeBases: "关联知识库",
selectKnowledgeBases: "请选择知识库",
allowUserKBSelection: "允许用户选择知识库",
allowUserKBSelectionDesc: "关闭后,用户将无法在对话时选择知识库",
rerankModel: "ReRank 模型",
rerankModelDesc: "用于对知识库检索结果进行重排序,提高回答准确性",
rerankModelPlaceholder: "请选择 ReRank 模型",
maxIterations: "最大迭代次数",
allowedTools: "允许的工具",
multiTurn: "多轮对话",
historyTurns: "保留轮数",
},
selector: {
title: "选择智能体",
builtinSection: "内置智能体",
customSection: "我的智能体",
addNew: "添加新智能体",
},
builtinAgents: "内置智能体",
customAgents: "自定义智能体",
manageAgents: "管理智能体",
},
file: {
upload: "上传文件",
uploadSuccess: "文件上传成功",
@@ -1431,10 +1542,11 @@ export default {
placeholderWithContext: "输入问题,将基于上方选中的知识库/文件回答",
placeholderWebOnly: "输入问题,将结合网络搜索回答",
placeholderKbAndWeb: "输入问题,将基于知识库和网络搜索回答",
agentMode: "Agent 模式",
normalMode: "普通模式",
placeholderAgent: "向 {name} 提问",
agentMode: "智能推理",
normalMode: "快速问答",
normalModeDesc: "基于知识库的 RAG 问答",
agentModeDesc: "ReAct 推理框架,多步思考",
agentModeDesc: "多步思考,深度分析",
agentNotReadyTooltip: "Agent 未就绪,请先在设置中完成配置",
agentNotReadyDetail:
"Agent 未就绪,需要配置以下内容:{reasons}",
@@ -1462,6 +1574,7 @@ export default {
replying: "正在回复中,请稍后再试!",
agentSwitchedOn: "已切换到 Agent 模式",
agentSwitchedOff: "已切换到普通模式",
agentSelected: "已选择智能体「{name}」",
agentEnabled: "Agent 模式已启用",
agentDisabled: "Agent 模式已禁用",
agentNotReadyDetail:
@@ -1475,6 +1588,13 @@ export default {
stopSuccess: "已停止生成",
stopFailed: "停止失败,请重试",
},
webSearchDisabledByAgent: "当前智能体已禁用网络搜索",
webSearchForcedByAgent: "当前智能体已启用网络搜索,无法关闭",
kbLockedByAgent: "当前智能体已锁定知识库配置",
kbDisabledByAgent: "当前智能体已禁用知识库功能",
cannotRemoveAgentKb: "智能体配置的知识库无法移除",
agentConfiguredKb: "由智能体配置,不可删除",
modelLockedByAgent: "当前智能体已锁定模型配置",
},
agentSettings: {
title: "Agent 配置",
+6
View File
@@ -51,6 +51,12 @@ const router = createRouter({
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "agents",
name: "agentList",
component: () => import("../views/agent/AgentList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "creatChat",
name: "globalCreatChat",
+5 -4
View File
@@ -18,6 +18,7 @@ const createMenuChildren = () => reactive<MenuChild[]>([])
export const useMenuStore = defineStore('menuStore', () => {
const menuArr = reactive<MenuItem[]>([
{ title: '', titleKey: 'menu.knowledgeBase', icon: 'zhishiku', path: 'knowledge-bases' },
{ title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents' },
{
title: '',
titleKey: 'menu.chat',
@@ -52,14 +53,14 @@ export const useMenuStore = defineStore('menuStore', () => {
)
const clearMenuArr = () => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
if (chatMenu && chatMenu.children) {
chatMenu.children = createMenuChildren()
}
}
const updatemenuArr = (obj: any) => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
if (!chatMenu.children) {
chatMenu.children = createMenuChildren()
}
@@ -70,7 +71,7 @@ export const useMenuStore = defineStore('menuStore', () => {
}
const updataMenuChildren = (item: MenuChild) => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
if (!chatMenu.children) {
chatMenu.children = createMenuChildren()
}
@@ -78,7 +79,7 @@ export const useMenuStore = defineStore('menuStore', () => {
}
const updatasessionTitle = (sessionId: string, title: string) => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
chatMenu.children?.forEach((item: MenuChild) => {
if (item.id === sessionId) {
item.title = title
+24 -1
View File
@@ -13,6 +13,7 @@ interface Settings {
ollamaConfig: OllamaConfig; // Ollama配置
webSearchEnabled: boolean; // 网络搜索是否启用
conversationModels: ConversationModels;
selectedAgentId: string; // 当前选中的智能体ID
}
// Agent 配置接口
@@ -89,7 +90,8 @@ const defaultSettings: Settings = {
summaryModelId: "",
rerankModelId: "",
selectedChatModelId: "", // 用户当前选择的对话模型ID
}
},
selectedAgentId: "builtin-normal", // 默认选中普通模式
};
export const useSettingsStore = defineStore("settings", {
@@ -124,6 +126,9 @@ export const useSettingsStore = defineStore("settings", {
// 网络搜索是否启用
isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,
// 当前选中的智能体ID
selectedAgentId: (state) => state.settings.selectedAgentId || "builtin-normal",
},
actions: {
@@ -301,6 +306,24 @@ export const useSettingsStore = defineStore("settings", {
getSelectedFiles(): string[] {
return this.settings.selectedFiles || [];
},
// 选择智能体
selectAgent(agentId: string) {
this.settings.selectedAgentId = agentId;
// 根据智能体类型自动切换 Agent 模式
if (agentId === "builtin-normal") {
this.settings.isAgentEnabled = false;
} else if (agentId === "builtin-agent") {
this.settings.isAgentEnabled = true;
}
// 自定义智能体需要根据其配置来决定
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
// 获取选中的智能体ID
getSelectedAgentId(): string {
return this.settings.selectedAgentId || "builtin-normal";
},
},
});
File diff suppressed because it is too large Load Diff
+797
View File
@@ -0,0 +1,797 @@
<template>
<div class="agent-list-container">
<!-- 头部 -->
<div class="header">
<div class="header-title">
<h2>{{ $t('agent.title') }}</h2>
<p class="header-subtitle">{{ $t('agent.subtitle') }}</p>
</div>
</div>
<div class="header-divider"></div>
<!-- 卡片网格 -->
<div v-if="agents.length > 0" class="agent-card-wrap">
<div
v-for="agent in agents"
:key="agent.id"
class="agent-card"
:class="{
'is-builtin': agent.is_builtin,
'agent-mode-normal': agent.config?.agent_mode === 'normal',
'agent-mode-agent': agent.config?.agent_mode === 'agent'
}"
@click="handleCardClick(agent)"
>
<!-- 装饰星星 -->
<div class="card-decoration">
<svg class="star-icon" width="24" height="24" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" stroke="currentColor" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round" fill="currentColor" fill-opacity="0.15"/>
</svg>
<svg class="star-icon small" width="14" height="14" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" stroke="currentColor" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round" fill="currentColor" fill-opacity="0.15"/>
</svg>
</div>
<!-- 卡片头部 -->
<div class="card-header">
<div class="card-header-left">
<AgentAvatar :name="agent.name" size="medium" />
<span class="card-title" :title="agent.name">{{ agent.name }}</span>
</div>
<t-popup
v-if="!agent.is_builtin"
v-model="agent.showMore"
overlayClassName="card-more-popup"
:on-visible-change="(visible: boolean) => onVisibleChange(visible, agent)"
trigger="click"
destroy-on-close
placement="bottom-right"
>
<div
class="more-wrap"
@click.stop
:class="{ 'active-more': agent.showMore }"
>
<img class="more-icon" src="@/assets/img/more.png" alt="" />
</div>
<template #content>
<div class="popup-menu">
<div class="popup-menu-item" @click="handleEdit(agent)">
<t-icon class="menu-icon" name="edit" />
<span>{{ $t('common.edit') }}</span>
</div>
<div class="popup-menu-item delete" @click="handleDelete(agent)">
<t-icon class="menu-icon" name="delete" />
<span>{{ $t('common.delete') }}</span>
</div>
</div>
</template>
</t-popup>
<div v-else class="builtin-badge">
<t-icon name="lock-on" size="12px" />
<span>{{ $t('agent.builtin') }}</span>
</div>
</div>
<!-- 卡片内容 -->
<div class="card-content">
<div class="card-description">
{{ agent.description || $t('agent.noDescription') }}
</div>
</div>
<!-- 卡片底部 -->
<div class="card-bottom">
<div class="bottom-left">
<div class="type-badge" :class="{ 'normal': agent.config?.agent_mode === 'normal', 'agent': agent.config?.agent_mode === 'agent' }">
<t-icon :name="agent.config?.agent_mode === 'agent' ? 'control-platform' : 'chat'" size="14px" />
<span>{{ agent.config?.agent_mode === 'agent' ? $t('agent.mode.agent') : $t('agent.mode.normal') }}</span>
</div>
<div class="feature-badges">
<t-tooltip v-if="agent.config?.web_search_enabled" :content="$t('agent.features.webSearch')" placement="top">
<div class="feature-badge web-search">
<t-icon name="search" size="14px" />
</div>
</t-tooltip>
<t-tooltip v-if="agent.config?.knowledge_bases?.length" :content="$t('agent.features.knowledgeBase')" placement="top">
<div class="feature-badge knowledge">
<t-icon name="folder" size="14px" />
</div>
</t-tooltip>
<t-tooltip v-if="agent.config?.multi_turn_enabled" :content="$t('agent.features.multiTurn')" placement="top">
<div class="feature-badge multi-turn">
<t-icon name="chat-bubble" size="14px" />
</div>
</t-tooltip>
</div>
</div>
<span v-if="agent.updated_at" class="card-time">{{ formatDate(agent.updated_at) }}</span>
</div>
</div>
</div>
<!-- 空状态 -->
<div v-else-if="!loading" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
<span class="empty-txt">{{ $t('agent.empty.title') }}</span>
<span class="empty-desc">{{ $t('agent.empty.description') }}</span>
</div>
<!-- 删除确认对话框 -->
<t-dialog
v-model:visible="deleteVisible"
dialogClassName="del-agent-dialog"
:closeBtn="false"
:cancelBtn="null"
:confirmBtn="null"
>
<div class="circle-wrap">
<div class="dialog-header">
<img class="circle-img" src="@/assets/img/circle.png" alt="">
<span class="circle-title">{{ $t('agent.delete.confirmTitle') }}</span>
</div>
<span class="del-circle-txt">
{{ $t('agent.delete.confirmMessage', { name: deletingAgent?.name ?? '' }) }}
</span>
<div class="circle-btn">
<span class="circle-btn-txt" @click="deleteVisible = false">{{ $t('common.cancel') }}</span>
<span class="circle-btn-txt confirm" @click="confirmDelete">{{ $t('agent.delete.confirmButton') }}</span>
</div>
</div>
</t-dialog>
<!-- 智能体编辑器弹窗 -->
<AgentEditorModal
:visible="editorVisible"
:mode="editorMode"
:agent="editingAgent"
@update:visible="editorVisible = $event"
@success="handleEditorSuccess"
/>
</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { listAgents, deleteAgent, type CustomAgent } from '@/api/agent'
import { formatStringDate } from '@/utils/index'
import { useI18n } from 'vue-i18n'
import AgentEditorModal from './AgentEditorModal.vue'
import AgentAvatar from '@/components/AgentAvatar.vue'
const { t } = useI18n()
interface AgentWithUI extends CustomAgent {
showMore?: boolean
}
const agents = ref<AgentWithUI[]>([])
const loading = ref(false)
const deleteVisible = ref(false)
const deletingAgent = ref<AgentWithUI | null>(null)
const editorVisible = ref(false)
const editorMode = ref<'create' | 'edit'>('create')
const editingAgent = ref<CustomAgent | null>(null)
const fetchList = () => {
loading.value = true
return listAgents().then((res: any) => {
const data = res.data || []
// 过滤掉内置智能体,只展示自定义智能体
agents.value = data
.filter((agent: CustomAgent) => !agent.is_builtin)
.map((agent: CustomAgent) => ({
...agent,
showMore: false
}))
}).finally(() => loading.value = false)
}
// 监听菜单创建智能体事件
const handleOpenAgentEditor = (event: CustomEvent) => {
if (event.detail?.mode === 'create') {
openCreateModal()
}
}
onMounted(() => {
fetchList()
window.addEventListener('openAgentEditor', handleOpenAgentEditor as EventListener)
})
onUnmounted(() => {
window.removeEventListener('openAgentEditor', handleOpenAgentEditor as EventListener)
})
const onVisibleChange = (visible: boolean, agent: AgentWithUI) => {
if (!visible) {
agent.showMore = false
}
}
const handleCardClick = (agent: AgentWithUI) => {
// 如果弹窗正在显示,不触发编辑
if (agent.showMore) {
return
}
// 点击卡片查看详情或编辑
if (agent.is_builtin) {
// 内置智能体只能查看
MessagePlugin.info(t('agent.messages.builtinReadonly'))
} else {
handleEdit(agent)
}
}
const handleEdit = (agent: AgentWithUI) => {
agent.showMore = false
editingAgent.value = agent
editorMode.value = 'edit'
editorVisible.value = true
}
const handleDelete = (agent: AgentWithUI) => {
agent.showMore = false
deletingAgent.value = agent
deleteVisible.value = true
}
const confirmDelete = () => {
if (!deletingAgent.value) return
deleteAgent(deletingAgent.value.id).then((res: any) => {
if (res.success) {
MessagePlugin.success(t('agent.messages.deleted'))
deleteVisible.value = false
deletingAgent.value = null
fetchList()
} else {
MessagePlugin.error(res.message || t('agent.messages.deleteFailed'))
}
}).catch((e: any) => {
MessagePlugin.error(e?.message || t('agent.messages.deleteFailed'))
})
}
const handleEditorSuccess = () => {
editorVisible.value = false
editingAgent.value = null
fetchList()
}
const formatDate = (dateStr: string) => {
if (!dateStr) return ''
return formatStringDate(new Date(dateStr))
}
// 暴露创建方法供外部调用
const openCreateModal = () => {
editingAgent.value = null
editorMode.value = 'create'
editorVisible.value = true
}
defineExpose({
openCreateModal
})
</script>
<style scoped lang="less">
.agent-list-container {
padding: 24px 44px;
margin: 0 20px;
height: calc(100vh);
overflow-y: auto;
box-sizing: border-box;
flex: 1;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
.header-title {
display: flex;
flex-direction: column;
gap: 4px;
}
h2 {
margin: 0;
color: #000000e6;
font-family: "PingFang SC";
font-size: 24px;
font-weight: 600;
line-height: 32px;
}
}
.header-subtitle {
margin: 0;
color: #00000099;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 20px;
}
.header-divider {
height: 1px;
background: #e7ebf0;
margin-bottom: 20px;
}
.agent-card-wrap {
display: grid;
gap: 20px;
grid-template-columns: 1fr;
}
.agent-card {
border: 2px solid #fbfbfb;
border-radius: 6px;
overflow: hidden;
box-sizing: border-box;
box-shadow: 0 0 8px 0 #00000005;
background: #fff;
position: relative;
cursor: pointer;
transition: all 0.2s ease;
padding: 12px 16px 14px;
display: flex;
flex-direction: column;
min-height: 150px;
&:hover {
border-color: #07c05f;
}
// 普通模式样式
&.agent-mode-normal {
background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);
border-color: #e8f5ed;
&:hover {
border-color: #07c05f;
background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
}
.card-decoration {
color: rgba(7, 192, 95, 0.35);
}
&:hover .card-decoration {
color: rgba(7, 192, 95, 0.5);
}
}
// Agent 模式样式
&.agent-mode-agent {
background: linear-gradient(135deg, #ffffff 0%, #f8f5ff 100%);
border-color: #ede8ff;
&:hover {
border-color: #7c4dff;
background: linear-gradient(135deg, #ffffff 0%, #f3efff 100%);
}
.card-decoration {
color: rgba(124, 77, 255, 0.35);
}
&:hover .card-decoration {
color: rgba(124, 77, 255, 0.5);
}
}
// 确保内容在装饰之上
.card-header,
.card-content,
.card-bottom {
position: relative;
z-index: 1;
}
}
.card-decoration {
position: absolute;
top: 8px;
right: 8px;
display: flex;
align-items: flex-start;
gap: 2px;
pointer-events: none;
z-index: 0;
transition: color 0.2s ease;
.star-icon {
opacity: 0.8;
&.small {
margin-top: 12px;
opacity: 0.6;
}
}
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.card-header-left {
display: flex;
align-items: center;
gap: 10px;
flex: 1;
min-width: 0;
}
.card-title {
color: #000000e6;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 600;
line-height: 22px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.builtin-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 4px;
background: rgba(0, 0, 0, 0.05);
color: #00000066;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 400;
}
.more-wrap {
display: flex;
width: 32px;
height: 32px;
justify-content: center;
align-items: center;
border-radius: 6px;
cursor: pointer;
flex-shrink: 0;
transition: all 0.2s ease;
opacity: 0.7;
&:hover {
background: rgba(0, 0, 0, 0.06);
opacity: 1;
}
&.active-more {
background: rgba(0, 0, 0, 0.08);
opacity: 1;
}
.more-icon {
width: 16px;
height: 16px;
}
}
.card-content {
flex: 1;
margin-bottom: 10px;
}
.card-description {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
line-clamp: 2;
overflow: hidden;
color: #00000066;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 400;
line-height: 20px;
min-height: 40px;
}
.card-bottom {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 0 0;
border-top: 1px solid #f0f0f0;
margin-top: auto;
}
.bottom-left {
display: flex;
align-items: center;
gap: 8px;
}
.type-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 10px;
border-radius: 4px;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 500;
line-height: 18px;
&.normal {
background: rgba(7, 192, 95, 0.1);
color: #059669;
border: 1px solid rgba(7, 192, 95, 0.2);
}
&.agent {
background: rgba(124, 77, 255, 0.1);
color: #7c4dff;
border: 1px solid rgba(124, 77, 255, 0.2);
}
}
.feature-badges {
display: flex;
align-items: center;
gap: 6px;
}
.feature-badge {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 4px;
cursor: pointer;
&.web-search {
background: rgba(255, 152, 0, 0.1);
color: #ff9800;
border: 1px solid rgba(255, 152, 0, 0.2);
&:hover {
background: rgba(255, 152, 0, 0.15);
}
}
&.knowledge {
background: rgba(7, 192, 95, 0.1);
color: #059669;
border: 1px solid rgba(7, 192, 95, 0.2);
&:hover {
background: rgba(7, 192, 95, 0.15);
}
}
&.multi-turn {
background: rgba(0, 82, 217, 0.1);
color: #0052d9;
border: 1px solid rgba(0, 82, 217, 0.2);
&:hover {
background: rgba(0, 82, 217, 0.15);
}
}
}
.card-time {
color: #00000066;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 400;
}
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 60px 20px;
.empty-img {
width: 162px;
height: 162px;
margin-bottom: 20px;
}
.empty-txt {
color: #00000099;
font-family: "PingFang SC";
font-size: 16px;
font-weight: 600;
line-height: 26px;
margin-bottom: 8px;
}
.empty-desc {
color: #00000066;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 22px;
}
}
// 响应式布局
@media (min-width: 900px) {
.agent-card-wrap {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1250px) {
.agent-card-wrap {
grid-template-columns: repeat(3, 1fr);
}
}
@media (min-width: 1600px) {
.agent-card-wrap {
grid-template-columns: repeat(4, 1fr);
}
}
// 删除确认对话框样式
:deep(.del-agent-dialog) {
padding: 0px !important;
border-radius: 6px !important;
.t-dialog__header {
display: none;
}
.t-dialog__body {
padding: 16px;
}
.t-dialog__footer {
padding: 0;
}
}
:deep(.t-dialog__position.t-dialog--top) {
padding-top: 40vh !important;
}
.circle-wrap {
.dialog-header {
display: flex;
align-items: center;
margin-bottom: 8px;
}
.circle-img {
width: 20px;
height: 20px;
margin-right: 8px;
}
.circle-title {
color: #000000e6;
font-family: "PingFang SC";
font-size: 16px;
font-weight: 600;
line-height: 24px;
}
.del-circle-txt {
color: #00000099;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 22px;
display: inline-block;
margin-left: 29px;
margin-bottom: 21px;
}
.circle-btn {
height: 22px;
width: 100%;
display: flex;
justify-content: flex-end;
}
.circle-btn-txt {
color: #000000e6;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 22px;
cursor: pointer;
&:hover {
opacity: 0.8;
}
}
.confirm {
color: #FA5151;
margin-left: 40px;
&:hover {
opacity: 0.8;
}
}
}
</style>
<style lang="less">
// 更多操作弹窗样式
.card-more-popup {
z-index: 99 !important;
.t-popup__content {
padding: 6px 0 !important;
margin-top: 6px !important;
min-width: 140px;
border-radius: 6px !important;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
border: 1px solid #e7ebf0 !important;
}
}
.popup-menu {
display: flex;
flex-direction: column;
}
.popup-menu-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
cursor: pointer;
transition: all 0.2s ease;
color: #000000e6;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 20px;
.menu-icon {
font-size: 16px;
flex-shrink: 0;
color: #00000099;
transition: color 0.2s ease;
}
&:hover {
background: #f7f9fc;
.menu-icon {
color: #000000e6;
}
}
&.delete {
color: #000000e6;
&:hover {
background: #fff1f0;
color: #fa5151;
.menu-icon {
color: #fa5151;
}
}
}
}
</style>
+3
View File
@@ -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,
@@ -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
}
+11 -3
View File
@@ -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
@@ -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
}
@@ -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
}
+140 -20
View File
@@ -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(
+3
View File
@@ -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))
+298
View File
@@ -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",
})
}
+3
View File
@@ -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,
}
}
+406 -455
View File
@@ -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
+1
View File
@@ -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
+17 -6
View File
@@ -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
}
+19
View File
@@ -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)
}
}
+2
View File
@@ -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)
}
+186
View File
@@ -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),
}
}
@@ -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
+101
View File
@@ -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
}
+4
View File
@@ -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
@@ -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 $$;
@@ -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 $$;