Merge pull request #493 from lyingbug/main

Custom Agent System
main
lyingbug 2025-12-29 17:55:20 +08:00 committed by GitHub
commit 002f1c40fa
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
77 changed files with 10212 additions and 1981 deletions

View File

@ -2,6 +2,68 @@
All notable changes to this project will be documented in this file.
## [0.2.6] - 2025-12-29
### 🚀 New Features
- **NEW**: Custom Agent System
- Support for creating, configuring, and selecting custom agents
- Agent feature indicators display with MCP service capability support
- Built-in agent sorting logic ensuring multi-turn conversation auto-enabled in agent mode
- Agent knowledge base selection modes: all/specified/disabled
- **NEW**: Helm Chart for Kubernetes Deployment
- Complete Helm chart for Kubernetes deployment
- Neo4j template support for GraphRAG functionality
- Versioned image tags and official images compatibility
- **NEW**: Enhanced FAQ Management
- FAQ entry retrieval API supporting single entry query by ID
- FAQ list sorting by update time (ascending/descending)
- Enhanced FAQ search with field-specific search (standard question/similar questions/answer/all)
- Batch update exclusion for FAQ entries in ByTag operations
- Tag deletion with content_only mode to delete only tag contents
- **NEW**: Multi-Platform Model Adaptation
- Support for multiple platform model configurations
- Title generation model configuration
- Knowledge base selection mode without mandatory rerank model check
- **NEW**: Korean Language Support
- Added Korean (한국어) internationalization support
### ⚡ Improvements
- **IMPROVED**: Knowledge Base Operations
- Async knowledge base deletion with background cleanup via ProcessKBDelete
- Multi-knowledge base search support with specified file ID filtering
- Optimized knowledge chunk pagination with type-specific search and sorting logic
- Enhanced SearchKnowledgeRequest structure with backward compatibility
- **IMPROVED**: Prompt Template System
- Restructured prompt template system with multi-scenario template configuration
- Unified system prompts with optimized agent selector interface
- **IMPROVED**: Tag Management
- Enhanced tag deletion with ID exclusion support
- Async index deletion task for optimized deletion flow
- Batch TagID update functionality
- Optimized tag name batch queries for improved efficiency
- **IMPROVED**: API Documentation
- Updated API documentation links to new paths
- Added knowledge search API documentation
- Enhanced FAQ and tag deletion interface documentation
- Removed hardcoded host configuration from Swagger docs
### 🐛 Bug Fixes
- **FIXED**: Tag ID handling logic for empty strings and UntaggedTagID conditions
- **FIXED**: JSON query compatibility for different database types (MySQL/PostgreSQL)
- **FIXED**: GORM batch insert issue where zero-value fields (IsEnabled, Flags) were ignored
- **FIXED**: Helm chart versioned image tags and runAsNonRoot compatibility
### 🔧 Refactoring
- **REFACTORED**: Removed security validation and length limits, simplified input processing logic
- **REFACTORED**: Enhanced agent configuration with improved selection and state management
## [0.2.5] - 2025-12-22
### 🚀 New Features
@ -397,6 +459,7 @@ All notable changes to this project will be documented in this file.
- Docker Compose for quick startup and service orchestration.
- MCP server support for integrating with MCP-compatible clients.
[0.2.6]: https://github.com/Tencent/WeKnora/tree/v0.2.6
[0.2.5]: https://github.com/Tencent/WeKnora/tree/v0.2.5
[0.2.4]: https://github.com/Tencent/WeKnora/tree/v0.2.4
[0.2.3]: https://github.com/Tencent/WeKnora/tree/v0.2.3

View File

@ -22,7 +22,7 @@
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
</a>
<a href="./CHANGELOG.md">
<img alt="Version" src="https://img.shields.io/badge/version-0.2.5-2e6cc4?labelColor=d4eaf7">
<img alt="Version" src="https://img.shields.io/badge/version-0.2.6-2e6cc4?labelColor=d4eaf7">
</a>
</p>

View File

@ -22,7 +22,7 @@
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
</a>
<a href="./CHANGELOG.md">
<img alt="版本" src="https://img.shields.io/badge/version-0.2.5-2e6cc4?labelColor=d4eaf7">
<img alt="版本" src="https://img.shields.io/badge/version-0.2.6-2e6cc4?labelColor=d4eaf7">
</a>
</p>

View File

@ -22,7 +22,7 @@
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
</a>
<a href="./CHANGELOG.md">
<img alt="バージョン" src="https://img.shields.io/badge/version-0.2.5-2e6cc4?labelColor=d4eaf7">
<img alt="バージョン" src="https://img.shields.io/badge/version-0.2.6-2e6cc4?labelColor=d4eaf7">
</a>
</p>

View File

@ -1 +1 @@
0.2.5
0.2.6

View File

@ -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:
@ -182,7 +177,6 @@ conversation:
prompt: |
你是一个专业的智能信息检索助手,名为WeKnora。你犹如专业的高级秘书,依据检索到的信息回答用户问题,不能利用任何先验知识。
当用户提出问题时,助手会基于特定的信息进行解答。助手首先在心中思考推理过程,然后向用户提供答案。
context_template: |
## 回答问题规则
- 仅根据检索到的信息中的事实进行回复,不得运用任何先验知识,保持回应的客观性和准确性。
- 复杂问题和答案的按Markdown分结构展示,总述部分不需要拆分
@ -195,18 +189,7 @@ conversation:
- 以Markdown图文格式输出你的最终结果
- 输出内容要保证简短且全面,条理清晰,信息明确,不重复。
## 当前时间是:
{{.CurrentTime}} {{.CurrentWeek}}
## 检索到的信息如下:
------BEGIN------
{{range .Contexts}}
{{.}}
{{end}}
------END------
## 用户当前的问题是:
{{.Query}}
context_template: "{{query}}"
extract_entities_prompt: |
## 任务
用户提供的文本中,提取所有符合以下实体类型的实体:
@ -495,11 +478,11 @@ conversation:
generate_questions_prompt: |
你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
{{.Context}}
{{context}}
## 主要内容(请基于此内容生成问题)
文档名称:{{.DocName}}
文档名称:{{doc_name}}
文档内容:
{{.Content}}
{{content}}
## 核心要求
- 生成的问题必须与【主要内容】直接相关
@ -508,7 +491,7 @@ conversation:
- 问题应该是用户在实际场景中可能会提出的自然问题
- 问题应该多样化,覆盖内容的不同方面
- 每个问题应该简洁明了,长度控制在30字以内
- 生成的问题数量为 {{.QuestionCount}} 个
- 生成的问题数量为 {{question_count}} 个
## 问题类型建议
- 定义类:什么是...?...是什么?

View File

@ -0,0 +1,65 @@
# 上下文模板
templates:
- id: "default_context"
name: "标准模板"
description: "标准的上下文格式化模板"
has_knowledge_base: true
content: |
请根据以下参考资料回答用户问题。
参考资料:
{{contexts}}
用户问题:{{query}}
请基于上述参考资料进行回答。如果参考资料不足以回答问题,请明确告知。
- id: "detailed_context"
name: "详细模板"
description: "包含详细说明的上下文模板"
has_knowledge_base: true
content: |
## 任务说明
请根据提供的参考资料,准确、全面地回答用户问题。
## 参考资料
{{contexts}}
## 用户问题
{{query}}
## 回答要求
1. 仅基于参考资料回答,不要编造信息
2. 如果多个资料有冲突,请综合分析
3. 适当引用来源,增强可信度
4. 如果资料不足,请明确说明
当前时间:{{current_time}} {{current_week}}
- id: "simple_context"
name: "简洁模板"
description: "简洁的上下文模板"
has_knowledge_base: true
content: |
参考资料:
{{contexts}}
问题:{{query}}
请回答上述问题。
- id: "qa_context"
name: "问答模板"
description: "问答场景专用模板"
has_knowledge_base: true
content: |
你需要回答一个问题。以下是可能相关的资料:
{{contexts}}
用户的问题是:{{query}}
请基于以上资料回答问题。回答要求:
- 直接回答问题,不要重复问题
- 如果资料中没有相关信息,请说明
- 保持回答简洁准确

View File

@ -0,0 +1,47 @@
# 兜底提示词模板
templates:
- id: "default_fallback"
name: "标准兜底"
description: "标准的兜底回复模板"
content: |
抱歉,我在知识库中没有找到与您问题直接相关的内容。
您可以尝试:
1. 换一种方式描述您的问题
2. 提供更多具体信息
3. 咨询相关领域的专业人员
如果您有其他问题,我很乐意继续为您服务。
- id: "polite_fallback"
name: "礼貌兜底"
description: "更加礼貌友好的兜底回复"
content: |
非常抱歉,目前我无法为您提供这个问题的准确答案。这可能是因为:
- 该问题超出了我的知识范围
- 知识库中暂无相关内容
建议您:
1. 尝试用不同的关键词重新提问
2. 将问题拆分为更具体的小问题
3. 联系人工客服获取帮助
感谢您的理解,期待能在其他问题上帮助到您!
- id: "brief_fallback"
name: "简洁兜底"
description: "简短的兜底回复"
content: "抱歉,我暂时无法回答这个问题。请尝试换一种方式提问,或联系人工客服。"
- id: "model_fallback"
name: "模型兜底"
description: "交给模型继续生成的兜底提示词"
content: |
知识库中没有找到与用户问题直接相关的内容。请根据你的通用知识,尽可能帮助用户解答问题。
注意事项:
1. 明确告知用户这是基于通用知识的回答,而非知识库内容
2. 如果问题涉及特定领域或需要最新信息,建议用户查阅官方资料
3. 保持回答的准确性和客观性
用户问题:{{query}}

View File

@ -0,0 +1,30 @@
# 改写系统提示词模板
templates:
- id: "default_rewrite_system"
name: "标准改写"
description: "标准的问题改写系统提示词"
content: |
你是一个专业的问题改写助手。你的任务是将用户的后续问题改写为独立、完整的问题,使其可以脱离对话上下文独立理解。
改写规则:
1. 消解代词指代(如"它"、"这个"、"他们"等)
2. 补全省略的主语或宾语
3. 保持原问题的核心意图不变
4. 改写后的问题应该简洁清晰
只输出改写后的问题,不要输出其他内容。
- id: "strict_rewrite_system"
name: "严格改写"
description: "严格要求的问题改写模板"
content: |
你是问题改写专家。请将用户问题改写为完整、独立的问题。
严格要求:
1. 必须消解所有代词和指代
2. 必须补全所有省略内容
3. 不得改变原问题意图
4. 不得添加原问题没有的内容
5. 改写结果必须是一个问句
直接输出改写后的问题,不要有任何解释。

View File

@ -0,0 +1,30 @@
# 改写用户提示词模板
templates:
- id: "default_rewrite_user"
name: "标准格式"
description: "标准的改写用户提示词格式"
content: |
## 历史对话背景
{{conversation}}
## 需要改写的用户问题
{{query}}
## 改写后的问题
- id: "detailed_rewrite_user"
name: "详细格式"
description: "详细的改写用户提示词格式"
content: |
## 历史对话背景
以下是用户与助手的对话历史,请仔细阅读以理解上下文:
{{conversation}}
## 当前用户问题
{{query}}
## 任务要求
请根据以上对话历史,将当前问题改写为一个独立、完整、可以脱离上下文理解的问题。
## 改写后的问题

View File

@ -0,0 +1,113 @@
# 系统提示词模板
templates:
- id: "default_kb"
name: "知识库问答"
description: "基于知识库内容回答问题的标准模板"
has_knowledge_base: true
content: |
你是一个专业的知识库问答助手。请根据提供的参考资料回答用户问题。
要求:
1. 仅基于参考资料回答,不要编造信息
2. 如果参考资料不足以回答问题,请明确告知用户
3. 回答要准确、简洁、专业
4. 适当引用来源,增强可信度
当前时间:{{current_time}}
- id: "expert_assistant"
name: "领域专家"
description: "专业领域深度解答的专家模板"
has_knowledge_base: true
content: |
你是一位资深的领域专家助手,拥有丰富的专业知识和实践经验。
核心职责:
1. 深入分析用户问题,提供专业、全面的解答
2. 结合知识库内容,给出有据可依的建议
3. 必要时提供多角度分析和权衡利弊
4. 用通俗易懂的语言解释专业概念
回答风格:
- 条理清晰,逻辑严谨
- 重点突出,层次分明
- 实用性强,可操作性高
当前时间:{{current_time}}
- id: "customer_service"
name: "客服助手"
description: "友善专业的客服对话模板"
has_knowledge_base: true
content: |
你是一位专业、友善的客服助手,致力于为用户提供优质的服务体验。
服务准则:
1. 态度热情友好,用语礼貌得体
2. 准确理解用户需求,提供针对性解答
3. 基于知识库内容回答,确保信息准确
4. 遇到无法解答的问题,引导用户寻求其他帮助渠道
回答要求:
- 语气亲切自然,避免机械生硬
- 回答简洁明了,重点突出
- 必要时主动提供相关信息
当前时间:{{current_time}}
- id: "technical_support"
name: "技术支持"
description: "技术问题诊断与解决方案模板"
has_knowledge_base: true
content: |
你是一位专业的技术支持工程师,负责解答技术相关问题。
工作职责:
1. 准确诊断用户遇到的技术问题
2. 提供清晰、可执行的解决方案
3. 必要时提供代码示例或操作步骤
4. 解释技术原理,帮助用户理解
回答规范:
- 技术术语准确,解释清晰
- 步骤详细,便于操作
- 代码示例规范,注释完整
- 考虑不同场景和边界情况
当前时间:{{current_time}}
- id: "pure_chat"
name: "通用对话"
description: "无知识库的通用对话模板"
has_knowledge_base: false
content: |
你是一个智能对话助手,可以与用户进行自然流畅的对话。
特点:
1. 理解用户意图,提供有帮助的回答
2. 知识广泛,可以讨论多种话题
3. 回答准确、客观、有见地
4. 语言自然,富有亲和力
当前时间:{{current_time}}
- id: "web_search_assistant"
name: "网络搜索助手"
description: "结合网络搜索的智能助手模板"
has_knowledge_base: true
has_web_search: true
content: |
你是一个具备网络搜索能力的智能助手,可以获取最新信息来回答问题。
工作方式:
1. 结合网络搜索结果和知识库内容回答问题
2. 优先使用最新、最权威的信息来源
3. 明确标注信息来源,便于用户验证
4. 对于时效性强的问题,优先参考搜索结果
注意事项:
- 区分事实和观点
- 对比多个来源,提供全面视角
- 标注信息的时效性
当前时间:{{current_time}}

View File

@ -22,7 +22,8 @@ services:
- "${APP_PORT:-8080}:8080"
volumes:
- data-files:/data/files
- ./config/config.yaml:/app/config/config.yaml
# Optional: mount custom config file
# - ./config/config.yaml:/app/config/config.yaml
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 MiB

After

Width:  |  Height:  |  Size: 15 MiB

View File

