From 236b190b2695e4eedc9a30449ef6ca8f296b3b06 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 23 Dec 2025 11:25:39 +0800 Subject: [PATCH 01/17] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9EFAQ=E6=9D=A1?= =?UTF-8?q?=E7=9B=AE=E8=8E=B7=E5=8F=96=E6=8E=A5=E5=8F=A3=EF=BC=8C=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8C=89ID=E6=9F=A5=E8=AF=A2=E5=8D=95=E4=B8=AAFAQ?= =?UTF-8?q?=E6=9D=A1=E7=9B=AE=EF=BC=9B=E5=A2=9E=E5=BC=BA=E6=A0=87=E7=AD=BE?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=8A=9F=E8=83=BD=EF=BC=8C=E6=94=AF=E6=8C=81?= =?UTF-8?q?content=5Fonly=E6=A8=A1=E5=BC=8F=E4=BB=85=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=A0=87=E7=AD=BE=E4=B8=8B=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- client/faq.go | 17 ++++++++++ client/tag.go | 9 +++-- internal/application/service/knowledge.go | 41 +++++++++++++++++++++++ internal/application/service/tag.go | 16 ++++++++- internal/handler/faq.go | 32 ++++++++++++++++++ internal/handler/tag.go | 16 +++++---- internal/router/router.go | 1 + internal/types/interfaces/knowledge.go | 2 ++ internal/types/interfaces/tag.go | 3 +- 9 files changed, 126 insertions(+), 11 deletions(-) diff --git a/client/faq.go b/client/faq.go index a3c5c93a..5f2f32c9 100644 --- a/client/faq.go +++ b/client/faq.go @@ -209,6 +209,23 @@ func (c *Client) CreateFAQEntry(ctx context.Context, return response.Data, nil } +// GetFAQEntry retrieves a single FAQ entry by ID. +func (c *Client) GetFAQEntry(ctx context.Context, + knowledgeBaseID, entryID string, +) (*FAQEntry, error) { + path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%s", knowledgeBaseID, entryID) + resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil) + if err != nil { + return nil, err + } + + var response FAQEntryResponse + if err := parseResponse(resp, &response); err != nil { + return nil, err + } + return response.Data, nil +} + // UpdateFAQEntry updates a single FAQ entry. func (c *Client) UpdateFAQEntry(ctx context.Context, knowledgeBaseID, entryID string, payload *FAQEntryPayload, diff --git a/client/tag.go b/client/tag.go index e467b32d..4e21e5c7 100644 --- a/client/tag.go +++ b/client/tag.go @@ -137,15 +137,20 @@ func (c *Client) UpdateTag(ctx context.Context, return response.Data, nil } -// DeleteTag deletes a tag. Set force to true to delete even if the tag is referenced. +// DeleteTag deletes a tag. +// Set force to true to delete even if the tag is referenced. +// Set contentOnly to true to only delete the content under the tag but keep the tag itself. func (c *Client) DeleteTag(ctx context.Context, - knowledgeBaseID, tagID string, force bool, + knowledgeBaseID, tagID string, force bool, contentOnly bool, ) error { path := fmt.Sprintf("/api/v1/knowledge-bases/%s/tags/%s", knowledgeBaseID, tagID) query := url.Values{} if force { query.Add("force", "true") } + if contentOnly { + query.Add("content_only", "true") + } resp, err := c.doRequest(ctx, http.MethodDelete, path, nil, query) if err != nil { diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index 26aeb4ee..6c1e2662 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -3318,6 +3318,47 @@ func (s *knowledgeService) CreateFAQEntry(ctx context.Context, return entry, nil } +// GetFAQEntry retrieves a single FAQ entry by ID. +func (s *knowledgeService) GetFAQEntry(ctx context.Context, + kbID string, entryID string, +) (*types.FAQEntry, error) { + if entryID == "" { + return nil, werrors.NewBadRequestError("条目ID不能为空") + } + + kb, err := s.validateFAQKnowledgeBase(ctx, kbID) + if err != nil { + return nil, err + } + kb.EnsureDefaults() + + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) + + // 获取chunk + chunk, err := s.chunkService.GetChunkByID(ctx, entryID) + if err != nil { + return nil, err + } + + // 验证chunk属于当前知识库 + if chunk.KnowledgeBaseID != kb.ID || chunk.TenantID != tenantID { + return nil, werrors.NewNotFoundError("FAQ条目不存在") + } + + // 验证是FAQ类型 + if chunk.ChunkType != types.ChunkTypeFAQ { + return nil, werrors.NewNotFoundError("FAQ条目不存在") + } + + // 转换为FAQEntry返回 + entry, err := s.chunkToFAQEntry(chunk, kb) + if err != nil { + return nil, err + } + + return entry, nil +} + // UpdateFAQEntry updates a single FAQ entry. func (s *knowledgeService) UpdateFAQEntry(ctx context.Context, kbID string, entryID string, payload *types.FAQEntryPayload, diff --git a/internal/application/service/tag.go b/internal/application/service/tag.go index 06896310..d9a7d5d4 100644 --- a/internal/application/service/tag.go +++ b/internal/application/service/tag.go @@ -153,7 +153,8 @@ func (s *knowledgeTagService) UpdateTag( } // DeleteTag deletes a tag. When force=true, also deletes all chunks under this tag. -func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bool) error { +// When contentOnly=true, only deletes the content under the tag but keeps the tag itself. +func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bool, contentOnly bool) error { if id == "" { return werrors.NewBadRequestError("标签ID不能为空") } @@ -166,6 +167,19 @@ func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bo if err != nil { return err } + + // contentOnly mode: only delete content, keep the tag + if contentOnly { + if cCount > 0 { + if err := s.chunkRepo.DeleteChunksByTagID(ctx, tenantID, tag.KnowledgeBaseID, tag.ID); err != nil { + logger.Errorf(ctx, "Failed to delete chunks by tag ID %s: %v", tag.ID, err) + return werrors.NewInternalServerError("删除标签下的数据失败") + } + logger.Infof(ctx, "Deleted %d chunks under tag %s (content_only mode)", cCount, tag.ID) + } + return nil + } + if !force && (kCount > 0 || cCount > 0) { return werrors.NewBadRequestError("标签仍有知识或FAQ条目引用,无法删除") } diff --git a/internal/handler/faq.go b/internal/handler/faq.go index bca93ddd..8a7ef256 100644 --- a/internal/handler/faq.go +++ b/internal/handler/faq.go @@ -351,6 +351,38 @@ func (h *FAQHandler) ExportEntries(c *gin.Context) { c.Data(http.StatusOK, "text/csv; charset=utf-8", append(bom, csvData...)) } +// GetEntry godoc +// @Summary 获取FAQ条目详情 +// @Description 根据ID获取单个FAQ条目的详情 +// @Tags FAQ管理 +// @Accept json +// @Produce json +// @Param id path string true "知识库ID" +// @Param entry_id path string true "FAQ条目ID" +// @Success 200 {object} map[string]interface{} "FAQ条目详情" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Failure 404 {object} errors.AppError "条目不存在" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /knowledge-bases/{id}/faq/entries/{entry_id} [get] +func (h *FAQHandler) GetEntry(c *gin.Context) { + ctx := c.Request.Context() + kbID := secutils.SanitizeForLog(c.Param("id")) + entryID := secutils.SanitizeForLog(c.Param("entry_id")) + + entry, err := h.knowledgeService.GetFAQEntry(ctx, kbID, entryID) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + c.Error(err) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": entry, + }) +} + // GetImportProgress godoc // @Summary 获取FAQ导入进度 // @Description 获取FAQ导入任务的进度 diff --git a/internal/handler/tag.go b/internal/handler/tag.go index 43397d6f..6bc7c032 100644 --- a/internal/handler/tag.go +++ b/internal/handler/tag.go @@ -157,15 +157,16 @@ func (h *TagHandler) UpdateTag(c *gin.Context) { // DeleteTag godoc // @Summary 删除标签 -// @Description 删除标签,可使用force=true强制删除被引用的标签 +// @Description 删除标签,可使用force=true强制删除被引用的标签,content_only=true仅删除标签下的内容而保留标签本身 // @Tags 标签管理 // @Accept json // @Produce json -// @Param id path string true "知识库ID" -// @Param tag_id path string true "标签ID" -// @Param force query bool false "强制删除" -// @Success 200 {object} map[string]interface{} "删除成功" -// @Failure 400 {object} errors.AppError "请求参数错误" +// @Param id path string true "知识库ID" +// @Param tag_id path string true "标签ID" +// @Param force query bool false "强制删除" +// @Param content_only query bool false "仅删除内容,保留标签" +// @Success 200 {object} map[string]interface{} "删除成功" +// @Failure 400 {object} errors.AppError "请求参数错误" // @Security Bearer // @Security ApiKeyAuth // @Router /knowledge-bases/{id}/tags/{tag_id} [delete] @@ -174,8 +175,9 @@ func (h *TagHandler) DeleteTag(c *gin.Context) { tagID := secutils.SanitizeForLog(c.Param("tag_id")) force := c.Query("force") == "true" + contentOnly := c.Query("content_only") == "true" - if err := h.tagService.DeleteTag(ctx, tagID, force); err != nil { + if err := h.tagService.DeleteTag(ctx, tagID, force, contentOnly); err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ "tag_id": tagID, }) diff --git a/internal/router/router.go b/internal/router/router.go index 17a2444a..fcf6219b 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -183,6 +183,7 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler) { { faq.GET("/entries", handler.ListEntries) faq.GET("/entries/export", handler.ExportEntries) + faq.GET("/entries/:entry_id", handler.GetEntry) faq.POST("/entries", handler.UpsertEntries) faq.POST("/entry", handler.CreateEntry) faq.PUT("/entries/:entry_id", handler.UpdateEntry) diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.go index 4f3edb23..ad0a25b5 100644 --- a/internal/types/interfaces/knowledge.go +++ b/internal/types/interfaces/knowledge.go @@ -86,6 +86,8 @@ type KnowledgeService interface { UpsertFAQEntries(ctx context.Context, kbID string, payload *types.FAQBatchUpsertPayload) (string, error) // CreateFAQEntry creates a single FAQ entry synchronously. CreateFAQEntry(ctx context.Context, kbID string, payload *types.FAQEntryPayload) (*types.FAQEntry, error) + // GetFAQEntry retrieves a single FAQ entry by ID. + GetFAQEntry(ctx context.Context, kbID string, entryID string) (*types.FAQEntry, error) // UpdateFAQEntry updates a single FAQ entry. UpdateFAQEntry(ctx context.Context, kbID string, entryID string, payload *types.FAQEntryPayload) error // UpdateFAQEntryFieldsBatch updates multiple fields for FAQ entries in batch. diff --git a/internal/types/interfaces/tag.go b/internal/types/interfaces/tag.go index 4d413b19..471c2d2e 100644 --- a/internal/types/interfaces/tag.go +++ b/internal/types/interfaces/tag.go @@ -15,7 +15,8 @@ type KnowledgeTagService interface { // UpdateTag updates tag basic information. UpdateTag(ctx context.Context, id string, name *string, color *string, sortOrder *int) (*types.KnowledgeTag, error) // DeleteTag deletes a tag. - DeleteTag(ctx context.Context, id string, force bool) error + // When contentOnly=true, only deletes the content under the tag but keeps the tag itself. + DeleteTag(ctx context.Context, id string, force bool, contentOnly bool) error // FindOrCreateTagByName finds a tag by name or creates it if not exists. FindOrCreateTagByName(ctx context.Context, kbID string, name string) (*types.KnowledgeTag, error) } From d0c5c4f6b0461379fcc7b5aabf248334455f380f Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 24 Dec 2025 10:34:41 +0800 Subject: [PATCH 02/17] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E6=99=BA?= =?UTF-8?q?=E8=83=BD=E4=BD=93=E5=8A=9F=E8=83=BD=E6=A8=A1=E5=9D=97=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=87=AA=E5=AE=9A=E4=B9=89=E6=99=BA=E8=83=BD?= =?UTF-8?q?=E4=BD=93=E5=88=9B=E5=BB=BA=E3=80=81=E9=85=8D=E7=BD=AE=E5=92=8C?= =?UTF-8?q?=E9=80=89=E6=8B=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/api/agent/index.ts | 94 ++ frontend/src/api/chat/streame.ts | 6 +- frontend/src/assets/img/agent-green.svg | 5 + frontend/src/assets/img/agent.svg | 8 +- frontend/src/components/AgentAvatar.vue | 155 ++ frontend/src/components/AgentSelector.vue | 430 +++++ frontend/src/components/Input-field.vue | 472 ++++-- frontend/src/components/menu.vue | 42 +- frontend/src/i18n/locales/en-US.ts | 130 +- frontend/src/i18n/locales/ru-RU.ts | 7 +- frontend/src/i18n/locales/zh-CN.ts | 144 +- frontend/src/router/index.ts | 6 + frontend/src/stores/menu.ts | 9 +- frontend/src/stores/settings.ts | 25 +- frontend/src/views/agent/AgentEditorModal.vue | 1435 +++++++++++++++++ frontend/src/views/agent/AgentList.vue | 797 +++++++++ frontend/src/views/chat/index.vue | 3 + .../application/repository/custom_agent.go | 62 + internal/application/service/agent_service.go | 14 +- internal/application/service/custom_agent.go | 267 +++ .../service/llmcontext/context_manager.go | 39 + internal/application/service/session.go | 160 +- internal/container/container.go | 3 + internal/handler/custom_agent.go | 298 ++++ internal/handler/session/handler.go | 3 + internal/handler/session/qa.go | 861 +++++----- internal/handler/session/types.go | 1 + internal/models/chat/remote_api.go | 23 +- internal/router/router.go | 19 + internal/types/agent.go | 2 + internal/types/custom_agent.go | 186 +++ internal/types/interfaces/context_manager.go | 4 + internal/types/interfaces/custom_agent.go | 101 ++ internal/types/interfaces/session.go | 4 + .../versioned/000006_custom_agents.down.sql | 19 + .../versioned/000006_custom_agents.up.sql | 33 + 36 files changed, 5195 insertions(+), 672 deletions(-) create mode 100644 frontend/src/api/agent/index.ts create mode 100644 frontend/src/assets/img/agent-green.svg create mode 100644 frontend/src/components/AgentAvatar.vue create mode 100644 frontend/src/components/AgentSelector.vue create mode 100644 frontend/src/views/agent/AgentEditorModal.vue create mode 100644 frontend/src/views/agent/AgentList.vue create mode 100644 internal/application/repository/custom_agent.go create mode 100644 internal/application/service/custom_agent.go create mode 100644 internal/handler/custom_agent.go create mode 100644 internal/types/custom_agent.go create mode 100644 internal/types/interfaces/custom_agent.go create mode 100644 migrations/versioned/000006_custom_agents.down.sql create mode 100644 migrations/versioned/000006_custom_agents.up.sql diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts new file mode 100644 index 00000000..b41e9566 --- /dev/null +++ b/frontend/src/api/agent/index.ts @@ -0,0 +1,94 @@ +import { get, post, put, del } from "../../utils/request"; + +// 智能体类型 +export type CustomAgentType = 'normal' | 'agent' | 'custom'; + +// 智能体配置 +export interface CustomAgentConfig { + agent_mode?: 'normal' | 'agent'; // 运行模式:normal=RAG模式, agent=ReAct Agent模式 + system_prompt?: string; + model_id?: string; + rerank_model_id?: string; // ReRank 模型 ID(当使用知识库时需要) + temperature?: number; + max_iterations?: number; + allowed_tools?: string[]; + knowledge_bases?: string[]; + // 当没有配置知识库时,是否允许用户自由选择知识库 + // true (默认): 用户可以自由选择任意知识库 + // false: 禁用知识库选择功能 + allow_user_kb_selection?: boolean; + web_search_enabled?: boolean; + web_search_max_results?: number; + reflection_enabled?: boolean; + welcome_message?: string; + suggested_prompts?: string[]; + multi_turn_enabled?: boolean; // 是否启用多轮对话 + history_turns?: number; // 保留历史轮数 +} + +// 智能体 +export interface CustomAgent { + id: string; + name: string; + description?: string; + avatar?: string; + is_builtin: boolean; + type: CustomAgentType; + tenant_id?: number; + created_by?: string; + config: CustomAgentConfig; + created_at?: string; + updated_at?: string; +} + +// 创建智能体请求 +export interface CreateAgentRequest { + name: string; + description?: string; + avatar?: string; + type?: CustomAgentType; + config?: CustomAgentConfig; +} + +// 更新智能体请求 +export interface UpdateAgentRequest { + name: string; + description?: string; + avatar?: string; + type?: CustomAgentType; + config?: CustomAgentConfig; +} + +// 内置智能体 ID +export const BUILTIN_AGENT_NORMAL_ID = 'builtin-normal'; +export const BUILTIN_AGENT_AGENT_ID = 'builtin-agent'; + +// 获取智能体列表(包括内置智能体) +export function listAgents() { + return get<{ data: CustomAgent[] }>('/api/v1/agents'); +} + +// 获取智能体详情 +export function getAgentById(id: string) { + return get<{ data: CustomAgent }>(`/api/v1/agents/${id}`); +} + +// 创建智能体 +export function createAgent(data: CreateAgentRequest) { + return post<{ data: CustomAgent }>('/api/v1/agents', data); +} + +// 更新智能体 +export function updateAgent(id: string, data: UpdateAgentRequest) { + return put<{ data: CustomAgent }>(`/api/v1/agents/${id}`, data); +} + +// 删除智能体 +export function deleteAgent(id: string) { + return del<{ success: boolean }>(`/api/v1/agents/${id}`); +} + +// 判断是否为内置智能体 +export function isBuiltinAgent(agentId: string): boolean { + return agentId === BUILTIN_AGENT_NORMAL_ID || agentId === BUILTIN_AGENT_AGENT_ID; +} diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts index 4b0ae712..f7dd5628 100644 --- a/frontend/src/api/chat/streame.ts +++ b/frontend/src/api/chat/streame.ts @@ -28,7 +28,7 @@ export function useStream() { let renderTimer: number | null = null // 启动流式请求 - const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => { + const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => { // 重置状态 output.value = ''; error.value = null; @@ -89,6 +89,10 @@ export function useStream() { if (params.knowledge_ids !== undefined && params.knowledge_ids.length > 0) { postBody.knowledge_ids = params.knowledge_ids; } + // Include agent_id if provided (for custom agent configuration) + if (params.agent_id) { + postBody.agent_id = params.agent_id; + } // Include web_search_enabled if provided if (params.web_search_enabled !== undefined) { postBody.web_search_enabled = params.web_search_enabled; diff --git a/frontend/src/assets/img/agent-green.svg b/frontend/src/assets/img/agent-green.svg new file mode 100644 index 00000000..96b5b46c --- /dev/null +++ b/frontend/src/assets/img/agent-green.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/assets/img/agent.svg b/frontend/src/assets/img/agent.svg index 458f55da..3b94a604 100644 --- a/frontend/src/assets/img/agent.svg +++ b/frontend/src/assets/img/agent.svg @@ -1,5 +1,5 @@ - - - - \ No newline at end of file + + + + diff --git a/frontend/src/components/AgentAvatar.vue b/frontend/src/components/AgentAvatar.vue new file mode 100644 index 00000000..570e5181 --- /dev/null +++ b/frontend/src/components/AgentAvatar.vue @@ -0,0 +1,155 @@ + + + + + diff --git a/frontend/src/components/AgentSelector.vue b/frontend/src/components/AgentSelector.vue new file mode 100644 index 00000000..e8d6701f --- /dev/null +++ b/frontend/src/components/AgentSelector.vue @@ -0,0 +1,430 @@ + + + + + diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 28077bac..8499351c 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -9,8 +9,10 @@ import { listKnowledgeBases, searchKnowledge, batchQueryKnowledge } from '@/api/ import { stopSession } from '@/api/chat'; import KnowledgeBaseSelector from './KnowledgeBaseSelector.vue'; import MentionSelector from './MentionSelector.vue'; +import AgentSelector from './AgentSelector.vue'; import { getCaretCoordinates } from '@/utils/caret'; import { listModels, type ModelConfig } from '@/api/model'; +import { listAgents, type CustomAgent } from '@/api/agent'; import { getTenantWebSearchConfig } from '@/api/web-search'; import { getConversationConfig, updateConversationConfig, type ConversationConfig } from '@/api/system'; import { useI18n } from 'vue-i18n'; @@ -26,6 +28,81 @@ const showAgentModeSelector = ref(false); const agentModeButtonRef = ref(); const agentModeDropdownStyle = ref>({}); +// 智能体相关状态 +const agents = ref([]); +const selectedAgentId = computed({ + get: () => settingsStore.selectedAgentId || 'builtin-normal', + set: (val: string) => settingsStore.selectAgent(val) +}); +const selectedAgent = computed(() => { + return agents.value.find(a => a.id === selectedAgentId.value) || { + id: 'builtin-normal', + name: t('input.normalMode'), + type: 'normal', + is_builtin: true + } as CustomAgent; +}); + +// 判断是否为自定义智能体(非内置) +const isCustomAgent = computed(() => { + const agent = selectedAgent.value; + return agent && !agent.is_builtin && agent.type === 'custom'; +}); + +// 智能体预配置的知识库 IDs +const agentKnowledgeBases = computed(() => { + if (!isCustomAgent.value) return []; + return selectedAgent.value?.config?.knowledge_bases || []; +}); + +// 智能体是否启用了网络搜索 +const agentWebSearchEnabled = computed(() => { + if (!isCustomAgent.value) return null; // null 表示不受智能体控制 + return selectedAgent.value?.config?.web_search_enabled ?? false; +}); + +// 网络搜索是否被智能体禁用(只读状态) +const isWebSearchDisabledByAgent = computed(() => { + return isCustomAgent.value && agentWebSearchEnabled.value === false; +}); + +// 网络搜索是否被智能体强制启用 +const isWebSearchForcedByAgent = computed(() => { + return isCustomAgent.value && agentWebSearchEnabled.value === true; +}); + +// 知识库选择是否被智能体锁定 +// 1. 如果智能体配置了知识库 → 锁定到这些知识库 +// 2. 如果智能体没配置知识库,但 allow_user_kb_selection=false → 禁用知识库选择 +const isKnowledgeBaseLockedByAgent = computed(() => { + if (!isCustomAgent.value) return false; + // 有预配置知识库时,锁定到这些知识库 + if (agentKnowledgeBases.value.length > 0) return true; + // 没有预配置知识库,但禁止用户选择 + const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection; + // 默认为 true(允许用户选择),只有明确设置为 false 时才禁用 + return allowUserKBSelection === false; +}); + +// 知识库是否被智能体完全禁用(没有预配置且不允许用户选择) +const isKnowledgeBaseDisabledByAgent = computed(() => { + if (!isCustomAgent.value) return false; + if (agentKnowledgeBases.value.length > 0) return false; // 有预配置的不算禁用 + const allowUserKBSelection = selectedAgent.value?.config?.allow_user_kb_selection; + return allowUserKBSelection === false; +}); + +// 智能体配置的模型 ID +const agentModelId = computed(() => { + if (!isCustomAgent.value) return null; + return selectedAgent.value?.config?.model_id || null; +}); + +// 模型选择是否被智能体锁定 +const isModelLockedByAgent = computed(() => { + return isCustomAgent.value && !!agentModelId.value; +}); + // Mention related state const showMention = ref(false); const mentionQuery = ref(""); @@ -80,21 +157,49 @@ const selectedFiles = computed(() => { }); // 合并所有选中项(用于输入框内显示) + // 包括用户选择的和智能体预配置的知识库 const allSelectedItems = computed(() => { - const kbs = selectedKbs.value.map(kb => ({ - ...kb, - type: 'kb' as const, - kbType: kb.type // 保留原始类型用于显示区分 - })); + // 获取智能体预配置的知识库 IDs + const agentKbIds = agentKnowledgeBases.value; + + // 用户选择的知识库(排除智能体已配置的) + const userSelectedKbs = selectedKbs.value + .filter(kb => !agentKbIds.includes(kb.id)) + .map(kb => ({ + ...kb, + type: 'kb' as const, + kbType: kb.type, + isAgentConfigured: false + })); + + // 智能体预配置的知识库 + const agentConfiguredKbs = knowledgeBases.value + .filter(kb => agentKbIds.includes(kb.id)) + .map(kb => ({ + ...kb, + type: 'kb' as const, + kbType: kb.type, + isAgentConfigured: true // 标记为智能体配置,不可删除 + })); + + // 用户选择的文件 const files = selectedFiles.value.map((f: { id: string; name: string }) => ({ ...f, - type: 'file' as const + type: 'file' as const, + isAgentConfigured: false })); - return [...kbs, ...files]; + + // 智能体配置的放在前面 + return [...agentConfiguredKbs, ...userSelectedKbs, ...files]; }); -// 移除选中项 -const removeSelectedItem = (item: { id: string; type: 'kb' | 'file' }) => { +// 移除选中项(智能体配置的项不可移除) +const removeSelectedItem = (item: { id: string; type: 'kb' | 'file'; isAgentConfigured?: boolean }) => { + // 如果是智能体配置的,不允许删除 + if (item.isAgentConfigured) { + MessagePlugin.warning(t('input.cannotRemoveAgentKb')); + return; + } if (item.type === 'kb') { settingsStore.removeKnowledgeBase(item.id); } else { @@ -123,6 +228,15 @@ const remainingCount = computed(() => Math.max(0, selectedKbs.value.length - 2)) // 根据不同状态组合计算输入框的 placeholder const inputPlaceholder = computed(() => { + // 如果选择了自定义智能体 + if (isCustomAgent.value && selectedAgent.value) { + // 有描述时显示描述,否则显示"向 [名称] 提问" + if (selectedAgent.value.description) { + return selectedAgent.value.description; + } + return t('input.placeholderAgent', { name: selectedAgent.value.name }); + } + const hasKnowledge = allSelectedItems.value.length > 0; const hasWebSearch = isWebSearchEnabled.value && isWebSearchConfigured.value; @@ -211,6 +325,16 @@ const loadWebSearchConfig = async () => { } }; +// 加载智能体列表 +const loadAgents = async () => { + try { + const response = await listAgents(); + agents.value = response.data || []; + } catch (error) { + console.error('Failed to load agents:', error); + } +}; + const loadConversationConfig = async () => { try { const response = await getConversationConfig(); @@ -619,6 +743,13 @@ const onCompositionEnd = (e: CompositionEvent) => { }; const triggerMention = () => { + // 如果智能体锁定或禁用了知识库,不允许打开选择器 + if (isKnowledgeBaseLockedByAgent.value) { + const msgKey = isKnowledgeBaseDisabledByAgent.value ? 'input.kbDisabledByAgent' : 'input.kbLockedByAgent'; + MessagePlugin.warning(t(msgKey)); + return; + } + const textarea = getTextareaEl(); if (!textarea) return; @@ -712,6 +843,12 @@ const removeFile = (id: string) => { }; const toggleModelSelector = () => { + // 如果智能体锁定了模型,不允许打开选择器 + if (isModelLockedByAgent.value) { + MessagePlugin.warning(t('input.modelLockedByAgent')); + return; + } + // 互斥:关闭其他 showMention.value = false; showAgentModeSelector.value = false; @@ -761,6 +898,7 @@ onMounted(() => { loadWebSearchConfig(); loadConversationConfig(); loadChatModels(); + loadAgents(); // 如果从知识库内部进入,自动选中该知识库 const kbId = (route.params as any)?.kbId as string; @@ -931,18 +1069,14 @@ const updateAgentModeDropdownPosition = () => { }; const toggleAgentModeSelector = () => { - // 如果 Agent 未就绪,显示提示 - if (!settingsStore.isAgentReady && !isAgentEnabled.value) { - toggleAgentMode(); - return; - } - // 互斥 showMention.value = false; showModelSelector.value = false; showAgentModeSelector.value = !showAgentModeSelector.value; if (showAgentModeSelector.value) { + // 重新加载智能体列表 + loadAgents(); // 多次更新位置确保准确 nextTick(() => { updateAgentModeDropdownPosition(); @@ -966,11 +1100,51 @@ const selectAgentMode = (mode: 'normal' | 'agent') => { const shouldEnableAgent = mode === 'agent'; if (shouldEnableAgent !== isAgentEnabled.value) { settingsStore.toggleAgent(shouldEnableAgent); + // 同时更新选中的智能体 + settingsStore.selectAgent(shouldEnableAgent ? 'builtin-agent' : 'builtin-normal'); MessagePlugin.success(shouldEnableAgent ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff')); } showAgentModeSelector.value = false; } +// 选择智能体(新版) +const handleSelectAgent = (agent: CustomAgent) => { + selectedAgentId.value = agent.id; + + // 根据智能体类型切换 Agent 模式 + const isAgentType = agent.type === 'agent' || (agent.type === 'custom' && (agent.config?.max_iterations ?? 0) > 1); + + if (isAgentType && !settingsStore.isAgentReady) { + // Agent 模式未就绪,显示提示 + toggleAgentMode(); + return; + } + + settingsStore.toggleAgent(!!isAgentType); + + // 如果是自定义智能体,同步网络搜索状态和模型 + if (!agent.is_builtin && agent.type === 'custom') { + const agentWebSearch = agent.config?.web_search_enabled; + if (agentWebSearch !== undefined) { + // 智能体配置了网络搜索设置,同步到 store + settingsStore.toggleWebSearch(agentWebSearch); + } + + // 如果智能体配置了模型,同步到 store + const agentModel = agent.config?.model_id; + if (agentModel) { + selectedModelId.value = agentModel; + } + } + + showAgentModeSelector.value = false; + + const message = agent.is_builtin + ? (isAgentType ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff')) + : t('input.messages.agentSelected', { name: agent.name }); + MessagePlugin.success(message); +} + const clearvalue = () => { query.value = ""; } @@ -1107,6 +1281,18 @@ const toggleWebSearch = () => { showModelSelector.value = false; showAgentModeSelector.value = false; + // 如果智能体禁用了网络搜索,不允许开启 + if (isWebSearchDisabledByAgent.value) { + MessagePlugin.warning(t('input.webSearchDisabledByAgent')); + return; + } + + // 如果智能体强制启用了网络搜索,不允许关闭 + if (isWebSearchForcedByAgent.value) { + MessagePlugin.warning(t('input.webSearchForcedByAgent')); + return; + } + if (!isWebSearchConfigured.value) { const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 6px; max-width: 280px;' }, [ h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.messages.webSearchNotConfigured')), @@ -1182,14 +1368,15 @@ onBeforeRouteUpdate((to, from, next) => {
- +
@@ -1197,7 +1384,8 @@ onBeforeRouteUpdate((to, from, next) => { {{ item.name }} - × + + ×
@@ -1243,28 +1431,8 @@ onBeforeRouteUpdate((to, from, next) => { }" @click.stop="toggleAgentModeSelector" > - - - - - {{ isAgentEnabled ? $t('input.agentMode') : $t('input.normalMode') }} + {{ selectedAgent.name || (isAgentEnabled ? $t('input.agentMode') : $t('input.normalMode')) }} {
- - -
-
-
-
- {{ $t('input.normalMode') }} - {{ $t('input.normalModeDesc') }} -
- - - -
-
-
- {{ $t('input.agentMode') }} - {{ $t('input.agentModeDesc') }} -
- - - -
- - - -
-
- -
-
-
+ +
{ fill="none" xmlns="http://www.w3.org/2000/svg" class="control-icon websearch-icon" - :class="{ 'active': isWebSearchEnabled && isWebSearchConfigured }" + :class="{ 'active': (isWebSearchEnabled && isWebSearchConfigured) || isWebSearchForcedByAgent }" > @@ -1380,11 +1494,14 @@ onBeforeRouteUpdate((to, from, next) => { - +
@@ -1394,27 +1511,29 @@ onBeforeRouteUpdate((to, from, next) => { -
-
- - {{ selectedModel?.name || $t('input.notConfigured') }} - - +
+
- - + + {{ selectedModel?.name || $t('input.notConfigured') }} + + + + +
-
+
@@ -1609,6 +1728,12 @@ const getImgSrc = (url: string) => { background: rgba(0, 0, 0, 0.1); } } + + // 智能体配置的标签样式(用虚线边框区分,不显示锁图标) + &.agent-configured { + border-style: dashed; + opacity: 0.9; + } } :deep(.t-textarea__inner) { @@ -1788,6 +1913,19 @@ const getImgSrc = (url: string) => { background: rgba(16, 185, 129, 0.15); } } + + &.agent-controlled { + cursor: not-allowed; + opacity: 0.85; + + &:hover { + background: var(--td-bg-color-secondarycontainer, #f5f5f5); + } + + &.active:hover { + background: rgba(16, 185, 129, 0.1); + } + } } .kb-count { @@ -1826,6 +1964,7 @@ const getImgSrc = (url: string) => { display: flex; align-items: center; justify-content: center; + position: relative; &.active { background: rgba(16, 185, 129, 0.1); @@ -1852,6 +1991,19 @@ const getImgSrc = (url: string) => { } } } + + &.agent-controlled { + cursor: not-allowed; + opacity: 0.85; + + &:hover { + background: var(--td-bg-color-secondarycontainer, #f5f5f5); + } + + &.active:hover { + background: rgba(16, 185, 129, 0.1); + } + } } :global(.websearch-tooltip-disabled) { @@ -1956,6 +2108,18 @@ const getImgSrc = (url: string) => { align-items: center; margin-left: auto; flex-shrink: 0; + + &.agent-controlled { + .model-selector-trigger { + cursor: not-allowed; + opacity: 0.85; + + &:hover { + background: rgba(16, 185, 129, 0.1); + border-color: rgba(16, 185, 129, 0.3); + } + } + } } .model-selector-trigger { @@ -2040,12 +2204,12 @@ const getImgSrc = (url: string) => { display: flex; align-items: center; justify-content: space-between; - padding: 8px 10px; - border-bottom: 1px solid var(--td-component-border, #f2f4f5); - background: var(--td-bg-color-secondarycontainer, #fafcfc); + padding: 8px 12px; + border-bottom: 1px solid var(--td-component-stroke, #f0f0f0); + background: var(--td-bg-color-container, #fff); font-size: 12px; - font-weight: 600; - color: var(--td-text-color-primary, #222); + font-weight: 500; + color: var(--td-text-color-secondary, #666); } .model-selector-content { @@ -2061,26 +2225,26 @@ const getImgSrc = (url: string) => { display: inline-flex; align-items: center; gap: 4px; - padding: 3px 8px; - border-radius: 6px; - border: 1px solid var(--td-component-border, #e1e5e6); - background: var(--td-bg-color-container, #fff); - color: var(--td-text-color-secondary, #52575a); - font-size: 11px; + padding: 2px 8px; + border-radius: 4px; + border: 1px solid transparent; + background: transparent; + color: var(--td-brand-color, #07c05f); + font-size: 12px; font-weight: 500; cursor: pointer; - transition: all 0.12s; -} - -.model-selector-add .add-icon { - font-size: 12px; - line-height: 1; -} - -.model-selector-add:hover { - border-color: #10b981; - color: #10b981; - background: #f0fdf6; + transition: all 0.2s; + + .add-icon { + font-size: 14px; + line-height: 1; + font-weight: 400; + } + + &:hover { + color: var(--td-brand-color-hover, #05a04f); + background: var(--td-bg-color-secondarycontainer, #f3f3f3); + } } .model-option { diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index c6e7ad24..da2c6057 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -24,6 +24,18 @@
+ -
- - {{ $t('agent.builtin') }} + +
+
@@ -178,13 +182,11 @@ const fetchList = () => { loading.value = true return listAgents().then((res: any) => { const data = res.data || [] - // 过滤掉内置智能体,只展示自定义智能体 - agents.value = data - .filter((agent: CustomAgent) => !agent.is_builtin) - .map((agent: CustomAgent) => ({ - ...agent, - showMore: false - })) + // 显示所有智能体(包括内置智能体) + agents.value = data.map((agent: CustomAgent) => ({ + ...agent, + showMore: false + })) }).finally(() => loading.value = false) } @@ -215,13 +217,8 @@ const handleCardClick = (agent: AgentWithUI) => { if (agent.showMore) { return } - // 点击卡片查看详情或编辑 - if (agent.is_builtin) { - // 内置智能体只能查看 - MessagePlugin.info(t('agent.messages.builtinReadonly')) - } else { - handleEdit(agent) - } + // 点击卡片编辑(包括内置智能体) + handleEdit(agent) } const handleEdit = (agent: AgentWithUI) => { @@ -456,6 +453,25 @@ defineExpose({ font-family: "PingFang SC"; font-size: 12px; font-weight: 400; + flex-shrink: 0; +} + +.edit-btn { + display: flex; + width: 32px; + height: 32px; + justify-content: center; + align-items: center; + border-radius: 6px; + cursor: pointer; + flex-shrink: 0; + transition: all 0.2s ease; + color: #00000066; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: #07c05f; + } } .more-wrap { diff --git a/frontend/src/views/settings/AgentSettings.vue b/frontend/src/views/settings/AgentSettings.vue index 2164da69..86cc9af7 100644 --- a/frontend/src/views/settings/AgentSettings.vue +++ b/frontend/src/views/settings/AgentSettings.vue @@ -4,6 +4,10 @@

{{ $t('settings.conversationStrategy') }}

{{ $t('conversationSettings.description') }}

+
+ + 这些是全局默认配置,新建智能体时会继承这些设置。您也可以在智能体列表中单独配置每个智能体。 +
@@ -146,17 +150,7 @@
-
- {{ $t('agentSettings.systemPrompt.custom') }} - -

- {{ $t('agentSettings.systemPrompt.tabHint') }} + {{ $t('agentSettings.systemPrompt.tabHint') }}(留空则使用系统默认)

-

- {{ $t('agentSettings.systemPrompt.disabledHint') }} -

-
+
-
+
+
-
+
+
@@ -214,7 +213,7 @@
@@ -249,24 +248,10 @@
-

{{ $t('conversationSettings.systemPrompt.desc') }}

+

{{ $t('conversationSettings.systemPrompt.desc') }}(留空则使用系统默认)

-
-
- {{ $t('conversationSettings.systemPrompt.custom') }} - -
-
-

- {{ $t('conversationSettings.systemPrompt.disabledHint') }} -

-
+
+
- +
-

{{ $t('conversationSettings.contextTemplate.desc') }}

+

{{ $t('conversationSettings.contextTemplate.desc') }}(留空则使用系统默认)

-
-
- {{ $t('conversationSettings.contextTemplate.custom') }} - -
-
-

- {{ $t('conversationSettings.contextTemplate.disabledHint') }} -

-
+
+
@@ -540,11 +523,18 @@

{{ $t('conversationSettings.rewritePrompt.desc') }}

- +
+ + +
@@ -554,11 +544,18 @@

{{ $t('conversationSettings.rewritePrompt.userDesc') }}

- +
+ + +
@@ -583,26 +580,40 @@

{{ $t('conversationSettings.fallbackResponse.desc') }}

- +
+ + +
- +

{{ $t('conversationSettings.fallbackPrompt.desc') }}

- +
+ + +
@@ -659,6 +670,7 @@ import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next' import { useI18n } from 'vue-i18n' import { listModels, type ModelConfig } from '@/api/model' import { getAgentConfig, updateAgentConfig, getConversationConfig, updateConversationConfig, type AgentConfig, type ConversationConfig, type ToolDefinition, type PlaceholderDefinition } from '@/api/system' +import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue' const props = defineProps<{ // 来自外部设置弹窗的子菜单 key: 'modes' | 'models' | 'thresholds' | 'advanced' @@ -680,8 +692,6 @@ const getDefaultConversationConfig = (): ConversationConfig => ({ context_template: '', temperature: 0.3, max_completion_tokens: 2048, - use_custom_system_prompt: true, - use_custom_context_template: true, max_rounds: 5, embedding_top_k: 10, keyword_threshold: 0.3, @@ -727,7 +737,6 @@ const savedSystemPromptMap: Record = { } const getPromptRefByTab = (tab: SystemPromptTab) => systemPromptRefs[tab] const getActivePromptRef = () => getPromptRefByTab(activeSystemPromptTab.value) -const localUseCustomSystemPrompt = ref(false) // 普通模式本地状态 const localContextTemplate = ref('') @@ -755,10 +764,6 @@ const localRewritePromptUser = ref('') const localSummaryModelId = ref('') const localConversationRerankModelId = ref('') -// 普通模式 Prompt 是否自定义(关闭时使用系统默认) -const localUseCustomSystemPromptNormal = ref(true) -const localUseCustomContextTemplate = ref(true) - const syncConversationLocals = () => { const cfg = conversationConfig.value localContextTemplate.value = cfg.context_template ?? '' @@ -785,8 +790,6 @@ const syncConversationLocals = () => { localRewritePromptUser.value = cfg.rewrite_prompt_user ?? '' localSummaryModelId.value = cfg.summary_model_id ?? '' localConversationRerankModelId.value = cfg.rerank_model_id ?? '' - localUseCustomSystemPromptNormal.value = cfg.use_custom_system_prompt ?? true - localUseCustomContextTemplate.value = cfg.use_custom_context_template ?? true settingsStore.updateConversationModels({ summaryModelId: localSummaryModelId.value || '', @@ -837,7 +840,6 @@ const buildAgentConfigPayload = (overrides: Partial = {}): AgentCon temperature: localTemperature.value, system_prompt_web_enabled: localSystemPromptWebEnabled.value, system_prompt_web_disabled: localSystemPromptWebDisabled.value, - use_custom_system_prompt: localUseCustomSystemPrompt.value, ...overrides, }) @@ -916,9 +918,6 @@ const loadingConfig = ref(false) const configLoaded = ref(false) // 防止重复加载 const isInitializing = ref(true) // 标记是否正在初始化,防止初始化时触发保存 -// 保存的 Prompt 值,用于比较是否变化 -let savedUseCustomSystemPrompt = false - // 恢复默认 Prompt 的加载状态 const isResettingPrompt = ref(false) @@ -1055,9 +1054,6 @@ onMounted(async () => { localSystemPromptWebDisabled.value = promptWebDisabled savedSystemPromptMap['web-enabled'] = promptWebEnabled savedSystemPromptMap['web-disabled'] = promptWebDisabled - const useCustomPrompt = config.use_custom_system_prompt ?? false - localUseCustomSystemPrompt.value = useCustomPrompt - savedUseCustomSystemPrompt = useCustomPrompt availableTools.value = config.available_tools || [] availablePlaceholders.value = config.available_placeholders || [] @@ -1076,7 +1072,6 @@ onMounted(async () => { allowedTools: config.allowed_tools || [], system_prompt_web_enabled: promptWebEnabled, system_prompt_web_disabled: promptWebDisabled, - use_custom_system_prompt: useCustomPrompt }) // 加载普通模式配置 @@ -1232,25 +1227,6 @@ const handleTemperatureChange = async (value: number) => { } } -// 切换是否启用自定义 Prompt -const handleUseCustomPromptToggle = async (value: boolean) => { - if (isInitializing.value) return - if (value === savedUseCustomSystemPrompt) return - - try { - const config = buildAgentConfigPayload({ use_custom_system_prompt: value }) - await updateAgentConfig(config) - savedUseCustomSystemPrompt = value - - MessagePlugin.success(value ? t('agentSettings.toasts.customPromptEnabled') : t('agentSettings.toasts.defaultPromptEnabled')) - } catch (error) { - console.error('切换自定义 Prompt 失败:', error) - MessagePlugin.error(getErrorMessage(error)) - // 回滚开关状态 - localUseCustomSystemPrompt.value = savedUseCustomSystemPrompt - } -} - // 处理系统 Prompt 键盘事件(作为备用,主要逻辑在原生事件监听器中) const handlePromptKeydown = (e: KeyboardEvent) => { // 如果正在显示占位符提示,且输入的是字母、数字或下划线,实时更新过滤 @@ -1461,7 +1437,6 @@ const handleResetToDefault = async () => { const tempConfig = buildAgentConfigPayload({ system_prompt_web_enabled: '', system_prompt_web_disabled: '', - use_custom_system_prompt: false, }) await updateAgentConfig(tempConfig) @@ -1470,15 +1445,12 @@ const handleResetToDefault = async () => { const res = await getAgentConfig() const defaultPromptWebEnabled = res.data.system_prompt_web_enabled || '' const defaultPromptWebDisabled = res.data.system_prompt_web_disabled || '' - const useCustom = res.data.use_custom_system_prompt ?? false // 设置为默认 Prompt 的内容 localSystemPromptWebEnabled.value = defaultPromptWebEnabled localSystemPromptWebDisabled.value = defaultPromptWebDisabled savedSystemPromptMap['web-enabled'] = defaultPromptWebEnabled savedSystemPromptMap['web-disabled'] = defaultPromptWebDisabled - localUseCustomSystemPrompt.value = useCustom - savedUseCustomSystemPrompt = useCustom MessagePlugin.success(t('agentSettings.toasts.resetToDefault')) confirmDialog.hide() @@ -1559,7 +1531,6 @@ const handleContextTemplateChange = async () => { await saveConversationConfig( { context_template: localContextTemplate.value, - use_custom_context_template: localUseCustomContextTemplate.value, }, t('conversationSettings.toasts.contextTemplateSaved') ) @@ -1576,66 +1547,6 @@ const reloadConversationConfig = async () => { syncConversationLocals() } -const handleUseCustomSystemPromptNormalToggle = async (value: boolean) => { - if (!conversationConfigLoaded.value) return - - try { - if (!value) { - await saveConversationConfig( - { - prompt: '', - use_custom_system_prompt: false, - }, - t('conversationSettings.toasts.defaultPromptEnabled') - ) - await reloadConversationConfig() - } else { - await saveConversationConfig( - { - prompt: localSystemPromptNormal.value, - use_custom_system_prompt: true, - }, - t('conversationSettings.toasts.customPromptEnabled') - ) - savedSystemPromptNormal = localSystemPromptNormal.value - } - } catch (error) { - console.error('切换普通模式 System Prompt 自定义失败:', error) - MessagePlugin.error(getErrorMessage(error)) - localUseCustomSystemPromptNormal.value = !value - } -} - -const handleUseCustomContextTemplateToggle = async (value: boolean) => { - if (!conversationConfigLoaded.value) return - - try { - if (!value) { - await saveConversationConfig( - { - context_template: '', - use_custom_context_template: false, - }, - t('conversationSettings.toasts.defaultContextTemplateEnabled') - ) - await reloadConversationConfig() - } else { - await saveConversationConfig( - { - context_template: localContextTemplate.value, - use_custom_context_template: true, - }, - t('conversationSettings.toasts.customContextTemplateEnabled') - ) - savedContextTemplate = localContextTemplate.value - } - } catch (error) { - console.error('切换普通模式 Context Template 自定义失败:', error) - MessagePlugin.error(getErrorMessage(error)) - localUseCustomContextTemplate.value = !value - } -} - const handleSystemPromptNormalChange = async () => { if (!conversationConfigLoaded.value) return @@ -1647,7 +1558,6 @@ const handleSystemPromptNormalChange = async () => { await saveConversationConfig( { prompt: localSystemPromptNormal.value, - use_custom_system_prompt: localUseCustomSystemPromptNormal.value, }, t('conversationSettings.toasts.systemPromptSaved') ) @@ -1813,6 +1723,39 @@ const handleFallbackPromptChange = async () => { } } +// 模板选择处理函数 +const handleAgentSystemPromptTemplateSelect = (template: string) => { + if (activeSystemPromptTab.value === 'web-enabled') { + localSystemPromptWebEnabled.value = template + } else { + localSystemPromptWebDisabled.value = template + } +} + +const handleNormalSystemPromptTemplateSelect = (template: string) => { + localSystemPromptNormal.value = template +} + +const handleContextTemplateTemplateSelect = (template: string) => { + localContextTemplate.value = template +} + +const handleRewriteSystemTemplateSelect = (template: string) => { + localRewritePromptSystem.value = template +} + +const handleRewriteUserTemplateSelect = (template: string) => { + localRewritePromptUser.value = template +} + +const handleFallbackResponseTemplateSelect = (template: string) => { + localFallbackResponse.value = template +} + +const handleFallbackPromptTemplateSelect = (template: string) => { + localFallbackPrompt.value = template +} + const navigateToModelSettings = (subsection: 'chat' | 'rerank') => { router.push('/platform/settings') @@ -1881,9 +1824,29 @@ const handleConversationRerankModelChange = async (value: string) => { .section-description { font-size: 14px; color: #666666; - margin: 0 0 20px 0; + margin: 0 0 12px 0; line-height: 1.5; } + + .global-config-notice { + display: flex; + align-items: flex-start; + gap: 8px; + padding: 12px 16px; + background: #f0f9ff; + border: 1px solid #bae0ff; + border-radius: 8px; + margin-bottom: 20px; + color: #0958d9; + font-size: 13px; + line-height: 1.5; + + .t-icon { + font-size: 16px; + flex-shrink: 0; + margin-top: 2px; + } + } } .agent-status-row { @@ -2056,6 +2019,17 @@ const handleConversationRerankModelChange = async (value: string) => { word-break: keep-all; white-space: normal; + .setting-info-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 4px; + + label { + margin-bottom: 0; + } + } + label { font-size: 15px; font-weight: 500; @@ -2263,6 +2237,11 @@ const handleConversationRerankModelChange = async (value: string) => { width: 100%; } +.textarea-with-template { + position: relative; + width: 100%; +} + .setting-control.full-width { display: flex; flex-direction: column; diff --git a/internal/application/repository/custom_agent.go b/internal/application/repository/custom_agent.go index 70a10612..5a8a339f 100644 --- a/internal/application/repository/custom_agent.go +++ b/internal/application/repository/custom_agent.go @@ -27,10 +27,10 @@ func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.Cu return r.db.WithContext(ctx).Create(agent).Error } -// GetAgentByID gets an agent by id -func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) { +// GetAgentByID gets an agent by id and tenant +func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) { var agent types.CustomAgent - if err := r.db.WithContext(ctx).Where("id = ?", id).First(&agent).Error; err != nil { + if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&agent).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrCustomAgentNotFound } diff --git a/internal/application/service/chat_pipline/common.go b/internal/application/service/chat_pipline/common.go index cf28ff6a..dcda8d30 100644 --- a/internal/application/service/chat_pipline/common.go +++ b/internal/application/service/chat_pipline/common.go @@ -2,6 +2,8 @@ package chatpipline import ( "context" + "strings" + "time" "github.com/Tencent/WeKnora/internal/common" "github.com/Tencent/WeKnora/internal/logger" @@ -51,8 +53,11 @@ func prepareChatModel(ctx context.Context, modelService interfaces.ModelService, // prepareMessagesWithHistory prepare complete messages including history func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message { + // Replace placeholders in system prompt + systemPrompt := renderSystemPromptPlaceholders(chatManage.SummaryConfig.Prompt) + chatMessages := []chat.Message{ - {Role: "system", Content: chatManage.SummaryConfig.Prompt}, + {Role: "system", Content: systemPrompt}, } chatHistory := chatManage.History @@ -71,3 +76,18 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message { return chatMessages } + +// renderSystemPromptPlaceholders replaces placeholders in system prompt +// Supported placeholders: +// - {{current_time}} -> current time in RFC3339 format +func renderSystemPromptPlaceholders(prompt string) string { + result := prompt + + // Replace {{current_time}} placeholder + if strings.Contains(result, "{{current_time}}") { + currentTime := time.Now().Format(time.RFC3339) + result = strings.ReplaceAll(result, "{{current_time}}", currentTime) + } + + return result +} diff --git a/internal/application/service/chat_pipline/into_chat_message.go b/internal/application/service/chat_pipline/into_chat_message.go index 4193345f..73d92b1e 100644 --- a/internal/application/service/chat_pipline/into_chat_message.go +++ b/internal/application/service/chat_pipline/into_chat_message.go @@ -1,11 +1,9 @@ package chatpipline import ( - "bytes" "context" "encoding/json" "fmt" - "html/template" "regexp" "strings" "time" @@ -46,20 +44,6 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context, passages[i] = getEnrichedPassageForChat(ctx, result) } - // Parse the context template - tmpl, err := template.New("searchContent").Parse(chatManage.SummaryConfig.ContextTemplate) - if err != nil { - pipelineError(ctx, "IntoChatMessage", "parse_template", map[string]interface{}{ - "session_id": chatManage.SessionID, - "error": err.Error(), - }) - return ErrTemplateParse.WithError(err) - } - - // Prepare weekday names for template - weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"} - var userContent bytes.Buffer - // 验证用户查询的安全性 safeQuery, isValid := secutils.ValidateInput(chatManage.Query) if !isValid { @@ -69,23 +53,27 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context, return ErrTemplateExecute.WithError(fmt.Errorf("用户查询包含非法内容")) } - // Execute template with context data - err = tmpl.Execute(&userContent, map[string]interface{}{ - "Query": safeQuery, // User's original query - "Contexts": passages, // Extracted passages from search results - "CurrentTime": time.Now().Format("2006-01-02 15:04:05"), // Formatted current time - "CurrentWeek": weekdayName[time.Now().Weekday()], // Current weekday in Chinese - }) - if err != nil { - pipelineError(ctx, "IntoChatMessage", "render_template", map[string]interface{}{ - "session_id": chatManage.SessionID, - "error": err.Error(), - }) - return ErrTemplateExecute.WithError(err) + // Prepare weekday names + weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"} + + // Build contexts string from passages + var contextsBuilder strings.Builder + for i, passage := range passages { + if i > 0 { + contextsBuilder.WriteString("\n\n") + } + contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage)) } + // Replace placeholders in context template + userContent := chatManage.SummaryConfig.ContextTemplate + userContent = strings.ReplaceAll(userContent, "{{query}}", safeQuery) + userContent = strings.ReplaceAll(userContent, "{{contexts}}", contextsBuilder.String()) + userContent = strings.ReplaceAll(userContent, "{{current_time}}", time.Now().Format("2006-01-02 15:04:05")) + userContent = strings.ReplaceAll(userContent, "{{current_week}}", weekdayName[time.Now().Weekday()]) + // Set formatted content back to chat management - chatManage.UserContent = userContent.String() + chatManage.UserContent = userContent pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{ "session_id": chatManage.SessionID, "user_content_len": len(chatManage.UserContent), diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index c4ad9c6e..f375037c 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -16,7 +16,7 @@ import ( // Custom agent related errors var ( ErrAgentNotFound = errors.New("agent not found") - ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent") + ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent basic info") ErrCannotDeleteBuiltin = errors.New("cannot delete built-in agent") ErrAgentNameRequired = errors.New("agent name is required") ) @@ -96,15 +96,22 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type } // Check if it's a built-in agent - if id == types.BuiltinAgentNormalID { - return types.GetBuiltinNormalAgent(tenantID), nil - } - if id == types.BuiltinAgentAgentID { + if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID { + // 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 + } return types.GetBuiltinAgentAgent(tenantID), nil } // Query from database - agent, err := s.repo.GetAgentByID(ctx, id) + agent, err := s.repo.GetAgentByID(ctx, id, tenantID) if err != nil { if errors.Is(err, repository.ErrCustomAgentNotFound) { return nil, ErrAgentNotFound @@ -115,11 +122,6 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type return nil, err } - // Verify tenant ownership - if agent.TenantID != tenantID { - return nil, ErrAgentNotFound - } - return agent, nil } @@ -130,11 +132,8 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge return nil, ErrInvalidTenantID } - // Get built-in agents first - builtinAgents := types.GetBuiltinAgents(tenantID) - - // Get custom agents from database - customAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID) + // Get all agents from database (including built-in agents with customized config) + allAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ "tenant_id": tenantID, @@ -142,10 +141,51 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge return nil, err } - // Combine: built-in agents first, then custom agents - result := make([]*types.CustomAgent, 0, len(builtinAgents)+len(customAgents)) - result = append(result, builtinAgents...) - result = append(result, customAgents...) + // Check if built-in agents exist in database + hasNormalBuiltin := false + hasAgentBuiltin := false + for _, agent := range allAgents { + if agent.ID == types.BuiltinAgentNormalID { + hasNormalBuiltin = true + } + if agent.ID == types.BuiltinAgentAgentID { + hasAgentBuiltin = true + } + } + + // Build result: built-in agents first, then custom agents + result := make([]*types.CustomAgent, 0, len(allAgents)+2) + + // Add built-in normal agent + if hasNormalBuiltin { + for _, agent := range allAgents { + if agent.ID == types.BuiltinAgentNormalID { + 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 { + result = append(result, agent) + } + } return result, nil } @@ -157,19 +197,20 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo return nil, errors.New("agent ID cannot be empty") } - // Cannot modify built-in agents - if agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID { - return nil, ErrCannotModifyBuiltin - } - // Get tenant ID from context tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64) if !ok { return nil, ErrInvalidTenantID } + // Handle built-in agents specially + isBuiltinAgent := agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID + if isBuiltinAgent { + return s.updateBuiltinAgent(ctx, agent, tenantID) + } + // Get existing agent - existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID) + existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID) if err != nil { if errors.Is(err, repository.ErrCustomAgentNotFound) { return nil, ErrAgentNotFound @@ -177,11 +218,6 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo return nil, err } - // Verify tenant ownership - if existingAgent.TenantID != tenantID { - return nil, ErrAgentNotFound - } - // Cannot modify built-in status if existingAgent.IsBuiltin { return nil, ErrCannotModifyBuiltin @@ -216,6 +252,70 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo return existingAgent, nil } +// 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) + } + + // Try to get existing customized config from database + existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID) + if err != nil && !errors.Is(err, repository.ErrCustomAgentNotFound) { + return nil, err + } + + if existingAgent != nil { + // Update existing record - only update config, keep basic info unchanged + existingAgent.Config = agent.Config + existingAgent.UpdatedAt = time.Now() + existingAgent.EnsureDefaults() + + logger.Infof(ctx, "Updating built-in agent config, ID: %s", agent.ID) + + if err := s.repo.UpdateAgent(ctx, existingAgent); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": agent.ID, + }) + return nil, err + } + + logger.Infof(ctx, "Built-in agent config updated successfully, ID: %s", agent.ID) + return existingAgent, nil + } + + // Create new record for built-in agent with customized config + newAgent := &types.CustomAgent{ + ID: defaultAgent.ID, + Name: defaultAgent.Name, + Description: defaultAgent.Description, + Avatar: defaultAgent.Avatar, + IsBuiltin: true, + Type: defaultAgent.Type, + TenantID: tenantID, + Config: agent.Config, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + } + newAgent.EnsureDefaults() + + logger.Infof(ctx, "Creating built-in agent config record, ID: %s, tenant ID: %d", agent.ID, tenantID) + + if err := s.repo.CreateAgent(ctx, newAgent); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "agent_id": agent.ID, + "tenant_id": tenantID, + }) + return nil, err + } + + logger.Infof(ctx, "Built-in agent config record created successfully, ID: %s", agent.ID) + return newAgent, nil +} + // DeleteAgent deletes an agent func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error { if id == "" { @@ -235,7 +335,7 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error { } // Get existing agent to verify ownership - existingAgent, err := s.repo.GetAgentByID(ctx, id) + existingAgent, err := s.repo.GetAgentByID(ctx, id, tenantID) if err != nil { if errors.Is(err, repository.ErrCustomAgentNotFound) { return ErrAgentNotFound @@ -243,11 +343,6 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error { return err } - // Verify tenant ownership - if existingAgent.TenantID != tenantID { - return ErrAgentNotFound - } - // Cannot delete built-in agents if existingAgent.IsBuiltin { return ErrCannotDeleteBuiltin diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index fe18c966..9ca706bb 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -3403,47 +3403,6 @@ func (s *knowledgeService) GetFAQEntry(ctx context.Context, return entry, nil } -// GetFAQEntry retrieves a single FAQ entry by ID. -func (s *knowledgeService) GetFAQEntry(ctx context.Context, - kbID string, entryID string, -) (*types.FAQEntry, error) { - if entryID == "" { - return nil, werrors.NewBadRequestError("条目ID不能为空") - } - - kb, err := s.validateFAQKnowledgeBase(ctx, kbID) - if err != nil { - return nil, err - } - kb.EnsureDefaults() - - tenantID := ctx.Value(types.TenantIDContextKey).(uint64) - - // 获取chunk - chunk, err := s.chunkService.GetChunkByID(ctx, entryID) - if err != nil { - return nil, err - } - - // 验证chunk属于当前知识库 - if chunk.KnowledgeBaseID != kb.ID || chunk.TenantID != tenantID { - return nil, werrors.NewNotFoundError("FAQ条目不存在") - } - - // 验证是FAQ类型 - if chunk.ChunkType != types.ChunkTypeFAQ { - return nil, werrors.NewNotFoundError("FAQ条目不存在") - } - - // 转换为FAQEntry返回 - entry, err := s.chunkToFAQEntry(chunk, kb) - if err != nil { - return nil, err - } - - return entry, nil -} - // UpdateFAQEntry updates a single FAQ entry. func (s *knowledgeService) UpdateFAQEntry(ctx context.Context, kbID string, entryID string, payload *types.FAQEntryPayload, @@ -5901,4 +5860,3 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, } return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit) } - diff --git a/internal/application/service/session.go b/internal/application/service/session.go index d27af700..c6386f92 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -87,8 +87,7 @@ func (s *sessionService) CreateSession(ctx context.Context, session *types.Sessi return nil, errors.New("tenant ID is required") } - logger.Infof(ctx, "Creating session, tenant ID: %d, model ID: %s, knowledge base ID: %s", - session.TenantID, session.SummaryModelID, session.KnowledgeBaseID) + logger.Infof(ctx, "Creating session, tenant ID: %d", session.TenantID) // Create session in repository createdSession, err := s.sessionRepo.Create(ctx, session) @@ -259,31 +258,29 @@ func (s *sessionService) GenerateTitle(ctx context.Context, return "", errors.New("no user message found") } - // Get chat model, use default if SummaryModelID is empty - modelID := session.SummaryModelID - if modelID == "" { - // Try to get an available KnowledgeQA model - models, err := s.modelService.ListModels(ctx) - if err != nil { - logger.ErrorWithFields(ctx, err, nil) - return "", fmt.Errorf("failed to list models: %w", err) + // Get chat model, find an available model + modelID := "" + // Try to get an available KnowledgeQA model + models, err := s.modelService.ListModels(ctx) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + return "", fmt.Errorf("failed to list models: %w", err) + } + // Find first available KnowledgeQA model + for _, model := range models { + if model == nil { + continue } - // Find first available KnowledgeQA model - for _, model := range models { - if model == nil { - continue - } if model.Type == types.ModelTypeKnowledgeQA { - modelID = model.ID - logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID) - break - } - } - if modelID == "" { - logger.Error(ctx, "No KnowledgeQA model found") - return "", errors.New("no KnowledgeQA model available for title generation") + modelID = model.ID + logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID) + break } } + if modelID == "" { + logger.Error(ctx, "No KnowledgeQA model found") + return "", errors.New("no KnowledgeQA model available for title generation") + } chatModel, err := s.modelService.GetChatModel(ctx, modelID) if err != nil { @@ -413,16 +410,6 @@ func (s *sessionService) KnowledgeQA( webSearchEnabled, ) - // If no knowledge base IDs provided, fall back to session's default - if len(knowledgeBaseIDs) == 0 { - if session.KnowledgeBaseID != "" { - knowledgeBaseIDs = []string{session.KnowledgeBaseID} - logger.Infof(ctx, "No knowledge base IDs provided, using session default: %s", session.KnowledgeBaseID) - } else { - logger.Warnf(ctx, "Session has no associated knowledge base, session ID: %s", session.ID) - } - } - // Merge custom agent's configured knowledge bases if customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 { // Create a set of existing knowledge base IDs to avoid duplicates @@ -447,83 +434,28 @@ func (s *sessionService) KnowledgeQA( return err } + // Initialize default values from config.yaml rewritePromptSystem := s.cfg.Conversation.RewritePromptSystem rewritePromptUser := s.cfg.Conversation.RewritePromptUser - var tenantConv *types.ConversationConfig - if tc, err := getTenantConversationConfig(ctx); err == nil { - tenantConv = tc - } else { - logger.Warnf(ctx, "Failed to load tenant conversation config, tenant ID: %d, error: %v", session.TenantID, err) - } + vectorThreshold := s.cfg.Conversation.VectorThreshold + keywordThreshold := s.cfg.Conversation.KeywordThreshold + embeddingTopK := s.cfg.Conversation.EmbeddingTopK + rerankTopK := s.cfg.Conversation.RerankTopK + rerankThreshold := s.cfg.Conversation.RerankThreshold + maxRounds := s.cfg.Conversation.MaxRounds + fallbackStrategy := types.FallbackStrategy(s.cfg.Conversation.FallbackStrategy) + fallbackResponse := s.cfg.Conversation.FallbackResponse + fallbackPrompt := s.cfg.Conversation.FallbackPrompt + enableRewrite := s.cfg.Conversation.EnableRewrite + enableQueryExpansion := s.cfg.Conversation.EnableQueryExpansion + rerankModelID := "" - vectorThreshold := session.VectorThreshold - keywordThreshold := session.KeywordThreshold - embeddingTopK := session.EmbeddingTopK - rerankModelID := session.RerankModelID - rerankTopK := session.RerankTopK - rerankThreshold := session.RerankThreshold - maxRounds := session.MaxRounds - fallbackStrategy := session.FallbackStrategy - fallbackResponse := session.FallbackResponse - fallbackPrompt := "" - enableRewrite := session.EnableRewrite - enableQueryExpansion := true - - summaryParams := session.SummaryParameters - if summaryParams == nil { - summaryParams = &types.SummaryConfig{} - } summaryConfig := types.SummaryConfig{ - MaxTokens: summaryParams.MaxTokens, - RepeatPenalty: summaryParams.RepeatPenalty, - TopK: summaryParams.TopK, - TopP: summaryParams.TopP, - FrequencyPenalty: summaryParams.FrequencyPenalty, - PresencePenalty: summaryParams.PresencePenalty, - Prompt: summaryParams.Prompt, - ContextTemplate: summaryParams.ContextTemplate, - Temperature: summaryParams.Temperature, - Seed: summaryParams.Seed, - NoMatchPrefix: summaryParams.NoMatchPrefix, - MaxCompletionTokens: summaryParams.MaxCompletionTokens, - } - - if tenantConv != nil { - vectorThreshold = tenantConv.VectorThreshold - keywordThreshold = tenantConv.KeywordThreshold - embeddingTopK = tenantConv.EmbeddingTopK - rerankModelID = tenantConv.RerankModelID - rerankTopK = tenantConv.RerankTopK - rerankThreshold = tenantConv.RerankThreshold - maxRounds = tenantConv.MaxRounds - if tenantConv.FallbackStrategy != "" { - fallbackStrategy = types.FallbackStrategy(tenantConv.FallbackStrategy) - } - fallbackResponse = tenantConv.FallbackResponse - if tenantConv.FallbackPrompt != "" { - fallbackPrompt = tenantConv.FallbackPrompt - } - enableRewrite = tenantConv.EnableRewrite - enableQueryExpansion = tenantConv.EnableQueryExpansion - - if tenantConv.MaxCompletionTokens != 0 { - summaryConfig.MaxCompletionTokens = tenantConv.MaxCompletionTokens - } - if tenantConv.Prompt != "" { - summaryConfig.Prompt = tenantConv.Prompt - } - if tenantConv.ContextTemplate != "" { - summaryConfig.ContextTemplate = tenantConv.ContextTemplate - } - if tenantConv.Temperature != 0 { - summaryConfig.Temperature = tenantConv.Temperature - } - if tenantConv.RewritePromptSystem != "" { - rewritePromptSystem = tenantConv.RewritePromptSystem - } - if tenantConv.RewritePromptUser != "" { - rewritePromptUser = tenantConv.RewritePromptUser - } + Prompt: s.cfg.Conversation.Summary.Prompt, + ContextTemplate: s.cfg.Conversation.Summary.ContextTemplate, + Temperature: s.cfg.Conversation.Summary.Temperature, + NoMatchPrefix: s.cfg.Conversation.Summary.NoMatchPrefix, + MaxCompletionTokens: s.cfg.Conversation.Summary.MaxCompletionTokens, } // Set default fallback strategy if not set @@ -533,26 +465,75 @@ func (s *sessionService) KnowledgeQA( } // Apply custom agent configuration if provided - multiTurnEnabled := true // Default: enable multi-turn if customAgent != nil { - // Override system prompt with customAgent's SystemPrompt + // Ensure defaults are set + customAgent.EnsureDefaults() + + // Override system prompt if customAgent.Config.SystemPrompt != "" { summaryConfig.Prompt = customAgent.Config.SystemPrompt logger.Infof(ctx, "Using custom agent's system_prompt") } - // Override temperature with customAgent's Temperature + // Override context template + if customAgent.Config.ContextTemplate != "" { + summaryConfig.ContextTemplate = customAgent.Config.ContextTemplate + logger.Infof(ctx, "Using custom agent's context_template") + } + // Override temperature if customAgent.Config.Temperature > 0 { summaryConfig.Temperature = customAgent.Config.Temperature logger.Infof(ctx, "Using custom agent's temperature: %f", customAgent.Config.Temperature) } - // Override maxRounds with customAgent's HistoryTurns + // Override max completion tokens + if customAgent.Config.MaxCompletionTokens > 0 { + summaryConfig.MaxCompletionTokens = customAgent.Config.MaxCompletionTokens + logger.Infof(ctx, "Using custom agent's max_completion_tokens: %d", customAgent.Config.MaxCompletionTokens) + } + // Override retrieval strategy settings + if customAgent.Config.EmbeddingTopK > 0 { + embeddingTopK = customAgent.Config.EmbeddingTopK + } + if customAgent.Config.KeywordThreshold > 0 { + keywordThreshold = customAgent.Config.KeywordThreshold + } + if customAgent.Config.VectorThreshold > 0 { + vectorThreshold = customAgent.Config.VectorThreshold + } + if customAgent.Config.RerankTopK > 0 { + rerankTopK = customAgent.Config.RerankTopK + } + if customAgent.Config.RerankThreshold > 0 { + rerankThreshold = customAgent.Config.RerankThreshold + } + if customAgent.Config.RerankModelID != "" { + rerankModelID = customAgent.Config.RerankModelID + } + // Override rewrite settings + enableRewrite = customAgent.Config.EnableRewrite + enableQueryExpansion = customAgent.Config.EnableQueryExpansion + if customAgent.Config.RewritePromptSystem != "" { + rewritePromptSystem = customAgent.Config.RewritePromptSystem + } + if customAgent.Config.RewritePromptUser != "" { + rewritePromptUser = customAgent.Config.RewritePromptUser + } + // Override fallback settings + if customAgent.Config.FallbackStrategy != "" { + fallbackStrategy = types.FallbackStrategy(customAgent.Config.FallbackStrategy) + } + if customAgent.Config.FallbackResponse != "" { + fallbackResponse = customAgent.Config.FallbackResponse + } + if customAgent.Config.FallbackPrompt != "" { + fallbackPrompt = customAgent.Config.FallbackPrompt + } + // Override history turns if customAgent.Config.HistoryTurns > 0 { maxRounds = customAgent.Config.HistoryTurns logger.Infof(ctx, "Using custom agent's history_turns: %d", maxRounds) } // Check if multi-turn is disabled - multiTurnEnabled = customAgent.Config.MultiTurnEnabled - if !multiTurnEnabled { + if !customAgent.Config.MultiTurnEnabled { maxRounds = 0 // Disable history logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history") } @@ -625,8 +606,7 @@ func (s *sessionService) KnowledgeQA( err = s.KnowledgeQAByEvent(ctx, chatManage, pipeline) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ - "session_id": session.ID, - "knowledge_base_id": session.KnowledgeBaseID, + "session_id": session.ID, }) return err } @@ -703,10 +683,6 @@ func (s *sessionService) selectChatModelID( knowledgeIDs []string, ) (string, error) { - // First, check if session has a SummaryModelID and if it's a Remote model - if session.SummaryModelID != "" { - return session.SummaryModelID, nil - } // If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) > 0 { tenantID := ctx.Value(types.TenantIDContextKey).(uint64) @@ -728,7 +704,7 @@ func (s *sessionService) selectChatModelID( len(knowledgeBaseIDs), len(knowledgeIDs)) } } - // If no Remote model found from session, check knowledge bases for Remote models + // Check knowledge bases for models if len(knowledgeBaseIDs) > 0 { // Try to find a knowledge base with Remote model for _, kbID := range knowledgeBaseIDs { @@ -746,13 +722,7 @@ func (s *sessionService) selectChatModelID( } } - // If still no Remote model found, use session's SummaryModelID if available - if session.SummaryModelID != "" { - logger.Infof(ctx, "No Remote model found, using session's summary model: %s", session.SummaryModelID) - return session.SummaryModelID, nil - } - - // If still empty, use first knowledge base's model + // If no Remote model found, use first knowledge base's model kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, knowledgeBaseIDs[0]) if err != nil { logger.Errorf(ctx, "Failed to get knowledge base for model ID: %v", err) @@ -766,22 +736,24 @@ func (s *sessionService) selectChatModelID( kb.SummaryModelID, ) return kb.SummaryModelID, nil - } else { - logger.Errorf(ctx, "Knowledge base %s has no summary model ID", knowledgeBaseIDs[0]) - return "", fmt.Errorf("knowledge base %s has no summary model configured", knowledgeBaseIDs[0]) } } - // No knowledge bases - use session's SummaryModelID if available - if session.SummaryModelID != "" { - logger.Infof(ctx, "No knowledge bases, using session's summary model: %s", session.SummaryModelID) - return session.SummaryModelID, nil + // No knowledge bases - try to find any available chat model + models, err := s.modelService.ListModels(ctx) + if err != nil { + logger.Errorf(ctx, "Failed to list models: %v", err) + return "", fmt.Errorf("failed to list models: %w", err) + } + for _, model := range models { + if model != nil && model.Type == types.ModelTypeKnowledgeQA { + logger.Infof(ctx, "Using first available KnowledgeQA model: %s", model.ID) + return model.ID, nil + } } logger.Error(ctx, "No chat model ID available") - return "", errors.New( - "no chat model ID available: session has no SummaryModelID and no knowledge bases configured", - ) + return "", errors.New("no chat model ID available: no knowledge bases configured and no available models") } // buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs @@ -1049,18 +1021,20 @@ func (s *sessionService) AgentQA( sessionID, tenantID, query, string(sessionJSON)) // Build effective agent configuration by merging session and tenant configs - // Session-level config: Enabled, KnowledgeBases (stored in session.AgentConfig) - // Tenant-level config: MaxIterations, Temperature, Models, Tools, etc. (from tenant.AgentConfig) + // All config now comes from customAgent parameter tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - // Check if agent is enabled at session level - if session.AgentConfig == nil { - logger.Warnf(ctx, "Agent config not found for session: %s", sessionID) - return errors.New("agent config not found for session") + // customAgent is required for AgentQA + if customAgent == nil { + logger.Warnf(ctx, "Custom agent not provided for session: %s", sessionID) + return errors.New("custom agent configuration is required for agent QA") } - // Check if tenant has agent configuration + // Ensure defaults are set + customAgent.EnsureDefaults() + + // Check if tenant has agent configuration (for defaults) if tenantInfo.AgentConfig == nil { tenantInfo.AgentConfig = &types.AgentConfig{ MaxIterations: agent.DefaultAgentMaxIterations, @@ -1073,76 +1047,35 @@ func (s *sessionService) AgentQA( } } - // Create runtime AgentConfig - // Priority: CustomAgent config > Tenant config > Defaults - // Session config provides KnowledgeBases and KnowledgeIDs - var agentConfig *types.AgentConfig - - if customAgent != nil && customAgent.ID != types.BuiltinAgentNormalID && customAgent.ID != types.BuiltinAgentAgentID { - // Use custom agent configuration - logger.Infof(ctx, "Using custom agent configuration, agent ID: %s, name: %s", customAgent.ID, customAgent.Name) - customAgent.EnsureDefaults() - - agentConfig = &types.AgentConfig{ - MaxIterations: customAgent.Config.MaxIterations, - ReflectionEnabled: customAgent.Config.ReflectionEnabled, - Temperature: customAgent.Config.Temperature, - WebSearchEnabled: customAgent.Config.WebSearchEnabled, - WebSearchMaxResults: customAgent.Config.WebSearchMaxResults, - MultiTurnEnabled: customAgent.Config.MultiTurnEnabled, - HistoryTurns: customAgent.Config.HistoryTurns, - } - - // Use custom agent's allowed tools if specified, otherwise use defaults - if len(customAgent.Config.AllowedTools) > 0 { - agentConfig.AllowedTools = customAgent.Config.AllowedTools - } else { - agentConfig.AllowedTools = tools.DefaultAllowedTools() - } - - // Use custom agent's system prompt if specified - if customAgent.Config.SystemPrompt != "" { - agentConfig.UseCustomSystemPrompt = true - agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt - agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt - } - - // Use custom agent's knowledge bases if specified, otherwise use session's - if len(customAgent.Config.KnowledgeBases) > 0 { - agentConfig.KnowledgeBases = customAgent.Config.KnowledgeBases - } else { - agentConfig.KnowledgeBases = session.AgentConfig.KnowledgeBases - } - agentConfig.KnowledgeIDs = session.AgentConfig.KnowledgeIDs - - // Override summary model if custom agent specifies one - if customAgent.Config.ModelID != "" { - session.SummaryModelID = customAgent.Config.ModelID - } - - logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v", - agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled) - } else { - // Use tenant configuration (default behavior) - agentConfig = &types.AgentConfig{ - MaxIterations: tenantInfo.AgentConfig.MaxIterations, - ReflectionEnabled: tenantInfo.AgentConfig.ReflectionEnabled, - AllowedTools: tools.DefaultAllowedTools(), - Temperature: tenantInfo.AgentConfig.Temperature, - KnowledgeBases: session.AgentConfig.KnowledgeBases, // Use session's knowledge bases - KnowledgeIDs: session.AgentConfig.KnowledgeIDs, // Use session's knowledge IDs (individual documents) - WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config - MultiTurnEnabled: true, // Default: enable multi-turn - HistoryTurns: 5, // Default: keep 5 turns - } - - agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt - if agentConfig.UseCustomSystemPrompt { - agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true) - agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false) - } + // Create runtime AgentConfig from customAgent + agentConfig := &types.AgentConfig{ + MaxIterations: customAgent.Config.MaxIterations, + ReflectionEnabled: customAgent.Config.ReflectionEnabled, + Temperature: customAgent.Config.Temperature, + WebSearchEnabled: customAgent.Config.WebSearchEnabled, + WebSearchMaxResults: customAgent.Config.WebSearchMaxResults, + MultiTurnEnabled: customAgent.Config.MultiTurnEnabled, + HistoryTurns: customAgent.Config.HistoryTurns, + KnowledgeBases: customAgent.Config.KnowledgeBases, } + // Use custom agent's allowed tools if specified, otherwise use defaults + if len(customAgent.Config.AllowedTools) > 0 { + agentConfig.AllowedTools = customAgent.Config.AllowedTools + } else { + agentConfig.AllowedTools = tools.DefaultAllowedTools() + } + + // Use custom agent's system prompt if specified + if customAgent.Config.SystemPrompt != "" { + agentConfig.UseCustomSystemPrompt = true + agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt + agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt + } + + logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v", + agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled) + // Set web search max results from tenant config if not set (default: 5) if agentConfig.WebSearchMaxResults == 0 { agentConfig.WebSearchMaxResults = 5 @@ -1153,31 +1086,13 @@ func (s *sessionService) AgentQA( logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, sessionID) - // Log knowledge IDs if present - if len(agentConfig.KnowledgeIDs) > 0 { - logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s): %v", - len(agentConfig.KnowledgeIDs), agentConfig.KnowledgeIDs) - } - - // Determine knowledge bases for agent - // Priority: Session.AgentConfig.KnowledgeBases > Session.KnowledgeBaseID > All tenant knowledge bases - // Exception: If KnowledgeIDs are specified, don't auto-add all KBs (let buildSearchTargets handle it) - if len(agentConfig.KnowledgeBases) == 0 && len(agentConfig.KnowledgeIDs) == 0 { - if session.KnowledgeBaseID != "" { - // Use session's knowledge base as fallback - agentConfig.KnowledgeBases = []string{session.KnowledgeBaseID} - logger.Infof(ctx, "Using session's knowledge base for agent: %s", session.KnowledgeBaseID) - } else { - // Allow running without knowledge bases (Pure Agent mode) - logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode") - } - } else if len(agentConfig.KnowledgeIDs) > 0 && len(agentConfig.KnowledgeBases) == 0 { - // User specified individual files but no KBs - don't auto-add all KBs - logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s), no KB auto-expansion", - len(agentConfig.KnowledgeIDs)) - } else { + // Log knowledge bases if present + if len(agentConfig.KnowledgeBases) > 0 { logger.Infof(ctx, "Agent configured with %d knowledge base(s): %v", len(agentConfig.KnowledgeBases), agentConfig.KnowledgeBases) + } else { + // Allow running without knowledge bases (Pure Agent mode) + logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode") } // Build search targets for agent (pre-compute once to avoid repeated queries) @@ -1189,7 +1104,8 @@ func (s *sessionService) AgentQA( agentConfig.SearchTargets = searchTargets logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets)) - summaryModelID := session.SummaryModelID + // Get summary model from custom agent config or tenant config + summaryModelID := customAgent.Config.ModelID if summaryModelID == "" && tenantInfo.ConversationConfig != nil { summaryModelID = tenantInfo.ConversationConfig.SummaryModelID } @@ -1204,7 +1120,8 @@ func (s *sessionService) AgentQA( return fmt.Errorf("failed to get chat model: %w", err) } - rerankModelID := session.RerankModelID + // Get rerank model from custom agent config or tenant config + rerankModelID := customAgent.Config.RerankModelID if rerankModelID == "" && tenantInfo.ConversationConfig != nil { rerankModelID = tenantInfo.ConversationConfig.RerankModelID } @@ -1296,13 +1213,9 @@ func (s *sessionService) getContextManagerForSession( ) interfaces.ContextManager { // Get tenant to access global context configuration tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - // Determine which context config to use: session-specific or tenant-level + // Determine which context config to use: tenant-level or default var contextConfig *types.ContextConfig - if session.ContextConfig != nil { - // Use session-specific configuration - contextConfig = session.ContextConfig - logger.Infof(ctx, "Using session-specific context config for session %s", session.ID) - } else if tenant.ContextConfig != nil { + if tenant != nil && tenant.ContextConfig != nil { // Use tenant-level configuration contextConfig = tenant.ContextConfig logger.Infof(ctx, "Using tenant-level context config for session %s", session.ID) diff --git a/internal/config/config.go b/internal/config/config.go index f70fe9e1..9a137a3b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( "fmt" "os" + "path/filepath" "regexp" "strings" "time" @@ -10,20 +11,22 @@ import ( "github.com/Tencent/WeKnora/internal/types" "github.com/go-viper/mapstructure/v2" "github.com/spf13/viper" + "gopkg.in/yaml.v3" ) // Config 应用程序总配置 type Config struct { - Conversation *ConversationConfig `yaml:"conversation" json:"conversation"` - Server *ServerConfig `yaml:"server" json:"server"` - KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"` - Tenant *TenantConfig `yaml:"tenant" json:"tenant"` - Models []ModelConfig `yaml:"models" json:"models"` - VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"` - DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"` - StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"` - ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"` - WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"` + Conversation *ConversationConfig `yaml:"conversation" json:"conversation"` + Server *ServerConfig `yaml:"server" json:"server"` + KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"` + Tenant *TenantConfig `yaml:"tenant" json:"tenant"` + Models []ModelConfig `yaml:"models" json:"models"` + VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"` + DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"` + StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"` + ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"` + WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"` + PromptTemplates *PromptTemplatesConfig `yaml:"prompt_templates" json:"prompt_templates"` } type DocReaderConfig struct { @@ -108,6 +111,25 @@ type TenantConfig struct { EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"` } +// PromptTemplate 提示词模板 +type PromptTemplate struct { + ID string `yaml:"id" json:"id"` + Name string `yaml:"name" json:"name"` + Description string `yaml:"description" json:"description"` + Content string `yaml:"content" json:"content"` + HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"` + HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"` +} + +// PromptTemplatesConfig 提示词模板配置 +type PromptTemplatesConfig struct { + SystemPrompt []PromptTemplate `yaml:"system_prompt" json:"system_prompt"` + ContextTemplate []PromptTemplate `yaml:"context_template" json:"context_template"` + RewriteSystem []PromptTemplate `yaml:"rewrite_system" json:"rewrite_system"` + RewriteUser []PromptTemplate `yaml:"rewrite_user" json:"rewrite_user"` + Fallback []PromptTemplate `yaml:"fallback" json:"fallback"` +} + // ModelConfig 模型配置 type ModelConfig struct { Type string `yaml:"type" json:"type"` @@ -192,9 +214,68 @@ func LoadConfig() (*Config, error) { return nil, fmt.Errorf("unable to decode config into struct: %w", err) } fmt.Printf("Using configuration file: %s\n", viper.ConfigFileUsed()) + + // 加载提示词模板(从目录或配置文件) + configDir := filepath.Dir(viper.ConfigFileUsed()) + promptTemplates, err := loadPromptTemplates(configDir) + if err != nil { + fmt.Printf("Warning: failed to load prompt templates from directory: %v\n", err) + // 如果目录加载失败,使用配置文件中的模板(如果有) + } else if promptTemplates != nil { + cfg.PromptTemplates = promptTemplates + } + return &cfg, nil } +// promptTemplateFile 用于解析模板文件 +type promptTemplateFile struct { + Templates []PromptTemplate `yaml:"templates"` +} + +// loadPromptTemplates 从目录加载提示词模板 +func loadPromptTemplates(configDir string) (*PromptTemplatesConfig, error) { + templatesDir := filepath.Join(configDir, "prompt_templates") + + // 检查目录是否存在 + if _, err := os.Stat(templatesDir); os.IsNotExist(err) { + return nil, nil // 目录不存在,返回nil让调用者使用配置文件中的模板 + } + + config := &PromptTemplatesConfig{} + + // 定义模板文件映射 + templateFiles := map[string]*[]PromptTemplate{ + "system_prompt.yaml": &config.SystemPrompt, + "context_template.yaml": &config.ContextTemplate, + "rewrite_system.yaml": &config.RewriteSystem, + "rewrite_user.yaml": &config.RewriteUser, + "fallback.yaml": &config.Fallback, + } + + // 加载每个模板文件 + for filename, target := range templateFiles { + filePath := filepath.Join(templatesDir, filename) + if _, err := os.Stat(filePath); os.IsNotExist(err) { + continue // 文件不存在,跳过 + } + + data, err := os.ReadFile(filePath) + if err != nil { + return nil, fmt.Errorf("failed to read %s: %w", filename, err) + } + + var file promptTemplateFile + if err := yaml.Unmarshal(data, &file); err != nil { + return nil, fmt.Errorf("failed to parse %s: %w", filename, err) + } + + *target = file.Templates + } + + return config, nil +} + // WebSearchConfig represents the web search configuration type WebSearchConfig struct { Providers []WebSearchProviderConfig `yaml:"providers" json:"providers"` diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go index b147fcb8..1eb2f39d 100644 --- a/internal/handler/custom_agent.go +++ b/internal/handler/custom_agent.go @@ -35,7 +35,7 @@ type CreateAgentRequest struct { // UpdateAgentRequest defines the request body for updating an agent type UpdateAgentRequest struct { - Name string `json:"name" binding:"required"` + Name string `json:"name"` Description string `json:"description"` Avatar string `json:"avatar"` Type types.CustomAgentType `json:"type"` diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index ee3e0cb7..39ba42e9 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -1,7 +1,6 @@ package session import ( - "context" "net/http" "github.com/Tencent/WeKnora/internal/config" @@ -74,75 +73,17 @@ func (h *Handler) CreateSession(c *gin.Context) { // Validate session creation request // Sessions are now knowledge-base-independent: - // - KnowledgeBaseID is optional during session creation - // - Knowledge base can be specified in each query request (AgentQA/KnowledgeQA) - // - Agent mode can access multiple knowledge bases via AgentConfig.KnowledgeBases - // - Knowledge base can be switched during conversation - isAgentMode := request.AgentConfig != nil && request.AgentConfig.AgentModeEnabled - hasAgentKnowledgeBases := request.AgentConfig != nil && len(request.AgentConfig.KnowledgeBases) > 0 - + // - All configuration comes from custom agent at query time + // - Session only stores basic info (tenant ID, title, etc.) logger.Infof( ctx, - "Processing session creation request, tenant ID: %d, knowledge base ID: %s, agent mode: %v, agent KBs: %v", + "Processing session creation request, tenant ID: %d", tenantID, - request.KnowledgeBaseID, - isAgentMode, - hasAgentKnowledgeBases, ) // Create session object with base properties createdSession := &types.Session{ - TenantID: tenantID.(uint64), - KnowledgeBaseID: request.KnowledgeBaseID, - AgentConfig: request.AgentConfig, // Set agent config if provided - } - - // If summary model parameters are empty, set defaults - if request.SessionStrategy != nil { - createdSession.RerankModelID = request.SessionStrategy.RerankModelID - createdSession.SummaryModelID = request.SessionStrategy.SummaryModelID - createdSession.MaxRounds = request.SessionStrategy.MaxRounds - createdSession.EnableRewrite = request.SessionStrategy.EnableRewrite - createdSession.FallbackStrategy = request.SessionStrategy.FallbackStrategy - createdSession.FallbackResponse = request.SessionStrategy.FallbackResponse - createdSession.EmbeddingTopK = request.SessionStrategy.EmbeddingTopK - createdSession.KeywordThreshold = request.SessionStrategy.KeywordThreshold - createdSession.VectorThreshold = request.SessionStrategy.VectorThreshold - createdSession.RerankTopK = request.SessionStrategy.RerankTopK - createdSession.RerankThreshold = request.SessionStrategy.RerankThreshold - if request.SessionStrategy.SummaryParameters != nil { - createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters - } else { - createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx) - } - h.fillSummaryConfigDefaults(ctx, createdSession.SummaryParameters) - - logger.Debug(ctx, "Custom session strategy set") - } else { - tenantInfo, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant) - h.applyConversationDefaults(ctx, createdSession, tenantInfo) - logger.Debug(ctx, "Using default session strategy") - } - - // Fetch knowledge base if KnowledgeBaseID is provided to inherit its model configurations - // If no KB is provided, models will be determined at query time or use tenant/system defaults - if request.KnowledgeBaseID != "" { - kb, err := h.knowledgebaseService.GetKnowledgeBaseByID(ctx, request.KnowledgeBaseID) - if err != nil { - logger.Error(ctx, "Failed to get knowledge base", err) - c.Error(errors.NewInternalServerError(err.Error())) - return - } - - // Use knowledge base's summary model if session doesn't specify it - if createdSession.SummaryModelID == "" { - createdSession.SummaryModelID = kb.SummaryModelID - } - - logger.Debugf(ctx, "Knowledge base fetched: %s, summary model: %s", - kb.ID, kb.SummaryModelID) - } else { - logger.Debug(ctx, "No knowledge base ID provided, models will use session strategy or be determined at query time") + TenantID: tenantID.(uint64), } // Call service to create session @@ -162,45 +103,6 @@ func (h *Handler) CreateSession(c *gin.Context) { }) } -func (h *Handler) applyConversationDefaults(ctx context.Context, session *types.Session, tenant *types.Tenant) { - session.MaxRounds = h.config.Conversation.MaxRounds - session.EnableRewrite = h.config.Conversation.EnableRewrite - session.FallbackStrategy = types.FallbackStrategy(h.config.Conversation.FallbackStrategy) - session.FallbackResponse = h.config.Conversation.FallbackResponse - session.EmbeddingTopK = h.config.Conversation.EmbeddingTopK - session.KeywordThreshold = h.config.Conversation.KeywordThreshold - session.VectorThreshold = h.config.Conversation.VectorThreshold - session.RerankThreshold = h.config.Conversation.RerankThreshold - session.RerankTopK = h.config.Conversation.RerankTopK - session.RerankModelID = "" - session.SummaryModelID = "" - - if tenant != nil && tenant.ConversationConfig != nil { - tc := tenant.ConversationConfig - session.MaxRounds = tc.MaxRounds - session.EnableRewrite = tc.EnableRewrite - if tc.FallbackStrategy != "" { - session.FallbackStrategy = types.FallbackStrategy(tc.FallbackStrategy) - } - if tc.FallbackResponse != "" { - session.FallbackResponse = tc.FallbackResponse - } - session.EmbeddingTopK = tc.EmbeddingTopK - session.KeywordThreshold = tc.KeywordThreshold - session.VectorThreshold = tc.VectorThreshold - session.RerankThreshold = tc.RerankThreshold - session.RerankTopK = tc.RerankTopK - if tc.RerankModelID != "" { - session.RerankModelID = tc.RerankModelID - } - if tc.SummaryModelID != "" { - session.SummaryModelID = tc.SummaryModelID - } - } - - session.SummaryParameters = h.createDefaultSummaryConfig(ctx) -} - // GetSession godoc // @Summary 获取会话详情 // @Description 根据ID获取会话详情 diff --git a/internal/handler/session/helpers.go b/internal/handler/session/helpers.go index f14ebc77..b1e76d77 100644 --- a/internal/handler/session/helpers.go +++ b/internal/handler/session/helpers.go @@ -203,20 +203,13 @@ func (h *Handler) createDefaultSummaryConfig(ctx context.Context) *types.Summary // Override with tenant-level conversation config if available if tenant != nil && tenant.ConversationConfig != nil { - useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt - if !useSystemPrompt && tenant.ConversationConfig.Prompt != "" { - // Backward compatibility: treat legacy configs without flag as custom - useSystemPrompt = true - } - if useSystemPrompt && tenant.ConversationConfig.Prompt != "" { + // Use custom prompt if provided + if tenant.ConversationConfig.Prompt != "" { cfg.Prompt = tenant.ConversationConfig.Prompt } - useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate - if !useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" { - useContextTemplate = true - } - if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" { + // Use custom context template if provided + if tenant.ConversationConfig.ContextTemplate != "" { cfg.ContextTemplate = tenant.ConversationConfig.ContextTemplate } if tenant.ConversationConfig.Temperature > 0 { @@ -242,13 +235,13 @@ func (h *Handler) fillSummaryConfigDefaults(ctx context.Context, config *types.S var defaultMaxCompletionTokens int if tenant != nil && tenant.ConversationConfig != nil { - useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt - if useSystemPrompt && tenant.ConversationConfig.Prompt != "" { + // Use custom prompt if provided + if tenant.ConversationConfig.Prompt != "" { defaultPrompt = tenant.ConversationConfig.Prompt } - useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate - if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" { + // Use custom context template if provided + if tenant.ConversationConfig.ContextTemplate != "" { defaultContextTemplate = tenant.ConversationConfig.ContextTemplate } defaultTemperature = tenant.ConversationConfig.Temperature diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 4a4ae8c0..d5254c54 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -111,118 +111,6 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo return reqCtx, &request, nil } -// detectAndApplyConfigChanges detects configuration changes and updates session if needed -// Returns true if any configuration changed -func (h *Handler) detectAndApplyConfigChanges( - reqCtx *qaRequestContext, - request *CreateKnowledgeQARequest, -) (bool, error) { - ctx := reqCtx.ctx - session := reqCtx.session - sessionID := reqCtx.sessionID - - // Initialize AgentConfig if it doesn't exist - if session.AgentConfig == nil { - session.AgentConfig = &types.SessionAgentConfig{} - } - - configChanged := false - - // Check knowledge bases change - if hasArrayChanged(session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs) { - logger.Infof(ctx, "Knowledge bases changed from %v to %v", - session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs) - configChanged = true - } - - // Check knowledge IDs change - if hasArrayChanged(session.AgentConfig.KnowledgeIDs, request.KnowledgeIds) { - logger.Infof(ctx, "Knowledge IDs changed from %v to %v", - session.AgentConfig.KnowledgeIDs, request.KnowledgeIds) - configChanged = true - } - - // Check agent mode change - if request.AgentEnabled != session.AgentConfig.AgentModeEnabled { - logger.Infof(ctx, "Agent mode changed from %v to %v", - session.AgentConfig.AgentModeEnabled, request.AgentEnabled) - configChanged = true - } - - // Check web search change - if request.WebSearchEnabled != session.AgentConfig.WebSearchEnabled { - logger.Infof(ctx, "Web search mode changed from %v to %v", - session.AgentConfig.WebSearchEnabled, request.WebSearchEnabled) - configChanged = true - } - - // Resolve summary model ID - summaryModelID := reqCtx.summaryModelID - if summaryModelID == "" { - summaryModelID = session.SummaryModelID - } - if summaryModelID == "" { - if tenantInfo, ok := ctx.Value(types.TenantInfoContextKey).(*types.Tenant); ok && tenantInfo.ConversationConfig != nil { - summaryModelID = tenantInfo.ConversationConfig.SummaryModelID - } - } - if summaryModelID != session.SummaryModelID { - configChanged = true - } - - // Apply changes if any - if configChanged { - logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID) - - // Clear LLM context - if err := h.sessionService.ClearContext(ctx, sessionID); err != nil { - logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err) - } - - // Delete temp KB state - if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil { - logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err) - } - - // Update session config - session.AgentConfig.KnowledgeBases = secutils.SanitizeForLogArray(request.KnowledgeBaseIDs) - session.AgentConfig.KnowledgeIDs = secutils.SanitizeForLogArray(request.KnowledgeIds) - session.AgentConfig.AgentModeEnabled = request.AgentEnabled - session.AgentConfig.WebSearchEnabled = request.WebSearchEnabled - session.SummaryModelID = summaryModelID - - // Persist changes - if err := h.sessionService.UpdateSession(ctx, session); err != nil { - logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err) - return false, errors.NewInternalServerError("Failed to update session configuration") - } - logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID) - } - - return configChanged, nil -} - -// hasArrayChanged checks if two string arrays are different -func hasArrayChanged(current, new []string) bool { - if len(current) != len(new) { - return true - } - if len(current) == 0 && len(new) == 0 { - return false - } - - currentMap := make(map[string]bool) - for _, v := range current { - currentMap[v] = true - } - for _, v := range new { - if !currentMap[v] { - return true - } - } - return false -} - // sseStreamContext holds the context for SSE streaming type sseStreamContext struct { eventBus *event.EventBus @@ -388,12 +276,6 @@ func (h *Handler) AgentQA(c *gin.Context) { return } - // Detect and apply configuration changes - if _, err := h.detectAndApplyConfigChanges(reqCtx, request); err != nil { - c.Error(err) - return - } - // Determine if agent mode should be enabled // Priority: customAgent.IsAgentMode() > request.AgentEnabled agentModeEnabled := request.AgentEnabled @@ -408,13 +290,7 @@ func (h *Handler) AgentQA(c *gin.Context) { h.executeAgentModeQA(reqCtx) } else { logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID) - // Fallback to session's knowledge bases if not specified in request - if len(reqCtx.knowledgeBaseIDs) == 0 { - reqCtx.knowledgeBaseIDs = reqCtx.session.AgentConfig.KnowledgeBases - } - if len(reqCtx.knowledgeBaseIDs) == 0 && reqCtx.session.KnowledgeBaseID != "" { - reqCtx.knowledgeBaseIDs = []string{reqCtx.session.KnowledgeBaseID} - } + // Knowledge bases should be specified in request or from custom agent h.executeNormalModeQA(reqCtx, false) } } diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go index eac5b405..b9bcd734 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -425,7 +425,6 @@ type AgentConfigRequest struct { Temperature float64 `json:"temperature"` SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` - UseCustomPrompt *bool `json:"use_custom_system_prompt"` } // GetTenantAgentConfig godoc @@ -497,8 +496,6 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) { systemPromptWithoutWeb = agent.ProgressiveRAGSystemPromptWithoutWeb } - useCustomPrompt := tenant.AgentConfig.UseCustomSystemPrompt - logger.Infof(ctx, "Retrieved tenant agent config successfully, Tenant ID: %d", tenant.ID) c.JSON(http.StatusOK, gin.H{ "success": true, @@ -509,7 +506,6 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) { "temperature": tenant.AgentConfig.Temperature, "system_prompt_web_enabled": systemPromptWithWeb, "system_prompt_web_disabled": systemPromptWithoutWeb, - "use_custom_system_prompt": useCustomPrompt, "available_tools": availableTools, "available_placeholders": availablePlaceholders, }, @@ -546,13 +542,8 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) { return } // Update agent configuration - useCustomPrompt := false - if tenant.AgentConfig != nil { - useCustomPrompt = tenant.AgentConfig.UseCustomSystemPrompt - } - if req.UseCustomPrompt != nil { - useCustomPrompt = *req.UseCustomPrompt - } + // Determine if using custom prompt based on whether custom prompts are set + useCustomPrompt := req.SystemPromptWebEnabled != "" || req.SystemPromptWebDisabled != "" tenant.AgentConfig = &types.AgentConfig{ MaxIterations: req.MaxIterations, @@ -610,6 +601,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) { case "conversation-config": h.GetTenantConversationConfig(c) return + case "prompt-templates": + h.GetPromptTemplates(c) + return default: logger.Info(ctx, "KV key not supported", "key", key) c.Error(errors.NewBadRequestError("unsupported key")) @@ -726,25 +720,23 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) { func (h *TenantHandler) buildDefaultConversationConfig() *types.ConversationConfig { return &types.ConversationConfig{ - Prompt: h.config.Conversation.Summary.Prompt, - ContextTemplate: h.config.Conversation.Summary.ContextTemplate, - UseCustomContextTemplate: true, - UseCustomSystemPrompt: true, - Temperature: h.config.Conversation.Summary.Temperature, - MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens, - MaxRounds: h.config.Conversation.MaxRounds, - EmbeddingTopK: h.config.Conversation.EmbeddingTopK, - KeywordThreshold: h.config.Conversation.KeywordThreshold, - VectorThreshold: h.config.Conversation.VectorThreshold, - RerankTopK: h.config.Conversation.RerankTopK, - RerankThreshold: h.config.Conversation.RerankThreshold, - EnableRewrite: h.config.Conversation.EnableRewrite, - EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion, - FallbackStrategy: h.config.Conversation.FallbackStrategy, - FallbackResponse: h.config.Conversation.FallbackResponse, - FallbackPrompt: h.config.Conversation.FallbackPrompt, - RewritePromptUser: h.config.Conversation.RewritePromptUser, - RewritePromptSystem: h.config.Conversation.RewritePromptSystem, + Prompt: h.config.Conversation.Summary.Prompt, + ContextTemplate: h.config.Conversation.Summary.ContextTemplate, + Temperature: h.config.Conversation.Summary.Temperature, + MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens, + MaxRounds: h.config.Conversation.MaxRounds, + EmbeddingTopK: h.config.Conversation.EmbeddingTopK, + KeywordThreshold: h.config.Conversation.KeywordThreshold, + VectorThreshold: h.config.Conversation.VectorThreshold, + RerankTopK: h.config.Conversation.RerankTopK, + RerankThreshold: h.config.Conversation.RerankThreshold, + EnableRewrite: h.config.Conversation.EnableRewrite, + EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion, + FallbackStrategy: h.config.Conversation.FallbackStrategy, + FallbackResponse: h.config.Conversation.FallbackResponse, + FallbackPrompt: h.config.Conversation.FallbackPrompt, + RewritePromptUser: h.config.Conversation.RewritePromptUser, + RewritePromptSystem: h.config.Conversation.RewritePromptSystem, } } @@ -803,91 +795,8 @@ func (h *TenantHandler) GetTenantConversationConfig(c *gin.Context) { // If tenant has no conversation config, return defaults from config.yaml var response *types.ConversationConfig - if tc := tenant.ConversationConfig; tc == nil { - logger.Info(ctx, "Tenant has no conversation config, returning defaults") - response = h.buildDefaultConversationConfig() - } else { - logger.Infof(ctx, "Tenant has conversation config, merging with defaults, Tenant ID: %d", tenant.ID) - // Merge tenant config with defaults, so that newly added fields always have valid values - defaultCfg := h.buildDefaultConversationConfig() - // Prompt related - defaultCfg.UseCustomSystemPrompt = tc.UseCustomSystemPrompt - if !defaultCfg.UseCustomSystemPrompt && tc.Prompt != "" { - // Legacy configs without explicit flag - defaultCfg.UseCustomSystemPrompt = true - } - defaultCfg.UseCustomContextTemplate = tc.UseCustomContextTemplate - if !defaultCfg.UseCustomContextTemplate && tc.ContextTemplate != "" { - defaultCfg.UseCustomContextTemplate = true - } - if tc.Prompt != "" { - defaultCfg.Prompt = tc.Prompt - } - if tc.ContextTemplate != "" { - defaultCfg.ContextTemplate = tc.ContextTemplate - } - if tc.Temperature > 0 { - defaultCfg.Temperature = tc.Temperature - } - if tc.MaxCompletionTokens > 0 { - defaultCfg.MaxCompletionTokens = tc.MaxCompletionTokens - } - - // Retrieval parameters - if tc.MaxRounds > 0 { - defaultCfg.MaxRounds = tc.MaxRounds - } - if tc.EmbeddingTopK > 0 { - defaultCfg.EmbeddingTopK = tc.EmbeddingTopK - } - if tc.KeywordThreshold > 0 { - defaultCfg.KeywordThreshold = tc.KeywordThreshold - } - if tc.VectorThreshold > 0 { - defaultCfg.VectorThreshold = tc.VectorThreshold - } - if tc.RerankTopK > 0 { - defaultCfg.RerankTopK = tc.RerankTopK - } - if tc.RerankThreshold > 0 { - defaultCfg.RerankThreshold = tc.RerankThreshold - } - // EnableRewrite 需要允许显式关闭,因此直接覆盖 - defaultCfg.EnableRewrite = tc.EnableRewrite - - // Query expansion toggle - defaultCfg.EnableQueryExpansion = tc.EnableQueryExpansion - - // Model IDs - if tc.SummaryModelID != "" { - defaultCfg.SummaryModelID = tc.SummaryModelID - } - if tc.RerankModelID != "" { - defaultCfg.RerankModelID = tc.RerankModelID - } - - // Fallback settings - if tc.FallbackStrategy != "" { - defaultCfg.FallbackStrategy = tc.FallbackStrategy - } - if tc.FallbackResponse != "" { - defaultCfg.FallbackResponse = tc.FallbackResponse - } - if tc.FallbackPrompt != "" { - defaultCfg.FallbackPrompt = tc.FallbackPrompt - } - - // Rewrite prompts - if tc.RewritePromptSystem != "" { - defaultCfg.RewritePromptSystem = tc.RewritePromptSystem - } - if tc.RewritePromptUser != "" { - defaultCfg.RewritePromptUser = tc.RewritePromptUser - } - - response = defaultCfg - } - + logger.Info(ctx, "Tenant has no conversation config, returning defaults") + response = h.buildDefaultConversationConfig() c.JSON(http.StatusOK, gin.H{ "success": true, "data": response, @@ -943,3 +852,27 @@ func (h *TenantHandler) updateTenantConversationInternal(c *gin.Context) { "message": "Conversation configuration updated successfully", }) } + +// GetPromptTemplates godoc +// @Summary 获取提示词模板 +// @Description 获取系统配置的提示词模板列表 +// @Tags 租户管理 +// @Accept json +// @Produce json +// @Success 200 {object} map[string]interface{} "提示词模板配置" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /tenants/kv/prompt-templates [get] +func (h *TenantHandler) GetPromptTemplates(c *gin.Context) { + // Return prompt templates from config.yaml + templates := h.config.PromptTemplates + if templates == nil { + templates = &config.PromptTemplatesConfig{} + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": templates, + }) +} diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go index 4f00e8d3..b3d0b446 100644 --- a/internal/types/custom_agent.go +++ b/internal/types/custom_agent.go @@ -56,34 +56,83 @@ 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 AgentMode string `yaml:"agent_mode" json:"agent_mode"` - // System prompt for the agent + // System prompt for the agent (for normal mode, or agent mode when web search is disabled) SystemPrompt string `yaml:"system_prompt" json:"system_prompt"` + // System prompt for agent mode when web search is enabled + SystemPromptWebEnabled string `yaml:"system_prompt_web_enabled" json:"system_prompt_web_enabled"` + // Context template for normal mode (how to format retrieved chunks) + ContextTemplate string `yaml:"context_template" json:"context_template"` + + // ===== Model Settings ===== // Model ID to use for conversations ModelID string `yaml:"model_id" json:"model_id"` + // ReRank model ID for retrieval + RerankModelID string `yaml:"rerank_model_id" json:"rerank_model_id"` // Temperature for LLM (0-1) Temperature float64 `yaml:"temperature" json:"temperature"` + // Maximum completion tokens (only for normal mode) + MaxCompletionTokens int `yaml:"max_completion_tokens" json:"max_completion_tokens"` + + // ===== Agent Mode Settings ===== // Maximum iterations for ReAct loop (only for agent type) MaxIterations int `yaml:"max_iterations" json:"max_iterations"` // Allowed tools (only for agent type) AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"` - // Associated knowledge base IDs + // Whether reflection is enabled (only for agent type) + ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"` + + // ===== 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 when no KnowledgeBases are configured - // If true (default), user can freely select any knowledge base - // If false, knowledge base selection is disabled for this agent + // 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 WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"` // Maximum web search results WebSearchMaxResults int `yaml:"web_search_max_results" json:"web_search_max_results"` - // Whether reflection is enabled (only for agent type) - ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"` - // Welcome message displayed when agent is selected + + // ===== Multi-turn Conversation Settings ===== + // Whether multi-turn conversation is enabled MultiTurnEnabled bool `yaml:"multi_turn_enabled" json:"multi_turn_enabled"` // Number of history turns to keep in context HistoryTurns int `yaml:"history_turns" json:"history_turns"` + + // ===== Retrieval Strategy Settings (for both modes) ===== + // Embedding/Vector retrieval top K + EmbeddingTopK int `yaml:"embedding_top_k" json:"embedding_top_k"` + // Keyword retrieval threshold + KeywordThreshold float64 `yaml:"keyword_threshold" json:"keyword_threshold"` + // Vector retrieval threshold + VectorThreshold float64 `yaml:"vector_threshold" json:"vector_threshold"` + // Rerank top K + RerankTopK int `yaml:"rerank_top_k" json:"rerank_top_k"` + // Rerank threshold + RerankThreshold float64 `yaml:"rerank_threshold" json:"rerank_threshold"` + + // ===== Advanced Settings (mainly for normal mode) ===== + // Whether to enable query expansion + EnableQueryExpansion bool `yaml:"enable_query_expansion" json:"enable_query_expansion"` + // Whether to enable query rewrite for multi-turn conversations + EnableRewrite bool `yaml:"enable_rewrite" json:"enable_rewrite"` + // Rewrite prompt system message + RewritePromptSystem string `yaml:"rewrite_prompt_system" json:"rewrite_prompt_system"` + // Rewrite prompt user message template + RewritePromptUser string `yaml:"rewrite_prompt_user" json:"rewrite_prompt_user"` + // Fallback strategy: "fixed" for fixed response, "model" for model generation + FallbackStrategy string `yaml:"fallback_strategy" json:"fallback_strategy"` + // Fixed fallback response (when FallbackStrategy is "fixed") + FallbackResponse string `yaml:"fallback_response" json:"fallback_response"` + // Fallback prompt (when FallbackStrategy is "model") + FallbackPrompt string `yaml:"fallback_prompt" json:"fallback_prompt"` } // Value implements driver.Valuer interface for CustomAgentConfig @@ -128,6 +177,29 @@ func (a *CustomAgent) EnsureDefaults() { if a.Config.HistoryTurns == 0 { a.Config.HistoryTurns = 5 } + // Retrieval strategy defaults + if a.Config.EmbeddingTopK == 0 { + a.Config.EmbeddingTopK = 10 + } + if a.Config.KeywordThreshold == 0 { + a.Config.KeywordThreshold = 0.3 + } + if a.Config.VectorThreshold == 0 { + a.Config.VectorThreshold = 0.5 + } + if a.Config.RerankTopK == 0 { + a.Config.RerankTopK = 5 + } + if a.Config.RerankThreshold == 0 { + a.Config.RerankThreshold = 0.5 + } + // Advanced settings defaults + if a.Config.FallbackStrategy == "" { + a.Config.FallbackStrategy = "model" + } + if a.Config.MaxCompletionTokens == 0 { + a.Config.MaxCompletionTokens = 2048 + } } // IsAgentMode returns true if this agent uses ReAct agent mode @@ -146,10 +218,23 @@ func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent { Type: CustomAgentTypeNormal, TenantID: tenantID, Config: CustomAgentConfig{ - AgentMode: "normal", - SystemPrompt: "", - Temperature: 0.7, - WebSearchEnabled: false, + AgentMode: "normal", + SystemPrompt: "", + Temperature: 0.7, + MaxCompletionTokens: 2048, + WebSearchEnabled: false, + MultiTurnEnabled: true, + HistoryTurns: 5, + // Retrieval strategy + EmbeddingTopK: 10, + KeywordThreshold: 0.3, + VectorThreshold: 0.5, + RerankTopK: 5, + RerankThreshold: 0.5, + // Advanced settings + EnableQueryExpansion: true, + EnableRewrite: true, + FallbackStrategy: "model", }, } } @@ -169,10 +254,18 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent { SystemPrompt: "", Temperature: 0.7, MaxIterations: 10, - AllowedTools: []string{"knowledge_search", "web_search"}, + AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"}, WebSearchEnabled: true, WebSearchMaxResults: 5, ReflectionEnabled: false, + MultiTurnEnabled: true, + HistoryTurns: 5, + // Retrieval strategy + EmbeddingTopK: 10, + KeywordThreshold: 0.3, + VectorThreshold: 0.5, + RerankTopK: 5, + RerankThreshold: 0.5, }, } } diff --git a/internal/types/interfaces/custom_agent.go b/internal/types/interfaces/custom_agent.go index fde98379..bf9a8c22 100644 --- a/internal/types/interfaces/custom_agent.go +++ b/internal/types/interfaces/custom_agent.go @@ -65,14 +65,15 @@ type CustomAgentRepository interface { // - Possible errors such as database connection failure, unique constraint conflicts, etc. CreateAgent(ctx context.Context, agent *types.CustomAgent) error - // GetAgentByID queries an agent by ID + // GetAgentByID queries an agent by ID and tenant // Parameters: // - ctx: Context information // - id: Agent ID + // - tenantID: Tenant ID for isolation // Returns: // - Agent object, if found // - Possible errors such as record not existing, database errors, etc. - GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) + GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) // ListAgentsByTenantID lists all agents for a specific tenant // Parameters: diff --git a/internal/types/session.go b/internal/types/session.go index d239563d..9d5cfd96 100644 --- a/internal/types/session.go +++ b/internal/types/session.go @@ -80,22 +80,22 @@ type Session struct { // Tenant ID TenantID uint64 `json:"tenant_id" gorm:"index"` - // Strategy configuration - KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID - MaxRounds int `json:"max_rounds"` // 多轮保持轮数 - EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关 - FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略 - FallbackResponse string `json:"fallback_response"` // 固定回复内容 - EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK - KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值 - VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值 - RerankModelID string `json:"rerank_model_id"` // 排序模型ID - RerankTopK int `json:"rerank_top_k"` // 排序TopK - RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值 - SummaryModelID string `json:"summary_model_id"` // 总结模型ID - SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数 - AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases) - ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选) + // // Strategy configuration + // KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID + // MaxRounds int `json:"max_rounds"` // 多轮保持轮数 + // EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关 + // FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略 + // FallbackResponse string `json:"fallback_response"` // 固定回复内容 + // EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK + // KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值 + // VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值 + // RerankModelID string `json:"rerank_model_id"` // 排序模型ID + // RerankTopK int `json:"rerank_top_k"` // 排序TopK + // RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值 + // SummaryModelID string `json:"summary_model_id"` // 总结模型ID + // SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数 + // AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases) + // ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选) CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` diff --git a/internal/types/tenant.go b/internal/types/tenant.go index 3430294e..ebafea3a 100644 --- a/internal/types/tenant.go +++ b/internal/types/tenant.go @@ -126,9 +126,7 @@ func (c *RetrieverEngines) Scan(value interface{}) error { // ConversationConfig represents the conversation configuration for normal mode type ConversationConfig struct { // Prompt is the system prompt for normal mode - UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` - Prompt string `json:"prompt"` - UseCustomContextTemplate bool `json:"use_custom_context_template"` + Prompt string `json:"prompt"` // ContextTemplate is the prompt template for summarizing retrieval results ContextTemplate string `json:"context_template"` // Temperature controls the randomness of the model output From 0ca947981aab284bb57beb53c2d625e44a8f9393 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 26 Dec 2025 21:31:02 +0800 Subject: [PATCH 11/17] =?UTF-8?q?refactor:=20=E8=B0=83=E6=95=B4=E6=99=BA?= =?UTF-8?q?=E8=83=BD=E4=BD=93=E9=85=8D=E7=BD=AE=EF=BC=8C=E5=A2=9E=E5=BC=BA?= =?UTF-8?q?=E6=99=BA=E8=83=BD=E4=BD=93=E9=80=89=E6=8B=A9=E4=B8=8E=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.yaml | 21 +- config/prompt_templates/fallback.yaml | 2 +- config/prompt_templates/rewrite_user.yaml | 17 +- frontend/src/api/agent/index.ts | 64 +- frontend/src/components/AgentAvatar.vue | 13 +- frontend/src/components/AgentSelector.vue | 30 +- frontend/src/components/Input-field.vue | 440 ++++--- frontend/src/components/UserMenu.vue | 4 - frontend/src/i18n/locales/en-US.ts | 22 +- frontend/src/i18n/locales/zh-CN.ts | 20 +- frontend/src/stores/settings.ts | 21 +- frontend/src/views/agent/AgentEditorModal.vue | 1084 +++++++++++++---- frontend/src/views/agent/AgentList.vue | 268 ++-- .../src/views/knowledge/KnowledgeBaseList.vue | 203 ++- frontend/src/views/settings/Settings.vue | 17 - internal/agent/prompts.go | 30 +- .../application/repository/custom_agent.go | 4 +- internal/application/service/agent_service.go | 56 +- .../service/chat_pipline/common.go | 9 +- .../service/chat_pipline/load_history.go | 126 ++ .../service/chat_pipline/rewrite.go | 84 +- internal/application/service/custom_agent.go | 142 ++- internal/application/service/knowledge.go | 16 +- internal/application/service/session.go | 40 +- internal/container/container.go | 1 + internal/handler/custom_agent.go | 85 +- internal/handler/session/qa.go | 4 +- internal/router/router.go | 4 + internal/types/agent.go | 3 + internal/types/chat_manage.go | 8 +- internal/types/custom_agent.go | 156 ++- internal/types/interfaces/custom_agent.go | 12 +- internal/types/placeholder.go | 165 +++ internal/types/tenant.go | 6 +- .../versioned/000006_custom_agents.down.sql | 3 +- .../versioned/000006_custom_agents.up.sql | 157 ++- 36 files changed, 2421 insertions(+), 916 deletions(-) create mode 100644 internal/application/service/chat_pipline/load_history.go create mode 100644 internal/types/placeholder.go diff --git a/config/config.yaml b/config/config.yaml index 693a7064..7cdb6e31 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -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}} 个 ## 问题类型建议 - 定义类:什么是...?...是什么? diff --git a/config/prompt_templates/fallback.yaml b/config/prompt_templates/fallback.yaml index e1902d11..5f0e722a 100644 --- a/config/prompt_templates/fallback.yaml +++ b/config/prompt_templates/fallback.yaml @@ -44,4 +44,4 @@ templates: 2. 如果问题涉及特定领域或需要最新信息,建议用户查阅官方资料 3. 保持回答的准确性和客观性 - 用户问题:{{.Query}} + 用户问题:{{query}} diff --git a/config/prompt_templates/rewrite_user.yaml b/config/prompt_templates/rewrite_user.yaml index 54e0f994..8605c1af 100644 --- a/config/prompt_templates/rewrite_user.yaml +++ b/config/prompt_templates/rewrite_user.yaml @@ -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}} ## 任务要求 请根据以上对话历史,将当前问题改写为一个独立、完整、可以脱离上下文理解的问题。 diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 43987153..927daa63 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -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'); } diff --git a/frontend/src/components/AgentAvatar.vue b/frontend/src/components/AgentAvatar.vue index 570e5181..af91eb24 100644 --- a/frontend/src/components/AgentAvatar.vue +++ b/frontend/src/components/AgentAvatar.vue @@ -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; } } diff --git a/frontend/src/components/AgentSelector.vue b/frontend/src/components/AgentSelector.vue index e8d6701f..701da0ae 100644 --- a/frontend/src/components/AgentSelector.vue +++ b/frontend/src/components/AgentSelector.vue @@ -32,8 +32,8 @@ :class="{ 'selected': currentAgentId === agent.id }" @click="selectAgent(agent)" > -
- +
+
{{ agent.name }} >({}); 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')); diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 739b9027..5d6316f5 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -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>({}); // 智能体相关状态 const agents = ref([]); 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 = { 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) => { /> - + {{ $t('input.webSearchDisabledByAgent') }} - {{ $t('input.webSearchForcedByAgent') }} + {{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }} -
+ @@ -1515,9 +1595,8 @@ onBeforeRouteUpdate((to, from, next) => {
@@ -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 }" > @@ -1540,13 +1619,20 @@ onBeforeRouteUpdate((to, from, next) => { - + +
{ 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; } diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index 969b6fe6..a835c0d8 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -24,10 +24,6 @@ Ollama
- @@ -695,13 +820,31 @@

当无法从知识库找到答案时,引导模型生成回复的提示词

+
+ 可用变量: + + + + +
-
+
+ +
+
+
+
+ +
+
{{ placeholder.description }}
+
+
+
+
@@ -732,12 +898,17 @@ import { ref, computed, watch, nextTick } from 'vue'; import { useI18n } from 'vue-i18n'; import { MessagePlugin } from 'tdesign-vue-next'; -import { createAgent, updateAgent, type CustomAgent } from '@/api/agent'; -import { listModels } from '@/api/model'; +import { createAgent, updateAgent, getPlaceholders, type CustomAgent, type PlaceholderDefinition } from '@/api/agent'; +import { listModels, type ModelConfig } from '@/api/model'; import { listKnowledgeBases } from '@/api/knowledge-base'; -import { getAgentConfig, getConversationConfig, type PlaceholderDefinition } from '@/api/system'; +import { listMCPServices, type MCPService } from '@/api/mcp-service'; +import { getAgentConfig, getConversationConfig } from '@/api/system'; +import { useUIStore } from '@/stores/ui'; import AgentAvatar from '@/components/AgentAvatar.vue'; import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue'; +import ModelSelector from '@/components/ModelSelector.vue'; + +const uiStore = useUIStore(); const { t } = useI18n(); @@ -745,6 +916,7 @@ const props = defineProps<{ visible: boolean; mode: 'create' | 'edit'; agent?: CustomAgent | null; + initialSection?: string; }>(); const emit = defineEmits<{ @@ -752,14 +924,16 @@ const emit = defineEmits<{ (e: 'success'): void; }>(); -const currentSection = ref('basic'); +const currentSection = ref(props.initialSection || 'basic'); const saving = ref(false); -const modelOptions = ref<{ label: string; value: string }[]>([]); -const rerankModelOptions = ref<{ label: string; value: string }[]>([]); +const allModels = ref([]); const kbOptions = ref<{ label: string; value: string }[]>([]); +const mcpOptions = ref<{ label: string; value: string }[]>([]); // 系统默认配置(用于内置智能体显示默认提示词) -const defaultSystemPrompt = ref(''); +const defaultSystemPrompt = ref(''); // 普通模式默认提示词 +const defaultSystemPromptWebEnabled = ref(''); // Agent模式 Web开启时默认提示词 +const defaultSystemPromptWebDisabled = ref(''); // Agent模式 Web关闭时默认提示词 const defaultContextTemplate = ref(''); const defaultRewritePromptSystem = ref(''); const defaultRewritePromptUser = ref(''); @@ -780,6 +954,9 @@ const knowledgeBaseTools = ['grep_chunks', 'knowledge_search', 'list_knowledge_c // 知识库选择模式:all=全部, selected=指定, none=不使用 const kbSelectionMode = ref<'all' | 'selected' | 'none'>('none'); +// MCP 服务选择模式:all=全部, selected=指定, none=不使用 +const mcpSelectionMode = ref<'all' | 'selected' | 'none'>('none'); + // 可用工具列表 (与后台 definitions.go 保持一致) const allTools = [ { value: 'thinking', label: '思考', description: '动态和反思性的问题解决思考工具', requiresKB: false }, @@ -797,14 +974,6 @@ const hasKnowledgeBase = computed(() => { return kbSelectionMode.value !== 'none'; }); -// 允许用户选择知识库的描述 -const allowUserKBSelectionDesc = computed(() => { - if (kbSelectionMode.value === 'all') { - return t('agent.editor.allowUserKBSelectionDescAll'); - } - return t('agent.editor.allowUserKBSelectionDescSelected'); -}); - const availableTools = computed(() => { return allTools.map(tool => ({ ...tool, @@ -812,8 +981,40 @@ const availableTools = computed(() => { })); }); -// 占位符相关 -const availablePlaceholders = ref([]); +// 占位符相关 - 从 API 获取 +const placeholderData = ref<{ + system_prompt: PlaceholderDefinition[]; + agent_system_prompt: PlaceholderDefinition[]; + context_template: PlaceholderDefinition[]; + rewrite_system_prompt: PlaceholderDefinition[]; + rewrite_prompt: PlaceholderDefinition[]; + fallback_prompt: PlaceholderDefinition[]; +}>({ + system_prompt: [], + agent_system_prompt: [], + context_template: [], + rewrite_system_prompt: [], + rewrite_prompt: [], + fallback_prompt: [], +}); + +// 系统提示词占位符(根据模式动态选择) +const availablePlaceholders = computed(() => { + return isAgentMode.value ? placeholderData.value.agent_system_prompt : placeholderData.value.system_prompt; +}); + +// 上下文模板占位符 +const contextTemplatePlaceholders = computed(() => placeholderData.value.context_template); + +// 改写系统提示词占位符 +const rewriteSystemPlaceholders = computed(() => placeholderData.value.rewrite_system_prompt); + +// 改写用户提示词占位符 +const rewritePlaceholders = computed(() => placeholderData.value.rewrite_prompt); + +// 兜底提示词占位符 +const fallbackPlaceholders = computed(() => placeholderData.value.fallback_prompt); + const promptTextareaRef = ref(null); const showPlaceholderPopup = ref(false); const selectedPlaceholderIndex = ref(0); @@ -829,13 +1030,30 @@ const contextPlaceholderPrefix = ref(''); const contextPopupStyle = ref({ top: '0px', left: '0px' }); let contextPlaceholderPopupTimer: any = null; -// 上下文模板可用的占位符 -const contextTemplatePlaceholders = computed(() => [ - { name: 'query', description: t('agent.editor.placeholderQuery') || '用户的问题' }, - { name: 'contexts', description: t('agent.editor.placeholderContexts') || '检索到的内容列表' }, - { name: 'current_time', description: t('agent.editor.placeholderCurrentTime') || '当前时间(格式:2006-01-02 15:04:05)' }, - { name: 'current_week', description: t('agent.editor.placeholderCurrentWeek') || '当前星期(如:星期一)' }, -]); +// 通用占位符弹出相关(用于改写提示词和兜底提示词) +interface PlaceholderPopupState { + show: boolean; + selectedIndex: number; + prefix: string; + style: { top: string; left: string }; + timer: any; + fieldKey: string; + placeholders: PlaceholderDefinition[]; +} + +const rewriteSystemPopup = ref({ + show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'rewrite_prompt_system', placeholders: [] +}); +const rewriteUserPopup = ref({ + show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'rewrite_prompt_user', placeholders: [] +}); +const fallbackPromptPopup = ref({ + show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'fallback_prompt', placeholders: [] +}); + +const rewriteSystemTextareaRef = ref(null); +const rewriteUserTextareaRef = ref(null); +const fallbackPromptTextareaRef = ref(null); const navItems = computed(() => { const items: { key: string; icon: string; label: string }[] = [ @@ -869,11 +1087,10 @@ const navItems = computed(() => { const defaultFormData = { name: '', description: '', - type: 'custom' as const, is_builtin: false, config: { // 基础设置 - agent_mode: 'normal' as 'normal' | 'agent', + agent_mode: 'quick-answer' as 'quick-answer' | 'smart-reasoning', system_prompt: '', system_prompt_web_enabled: '', context_template: '{{query}}', @@ -886,10 +1103,12 @@ const defaultFormData = { max_iterations: 10, allowed_tools: [] as string[], reflection_enabled: false, + // MCP 服务设置 + mcp_selection_mode: 'none' as 'all' | 'selected' | 'none', + mcp_services: [] as string[], // 知识库设置 kb_selection_mode: 'none' as 'all' | 'selected' | 'none', knowledge_bases: [] as string[], - allow_user_kb_selection: false, // 网络搜索设置 web_search_enabled: false, web_search_max_results: 5, @@ -919,29 +1138,33 @@ const defaultFormData = { const formData = ref(JSON.parse(JSON.stringify(defaultFormData))); const agentMode = computed({ get: () => formData.value.config.agent_mode, - set: (val: 'normal' | 'agent') => { formData.value.config.agent_mode = val; } + set: (val: 'quick-answer' | 'smart-reasoning') => { formData.value.config.agent_mode = val; } }); -const isAgentMode = computed(() => agentMode.value === 'agent'); +const isAgentMode = computed(() => agentMode.value === 'smart-reasoning'); // 是否为内置智能体 const isBuiltinAgent = computed(() => { return formData.value.is_builtin === true; }); -// 系统提示词的 placeholder(内置智能体显示默认提示词,自定义智能体显示普通提示) +// 系统提示词的 placeholder const systemPromptPlaceholder = computed(() => { - if (isBuiltinAgent.value && defaultSystemPrompt.value) { - return t('agent.editor.defaultPromptHint') + '\n\n' + defaultSystemPrompt.value; - } return t('agent.editor.systemPromptPlaceholder'); }); -// 上下文模板的 placeholder(内置智能体显示默认模板,自定义智能体显示普通提示) +// Agent模式 Web关闭时的 placeholder +const systemPromptWebDisabledPlaceholder = computed(() => { + return t('agent.editor.systemPromptPlaceholder'); +}); + +// Agent模式 Web开启时的 placeholder +const systemPromptWebEnabledPlaceholder = computed(() => { + return t('agent.editor.systemPromptWebEnabledPlaceholder') || '网络搜索开启时使用的系统提示词'; +}); + +// 上下文模板的 placeholder const contextTemplatePlaceholder = computed(() => { - if (isBuiltinAgent.value && defaultContextTemplate.value) { - return t('agent.editor.defaultContextTemplateHint') + '\n\n' + defaultContextTemplate.value; - } return t('agent.editor.contextTemplatePlaceholder'); }); @@ -956,7 +1179,7 @@ const needsRerankModel = computed(() => { // 监听可见性变化,重置表单 watch(() => props.visible, async (val) => { if (val) { - currentSection.value = 'basic'; + currentSection.value = props.initialSection || 'basic'; // 先加载依赖数据(包括默认配置) await loadDependencies(); @@ -976,16 +1199,22 @@ watch(() => props.visible, async (val) => { if (!agentData.config.suggested_prompts) agentData.config.suggested_prompts = []; if (!agentData.config.knowledge_bases) agentData.config.knowledge_bases = []; if (!agentData.config.allowed_tools) agentData.config.allowed_tools = []; + if (!agentData.config.mcp_services) agentData.config.mcp_services = []; // 兼容旧数据:如果没有 agent_mode 字段,根据 allowed_tools 推断 if (!agentData.config.agent_mode) { const isAgent = agentData.config.max_iterations > 1 || (agentData.config.allowed_tools && agentData.config.allowed_tools.length > 0); - agentData.config.agent_mode = isAgent ? 'agent' : 'normal'; + agentData.config.agent_mode = isAgent ? 'smart-reasoning' : 'quick-answer'; } formData.value = agentData; // 初始化知识库选择模式 initKbSelectionMode(); + initMcpSelectionMode(); + // 内置智能体:如果提示词为空,填入系统默认值 + if (agentData.is_builtin) { + fillBuiltinAgentDefaults(); + } } else { // 创建新智能体,使用系统默认值 const newFormData = JSON.parse(JSON.stringify(defaultFormData)); @@ -1003,6 +1232,7 @@ watch(() => props.visible, async (val) => { } formData.value = newFormData; kbSelectionMode.value = 'none'; + mcpSelectionMode.value = 'none'; } } }); @@ -1015,21 +1245,68 @@ const initKbSelectionMode = () => { } else if (formData.value.config.knowledge_bases?.length > 0) { // 有指定知识库 kbSelectionMode.value = 'selected'; - } else if (formData.value.config.allow_user_kb_selection) { - // 允许用户选择(旧数据兼容:没有指定知识库但允许选择 = 全部) - kbSelectionMode.value = 'all'; } else { kbSelectionMode.value = 'none'; } }; +// 初始化 MCP 选择模式 +const initMcpSelectionMode = () => { + if (formData.value.config.mcp_selection_mode) { + // 如果有保存的模式,直接使用 + mcpSelectionMode.value = formData.value.config.mcp_selection_mode; + } else if (formData.value.config.mcp_services?.length > 0) { + // 有指定 MCP 服务 + mcpSelectionMode.value = 'selected'; + } else { + mcpSelectionMode.value = 'none'; + } +}; + +// 内置智能体:填入系统默认值 +const fillBuiltinAgentDefaults = () => { + const config = formData.value.config; + const isAgent = config.agent_mode === 'smart-reasoning'; + + if (isAgent) { + // Agent 模式:填入 Web 开启/关闭的默认提示词 + if (!config.system_prompt && defaultSystemPromptWebDisabled.value) { + config.system_prompt = defaultSystemPromptWebDisabled.value; + } + if (!config.system_prompt_web_enabled && defaultSystemPromptWebEnabled.value) { + config.system_prompt_web_enabled = defaultSystemPromptWebEnabled.value; + } + } else { + // 普通模式:填入默认系统提示词和上下文模板 + if (!config.system_prompt && defaultSystemPrompt.value) { + config.system_prompt = defaultSystemPrompt.value; + } + if (!config.context_template && defaultContextTemplate.value) { + config.context_template = defaultContextTemplate.value; + } + } + + // 通用默认值 + if (!config.rewrite_prompt_system && defaultRewritePromptSystem.value) { + config.rewrite_prompt_system = defaultRewritePromptSystem.value; + } + if (!config.rewrite_prompt_user && defaultRewritePromptUser.value) { + config.rewrite_prompt_user = defaultRewritePromptUser.value; + } + if (!config.fallback_prompt && defaultFallbackPrompt.value) { + config.fallback_prompt = defaultFallbackPrompt.value; + } + if (!config.fallback_response && defaultFallbackResponse.value) { + config.fallback_response = defaultFallbackResponse.value; + } +}; + // 监听知识库选择模式变化 watch(kbSelectionMode, (mode) => { formData.value.config.kb_selection_mode = mode; if (mode === 'none') { // 不使用知识库,清空相关配置 formData.value.config.knowledge_bases = []; - formData.value.config.allow_user_kb_selection = false; } else if (mode === 'all') { // 全部知识库,清空指定列表 formData.value.config.knowledge_bases = []; @@ -1037,9 +1314,22 @@ watch(kbSelectionMode, (mode) => { // selected 模式保持 knowledge_bases 不变 }); +// 监听 MCP 选择模式变化 +watch(mcpSelectionMode, (mode) => { + formData.value.config.mcp_selection_mode = mode; + if (mode === 'none') { + // 不使用 MCP,清空相关配置 + formData.value.config.mcp_services = []; + } else if (mode === 'all') { + // 全部 MCP,清空指定列表 + formData.value.config.mcp_services = []; + } + // selected 模式保持 mcp_services 不变 +}); + // 监听模式变化,自动调整配置 watch(agentMode, (val) => { - if (val === 'agent') { + if (val === 'smart-reasoning') { // 切换到 Agent 模式,根据知识库配置启用工具 if (formData.value.config.allowed_tools.length === 0) { if (hasKnowledgeBase.value) { @@ -1106,16 +1396,10 @@ watch(isAgentMode, (isAgent) => { // 加载依赖数据 const loadDependencies = async () => { try { - // 加载模型列表 (只加载 KnowledgeQA 类型的模型) - const models = await listModels('KnowledgeQA'); + // 加载所有模型列表(ModelSelector 组件会自动按类型过滤) + const models = await listModels(); if (models && models.length > 0) { - modelOptions.value = models.map((m: any) => ({ label: m.name || m.id, value: m.id })); - } - - // 加载 ReRank 模型列表 - const rerankModels = await listModels('Rerank'); - if (rerankModels && rerankModels.length > 0) { - rerankModelOptions.value = rerankModels.map((m: any) => ({ label: m.name || m.id, value: m.id })); + allModels.value = models; } // 加载知识库列表 @@ -1124,10 +1408,35 @@ const loadDependencies = async () => { kbOptions.value = kbRes.data.map((kb: any) => ({ label: kb.name, value: kb.id })); } - // 加载可用占位符 + // 加载 MCP 服务列表(只加载启用的) + try { + const mcpList = await listMCPServices(); + if (mcpList && mcpList.length > 0) { + mcpOptions.value = mcpList + .filter((mcp: MCPService) => mcp.enabled) + .map((mcp: MCPService) => ({ label: mcp.name, value: mcp.id })); + } + } catch (e) { + console.warn('Failed to load MCP services', e); + } + + // 加载占位符定义(从统一 API) + try { + const placeholdersRes = await getPlaceholders(); + if (placeholdersRes.data) { + placeholderData.value = placeholdersRes.data; + } + } catch (e) { + console.warn('Failed to load placeholders', e); + } + + // 加载 Agent 模式默认提示词 const agentConfig = await getAgentConfig(); - if (agentConfig.data?.available_placeholders) { - availablePlaceholders.value = agentConfig.data.available_placeholders; + if (agentConfig.data?.system_prompt_web_enabled) { + defaultSystemPromptWebEnabled.value = agentConfig.data.system_prompt_web_enabled; + } + if (agentConfig.data?.system_prompt_web_disabled) { + defaultSystemPromptWebDisabled.value = agentConfig.data.system_prompt_web_disabled; } // 加载系统默认配置(用于内置智能体显示默认提示词) @@ -1177,9 +1486,17 @@ const loadDependencies = async () => { } }; +// 跳转到模型管理页面添加模型 +const handleAddModel = (subSection: string) => { + uiStore.openSettings('models', subSection); +}; + const handleClose = () => { showPlaceholderPopup.value = false; showContextPlaceholderPopup.value = false; + rewriteSystemPopup.value.show = false; + rewriteUserPopup.value.show = false; + fallbackPromptPopup.value.show = false; emit('update:visible', false); }; @@ -1205,6 +1522,39 @@ const filteredContextPlaceholders = computed(() => { ); }); +// 过滤后的改写系统提示词占位符列表 +const filteredRewriteSystemPlaceholders = computed(() => { + if (!rewriteSystemPopup.value.prefix) { + return rewriteSystemPlaceholders.value; + } + const prefix = rewriteSystemPopup.value.prefix.toLowerCase(); + return rewriteSystemPlaceholders.value.filter(p => + p.name.toLowerCase().startsWith(prefix) + ); +}); + +// 过滤后的改写用户提示词占位符列表 +const filteredRewriteUserPlaceholders = computed(() => { + if (!rewriteUserPopup.value.prefix) { + return rewritePlaceholders.value; + } + const prefix = rewriteUserPopup.value.prefix.toLowerCase(); + return rewritePlaceholders.value.filter(p => + p.name.toLowerCase().startsWith(prefix) + ); +}); + +// 过滤后的兜底提示词占位符列表 +const filteredFallbackPlaceholders = computed(() => { + if (!fallbackPromptPopup.value.prefix) { + return fallbackPlaceholders.value; + } + const prefix = fallbackPromptPopup.value.prefix.toLowerCase(); + return fallbackPlaceholders.value.filter(p => + p.name.toLowerCase().startsWith(prefix) + ); +}); + // 获取 textarea 元素 const getTextareaElement = (): HTMLTextAreaElement | null => { if (promptTextareaRef.value) { @@ -1310,7 +1660,7 @@ const handlePromptInput = () => { }; // 插入占位符 -const insertPlaceholder = (placeholderName: string) => { +const insertPlaceholder = (placeholderName: string, fromPopup: boolean = false) => { const textarea = getTextareaElement(); if (!textarea) return; @@ -1320,30 +1670,43 @@ const insertPlaceholder = (placeholderName: string) => { nextTick(() => { const cursorPos = textarea.selectionStart; - const currentValue = formData.value.config.system_prompt; + const currentValue = formData.value.config.system_prompt || ''; const textBeforeCursor = currentValue.substring(0, cursorPos); const textAfterCursor = currentValue.substring(cursorPos); - // 找到 {{ 的位置 - let lastOpenPos = -1; - for (let i = textBeforeCursor.length - 1; i >= 1; i--) { - if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') { - lastOpenPos = i - 1; - break; + // 只有从下拉列表选择时才查找 {{ 并替换 + if (fromPopup) { + let lastOpenPos = -1; + for (let i = textBeforeCursor.length - 1; i >= 1; i--) { + if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') { + lastOpenPos = i - 1; + break; + } + } + + if (lastOpenPos !== -1) { + const textBeforeOpen = currentValue.substring(0, lastOpenPos); + const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor; + formData.value.config.system_prompt = newValue; + + nextTick(() => { + const newCursorPos = textBeforeOpen.length + placeholderName.length + 4; + textarea.setSelectionRange(newCursorPos, newCursorPos); + textarea.focus(); + }); + return; } } - if (lastOpenPos !== -1) { - const textBeforeOpen = currentValue.substring(0, lastOpenPos); - const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor; - formData.value.config.system_prompt = newValue; - - nextTick(() => { - const newCursorPos = textBeforeOpen.length + placeholderName.length + 4; - textarea.setSelectionRange(newCursorPos, newCursorPos); - textarea.focus(); - }); - } + // 直接在光标位置插入完整占位符 + const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor; + formData.value.config.system_prompt = newValue; + + nextTick(() => { + const newCursorPos = cursorPos + placeholderName.length + 4; + textarea.setSelectionRange(newCursorPos, newCursorPos); + textarea.focus(); + }); }); }; @@ -1449,7 +1812,7 @@ const handleContextTemplateInput = () => { }; // 插入上下文模板占位符 -const insertContextPlaceholder = (placeholderName: string) => { +const insertContextPlaceholder = (placeholderName: string, fromPopup: boolean = false) => { const textarea = getContextTemplateTextareaElement(); if (!textarea) return; @@ -1459,29 +1822,238 @@ const insertContextPlaceholder = (placeholderName: string) => { nextTick(() => { const cursorPos = textarea.selectionStart; - const currentValue = formData.value.config.context_template; + const currentValue = formData.value.config.context_template || ''; const textBeforeCursor = currentValue.substring(0, cursorPos); const textAfterCursor = currentValue.substring(cursorPos); - let lastOpenPos = -1; - for (let i = textBeforeCursor.length - 1; i >= 1; i--) { - if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') { + // 只有从下拉列表选择时才查找 {{ 并替换 + if (fromPopup) { + let lastOpenPos = -1; + for (let i = textBeforeCursor.length - 1; i >= 1; i--) { + if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') { + lastOpenPos = i - 1; + break; + } + } + + if (lastOpenPos !== -1) { + const textBeforeOpen = currentValue.substring(0, lastOpenPos); + const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor; + formData.value.config.context_template = newValue; + + nextTick(() => { + const newCursorPos = textBeforeOpen.length + placeholderName.length + 4; + textarea.setSelectionRange(newCursorPos, newCursorPos); + textarea.focus(); + }); + return; + } + } + + // 直接在光标位置插入完整占位符 + const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor; + formData.value.config.context_template = newValue; + + nextTick(() => { + const newCursorPos = cursorPos + placeholderName.length + 4; + textarea.setSelectionRange(newCursorPos, newCursorPos); + textarea.focus(); + }); + }); +}; + +// 通用获取 textarea 元素 +const getGenericTextareaElement = (type: 'rewriteSystem' | 'rewriteUser' | 'fallback'): HTMLTextAreaElement | null => { + const refMap = { + rewriteSystem: rewriteSystemTextareaRef, + rewriteUser: rewriteUserTextareaRef, + fallback: fallbackPromptTextareaRef, + }; + const ref = refMap[type]; + if (ref.value) { + if (ref.value.$el) { + return ref.value.$el.querySelector('textarea'); + } + if (ref.value instanceof HTMLTextAreaElement) { + return ref.value; + } + } + return null; +}; + +// 通用计算光标位置 +const calculateGenericCursorPosition = (textarea: HTMLTextAreaElement, fieldValue: string) => { + const cursorPos = textarea.selectionStart; + const textBeforeCursor = fieldValue.substring(0, cursorPos); + const lines = textBeforeCursor.split('\n'); + const currentLine = lines.length - 1; + const currentLineText = lines[currentLine]; + + const textareaRect = textarea.getBoundingClientRect(); + const style = window.getComputedStyle(textarea); + const lineHeight = parseFloat(style.lineHeight) || 20; + const paddingTop = parseFloat(style.paddingTop) || 0; + const paddingLeft = parseFloat(style.paddingLeft) || 0; + + const span = document.createElement('span'); + span.style.font = style.font; + span.style.visibility = 'hidden'; + span.style.position = 'absolute'; + span.style.whiteSpace = 'pre'; + span.textContent = currentLineText; + document.body.appendChild(span); + const textWidth = span.offsetWidth; + document.body.removeChild(span); + + const scrollTop = textarea.scrollTop; + const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4; + const scrollLeft = textarea.scrollLeft; + const left = textareaRect.left + paddingLeft + textWidth - scrollLeft; + + return { top, left }; +}; + +// 通用检查并显示占位符弹出 +const checkAndShowGenericPlaceholderPopup = ( + type: 'rewriteSystem' | 'rewriteUser' | 'fallback', + popup: typeof rewriteSystemPopup, + fieldKey: keyof typeof formData.value.config, + filteredPlaceholders: PlaceholderDefinition[] +) => { + const textarea = getGenericTextareaElement(type); + if (!textarea) return; + + const cursorPos = textarea.selectionStart; + const fieldValue = String(formData.value.config[fieldKey] || ''); + const textBeforeCursor = fieldValue.substring(0, cursorPos); + + let lastOpenPos = -1; + for (let i = textBeforeCursor.length - 1; i >= 1; i--) { + if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') { + const textAfterOpen = textBeforeCursor.substring(i + 1); + if (!textAfterOpen.includes('}}')) { lastOpenPos = i - 1; break; } } + } + + if (lastOpenPos === -1) { + popup.value.show = false; + popup.value.prefix = ''; + return; + } + + const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2); + popup.value.prefix = textAfterOpen; + + if (filteredPlaceholders.length > 0) { + nextTick(() => { + const position = calculateGenericCursorPosition(textarea, fieldValue); + popup.value.style = { + top: `${position.top}px`, + left: `${position.left}px` + }; + popup.value.show = true; + popup.value.selectedIndex = 0; + }); + } else { + popup.value.show = false; + } +}; + +// 处理改写系统提示词输入 +const handleRewriteSystemInput = () => { + if (rewriteSystemPopup.value.timer) { + clearTimeout(rewriteSystemPopup.value.timer); + } + rewriteSystemPopup.value.timer = setTimeout(() => { + checkAndShowGenericPlaceholderPopup('rewriteSystem', rewriteSystemPopup, 'rewrite_prompt_system', filteredRewriteSystemPlaceholders.value); + }, 50); +}; + +// 处理改写用户提示词输入 +const handleRewriteUserInput = () => { + if (rewriteUserPopup.value.timer) { + clearTimeout(rewriteUserPopup.value.timer); + } + rewriteUserPopup.value.timer = setTimeout(() => { + checkAndShowGenericPlaceholderPopup('rewriteUser', rewriteUserPopup, 'rewrite_prompt_user', filteredRewriteUserPlaceholders.value); + }, 50); +}; + +// 处理兜底提示词输入 +const handleFallbackPromptInput = () => { + if (fallbackPromptPopup.value.timer) { + clearTimeout(fallbackPromptPopup.value.timer); + } + fallbackPromptPopup.value.timer = setTimeout(() => { + checkAndShowGenericPlaceholderPopup('fallback', fallbackPromptPopup, 'fallback_prompt', filteredFallbackPlaceholders.value); + }, 50); +}; + +// 通用插入占位符 +const insertGenericPlaceholder = (type: 'rewriteSystem' | 'rewriteUser' | 'fallback', placeholderName: string, fromPopup: boolean = false) => { + const textarea = getGenericTextareaElement(type); + if (!textarea) return; + + const popupMap = { + rewriteSystem: rewriteSystemPopup, + rewriteUser: rewriteUserPopup, + fallback: fallbackPromptPopup, + }; + const fieldKeyMap: Record = { + rewriteSystem: 'rewrite_prompt_system', + rewriteUser: 'rewrite_prompt_user', + fallback: 'fallback_prompt', + }; + + const popup = popupMap[type]; + const fieldKey = fieldKeyMap[type]; + + popup.value.show = false; + popup.value.prefix = ''; + popup.value.selectedIndex = 0; + + nextTick(() => { + const cursorPos = textarea.selectionStart; + const currentValue = String(formData.value.config[fieldKey] || ''); + const textBeforeCursor = currentValue.substring(0, cursorPos); + const textAfterCursor = currentValue.substring(cursorPos); - if (lastOpenPos !== -1) { - const textBeforeOpen = currentValue.substring(0, lastOpenPos); - const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor; - formData.value.config.context_template = newValue; + // 只有从下拉列表选择时才查找 {{ 并替换 + if (fromPopup) { + let lastOpenPos = -1; + for (let i = textBeforeCursor.length - 1; i >= 1; i--) { + if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') { + lastOpenPos = i - 1; + break; + } + } - nextTick(() => { - const newCursorPos = textBeforeOpen.length + placeholderName.length + 4; - textarea.setSelectionRange(newCursorPos, newCursorPos); - textarea.focus(); - }); + if (lastOpenPos !== -1) { + const textBeforeOpen = currentValue.substring(0, lastOpenPos); + const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor; + (formData.value.config as any)[fieldKey] = newValue; + + nextTick(() => { + const newCursorPos = textBeforeOpen.length + placeholderName.length + 4; + textarea.setSelectionRange(newCursorPos, newCursorPos); + textarea.focus(); + }); + return; + } } + + // 直接在光标位置插入完整占位符 + const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor; + (formData.value.config as any)[fieldKey] = newValue; + + nextTick(() => { + const newCursorPos = cursorPos + placeholderName.length + 4; + textarea.setSelectionRange(newCursorPos, newCursorPos); + textarea.focus(); + }); }); }; @@ -1513,7 +2085,7 @@ const setupContextTemplateEventListeners = () => { e.stopPropagation(); const selected = filteredContextPlaceholders.value[selectedContextPlaceholderIndex.value]; if (selected) { - insertContextPlaceholder(selected.name); + insertContextPlaceholder(selected.name, true); } } else if (e.key === 'Escape') { e.preventDefault(); @@ -1555,7 +2127,7 @@ const setupTextareaEventListeners = () => { e.stopPropagation(); const selected = filteredPlaceholders.value[selectedPlaceholderIndex.value]; if (selected) { - insertPlaceholder(selected.name); + insertPlaceholder(selected.name, true); } } else if (e.key === 'Escape') { e.preventDefault(); @@ -1569,12 +2141,73 @@ const setupTextareaEventListeners = () => { }); }; +// 通用设置 textarea 事件监听 +const setupGenericTextareaEventListeners = ( + type: 'rewriteSystem' | 'rewriteUser' | 'fallback', + popup: typeof rewriteSystemPopup, + filteredPlaceholders: () => PlaceholderDefinition[] +) => { + nextTick(() => { + const textarea = getGenericTextareaElement(type); + if (textarea) { + textarea.addEventListener('keydown', (e: KeyboardEvent) => { + const filtered = filteredPlaceholders(); + if (popup.value.show && filtered.length > 0) { + if (e.key === 'ArrowDown') { + e.preventDefault(); + e.stopPropagation(); + if (popup.value.selectedIndex < filtered.length - 1) { + popup.value.selectedIndex++; + } else { + popup.value.selectedIndex = 0; + } + } else if (e.key === 'ArrowUp') { + e.preventDefault(); + e.stopPropagation(); + if (popup.value.selectedIndex > 0) { + popup.value.selectedIndex--; + } else { + popup.value.selectedIndex = filtered.length - 1; + } + } else if (e.key === 'Enter' || e.key === 'Tab') { + e.preventDefault(); + e.stopPropagation(); + const selected = filtered[popup.value.selectedIndex]; + if (selected) { + insertGenericPlaceholder(type, selected.name, true); + } + } else if (e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + popup.value.show = false; + popup.value.prefix = ''; + } + } + }, true); + } + }); +}; + +// 处理点击占位符标签 +const handlePlaceholderClick = (type: 'system' | 'context' | 'rewriteSystem' | 'rewriteUser' | 'fallback', placeholderName: string) => { + if (type === 'system') { + insertPlaceholder(placeholderName); + } else if (type === 'context') { + insertContextPlaceholder(placeholderName); + } else { + insertGenericPlaceholder(type, placeholderName); + } +}; + // 监听 visible 变化设置事件监听 watch(() => props.visible, (val) => { if (val) { nextTick(() => { setupTextareaEventListeners(); setupContextTemplateEventListeners(); + setupGenericTextareaEventListeners('rewriteSystem', rewriteSystemPopup, () => filteredRewriteSystemPlaceholders.value); + setupGenericTextareaEventListeners('rewriteUser', rewriteUserPopup, () => filteredRewriteUserPlaceholders.value); + setupGenericTextareaEventListeners('fallback', fallbackPromptPopup, () => filteredFallbackPlaceholders.value); }); } }); @@ -1650,11 +2283,6 @@ const handleSave = async () => { formData.value.config.suggested_prompts = formData.value.config.suggested_prompts.filter((p: string) => p.trim() !== ''); } - // 确保类型设置正确(内置智能体保持原类型) - if (!isBuiltinAgent.value) { - formData.value.type = 'custom'; - } - saving.value = true; try { if (props.mode === 'create') { @@ -1854,6 +2482,11 @@ const handleSave = async () => { &.setting-row-vertical { flex-direction: column; gap: 12px; + + .setting-info { + max-width: 100%; + padding-right: 0; + } } } @@ -2194,46 +2827,64 @@ const handleSave = async () => { } } -// 占位符提示样式 -.placeholder-hint { - margin-top: 12px; - padding: 12px; - background: #f8fafc; - border-radius: 6px; - border: 1px solid #e1e8ed; +// 占位符标签组样式 +.placeholder-tags { + margin-top: 6px; + display: flex; + align-items: center; + gap: 5px; font-size: 12px; - max-width: 480px; - - .hint-title { - font-weight: 500; - color: #333; - margin: 0 0 8px 0; + line-height: 1.4; + overflow-x: auto; + white-space: nowrap; + padding-bottom: 4px; + + // 隐藏滚动条但保持可滚动 + scrollbar-width: thin; + &::-webkit-scrollbar { + height: 4px; + } + &::-webkit-scrollbar-thumb { + background: rgba(0, 0, 0, 0.1); + border-radius: 2px; } - .placeholder-list { - margin: 8px 0; - padding-left: 20px; - color: #666; + .placeholder-label { + color: var(--td-text-color-secondary, #666); + flex-shrink: 0; + } - li { - margin: 4px 0; + .placeholder-hint { + color: var(--td-text-color-placeholder, #999); + font-size: 11px; + user-select: none; + flex-shrink: 0; + } - code { - background: #fff; - padding: 2px 6px; - border-radius: 3px; - font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; - font-size: 11px; - color: #e83e8c; - border: 1px solid #e1e8ed; - } + .placeholder-tag { + display: inline-flex; + align-items: center; + padding: 1px 5px; + border-radius: 3px; + font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; + font-size: 11px; + color: var(--td-text-color-primary, #333); + background-color: var(--td-bg-color-secondarycontainer, #f3f3f3); + cursor: pointer; + transition: all 0.2s; + user-select: none; + border: 1px solid transparent; + flex-shrink: 0; + + &:hover { + color: var(--td-brand-color, #0052d9); + background-color: var(--td-brand-color-light, #ecf2fe); + border-color: var(--td-brand-color-focus, #d0e0fd); } - } - .hint-tip { - margin: 8px 0 0 0; - color: #999; - font-style: italic; + &:active { + background-color: var(--td-brand-color-focus, #d0e0fd); + } } } @@ -2244,43 +2895,43 @@ const handleSave = async () => { } .placeholder-popup { - background: #fff; - border: 1px solid #e5e7eb; - border-radius: 4px; - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); - max-width: 400px; - max-height: 300px; + background: var(--td-bg-color-container, #fff); + border: 1px solid var(--td-component-stroke, #e5e7eb); + border-radius: 6px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12); + max-width: 320px; + max-height: 240px; overflow-y: auto; - padding: 4px 0; + padding: 4px; } .placeholder-item { - padding: 8px 12px; + padding: 6px 10px; cursor: pointer; - transition: background-color 0.2s; + transition: background-color 0.15s; + border-radius: 4px; &:hover, &.active { - background-color: #f5f7fa; + background-color: var(--td-bg-color-container-hover, #f5f7fa); } .placeholder-name { - font-weight: 500; - margin-bottom: 4px; + margin-bottom: 2px; code { - background: #f5f7fa; - padding: 2px 6px; + background: var(--td-bg-color-container-hover, #f5f7fa); + padding: 2px 5px; border-radius: 3px; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; - font-size: 12px; - color: #e83e8c; + font-size: 11px; + color: var(--td-brand-color, #0052d9); } } .placeholder-desc { - font-size: 12px; - color: #666; + font-size: 11px; + color: var(--td-text-color-secondary, #666); } } @@ -2303,6 +2954,27 @@ const handleSave = async () => { } } +// 内置智能体头像 +.builtin-avatar { + display: flex; + align-items: center; + justify-content: center; + width: 48px; + height: 48px; + border-radius: 12px; + 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; + } +} + // 提示词开关 .prompt-toggle { display: flex; diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue index f218a83d..f373d49c 100644 --- a/frontend/src/views/agent/AgentList.vue +++ b/frontend/src/views/agent/AgentList.vue @@ -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 @@
- - {{ agent.name }} -
- - {{ $t('agent.builtin') }} + +
+
+ + + {{ agent.name }}
{{ $t('common.edit') }}
- - -
- -
@@ -87,11 +87,12 @@
-
- - {{ agent.config?.agent_mode === 'agent' ? $t('agent.mode.agent') : $t('agent.mode.normal') }} -
+ +
+ +
+
- {{ formatDate(agent.updated_at) }} +
+ + {{ $t('agent.builtin') }} +
+ {{ formatDate(agent.updated_at) }}
@@ -149,6 +154,7 @@ :visible="editorVisible" :mode="editorMode" :agent="editingAgent" + :initialSection="editorInitialSection" @update:visible="editorVisible = $event" @success="handleEditorSuccess" /> @@ -157,14 +163,17 @@