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,