@ -0,0 +1,163 @@
import { get, post, put, del } from "../../utils/request";
// 智能体配置
export interface CustomAgentConfig {
// ===== 基础设置 =====
agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式
system_prompt?: string; // 统一系统提示词(使用 {{web_search_status}} 占位符动态控制行为)
context_template?: string; // 上下文模板(普通模式)
// ===== 模型设置 =====
model_id?: string;
rerank_model_id?: string; // ReRank 模型 ID
temperature?: number;
max_completion_tokens?: number; // 最大生成token数(普通模式)
// ===== Agent模式设置 =====
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[];
// ===== 网络搜索设置 =====
web_search_enabled?: boolean;
web_search_max_results?: number;
// ===== 多轮对话设置 =====
multi_turn_enabled?: boolean; // 是否启用多轮对话
history_turns?: number; // 保留历史轮数
// ===== 检索策略设置 =====
embedding_top_k?: number; // 向量召回TopK
keyword_threshold?: number; // 关键词召回阈值
vector_threshold?: number; // 向量召回阈值
rerank_top_k?: number; // 重排TopK
rerank_threshold?: number; // 重排阈值
// ===== 高级设置(主要用于普通模式)=====
enable_query_expansion?: boolean; // 是否启用查询扩展
enable_rewrite?: boolean; // 是否启用问题改写
rewrite_prompt_system?: string; // 改写系统提示词
rewrite_prompt_user?: string; // 改写用户提示词模板
fallback_strategy?: 'fixed' | 'model'; // 兜底策略
fallback_response?: string; // 固定兜底回复
fallback_prompt?: string; // 兜底提示词(模型生成时)
// ===== 已废弃字段(保留兼容)=====
welcome_message?: string;
suggested_prompts?: string[];
}
// 智能体
export interface CustomAgent {
id: string;
name: string;
description?: string;
avatar?: string;
is_builtin: boolean;
tenant_id?: number;
created_by?: string;
config: CustomAgentConfig;
created_at?: string;
updated_at?: string;
}
// 创建智能体请求
export interface CreateAgentRequest {
name: string;
description?: string;
avatar?: string;
config?: CustomAgentConfig;
}
// 更新智能体请求
export interface UpdateAgentRequest {
name: string;
description?: string;
avatar?: string;
config?: CustomAgentConfig;
}
// 内置智能体 ID
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() {
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 copyAgent(id: string) {
return post<{ data: CustomAgent }>(`/api/v1/agents/${id}/copy`);
}
// 判断是否为内置智能体
export function isBuiltinAgent(agentId: string): boolean {
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');
}

View File

@ -28,7 +28,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => {
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => {
// 重置状态
output.value = '';
error.value = null;
@ -89,6 +89,10 @@ export function useStream() {
if (params.knowledge_ids !== undefined && params.knowledge_ids.length > 0) {
postBody.knowledge_ids = params.knowledge_ids;
}
// Include agent_id if provided (for custom agent configuration)
if (params.agent_id) {
postBody.agent_id = params.agent_id;
}
// Include web_search_enabled if provided
if (params.web_search_enabled !== undefined) {
postBody.web_search_enabled = params.web_search_enabled;

View File

@ -29,9 +29,7 @@ export interface AgentConfig {
allowed_tools: string[]
temperature: number
knowledge_bases?: string[]
system_prompt_web_enabled?: string // Custom system prompt when web search is enabled
system_prompt_web_disabled?: string // Custom system prompt when web search is disabled
use_custom_system_prompt?: boolean
system_prompt?: string // Unified system prompt (uses {{web_search_status}} placeholder)
available_tools?: ToolDefinition[] // GET 响应中包含,POST/PUT 不需要
available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要
}
@ -41,8 +39,6 @@ export interface ConversationConfig {
context_template: string
temperature: number
max_completion_tokens: number
use_custom_system_prompt?: boolean
use_custom_context_template?: boolean
max_rounds: number
embedding_top_k: number
keyword_threshold: number
@ -60,6 +56,23 @@ export interface ConversationConfig {
enable_query_expansion?: boolean
}
export interface PromptTemplate {
id: string
name: string
description: string
content: string
has_knowledge_base?: boolean
has_web_search?: boolean
}
export interface PromptTemplatesConfig {
system_prompt: PromptTemplate[]
context_template: PromptTemplate[]
rewrite_system: PromptTemplate[]
rewrite_user: PromptTemplate[]
fallback: PromptTemplate[]
}
export function getSystemInfo(): Promise<{ data: SystemInfo }> {
return get('/api/v1/system/info')
}
@ -79,3 +92,7 @@ export function getConversationConfig(): Promise<{ data: ConversationConfig }> {
export function updateConversationConfig(config: ConversationConfig): Promise<{ data: ConversationConfig }> {
return put('/api/v1/tenants/kv/conversation-config', config)
}
export function getPromptTemplates(): Promise<{ data: PromptTemplatesConfig }> {
return get('/api/v1/tenants/kv/prompt-templates')
}

View File

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

After

Width:  |  Height:  |  Size: 996 B

View File

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

Before

Width:  |  Height:  |  Size: 995 B

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -0,0 +1,160 @@
<template>
<div
class="agent-avatar"
:style="avatarStyle"
:class="{ 'agent-avatar-small': size === 'small', 'agent-avatar-large': size === 'large' }"
>
<!-- 星星装饰 - 融入背景 -->
<svg class="agent-sparkles" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<!-- 右上角小星星 -->
<path d="M24 5L24.4 6.6C24.45 6.85 24.65 7.05 24.9 7.1L26.5 7.5L24.9 7.9C24.65 7.95 24.45 8.15 24.4 8.4L24 10L23.6 8.4C23.55 8.15 23.35 7.95 23.1 7.9L21.5 7.5L23.1 7.1C23.35 7.05 23.55 6.85 23.6 6.6L24 5Z" fill="rgba(255,255,255,0.6)"/>
<!-- 左下角小星星 -->
<path d="M7 22L7.4 23.6C7.45 23.85 7.65 24.05 7.9 24.1L9.5 24.5L7.9 24.9C7.65 24.95 7.45 25.15 7.4 25.4L7 27L6.6 25.4C6.55 25.15 6.35 24.95 6.1 24.9L4.5 24.5L6.1 24.1C6.35 24.05 6.55 23.85 6.6 23.6L7 22Z" fill="rgba(255,255,255,0.5)"/>
</svg>
<span class="agent-avatar-letter" :style="letterStyle">{{ letter }}</span>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = withDefaults(defineProps<{
name: string;
size?: 'small' | 'medium' | 'large';
}>(), {
size: 'medium'
});
// 预定义的渐变色方案 - 现代、柔和、专业
const gradients = [
{ from: '#667eea', to: '#764ba2' }, // 紫蓝渐变
{ from: '#4facfe', to: '#00f2fe' }, // 蓝青渐变
{ from: '#43e97b', to: '#38f9d7' }, // 绿青渐变
{ from: '#11998e', to: '#38ef7d' }, // 深绿渐变
{ from: '#5ee7df', to: '#b490ca' }, // 青紫渐变
{ from: '#48c6ef', to: '#6f86d6' }, // 蓝紫渐变
{ from: '#a8edea', to: '#fed6e3' }, // 青粉渐变(柔和)
{ from: '#667db6', to: '#0082c8' }, // 蓝色渐变
{ from: '#36d1dc', to: '#5b86e5' }, // 青蓝渐变
{ from: '#56ab2f', to: '#a8e063' }, // 草绿渐变
{ from: '#614385', to: '#516395' }, // 深紫蓝渐变
{ from: '#02aab0', to: '#00cdac' }, // 青绿渐变
{ from: '#6a82fb', to: '#fc5c7d' }, // 蓝粉渐变(柔和)
{ from: '#834d9b', to: '#d04ed6' }, // 紫色渐变
{ from: '#4776e6', to: '#8e54e9' }, // 蓝紫渐变
{ from: '#00b09b', to: '#96c93d' }, // 青绿渐变
];
// 根据名称生成一个稳定的哈希值
const hashCode = (str: string): number => {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return Math.abs(hash);
};
// 获取首字母(支持中文)
const letter = computed(() => {
const name = props.name?.trim() || '';
if (!name) return '?';
// 获取第一个字符
const firstChar = name.charAt(0);
// 如果是英文字母,转大写
if (/[a-zA-Z]/.test(firstChar)) {
return firstChar.toUpperCase();
}
// 中文或其他字符直接返回
return firstChar;
});
// 根据名称选择渐变色
const gradient = computed(() => {
const hash = hashCode(props.name || '');
return gradients[hash % gradients.length];
});
// 生成样式
const avatarStyle = computed(() => {
const g = gradient.value;
return {
background: `linear-gradient(135deg, ${g.from} 0%, ${g.to} 100%)`
};
});
// 字母样式 - 白色 + 背景色阴影增加层次感
const letterStyle = computed(() => {
const g = gradient.value;
return {
textShadow: `0 1px 2px ${g.to}80, 0 0 8px ${g.from}30`
};
});
</script>
<style scoped lang="less">
.agent-avatar {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
flex-shrink: 0;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
overflow: hidden;
&.agent-avatar-small {
width: 22px;
height: 22px;
border-radius: 5px;
box-shadow: none;
.agent-avatar-letter {
font-size: 11px;
}
.agent-sparkles {
display: none;
}
}
&.agent-avatar-large {
width: 48px;
height: 48px;
border-radius: 12px;
.agent-avatar-letter {
font-size: 20px;
}
.agent-sparkles {
opacity: 0.9;
}
}
}
.agent-sparkles {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
opacity: 0.85;
}
.agent-avatar-letter {
position: relative;
z-index: 1;
color: #fff;
font-size: 14px;
font-weight: 600;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
</style>

View File

@ -0,0 +1,556 @@
<template>
<Teleport to="body">
<div v-if="visible" class="agent-selector-overlay" @click="$emit('close')">
<div
class="agent-selector-dropdown"
:style="dropdownStyle"
@click.stop
>
<!-- 头部 -->
<div class="agent-selector-header">
<span>{{ $t('agent.selectAgent') }}</span>
<router-link to="/platform/agents" class="agent-selector-add" @click="$emit('close')">
<span class="add-icon">+</span>
<span class="add-text">{{ $t('agent.manageAgents') }}</span>
</router-link>
</div>
<!-- 内容区域 -->
<div class="agent-selector-content">
<!-- 内置智能体分组 -->
<div class="agent-group">
<div class="agent-group-title">{{ $t('agent.builtinAgents') }}</div>
<t-popup
v-for="agent in builtinAgents"
:key="agent.id"
placement="right"
trigger="hover"
:show-arrow="true"
:overlay-inner-class-name="'agent-tooltip-popup'"
>
<div
class="agent-option"
:class="{ 'selected': currentAgentId === agent.id }"
@click="selectAgent(agent)"
>
<div class="builtin-icon" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">
<TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" />
</div>
<span class="agent-option-name">{{ agent.name }}</span>
<svg
v-if="currentAgentId === agent.id"
width="14"
height="14"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
</div>
<template #content>
<div class="agent-tooltip-content">
<div class="agent-tooltip-header">
<div class="builtin-icon" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">
<TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" />
</div>
<div class="agent-tooltip-title">
<span class="agent-tooltip-name">{{ agent.name }}</span>
<span v-if="currentAgentId === agent.id" class="agent-tooltip-selected">{{ $t('agent.selector.current') }}</span>
</div>
</div>
<p class="agent-tooltip-desc">{{ agent.description || $t('agent.noDescription') }}</p>
<div class="agent-tooltip-capabilities">
<div class="capability-item">
<TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="12px" />
<span>{{ agent.config?.agent_mode === 'smart-reasoning' ? $t('agent.type.agent') : $t('agent.type.normal') }}</span>
</div>
</div>
</div>
</template>
</t-popup>
</div>
<!-- 自定义智能体分组 -->
<div v-if="customAgents.length > 0" class="agent-group">
<div class="agent-group-title">{{ $t('agent.customAgents') }}</div>
<t-popup
v-for="agent in customAgents"
:key="agent.id"
placement="right"
trigger="hover"
:show-arrow="true"
:overlay-inner-class-name="'agent-tooltip-popup'"
>
<div
class="agent-option"
:class="{ 'selected': currentAgentId === agent.id }"
@click="selectAgent(agent)"
>
<AgentAvatar :name="agent.name" size="small" />
<span class="agent-option-name">{{ agent.name }}</span>
<svg
v-if="currentAgentId === agent.id"
width="14"
height="14"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
</div>
<template #content>
<div class="agent-tooltip-content">
<div class="agent-tooltip-header">
<AgentAvatar :name="agent.name" size="small" />
<div class="agent-tooltip-title">
<span class="agent-tooltip-name">{{ agent.name }}</span>
<span v-if="currentAgentId === agent.id" class="agent-tooltip-selected">{{ $t('agent.selector.current') }}</span>
</div>
</div>
<p class="agent-tooltip-desc">{{ agent.description || $t('agent.noDescription') }}</p>
<div class="agent-tooltip-capabilities">
<div class="capability-item">
<TIcon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="12px" />
<span>{{ agent.config?.agent_mode === 'smart-reasoning' ? $t('agent.type.agent') : $t('agent.type.normal') }}</span>
</div>
<div v-if="getKbCapability(agent)" class="capability-item">
<TIcon name="folder" size="12px" />
<span>{{ getKbCapability(agent) }}</span>
</div>
<div v-if="agent.config?.web_search_enabled" class="capability-item">
<TIcon name="internet" size="12px" />
<span>{{ $t('agent.capabilities.webSearchOn') }}</span>
</div>
<div v-if="agent.config?.mcp_services?.length || agent.config?.mcp_selection_mode === 'all'" class="capability-item">
<TIcon name="extension" size="12px" />
<span>{{ $t('agent.capabilities.mcpEnabled') }}</span>
</div>
<div v-if="agent.config?.multi_turn_enabled" class="capability-item">
<TIcon name="chat-bubble" size="12px" />
<span>{{ $t('agent.capabilities.multiTurn') }}</span>
</div>
</div>
</div>
</template>
</t-popup>
</div>
<!-- 空状态 -->
<div v-if="builtinAgents.length === 0 && customAgents.length === 0" class="agent-option empty">
{{ $t('agent.noAgents') }}
</div>
</div>
</div>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { Icon as TIcon, Popup as TPopup } from 'tdesign-vue-next';
import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';
import AgentAvatar from '@/components/AgentAvatar.vue';
const { t } = useI18n();
const props = defineProps<{
visible: boolean;
anchorEl?: HTMLElement;
currentAgentId: string;
}>();
const emit = defineEmits<{
(e: 'close'): void;
(e: 'select', agent: CustomAgent): void;
}>();
const agents = ref<CustomAgent[]>([]);
const dropdownStyle = ref<Record<string, string>>({});
// 内置智能体
const builtinAgents = computed(() => {
return [
{
id: BUILTIN_QUICK_ANSWER_ID,
name: t('input.normalMode'),
description: t('input.normalModeDesc'),
is_builtin: true,
config: { agent_mode: 'quick-answer' as const }
},
{
id: BUILTIN_SMART_REASONING_ID,
name: t('input.agentMode'),
description: t('input.agentModeDesc'),
is_builtin: true,
config: { agent_mode: 'smart-reasoning' as const }
}
] as CustomAgent[];
});
// 自定义智能体
const customAgents = computed(() => {
return agents.value.filter(a => !a.is_builtin);
});
// 获取知识库能力描述
const getKbCapability = (agent: CustomAgent): string => {
const config = agent.config || {};
if (config.kb_selection_mode === 'none') {
return '';
} else if (config.knowledge_bases && config.knowledge_bases.length > 0) {
return t('agent.capabilities.kbCount', { count: config.knowledge_bases.length });
} else if (config.kb_selection_mode === 'all') {
return t('agent.capabilities.kbAll');
}
return '';
};
// 加载智能体列表
const loadAgents = async () => {
try {
const response = await listAgents();
agents.value = response.data || [];
} catch (error) {
console.error('Failed to load agents:', error);
}
};
// 选择智能体
const selectAgent = (agent: CustomAgent) => {
emit('select', agent);
};
// 更新下拉框位置(与模型选择器一致)
const updateDropdownPosition = () => {
if (!props.anchorEl) return;
const rect = props.anchorEl.getBoundingClientRect();
const dropdownWidth = 200;
const offsetY = 8;
const vh = window.innerHeight;
const vw = window.innerWidth;
// 水平位置:左对齐
let left = Math.floor(rect.left);
const minLeft = 16;
const maxLeft = Math.max(16, vw - dropdownWidth - 16);
left = Math.max(minLeft, Math.min(maxLeft, left));
// 垂直位置
const preferredDropdownHeight = 320;
const minDropdownHeight = 100;
const topMargin = 20;
const spaceBelow = vh - rect.bottom;
const spaceAbove = rect.top;
let actualHeight: number;
if (spaceBelow >= minDropdownHeight + offsetY) {
// 向下弹出
actualHeight = Math.min(preferredDropdownHeight, spaceBelow - offsetY - 16);
const top = Math.floor(rect.bottom + offsetY);
dropdownStyle.value = {
position: 'fixed',
width: `${dropdownWidth}px`,
left: `${left}px`,
top: `${top}px`,
maxHeight: `${actualHeight}px`,
zIndex: '9999'
};
} else {
// 向上弹出
const availableHeight = spaceAbove - offsetY - topMargin;
actualHeight = availableHeight >= preferredDropdownHeight
? preferredDropdownHeight
: Math.max(minDropdownHeight, availableHeight);
const bottom = vh - rect.top + offsetY;
dropdownStyle.value = {
position: 'fixed',
width: `${dropdownWidth}px`,
left: `${left}px`,
bottom: `${bottom}px`,
maxHeight: `${actualHeight}px`,
zIndex: '9999'
};
}
};
// 监听显示状态
watch(() => props.visible, (newVal) => {
if (newVal) {
loadAgents();
nextTick(() => {
updateDropdownPosition();
});
}
});
onMounted(() => {
if (props.visible) {
loadAgents();
}
});
</script>
<style scoped lang="less">
.agent-selector-overlay {
position: fixed;
inset: 0;
z-index: 9998;
background: transparent;
touch-action: none;
}
.agent-selector-dropdown {
position: fixed;
background: var(--td-bg-color-container, #fff);
border-radius: 10px;
box-shadow: var(--td-shadow-2, 0 6px 28px rgba(15, 23, 42, 0.08));
border: 1px solid var(--td-component-border, #e7e9eb);
overflow: hidden;
display: flex;
flex-direction: column;
}
.agent-selector-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
border-bottom: 1px solid var(--td-component-stroke, #f0f0f0);
background: var(--td-bg-color-container, #fff);
font-size: 12px;
font-weight: 500;
color: var(--td-text-color-secondary, #666);
}
.agent-selector-add {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 4px;
border: 1px solid transparent;
background: transparent;
color: var(--td-brand-color, #07c05f);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
text-decoration: none;
.add-icon {
font-size: 14px;
line-height: 1;
font-weight: 400;
}
&:hover {
color: var(--td-brand-color-hover, #05a04f);
background: var(--td-bg-color-secondarycontainer, #f3f3f3);
}
}
.agent-selector-content {
flex: 1;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
padding: 6px 8px;
}
.agent-group {
&:not(:last-child) {
margin-bottom: 8px;
padding-bottom: 8px;
border-bottom: 1px solid var(--td-component-stroke, #f0f0f0);
}
}
.agent-group-title {
font-size: 11px;
color: var(--td-text-color-placeholder, #999);
padding: 4px 8px 6px;
font-weight: 500;
}
.agent-option {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
cursor: pointer;
transition: background 0.12s;
border-radius: 6px;
margin-bottom: 4px;
&:last-child {
margin-bottom: 0;
}
&:hover {
background: var(--td-bg-color-container-hover, #f6f8f7);
}
&.selected {
background: var(--td-brand-color-light, #eefdf5);
.agent-option-name {
color: #10b981;
font-weight: 600;
}
}
&.empty {
color: var(--td-text-color-disabled, #9aa0a6);
cursor: default;
text-align: center;
padding: 20px 8px;
&:hover {
background: transparent;
}
}
}
.agent-option-name {
font-size: 12px;
color: var(--td-text-color-primary, #222);
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.4;
}
.builtin-icon {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 6px;
flex-shrink: 0;
&.normal {
background: rgba(7, 192, 95, 0.1);
color: #059669;
}
&.agent {
background: rgba(124, 77, 255, 0.1);
color: #7c4dff;
}
}
.check-icon {
width: 14px;
height: 14px;
color: #10b981;
flex-shrink: 0;
margin-left: 6px;
}
// Tooltip 内容样式
.agent-tooltip-content {
padding: 4px 0;
min-width: 200px;
max-width: 280px;
}
.agent-tooltip-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
.builtin-icon {
width: 28px;
height: 28px;
}
}
.agent-tooltip-title {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.agent-tooltip-name {
font-size: 13px;
font-weight: 600;
color: var(--td-text-color-primary, #222);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.agent-tooltip-selected {
font-size: 10px;
color: #10b981;
font-weight: 500;
}
.agent-tooltip-desc {
font-size: 12px;
color: var(--td-text-color-secondary, #666);
line-height: 1.5;
margin: 0 0 10px 0;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.agent-tooltip-capabilities {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding-top: 8px;
border-top: 1px solid var(--td-component-stroke, #f0f0f0);
}
.capability-item {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
border-radius: 4px;
font-size: 11px;
color: var(--td-text-color-secondary, #666);
:deep(.t-icon) {
color: var(--td-text-color-placeholder, #999);
}
}
</style>
<!-- 全局样式覆盖 TDesign Popup -->
<style lang="less">
.agent-tooltip-popup {
&.t-popup__content {
background: var(--td-bg-color-container, #fff) !important;
border: 1px solid var(--td-component-border, #e7e9eb) !important;
border-radius: 8px !important;
box-shadow: var(--td-shadow-2, 0 6px 28px rgba(15, 23, 42, 0.08)) !important;
padding: 10px 12px !important;
}
.t-popup__arrow {
&::before {
background: var(--td-bg-color-container, #fff) !important;
border-color: var(--td-component-border, #e7e9eb) !important;
}
}
}
</style>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,261 @@
<template>
<div class="prompt-template-selector" :class="{ 'position-corner': position === 'corner' }">
<t-popup
trigger="click"
placement="top-right"
:visible="popupVisible"
@visible-change="handleVisibleChange"
>
<template #content>
<div class="template-popup">
<div class="template-header">
<span class="template-title">{{ $t('promptTemplate.selectTemplate') }}</span>
</div>
<div v-if="loading" class="template-loading">
<t-loading size="small" />
</div>
<div v-else-if="templates.length === 0" class="template-empty">
{{ $t('promptTemplate.noTemplates') || '暂无模板' }}
</div>
<div v-else class="template-list">
<div
v-for="template in templates"
:key="template.id"
class="template-item"
@click="selectTemplate(template)"
>
<div class="template-item-header">
<span class="template-name">{{ template.name }}</span>
<span v-if="template.has_knowledge_base" class="template-tag kb-tag">
<t-icon name="folder" size="12px" />
{{ $t('promptTemplate.withKnowledgeBase') }}
</span>
<span v-if="template.has_web_search" class="template-tag web-tag">
<t-icon name="internet" size="12px" />
{{ $t('promptTemplate.withWebSearch') }}
</span>
</div>
<p class="template-desc">{{ template.description }}</p>
</div>
</div>
</div>
</template>
<t-button
variant="outline"
size="small"
class="template-trigger-btn"
:loading="loading"
>
<t-icon name="view-module" />
<span>{{ $t('promptTemplate.useTemplate') }}</span>
</t-button>
</t-popup>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getPromptTemplates, type PromptTemplate, type PromptTemplatesConfig } from '@/api/system';
const props = defineProps<{
type: 'systemPrompt' | 'contextTemplate' | 'rewriteSystem' | 'rewriteUser' | 'fallback';
hasKnowledgeBase?: boolean;
position?: 'inline' | 'corner'; // inline: 行内显示, corner: 输入框右下角
}>();
const emit = defineEmits<{
(e: 'select', content: string): void;
}>();
const popupVisible = ref(false);
const loading = ref(false);
const templatesConfig = ref<PromptTemplatesConfig | null>(null);
const handleVisibleChange = async (visible: boolean) => {
popupVisible.value = visible;
// 首次打开时加载模板
if (visible && !templatesConfig.value) {
await loadTemplates();
}
};
const loadTemplates = async () => {
if (loading.value) return;
loading.value = true;
try {
const response = await getPromptTemplates();
templatesConfig.value = response.data;
} catch (error) {
console.error('Failed to load prompt templates:', error);
} finally {
loading.value = false;
}
};
// 根据类型获取对应的模板列表
const templates = computed<PromptTemplate[]>(() => {
if (!templatesConfig.value) return [];
switch (props.type) {
case 'systemPrompt':
return templatesConfig.value.system_prompt || [];
case 'contextTemplate':
return templatesConfig.value.context_template || [];
case 'rewriteSystem':
return templatesConfig.value.rewrite_system || [];
case 'rewriteUser':
return templatesConfig.value.rewrite_user || [];
case 'fallback':
return templatesConfig.value.fallback || [];
default:
return [];
}
});
const selectTemplate = (template: PromptTemplate) => {
emit('select', template.content);
popupVisible.value = false;
};
// 预加载模板(可选)
onMounted(() => {
// 可以在这里预加载,也可以等用户点击时再加载
// loadTemplates();
});
</script>
<style scoped lang="less">
.prompt-template-selector {
display: inline-flex;
&.position-corner {
position: absolute;
right: 8px;
bottom: 8px;
z-index: 10;
}
}
.template-trigger-btn {
display: inline-flex;
align-items: center;
gap: 4px;
color: #666;
border-color: #d9d9d9;
font-size: 12px;
height: 26px;
padding: 0 8px;
background: rgba(255, 255, 255, 0.95);
&:hover {
color: #07c05f;
border-color: #07c05f;
background: #fff;
}
:deep(.t-button__text) {
display: inline-flex;
align-items: center;
gap: 4px;
}
:deep(.t-icon) {
vertical-align: middle;
line-height: 1;
}
}
.template-popup {
width: 420px;
max-height: 400px;
overflow: hidden;
display: flex;
flex-direction: column;
}
.template-header {
padding: 12px 16px;
border-bottom: 1px solid #e5e7eb;
flex-shrink: 0;
}
.template-title {
font-size: 14px;
font-weight: 500;
color: #333;
}
.template-loading,
.template-empty {
padding: 40px 16px;
text-align: center;
color: #999;
font-size: 13px;
}
.template-list {
overflow-y: auto;
padding: 8px;
flex: 1;
}
.template-item {
padding: 12px;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
margin-bottom: 4px;
&:last-child {
margin-bottom: 0;
}
&:hover {
background: #f5f7fa;
}
}
.template-item-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
flex-wrap: wrap;
}
.template-name {
font-size: 14px;
font-weight: 500;
color: #333;
}
.template-tag {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 2px 6px;
border-radius: 4px;
font-size: 11px;
&.kb-tag {
background: #e6f7ff;
color: #1890ff;
}
&.web-tag {
background: #f0faf5;
color: #07c05f;
}
}
.template-desc {
font-size: 12px;
color: #666;
margin: 0;
line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@ -24,10 +24,6 @@
<t-icon name="server" class="menu-icon" />
<span>Ollama</span>
</div>
<div class="menu-item" @click="handleQuickNav('agent')">
<t-icon name="chat" class="menu-icon" />
<span>{{ $t('settings.conversationStrategy') }}</span>
</div>
<div class="menu-item" @click="handleQuickNav('websearch')">
<svg
width="16"

View File

@ -24,6 +24,18 @@
</div>
</div>
</template>
<template v-else-if="showCreateAgentAction">
<div class="menu_item kb-action-item" @click.stop="handleCreateAgent">
<div class="kb-action-icon-wrapper">
<svg class="kb-action-icon" width="18" height="18" viewBox="0 0 18 18" fill="none">
<path d="M9 3.75V14.25M3.75 9H14.25" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</div>
<div class="kb-action-content">
<span class="kb-action-title">{{ t('agent.createAgent') }}</span>
</div>
</div>
</template>
<template v-else-if="showDocActions">
<div class="menu_item kb-action-item" @click.stop="handleDocUploadClick">
<div class="kb-action-icon-wrapper">
@ -138,7 +150,7 @@
:class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : isMenuItemActive(item.path) ? 'menu_item_active' : '']">
<div class="menu_item-box">
<div class="menu_icon">
<img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
<img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'agent' ? agentIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
</div>
<span class="menu_title" :title="item.title">{{ item.title }}</span>
<t-icon v-if="item.path === 'creatChat'" name="add" class="menu-create-hint" />
@ -253,6 +265,9 @@ const isInCreatChat = computed<boolean>(() => {
// 是否在对话详情页
const isInChatDetail = computed<boolean>(() => route.name === 'chat');
// 是否在智能体列表页面
const isInAgentList = computed<boolean>(() => route.name === 'agentList');
// 统一的菜单项激活状态判断
const isMenuItemActive = (itemPath: string): boolean => {
const currentRoute = route.name;
@ -262,6 +277,8 @@ const isMenuItemActive = (itemPath: string): boolean => {
return currentRoute === 'knowledgeBaseList' ||
currentRoute === 'knowledgeBaseDetail' ||
currentRoute === 'knowledgeBaseSettings';
case 'agents':
return currentRoute === 'agentList';
case 'creatChat':
return currentRoute === 'kbCreatChat' || currentRoute === 'globalCreatChat';
case 'settings':
@ -290,13 +307,13 @@ const getIconActiveState = (itemPath: string) => {
// 分离上下两部分菜单
const topMenuItems = computed<MenuItem[]>(() => {
return (menuArr.value as unknown as MenuItem[]).filter((item: MenuItem) =>
item.path === 'knowledge-bases' || item.path === 'creatChat'
item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'creatChat'
);
});
const bottomMenuItems = computed<MenuItem[]>(() => {
return (menuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => {
if (item.path === 'knowledge-bases' || item.path === 'creatChat') {
if (item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'creatChat') {
return false;
}
return true;
@ -325,12 +342,14 @@ const showKbActions = computed(() =>
(isInKnowledgeBase.value && !!currentKbInfo.value) ||
isInKnowledgeBaseList.value ||
isInCreatChat.value ||
isInChatDetail.value
isInChatDetail.value ||
isInAgentList.value
)
const currentKbType = computed(() => currentKbInfo.value?.type || 'document')
const showDocActions = computed(() => showKbActions.value && isInKnowledgeBase.value && currentKbType.value !== 'faq')
const showFaqActions = computed(() => showKbActions.value && isInKnowledgeBase.value && currentKbType.value === 'faq')
const showCreateKbAction = computed(() => showKbActions.value && (isInKnowledgeBaseList.value || isInCreatChat.value || isInChatDetail.value))
const showCreateAgentAction = computed(() => showKbActions.value && isInAgentList.value)
// 时间分组函数
const getTimeCategory = (dateStr: string): string => {
@ -570,16 +589,21 @@ let knowledgeIcon = ref('zhishiku-green.svg');
let prefixIcon = ref('prefixIcon.svg');
let logoutIcon = ref('logout.svg');
let settingIcon = ref('setting.svg'); // 设置图标
let agentIcon = ref('agent.svg'); // 智能体图标
let pathPrefix = ref(route.name)
const getIcon = (path: string) => {
// 根据当前路由状态更新所有图标
const kbActiveState = getIconActiveState('knowledge-bases');
const creatChatActiveState = getIconActiveState('creatChat');
const settingsActiveState = getIconActiveState('settings');
const agentsActiveState = route.name === 'agentList';
// 知识库图标:只在知识库页面显示绿色
knowledgeIcon.value = kbActiveState.isKbActive ? 'zhishiku-green.svg' : 'zhishiku.svg';
// 智能体图标:只在智能体页面显示绿色
agentIcon.value = agentsActiveState ? 'agent-green.svg' : 'agent.svg';
// 对话图标:只在对话创建页面显示绿色,在知识库页面显示灰色,其他情况显示默认
prefixIcon.value = creatChatActiveState.isCreatChatActive ? 'prefixIcon-green.svg' :
kbActiveState.isKbActive ? 'prefixIcon-grey.svg' :
@ -601,6 +625,9 @@ const handleMenuClick = async (path: string) => {
} else {
router.push('/platform/knowledge-bases')
}
} else if (path === 'agents') {
// 智能体菜单项:跳转到智能体列表
router.push('/platform/agents')
} else if (path === 'settings') {
// 设置菜单项:打开设置弹窗并跳转路由
uiStore.openSettings()
@ -1238,6 +1265,13 @@ const handleCreateKnowledgeBase = () => {
uiStore.openCreateKB()
}
const handleCreateAgent = () => {
// 触发创建智能体事件,由 AgentList 页面监听处理
window.dispatchEvent(new CustomEvent('openAgentEditor', {
detail: { mode: 'create' }
}))
}
</script>
<style lang="less" scoped>
.aside_box {

View File

@ -1,6 +1,7 @@
export default {
menu: {
knowledgeBase: 'Knowledge Base',
agents: 'Agents',
chat: 'Chat',
createChat: 'Create Chat',
tenant: 'Account Info',
@ -204,7 +205,197 @@ export default {
updatePlan: 'Update Plan',
webSearchFound: 'Found <strong>{count}</strong> web search result(s)',
argumentsLabel: 'Arguments',
toolFallback: 'Tool'
toolFallback: 'Tool',
title: 'Agents',
subtitle: 'Configure and manage your agents to customize conversation behavior and capabilities',
createAgent: 'Create Agent',
builtin: 'Built-in',
noDescription: 'No description',
selectAgent: 'Select Agent',
noAgents: 'No agents',
manageAgents: 'Manage',
builtinAgents: 'Built-in Agents',
customAgents: 'Custom Agents',
capabilities: {
normal: 'Quick response, direct answers',
agent: 'Multi-step thinking, deep analysis for complex questions',
modelSpecified: 'Model specified',
kbCount: '{count} knowledge base(s) specified',
kbAll: 'Access to all knowledge bases',
kbDisabled: 'Knowledge base disabled',
rerankSpecified: 'ReRank model specified',
webSearchOn: 'Web search enabled',
webSearchOff: 'Web search disabled',
hasPrompt: 'Custom prompt',
default: 'Default configuration',
mcpEnabled: 'MCP services enabled',
multiTurn: 'Multi-turn conversation',
},
type: {
normal: 'Quick Answer',
agent: 'Smart Reasoning',
custom: 'Custom',
},
mode: {
normal: 'Quick Answer',
agent: 'Smart Reasoning',
},
features: {
webSearch: 'Web Search Enabled',
knowledgeBase: 'Knowledge Base Linked',
mcp: 'MCP Services Enabled',
multiTurn: 'Multi-turn Conversation',
},
empty: {
title: 'No Custom Agents',
description: 'Click the button in the top right to create your first agent',
},
delete: {
confirmTitle: 'Delete Agent',
confirmMessage: 'Are you sure you want to delete agent "{name}"? This action cannot be undone.',
confirmButton: 'Confirm Delete',
},
messages: {
created: 'Agent created successfully',
updated: 'Agent updated successfully',
deleted: 'Agent deleted',
deleteFailed: 'Delete failed',
saveFailed: 'Save failed',
builtinReadonly: 'Built-in agents cannot be edited',
copied: 'Agent copied successfully',
copyFailed: 'Copy failed',
},
editor: {
createTitle: 'Create Agent',
editTitle: 'Edit Agent',
basicInfo: 'Basic Info',
basicInfoDesc: 'Configure agent basic information',
modelConfig: 'Model Config',
modelConfigDesc: 'Configure agent model parameters',
capabilities: 'Capabilities',
capabilitiesDesc: 'Configure agent capabilities and tools',
toolsConfig: 'Tools',
toolsConfigDesc: 'Configure tools available to the Agent',
knowledgeConfig: 'Knowledge Base',
knowledgeConfigDesc: 'Configure knowledge bases for the agent',
webSearchConfig: 'Web Search',
webSearchConfigDesc: 'Configure web search capabilities for the agent',
configuration: 'Configuration',
name: 'Name',
namePlaceholder: 'Enter agent name',
nameRequired: 'Agent name is required',
systemPromptRequired: 'System prompt is required',
modelRequired: 'Please select a model',
rerankModelRequired: 'ReRank model is required when using knowledge bases',
contextsMissing: 'Context template must contain {{contexts}} placeholder when knowledge base is enabled',
queryMissingInContext: 'Context template must contain {{query}} placeholder',
knowledgeBasesMissing: 'It is recommended to include {{knowledge_bases}} placeholder in system prompt so the model knows available knowledge bases',
queryMissingInRewrite: 'Rewrite user prompt must contain {{query}} placeholder',
conversationMissing: 'Rewrite user prompt must contain {{conversation}} placeholder',
queryMissingInFallback: 'Fallback prompt must contain {{query}} placeholder',
avatar: 'Avatar',
avatarPlaceholder: 'Enter Emoji or select',
description: 'Description',
descriptionPlaceholder: 'Enter agent description',
baseType: 'Base Type',
normalDesc: 'Quick response, direct answers',
agentDesc: 'Multi-step thinking, deep analysis for complex questions',
model: 'Model',
modelPlaceholder: 'Select Model',
systemPrompt: 'System Prompt',
systemPromptPlaceholder: 'Custom system prompt to define agent behavior and role (use {{web_search_status}} placeholder for dynamic web search behavior)',
defaultPromptHint: 'Leave empty to use the following default system prompt:',
defaultContextTemplateHint: 'Leave empty to use the following default context template:',
contextTemplateRequired: 'Context template is required',
availablePlaceholders: 'Available Placeholders',
placeholderHint: 'Type {{ to trigger autocomplete',
temperature: 'Temperature',
welcomeMessage: 'Welcome Message',
welcomeMessagePlaceholder: 'Message displayed when this agent is selected',
suggestedPrompts: 'Suggested Prompts',
mode: 'Running Mode',
webSearch: 'Web Search',
webSearchMaxResults: 'Max Search Results',
knowledgeBases: 'Knowledge Bases',
allKnowledgeBases: 'All Knowledge Bases',
allKnowledgeBasesDesc: 'Agent can access all knowledge bases',
selectedKnowledgeBases: 'Selected Knowledge Bases',
selectedKnowledgeBasesDesc: 'Only access selected knowledge bases',
noKnowledgeBase: 'No Knowledge Base',
noKnowledgeBaseDesc: 'Pure model conversation, no knowledge retrieval',
selectKnowledgeBases: 'Select Knowledge Bases',
rerankModel: 'ReRank Model',
rerankModelDesc: 'Used to rerank knowledge base retrieval results for better accuracy',
rerankModelPlaceholder: 'Select ReRank Model',
maxIterations: 'Max Iterations',
allowedTools: 'Allowed Tools',
multiTurn: 'Multi-turn Conversation',
historyTurns: 'History Turns',
// Retrieval Strategy
retrievalStrategy: 'Retrieval Strategy',
embeddingTopK: 'Embedding Top K',
keywordThreshold: 'Keyword Threshold',
vectorThreshold: 'Vector Threshold',
rerankTopK: 'Rerank Top K',
rerankThreshold: 'Rerank Threshold',
// Conversation Settings
conversationSettings: 'Conversation',
// Advanced Settings
advancedSettings: 'Advanced Settings',
contextTemplate: 'Context Template',
contextTemplatePlaceholder: 'Custom context template...',
availableContextPlaceholders: 'Available Placeholders',
placeholderQuery: 'User query',
placeholderContexts: 'Retrieved content list',
placeholderCurrentTime: 'Current time (format: 2006-01-02 15:04:05)',
placeholderCurrentWeek: 'Current weekday (e.g., Monday)',
enableQueryExpansion: 'Query Expansion',
enableRewrite: 'Query Rewrite',
rewritePromptSystem: 'Rewrite System Prompt',
rewritePromptSystemPlaceholder: 'Leave empty to use default prompt',
rewritePromptUser: 'Rewrite User Prompt',
rewritePromptUserPlaceholder: 'Leave empty to use default prompt',
maxCompletionTokens: 'Max Completion Tokens',
fallbackStrategy: 'Fallback Strategy',
fallbackResponse: 'Fixed Response',
fallbackResponsePlaceholder: 'Sorry, I cannot answer this question.',
fallbackPrompt: 'Fallback Prompt',
fallbackPromptPlaceholder: 'Leave empty to use default prompt',
},
selector: {
title: 'Select Agent',
builtinSection: 'Built-in Agents',
customSection: 'My Agents',
addNew: 'Add New Agent',
current: 'Current',
},
// Built-in agent information
builtinInfo: {
quickAnswer: {
name: 'Quick Answer',
description: 'Knowledge base RAG Q&A for fast and accurate answers',
},
smartReasoning: {
name: 'Smart Reasoning',
description: 'ReAct reasoning framework with multi-step thinking and tool calling',
},
deepResearcher: {
name: 'Deep Researcher',
description: 'Focused on in-depth research and comprehensive analysis, capable of creating research plans, multi-dimensional information retrieval, deep thinking and providing thorough analysis reports',
},
dataAnalyst: {
name: 'Data Analyst',
description: 'Focused on database queries and data analysis, capable of understanding business needs, building SQL queries, analyzing data and providing insights',
},
knowledgeGraphExpert: {
name: 'Knowledge Graph Expert',
description: 'Focused on knowledge graph queries and relationship analysis, capable of exploring entity relationships, discovering hidden connections and building knowledge networks',
},
documentAssistant: {
name: 'Document Assistant',
description: 'Focused on document retrieval and content organization, capable of quickly locating documents, extracting key information and generating summaries',
},
},
},
settings: {
title: 'Settings',
@ -604,6 +795,7 @@ export default {
save: 'Save',
delete: 'Delete',
edit: 'Edit',
copy: 'Copy',
default: 'Default',
create: 'Create',
search: 'Search',
@ -752,16 +944,25 @@ export default {
placeholderWithContext: 'Enter your question, will answer based on selected knowledge bases/files above',
placeholderWebOnly: 'Enter your question, will answer with web search',
placeholderKbAndWeb: 'Enter your question, will answer based on knowledge base and web search',
agentMode: 'Agent Mode',
normalMode: 'Normal Mode',
placeholderAgent: 'Ask {name}',
agentMode: 'Smart Reasoning',
normalMode: 'Quick Answer',
normalModeDesc: 'Knowledge base RAG Q&A',
agentModeDesc: 'ReAct reasoning framework with multi-step thinking',
agentModeDesc: 'Multi-step thinking, deep analysis',
agentNotReadyTooltip: 'Agent is not ready. Please finish configuration first.',
agentNotReadyDetail: 'Agent is not ready. Please configure the following: {reasons}',
agentMissingAllowedTools: 'Allowed tools',
agentMissingSummaryModel: 'Chat Model (Summary Model)',
agentMissingRerankModel: 'Rerank Model',
goToSettings: 'Go to settings →',
customAgentNotReadyTooltip: 'Agent is not ready. Please finish configuration first.',
customAgentNotReadyDetail: 'Agent is not ready. Please configure the following: {reasons}',
customAgentMissingSummaryModel: 'Chat Model (Summary Model)',
customAgentMissingRerankModel: 'Rerank Model',
goToAgentEditor: 'Go to configure →',
builtinAgentNotReadyDetail: 'Built-in agent "{agentName}" is not ready. Please configure: {reasons}',
builtinAgentSettingName: 'Intelligent Reasoning',
builtinNormalSettingName: 'Quick Q&A',
webSearch: {
toggleOn: 'Enable Web Search',
toggleOff: 'Disable Web Search',
@ -780,8 +981,9 @@ export default {
enterContent: 'Please enter content first!',
selectKnowledge: 'Please select a knowledge base first!',
replying: 'Currently replying, please try again later!',
agentSwitchedOn: 'Switched to Agent Mode',
agentSwitchedOff: 'Switched to Normal Mode',
agentSwitchedOn: 'Switched to Intelligent Reasoning',
agentSwitchedOff: 'Switched to Quick Q&A',
agentSelected: 'Selected agent "{name}"',
agentEnabled: 'Agent Mode enabled',
agentDisabled: 'Agent Mode disabled',
agentNotReadyDetail: 'Agent is not ready. Please configure the following: {reasons}',
@ -795,7 +997,15 @@ export default {
messageMissing: 'Unable to get message ID. Please refresh the page and try again.',
stopSuccess: 'Generation stopped',
stopFailed: 'Failed to stop. Please try again.'
}
},
webSearchDisabledByAgent: 'Web search is disabled by the current agent',
webSearchForcedByAgent: 'Web search is enabled by the current agent and cannot be turned off',
kbLockedByAgent: 'Knowledge base configuration is locked by the current agent',
kbDisabledByAgent: 'Knowledge base is disabled by the current agent',
cannotRemoveAgentKb: 'Cannot remove knowledge base configured by agent',
agentConfiguredKb: 'Configured by agent, cannot be removed',
modelLockedByAgent: 'Model selection is locked by the current agent',
goToAgentSettings: 'Go to agent settings'
},
createChat: {
title: 'Knowledge-base Q&A - AI Assistant',
@ -1589,9 +1799,7 @@ export default {
custom: 'Custom Prompt',
disabledHint: 'Currently using the default prompt. Enable custom to apply the content below.',
placeholder: 'Enter the system prompt, or leave blank to use the default...',
tabHint: 'Configure separate prompts for sessions with web search on or off.',
tabWebOn: 'Web search enabled',
tabWebOff: 'Web search disabled'
tabHint: 'Unified system prompt using {{web_search_status}} placeholder for dynamic web search behavior'
},
reset: {
header: 'Reset to Default Prompt',
@ -1931,5 +2139,93 @@ export default {
createFailed: 'Failed to create MCP service',
updateFailed: 'Failed to update MCP service'
}
}
},
promptTemplate: {
selectTemplate: 'Select Template',
useTemplate: 'Use Template',
withKnowledgeBase: 'KB',
withWebSearch: 'Web Search',
systemPrompt: {
defaultKB: {
name: 'Knowledge Base Assistant',
desc: 'Basic knowledge base Q&A template for most scenarios',
},
expert: {
name: 'Domain Expert',
desc: 'Professional and in-depth answers for technical domains',
},
customerService: {
name: 'Customer Service',
desc: 'Friendly and warm service style for customer support',
},
techSupport: {
name: 'Technical Support',
desc: 'Professional technical problem solving with code examples',
},
pureChat: {
name: 'General Chat',
desc: 'General conversation assistant without knowledge base',
},
webSearch: {
name: 'Web Search Assistant',
desc: 'Combines web search for up-to-date information',
},
},
contextTemplate: {
default: {
name: 'Standard Template',
desc: 'Basic context template with clear references and questions',
},
detailed: {
name: 'Detailed Template',
desc: 'Complete template with detailed instructions and requirements',
},
simple: {
name: 'Simple Template',
desc: 'Minimal template format for simple Q&A scenarios',
},
qa: {
name: 'Q&A Template',
desc: 'Optimized template for Q&A scenarios',
},
},
rewriteSystem: {
default: {
name: 'Standard Rewrite',
desc: 'Standard rules for resolving references and completing omissions',
},
strict: {
name: 'Strict Rewrite',
desc: 'Stricter requirements for complete and independent questions',
},
},
rewriteUser: {
default: {
name: 'Standard Format',
desc: 'Standard format with conversation history and current question',
},
detailed: {
name: 'Detailed Format',
desc: 'Detailed format with task instructions',
},
},
fallback: {
default: {
name: 'Standard Fallback',
desc: 'Friendly message with suggestions when unable to answer',
},
polite: {
name: 'Polite Fallback',
desc: 'More polite and detailed unable-to-answer message',
},
brief: {
name: 'Brief Fallback',
desc: 'Short unable-to-answer message',
},
model: {
name: 'Model Fallback Prompt',
desc: 'Prompt to guide model to answer with general knowledge',
},
},
},
}

View File

@ -1733,10 +1733,11 @@ export default {
placeholderWithContext: 'Введите вопрос, ответ будет основан на выбранных выше базах знаний/файлах',
placeholderWebOnly: 'Введите вопрос, ответ будет основан на веб-поиске',
placeholderKbAndWeb: 'Введите вопрос, ответ будет основан на базе знаний и веб-поиске',
agentMode: 'Agent режим',
normalMode: 'Обычный режим',
placeholderAgent: 'Спросить {name}',
agentMode: 'Умный анализ',
normalMode: 'Быстрый ответ',
normalModeDesc: 'RAG-вопросы и ответы по базе знаний',
agentModeDesc: 'Шаблон рассуждений ReAct, многошаговое мышление',
agentModeDesc: 'Многошаговое мышление, глубокий анализ',
agentNotReadyTooltip: 'Agent не готов. Пожалуйста, завершите настройку.',
agentNotReadyDetail: 'Agent не готов. Пожалуйста, настройте следующее: {reasons}',
agentMissingAllowedTools: 'Разрешённые инструменты',

View File

@ -1,6 +1,7 @@
export default {
menu: {
knowledgeBase: "知识库",
agents: "智能体",
chat: "对话",
createChat: "创建对话",
tenant: "账户信息",
@ -297,15 +298,6 @@ export default {
selectKnowledgeBaseWarning: "请至少选择一个知识库",
processError: "处理出错",
},
agent: {
taskLabel: "任务:",
copy: "复制",
addToKnowledgeBase: "添加到知识库",
updatePlan: "更新计划",
webSearchFound: "找到 <strong>{count}</strong> 个网络搜索结果",
argumentsLabel: "参数",
toolFallback: "工具",
},
settings: {
title: "设置",
modelConfig: "模型配置",
@ -697,6 +689,7 @@ export default {
save: "保存",
delete: "删除",
edit: "编辑",
copy: "复制",
default: "默认",
create: "创建",
search: "搜索",
@ -735,6 +728,205 @@ export default {
knowledgeBase: "知识库",
noResult: "无结果",
},
agent: {
taskLabel: "任务:",
copy: "复制",
addToKnowledgeBase: "添加到知识库",
updatePlan: "更新计划",
webSearchFound: "找到 <strong>{count}</strong> 个网络搜索结果",
argumentsLabel: "参数",
toolFallback: "工具",
title: "智能体",
subtitle: "配置和管理您的智能体,自定义对话行为和能力",
createAgent: "创建智能体",
builtin: "内置",
noDescription: "暂无描述",
selectAgent: "选择智能体",
noAgents: "暂无智能体",
manageAgents: "管理",
builtinAgents: "内置智能体",
customAgents: "自定义智能体",
capabilities: {
normal: "快速响应,直接回答问题",
agent: "多步思考,深度分析复杂问题",
modelSpecified: "指定模型",
kbCount: "指定 {count} 个知识库",
kbAll: "可访问全部知识库",
kbDisabled: "禁用知识库",
rerankSpecified: "指定 ReRank 模型",
webSearchOn: "启用网络搜索",
webSearchOff: "禁用网络搜索",
hasPrompt: "自定义提示词",
default: "默认配置",
mcpEnabled: "启用 MCP 服务",
multiTurn: "多轮对话",
},
type: {
normal: "快速问答",
agent: "智能推理",
custom: "自定义",
},
mode: {
normal: "快速问答",
agent: "智能推理",
},
features: {
webSearch: "支持网络搜索",
knowledgeBase: "关联知识库",
mcp: "支持MCP服务",
multiTurn: "多轮对话",
},
empty: {
title: "暂无自定义智能体",
description: "点击右上角按钮创建您的第一个智能体",
},
delete: {
confirmTitle: "删除智能体",
confirmMessage: "确定要删除智能体「{name}」吗?此操作不可恢复。",
confirmButton: "确认删除",
},
messages: {
created: "智能体创建成功",
updated: "智能体更新成功",
deleted: "智能体已删除",
deleteFailed: "删除失败",
saveFailed: "保存失败",
builtinReadonly: "内置智能体不可编辑",
copied: "智能体复制成功",
copyFailed: "复制失败",
},
editor: {
createTitle: "创建智能体",
editTitle: "编辑智能体",
basicInfo: "基本信息",
basicInfoDesc: "配置智能体的基本信息",
modelConfig: "模型配置",
modelConfigDesc: "配置智能体的模型参数",
capabilities: "能力与工具",
capabilitiesDesc: "配置智能体的能力和工具",
toolsConfig: "工具配置",
toolsConfigDesc: "配置 Agent 可以使用的工具",
knowledgeConfig: "知识库",
knowledgeConfigDesc: "配置智能体可访问的知识库",
webSearchConfig: "网络搜索",
webSearchConfigDesc: "配置智能体的网络搜索能力",
configuration: "配置项",
name: "名称",
namePlaceholder: "请输入智能体名称",
nameRequired: "请输入智能体名称",
systemPromptRequired: "请输入系统提示词",
modelRequired: "请选择模型",
rerankModelRequired: "使用知识库时请选择 ReRank 模型",
contextsMissing: "开启知识库时,上下文模板必须包含 {{contexts}} 占位符",
queryMissingInContext: "上下文模板必须包含 {{query}} 占位符",
knowledgeBasesMissing: "建议在系统提示词中包含 {{knowledge_bases}} 占位符,以便模型了解可用的知识库",
queryMissingInRewrite: "改写用户提示词必须包含 {{query}} 占位符",
conversationMissing: "改写用户提示词必须包含 {{conversation}} 占位符",
queryMissingInFallback: "兜底提示词必须包含 {{query}} 占位符",
avatar: "图标",
avatarPlaceholder: "输入 Emoji 或点击选择",
description: "描述",
descriptionPlaceholder: "请输入智能体描述",
baseType: "基础类型",
normalDesc: "快速响应,直接回答问题",
agentDesc: "多步思考,深度分析复杂问题",
model: "模型",
modelPlaceholder: "请选择模型",
systemPrompt: "系统提示词",
systemPromptPlaceholder: "自定义系统提示词,定义智能体的行为和角色(使用 {{web_search_status}} 占位符动态控制网络搜索行为)",
defaultPromptHint: "留空将使用以下系统默认提示词:",
defaultContextTemplateHint: "留空将使用以下系统默认上下文模板:",
contextTemplateRequired: "请输入上下文模板",
availablePlaceholders: "可用占位符",
placeholderHint: "输入 {{ 触发自动补全",
temperature: "温度",
welcomeMessage: "欢迎消息",
welcomeMessagePlaceholder: "选择该智能体时显示的欢迎消息",
suggestedPrompts: "推荐问题",
mode: "运行模式",
webSearch: "网络搜索",
webSearchMaxResults: "最大搜索结果数",
knowledgeBases: "关联知识库",
allKnowledgeBases: "全部知识库",
allKnowledgeBasesDesc: "智能体可访问所有知识库",
selectedKnowledgeBases: "指定知识库",
selectedKnowledgeBasesDesc: "仅访问选定的知识库",
noKnowledgeBase: "不使用知识库",
noKnowledgeBaseDesc: "纯模型对话,不检索知识库",
selectKnowledgeBases: "选择知识库",
rerankModel: "ReRank 模型",
rerankModelDesc: "用于对知识库检索结果进行重排序,提高回答准确性",
rerankModelPlaceholder: "请选择 ReRank 模型",
maxIterations: "最大迭代次数",
allowedTools: "允许的工具",
multiTurn: "多轮对话",
historyTurns: "保留轮数",
// 检索策略
retrievalStrategy: "检索策略",
embeddingTopK: "向量召回数量",
keywordThreshold: "关键词阈值",
vectorThreshold: "向量阈值",
rerankTopK: "重排数量",
rerankThreshold: "重排阈值",
// 多轮对话
conversationSettings: "多轮对话",
// 高级设置
advancedSettings: "高级设置",
contextTemplate: "上下文模板",
contextTemplatePlaceholder: "自定义上下文模板...",
availableContextPlaceholders: "可用占位符",
placeholderQuery: "用户的问题",
placeholderContexts: "检索到的内容列表",
placeholderCurrentTime: "当前时间(格式:2006-01-02 15:04:05)",
placeholderCurrentWeek: "当前星期(如:星期一)",
enableQueryExpansion: "查询扩展",
enableRewrite: "问题改写",
rewritePromptSystem: "改写系统提示词",
rewritePromptSystemPlaceholder: "留空使用系统默认提示词",
rewritePromptUser: "改写用户提示词",
rewritePromptUserPlaceholder: "留空使用系统默认提示词",
maxCompletionTokens: "最大生成Token数",
fallbackStrategy: "兜底策略",
fallbackResponse: "固定回复内容",
fallbackResponsePlaceholder: "抱歉,我无法回答这个问题。",
fallbackPrompt: "兜底提示词",
fallbackPromptPlaceholder: "留空使用系统默认提示词",
},
selector: {
title: "选择智能体",
builtinSection: "内置智能体",
customSection: "我的智能体",
addNew: "添加新智能体",
current: "当前",
},
// 内置智能体信息
builtinInfo: {
quickAnswer: {
name: "快速问答",
description: "基于知识库的 RAG 问答,快速准确地回答问题",
},
smartReasoning: {
name: "智能推理",
description: "ReAct 推理框架,支持多步思考和工具调用",
},
deepResearcher: {
name: "深度研究员",
description: "专注于深度研究和综合分析,能够制定研究计划、多维度检索信息、深入思考并给出全面的分析报告",
},
dataAnalyst: {
name: "数据分析师",
description: "专注于数据库查询和数据分析,能够理解业务需求、构建SQL查询、分析数据并提供洞察",
},
knowledgeGraphExpert: {
name: "知识图谱专家",
description: "专注于知识图谱查询和关系分析,能够探索实体关系、发现隐藏联系并构建知识网络",
},
documentAssistant: {
name: "文档助手",
description: "专注于文档检索和内容整理,能够快速定位文档、提取关键信息并生成摘要",
},
},
},
file: {
upload: "上传文件",
uploadSuccess: "文件上传成功",
@ -1465,10 +1657,11 @@ export default {
placeholderWithContext: "输入问题,将基于上方选中的知识库/文件回答",
placeholderWebOnly: "输入问题,将结合网络搜索回答",
placeholderKbAndWeb: "输入问题,将基于知识库和网络搜索回答",
agentMode: "Agent 模式",
normalMode: "普通模式",
placeholderAgent: "向 {name} 提问",
agentMode: "智能推理",
normalMode: "快速问答",
normalModeDesc: "基于知识库的 RAG 问答",
agentModeDesc: "ReAct 推理框架,多步思考",
agentModeDesc: "多步思考,深度分析",
agentNotReadyTooltip: "Agent 未就绪,请先在设置中完成配置",
agentNotReadyDetail:
"Agent 未就绪,需要配置以下内容:{reasons}",
@ -1476,6 +1669,14 @@ export default {
agentMissingSummaryModel: "对话模型(Summary Model)",
agentMissingRerankModel: "重排模型(Rerank Model)",
goToSettings: "前往设置 →",
customAgentNotReadyTooltip: "智能体未就绪,请先完成配置",
customAgentNotReadyDetail: "智能体未就绪,需要配置以下内容:{reasons}",
customAgentMissingSummaryModel: "对话模型(Summary Model)",
customAgentMissingRerankModel: "重排模型(Rerank Model)",
goToAgentEditor: "前往配置 →",
builtinAgentNotReadyDetail: "内置智能体「{agentName}」未就绪,需要配置以下内容:{reasons}",
builtinAgentSettingName: "智能推理",
builtinNormalSettingName: "快速问答",
webSearch: {
toggleOn: "开启网络搜索",
toggleOff: "关闭网络搜索",
@ -1494,8 +1695,9 @@ export default {
enterContent: "请先输入内容!",
selectKnowledge: "请先选择知识库!",
replying: "正在回复中,请稍后再试!",
agentSwitchedOn: "已切换到 Agent 模式",
agentSwitchedOff: "已切换到普通模式",
agentSwitchedOn: "已切换到智能推理",
agentSwitchedOff: "已切换到快速问答",
agentSelected: "已选择智能体「{name}」",
agentEnabled: "Agent 模式已启用",
agentDisabled: "Agent 模式已禁用",
agentNotReadyDetail:
@ -1509,6 +1711,14 @@ export default {
stopSuccess: "已停止生成",
stopFailed: "停止失败,请重试",
},
webSearchDisabledByAgent: "当前智能体已禁用网络搜索",
webSearchForcedByAgent: "当前智能体已启用网络搜索,无法关闭",
kbLockedByAgent: "当前智能体已锁定知识库配置",
kbDisabledByAgent: "当前智能体已禁用知识库功能",
cannotRemoveAgentKb: "智能体配置的知识库无法移除",
agentConfiguredKb: "由智能体配置,不可删除",
modelLockedByAgent: "当前智能体已锁定模型配置",
goToAgentSettings: "去设置智能体",
},
agentSettings: {
title: "Agent 配置",
@ -1568,9 +1778,7 @@ export default {
custom: "自定义 Prompt",
disabledHint: "当前使用系统默认 Prompt,开启自定义后才会应用下方内容。",
placeholder: "请输入系统 Prompt,或留空使用默认 Prompt...",
tabHint: "根据是否启用网络搜索分别配置系统 Prompt。",
tabWebOn: "网络搜索已启用",
tabWebOff: "网络搜索未启用",
tabHint: "统一的系统提示词,使用 {{web_search_status}} 占位符动态控制网络搜索行为",
},
reset: {
header: "恢复默认 Prompt",
@ -1913,4 +2121,92 @@ export default {
updateFailed: "更新 MCP 服务失败",
},
},
promptTemplate: {
selectTemplate: "选择模板",
useTemplate: "使用模板",
withKnowledgeBase: "知识库",
withWebSearch: "网络搜索",
systemPrompt: {
defaultKB: {
name: "知识库问答助手",
desc: "基础的知识库问答模板,适用于大多数场景",
},
expert: {
name: "领域专家助手",
desc: "专业深入的解答风格,适合技术或专业领域",
},
customerService: {
name: "客服助手",
desc: "友善热情的服务风格,适合客户服务场景",
},
techSupport: {
name: "技术支持",
desc: "专业的技术问题解答,包含代码示例",
},
pureChat: {
name: "通用对话",
desc: "不依赖知识库的通用对话助手",
},
webSearch: {
name: "网络搜索助手",
desc: "结合网络搜索获取最新信息",
},
},
contextTemplate: {
default: {
name: "标准模板",
desc: "基础的上下文模板,清晰展示参考资料和问题",
},
detailed: {
name: "详细模板",
desc: "包含详细说明和回答要求的完整模板",
},
simple: {
name: "简洁模板",
desc: "精简的模板格式,适合简单问答场景",
},
qa: {
name: "问答模板",
desc: "针对问答场景优化的模板",
},
},
rewriteSystem: {
default: {
name: "标准改写",
desc: "消解指代、补全省略的标准改写规则",
},
strict: {
name: "严格改写",
desc: "更严格的改写要求,确保问题完整独立",
},
},
rewriteUser: {
default: {
name: "标准格式",
desc: "包含对话历史和当前问题的标准格式",
},
detailed: {
name: "详细格式",
desc: "带有任务说明的详细格式",
},
},
fallback: {
default: {
name: "标准兜底",
desc: "友好告知无法回答并提供建议",
},
polite: {
name: "礼貌兜底",
desc: "更加礼貌详细的无法回答提示",
},
brief: {
name: "简洁兜底",
desc: "简短的无法回答提示",
},
model: {
name: "模型兜底提示",
desc: "引导模型基于通用知识回答的提示词",
},
},
},
};

View File

@ -51,6 +51,12 @@ const router = createRouter({
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "agents",
name: "agentList",
component: () => import("../views/agent/AgentList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "creatChat",
name: "globalCreatChat",

View File

@ -18,6 +18,7 @@ const createMenuChildren = () => reactive<MenuChild[]>([])
export const useMenuStore = defineStore('menuStore', () => {
const menuArr = reactive<MenuItem[]>([
{ title: '', titleKey: 'menu.knowledgeBase', icon: 'zhishiku', path: 'knowledge-bases' },
{ title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents' },
{
title: '',
titleKey: 'menu.chat',
@ -52,14 +53,14 @@ export const useMenuStore = defineStore('menuStore', () => {
)
const clearMenuArr = () => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
if (chatMenu && chatMenu.children) {
chatMenu.children = createMenuChildren()
}
}
const updatemenuArr = (obj: any) => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
if (!chatMenu.children) {
chatMenu.children = createMenuChildren()
}
@ -70,7 +71,7 @@ export const useMenuStore = defineStore('menuStore', () => {
}
const updataMenuChildren = (item: MenuChild) => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
if (!chatMenu.children) {
chatMenu.children = createMenuChildren()
}
@ -78,7 +79,7 @@ export const useMenuStore = defineStore('menuStore', () => {
}
const updatasessionTitle = (sessionId: string, title: string) => {
const chatMenu = menuArr[1]
const chatMenu = menuArr[2]
chatMenu.children?.forEach((item: MenuChild) => {
if (item.id === sessionId) {
item.title = title

View File

@ -1,4 +1,5 @@
import { defineStore } from "pinia";
import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent";
// 定义设置接口
interface Settings {
@ -13,6 +14,7 @@ interface Settings {
ollamaConfig: OllamaConfig; // Ollama配置
webSearchEnabled: boolean; // 网络搜索是否启用
conversationModels: ConversationModels;
selectedAgentId: string; // 当前选中的智能体ID
}
// Agent 配置接口
@ -20,9 +22,7 @@ interface AgentConfig {
maxIterations: number;
temperature: number;
allowedTools: string[];
system_prompt_web_enabled?: string;
system_prompt_web_disabled?: string;
use_custom_system_prompt?: boolean;
system_prompt?: string; // Unified system prompt (uses {{web_search_status}} placeholder)
}
interface ConversationModels {
@ -68,9 +68,7 @@ const defaultSettings: Settings = {
maxIterations: 5,
temperature: 0.7,
allowedTools: [], // 默认为空,需要通过 API 从后端加载
system_prompt_web_enabled: "",
system_prompt_web_disabled: "",
use_custom_system_prompt: false
system_prompt: "",
},
selectedKnowledgeBases: [], // 默认为空数组
selectedFiles: [], // 默认为空数组
@ -89,7 +87,8 @@ const defaultSettings: Settings = {
summaryModelId: "",
rerankModelId: "",
selectedChatModelId: "", // 用户当前选择的对话模型ID
}
},
selectedAgentId: BUILTIN_QUICK_ANSWER_ID, // 默认选中快速问答模式
};
export const useSettingsStore = defineStore("settings", {
@ -114,6 +113,16 @@ export const useSettingsStore = defineStore("settings", {
)
},
// 普通模式(快速回答)是否就绪
// 需要满足:1) 设置了对话模型 2) 设置了重排模型
isNormalModeReady: (state) => {
const models = state.settings.conversationModels || defaultSettings.conversationModels
return Boolean(
models.summaryModelId && models.summaryModelId.trim() !== '' &&
models.rerankModelId && models.rerankModelId.trim() !== ''
)
},
// 获取 Agent 配置
agentConfig: (state) => state.settings.agentConfig || defaultSettings.agentConfig,
@ -124,6 +133,9 @@ export const useSettingsStore = defineStore("settings", {
// 网络搜索是否启用
isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,
// 当前选中的智能体ID
selectedAgentId: (state) => state.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,
},
actions: {
@ -301,6 +313,30 @@ export const useSettingsStore = defineStore("settings", {
getSelectedFiles(): string[] {
return this.settings.selectedFiles || [];
},
// 选择智能体
selectAgent(agentId: string) {
this.settings.selectedAgentId = agentId;
// 根据智能体类型自动切换 Agent 模式
if (agentId === BUILTIN_QUICK_ANSWER_ID) {
this.settings.isAgentEnabled = false;
} else if (agentId === BUILTIN_SMART_REASONING_ID) {
this.settings.isAgentEnabled = true;
}
// 自定义智能体需要根据其配置来决定
// 切换智能体时重置知识库和文件选择状态
// 因为不同智能体关联的知识库不同,需要清空用户之前的选择
this.settings.selectedKnowledgeBases = [];
this.settings.selectedFiles = [];
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
// 获取选中的智能体ID
getSelectedAgentId(): string {
return this.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID;
},
},
});

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,894 @@
<template>
<div class="agent-list-container">
<!-- 头部 -->
<div class="header">
<div class="header-title">
<h2>{{ $t('agent.title') }}</h2>
<p class="header-subtitle">{{ $t('agent.subtitle') }}</p>
</div>
</div>
<div class="header-divider"></div>
<!-- 卡片网格 -->
<div v-if="agents.length > 0" class="agent-card-wrap">
<div
v-for="agent in agents"
:key="agent.id"
class="agent-card"
:class="{
'is-builtin': agent.is_builtin,
'agent-mode-normal': agent.config?.agent_mode === 'quick-answer',
'agent-mode-agent': agent.config?.agent_mode === 'smart-reasoning'
}"
@click="handleCardClick(agent)"
>
<!-- 装饰星星 -->
<div class="card-decoration">
<svg class="star-icon" width="24" height="24" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" stroke="currentColor" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round" fill="currentColor" fill-opacity="0.15"/>
</svg>
<svg class="star-icon small" width="14" height="14" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" stroke="currentColor" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round" fill="currentColor" fill-opacity="0.15"/>
</svg>
</div>
<!-- 卡片头部 -->
<div class="card-header">
<div class="card-header-left">
<!-- 内置智能体使用简洁图标 -->
<div v-if="agent.is_builtin" class="builtin-avatar" :class="agent.config?.agent_mode === 'smart-reasoning' ? 'agent' : 'normal'">
<t-icon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="18px" />
</div>
<!-- 自定义智能体使用 AgentAvatar -->
<AgentAvatar v-else :name="agent.name" size="medium" />
<span class="card-title" :title="agent.name">{{ agent.name }}</span>
</div>
<t-popup
v-model="agent.showMore"
overlayClassName="card-more-popup"
:on-visible-change="(visible: boolean) => onVisibleChange(visible, agent)"
trigger="click"
destroy-on-close
placement="bottom-right"
>
<div
class="more-wrap"
@click.stop
:class="{ 'active-more': agent.showMore }"
>
<img class="more-icon" src="@/assets/img/more.png" alt="" />
</div>
<template #content>
<div class="popup-menu">
<div class="popup-menu-item" @click="handleEdit(agent)">
<t-icon class="menu-icon" name="edit" />
<span>{{ $t('common.edit') }}</span>
</div>
<div class="popup-menu-item" @click="handleCopy(agent)">
<t-icon class="menu-icon" name="file-copy" />
<span>{{ $t('common.copy') }}</span>
</div>
<div v-if="!agent.is_builtin" class="popup-menu-item delete" @click="handleDelete(agent)">
<t-icon class="menu-icon" name="delete" />
<span>{{ $t('common.delete') }}</span>
</div>
</div>
</template>
</t-popup>
</div>
<!-- 卡片内容 -->
<div class="card-content">
<div class="card-description">
{{ agent.description || $t('agent.noDescription') }}
</div>
</div>
<!-- 卡片底部 -->
<div class="card-bottom">
<div class="bottom-left">
<div class="feature-badges">
<t-tooltip :content="agent.config?.agent_mode === 'smart-reasoning' ? $t('agent.mode.agent') : $t('agent.mode.normal')" placement="top">
<div class="feature-badge" :class="{ 'mode-normal': agent.config?.agent_mode === 'quick-answer', 'mode-agent': agent.config?.agent_mode === 'smart-reasoning' }">
<t-icon :name="agent.config?.agent_mode === 'smart-reasoning' ? 'control-platform' : 'chat'" size="14px" />
</div>
</t-tooltip>
<t-tooltip v-if="agent.config?.web_search_enabled" :content="$t('agent.features.webSearch')" placement="top">
<div class="feature-badge web-search">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="1.2" fill="none"/>
<ellipse cx="8" cy="8" rx="2.5" ry="6" stroke="currentColor" stroke-width="1.2" fill="none"/>
<line x1="2" y1="6" x2="14" y2="6" stroke="currentColor" stroke-width="1.2"/>
<line x1="2" y1="10" x2="14" y2="10" stroke="currentColor" stroke-width="1.2"/>
</svg>
</div>
</t-tooltip>
<t-tooltip v-if="agent.config?.knowledge_bases?.length || agent.config?.kb_selection_mode === 'all'" :content="$t('agent.features.knowledgeBase')" placement="top">
<div class="feature-badge knowledge">
<t-icon name="folder" size="16px" />
</div>
</t-tooltip>
<t-tooltip v-if="agent.config?.mcp_services?.length || agent.config?.mcp_selection_mode === 'all'" :content="$t('agent.features.mcp')" placement="top">
<div class="feature-badge mcp">
<t-icon name="extension" size="16px" />
</div>
</t-tooltip>
<t-tooltip v-if="agent.config?.multi_turn_enabled" :content="$t('agent.features.multiTurn')" placement="top">
<div class="feature-badge multi-turn">
<t-icon name="chat-bubble" size="16px" />
</div>
</t-tooltip>
</div>
</div>
<div v-if="agent.is_builtin" class="builtin-badge">
<t-icon name="lock-on" size="12px" />
<span>{{ $t('agent.builtin') }}</span>
</div>
<span v-else-if="agent.updated_at" class="card-time">{{ formatDate(agent.updated_at) }}</span>
</div>
</div>
</div>
<!-- 空状态 -->
<div v-else-if="!loading" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
<span class="empty-txt">{{ $t('agent.empty.title') }}</span>
<span class="empty-desc">{{ $t('agent.empty.description') }}</span>
</div>
<!-- 删除确认对话框 -->
<t-dialog
v-model:visible="deleteVisible"
dialogClassName="del-agent-dialog"
:closeBtn="false"
:cancelBtn="null"
:confirmBtn="null"
>
<div class="circle-wrap">
<div class="dialog-header">
<img class="circle-img" src="@/assets/img/circle.png" alt="">
<span class="circle-title">{{ $t('agent.delete.confirmTitle') }}</span>
</div>
<span class="del-circle-txt">
{{ $t('agent.delete.confirmMessage', { name: deletingAgent?.name ?? '' }) }}
</span>
<div class="circle-btn">
<span class="circle-btn-txt" @click="deleteVisible = false">{{ $t('common.cancel') }}</span>
<span class="circle-btn-txt confirm" @click="confirmDelete">{{ $t('agent.delete.confirmButton') }}</span>
</div>
</div>
</t-dialog>
<!-- 智能体编辑器弹窗 -->
<AgentEditorModal
:visible="editorVisible"
:mode="editorMode"
:agent="editingAgent"
:initialSection="editorInitialSection"
@update:visible="editorVisible = $event"
@success="handleEditorSuccess"
/>
</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { listAgents, deleteAgent, copyAgent, type CustomAgent } from '@/api/agent'
import { formatStringDate } from '@/utils/index'
import { useI18n } from 'vue-i18n'
import AgentEditorModal from './AgentEditorModal.vue'
import AgentAvatar from '@/components/AgentAvatar.vue'
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
interface AgentWithUI extends CustomAgent {
showMore?: boolean
}
const agents = ref<AgentWithUI[]>([])
const loading = ref(false)
const deleteVisible = ref(false)
const deletingAgent = ref<AgentWithUI | null>(null)
const editorVisible = ref(false)
const editorMode = ref<'create' | 'edit'>('create')
const editingAgent = ref<CustomAgent | null>(null)
const editorInitialSection = ref<string>('basic')
const fetchList = () => {
loading.value = true
return listAgents().then((res: any) => {
const data = res.data || []
// 显示所有智能体(包括内置智能体)
agents.value = data.map((agent: CustomAgent) => ({
...agent,
showMore: false
}))
// 检查 URL 中是否有 edit 参数,如果有则打开对应智能体的编辑模态框
checkAndOpenEditModal()
}).finally(() => loading.value = false)
}
// 检查 URL 参数并打开编辑模态框
const checkAndOpenEditModal = () => {
const editId = route.query.edit as string
const section = route.query.section as string
if (editId) {
const agent = agents.value.find(a => a.id === editId)
if (agent) {
editingAgent.value = agent
editorMode.value = 'edit'
editorInitialSection.value = section || 'basic'
editorVisible.value = true
}
// 清除 URL 中的参数
router.replace({ path: route.path, query: {} })
}
}
// 监听菜单创建智能体事件
const handleOpenAgentEditor = (event: CustomEvent) => {
if (event.detail?.mode === 'create') {
openCreateModal()
}
}
onMounted(() => {
fetchList()
window.addEventListener('openAgentEditor', handleOpenAgentEditor as EventListener)
})
onUnmounted(() => {
window.removeEventListener('openAgentEditor', handleOpenAgentEditor as EventListener)
})
const onVisibleChange = (visible: boolean, agent: AgentWithUI) => {
if (!visible) {
agent.showMore = false
}
}
const handleCardClick = (agent: AgentWithUI) => {
// 如果弹窗正在显示,不触发编辑
if (agent.showMore) {
return
}
// 点击卡片编辑(包括内置智能体)
handleEdit(agent)
}
const handleEdit = (agent: AgentWithUI) => {
agent.showMore = false
editingAgent.value = agent
editorMode.value = 'edit'
editorVisible.value = true
}
const handleDelete = (agent: AgentWithUI) => {
agent.showMore = false
deletingAgent.value = agent
deleteVisible.value = true
}
const handleCopy = (agent: AgentWithUI) => {
agent.showMore = false
copyAgent(agent.id).then((res: any) => {
if (res.data) {
MessagePlugin.success(t('agent.messages.copied'))
fetchList()
} else {
MessagePlugin.error(res.message || t('agent.messages.copyFailed'))
}
}).catch((e: any) => {
MessagePlugin.error(e?.message || t('agent.messages.copyFailed'))
})
}
const confirmDelete = () => {
if (!deletingAgent.value) return
deleteAgent(deletingAgent.value.id).then((res: any) => {
if (res.success) {
MessagePlugin.success(t('agent.messages.deleted'))
deleteVisible.value = false
deletingAgent.value = null
fetchList()
} else {
MessagePlugin.error(res.message || t('agent.messages.deleteFailed'))
}
}).catch((e: any) => {
MessagePlugin.error(e?.message || t('agent.messages.deleteFailed'))
})
}
const handleEditorSuccess = () => {
editorVisible.value = false
editingAgent.value = null
fetchList()
}
const formatDate = (dateStr: string) => {
if (!dateStr) return ''
return formatStringDate(new Date(dateStr))
}
// 暴露创建方法供外部调用
const openCreateModal = () => {
editingAgent.value = null
editorMode.value = 'create'
editorVisible.value = true
}
defineExpose({
openCreateModal
})
</script>
<style scoped lang="less">
.agent-list-container {
padding: 24px 44px;
margin: 0 20px;
height: calc(100vh);
overflow-y: auto;
box-sizing: border-box;
flex: 1;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
.header-title {
display: flex;
flex-direction: column;
gap: 4px;
}
h2 {
margin: 0;
color: #000000e6;
font-family: "PingFang SC";
font-size: 24px;
font-weight: 600;
line-height: 32px;
}
}
.header-subtitle {
margin: 0;
color: #00000099;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 20px;
}
.header-divider {
height: 1px;
background: #e7ebf0;
margin-bottom: 20px;
}
.agent-card-wrap {
display: grid;
gap: 16px;
grid-template-columns: 1fr;
}
.agent-card {
border: 1px solid #f0f0f0;
border-radius: 12px;
overflow: hidden;
box-sizing: border-box;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
background: #fff;
position: relative;
cursor: pointer;
transition: all 0.25s ease;
padding: 16px 18px;
display: flex;
flex-direction: column;
height: 160px;
&:hover {
border-color: #07c05f;
box-shadow: 0 4px 12px rgba(7, 192, 95, 0.12);
}
// 普通模式样式
&.agent-mode-normal {
background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);
border-color: #e8f5ed;
&:hover {
border-color: #07c05f;
background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
}
.card-decoration {
color: rgba(7, 192, 95, 0.35);
}
&:hover .card-decoration {
color: rgba(7, 192, 95, 0.5);
}
}
// Agent 模式样式
&.agent-mode-agent {
background: linear-gradient(135deg, #ffffff 0%, #f8f5ff 100%);
border-color: #ede8ff;
&:hover {
border-color: #7c4dff;
box-shadow: 0 4px 12px rgba(124, 77, 255, 0.12);
background: linear-gradient(135deg, #ffffff 0%, #f3efff 100%);
}
.card-decoration {
color: rgba(124, 77, 255, 0.35);
}
&:hover .card-decoration {
color: rgba(124, 77, 255, 0.5);
}
}
// 确保内容在装饰之上
.card-header,
.card-content,
.card-bottom {
position: relative;
z-index: 1;
}
}
.card-decoration {
position: absolute;
top: 12px;
right: 50px;
display: flex;
align-items: flex-start;
gap: 4px;
pointer-events: none;
z-index: 0;
transition: color 0.25s ease;
.star-icon {
opacity: 0.9;
&.small {
margin-top: 14px;
opacity: 0.7;
}
}
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.card-header-left {
display: flex;
align-items: center;
gap: 10px;
flex: 1;
min-width: 0;
}
.card-title {
color: #1a1a1a;
font-family: "PingFang SC";
font-size: 15px;
font-weight: 600;
line-height: 22px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.builtin-badge {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 2px 8px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.04);
color: #666;
font-family: "PingFang SC";
font-size: 11px;
font-weight: 500;
flex-shrink: 0;
}
.builtin-avatar {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
flex-shrink: 0;
&.normal {
background: linear-gradient(135deg, rgba(7, 192, 95, 0.15) 0%, rgba(7, 192, 95, 0.08) 100%);
color: #059669;
}
&.agent {
background: linear-gradient(135deg, rgba(124, 77, 255, 0.15) 0%, rgba(124, 77, 255, 0.08) 100%);
color: #7c4dff;
}
}
.edit-btn {
display: flex;
width: 32px;
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 {
display: flex;
width: 28px;
height: 28px;
justify-content: center;
align-items: center;
border-radius: 6px;
cursor: pointer;
flex-shrink: 0;
transition: all 0.2s ease;
opacity: 0;
.agent-card:hover & {
opacity: 0.6;
}
&:hover {
background: rgba(0, 0, 0, 0.05);
opacity: 1 !important;
}
&.active-more {
background: rgba(0, 0, 0, 0.06);
opacity: 1 !important;
}
.more-icon {
width: 16px;
height: 16px;
}
}
.card-content {
flex: 1;
margin-bottom: 12px;
overflow: hidden;
}
.card-description {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
line-clamp: 2;
overflow: hidden;
color: #666;
font-family: "PingFang SC";
font-size: 13px;
font-weight: 400;
line-height: 20px;
}
.card-bottom {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: auto;
padding-top: 12px;
border-top: 1px solid #f0f0f0;
}
.bottom-left {
display: flex;
align-items: center;
gap: 8px;
}
.feature-badges {
display: flex;
align-items: center;
gap: 4px;
}
.feature-badge {
display: flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border-radius: 6px;
cursor: default;
transition: background 0.2s ease;
&.mode-normal {
background: rgba(7, 192, 95, 0.08);
color: #059669;
&:hover {
background: rgba(7, 192, 95, 0.12);
}
}
&.mode-agent {
background: rgba(124, 77, 255, 0.08);
color: #7c4dff;
&:hover {
background: rgba(124, 77, 255, 0.12);
}
}
&.web-search {
background: rgba(255, 152, 0, 0.08);
color: #f59e0b;
&:hover {
background: rgba(255, 152, 0, 0.12);
}
}
&.knowledge {
background: rgba(7, 192, 95, 0.08);
color: #059669;
&:hover {
background: rgba(7, 192, 95, 0.12);
}
}
&.mcp {
background: rgba(236, 72, 153, 0.08);
color: #ec4899;
&:hover {
background: rgba(236, 72, 153, 0.12);
}
}
&.multi-turn {
background: rgba(59, 130, 246, 0.08);
color: #3b82f6;
&:hover {
background: rgba(59, 130, 246, 0.12);
}
}
}
.card-time {
color: #999;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 400;
}
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 60px 20px;
.empty-img {
width: 162px;
height: 162px;
margin-bottom: 20px;
}
.empty-txt {
color: #00000099;
font-family: "PingFang SC";
font-size: 16px;
font-weight: 600;
line-height: 26px;
margin-bottom: 8px;
}
.empty-desc {
color: #00000066;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 22px;
}
}
// 响应式布局
@media (min-width: 900px) {
.agent-card-wrap {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1250px) {
.agent-card-wrap {
grid-template-columns: repeat(3, 1fr);
}
}
@media (min-width: 1600px) {
.agent-card-wrap {
grid-template-columns: repeat(4, 1fr);
}
}
// 删除确认对话框样式
:deep(.del-agent-dialog) {
padding: 0px !important;
border-radius: 6px !important;
.t-dialog__header {
display: none;
}
.t-dialog__body {
padding: 16px;
}
.t-dialog__footer {
padding: 0;
}
}
:deep(.t-dialog__position.t-dialog--top) {
padding-top: 40vh !important;
}
.circle-wrap {
.dialog-header {
display: flex;
align-items: center;
margin-bottom: 8px;
}
.circle-img {
width: 20px;
height: 20px;
margin-right: 8px;
}
.circle-title {
color: #000000e6;
font-family: "PingFang SC";
font-size: 16px;
font-weight: 600;
line-height: 24px;
}
.del-circle-txt {
color: #00000099;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 22px;
display: inline-block;
margin-left: 29px;
margin-bottom: 21px;
}
.circle-btn {
height: 22px;
width: 100%;
display: flex;
justify-content: flex-end;
}
.circle-btn-txt {
color: #000000e6;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 22px;
cursor: pointer;
&:hover {
opacity: 0.8;
}
}
.confirm {
color: #FA5151;
margin-left: 40px;
&:hover {
opacity: 0.8;
}
}
}
</style>
<style lang="less">
// 更多操作弹窗样式
.card-more-popup {
z-index: 99 !important;
.t-popup__content {
padding: 6px 0 !important;
margin-top: 6px !important;
min-width: 140px;
border-radius: 6px !important;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
border: 1px solid #e7ebf0 !important;
}
}
.popup-menu {
display: flex;
flex-direction: column;
}
.popup-menu-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
cursor: pointer;
transition: all 0.2s ease;
color: #000000e6;
font-family: "PingFang SC";
font-size: 14px;
font-weight: 400;
line-height: 20px;
.menu-icon {
font-size: 16px;
flex-shrink: 0;
color: #00000099;
transition: color 0.2s ease;
}
&:hover {
background: #f7f9fc;
.menu-icon {
color: #000000e6;
}
}
&.delete {
color: #000000e6;
&:hover {
background: #fff1f0;
color: #fa5151;
.menu-icon {
color: #fa5151;
}
}
}
}
</style>

View File

@ -314,6 +314,8 @@ const sendMsg = async (value, modelId = '', mentionedItems = []) => {
const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
const knowledgeIds = useSettingsStoreInstance.settings.selectedFiles || [];
// Get selected agent ID
const selectedAgentId = useSettingsStoreInstance.selectedAgentId || '';
// Use agent-chat endpoint when agent is enabled, otherwise use knowledge-chat
@ -327,6 +329,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = []) => {
knowledge_base_ids: kbIds,
knowledge_ids: knowledgeIds,
agent_enabled: agentEnabled,
agent_id: selectedAgentId, // 传递选中的智能体 ID
web_search_enabled: webSearchEnabled,
summary_model_id: modelId,
mcp_service_ids: mcpServiceIds,

View File

@ -116,23 +116,14 @@
<!-- 卡片底部 -->
<div class="card-bottom">
<div class="bottom-left">
<div class="type-badge" :class="{ 'document': (kb.type || 'document') === 'document', 'faq': kb.type === 'faq' }">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" size="14px" />
<span>
{{ kb.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument') }}
({{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }})
</span>
<t-tooltip
v-if="kb.isProcessing"
:content="kb.type === 'document' && (kb.processing_count || 0) > 0
? $t('knowledgeList.processingDocuments', { count: kb.processing_count || 0 })
: $t('knowledgeList.processing')"
placement="top"
>
<t-icon name="loading" size="14px" class="processing-icon" />
</t-tooltip>
</div>
<div class="feature-badges">
<t-tooltip :content="kb.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument')" placement="top">
<div class="feature-badge" :class="{ 'type-document': (kb.type || 'document') === 'document', 'type-faq': kb.type === 'faq' }">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" size="14px" />
<span class="badge-count">{{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }}</span>
<t-icon v-if="kb.isProcessing" name="loading" size="12px" class="processing-icon" />
</div>
</t-tooltip>
<t-tooltip v-if="kb.extract_config?.enabled" :content="$t('knowledgeList.features.knowledgeGraph')" placement="top">
<div class="feature-badge kg">
<t-icon name="relation" size="14px" />
@ -700,27 +691,28 @@ const handleUploadFinishedEvent = (event: Event) => {
.kb-card-wrap {
display: grid;
gap: 20px;
gap: 16px;
grid-template-columns: 1fr;
}
.kb-card {
border: 2px solid #fbfbfb;
border-radius: 6px;
border: 1px solid #f0f0f0;
border-radius: 12px;
overflow: hidden;
box-sizing: border-box;
box-shadow: 0 0 8px 0 #00000005;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
background: #fff;
position: relative;
cursor: pointer;
transition: all 0.2s ease;
padding: 12px 16px 14px;
transition: all 0.25s ease;
padding: 16px 18px;
display: flex;
flex-direction: column;
min-height: 150px;
height: 160px;
&:hover {
border-color: #07c05f;
box-shadow: 0 4px 12px rgba(7, 192, 95, 0.12);
}
&.uninitialized {
@ -731,12 +723,12 @@ const handleUploadFinishedEvent = (event: Event) => {
&.kb-type-document {
background: linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);
border-color: #e8f5ed;
&:hover {
border-color: #07c05f;
background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
}
// 右上角装饰
&::after {
content: '';
@ -746,7 +738,7 @@ const handleUploadFinishedEvent = (event: Event) => {
width: 60px;
height: 60px;
background: linear-gradient(135deg, rgba(7, 192, 95, 0.08) 0%, transparent 100%);
border-radius: 0 6px 0 100%;
border-radius: 0 12px 0 100%;
pointer-events: none;
z-index: 0;
}
@ -756,12 +748,13 @@ const handleUploadFinishedEvent = (event: Event) => {
&.kb-type-faq {
background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
border-color: #e6f0ff;
&:hover {
border-color: #0052d9;
box-shadow: 0 4px 12px rgba(0, 82, 217, 0.12);
background: linear-gradient(135deg, #ffffff 0%, #eff6ff 100%);
}
// 右上角装饰
&::after {
content: '';
@ -771,7 +764,7 @@ const handleUploadFinishedEvent = (event: Event) => {
width: 60px;
height: 60px;
background: linear-gradient(135deg, rgba(0, 82, 217, 0.08) 0%, transparent 100%);
border-radius: 0 6px 0 100%;
border-radius: 0 12px 0 100%;
pointer-events: none;
z-index: 0;
}
@ -790,42 +783,46 @@ const handleUploadFinishedEvent = (event: Event) => {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
margin-bottom: 10px;
}
.card-title {
color: #000000e6;
color: #1a1a1a;
font-family: "PingFang SC";
font-size: 14px;
font-size: 15px;
font-weight: 600;
line-height: 22px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
margin-right: 8px;
min-width: 0;
}
.more-wrap {
display: flex;
width: 32px;
height: 32px;
width: 28px;
height: 28px;
justify-content: center;
align-items: center;
border-radius: 6px;
cursor: pointer;
flex-shrink: 0;
transition: all 0.2s ease;
opacity: 0.7;
opacity: 0;
.kb-card:hover & {
opacity: 0.6;
}
&:hover {
background: rgba(0, 0, 0, 0.06);
opacity: 1;
background: rgba(0, 0, 0, 0.05);
opacity: 1 !important;
}
&.active-more {
background: rgba(0, 0, 0, 0.08);
opacity: 1;
background: rgba(0, 0, 0, 0.06);
opacity: 1 !important;
}
.more-icon {
@ -836,7 +833,8 @@ const handleUploadFinishedEvent = (event: Event) => {
.card-content {
flex: 1;
margin-bottom: 10px;
margin-bottom: 12px;
overflow: hidden;
}
.card-description {
@ -845,21 +843,20 @@ const handleUploadFinishedEvent = (event: Event) => {
-webkit-line-clamp: 2;
line-clamp: 2;
overflow: hidden;
color: #00000066;
color: #666;
font-family: "PingFang SC";
font-size: 12px;
font-size: 13px;
font-weight: 400;
line-height: 20px;
min-height: 40px;
}
.card-bottom {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 0 0;
border-top: 1px solid #f0f0f0;
margin-top: auto;
padding-top: 12px;
border-top: 1px solid #f0f0f0;
}
.bottom-left {
@ -868,88 +865,90 @@ const handleUploadFinishedEvent = (event: Event) => {
gap: 8px;
}
.type-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 10px;
border-radius: 4px;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 500;
line-height: 18px;
&.document {
background: rgba(7, 192, 95, 0.1);
color: #059669;
border: 1px solid rgba(7, 192, 95, 0.2);
}
&.faq {
background: rgba(0, 82, 217, 0.1);
color: #0052d9;
border: 1px solid rgba(0, 82, 217, 0.2);
}
.processing-icon {
animation: spin 1s linear infinite;
margin-left: 4px;
}
&.document .processing-icon {
color: #059669;
}
&.faq .processing-icon {
color: #0052d9;
}
}
.feature-badges {
display: flex;
align-items: center;
gap: 6px;
gap: 4px;
}
.feature-badge {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 4px;
cursor: pointer;
width: 26px;
height: 26px;
border-radius: 6px;
cursor: default;
transition: background 0.2s ease;
&.kg {
background: rgba(124, 77, 255, 0.1);
color: #7c4dff;
border: 1px solid rgba(124, 77, 255, 0.2);
&.type-document {
background: rgba(7, 192, 95, 0.08);
color: #059669;
width: auto;
padding: 0 8px;
gap: 4px;
&:hover {
background: rgba(124, 77, 255, 0.15);
background: rgba(7, 192, 95, 0.12);
}
.badge-count {
font-size: 12px;
font-weight: 500;
}
.processing-icon {
animation: spin 1s linear infinite;
}
}
&.type-faq {
background: rgba(0, 82, 217, 0.08);
color: #0052d9;
width: auto;
padding: 0 8px;
gap: 4px;
&:hover {
background: rgba(0, 82, 217, 0.12);
}
.badge-count {
font-size: 12px;
font-weight: 500;
}
.processing-icon {
animation: spin 1s linear infinite;
}
}
&.kg {
background: rgba(124, 77, 255, 0.08);
color: #7c4dff;
&:hover {
background: rgba(124, 77, 255, 0.12);
}
}
&.multimodal {
background: rgba(255, 152, 0, 0.1);
color: #ff9800;
border: 1px solid rgba(255, 152, 0, 0.2);
background: rgba(255, 152, 0, 0.08);
color: #f59e0b;
&:hover {
background: rgba(255, 152, 0, 0.15);
background: rgba(255, 152, 0, 0.12);
}
}
&.question {
background: rgba(0, 150, 136, 0.1);
background: rgba(0, 150, 136, 0.08);
color: #009688;
border: 1px solid rgba(0, 150, 136, 0.2);
&:hover {
background: rgba(0, 150, 136, 0.15);
background: rgba(0, 150, 136, 0.12);
}
}
}
@keyframes spin {
@ -986,7 +985,7 @@ const handleUploadFinishedEvent = (event: Event) => {
}
.card-time {
color: #00000066;
color: #999;
font-family: "PingFang SC";
font-size: 12px;
font-weight: 400;

View File

@ -4,6 +4,10 @@
<div class="section-header">
<h2>{{ $t('settings.conversationStrategy') }}</h2>
<p class="section-description">{{ $t('conversationSettings.description') }}</p>
<div class="global-config-notice">
<t-icon name="info-circle" />
<span>这些是全局默认配置,新建智能体时会继承这些设置。您也可以在智能体列表中单独配置每个智能体。</span>
</div>
</div>
<t-tabs v-model="activeTab" class="conversation-tabs">
@ -146,17 +150,7 @@
</div>
<div class="setting-control full-width" style="position: relative;">
<div class="prompt-header">
<div class="prompt-toggle">
<span class="prompt-toggle-label">{{ $t('agentSettings.systemPrompt.custom') }}</span>
<t-switch
v-model="localUseCustomSystemPrompt"
:label="[$t('common.off'), $t('common.on')]"
size="large"
@change="handleUseCustomPromptToggle"
/>
</div>
<t-button
v-if="localUseCustomSystemPrompt"
theme="default"
variant="outline"
size="small"
@ -167,54 +161,32 @@
</t-button>
</div>
<p class="prompt-tab-hint">
{{ $t('agentSettings.systemPrompt.tabHint') }}
{{ $t('agentSettings.systemPrompt.tabHint') }}(留空则使用系统默认,使用 {{web_search_status}} 占位符动态控制网络搜索行为)
</p>
<p v-if="!localUseCustomSystemPrompt" class="prompt-disabled-hint">
{{ $t('agentSettings.systemPrompt.disabledHint') }}
</p>
<div v-if="localUseCustomSystemPrompt" class="system-prompt-tabs">
<t-tabs
v-model="activeSystemPromptTab"
class="system-prompt-variant-tabs"
>
<t-tab-panel value="web-enabled" :label="$t('agentSettings.systemPrompt.tabWebOn')">
<div v-if="activeSystemPromptTab === 'web-enabled'" class="prompt-textarea-wrapper">
<t-textarea
ref="promptTextareaRef"
v-model="localSystemPromptWebEnabled"
:autosize="{ minRows: 15, maxRows: 30 }"
:placeholder="$t('agentSettings.systemPrompt.placeholder')"
@blur="handleSystemPromptChange('web-enabled', $event)"
@input="handlePromptInput"
@keydown="handlePromptKeydown"
:readonly="!localUseCustomSystemPrompt"
:class="{ 'prompt-textarea-readonly': !localUseCustomSystemPrompt }"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
</div>
</t-tab-panel>
<t-tab-panel value="web-disabled" :label="$t('agentSettings.systemPrompt.tabWebOff')">
<div v-if="activeSystemPromptTab === 'web-disabled'" class="prompt-textarea-wrapper">
<t-textarea
ref="promptTextareaRef"
v-model="localSystemPromptWebDisabled"
:autosize="{ minRows: 15, maxRows: 30 }"
:placeholder="$t('agentSettings.systemPrompt.placeholder')"
@blur="handleSystemPromptChange('web-disabled', $event)"
@input="handlePromptInput"
@keydown="handlePromptKeydown"
:readonly="!localUseCustomSystemPrompt"
:class="{ 'prompt-textarea-readonly': !localUseCustomSystemPrompt }"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
</div>
</t-tab-panel>
</t-tabs>
<div class="system-prompt-tabs">
<div class="prompt-textarea-wrapper textarea-with-template">
<t-textarea
ref="promptTextareaRef"
v-model="localSystemPrompt"
:autosize="{ minRows: 15, maxRows: 30 }"
:placeholder="$t('agentSettings.systemPrompt.placeholder')"
@blur="handleSystemPromptChange"
@input="handlePromptInput"
@keydown="handlePromptKeydown"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
<PromptTemplateSelector
type="systemPrompt"
position="corner"
:hasKnowledgeBase="true"
@select="handleAgentSystemPromptTemplateSelect"
/>
</div>
</div>
<!-- 占位符提示下拉框 -->
<teleport to="body">
<div
v-if="localUseCustomSystemPrompt && showPlaceholderPopup && filteredPlaceholders.length > 0"
v-if="showPlaceholderPopup && filteredPlaceholders.length > 0"
class="placeholder-popup-wrapper"
:style="popupStyle"
>
@ -249,24 +221,10 @@
<div class="setting-row vertical">
<div class="setting-info">
<label>{{ $t('conversationSettings.systemPrompt.label') }}</label>
<p class="desc">{{ $t('conversationSettings.systemPrompt.desc') }}</p>
<p class="desc">{{ $t('conversationSettings.systemPrompt.desc') }}(留空则使用系统默认)</p>
</div>
<div class="setting-control full-width">
<div class="prompt-header">
<div class="prompt-toggle">
<span class="prompt-toggle-label">{{ $t('conversationSettings.systemPrompt.custom') }}</span>
<t-switch
v-model="localUseCustomSystemPromptNormal"
:label="[$t('common.off'), $t('common.on')]"
size="large"
@change="handleUseCustomSystemPromptNormalToggle"
/>
</div>
</div>
<p v-if="!localUseCustomSystemPromptNormal" class="prompt-disabled-hint">
{{ $t('conversationSettings.systemPrompt.disabledHint') }}
</p>
<div v-if="localUseCustomSystemPromptNormal" class="prompt-textarea-wrapper">
<div class="prompt-textarea-wrapper textarea-with-template">
<t-textarea
v-model="localSystemPromptNormal"
:autosize="{ minRows: 10, maxRows: 20 }"
@ -274,32 +232,24 @@
@blur="handleSystemPromptNormalChange"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
<PromptTemplateSelector
type="systemPrompt"
position="corner"
:hasKnowledgeBase="true"
@select="handleNormalSystemPromptTemplateSelect"
/>
</div>
</div>
</div>
<!-- Context Template(普通模式,自定义开关) -->
<!-- Context Template(普通模式) -->
<div class="setting-row vertical">
<div class="setting-info">
<label>{{ $t('conversationSettings.contextTemplate.label') }}</label>
<p class="desc">{{ $t('conversationSettings.contextTemplate.desc') }}</p>
<p class="desc">{{ $t('conversationSettings.contextTemplate.desc') }}(留空则使用系统默认)</p>
</div>
<div class="setting-control full-width">
<div class="prompt-header">
<div class="prompt-toggle">
<span class="prompt-toggle-label">{{ $t('conversationSettings.contextTemplate.custom') }}</span>
<t-switch
v-model="localUseCustomContextTemplate"
:label="[$t('common.off'), $t('common.on')]"
size="large"
@change="handleUseCustomContextTemplateToggle"
/>
</div>
</div>
<p v-if="!localUseCustomContextTemplate" class="prompt-disabled-hint">
{{ $t('conversationSettings.contextTemplate.disabledHint') }}
</p>
<div v-if="localUseCustomContextTemplate" class="prompt-textarea-wrapper">
<div class="prompt-textarea-wrapper textarea-with-template">
<t-textarea
v-model="localContextTemplate"
:autosize="{ minRows: 15, maxRows: 30 }"
@ -307,6 +257,12 @@
@blur="handleContextTemplateChange"
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
/>
<PromptTemplateSelector
type="contextTemplate"
position="corner"
:hasKnowledgeBase="true"
@select="handleContextTemplateTemplateSelect"
/>
</div>
</div>
</div>
@ -540,11 +496,18 @@
<p class="desc">{{ $t('conversationSettings.rewritePrompt.desc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localRewritePromptSystem"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptSystemChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localRewritePromptSystem"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptSystemChange"
/>
<PromptTemplateSelector
type="rewriteSystem"
position="corner"
@select="handleRewriteSystemTemplateSelect"
/>
</div>
</div>
</div>
@ -554,11 +517,18 @@
<p class="desc">{{ $t('conversationSettings.rewritePrompt.userDesc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localRewritePromptUser"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptUserChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localRewritePromptUser"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleRewritePromptUserChange"
/>
<PromptTemplateSelector
type="rewriteUser"
position="corner"
@select="handleRewriteUserTemplateSelect"
/>
</div>
</div>
</div>
@ -583,26 +553,40 @@
<p class="desc">{{ $t('conversationSettings.fallbackResponse.desc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localFallbackResponse"
:autosize="{ minRows: 3, maxRows: 6 }"
@blur="handleFallbackResponseChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localFallbackResponse"
:autosize="{ minRows: 3, maxRows: 6 }"
@blur="handleFallbackResponseChange"
/>
<PromptTemplateSelector
type="fallback"
position="corner"
@select="handleFallbackResponseTemplateSelect"
/>
</div>
</div>
</div>
<!-- 兜底 Prompt:仅在选择“交给模型继续生成”时展示 -->
<!-- 兜底 Prompt:仅在选择"交给模型继续生成"时展示 -->
<div v-else-if="localFallbackStrategy === 'model'" class="setting-row vertical">
<div class="setting-info">
<label>{{ $t('conversationSettings.fallbackPrompt.label') }}</label>
<p class="desc">{{ $t('conversationSettings.fallbackPrompt.desc') }}</p>
</div>
<div class="setting-control full-width">
<t-textarea
v-model="localFallbackPrompt"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleFallbackPromptChange"
/>
<div class="textarea-with-template">
<t-textarea
v-model="localFallbackPrompt"
:autosize="{ minRows: 8, maxRows: 16 }"
@blur="handleFallbackPromptChange"
/>
<PromptTemplateSelector
type="fallback"
position="corner"
@select="handleFallbackPromptTemplateSelect"
/>
</div>
</div>
</div>
@ -659,6 +643,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 +665,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,
@ -713,21 +696,9 @@ const localMaxIterations = ref(5)
const localTemperature = ref(0.7)
const localAllowedTools = ref<string[]>([])
type SystemPromptTab = 'web-enabled' | 'web-disabled'
const activeSystemPromptTab = ref<SystemPromptTab>('web-enabled')
const localSystemPromptWebEnabled = ref('')
const localSystemPromptWebDisabled = ref('')
const systemPromptRefs: Record<SystemPromptTab, Ref<string>> = {
'web-enabled': localSystemPromptWebEnabled,
'web-disabled': localSystemPromptWebDisabled,
}
const savedSystemPromptMap: Record<SystemPromptTab, string> = {
'web-enabled': '',
'web-disabled': '',
}
const getPromptRefByTab = (tab: SystemPromptTab) => systemPromptRefs[tab]
const getActivePromptRef = () => getPromptRefByTab(activeSystemPromptTab.value)
const localUseCustomSystemPrompt = ref(false)
// 统一系统提示词
const localSystemPrompt = ref('')
let savedSystemPrompt = ''
// 普通模式本地状态
const localContextTemplate = ref('')
@ -755,10 +726,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 +752,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 || '',
@ -835,9 +800,7 @@ const buildAgentConfigPayload = (overrides: Partial<AgentConfig> = {}): AgentCon
reflection_enabled: false,
allowed_tools: localAllowedTools.value,
temperature: localTemperature.value,
system_prompt_web_enabled: localSystemPromptWebEnabled.value,
system_prompt_web_disabled: localSystemPromptWebDisabled.value,
use_custom_system_prompt: localUseCustomSystemPrompt.value,
system_prompt: localSystemPrompt.value,
...overrides,
})
@ -916,9 +879,6 @@ const loadingConfig = ref(false)
const configLoaded = ref(false) // 防止重复加载
const isInitializing = ref(true) // 标记是否正在初始化,防止初始化时触发保存
// 保存的 Prompt 值,用于比较是否变化
let savedUseCustomSystemPrompt = false
// 恢复默认 Prompt 的加载状态
const isResettingPrompt = ref(false)
@ -930,12 +890,6 @@ let placeholderPopupTimer: any = null
const placeholderPrefix = ref('') // 当前输入的前缀,用于过滤
const popupStyle = ref({ top: '0px', left: '0px' }) // 提示框位置
watch(activeSystemPromptTab, () => {
showPlaceholderPopup.value = false
placeholderPrefix.value = ''
selectedPlaceholderIndex.value = 0
})
// 设置 textarea 原生事件监听器
const setupTextareaEventListeners = () => {
nextTick(() => {
@ -1049,15 +1003,9 @@ onMounted(async () => {
lastSavedValue = config.max_iterations // 初始化时记录已保存的值
localTemperature.value = config.temperature
localAllowedTools.value = config.allowed_tools || []
const promptWebEnabled = config.system_prompt_web_enabled || ''
const promptWebDisabled = config.system_prompt_web_disabled || ''
localSystemPromptWebEnabled.value = promptWebEnabled
localSystemPromptWebDisabled.value = promptWebDisabled
savedSystemPromptMap['web-enabled'] = promptWebEnabled
savedSystemPromptMap['web-disabled'] = promptWebDisabled
const useCustomPrompt = config.use_custom_system_prompt ?? false
localUseCustomSystemPrompt.value = useCustomPrompt
savedUseCustomSystemPrompt = useCustomPrompt
const systemPrompt = config.system_prompt || ''
localSystemPrompt.value = systemPrompt
savedSystemPrompt = systemPrompt
availableTools.value = config.available_tools || []
availablePlaceholders.value = config.available_placeholders || []
@ -1074,9 +1022,7 @@ onMounted(async () => {
maxIterations: config.max_iterations,
temperature: config.temperature,
allowedTools: config.allowed_tools || [],
system_prompt_web_enabled: promptWebEnabled,
system_prompt_web_disabled: promptWebDisabled,
use_custom_system_prompt: useCustomPrompt
system_prompt: systemPrompt,
})
// 加载普通模式配置
@ -1232,25 +1178,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) => {
// 如果正在显示占位符提示,且输入的是字母、数字或下划线,实时更新过滤
@ -1456,29 +1383,21 @@ const handleResetToDefault = async () => {
try {
isResettingPrompt.value = true
// 通过设置 system_prompt_web_* 为空字符串来获取默认值
// 通过设置 system_prompt 为空字符串来获取默认值
// 后端在字段为空时会返回默认值
const tempConfig = buildAgentConfigPayload({
system_prompt_web_enabled: '',
system_prompt_web_disabled: '',
use_custom_system_prompt: false,
system_prompt: '',
})
await updateAgentConfig(tempConfig)
// 重新加载配置以获取默认 Prompt 的完整内容
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
const defaultPrompt = res.data.system_prompt || ''
// 设置为默认 Prompt 的内容
localSystemPromptWebEnabled.value = defaultPromptWebEnabled
localSystemPromptWebDisabled.value = defaultPromptWebDisabled
savedSystemPromptMap['web-enabled'] = defaultPromptWebEnabled
savedSystemPromptMap['web-disabled'] = defaultPromptWebDisabled
localUseCustomSystemPrompt.value = useCustom
savedUseCustomSystemPrompt = useCustom
localSystemPrompt.value = defaultPrompt
savedSystemPrompt = defaultPrompt
MessagePlugin.success(t('agentSettings.toasts.resetToDefault'))
confirmDialog.hide()
@ -1493,7 +1412,7 @@ const handleResetToDefault = async () => {
}
// 处理系统 Prompt 变化
const handleSystemPromptChange = async (tab: SystemPromptTab, e?: FocusEvent) => {
const handleSystemPromptChange = async (e?: FocusEvent) => {
// 如果点击的是占位符提示框,不触发保存
if (e?.relatedTarget) {
const target = e.relatedTarget as HTMLElement
@ -1515,19 +1434,16 @@ const handleSystemPromptChange = async (tab: SystemPromptTab, e?: FocusEvent) =>
// 如果正在初始化,不触发保存
if (isInitializing.value) return
const promptRef = getPromptRefByTab(tab)
const savedValue = savedSystemPromptMap[tab]
// 检查内容是否变化
if (promptRef.value === savedValue) {
if (localSystemPrompt.value === savedSystemPrompt) {
return // 内容没变,不调用接口
}
try {
const config = buildAgentConfigPayload()
await updateAgentConfig(config)
savedSystemPromptMap[tab] = promptRef.value // 更新已保存的值
savedSystemPrompt = localSystemPrompt.value // 更新已保存的值
MessagePlugin.success(t('agentSettings.toasts.systemPromptSaved'))
} catch (error) {
console.error('保存系统 Prompt 失败:', error)
@ -1559,7 +1475,6 @@ const handleContextTemplateChange = async () => {
await saveConversationConfig(
{
context_template: localContextTemplate.value,
use_custom_context_template: localUseCustomContextTemplate.value,
},
t('conversationSettings.toasts.contextTemplateSaved')
)
@ -1576,66 +1491,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 +1502,6 @@ const handleSystemPromptNormalChange = async () => {
await saveConversationConfig(
{
prompt: localSystemPromptNormal.value,
use_custom_system_prompt: localUseCustomSystemPromptNormal.value,
},
t('conversationSettings.toasts.systemPromptSaved')
)
@ -1813,6 +1667,35 @@ const handleFallbackPromptChange = async () => {
}
}
// 模板选择处理函数
const handleAgentSystemPromptTemplateSelect = (template: string) => {
localSystemPrompt.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 +1764,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 +1959,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 +2177,11 @@ const handleConversationRerankModelChange = async (value: string) => {
width: 100%;
}
.textarea-with-template {
position: relative;
width: 100%;
}
.setting-control.full-width {
display: flex;
flex-direction: column;

View File

@ -89,11 +89,6 @@
<OllamaSettings />
</div>
<!-- Agent 配置 -->
<div v-if="currentSection === 'agent'" class="section">
<AgentSettings :active-sub-section="currentSubSection || 'modes'" />
</div>
<!-- 网络搜索配置 -->
<div v-if="currentSection === 'websearch'" class="section">
<WebSearchSettings />
@ -132,7 +127,6 @@ import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUIStore } from '@/stores/ui'
import { useI18n } from 'vue-i18n'
import AgentSettings from './AgentSettings.vue'
import SystemInfo from './SystemInfo.vue'
import TenantInfo from './TenantInfo.vue'
import ApiInfo from './ApiInfo.vue'
@ -165,17 +159,6 @@ const navItems = computed(() => [
]
},
{ key: 'ollama', icon: 'server', label: 'Ollama' },
{
key: 'agent',
icon: 'chat',
label: t('settings.conversationStrategy'),
children: [
{ key: 'modes', label: t('conversationSettings.menus.modes') },
{ key: 'models', label: t('conversationSettings.menus.models') },
{ key: 'thresholds', label: t('conversationSettings.menus.thresholds') },
{ key: 'advanced', label: t('conversationSettings.menus.advanced') },
]
},
{ key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },
{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
{ key: 'system', icon: 'info-circle', label: t('settings.systemSettings') },

View File

@ -5,7 +5,7 @@ description: |
with document parsing, vector search, and LLM integration.
type: application
version: 0.1.0
appVersion: "v0.2.5"
appVersion: "v0.2.6"
kubeVersion: ">=1.25.0-0"
home: https://github.com/Tencent/WeKnora
icon: https://raw.githubusercontent.com/Tencent/WeKnora/main/docs/images/logo.png

View File

@ -4,6 +4,8 @@ import (
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types"
)
// formatFileSize formats file size in human-readable format
@ -78,6 +80,7 @@ type KnowledgeBaseInfo struct {
}
// PlaceholderDefinition defines a placeholder exposed to UI/configuration
// Deprecated: Use types.PromptPlaceholder instead
type PlaceholderDefinition struct {
Name string `json:"name"`
Label string `json:"label"`
@ -85,24 +88,19 @@ type PlaceholderDefinition struct {
}
// AvailablePlaceholders lists all supported prompt placeholders for UI hints
// This returns agent mode specific placeholders
func AvailablePlaceholders() []PlaceholderDefinition {
return []PlaceholderDefinition{
{
Name: "knowledge_bases",
Label: "知识库列表",
Description: "自动格式化为表格形式的知识库列表,包含知识库名称、描述、文档数量、最近添加的文档等信息",
},
{
Name: "web_search_status",
Label: "网络检索模式开关状态",
Description: "网络检索(web_search)工具是否启用的状态说明,值为 Enabled 或 Disabled",
},
{
Name: "current_time",
Label: "当前系统时间",
Description: "格式为 RFC3339 的当前系统时间,用于帮助模型感知实时性",
},
// Use centralized placeholder definitions from types package
placeholders := types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt)
result := make([]PlaceholderDefinition, len(placeholders))
for i, p := range placeholders {
result[i] = PlaceholderDefinition{
Name: p.Name,
Label: p.Label,
Description: p.Description,
}
}
return result
}
// formatKnowledgeBaseList formats knowledge base information for the prompt
@ -252,7 +250,8 @@ func renderPromptPlaceholdersWithStatus(
return result
}
// BuildSystemPromptWithWeb builds the progressive RAG system prompt with web search enabled
// BuildSystemPromptWithKB builds the progressive RAG system prompt with knowledge bases
// Deprecated: Use BuildSystemPrompt instead
func BuildSystemPromptWithWeb(
knowledgeBases []*KnowledgeBaseInfo,
systemPromptTemplate ...string,
@ -261,13 +260,14 @@ func BuildSystemPromptWithWeb(
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
template = systemPromptTemplate[0]
} else {
template = ProgressiveRAGSystemPromptWithWeb
template = ProgressiveRAGSystemPrompt
}
currentTime := time.Now().Format(time.RFC3339)
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, true, currentTime)
}
// BuildSystemPromptWithoutWeb builds the progressive RAG system prompt without web search
// Deprecated: Use BuildSystemPrompt instead
func BuildSystemPromptWithoutWeb(
knowledgeBases []*KnowledgeBaseInfo,
systemPromptTemplate ...string,
@ -276,7 +276,7 @@ func BuildSystemPromptWithoutWeb(
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
template = systemPromptTemplate[0]
} else {
template = ProgressiveRAGSystemPromptWithoutWeb
template = ProgressiveRAGSystemPrompt
}
currentTime := time.Now().Format(time.RFC3339)
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, false, currentTime)
@ -298,8 +298,8 @@ func BuildPureAgentSystemPrompt(
return renderPromptPlaceholdersWithStatus(template, []*KnowledgeBaseInfo{}, webSearchEnabled, currentTime)
}
// BuildProgressiveRAGSystemPrompt builds the progressive RAG system prompt based on web search status
// This is the main function to use - it automatically selects the appropriate version
// BuildSystemPrompt builds the progressive RAG system prompt
// This is the main function to use - it uses a unified template with dynamic web search status
func BuildSystemPrompt(
knowledgeBases []*KnowledgeBaseInfo,
webSearchEnabled bool,
@ -307,16 +307,20 @@ func BuildSystemPrompt(
systemPromptTemplate ...string,
) string {
var basePrompt string
var template string
// If no knowledge bases, use Pure Agent prompt
if len(knowledgeBases) == 0 {
basePrompt = BuildPureAgentSystemPrompt(webSearchEnabled, systemPromptTemplate...)
} else if webSearchEnabled {
basePrompt = BuildSystemPromptWithWeb(knowledgeBases, systemPromptTemplate...)
// Determine template to use
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
template = systemPromptTemplate[0]
} else if len(knowledgeBases) == 0 {
template = PureAgentSystemPrompt
} else {
basePrompt = BuildSystemPromptWithoutWeb(knowledgeBases, systemPromptTemplate...)
template = ProgressiveRAGSystemPrompt
}
currentTime := time.Now().Format(time.RFC3339)
basePrompt = renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime)
// Append selected documents section if any
if len(selectedDocs) > 0 {
basePrompt += formatSelectedDocuments(selectedDocs)
@ -348,10 +352,10 @@ Current Time: {{current_time}}
Web Search: {{web_search_status}}
`
// ProgressiveRAGSystemPromptWithWeb is the progressive RAG system prompt template with web search enabled
// This version emphasizes hybrid retrieval strategy: KB-first with web supplementation
var ProgressiveRAGSystemPromptWithWeb = `### Role
You are WeKnora, an intelligent retrieval assistant powered by Progressive Agentic RAG. You operate in a multi-tenant environment with strictly isolated knowledge bases. Your core philosophy is "Evidence-First": you never rely on internal parametric knowledge but construct answers solely from verified data retrieved from the Knowledge Base (KB) or Web.
// ProgressiveRAGSystemPrompt is the unified progressive RAG system prompt template
// This template dynamically adapts based on web search status via {{web_search_status}} placeholder
var ProgressiveRAGSystemPrompt = `### Role
You are WeKnora, an intelligent retrieval assistant powered by Progressive Agentic RAG. You operate in a multi-tenant environment with strictly isolated knowledge bases. Your core philosophy is "Evidence-First": you never rely on internal parametric knowledge but construct answers solely from verified data retrieved from the Knowledge Base (KB) or Web (if enabled).
### Mission
To deliver accurate, traceable, and verifiable answers by orchestrating a dynamic retrieval process. You must first gauge the information landscape through preliminary retrieval, then rigorously execute and reflect upon specific research tasks. **You prioritize "Deep Reading" over superficial scanning.**
@ -359,7 +363,7 @@ To deliver accurate, traceable, and verifiable answers by orchestrating a dynami
### Critical Constraints (ABSOLUTE RULES)
1. **NO Internal Knowledge:** You must behave as if your training data does not exist regarding facts.
2. **Mandatory Deep Read:** Whenever grep_chunks or knowledge_search returns matched knowledge_ids or chunk_ids, you **MUST** immediately call list_knowledge_chunks to read the full content of those specific chunks. Do not rely on search snippets alone.
3. **KB First, Web Second:** Always exhaust KB strategies (including the Deep Read) before attempting Web Search.
3. **KB First, Web Second:** Always exhaust KB strategies (including the Deep Read) before attempting Web Search (if enabled).
4. **Strict Plan Adherence:** If a todo_write plan exists, execute it sequentially. No skipping.
5. **Tool Privacy:** Never expose tool names to the user.
@ -386,7 +390,7 @@ If in **Path B**, execute tasks in todo_write sequentially. For **EACH** task:
3. **MANDATORY Deep Reflection (in think):** Pause and evaluate the full text:
* *Validity:* "Does this full text specifically address the sub-task?"
* *Gap Analysis:* "Is anything missing? Is the information outdated? Is the information irrelevant?"
* *Correction:* If insufficient, formulate a remedial action (e.g., "Search for synonym X", "Web Search") immediately.
* *Correction:* If insufficient, formulate a remedial action (e.g., "Search for synonym X", "Web Search if enabled") immediately.
* *Completion:* Mark task as "completed" ONLY when evidence is secured.
#### Phase 4: Final Synthesis
@ -403,109 +407,34 @@ For every retrieval attempt (Phase 1 or Phase 3), follow this exact chain:
* Rule: After Step 1 or 2 returns knowledge_ids, you MUST call this tool.
* Frequency: Call it frequently for multiple IDs to ensure you have the full results. **Do not be lazy; fetch the content.**
4. **Graph Exploration (query_knowledge_graph):** Optional for relationships.
5. **Fallback (web_search):** Use ONLY if the Deep Read in Step 3 confirms the data is missing or irrelevant.
5. **Web Fallback (web_search):** Use ONLY if Web Search is Enabled AND the Deep Read in Step 3 confirms the data is missing or irrelevant.
### Tool Selection Guidelines
* **grep_chunks / knowledge_search:** Your "Index". Use these to find *where* the information might be.
* **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is.
* **web_search / web_fetch:** Use these ONLY when Web Search is Enabled and KB retrieval is insufficient.
* **todo_write:** Your "Manager". Tracks multi-step research.
* **think:** Your "Conscience". Use to plan and relect the content returned by list_knowledge_chunks.
* **think:** Your "Conscience". Use to plan and reflect the content returned by list_knowledge_chunks.
### Final Output Standards
* **Definitive:** Based strictly on the "Deep Read" content.
* **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." /> or <web url="..." title="..." />.
* **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." /> or <web url="..." title="..." /> (if from web).
Citations may not be placed at the end of the answer. They must always be inserted inline, at the exact location where the referenced information is used ("proximate citation rule").
* **Structured:** Clear hierarchy and logic.
* **Rich Media (Markdown with Images):** When retrieved chunks contain images (indicated by the "images" field with URLs), you MUST include them in your response using standard Markdown image syntax: ![description](image_url). Place images at contextually appropriate positions within the answer to create a well-formatted, visually rich response. Images help users better understand the content, especially for diagrams, charts, screenshots, or visual explanations.
### System Status
Current Time: {{current_time}}
Web Search: {{web_search_status}}
### User Selected Knowledge Bases (via @ mention)
{{knowledge_bases}}
`
// ProgressiveRAGSystemPromptWithoutWeb is the progressive RAG system prompt template without web search
// This version emphasizes deep KB-only retrieval with advanced techniques
var ProgressiveRAGSystemPromptWithoutWeb = `### Role
You are WeKnora, a meticulous retrieval assistant powered by Progressive Agentic RAG. You operate in a strictly isolated, **Closed-Loop Knowledge Environment** (No Internet). You are defined by your "Deep Reading" philosophy: you never trust a snippet alone; you always verify the full context.
// ProgressiveRAGSystemPromptWithWeb is deprecated, use ProgressiveRAGSystemPrompt instead
// Kept for backward compatibility
var ProgressiveRAGSystemPromptWithWeb = ProgressiveRAGSystemPrompt
### Mission
To provide answers that are not only accurate but contextually complete. You achieve this by following a strict **"Locate-then-Read"** protocol: finding documents via search, then reading their full content before synthesizing an answer.
### Critical Constraints (ABSOLUTE RULES)
1. **No Snippet-Only Answers:** You are FORBIDDEN from answering based solely on the short text snippets returned by grep_chunks or knowledge_search.
2. **Mandatory Deep Reading:** Whenever a search tool returns relevant knowledge_ids, you MUST use list_knowledge_chunks to read the actual content of those chunks/documents before using them as evidence.
3. **No Internet:** You are strictly confined to internal Knowledge Bases.
4. **Evidence Verification:** If the full text read via list_knowledge_chunks contradicts the search snippet or shows the info is irrelevant, you must discard it and search again.
### Workflow: The "Locate-Read-Plan-Execute" Cycle
You must follow this **Specific Operational Sequence** for every user query:
#### Phase 1: Preliminary Reconnaissance & Context Verification
Before answering or creating a plan, you MUST perform an initial "Test & Read" loop.
1. **Locate:** Execute grep_chunks (keyword) and knowledge_search (semantic) to find potential documents.
2. **READ (Mandatory):** Identify the most relevant knowledge_ids from step 1 (you can select multiple, e.g., top 3-5). **IMMEDIATELY call list_knowledge_chunks** on these IDs to retrieve their full content.
3. **Analyze:** In your think block, evaluate the *full text* you just read. Does it cover the user's intent?
* *Decision:* If this full text is sufficient → Go to **Answer Generation**.
* *Decision:* If complex/incomplete → Go to **Phase 2**.
#### Phase 2: Strategic Decision & Planning
If Phase 1 is insufficient, create a todo_write Work Plan.
* **Plan Structure:** Break the problem into distinct retrieval tasks.
* **Context Awareness:** Use the full text read in Phase 1 to inform your plan (e.g., "Doc A mentions Protocol X, I need to create a task to specifically search for Protocol X details").
#### Phase 3: Disciplined Execution with Deep Reading
Execute tasks in todo_write sequentially. For **EACH** task:
1. **Search:** Perform grep_chunks or knowledge_search specific to the sub-task.
2. **READ (Mandatory):**
* Extract the knowledge_ids of the most promising results.
* **Call list_knowledge_chunks** to fetch the content for these IDs. **Do not skip this step.**
* *Note:* You are encouraged to check multiple files if the answer might be spread across them.
3. **Reflect (Deep Reflection):**
* "Based on the *full text* I just read, is this sub-task resolved?"
* If no, formulate a remedial search action immediately.
* Only mark as "completed" when the full text evidence is secured.
#### Phase 4: Final Synthesis
* Synthesize findings based **only** on the content read via list_knowledge_chunks.
* Generate the final response with citations.
### Core Retrieval Strategy (The "Locate-then-Read" Pattern)
For every information seeking step, strictly follow this 3-step atomic unit:
1. **Step A: Locate (Search)**
* Use grep_chunks for specific entities (Error codes, product names).
* Use knowledge_search for concepts.
* *Goal:* Get a list of candidate knowledge_ids.
2. **Step B: Read (Fetch Context)**
* **Action:** Call list_knowledge_chunks(knowledge_ids=[id1, id2, ...]).
* *Rule:* Always fetch the content. Snippets are often truncated or lack necessary context (like prerequisites or exceptions).
* *Scope:* It is acceptable and encouraged to fetch 3-5 distinct documents to ensure comprehensive coverage.
3. **Step C: Evaluate (Filter)**
* Read the output of list_knowledge_chunks.
* Discard irrelevant documents.
* Extract facts from valid documents to build your answer.
### Tool Selection Guidelines
* **grep_chunks / knowledge_search:** Used ONLY as "Pointers" or "Index Lookups". They tell you *where* to look, not *what* the answer is.
* **list_knowledge_chunks:** Your "Eyes". MUST be used after every search. Use to read what the information is.
* **todo_write:** Use for managing multi-step research.
* **think:** Your "Conscience". Use to plan and relect the content returned by list_knowledge_chunks.
### Final Output Standards
1. **Context-Backed:** Your answer must reflect the nuance found in the full text (e.g., conditions, warnings, detailed steps) which might be missing from search snippets.
2. **Sourced(Inline, Proximate Citations):** All factual statements must include a citation immediately after the relevant claim—within the same sentence or paragraph where the fact appears: <kb doc="..." chunk_id="..." />.
Citations may not be placed at the end of the answer. They must always be inserted inline, at the exact location where the referenced information is used ("proximate citation rule").
3. **Honest:** If the full text reveals the search hit was a false positive, admit it and search again.
4. **Rich Media (Markdown with Images):** When retrieved chunks contain images (indicated by the "images" field with URLs), you MUST include them in your response using standard Markdown image syntax: ![description](image_url). Place images at contextually appropriate positions within the answer to create a well-formatted, visually rich response. Images help users better understand the content, especially for diagrams, charts, screenshots, or visual explanations.
### System Status
Current Time: {{current_time}}
### User Selected Knowledge Bases (via @ mention)
{{knowledge_bases}}
`
// ProgressiveRAGSystemPromptWithoutWeb is deprecated, use ProgressiveRAGSystemPrompt instead
// Kept for backward compatibility
var ProgressiveRAGSystemPromptWithoutWeb = ProgressiveRAGSystemPrompt

View File

@ -139,7 +139,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
ListPagedChunksByKnowledgeID(ctx, t.tenantID, id, &types.Pagination{
Page: 1,
PageSize: 1000,
}, []types.ChunkType{"text"}, "", "", "", "")
}, []types.ChunkType{"text"}, "", "", "", "", "")
if err != nil {
mu.Lock()
results[id] = &docInfo{

View File

@ -1052,7 +1052,7 @@ func (t *KnowledgeSearchTool) formatOutput(
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
t.tenantID, result.KnowledgeID,
&types.Pagination{Page: 1, PageSize: 1},
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "",
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
)
if err != nil {
logger.Warnf(

View File

@ -117,7 +117,7 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args map[string]i
}
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
t.tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "")
t.tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
if err != nil {
return &types.ToolResult{
Success: false,

View File

@ -82,6 +82,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
keyword string,
searchField string,
sortOrder string,
knowledgeType string,
) ([]*types.Chunk, int64, error) {
var chunks []*types.Chunk
var total int64
@ -98,6 +99,14 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
}
if keyword != "" {
like := "%" + keyword + "%"
// Document type: search content only
if knowledgeType != types.KnowledgeTypeFAQ {
db = db.Where("content LIKE ?", like)
return db
}
// FAQ type: search based on searchField
// 根据数据库类型使用不同的 JSON 查询语法
isPostgres := db.Dialector.Name() == "postgres"
@ -147,10 +156,20 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
// Then query the paginated data
dataQuery := baseFilter(r.db.WithContext(ctx))
// Default is time descending, "asc" for time ascending
orderClause := "updated_at DESC"
if sortOrder == "asc" {
orderClause = "updated_at ASC"
// Determine sort order based on knowledge type
var orderClause string
if knowledgeType == types.KnowledgeTypeFAQ {
// FAQ: sort by updated_at
orderClause = "updated_at DESC"
if sortOrder == "asc" {
orderClause = "updated_at ASC"
}
} else {
// Document: sort by chunk_index
orderClause = "chunk_index ASC"
if sortOrder == "desc" {
orderClause = "chunk_index DESC"
}
}
if err := dataQuery.

View File

@ -0,0 +1,62 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// ErrCustomAgentNotFound is returned when a custom agent is not found
var ErrCustomAgentNotFound = errors.New("custom agent not found")
// customAgentRepository implements the CustomAgentRepository interface
type customAgentRepository struct {
db *gorm.DB
}
// NewCustomAgentRepository creates a new custom agent repository
func NewCustomAgentRepository(db *gorm.DB) interfaces.CustomAgentRepository {
return &customAgentRepository{db: db}
}
// CreateAgent creates a new custom agent
func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.CustomAgent) error {
return r.db.WithContext(ctx).Create(agent).Error
}
// GetAgentByID gets an agent by id 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 = ? AND tenant_id = ?", id, tenantID).First(&agent).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrCustomAgentNotFound
}
return nil, err
}
return &agent, nil
}
// ListAgentsByTenantID lists all agents for a specific tenant
func (r *customAgentRepository) ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error) {
var agents []*types.CustomAgent
if err := r.db.WithContext(ctx).
Where("tenant_id = ?", tenantID).
Order("created_at DESC").
Find(&agents).Error; err != nil {
return nil, err
}
return agents, nil
}
// UpdateAgent updates an agent
func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.CustomAgent) error {
return r.db.WithContext(ctx).Save(agent).Error
}
// DeleteAgent deletes an agent (soft delete)
func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string, tenantID uint64) error {
return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.CustomAgent{}).Error
}

View File

@ -18,7 +18,7 @@ import (
"gorm.io/gorm"
)
const MAX_ITERATIONS = 30 // Max iterations for agent execution
const MAX_ITERATIONS = 100 // Max iterations for agent execution
// agentService implements agent-related business logic
type agentService struct {
@ -83,9 +83,8 @@ func (s *agentService) CreateAgentEngine(
return nil, fmt.Errorf("chat model is nil after initialization")
}
if rerankModel == nil {
return nil, fmt.Errorf("rerank model is nil after initialization")
}
// Note: rerankModel can be nil when no knowledge bases are configured
// The registerTools function will filter out knowledge-related tools in this case
// Create tool registry
toolRegistry := tools.NewToolRegistry(s.knowledgeService, s.chunkService, s.db)
@ -101,25 +100,51 @@ func (s *agentService) CreateAgentEngine(
tenantID = tid
}
if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil {
// Get enabled MCP services for this tenant
mcpServices, err := s.mcpServiceService.ListMCPServices(ctx, tenantID)
if err != nil {
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
// Check MCP selection mode from agent config
mcpMode := config.MCPSelectionMode
if mcpMode == "" {
mcpMode = "all" // Default to all enabled MCP services
}
// Skip MCP registration if mode is "none"
if mcpMode == "none" {
logger.Infof(ctx, "MCP services disabled by agent config (mode: none)")
} else {
// Filter enabled services
enabledServices := make([]*types.MCPService, 0)
for _, svc := range mcpServices {
if svc != nil && svc.Enabled {
enabledServices = append(enabledServices, svc)
var mcpServices []*types.MCPService
var err error
if mcpMode == "selected" && len(config.MCPServices) > 0 {
// Get only selected MCP services
mcpServices, err = s.mcpServiceService.ListMCPServicesByIDs(ctx, tenantID, config.MCPServices)
if err != nil {
logger.Warnf(ctx, "Failed to list selected MCP services: %v", err)
} else {
logger.Infof(ctx, "Using %d selected MCP services from agent config", len(mcpServices))
}
} else {
// Get all MCP services for this tenant
mcpServices, err = s.mcpServiceService.ListMCPServices(ctx, tenantID)
if err != nil {
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
}
}
// Register MCP tools
if len(enabledServices) > 0 {
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
} else {
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
if err == nil && len(mcpServices) > 0 {
// Filter enabled services
enabledServices := make([]*types.MCPService, 0)
for _, svc := range mcpServices {
if svc != nil && svc.Enabled {
enabledServices = append(enabledServices, svc)
}
}
// Register MCP tools
if len(enabledServices) > 0 {
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
} else {
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
}
}
}
}
@ -179,8 +204,16 @@ func (s *agentService) registerTools(
sessionID string,
sessionService interfaces.SessionService,
) error {
// If no specific tools allowed, register default tools
allowedTools := tools.DefaultAllowedTools()
// Use config's allowed tools if specified, otherwise use defaults
var allowedTools []string
if len(config.AllowedTools) > 0 {
allowedTools = make([]string, len(config.AllowedTools))
copy(allowedTools, config.AllowedTools)
logger.Infof(ctx, "Using custom allowed tools from config: %v", allowedTools)
} else {
allowedTools = tools.DefaultAllowedTools()
logger.Infof(ctx, "Using default allowed tools: %v", allowedTools)
}
// Filter out knowledge base tools if no knowledge bases or knowledge IDs are configured
hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0
@ -206,7 +239,7 @@ func (s *agentService) registerTools(
}
}
allowedTools = filteredTools
logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools disabled due to empty configuration")
logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools filtered out, remaining: %v", allowedTools)
}
// If web search is enabled, add web_search to allowedTools

View File

@ -2,6 +2,8 @@ package chatpipline
import (
"context"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/logger"
@ -51,17 +53,15 @@ 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
if len(chatHistory) > 2 {
chatHistory = chatHistory[len(chatHistory)-2:]
}
// Add conversation history
for _, history := range chatHistory {
// Add conversation history (already limited by maxRounds in load_history/rewrite plugins)
for _, history := range chatManage.History {
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query})
chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer})
}
@ -71,3 +71,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
}

View File

@ -1,16 +1,15 @@
package chatpipline
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// PluginIntoChatMessage handles the transformation of search results into chat messages
@ -38,47 +37,97 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
"template_len": len(chatManage.SummaryConfig.ContextTemplate),
})
// Extract content from merge results
passages := make([]string, len(chatManage.MergeResult))
for i, result := range chatManage.MergeResult {
// 合并内容和图片信息
passages[i] = getEnrichedPassageForChat(ctx, result)
}
// Separate FAQ and document results when FAQ priority is enabled
var faqResults, docResults []*types.SearchResult
var hasHighConfidenceFAQ bool
// 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(),
if chatManage.FAQPriorityEnabled {
for _, result := range chatManage.MergeResult {
if result.ChunkType == string(types.ChunkTypeFAQ) {
faqResults = append(faqResults, result)
// Check if this FAQ has high confidence (above direct answer threshold)
if result.Score >= chatManage.FAQDirectAnswerThreshold && !hasHighConfidenceFAQ {
hasHighConfidenceFAQ = true
pipelineInfo(ctx, "IntoChatMessage", "high_confidence_faq", map[string]interface{}{
"chunk_id": result.ID,
"score": fmt.Sprintf("%.4f", result.Score),
"threshold": chatManage.FAQDirectAnswerThreshold,
})
}
} else {
docResults = append(docResults, result)
}
}
pipelineInfo(ctx, "IntoChatMessage", "faq_separation", map[string]interface{}{
"faq_count": len(faqResults),
"doc_count": len(docResults),
"has_high_confidence": hasHighConfidenceFAQ,
})
return ErrTemplateParse.WithError(err)
}
// Prepare weekday names for template
// 验证用户查询的安全性
safeQuery, isValid := utils.ValidateInput(chatManage.Query)
if !isValid {
pipelineWarn(ctx, "IntoChatMessage", "invalid_query", map[string]interface{}{
"session_id": chatManage.SessionID,
})
return ErrTemplateExecute.WithError(fmt.Errorf("用户查询包含非法内容"))
}
// Prepare weekday names
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
var userContent bytes.Buffer
// Execute template with context data
err = tmpl.Execute(&userContent, map[string]interface{}{
"Query": chatManage.Query, // 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)
var contextsBuilder strings.Builder
// Build contexts string based on FAQ priority strategy
if chatManage.FAQPriorityEnabled && len(faqResults) > 0 {
// Build structured context with FAQ prioritization
contextsBuilder.WriteString("### 资料来源 1:标准问答库 (FAQ)\n")
contextsBuilder.WriteString("【高置信度 - 请优先参考】\n")
for i, result := range faqResults {
passage := getEnrichedPassageForChat(ctx, result)
if hasHighConfidenceFAQ && i == 0 {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] ⭐ 精准匹配: %s\n", i+1, passage))
} else {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] %s\n", i+1, passage))
}
}
if len(docResults) > 0 {
contextsBuilder.WriteString("\n### 资料来源 2:参考文档\n")
contextsBuilder.WriteString("【补充资料 - 仅在FAQ无法解答时参考】\n")
for i, result := range docResults {
passage := getEnrichedPassageForChat(ctx, result)
contextsBuilder.WriteString(fmt.Sprintf("[DOC-%d] %s\n", i+1, passage))
}
}
} else {
// Original behavior: simple numbered list
passages := make([]string, len(chatManage.MergeResult))
for i, result := range chatManage.MergeResult {
passages[i] = getEnrichedPassageForChat(ctx, result)
}
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),
"faq_priority": chatManage.FAQPriorityEnabled,
})
return next()
}

View File

@ -0,0 +1,126 @@
// Package chatpipline provides chat pipeline processing capabilities
package chatpipline
import (
"context"
"regexp"
"slices"
"sort"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// PluginLoadHistory is a plugin for loading conversation history without query rewriting
// It loads historical dialog context for multi-turn conversations
type PluginLoadHistory struct {
messageService interfaces.MessageService // Message service for retrieving historical messages
config *config.Config // System configuration
}
// regThink is a regular expression used to match and remove content between <think></think> tags
var regThink = regexp.MustCompile(`(?s)<think>.*?</think>`)
// NewPluginLoadHistory creates a new history loading plugin instance
// Also registers the plugin with the event manager
func NewPluginLoadHistory(eventManager *EventManager,
messageService interfaces.MessageService,
config *config.Config,
) *PluginLoadHistory {
res := &PluginLoadHistory{
messageService: messageService,
config: config,
}
eventManager.Register(res)
return res
}
// ActivationEvents returns the list of event types this plugin responds to
// This plugin only responds to LOAD_HISTORY events
func (p *PluginLoadHistory) ActivationEvents() []types.EventType {
return []types.EventType{types.LOAD_HISTORY}
}
// OnEvent processes triggered events
// When receiving a LOAD_HISTORY event, it loads conversation history without rewriting the query
func (p *PluginLoadHistory) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
// Determine max rounds from config or request
maxRounds := p.config.Conversation.MaxRounds
if chatManage.MaxRounds > 0 {
maxRounds = chatManage.MaxRounds
}
pipelineInfo(ctx, "LoadHistory", "input", map[string]interface{}{
"session_id": chatManage.SessionID,
"max_rounds": maxRounds,
})
// Get conversation history (fetch more to account for incomplete pairs)
history, err := p.messageService.GetRecentMessagesBySession(ctx, chatManage.SessionID, maxRounds*2+10)
if err != nil {
pipelineWarn(ctx, "LoadHistory", "history_fetch", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
pipelineInfo(ctx, "LoadHistory", "fetched", map[string]interface{}{
"session_id": chatManage.SessionID,
"message_count": len(history),
})
// Convert historical messages to conversation history structure
historyMap := make(map[string]*types.History)
// Process historical messages, grouped by requestID
for _, message := range history {
h, ok := historyMap[message.RequestID]
if !ok {
h = &types.History{}
}
if message.Role == "user" {
// User message as query
h.Query = message.Content
h.CreateAt = message.CreatedAt
} else {
// System message as answer, while removing thinking process
h.Answer = regThink.ReplaceAllString(message.Content, "")
h.KnowledgeReferences = message.KnowledgeReferences
}
historyMap[message.RequestID] = h
}
// Convert to list and filter incomplete conversations
historyList := make([]*types.History, 0)
for _, h := range historyMap {
if h.Answer != "" && h.Query != "" {
historyList = append(historyList, h)
}
}
// Sort by time, keep the most recent conversations
sort.Slice(historyList, func(i, j int) bool {
return historyList[i].CreateAt.After(historyList[j].CreateAt)
})
// Limit the number of historical records
if len(historyList) > maxRounds {
historyList = historyList[:maxRounds]
}
// Reverse to chronological order
slices.Reverse(historyList)
chatManage.History = historyList
pipelineInfo(ctx, "LoadHistory", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"history_rounds": len(historyList),
"max_rounds": maxRounds,
})
return next()
}

View File

@ -145,6 +145,22 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base)
modelScore := rr.RelevanceScore
sr.Score = compositeScore(sr, modelScore, base)
// Apply FAQ score boost if enabled
if chatManage.FAQPriorityEnabled && chatManage.FAQScoreBoost > 1.0 &&
sr.ChunkType == string(types.ChunkTypeFAQ) {
originalScore := sr.Score
sr.Score = math.Min(sr.Score*chatManage.FAQScoreBoost, 1.0)
sr.Metadata["faq_boosted"] = "true"
sr.Metadata["faq_original_score"] = fmt.Sprintf("%.4f", originalScore)
pipelineInfo(ctx, "Rerank", "faq_boost", map[string]interface{}{
"chunk_id": sr.ID,
"original_score": fmt.Sprintf("%.4f", originalScore),
"boosted_score": fmt.Sprintf("%.4f", sr.Score),
"boost_factor": chatManage.FAQScoreBoost,
})
}
pipelineInfo(ctx, "Rerank", "composite_calc", map[string]interface{}{
"chunk_id": sr.ID,
"base_score": fmt.Sprintf("%.4f", base),

View File

@ -3,12 +3,11 @@
package chatpipline
import (
"bytes"
"context"
"html/template"
"regexp"
"slices"
"sort"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/config"
@ -144,54 +143,27 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
if chatManage.RewritePromptUser != "" {
userPrompt = chatManage.RewritePromptUser
}
userTmpl, err := template.New("rewriteContent").Parse(userPrompt)
if err != nil {
pipelineError(ctx, "Rewrite", "parse_user_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
systemPrompt := p.config.Conversation.RewritePromptSystem
if chatManage.RewritePromptSystem != "" {
systemPrompt = chatManage.RewritePromptSystem
}
systemTmpl, err := template.New("rewriteContent").Parse(systemPrompt)
if err != nil {
pipelineError(ctx, "Rewrite", "parse_system_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
// Format conversation history for template
conversationText := formatConversationHistory(historyList)
currentTime := time.Now().Format("2006-01-02 15:04:05")
var userContent, systemContent bytes.Buffer
err = userTmpl.Execute(&userContent, map[string]interface{}{
"Query": chatManage.Query,
"CurrentTime": currentTime,
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
"Conversation": historyList,
})
if err != nil {
pipelineError(ctx, "Rewrite", "render_user_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
err = systemTmpl.Execute(&systemContent, map[string]interface{}{
"Query": chatManage.Query,
"CurrentTime": currentTime,
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
"Conversation": historyList,
})
if err != nil {
pipelineError(ctx, "Rewrite", "render_system_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return next()
}
yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
// Replace placeholders in prompts
userContent := strings.ReplaceAll(userPrompt, "{{conversation}}", conversationText)
userContent = strings.ReplaceAll(userContent, "{{query}}", chatManage.Query)
userContent = strings.ReplaceAll(userContent, "{{current_time}}", currentTime)
userContent = strings.ReplaceAll(userContent, "{{yesterday}}", yesterday)
systemContent := strings.ReplaceAll(systemPrompt, "{{conversation}}", conversationText)
systemContent = strings.ReplaceAll(systemContent, "{{query}}", chatManage.Query)
systemContent = strings.ReplaceAll(systemContent, "{{current_time}}", currentTime)
systemContent = strings.ReplaceAll(systemContent, "{{yesterday}}", yesterday)
rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
if err != nil {
pipelineError(ctx, "Rewrite", "get_model", map[string]interface{}{
@ -207,11 +179,11 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
response, err := rewriteModel.Chat(ctx, []chat.Message{
{
Role: "system",
Content: systemContent.String(),
Content: systemContent,
},
{
Role: "user",
Content: userContent.String(),
Content: userContent,
},
}, &chat.ChatOptions{
Temperature: 0.3,
@ -236,3 +208,21 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
})
return next()
}
// formatConversationHistory formats conversation history for prompt template
func formatConversationHistory(historyList []*types.History) string {
if len(historyList) == 0 {
return ""
}
var builder strings.Builder
for _, h := range historyList {
builder.WriteString("------BEGIN------\n")
builder.WriteString("用户的问题是:")
builder.WriteString(h.Query)
builder.WriteString("\n助手的回答是:")
builder.WriteString(h.Answer)
builder.WriteString("\n------END------\n")
}
return builder.String()
}

View File

@ -153,6 +153,7 @@ func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context,
"",
"",
"",
"",
)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{

View File

@ -0,0 +1,396 @@
package service
import (
"context"
"errors"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// Custom agent related errors
var (
ErrAgentNotFound = errors.New("agent not found")
ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent basic info")
ErrCannotDeleteBuiltin = errors.New("cannot delete built-in agent")
ErrAgentNameRequired = errors.New("agent name is required")
)
// customAgentService implements the CustomAgentService interface
type customAgentService struct {
repo interfaces.CustomAgentRepository
}
// NewCustomAgentService creates a new custom agent service
func NewCustomAgentService(repo interfaces.CustomAgentRepository) interfaces.CustomAgentService {
return &customAgentService{
repo: repo,
}
}
// CreateAgent creates a new custom agent
func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
// Validate required fields
if strings.TrimSpace(agent.Name) == "" {
return nil, ErrAgentNameRequired
}
// Generate UUID and set creation timestamps
if agent.ID == "" {
agent.ID = uuid.New().String()
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
agent.TenantID = tenantID
// Set timestamps
agent.CreatedAt = time.Now()
agent.UpdatedAt = time.Now()
// Ensure agent mode is set for user-created agents
if agent.Config.AgentMode == "" {
agent.Config.AgentMode = types.AgentModeQuickAnswer
}
// Cannot create built-in agents
agent.IsBuiltin = false
// Set defaults
agent.EnsureDefaults()
logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s",
agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode)
if err := s.repo.CreateAgent(ctx, agent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agent.ID,
"tenant_id": agent.TenantID,
})
return nil, err
}
logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s", agent.ID, agent.Name)
return agent, nil
}
// GetAgentByID retrieves an agent by its ID (including built-in agents)
func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) {
if id == "" {
logger.Error(ctx, "Agent ID is empty")
return nil, errors.New("agent ID cannot be empty")
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Check if it's a built-in agent using the registry
if types.IsBuiltinAgentID(id) {
// Try to get from database first (for customized config)
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err == nil {
// Found in database, return with customized config
return agent, nil
}
// Not in database, return default built-in agent from registry
if builtinAgent := types.GetBuiltinAgent(id, tenantID); builtinAgent != nil {
return builtinAgent, nil
}
}
// Query from database
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
return nil, err
}
return agent, nil
}
// ListAgents lists all agents for the current tenant (including built-in agents)
func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAgent, error) {
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Get 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,
})
return nil, err
}
// Track which built-in agents exist in database
builtinInDB := make(map[string]bool)
for _, agent := range allAgents {
if types.IsBuiltinAgentID(agent.ID) {
builtinInDB[agent.ID] = true
}
}
// Build result: built-in agents first, then custom agents
builtinIDs := types.GetBuiltinAgentIDs()
result := make([]*types.CustomAgent, 0, len(allAgents)+len(builtinIDs))
// Add built-in agents in order
for _, builtinID := range builtinIDs {
if builtinInDB[builtinID] {
// Use customized config from database
for _, agent := range allAgents {
if agent.ID == builtinID {
result = append(result, agent)
break
}
}
} else {
// Use default built-in agent
if agent := types.GetBuiltinAgent(builtinID, tenantID); agent != nil {
result = append(result, agent)
}
}
}
// Add custom agents
for _, agent := range allAgents {
if !types.IsBuiltinAgentID(agent.ID) {
result = append(result, agent)
}
}
return result, nil
}
// UpdateAgent updates an agent's information
func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
if agent.ID == "" {
logger.Error(ctx, "Agent ID is empty")
return nil, errors.New("agent ID cannot be empty")
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Handle built-in agents specially using registry
if types.IsBuiltinAgentID(agent.ID) {
return s.updateBuiltinAgent(ctx, agent, tenantID)
}
// Get existing agent
existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
}
return nil, err
}
// Cannot modify built-in status
if existingAgent.IsBuiltin {
return nil, ErrCannotModifyBuiltin
}
// Validate name
if strings.TrimSpace(agent.Name) == "" {
return nil, ErrAgentNameRequired
}
// Update fields
existingAgent.Name = agent.Name
existingAgent.Description = agent.Description
existingAgent.Avatar = agent.Avatar
existingAgent.Config = agent.Config
existingAgent.UpdatedAt = time.Now()
// Ensure defaults
existingAgent.EnsureDefaults()
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s", agent.ID, agent.Name)
if err := s.repo.UpdateAgent(ctx, existingAgent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agent.ID,
})
return nil, err
}
logger.Infof(ctx, "Custom agent updated successfully, ID: %s", agent.ID)
return existingAgent, nil
}
// 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 from registry
defaultAgent := types.GetBuiltinAgent(agent.ID, tenantID)
if defaultAgent == nil {
return nil, ErrAgentNotFound
}
// 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,
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 == "" {
logger.Error(ctx, "Agent ID is empty")
return errors.New("agent ID cannot be empty")
}
// Cannot delete built-in agents using registry check
if types.IsBuiltinAgentID(id) {
return ErrCannotDeleteBuiltin
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return ErrInvalidTenantID
}
// Get existing agent to verify ownership
existingAgent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return ErrAgentNotFound
}
return err
}
// Cannot delete built-in agents
if existingAgent.IsBuiltin {
return ErrCannotDeleteBuiltin
}
logger.Infof(ctx, "Deleting custom agent, ID: %s", id)
if err := s.repo.DeleteAgent(ctx, id, tenantID); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
return err
}
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id)
return nil
}
// CopyAgent creates a copy of an existing agent
func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error) {
if id == "" {
logger.Error(ctx, "Agent ID is empty")
return nil, errors.New("agent ID cannot be empty")
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Get the source agent
sourceAgent, err := s.GetAgentByID(ctx, id)
if err != nil {
return nil, err
}
// Create a new agent with copied data
newAgent := &types.CustomAgent{
ID: uuid.New().String(),
Name: sourceAgent.Name + " (副本)",
Description: sourceAgent.Description,
Avatar: sourceAgent.Avatar,
IsBuiltin: false, // Copied agents are never built-in
TenantID: tenantID,
Config: sourceAgent.Config,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// Ensure defaults
newAgent.EnsureDefaults()
logger.Infof(ctx, "Copying agent, source ID: %s, new ID: %s", id, newAgent.ID)
if err := s.repo.CreateAgent(ctx, newAgent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"source_agent_id": id,
"new_agent_id": newAgent.ID,
})
return nil, err
}
logger.Infof(ctx, "Agent copied successfully, source ID: %s, new ID: %s", id, newAgent.ID)
return newAgent, nil
}

View File

@ -1956,10 +1956,10 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
}
// Replace placeholders
prompt = strings.ReplaceAll(prompt, "{{.QuestionCount}}", fmt.Sprintf("%d", questionCount))
prompt = strings.ReplaceAll(prompt, "{{.Content}}", content)
prompt = strings.ReplaceAll(prompt, "{{.Context}}", contextSection)
prompt = strings.ReplaceAll(prompt, "{{.DocName}}", docName)
prompt = strings.ReplaceAll(prompt, "{{question_count}}", fmt.Sprintf("%d", questionCount))
prompt = strings.ReplaceAll(prompt, "{{content}}", content)
prompt = strings.ReplaceAll(prompt, "{{context}}", contextSection)
prompt = strings.ReplaceAll(prompt, "{{doc_name}}", docName)
thinking := false
response, err := chatModel.Chat(ctx, []chat.Message{
@ -2000,11 +2000,11 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
// Default prompt for question generation with context support
const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
{{.Context}}
{{context}}
## 主要内容(请基于此内容生成问题)
文档名称:{{.DocName}}
文档名称:{{doc_name}}
文档内容:
{{.Content}}
{{content}}
## 核心要求
- 生成的问题必须与【主要内容】直接相关
@ -2013,7 +2013,7 @@ const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手
- 问题应该是用户在实际场景中可能会提出的自然问题
- 问题应该多样化,覆盖内容的不同方面
- 每个问题应该简洁明了,长度控制在30字以内
- 生成的问题数量为 {{.QuestionCount}} 个
- 生成的问题数量为 {{question_count}} 个
## 问题类型建议
- 定义类:什么是...?...是什么?
@ -2550,6 +2550,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
"",
"",
"",
"",
)
chunkPage++
if err != nil {
@ -2664,7 +2665,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
}
chunkType := []types.ChunkType{types.ChunkTypeFAQ}
chunks, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(
ctx, tenantID, faqKnowledge.ID, page, chunkType, tagID, keyword, searchField, sortOrder,
ctx, tenantID, faqKnowledge.ID, page, chunkType, tagID, keyword, searchField, sortOrder, types.KnowledgeTypeFAQ,
)
if err != nil {
return nil, err
@ -5860,4 +5861,3 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string,
}
return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit)
}

View File

@ -166,3 +166,42 @@ func (cm *contextManager) GetContextStats(ctx context.Context, sessionID string)
return stats, nil
}
// SetSystemPrompt sets or updates the system prompt for a session
// If a system message exists, it will be replaced; otherwise, a new one will be added at the beginning
func (cm *contextManager) SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error {
logger.Infof(ctx, "[ContextManager][Session-%s] Setting system prompt, length=%d", sessionID, len(systemPrompt))
// Load existing messages from storage
messages, err := cm.storage.Load(ctx, sessionID)
if err != nil {
logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to load context: %v", sessionID, err)
return fmt.Errorf("failed to load context: %w", err)
}
// Create new system message
systemMessage := chat.Message{
Role: "system",
Content: systemPrompt,
}
// Check if first message is a system message
if len(messages) > 0 && messages[0].Role == "system" {
// Replace existing system message
logger.Debugf(ctx, "[ContextManager][Session-%s] Replacing existing system prompt", sessionID)
messages[0] = systemMessage
} else {
// Insert system message at the beginning
logger.Debugf(ctx, "[ContextManager][Session-%s] Inserting new system prompt at beginning", sessionID)
messages = append([]chat.Message{systemMessage}, messages...)
}
// Save updated messages to storage
if err := cm.storage.Save(ctx, sessionID, messages); err != nil {
logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to save context: %v", sessionID, err)
return fmt.Errorf("failed to save context: %w", err)
}
logger.Infof(ctx, "[ContextManager][Session-%s] System prompt set successfully", sessionID)
return nil
}

View File

@ -1,15 +1,12 @@
package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"text/template"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/tools"
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext"
@ -17,6 +14,7 @@ import (
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@ -87,8 +85,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)
@ -221,8 +218,9 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
}
// GenerateTitle generates a title for the current conversation content
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
func (s *sessionService) GenerateTitle(ctx context.Context,
session *types.Session, messages []types.Message,
session *types.Session, messages []types.Message, modelID string,
) (string, error) {
if session == nil {
logger.Error(ctx, "Failed to generate title: session cannot be empty")
@ -259,23 +257,20 @@ 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
// Use provided modelID, or fallback to first available KnowledgeQA model
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)
}
// 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)
logger.Infof(ctx, "Using first available KnowledgeQA model for title: %s", modelID)
break
}
}
@ -283,6 +278,8 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
logger.Error(ctx, "No KnowledgeQA model found")
return "", errors.New("no KnowledgeQA model available for title generation")
}
} else {
logger.Infof(ctx, "Using specified model for title generation: %s", modelID)
}
chatModel, err := s.modelService.GetChatModel(ctx, modelID)
@ -329,10 +326,12 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
// GenerateTitleAsync generates a title for the session asynchronously
// This method clones the session and generates the title in a goroutine
// It emits an event when the title is generated
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
func (s *sessionService) GenerateTitleAsync(
ctx context.Context,
session *types.Session,
userQuery string,
modelID string,
eventBus *event.EventBus,
) {
// Extract values from context before cloning
@ -361,7 +360,7 @@ func (s *sessionService) GenerateTitleAsync(
},
}
title, err := s.GenerateTitle(bgCtx, session, messages)
title, err := s.GenerateTitle(bgCtx, session, messages, modelID)
if err != nil {
logger.ErrorWithFields(bgCtx, err, map[string]interface{}{
"session_id": session.ID,
@ -392,6 +391,7 @@ func (s *sessionService) GenerateTitleAsync(
// KnowledgeQA performs knowledge base question answering with LLM summarization
// Events are emitted through eventBus (references, answer chunks, completion)
// customAgent is optional - if provided, uses custom agent configuration for multiTurnEnabled and historyTurns
func (s *sessionService) KnowledgeQA(
ctx context.Context,
session *types.Session,
@ -402,6 +402,7 @@ func (s *sessionService) KnowledgeQA(
summaryModelID string,
webSearchEnabled bool,
eventBus *event.EventBus,
customAgent *types.CustomAgent,
) error {
logger.Infof(
ctx,
@ -411,101 +412,42 @@ 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)
}
// Use custom agent's knowledge bases only if request didn't specify any
// When user explicitly @mentions a knowledge base or document, only search those
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 {
knowledgeBaseIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent)
} else {
logger.Infof(ctx, "Using request-specified targets (ignoring agent config): kbs=%v, docs=%v", knowledgeBaseIDs, knowledgeIDs)
}
logger.Infof(ctx, "Using knowledge bases: %v", knowledgeBaseIDs)
// Determine chat model ID: prioritize request's summaryModelID, then Remote models
chatModelID, err := s.selectChatModelIDWithOverride(ctx, session, knowledgeBaseIDs, knowledgeIDs, summaryModelID)
if err != nil {
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
@ -514,6 +456,100 @@ func (s *sessionService) KnowledgeQA(
logger.Infof(ctx, "Fallback strategy not set, using default: %v", fallbackStrategy)
}
// Apply custom agent configuration if provided
if customAgent != nil {
// Ensure defaults are set
customAgent.EnsureDefaults()
// Override model ID
if customAgent.Config.ModelID != "" {
chatModelID = customAgent.Config.ModelID
logger.Infof(ctx, "Using custom agent's model_id: %s", chatModelID)
}
// Override system prompt
if customAgent.Config.SystemPrompt != "" {
summaryConfig.Prompt = customAgent.Config.SystemPrompt
logger.Infof(ctx, "Using custom agent's system_prompt")
}
// 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 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
if !customAgent.Config.MultiTurnEnabled {
maxRounds = 0 // Disable history
logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history")
}
}
// Extract FAQ strategy settings from custom agent
var faqPriorityEnabled bool
var faqDirectAnswerThreshold float64
var faqScoreBoost float64
if customAgent != nil {
faqPriorityEnabled = customAgent.Config.FAQPriorityEnabled
faqDirectAnswerThreshold = customAgent.Config.FAQDirectAnswerThreshold
faqScoreBoost = customAgent.Config.FAQScoreBoost
if faqPriorityEnabled {
logger.Infof(ctx, "FAQ priority enabled: threshold=%.2f, boost=%.2f",
faqDirectAnswerThreshold, faqScoreBoost)
}
}
// Build unified search targets (computed once, used throughout pipeline)
searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs)
if err != nil {
@ -556,6 +592,10 @@ func (s *sessionService) KnowledgeQA(
RewritePromptUser: rewritePromptUser,
EnableRewrite: enableRewrite,
EnableQueryExpansion: enableQueryExpansion,
// FAQ Strategy Settings
FAQPriorityEnabled: faqPriorityEnabled,
FAQDirectAnswerThreshold: faqDirectAnswerThreshold,
FAQScoreBoost: faqScoreBoost,
}
// Determine pipeline based on knowledge bases availability and web search setting
@ -563,10 +603,18 @@ func (s *sessionService) KnowledgeQA(
// Otherwise use rag_stream pipeline (which handles both KB search and web search)
var pipeline []types.EventType
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && !webSearchEnabled {
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat_stream pipeline")
pipeline = types.Pipline["chat_stream"]
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat pipeline")
// For pure chat, UserContent is the Query (since INTO_CHAT_MESSAGE is skipped)
chatManage.UserContent = query
// Use chat_history_stream if multi-turn is enabled, otherwise use chat_stream
if maxRounds > 0 {
logger.Infof(ctx, "Multi-turn enabled with maxRounds=%d, using chat_history_stream pipeline", maxRounds)
pipeline = types.Pipline["chat_history_stream"]
} else {
logger.Info(ctx, "Multi-turn disabled, using chat_stream pipeline")
pipeline = types.Pipline["chat_stream"]
}
} else {
if webSearchEnabled && len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 {
logger.Info(ctx, "Web search enabled without knowledge bases, using rag_stream pipeline for web search only")
@ -581,8 +629,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
}
@ -659,10 +706,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)
@ -684,7 +727,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 {
@ -702,13 +745,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)
@ -722,22 +759,66 @@ 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")
}
// resolveKnowledgeBasesFromAgent resolves knowledge base IDs based on agent's KBSelectionMode
// Returns the resolved knowledge base IDs based on the selection mode:
// - "all": fetches all knowledge bases for the tenant
// - "selected": uses the explicitly configured knowledge bases
// - "none": returns empty slice
// - default: falls back to configured knowledge bases for backward compatibility
func (s *sessionService) resolveKnowledgeBasesFromAgent(
ctx context.Context,
customAgent *types.CustomAgent,
) []string {
if customAgent == nil {
return nil
}
switch customAgent.Config.KBSelectionMode {
case "all":
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
if err != nil {
logger.Warnf(ctx, "Failed to list all knowledge bases: %v", err)
return nil
}
kbIDs := make([]string, 0, len(allKBs))
for _, kb := range allKBs {
kbIDs = append(kbIDs, kb.ID)
}
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases", len(kbIDs))
return kbIDs
case "selected":
logger.Infof(ctx, "KBSelectionMode=selected: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
return customAgent.Config.KnowledgeBases
case "none":
logger.Infof(ctx, "KBSelectionMode=none: no knowledge bases configured")
return nil
default:
// Default to "selected" behavior for backward compatibility
if len(customAgent.Config.KnowledgeBases) > 0 {
logger.Infof(ctx, "KBSelectionMode not set: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
}
return customAgent.Config.KnowledgeBases
}
}
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
@ -859,17 +940,6 @@ func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
return nil
}
func getTenantConversationConfig(ctx context.Context) (*types.ConversationConfig, error) {
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
if tenant == nil {
return nil, errors.New("tenant is empty")
}
if tenant.ConversationConfig == nil {
return nil, errors.New("tenant has no conversation config")
}
return tenant.ConversationConfig, nil
}
// SearchKnowledge performs knowledge base search without LLM summarization
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
// knowledgeIDs: list of specific knowledge (file) IDs to search
@ -985,12 +1055,16 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
}
// AgentQA performs agent-based question answering with conversation history and streaming support
// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults
func (s *sessionService) AgentQA(
ctx context.Context,
session *types.Session,
query string,
assistantMessageID string,
eventBus *event.EventBus,
customAgent *types.CustomAgent,
knowledgeBaseIDs []string,
knowledgeIDs []string,
) error {
sessionID := session.ID
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
@ -1003,82 +1077,82 @@ 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
if tenantInfo.AgentConfig == nil {
tenantInfo.AgentConfig = &types.AgentConfig{
MaxIterations: agent.DefaultAgentMaxIterations,
ReflectionEnabled: agent.DefaultAgentReflectionEnabled,
AllowedTools: tools.DefaultAllowedTools(),
Temperature: agent.DefaultAgentTemperature,
SystemPromptWebEnabled: agent.ProgressiveRAGSystemPromptWithWeb,
SystemPromptWebDisabled: agent.ProgressiveRAGSystemPromptWithoutWeb,
UseCustomSystemPrompt: agent.DefaultUseCustomSystemPrompt,
}
}
// Ensure defaults are set
customAgent.EnsureDefaults()
// Create runtime AgentConfig by merging session and tenant configs
// Tenant config provides the runtime parameters (MaxIterations, Temperature, Tools, Models)
// Session config provides KnowledgeBases and KnowledgeIDs
// Create runtime AgentConfig from customAgent
// Note: tenantInfo.AgentConfig is deprecated, all config comes from customAgent now
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
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,
MCPSelectionMode: customAgent.Config.MCPSelectionMode,
MCPServices: customAgent.Config.MCPServices,
}
agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt
if agentConfig.UseCustomSystemPrompt {
agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true)
agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false)
// Resolve knowledge bases: request-level @ mentions take priority over agent config
if len(knowledgeBaseIDs) > 0 || len(knowledgeIDs) > 0 {
// User explicitly specified via @ mention
if len(knowledgeBaseIDs) > 0 {
agentConfig.KnowledgeBases = knowledgeBaseIDs
logger.Infof(ctx, "Using request-specified knowledge bases: %v", knowledgeBaseIDs)
}
if len(knowledgeIDs) > 0 {
agentConfig.KnowledgeIDs = knowledgeIDs
logger.Infof(ctx, "Using request-specified knowledge IDs: %v", knowledgeIDs)
}
} else {
// Use agent's configured knowledge bases based on KBSelectionMode
agentConfig.KnowledgeBases = s.resolveKnowledgeBasesFromAgent(ctx, customAgent)
}
// Set web search max results from tenant config (default: 5)
agentConfig.WebSearchMaxResults = 5
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults
// 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.SystemPrompt = 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
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults
}
}
logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, sessionID)
// 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)
@ -1090,13 +1164,12 @@ func (s *sessionService) AgentQA(
agentConfig.SearchTargets = searchTargets
logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets))
summaryModelID := session.SummaryModelID
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
}
// Get summary model from custom agent config
// Note: tenantInfo.ConversationConfig is deprecated, all config comes from customAgent now
summaryModelID := customAgent.Config.ModelID
if summaryModelID == "" {
logger.Warnf(ctx, "No summary model configured for tenant %d or session %s", tenantInfo.ID, session.ID)
return errors.New("summary model is not configured in conversation settings")
logger.Warnf(ctx, "No summary model configured for custom agent %s", customAgent.ID)
return errors.New("summary model (model_id) is not configured in custom agent settings")
}
summaryModel, err := s.modelService.GetChatModel(ctx, summaryModelID)
@ -1105,23 +1178,39 @@ func (s *sessionService) AgentQA(
return fmt.Errorf("failed to get chat model: %w", err)
}
rerankModelID := session.RerankModelID
if rerankModelID == "" && tenantInfo.ConversationConfig != nil {
rerankModelID = tenantInfo.ConversationConfig.RerankModelID
}
if rerankModelID == "" {
logger.Warnf(ctx, "No rerank model configured for tenant %d or session %s", tenantInfo.ID, session.ID)
return errors.New("rerank model is not configured in conversation settings")
}
// Get rerank model from custom agent config (only required when knowledge bases are configured)
var rerankModel rerank.Reranker
hasKnowledge := len(agentConfig.KnowledgeBases) > 0 || len(agentConfig.KnowledgeIDs) > 0
if hasKnowledge {
rerankModelID := customAgent.Config.RerankModelID
if rerankModelID == "" {
logger.Warnf(ctx, "No rerank model configured for custom agent %s, but knowledge bases are specified", customAgent.ID)
return errors.New("rerank model (rerank_model_id) is not configured in custom agent settings")
}
rerankModel, err := s.modelService.GetRerankModel(ctx, rerankModelID)
if err != nil {
logger.Warnf(ctx, "Failed to get rerank model: %v", err)
return fmt.Errorf("failed to get rerank model: %w", err)
rerankModel, err = s.modelService.GetRerankModel(ctx, rerankModelID)
if err != nil {
logger.Warnf(ctx, "Failed to get rerank model: %v", err)
return fmt.Errorf("failed to get rerank model: %w", err)
}
} else {
logger.Infof(ctx, "No knowledge bases configured, skipping rerank model initialization")
}
// Get or create contextManager for this session
contextManager := s.getContextManagerForSession(ctx, session, summaryModel)
// Set system prompt for the current agent in context manager
// This ensures the context uses the correct system prompt when switching agents
systemPrompt := agentConfig.ResolveSystemPrompt(agentConfig.WebSearchEnabled)
if systemPrompt != "" {
if err := contextManager.SetSystemPrompt(ctx, sessionID, systemPrompt); err != nil {
logger.Warnf(ctx, "Failed to set system prompt in context manager: %v", err)
} else {
logger.Infof(ctx, "System prompt updated in context manager for agent")
}
}
// Get LLM context from context manager
llmContext, err := s.getContextForSession(ctx, contextManager, sessionID)
if err != nil {
@ -1130,6 +1219,15 @@ func (s *sessionService) AgentQA(
}
logger.Infof(ctx, "Loaded %d messages from LLM context manager", len(llmContext))
// Apply multi-turn configuration for Agent mode
// Note: In Agent mode, context is managed by contextManager with compression strategies,
// so we don't apply HistoryTurns limit here. HistoryTurns is used in normal (KnowledgeQA) mode.
if !agentConfig.MultiTurnEnabled {
// Multi-turn disabled, clear history
logger.Infof(ctx, "Multi-turn disabled for this agent, clearing history context")
llmContext = []chat.Message{}
}
// Create agent engine with EventBus and ContextManager
logger.Info(ctx, "Creating agent engine")
engine, err := s.agentService.CreateAgentEngine(
@ -1176,13 +1274,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)
@ -1409,20 +1503,9 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty
// renderFallbackPrompt renders the fallback prompt template with Query variable
func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *types.ChatManage) (string, error) {
tmpl, err := template.New("fallbackPrompt").Parse(chatManage.FallbackPrompt)
if err != nil {
return "", fmt.Errorf("failed to parse template: %w", err)
}
var promptContent bytes.Buffer
err = tmpl.Execute(&promptContent, map[string]interface{}{
"Query": chatManage.Query,
})
if err != nil {
return "", fmt.Errorf("failed to execute template: %w", err)
}
return promptContent.String(), nil
// Use simple string replacement instead of Go template
result := strings.ReplaceAll(chatManage.FallbackPrompt, "{{query}}", chatManage.Query)
return result, nil
}
// consumeFallbackStream consumes the streaming response and emits events

View File

@ -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"`

View File

@ -97,6 +97,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewAuthTokenRepository))
must(container.Provide(neo4jRepo.NewNeo4jRepository))
must(container.Provide(repository.NewMCPServiceRepository))
must(container.Provide(repository.NewCustomAgentRepository))
// MCP manager for managing MCP client connections
must(container.Provide(mcp.NewMCPManager))
@ -115,6 +116,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewChunkExtractService))
must(container.Provide(service.NewMessageService))
must(container.Provide(service.NewMCPServiceService))
must(container.Provide(service.NewCustomAgentService))
// Web search service (needed by AgentService)
must(container.Provide(service.NewWebSearchService))
@ -143,6 +145,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(chatpipline.NewPluginStreamFilter))
must(container.Invoke(chatpipline.NewPluginFilterTopK))
must(container.Invoke(chatpipline.NewPluginRewrite))
must(container.Invoke(chatpipline.NewPluginLoadHistory))
must(container.Invoke(chatpipline.NewPluginExtractEntity))
must(container.Invoke(chatpipline.NewPluginSearchEntity))
must(container.Invoke(chatpipline.NewPluginSearchParallel))
@ -163,6 +166,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewSystemHandler))
must(container.Provide(handler.NewMCPServiceHandler))
must(container.Provide(handler.NewWebSearchHandler))
must(container.Provide(handler.NewCustomAgentHandler))
// Router configuration
must(container.Provide(router.NewRouter))

View File

@ -0,0 +1,371 @@
package handler
import (
"net/http"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
)
// CustomAgentHandler defines the HTTP handler for custom agent operations
type CustomAgentHandler struct {
service interfaces.CustomAgentService
}
// NewCustomAgentHandler creates a new custom agent handler instance
func NewCustomAgentHandler(service interfaces.CustomAgentService) *CustomAgentHandler {
return &CustomAgentHandler{
service: service,
}
}
// CreateAgentRequest defines the request body for creating an agent
type CreateAgentRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Avatar string `json:"avatar"`
Config types.CustomAgentConfig `json:"config"`
}
// UpdateAgentRequest defines the request body for updating an agent
type UpdateAgentRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Avatar string `json:"avatar"`
Config types.CustomAgentConfig `json:"config"`
}
// CreateAgent godoc
// @Summary 创建智能体
// @Description 创建新的自定义智能体
// @Tags 智能体
// @Accept json
// @Produce json
// @Param request body CreateAgentRequest true "智能体信息"
// @Success 201 {object} map[string]interface{} "创建的智能体"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents [post]
func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start creating custom agent")
// Parse request body
var req CreateAgentRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
// Build agent object
agent := &types.CustomAgent{
Name: req.Name,
Description: req.Description,
Avatar: req.Avatar,
Config: req.Config,
}
logger.Infof(ctx, "Creating custom agent, name: %s, agent_mode: %s",
secutils.SanitizeForLog(req.Name), req.Config.AgentMode)
// Create agent using the service
createdAgent, err := h.service.CreateAgent(ctx, agent)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
if err == service.ErrAgentNameRequired {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s",
secutils.SanitizeForLog(createdAgent.ID), secutils.SanitizeForLog(createdAgent.Name))
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": createdAgent,
})
}
// GetAgent godoc
// @Summary 获取智能体详情
// @Description 根据ID获取智能体详情
// @Tags 智能体
// @Accept json
// @Produce json
// @Param id path string true "智能体ID"
// @Success 200 {object} map[string]interface{} "智能体详情"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "智能体不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/{id} [get]
func (h *CustomAgentHandler) GetAgent(c *gin.Context) {
ctx := c.Request.Context()
// Get agent ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Agent ID is empty")
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
return
}
agent, err := h.service.GetAgentByID(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
if err == service.ErrAgentNotFound {
c.Error(errors.NewNotFoundError("Agent not found"))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": agent,
})
}
// ListAgents godoc
// @Summary 获取智能体列表
// @Description 获取当前租户的所有智能体(包括内置智能体)
// @Tags 智能体
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "智能体列表"
// @Failure 500 {object} errors.AppError "服务器错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents [get]
func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
ctx := c.Request.Context()
// Get all agents for this tenant
agents, err := h.service.ListAgents(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": agents,
})
}
// UpdateAgent godoc
// @Summary 更新智能体
// @Description 更新智能体的名称、描述和配置
// @Tags 智能体
// @Accept json
// @Produce json
// @Param id path string true "智能体ID"
// @Param request body UpdateAgentRequest true "更新请求"
// @Success 200 {object} map[string]interface{} "更新后的智能体"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "无法修改内置智能体"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/{id} [put]
func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start updating custom agent")
// Get agent ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Agent ID is empty")
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
return
}
// Parse request body
var req UpdateAgentRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
// Build agent object
agent := &types.CustomAgent{
ID: id,
Name: req.Name,
Description: req.Description,
Avatar: req.Avatar,
Config: req.Config,
}
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s",
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.Name))
// Update the agent
updatedAgent, err := h.service.UpdateAgent(ctx, agent)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
switch err {
case service.ErrAgentNotFound:
c.Error(errors.NewNotFoundError("Agent not found"))
case service.ErrCannotModifyBuiltin:
c.Error(errors.NewForbiddenError("Cannot modify built-in agent"))
case service.ErrAgentNameRequired:
c.Error(errors.NewBadRequestError(err.Error()))
default:
c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
logger.Infof(ctx, "Custom agent updated successfully, ID: %s", secutils.SanitizeForLog(id))
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": updatedAgent,
})
}
// DeleteAgent godoc
// @Summary 删除智能体
// @Description 删除指定的智能体
// @Tags 智能体
// @Accept json
// @Produce json
// @Param id path string true "智能体ID"
// @Success 200 {object} map[string]interface{} "删除成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "无法删除内置智能体"
// @Failure 404 {object} errors.AppError "智能体不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/{id} [delete]
func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start deleting custom agent")
// Get agent ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Agent ID is empty")
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
return
}
logger.Infof(ctx, "Deleting custom agent, ID: %s", secutils.SanitizeForLog(id))
// Delete the agent
err := h.service.DeleteAgent(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
switch err {
case service.ErrAgentNotFound:
c.Error(errors.NewNotFoundError("Agent not found"))
case service.ErrCannotDeleteBuiltin:
c.Error(errors.NewForbiddenError("Cannot delete built-in agent"))
default:
c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", secutils.SanitizeForLog(id))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Agent deleted successfully",
})
}
// CopyAgent godoc
// @Summary 复制智能体
// @Description 复制指定的智能体
// @Tags 智能体
// @Accept json
// @Produce json
// @Param id path string true "智能体ID"
// @Success 201 {object} map[string]interface{} "复制成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "智能体不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/{id}/copy [post]
func (h *CustomAgentHandler) CopyAgent(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start copying custom agent")
// Get agent ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Agent ID is empty")
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
return
}
logger.Infof(ctx, "Copying custom agent, ID: %s", secutils.SanitizeForLog(id))
// Copy the agent
copiedAgent, err := h.service.CopyAgent(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
switch err {
case service.ErrAgentNotFound:
c.Error(errors.NewNotFoundError("Agent not found"))
default:
c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
logger.Infof(ctx, "Custom agent copied successfully, source ID: %s, new ID: %s",
secutils.SanitizeForLog(id), secutils.SanitizeForLog(copiedAgent.ID))
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": copiedAgent,
})
}
// GetPlaceholders godoc
// @Summary 获取占位符定义
// @Description 获取所有可用的提示词占位符定义,按字段类型分组
// @Tags 智能体
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "占位符定义"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/placeholders [get]
func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
// Return all placeholder definitions grouped by field type
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"all": types.AllPlaceholders(),
"system_prompt": types.PlaceholdersByField(types.PromptFieldSystemPrompt),
"agent_system_prompt": types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt),
"context_template": types.PlaceholdersByField(types.PromptFieldContextTemplate),
"rewrite_system_prompt": types.PlaceholdersByField(types.PromptFieldRewriteSystemPrompt),
"rewrite_prompt": types.PlaceholdersByField(types.PromptFieldRewritePrompt),
"fallback_prompt": types.PlaceholdersByField(types.PromptFieldFallbackPrompt),
},
})
}

View File

@ -1,7 +1,6 @@
package session
import (
"context"
"net/http"
"github.com/Tencent/WeKnora/internal/config"
@ -20,6 +19,7 @@ type Handler struct {
streamManager interfaces.StreamManager // Manager for handling streaming responses
config *config.Config // Application configuration
knowledgebaseService interfaces.KnowledgeBaseService // Service for managing knowledge bases
customAgentService interfaces.CustomAgentService // Service for managing custom agents
}
// NewHandler creates a new instance of Handler with all necessary dependencies
@ -29,6 +29,7 @@ func NewHandler(
streamManager interfaces.StreamManager,
config *config.Config,
knowledgebaseService interfaces.KnowledgeBaseService,
customAgentService interfaces.CustomAgentService,
) *Handler {
return &Handler{
sessionService: sessionService,
@ -36,6 +37,7 @@ func NewHandler(
streamManager: streamManager,
config: config,
knowledgebaseService: knowledgebaseService,
customAgentService: customAgentService,
}
}
@ -71,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
@ -159,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获取会话详情

View File

@ -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

View File

@ -16,6 +16,149 @@ import (
"github.com/gin-gonic/gin"
)
// qaRequestContext holds all the common data needed for QA requests
type qaRequestContext struct {
ctx context.Context
c *gin.Context
sessionID string
requestID string
query string
session *types.Session
customAgent *types.CustomAgent
assistantMessage *types.Message
knowledgeBaseIDs []string
knowledgeIDs []string
summaryModelID string
webSearchEnabled bool
mentionedItems types.MentionedItems
}
// parseQARequest parses and validates a QA request, returns the request context
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
ctx := logger.CloneContext(c.Request.Context())
logger.Infof(ctx, "[%s] Start processing request", logPrefix)
// Get session ID from URL parameter
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
if sessionID == "" {
logger.Error(ctx, "Session ID is empty")
return nil, nil, errors.NewBadRequestError(errors.ErrInvalidSessionID.Error())
}
// Parse request body
var request CreateKnowledgeQARequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse request data", err)
return nil, nil, errors.NewBadRequestError(err.Error())
}
// Validate query content
if request.Query == "" {
logger.Error(ctx, "Query content is empty")
return nil, nil, errors.NewBadRequestError("Query content cannot be empty")
}
// Log request details
if requestJSON, err := json.Marshal(request); err == nil {
logger.Infof(ctx, "[%s] Request: session_id=%s, request=%s",
logPrefix, sessionID, secutils.SanitizeForLog(string(requestJSON)))
}
// Get session
session, err := h.sessionService.GetSession(ctx, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
return nil, nil, errors.NewNotFoundError("Session not found")
}
// Get custom agent if agent_id is provided
var customAgent *types.CustomAgent
if request.AgentID != "" {
logger.Infof(ctx, "Fetching custom agent, agent ID: %s", secutils.SanitizeForLog(request.AgentID))
agent, err := h.customAgentService.GetAgentByID(ctx, request.AgentID)
if err != nil {
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
secutils.SanitizeForLog(request.AgentID), err)
} else {
customAgent = agent
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s",
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode)
}
}
// Build request context
reqCtx := &qaRequestContext{
ctx: ctx,
c: c,
sessionID: sessionID,
requestID: secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String())),
query: secutils.SanitizeForLog(request.Query),
session: session,
customAgent: customAgent,
assistantMessage: &types.Message{
SessionID: sessionID,
Role: "assistant",
RequestID: c.GetString(types.RequestIDContextKey.String()),
IsCompleted: false,
},
knowledgeBaseIDs: secutils.SanitizeForLogArray(request.KnowledgeBaseIDs),
knowledgeIDs: secutils.SanitizeForLogArray(request.KnowledgeIds),
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
webSearchEnabled: request.WebSearchEnabled,
mentionedItems: convertMentionedItems(request.MentionedItems),
}
return reqCtx, &request, nil
}
// sseStreamContext holds the context for SSE streaming
type sseStreamContext struct {
eventBus *event.EventBus
asyncCtx context.Context
cancel context.CancelFunc
assistantMessage *types.Message
}
// setupSSEStream sets up the SSE streaming context
func (h *Handler) setupSSEStream(reqCtx *qaRequestContext) *sseStreamContext {
// Set SSE headers
setSSEHeaders(reqCtx.c)
// Write initial agent_query event
h.writeAgentQueryEvent(reqCtx.ctx, reqCtx.sessionID, reqCtx.assistantMessage.ID)
// Create EventBus and cancellable context
eventBus := event.NewEventBus()
asyncCtx, cancel := context.WithCancel(logger.CloneContext(reqCtx.ctx))
streamCtx := &sseStreamContext{
eventBus: eventBus,
asyncCtx: asyncCtx,
cancel: cancel,
assistantMessage: reqCtx.assistantMessage,
}
// Setup stop event handler
h.setupStopEventHandler(eventBus, reqCtx.sessionID, reqCtx.assistantMessage, cancel)
// Setup stream handler
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
reqCtx.requestID, reqCtx.assistantMessage, eventBus)
// Generate title if needed
if reqCtx.session.Title == "" {
// Use the same model as the conversation for title generation
modelID := ""
if reqCtx.customAgent != nil && reqCtx.customAgent.Config.ModelID != "" {
modelID = reqCtx.customAgent.Config.ModelID
}
logger.Infof(reqCtx.ctx, "Session has no title, starting async title generation, session ID: %s, model: %s", reqCtx.sessionID, modelID)
h.sessionService.GenerateTitleAsync(asyncCtx, reqCtx.session, reqCtx.query, modelID, eventBus)
}
return streamCtx
}
// SearchKnowledge godoc
// @Summary 知识搜索
// @Description 在知识库中搜索(不使用LLM总结)
@ -30,7 +173,6 @@ import (
// @Router /sessions/search [post]
func (h *Handler) SearchKnowledge(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
logger.Info(ctx, "Start processing knowledge search request")
// Parse request body
@ -87,8 +229,6 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
}
logger.Infof(ctx, "Knowledge search completed, found %d results", len(searchResults))
// Return search results
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": searchResults,
@ -109,73 +249,15 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/knowledge-qa [post]
func (h *Handler) KnowledgeQA(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
logger.Info(ctx, "Start processing knowledge QA request")
// Get session ID from URL parameter
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
if sessionID == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Parse request body
var request CreateKnowledgeQARequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse request data", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
// Create assistant message
assistantMessage := &types.Message{
SessionID: sessionID,
Role: "assistant",
RequestID: c.GetString(types.RequestIDContextKey.String()),
IsCompleted: false,
}
// Validate query content
if request.Query == "" {
logger.Error(ctx, "Query content is empty")
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
return
}
logger.Infof(
ctx,
"Knowledge QA request, session ID: %s, query: %s",
sessionID,
secutils.SanitizeForLog(request.Query),
)
// Get session to prepare knowledge base IDs
session, err := h.sessionService.GetSession(ctx, sessionID)
// Parse and validate request
reqCtx, _, err := h.parseQARequest(c, "KnowledgeQA")
if err != nil {
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
c.Error(errors.NewInternalServerError(err.Error()))
c.Error(err)
return
}
// Prepare knowledge base IDs
knowledgeBaseIDs := request.KnowledgeBaseIDs
// if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" {
// knowledgeBaseIDs = []string{session.KnowledgeBaseID}
// logger.Infof(
// ctx,
// "No knowledge base IDs in request, using session default: %s",
// secutils.SanitizeForLog(session.KnowledgeBaseID),
// )
// }
// Use shared function to handle KnowledgeQA request
h.handleKnowledgeQARequest(ctx, c, session, secutils.SanitizeForLog(request.Query),
secutils.SanitizeForLogArray(knowledgeBaseIDs),
secutils.SanitizeForLogArray(request.KnowledgeIds),
assistantMessage, true, secutils.SanitizeForLog(request.SummaryModelID), request.WebSearchEnabled,
convertMentionedItems(request.MentionedItems))
// Execute normal mode QA
h.executeNormalModeQA(reqCtx, true)
}
// AgentQA godoc
@ -192,427 +274,100 @@ func (h *Handler) KnowledgeQA(c *gin.Context) {
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/agent-qa [post]
func (h *Handler) AgentQA(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
logger.Info(ctx, "Start processing agent QA request")
// Get session ID from URL parameter
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
if sessionID == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
// Parse and validate request
reqCtx, request, err := h.parseQARequest(c, "AgentQA")
if err != nil {
c.Error(err)
return
}
// Parse request body
var request CreateKnowledgeQARequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse request data", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
// Determine if agent mode should be enabled
// Priority: customAgent.IsAgentMode() > request.AgentEnabled
agentModeEnabled := request.AgentEnabled
if reqCtx.customAgent != nil {
agentModeEnabled = reqCtx.customAgent.IsAgentMode()
logger.Infof(reqCtx.ctx, "Agent mode determined by custom agent: %v (config.agent_mode=%s)",
agentModeEnabled, reqCtx.customAgent.Config.AgentMode)
}
if requestJSON, err := json.Marshal(request); err == nil {
logger.Infof(ctx, "Agent QA request, request: %s", secutils.SanitizeForLog(string(requestJSON)))
// Route to appropriate handler based on agent mode
if agentModeEnabled {
h.executeAgentModeQA(reqCtx)
} else {
logger.Warnf(ctx, "failed to marshal for logging: %s", secutils.SanitizeForLog(err.Error()))
logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID)
// Knowledge bases should be specified in request or from custom agent
h.executeNormalModeQA(reqCtx, false)
}
// Validate query content
if request.Query == "" {
logger.Error(ctx, "Query content is empty")
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
return
}
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
// Get session information first
session, err := h.sessionService.GetSession(ctx, sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
c.Error(errors.NewNotFoundError("Session not found"))
return
}
sessionJSON, err := json.Marshal(session)
if err != nil {
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Before AgentQA, Session: %s", secutils.SanitizeForLog(string(sessionJSON)))
// Create assistant message
assistantMessage := &types.Message{
SessionID: sessionID,
Role: "assistant",
RequestID: c.GetString(types.RequestIDContextKey.String()),
IsCompleted: false,
}
// Initialize AgentConfig if it doesn't exist
if session.AgentConfig == nil {
session.AgentConfig = &types.SessionAgentConfig{}
}
// Detect if knowledge bases or agent mode has changed
knowledgeBasesChanged := false
knowledgeIdsChanged := false
configChanged := false
// Check if knowledge bases array has changed
if len(request.KnowledgeBaseIDs) > 0 || len(session.AgentConfig.KnowledgeBases) > 0 {
// Compare arrays to detect changes
currentKBs := session.AgentConfig.KnowledgeBases
if len(currentKBs) != len(request.KnowledgeBaseIDs) {
knowledgeBasesChanged = true
configChanged = true
} else {
// Check if contents are different
kbMap := make(map[string]bool)
for _, kb := range currentKBs {
kbMap[kb] = true
}
for _, kb := range request.KnowledgeBaseIDs {
if !kbMap[kb] {
knowledgeBasesChanged = true
configChanged = true
break
}
}
}
if knowledgeBasesChanged {
logger.Infof(ctx, "Knowledge bases changed from %s to %s",
secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeBases)),
secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeBaseIDs)),
)
}
}
// Check if knowledge IDs array has changed
if len(request.KnowledgeIds) > 0 || len(session.AgentConfig.KnowledgeIDs) > 0 {
// Compare arrays to detect changes
currentKIDs := session.AgentConfig.KnowledgeIDs
if len(currentKIDs) != len(request.KnowledgeIds) {
knowledgeIdsChanged = true
configChanged = true
} else {
// Check if contents are different
kidMap := make(map[string]bool)
for _, kid := range currentKIDs {
kidMap[kid] = true
}
for _, kid := range request.KnowledgeIds {
if !kidMap[kid] {
knowledgeIdsChanged = true
configChanged = true
break
}
}
}
if knowledgeIdsChanged {
logger.Infof(ctx, "Knowledge IDs changed from %s to %s",
secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeIDs)),
secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeIds)),
)
}
}
// Check if agent mode has changed
currentAgentEnabled := session.AgentConfig.AgentModeEnabled
if request.AgentEnabled != currentAgentEnabled {
logger.Infof(ctx, "Agent mode changed from %v to %v", currentAgentEnabled, request.AgentEnabled)
configChanged = true
}
currentWebSearchEnabled := session.AgentConfig.WebSearchEnabled
if request.WebSearchEnabled != currentWebSearchEnabled {
logger.Infof(ctx, "Web search mode changed from %v to %v", currentWebSearchEnabled, request.WebSearchEnabled)
configChanged = true
}
summaryModelID := secutils.SanitizeForLog(request.SummaryModelID)
if summaryModelID == "" {
summaryModelID = session.SummaryModelID
}
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
}
if summaryModelID != session.SummaryModelID {
configChanged = true
session.SummaryModelID = summaryModelID
}
// If configuration changed, clear context and update session
if configChanged {
logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID)
// Clear the LLM context to prevent contamination
if err := h.sessionService.ClearContext(ctx, sessionID); err != nil {
logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err)
// Continue anyway - this is not a fatal error
}
if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil {
logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err)
// Continue anyway - this is not a fatal error
}
session.AgentConfig.KnowledgeBases = secutils.SanitizeForLogArray(request.KnowledgeBaseIDs)
session.AgentConfig.KnowledgeIDs = secutils.SanitizeForLogArray(request.KnowledgeIds)
session.AgentConfig.AgentModeEnabled = request.AgentEnabled
session.AgentConfig.WebSearchEnabled = request.WebSearchEnabled
session.SummaryModelID = secutils.SanitizeForLog(summaryModelID)
// Persist the session changes
if err := h.sessionService.UpdateSession(ctx, session); err != nil {
logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err)
c.Error(errors.NewInternalServerError("Failed to update session configuration"))
return
}
logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID)
}
// If Agent mode is disabled, delegate to KnowledgeQA
if !request.AgentEnabled {
logger.Infof(ctx, "Agent mode disabled, delegating to KnowledgeQA for session: %s", sessionID)
// Use knowledge bases from request or session config
knowledgeBaseIDs := secutils.SanitizeForLogArray(request.KnowledgeBaseIDs)
if len(knowledgeBaseIDs) == 0 {
knowledgeBaseIDs = session.AgentConfig.KnowledgeBases
}
// If still empty, use session default knowledge base
if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" {
knowledgeBaseIDs = []string{session.KnowledgeBaseID}
logger.Infof(
ctx,
"Using session default knowledge base: %s",
secutils.SanitizeForLog(session.KnowledgeBaseID),
)
}
logger.Infof(
ctx,
"Delegating to KnowledgeQA with knowledge bases: %s",
secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs)),
)
// Use shared function to handle KnowledgeQA request (no title generation for AgentQA fallback)
h.handleKnowledgeQARequest(
ctx,
c,
session,
secutils.SanitizeForLog(request.Query),
secutils.SanitizeForLogArray(
knowledgeBaseIDs,
),
secutils.SanitizeForLogArray(
request.KnowledgeIds,
),
assistantMessage,
false,
secutils.SanitizeForLog(request.SummaryModelID),
request.WebSearchEnabled,
convertMentionedItems(request.MentionedItems),
)
return
}
// Emit agent query event to create user message
requestID := secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String()))
if err := event.Emit(ctx, event.Event{
Type: event.EventAgentQuery,
SessionID: sessionID,
RequestID: requestID,
Data: event.AgentQueryData{
SessionID: sessionID,
Query: secutils.SanitizeForLog(request.Query),
RequestID: requestID,
},
}); err != nil {
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
return
}
// Set headers for SSE immediately
setSSEHeaders(c)
// Create user message
if err := h.createUserMessage(ctx, sessionID, secutils.SanitizeForLog(request.Query), requestID, convertMentionedItems(request.MentionedItems)); err != nil {
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Create assistant message (response)
assistantMessagePtr, err := h.createAssistantMessage(ctx, assistantMessage)
if err != nil {
c.Error(errors.NewInternalServerError(err.Error()))
return
}
assistantMessage = assistantMessagePtr
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
// Write initial agent_query event to StreamManager
h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID)
eventBus := event.NewEventBus()
// Create cancellable context for async operations
asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx))
// Create and subscribe stream handler
h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus)
// Start async title generation if session has no title
if session.Title == "" {
logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID)
h.sessionService.GenerateTitleAsync(asyncCtx, session, secutils.SanitizeForLog(request.Query), eventBus)
}
// Register stop event handler to cancel the context
h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel)
go func() {
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 1024)
runtime.Stack(buf, true)
logger.ErrorWithFields(asyncCtx,
errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))),
map[string]interface{}{
"session_id": sessionID,
})
}
h.completeAssistantMessage(asyncCtx, assistantMessage)
logger.Infof(asyncCtx, "Agent QA service completed for session: %s", sessionID)
}()
err := h.sessionService.AgentQA(
asyncCtx,
session,
secutils.SanitizeForLog(request.Query),
assistantMessage.ID,
eventBus,
)
if err != nil {
logger.ErrorWithFields(asyncCtx, err, nil)
// Emit error event to dedicated EventBus
eventBus.Emit(asyncCtx, event.Event{
Type: event.EventError,
SessionID: sessionID,
Data: event.ErrorData{
Error: err.Error(),
Stage: "agent_execution",
SessionID: sessionID,
},
})
return
}
}()
// Handle events for SSE (blocking until connection is done)
// Wait for title only if session has no title (first message in session)
h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "")
}
// handleKnowledgeQARequest handles a KnowledgeQA request with the given parameters
// This is a shared function used by both KnowledgeQA endpoint and AgentQA fallback
func (h *Handler) handleKnowledgeQARequest(
ctx context.Context,
c *gin.Context,
session *types.Session,
query string,
knowledgeBaseIDs []string,
knowledgeIDs []string,
assistantMessage *types.Message,
generateTitle bool, // Whether to generate title if session has no title
summaryModelID string, // Optional summary model ID (overrides session default)
webSearchEnabled bool, // Whether web search is enabled
mentionedItems types.MentionedItems, // @mentioned knowledge bases and files
) {
sessionID := session.ID
requestID := getRequestID(c)
// executeNormalModeQA executes the normal (KnowledgeQA) mode
func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle bool) {
ctx := reqCtx.ctx
sessionID := reqCtx.sessionID
// Create user message
if err := h.createUserMessage(ctx, sessionID, query, requestID, mentionedItems); err != nil {
c.Error(errors.NewInternalServerError(err.Error()))
if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil {
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Create assistant message (response)
if _, err := h.createAssistantMessage(ctx, assistantMessage); err != nil {
c.Error(errors.NewInternalServerError(err.Error()))
// Create assistant message
if _, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage); err != nil {
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Using knowledge bases: %s", secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs)))
logger.Infof(ctx, "Using knowledge bases: %v", reqCtx.knowledgeBaseIDs)
// Set headers for SSE
setSSEHeaders(c)
// Setup SSE stream
streamCtx := h.setupSSEStream(reqCtx)
// Write initial agent_query event to StreamManager
h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID)
// Create dedicated EventBus for this request
eventBus := event.NewEventBus()
// Create cancellable context for async operations
asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx))
// Register stop event handler and setup stream handler
h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel)
h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus)
// Generate title if needed
if generateTitle && session.Title == "" {
logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID)
h.sessionService.GenerateTitleAsync(asyncCtx, session, query, eventBus)
}
eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
// Setup completion handler for normal mode
streamCtx.eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if !ok {
return nil
}
assistantMessage.Content += data.Content
streamCtx.assistantMessage.Content += data.Content
if data.Done {
logger.Infof(asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
h.completeAssistantMessage(asyncCtx, assistantMessage)
// Emit completion event when stream finishes
if err := eventBus.Emit(asyncCtx, event.Event{
logger.Infof(streamCtx.asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage)
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
Type: event.EventAgentComplete,
SessionID: sessionID,
Data: event.AgentCompleteData{
FinalAnswer: assistantMessage.Content,
},
}); err != nil {
logger.Errorf(asyncCtx, "Failed to emit completion event: %v", err)
}
cancel() // Clean up context
return nil
Data: event.AgentCompleteData{FinalAnswer: streamCtx.assistantMessage.Content},
})
streamCtx.cancel()
}
return nil
})
// Call service to perform knowledge QA (async, emits events)
// Execute KnowledgeQA asynchronously
go func() {
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 10240)
runtime.Stack(buf, true)
logger.ErrorWithFields(
asyncCtx,
errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))),
nil,
)
logger.ErrorWithFields(streamCtx.asyncCtx,
errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))), nil)
}
}()
err := h.sessionService.KnowledgeQA(
asyncCtx,
session,
query,
knowledgeBaseIDs,
knowledgeIDs,
assistantMessage.ID,
summaryModelID,
webSearchEnabled,
eventBus,
streamCtx.asyncCtx,
reqCtx.session,
reqCtx.query,
reqCtx.knowledgeBaseIDs,
reqCtx.knowledgeIDs,
reqCtx.assistantMessage.ID,
reqCtx.summaryModelID,
reqCtx.webSearchEnabled,
streamCtx.eventBus,
reqCtx.customAgent,
)
if err != nil {
logger.ErrorWithFields(asyncCtx, err, nil)
// Emit error event to dedicated EventBus
eventBus.Emit(asyncCtx, event.Event{
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
Type: event.EventError,
SessionID: sessionID,
Data: event.ErrorData{
@ -621,13 +376,95 @@ func (h *Handler) handleKnowledgeQARequest(
SessionID: sessionID,
},
})
return
}
}()
// Handle events for SSE (blocking until connection is done)
// Wait for title only if session has no title (first message in session)
h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "")
// Handle SSE events (blocking)
shouldWaitForTitle := generateTitle && reqCtx.session.Title == ""
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
reqCtx.requestID, streamCtx.eventBus, shouldWaitForTitle)
}
// executeAgentModeQA executes the agent mode
func (h *Handler) executeAgentModeQA(reqCtx *qaRequestContext) {
ctx := reqCtx.ctx
sessionID := reqCtx.sessionID
// Emit agent query event
if err := event.Emit(ctx, event.Event{
Type: event.EventAgentQuery,
SessionID: sessionID,
RequestID: reqCtx.requestID,
Data: event.AgentQueryData{
SessionID: sessionID,
Query: reqCtx.query,
RequestID: reqCtx.requestID,
},
}); err != nil {
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
return
}
// Create user message
if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil {
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Create assistant message
assistantMessagePtr, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage)
if err != nil {
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
return
}
reqCtx.assistantMessage = assistantMessagePtr
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
// Setup SSE stream
streamCtx := h.setupSSEStream(reqCtx)
// Execute AgentQA asynchronously
go func() {
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 1024)
runtime.Stack(buf, true)
logger.ErrorWithFields(streamCtx.asyncCtx,
errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))),
map[string]interface{}{"session_id": sessionID})
}
h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage)
logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)
}()
err := h.sessionService.AgentQA(
streamCtx.asyncCtx,
reqCtx.session,
reqCtx.query,
reqCtx.assistantMessage.ID,
streamCtx.eventBus,
reqCtx.customAgent,
reqCtx.knowledgeBaseIDs,
reqCtx.knowledgeIDs,
)
if err != nil {
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
Type: event.EventError,
SessionID: sessionID,
Data: event.ErrorData{
Error: err.Error(),
Stage: "agent_execution",
SessionID: sessionID,
},
})
}
}()
// Handle SSE events (blocking)
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
reqCtx.requestID, streamCtx.eventBus, reqCtx.session.Title == "")
}
// completeAssistantMessage marks an assistant message as complete and updates it

View File

@ -52,7 +52,7 @@ func (h *Handler) GenerateTitle(c *gin.Context) {
// Call service to generate title
logger.Infof(ctx, "Generating session title, session ID: %s, message count: %d", sessionID, len(request.Messages))
title, err := h.sessionService.GenerateTitle(ctx, session, request.Messages)
title, err := h.sessionService.GenerateTitle(ctx, session, request.Messages, "")
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))

View File

@ -65,6 +65,7 @@ type CreateKnowledgeQARequest struct {
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
AgentID string `json:"agent_id"` // Selected custom agent ID for this request
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files

View File

@ -419,13 +419,11 @@ func (h *TenantHandler) SearchTenants(c *gin.Context) {
// AgentConfigRequest represents the request body for updating agent configuration
type AgentConfigRequest struct {
MaxIterations int `json:"max_iterations"`
ReflectionEnabled bool `json:"reflection_enabled"`
AllowedTools []string `json:"allowed_tools"`
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"`
MaxIterations int `json:"max_iterations"`
ReflectionEnabled bool `json:"reflection_enabled"`
AllowedTools []string `json:"allowed_tools"`
Temperature float64 `json:"temperature"`
SystemPrompt string `json:"system_prompt,omitempty"` // Unified system prompt (uses {{web_search_status}} placeholder)
}
// GetTenantAgentConfig godoc
@ -473,45 +471,37 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"max_iterations": agent.DefaultAgentMaxIterations,
"reflection_enabled": agent.DefaultAgentReflectionEnabled,
"allowed_tools": agenttools.DefaultAllowedTools(),
"temperature": agent.DefaultAgentTemperature,
"system_prompt_web_enabled": agent.ProgressiveRAGSystemPromptWithWeb,
"system_prompt_web_disabled": agent.ProgressiveRAGSystemPromptWithoutWeb,
"use_custom_system_prompt": false,
"available_tools": availableTools,
"available_placeholders": availablePlaceholders,
"max_iterations": agent.DefaultAgentMaxIterations,
"reflection_enabled": agent.DefaultAgentReflectionEnabled,
"allowed_tools": agenttools.DefaultAllowedTools(),
"temperature": agent.DefaultAgentTemperature,
"system_prompt": agent.ProgressiveRAGSystemPrompt,
"use_custom_system_prompt": false,
"available_tools": availableTools,
"available_placeholders": availablePlaceholders,
},
})
return
}
// Get system prompts for both web search states, use defaults if empty
systemPromptWithWeb := tenant.AgentConfig.ResolveSystemPrompt(true)
if systemPromptWithWeb == "" {
systemPromptWithWeb = agent.ProgressiveRAGSystemPromptWithWeb
// Get system prompt, use default if empty
systemPrompt := tenant.AgentConfig.ResolveSystemPrompt(true) // webSearchEnabled doesn't matter for unified prompt
if systemPrompt == "" {
systemPrompt = agent.ProgressiveRAGSystemPrompt
}
systemPromptWithoutWeb := tenant.AgentConfig.ResolveSystemPrompt(false)
if systemPromptWithoutWeb == "" {
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,
"data": gin.H{
"max_iterations": tenant.AgentConfig.MaxIterations,
"reflection_enabled": tenant.AgentConfig.ReflectionEnabled,
"allowed_tools": agenttools.DefaultAllowedTools(),
"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,
"max_iterations": tenant.AgentConfig.MaxIterations,
"reflection_enabled": tenant.AgentConfig.ReflectionEnabled,
"allowed_tools": agenttools.DefaultAllowedTools(),
"temperature": tenant.AgentConfig.Temperature,
"system_prompt": systemPrompt,
"use_custom_system_prompt": tenant.AgentConfig.UseCustomSystemPrompt,
"available_tools": availableTools,
"available_placeholders": availablePlaceholders,
},
})
}
@ -546,25 +536,21 @@ 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
// Support both new unified SystemPrompt and deprecated separate prompts
systemPrompt := req.SystemPrompt
useCustomPrompt := systemPrompt != ""
agentConfig := &types.AgentConfig{
MaxIterations: req.MaxIterations,
ReflectionEnabled: req.ReflectionEnabled,
AllowedTools: agenttools.DefaultAllowedTools(),
Temperature: req.Temperature,
SystemPrompt: systemPrompt,
UseCustomSystemPrompt: useCustomPrompt,
}
tenant.AgentConfig = &types.AgentConfig{
MaxIterations: req.MaxIterations,
ReflectionEnabled: req.ReflectionEnabled,
AllowedTools: agenttools.DefaultAllowedTools(),
Temperature: req.Temperature,
SystemPromptWebEnabled: req.SystemPromptWebEnabled,
SystemPromptWebDisabled: req.SystemPromptWebDisabled,
UseCustomSystemPrompt: useCustomPrompt,
}
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
_, err := h.service.UpdateTenant(ctx, tenant)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr)
@ -579,7 +565,7 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
logger.Infof(ctx, "Tenant agent config updated successfully, Tenant ID: %d", tenant.ID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": updatedTenant.AgentConfig,
"data": agentConfig,
"message": "Agent configuration updated successfully",
})
}
@ -610,6 +596,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 +715,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 +790,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 +847,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,
})
}

