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