View File

@ -208,12 +208,19 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
"enable_thinking": thinking,
}
// print req
// jsonData, err := json.Marshal(req)
// if err != nil {
// logger.Error(context.Background(), "marshal request: %w", err)
// }
// logger.Infof(context.Background(), "llm request: %s", string(jsonData))
// Log LLM request for debugging
if jsonData, err := json.MarshalIndent(req, "", " "); err == nil {
logger.Infof(context.Background(), "[LLM Request] model=%s, stream=%v, request:\n%s", c.modelName, isStream, string(jsonData))
}
// Log tools/functions separately for clarity
if len(req.Tools) > 0 {
toolNames := make([]string, 0, len(req.Tools))
for _, tool := range req.Tools {
toolNames = append(toolNames, tool.Function.Name)
}
logger.Infof(context.Background(), "[LLM Request] tools_count=%d, tool_names=%v", len(req.Tools), toolNames)
}
return req
}

View File

@ -47,6 +47,7 @@ type RouterParams struct {
WebSearchHandler *handler.WebSearchHandler
FAQHandler *handler.FAQHandler
TagHandler *handler.TagHandler
CustomAgentHandler *handler.CustomAgentHandler
}
// NewRouter 创建新的路由
@ -110,6 +111,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterSystemRoutes(v1, params.SystemHandler)
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler)
RegisterWebSearchRoutes(v1, params.WebSearchHandler)
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler)
}
return r
@ -412,3 +414,24 @@ func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSe
webSearch.GET("/providers", webSearchHandler.GetProviders)
}
}
// RegisterCustomAgentRoutes registers custom agent routes
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) {
agents := r.Group("/agents")
{
// Get placeholder definitions (must be before /:id to avoid conflict)
agents.GET("/placeholders", agentHandler.GetPlaceholders)
// Create custom agent
agents.POST("", agentHandler.CreateAgent)
// List all agents (including built-in)
agents.GET("", agentHandler.ListAgents)
// Get agent by ID
agents.GET("/:id", agentHandler.GetAgent)
// Update agent
agents.PUT("/:id", agentHandler.UpdateAgent)
// Delete agent
agents.DELETE("/:id", agentHandler.DeleteAgent)
// Copy agent
agents.POST("/:id/copy", agentHandler.CopyAgent)
}
}

View File

@ -10,18 +10,25 @@ import (
// AgentConfig represents the full agent configuration (used at tenant level and runtime)
// This includes all configuration parameters for agent execution
type AgentConfig struct {
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
Temperature float64 `json:"temperature"` // LLM temperature for agent
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
KnowledgeIDs []string `json:"knowledge_ids"` // Accessible knowledge IDs (individual documents)
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` // Custom prompt when web search is enabled
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` // Custom prompt when web search is disabled
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
Temperature float64 `json:"temperature"` // LLM temperature for agent
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
KnowledgeIDs []string `json:"knowledge_ids"` // Accessible knowledge IDs (individual documents)
SystemPrompt string `json:"system_prompt,omitempty"` // Unified system prompt (uses {{web_search_status}} placeholder for dynamic behavior)
// Deprecated: Use SystemPrompt instead. Kept for backward compatibility during migration.
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"` // Deprecated: Custom prompt when web search is enabled
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"` // Deprecated: Custom prompt when web search is disabled
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled
HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
// MCP service selection
MCPSelectionMode string `json:"mcp_selection_mode"` // MCP selection mode: "all", "selected", "none"
MCPServices []string `json:"mcp_services"` // Selected MCP service IDs (when mode is "selected")
}
// SessionAgentConfig represents session-level agent configuration
@ -68,11 +75,18 @@ func (c *SessionAgentConfig) Scan(value interface{}) error {
}
// ResolveSystemPrompt returns the prompt template for the given web search state.
// It uses the unified SystemPrompt field, falling back to deprecated fields for backward compatibility.
func (c *AgentConfig) ResolveSystemPrompt(webSearchEnabled bool) string {
if c == nil {
return ""
}
// First, try the new unified SystemPrompt field
if c.SystemPrompt != "" {
return c.SystemPrompt
}
// Fallback to deprecated fields for backward compatibility
if webSearchEnabled {
if c.SystemPromptWebEnabled != "" {
return c.SystemPromptWebEnabled

View File

@ -53,6 +53,11 @@ type ChatManage struct {
// Web search configuration (internal use)
TenantID uint64 `json:"-"` // Tenant ID for retrieving web search config
WebSearchEnabled bool `json:"-"` // Whether web search is enabled for this request
// FAQ Strategy Settings
FAQPriorityEnabled bool `json:"-"` // Whether FAQ priority strategy is enabled
FAQDirectAnswerThreshold float64 `json:"-"` // Threshold for direct FAQ answer (similarity > this value)
FAQScoreBoost float64 `json:"-"` // Score multiplier for FAQ results
}
// Clone creates a deep copy of the ChatManage object
@ -117,6 +122,10 @@ func (c *ChatManage) Clone() *ChatManage {
EnableRewrite: c.EnableRewrite,
EnableQueryExpansion: c.EnableQueryExpansion,
TenantID: c.TenantID,
// FAQ Strategy Settings
FAQPriorityEnabled: c.FAQPriorityEnabled,
FAQDirectAnswerThreshold: c.FAQDirectAnswerThreshold,
FAQScoreBoost: c.FAQScoreBoost,
}
}
@ -124,6 +133,7 @@ func (c *ChatManage) Clone() *ChatManage {
type EventType string
const (
LOAD_HISTORY EventType = "load_history" // Load conversation history without rewriting
REWRITE_QUERY EventType = "rewrite_query" // Query rewriting for better retrieval
CHUNK_SEARCH EventType = "chunk_search" // Search for relevant chunks
CHUNK_SEARCH_PARALLEL EventType = "chunk_search_parallel" // Parallel search: chunks + entities
@ -142,7 +152,12 @@ var Pipline = map[string][]EventType{
"chat": { // Simple chat without retrieval
CHAT_COMPLETION,
},
"chat_stream": { // Streaming chat without retrieval
"chat_stream": { // Streaming chat without retrieval (no history)
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
},
"chat_history_stream": { // Streaming chat with conversation history
LOAD_HISTORY,
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
},

View File

@ -0,0 +1,337 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
)
// BuiltinAgentID constants for built-in agents
const (
// BuiltinQuickAnswerID is the ID for the built-in quick answer (RAG) agent
BuiltinQuickAnswerID = "builtin-quick-answer"
// BuiltinSmartReasoningID is the ID for the built-in smart reasoning (ReAct) agent
BuiltinSmartReasoningID = "builtin-smart-reasoning"
// BuiltinDeepResearcherID is the ID for the built-in deep researcher agent
BuiltinDeepResearcherID = "builtin-deep-researcher"
// BuiltinDataAnalystID is the ID for the built-in data analyst agent
BuiltinDataAnalystID = "builtin-data-analyst"
// BuiltinKnowledgeGraphExpertID is the ID for the built-in knowledge graph expert agent
BuiltinKnowledgeGraphExpertID = "builtin-knowledge-graph-expert"
// BuiltinDocumentAssistantID is the ID for the built-in document assistant agent
BuiltinDocumentAssistantID = "builtin-document-assistant"
)
// AgentMode constants for agent running mode
const (
// AgentModeQuickAnswer is the RAG mode for quick Q&A
AgentModeQuickAnswer = "quick-answer"
// AgentModeSmartReasoning is the ReAct mode for multi-step reasoning
AgentModeSmartReasoning = "smart-reasoning"
)
// CustomAgent represents a configurable AI agent (similar to GPTs)
type CustomAgent struct {
// Unique identifier of the agent (composite primary key with TenantID)
// For built-in agents, this is 'builtin-quick-answer' or 'builtin-smart-reasoning'
// For custom agents, this is a UUID
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Name of the agent
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
// Description of the agent
Description string `yaml:"description" json:"description" gorm:"type:text"`
// Avatar/Icon of the agent (emoji or icon name)
Avatar string `yaml:"avatar" json:"avatar" gorm:"type:varchar(64)"`
// Whether this is a built-in agent (normal mode / agent mode)
IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"`
// Tenant ID (composite primary key with ID)
TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"primaryKey"`
// Created by user ID
CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"`
// Agent configuration
Config CustomAgentConfig `yaml:"config" json:"config" gorm:"type:json"`
// Timestamps
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
}
// CustomAgentConfig represents the configuration of a custom agent
type CustomAgentConfig struct {
// ===== Basic Settings =====
// Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent mode
AgentMode string `yaml:"agent_mode" json:"agent_mode"`
// System prompt for the agent (unified prompt, uses {{web_search_status}} placeholder for dynamic behavior)
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
// 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"`
// Whether reflection is enabled (only for agent type)
ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`
// MCP service selection mode: "all" = all enabled MCP services, "selected" = specific services, "none" = no MCP
MCPSelectionMode string `yaml:"mcp_selection_mode" json:"mcp_selection_mode"`
// Selected MCP service IDs (only used when MCPSelectionMode is "selected")
MCPServices []string `yaml:"mcp_services" json:"mcp_services"`
// ===== Knowledge Base Settings =====
// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`
// Associated knowledge base IDs (only used when KBSelectionMode is "selected")
KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"`
// ===== FAQ Strategy Settings =====
// Whether FAQ priority strategy is enabled (FAQ answers prioritized over document chunks)
FAQPriorityEnabled bool `yaml:"faq_priority_enabled" json:"faq_priority_enabled"`
// FAQ direct answer threshold - if similarity > this value, use FAQ answer directly
FAQDirectAnswerThreshold float64 `yaml:"faq_direct_answer_threshold" json:"faq_direct_answer_threshold"`
// FAQ score boost multiplier - FAQ results score multiplied by this factor
FAQScoreBoost float64 `yaml:"faq_score_boost" json:"faq_score_boost"`
// ===== 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"`
// ===== 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
func (c CustomAgentConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements sql.Scanner interface for CustomAgentConfig
func (c *CustomAgentConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// TableName returns the table name for CustomAgent
func (CustomAgent) TableName() string {
return "custom_agents"
}
// EnsureDefaults sets default values for the agent
func (a *CustomAgent) EnsureDefaults() {
if a == nil {
return
}
if a.Config.Temperature == 0 {
a.Config.Temperature = 0.7
}
if a.Config.MaxIterations == 0 {
a.Config.MaxIterations = 10
}
if a.Config.WebSearchMaxResults == 0 {
a.Config.WebSearchMaxResults = 5
}
if a.Config.HistoryTurns == 0 {
a.Config.HistoryTurns = 5
}
// 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
}
// Agent mode should always enable multi-turn conversation
if a.Config.AgentMode == AgentModeSmartReasoning {
a.Config.MultiTurnEnabled = true
}
}
// IsAgentMode returns true if this agent uses ReAct agent mode
func (a *CustomAgent) IsAgentMode() bool {
return a.Config.AgentMode == AgentModeSmartReasoning
}
// GetBuiltinQuickAnswerAgent returns the built-in quick answer (RAG) mode agent
func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinQuickAnswerID,
Name: "快速问答",
Description: "基于知识库的 RAG 问答,快速准确地回答问题",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeQuickAnswer,
SystemPrompt: "",
Temperature: 0.7,
MaxCompletionTokens: 2048,
WebSearchEnabled: true,
WebSearchMaxResults: 5,
MultiTurnEnabled: true,
HistoryTurns: 5,
KBSelectionMode: "all",
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 10,
RerankThreshold: 0.3,
// Advanced settings
EnableQueryExpansion: true,
EnableRewrite: true,
FallbackStrategy: "model",
},
}
}
// GetBuiltinSmartReasoningAgent returns the built-in smart reasoning (ReAct) mode agent
func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinSmartReasoningID,
Name: "智能推理",
Description: "ReAct 推理框架,支持多步思考和工具调用",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: "",
Temperature: 0.7,
MaxCompletionTokens: 2048,
MaxIterations: 50,
KBSelectionMode: "all",
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
WebSearchEnabled: true,
WebSearchMaxResults: 5,
ReflectionEnabled: false,
MultiTurnEnabled: true,
HistoryTurns: 5,
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 10,
RerankThreshold: 0.3,
},
}
}
// Deprecated: Use GetBuiltinQuickAnswerAgent instead
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
return GetBuiltinQuickAnswerAgent(tenantID)
}
// Deprecated: Use GetBuiltinSmartReasoningAgent instead
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
return GetBuiltinSmartReasoningAgent(tenantID)
}
// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
}
// builtinAgentIDsOrdered defines the fixed display order of built-in agents
var builtinAgentIDsOrdered = []string{
BuiltinQuickAnswerID,
BuiltinSmartReasoningID,
BuiltinDeepResearcherID,
BuiltinDataAnalystID,
BuiltinKnowledgeGraphExpertID,
BuiltinDocumentAssistantID,
}
// GetBuiltinAgentIDs returns all built-in agent IDs in fixed order
func GetBuiltinAgentIDs() []string {
return builtinAgentIDsOrdered
}
// IsBuiltinAgentID checks if the given ID is a built-in agent ID
func IsBuiltinAgentID(id string) bool {
_, exists := BuiltinAgentRegistry[id]
return exists
}
// GetBuiltinAgent returns a built-in agent by ID, or nil if not found
func GetBuiltinAgent(id string, tenantID uint64) *CustomAgent {
if factory, exists := BuiltinAgentRegistry[id]; exists {
return factory(tenantID)
}
return nil
}

View File

@ -18,8 +18,11 @@ type ChunkRepository interface {
ListChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error)
// ListPagedChunksByKnowledgeID lists paged chunks by knowledge id.
// When tagID is non-empty, results are filtered by tag_id.
// sortOrder: "asc" for time ascending (updated_at ASC), default is time descending (updated_at DESC)
// searchField: specifies which field to search in (for FAQ: "standard_question", "similar_questions", "answers", "" for all)
// knowledgeType: "faq" or "manual" - determines sort order and search behavior
// - FAQ: sorts by updated_at, searchField can be "standard_question", "similar_questions", "answers", or "" for all
// - Document (manual): sorts by chunk_index, keyword searches content only
// sortOrder: "asc" for ascending, default is descending
// searchField: specifies which field to search in (only applicable for FAQ type)
ListPagedChunksByKnowledgeID(
ctx context.Context,
tenantID uint64,
@ -30,6 +33,7 @@ type ChunkRepository interface {
keyword string,
searchField string,
sortOrder string,
knowledgeType string,
) ([]*types.Chunk, int64, error)
ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error)
// UpdateChunk updates a chunk

View File

@ -24,6 +24,10 @@ type ContextManager interface {
// GetContextStats returns statistics about the context
GetContextStats(ctx context.Context, sessionID string) (*ContextStats, error)
// SetSystemPrompt sets or updates the system prompt for a session
// If a system message exists, it will be replaced; otherwise, a new one will be added at the beginning
SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error
}
// ContextStats contains statistics about session context

View File

@ -0,0 +1,112 @@
// Package interfaces defines the interface contracts for custom agent management
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// CustomAgentService defines the custom agent service interface
// Provides high-level operations for agent creation, querying, updating, and deletion
type CustomAgentService interface {
// CreateAgent creates a new custom agent
// Parameters:
// - ctx: Context information, carrying request tracking, user identity, etc.
// - agent: Agent object containing basic information and configuration
// Returns:
// - Created agent object (including automatically generated ID)
// - Possible errors such as insufficient permissions, validation errors, etc.
CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error)
// GetAgentByID retrieves agent information by ID
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the agent
// Returns:
// - Agent object, if found (including built-in agents)
// - Possible errors such as not existing, insufficient permissions, etc.
GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error)
// ListAgents lists all agents under the current tenant (including built-in agents)
// Parameters:
// - ctx: Context information, containing tenant information
// Returns:
// - List of agent objects (built-in agents first, then custom agents sorted by creation time)
// - Possible errors such as insufficient permissions, etc.
ListAgents(ctx context.Context) ([]*types.CustomAgent, error)
// UpdateAgent updates agent information
// Parameters:
// - ctx: Context information
// - agent: Agent object containing update information
// Returns:
// - Updated agent object
// - Possible errors such as not existing, insufficient permissions, cannot modify built-in, etc.
UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error)
// DeleteAgent deletes an agent
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the agent
// Returns:
// - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc.
DeleteAgent(ctx context.Context, id string) error
// CopyAgent creates a copy of an existing agent
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the agent to copy
// Returns:
// - The newly created agent copy
// - Possible errors such as not existing, insufficient permissions, etc.
CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error)
}
// CustomAgentRepository defines the custom agent repository interface
// Responsible for agent data persistence and retrieval
type CustomAgentRepository interface {
// CreateAgent creates an agent record
// Parameters:
// - ctx: Context information
// - agent: Agent object
// Returns:
// - Possible errors such as database connection failure, unique constraint conflicts, etc.
CreateAgent(ctx context.Context, agent *types.CustomAgent) error
// GetAgentByID queries an agent by ID 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, tenantID uint64) (*types.CustomAgent, error)
// ListAgentsByTenantID lists all agents for a specific tenant
// Parameters:
// - ctx: Context information
// - tenantID: Tenant ID
// Returns:
// - List of agent objects
// - Possible errors such as database errors, etc.
ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error)
// UpdateAgent updates an agent record
// Parameters:
// - ctx: Context information
// - agent: Agent object containing update information
// Returns:
// - Possible errors such as record not existing, database errors, etc.
UpdateAgent(ctx context.Context, agent *types.CustomAgent) error
// DeleteAgent deletes an agent record
// Parameters:
// - ctx: Context information
// - id: Agent ID
// - tenantID: Tenant ID for isolation (required for composite primary key)
// Returns:
// - Possible errors such as record not existing, database errors, etc.
DeleteAgent(ctx context.Context, id string, tenantID uint64) error
}

View File

@ -22,19 +22,23 @@ type SessionService interface {
// DeleteSession deletes a session
DeleteSession(ctx context.Context, id string) error
// GenerateTitle generates a title for the current conversation
GenerateTitle(ctx context.Context, session *types.Session, messages []types.Message) (string, error)
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
GenerateTitle(ctx context.Context, session *types.Session, messages []types.Message, modelID string) (string, error)
// GenerateTitleAsync generates a title for the session asynchronously
// It emits an event when the title is generated
GenerateTitleAsync(ctx context.Context, session *types.Session, userQuery string, eventBus *event.EventBus)
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
GenerateTitleAsync(ctx context.Context, session *types.Session, userQuery string, modelID string, eventBus *event.EventBus)
// KnowledgeQA performs knowledge-based question answering
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
// knowledgeIDs: list of specific knowledge (file) IDs to search
// summaryModelID: optional summary model ID override (if empty, uses session/KB default)
// webSearchEnabled: whether to enable web search to supplement knowledge base results
// customAgent: optional custom agent for config override (multiTurnEnabled, historyTurns)
// Events are emitted through eventBus (references, answer chunks, completion)
KnowledgeQA(ctx context.Context,
session *types.Session, query string, knowledgeBaseIDs []string, knowledgeIDs []string,
assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus,
customAgent *types.CustomAgent,
) error
// KnowledgeQAByEvent performs knowledge-based question answering by event
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
@ -44,12 +48,16 @@ type SessionService interface {
SearchKnowledge(ctx context.Context, knowledgeBaseIDs []string, knowledgeIDs []string, query string) ([]*types.SearchResult, error)
// AgentQA performs agent-based question answering with conversation history and streaming support
// eventBus is optional - if nil, uses service's default EventBus
// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults
AgentQA(
ctx context.Context,
session *types.Session,
query string,
assistantMessageID string,
eventBus *event.EventBus,
customAgent *types.CustomAgent,
knowledgeBaseIDs []string,
knowledgeIDs []string,
) error
// ClearContext clears the LLM context for a session
ClearContext(ctx context.Context, sessionID string) error

View File

@ -0,0 +1,165 @@
package types
// PromptPlaceholder represents a placeholder that can be used in prompt templates
type PromptPlaceholder struct {
// Name is the placeholder name (without braces), e.g., "query"
Name string `json:"name"`
// Label is a short label for the placeholder
Label string `json:"label"`
// Description explains what this placeholder represents
Description string `json:"description"`
}
// PromptFieldType represents the type of prompt field
type PromptFieldType string
const (
// PromptFieldSystemPrompt is for system prompts (normal mode)
PromptFieldSystemPrompt PromptFieldType = "system_prompt"
// PromptFieldAgentSystemPrompt is for agent mode system prompts
PromptFieldAgentSystemPrompt PromptFieldType = "agent_system_prompt"
// PromptFieldContextTemplate is for context templates
PromptFieldContextTemplate PromptFieldType = "context_template"
// PromptFieldRewriteSystemPrompt is for rewrite system prompts
PromptFieldRewriteSystemPrompt PromptFieldType = "rewrite_system_prompt"
// PromptFieldRewritePrompt is for rewrite user prompts
PromptFieldRewritePrompt PromptFieldType = "rewrite_prompt"
// PromptFieldFallbackPrompt is for fallback prompts
PromptFieldFallbackPrompt PromptFieldType = "fallback_prompt"
)
// All available placeholders in the system
var (
// Common placeholders
PlaceholderQuery = PromptPlaceholder{
Name: "query",
Label: "用户问题",
Description: "用户当前的问题或查询内容",
}
PlaceholderContexts = PromptPlaceholder{
Name: "contexts",
Label: "检索内容",
Description: "从知识库检索到的相关内容列表",
}
PlaceholderCurrentTime = PromptPlaceholder{
Name: "current_time",
Label: "当前时间",
Description: "当前系统时间(格式:2006-01-02 15:04:05)",
}
PlaceholderCurrentWeek = PromptPlaceholder{
Name: "current_week",
Label: "当前星期",
Description: "当前星期几(如:星期一、Monday)",
}
// Rewrite prompt placeholders
PlaceholderConversation = PromptPlaceholder{
Name: "conversation",
Label: "历史对话",
Description: "格式化的历史对话内容,用于多轮对话改写",
}
PlaceholderYesterday = PromptPlaceholder{
Name: "yesterday",
Label: "昨天日期",
Description: "昨天的日期(格式:2006-01-02)",
}
PlaceholderAnswer = PromptPlaceholder{
Name: "answer",
Label: "助手回答",
Description: "助手的回答内容(用于对话历史格式化)",
}
// Agent mode specific placeholders
PlaceholderKnowledgeBases = PromptPlaceholder{
Name: "knowledge_bases",
Label: "知识库列表",
Description: "自动格式化的知识库列表,包含名称、描述、文档数量等信息",
}
PlaceholderWebSearchStatus = PromptPlaceholder{
Name: "web_search_status",
Label: "网络搜索状态",
Description: "网络搜索工具是否启用的状态(Enabled 或 Disabled)",
}
)
// PlaceholdersByField returns the available placeholders for a specific prompt field type
func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
switch fieldType {
case PromptFieldSystemPrompt:
// Normal mode system prompt
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
}
case PromptFieldAgentSystemPrompt:
// Agent mode system prompt
return []PromptPlaceholder{
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
PlaceholderCurrentTime,
}
case PromptFieldContextTemplate:
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
}
case PromptFieldRewriteSystemPrompt:
// Rewrite system prompt supports same placeholders as rewrite user prompt
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
}
case PromptFieldRewritePrompt:
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
}
case PromptFieldFallbackPrompt:
return []PromptPlaceholder{
PlaceholderQuery,
}
default:
return []PromptPlaceholder{}
}
}
// AllPlaceholders returns all available placeholders in the system
func AllPlaceholders() []PromptPlaceholder {
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
PlaceholderConversation,
PlaceholderYesterday,
PlaceholderAnswer,
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
}
}
// PlaceholderMap returns a map of field types to their available placeholders
func PlaceholderMap() map[PromptFieldType][]PromptPlaceholder {
return map[PromptFieldType][]PromptPlaceholder{
PromptFieldSystemPrompt: PlaceholdersByField(PromptFieldSystemPrompt),
PromptFieldAgentSystemPrompt: PlaceholdersByField(PromptFieldAgentSystemPrompt),
PromptFieldContextTemplate: PlaceholdersByField(PromptFieldContextTemplate),
PromptFieldRewriteSystemPrompt: PlaceholdersByField(PromptFieldRewriteSystemPrompt),
PromptFieldRewritePrompt: PlaceholdersByField(PromptFieldRewritePrompt),
PromptFieldFallbackPrompt: PlaceholdersByField(PromptFieldFallbackPrompt),
}
}

View File

@ -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"`

View File

@ -69,13 +69,15 @@ type Tenant struct {
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// Global Agent configuration for this tenant (default for all sessions)
// Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.
// This field is kept for backward compatibility and will be removed in future versions.
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`
// Global Context configuration for this tenant (default for all sessions)
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
// Global WebSearch configuration for this tenant
WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`
// Global Conversation configuration for this tenant (default for normal mode sessions)
// Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.
// This field is kept for backward compatibility and will be removed in future versions.
ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
@ -126,9 +128,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

View File

@ -0,0 +1,18 @@
-- Migration: 000006_custom_agents (rollback)
-- Description: Remove custom agents table and related changes
DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Starting custom agents rollback...'; END $$;
-- Remove agent_id column from sessions table
DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Removing agent_id column from sessions table'; END $$;
DROP INDEX IF EXISTS idx_sessions_agent_id;
ALTER TABLE sessions DROP COLUMN IF EXISTS agent_id;
-- Drop custom_agents table (includes built-in agents created during migration)
DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Dropping table: custom_agents'; END $$;
DROP INDEX IF EXISTS idx_custom_agents_tenant_id;
DROP INDEX IF EXISTS idx_custom_agents_is_builtin;
DROP INDEX IF EXISTS idx_custom_agents_deleted_at;
DROP TABLE IF EXISTS custom_agents;
DO $$ BEGIN RAISE NOTICE '[Migration 000006 DOWN] Custom agents rollback completed!'; END $$;

View File

@ -0,0 +1,176 @@
-- Migration: 000006_custom_agents
-- Description: Add custom agents table for GPTs-like agent configuration and migrate tenant config to built-in agents
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Starting custom agents setup...'; END $$;
-- Create custom_agents table with composite primary key (id, tenant_id)
-- This allows the same agent ID to exist for different tenants (e.g., 'builtin-normal' for each tenant)
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Creating table: custom_agents'; END $$;
CREATE TABLE IF NOT EXISTS custom_agents (
id VARCHAR(36) NOT NULL DEFAULT uuid_generate_v4(),
name VARCHAR(255) NOT NULL,
description TEXT,
avatar VARCHAR(64),
is_builtin BOOLEAN NOT NULL DEFAULT false,
tenant_id INTEGER NOT NULL,
created_by VARCHAR(36),
config JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
deleted_at TIMESTAMP WITH TIME ZONE,
PRIMARY KEY (id, tenant_id)
);
-- Add indexes for custom_agents
CREATE INDEX IF NOT EXISTS idx_custom_agents_tenant_id ON custom_agents(tenant_id);
CREATE INDEX IF NOT EXISTS idx_custom_agents_is_builtin ON custom_agents(is_builtin);
CREATE INDEX IF NOT EXISTS idx_custom_agents_deleted_at ON custom_agents(deleted_at);
-- Add agent_id column to sessions table to track which agent was used
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Adding agent_id column to sessions table'; END $$;
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS agent_id VARCHAR(36);
CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id);
-- Helper function to unify prompt placeholders from Go template format to simple format
CREATE OR REPLACE FUNCTION unify_prompt_placeholder(input TEXT) RETURNS TEXT AS $$
DECLARE
result TEXT := COALESCE(input, '');
replacements TEXT[][] := ARRAY[
-- Go template variables -> simple placeholders
['{{.Query}}', '{{query}}'],
['{{.Answer}}', '{{answer}}'],
['{{.CurrentTime}}', '{{current_time}}'],
['{{.CurrentWeek}}', '{{current_week}}'],
['{{.Yesterday}}', '{{yesterday}}'],
['{{.Contexts}}', '{{contexts}}'],
-- Go template control structures -> simple placeholders or remove
['{{range .Contexts}}', '{{contexts}}'],
-- Remove Go template syntax
['{{if .Contexts}}', ''],
['{{else}}', ''],
['{{.}}', '']
];
r TEXT[];
BEGIN
FOREACH r SLICE 1 IN ARRAY replacements LOOP
result := REPLACE(result, r[1], r[2]);
END LOOP;
-- Handle {{range .Conversation}}...{{end}} block specially
-- Replace the entire block with just {{conversation}}
-- The pattern matches: {{range .Conversation}} followed by any content until {{end}}
result := regexp_replace(
result,
'\{\{range \.Conversation\}\}[\s\S]*?\{\{end\}\}',
'{{conversation}}',
'g'
);
-- Clean up any remaining {{end}} tags
result := REPLACE(result, '{{end}}', '');
RETURN result;
END;
$$ LANGUAGE plpgsql;
-- Migrate tenant AgentConfig and ConversationConfig to built-in custom agents
DO $$ BEGIN RAISE NOTICE '[Migration 000006] Migrating tenant config to built-in agents...'; END $$;
-- Insert builtin-quick-answer agent for tenants with ConversationConfig
INSERT INTO custom_agents (id, name, description, avatar, is_builtin, tenant_id, config, created_at, updated_at)
SELECT
'builtin-quick-answer',
'快速问答',
'基于知识库的 RAG 问答,快速准确地回答问题',
'💬',
true,
t.id,
jsonb_build_object(
'agent_mode', 'quick-answer',
'system_prompt', unify_prompt_placeholder(t.conversation_config->>'prompt'),
'context_template', unify_prompt_placeholder(t.conversation_config->>'context_template'),
'model_id', COALESCE(t.conversation_config->>'summary_model_id', ''),
'rerank_model_id', COALESCE(t.conversation_config->>'rerank_model_id', ''),
'temperature', COALESCE((t.conversation_config->>'temperature')::float, 0.7),
'max_completion_tokens', COALESCE((t.conversation_config->>'max_completion_tokens')::int, 2048),
'max_iterations', 10,
'allowed_tools', '[]'::jsonb,
'reflection_enabled', false,
'kb_selection_mode', 'all',
'knowledge_bases', '[]'::jsonb,
'web_search_enabled', false,
'web_search_max_results', COALESCE((t.web_search_config->>'max_results')::int, 5),
'multi_turn_enabled', COALESCE((t.conversation_config->>'multi_turn_enabled')::bool, true),
'history_turns', COALESCE((t.conversation_config->>'max_rounds')::int, 5),
'embedding_top_k', COALESCE((t.conversation_config->>'embedding_top_k')::int, 10),
'keyword_threshold', COALESCE((t.conversation_config->>'keyword_threshold')::float, 0.3),
'vector_threshold', COALESCE((t.conversation_config->>'vector_threshold')::float, 0.5),
'rerank_top_k', COALESCE((t.conversation_config->>'rerank_top_k')::int, 5),
'rerank_threshold', COALESCE((t.conversation_config->>'rerank_threshold')::float, 0.5),
'enable_query_expansion', COALESCE((t.conversation_config->>'enable_query_expansion')::bool, true),
'enable_rewrite', COALESCE((t.conversation_config->>'enable_rewrite')::bool, true),
'rewrite_prompt_system', unify_prompt_placeholder(t.conversation_config->>'rewrite_prompt_system'),
'rewrite_prompt_user', unify_prompt_placeholder(t.conversation_config->>'rewrite_prompt_user'),
'fallback_strategy', COALESCE(t.conversation_config->>'fallback_strategy', 'model'),
'fallback_response', unify_prompt_placeholder(t.conversation_config->>'fallback_response'),
'fallback_prompt', unify_prompt_placeholder(t.conversation_config->>'fallback_prompt')
),
NOW(),
NOW()
FROM tenants t
WHERE t.conversation_config IS NOT NULL
AND t.deleted_at IS NULL
ON CONFLICT (id, tenant_id) DO UPDATE SET
config = EXCLUDED.config,
updated_at = NOW();
-- Insert builtin-smart-reasoning agent for tenants with AgentConfig
INSERT INTO custom_agents (id, name, description, avatar, is_builtin, tenant_id, config, created_at, updated_at)
SELECT
'builtin-smart-reasoning',
'智能推理',
'ReAct 推理框架,支持多步思考和工具调用',
'🤖',
true,
t.id,
jsonb_build_object(
'agent_mode', 'smart-reasoning',
'system_prompt', unify_prompt_placeholder(t.agent_config->>'system_prompt_web_disabled'),
'system_prompt_web_enabled', unify_prompt_placeholder(t.agent_config->>'system_prompt_web_enabled'),
'context_template', '',
'model_id', COALESCE(t.conversation_config->>'summary_model_id', ''),
'rerank_model_id', COALESCE(t.conversation_config->>'rerank_model_id', ''),
'temperature', COALESCE((t.agent_config->>'temperature')::float, 0.7),
'max_completion_tokens', 2048,
'max_iterations', COALESCE((t.agent_config->>'max_iterations')::int, 50),
'allowed_tools', COALESCE(t.agent_config->'allowed_tools', '["thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"]'::jsonb),
'reflection_enabled', COALESCE((t.agent_config->>'reflection_enabled')::bool, false),
'mcp_selection_mode', 'all',
'mcp_services', '[]'::jsonb,
'kb_selection_mode', 'all',
'knowledge_bases', COALESCE(t.agent_config->'knowledge_bases', '[]'::jsonb),
'web_search_enabled', COALESCE((t.agent_config->>'web_search_enabled')::bool, true),
'web_search_max_results', COALESCE((t.agent_config->>'web_search_max_results')::int, COALESCE((t.web_search_config->>'max_results')::int, 5)),
'multi_turn_enabled', COALESCE((t.agent_config->>'multi_turn_enabled')::bool, true),
'history_turns', COALESCE((t.agent_config->>'history_turns')::int, 5),
'embedding_top_k', 10,
'keyword_threshold', 0.3,
'vector_threshold', 0.5,
'rerank_top_k', 5,
'rerank_threshold', 0.5,
'enable_query_expansion', false,
'enable_rewrite', false,
'rewrite_prompt_system', '',
'rewrite_prompt_user', '',
'fallback_strategy', 'model',
'fallback_response', '',
'fallback_prompt', ''
),
NOW(),
NOW()
FROM tenants t
WHERE t.agent_config IS NOT NULL
AND t.deleted_at IS NULL
ON CONFLICT (id, tenant_id) DO UPDATE SET
config = EXCLUDED.config,
updated_at = NOW();