feat: Introduce conversation configuration management and localization updates
- Added new ConversationConfig interface and API endpoints for retrieving and updating conversation settings. - Enhanced AgentSettings.vue to include UI for configuring conversation parameters such as prompt, context template, temperature, and max tokens. - Updated localization files in English and Chinese to include new strings for conversation settings. - Implemented logic to load and save conversation configuration for tenants, ensuring defaults are applied when no specific configuration exists.
This commit is contained in:
@@ -38,6 +38,13 @@ export interface AgentConfig {
|
||||
available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要
|
||||
}
|
||||
|
||||
export interface ConversationConfig {
|
||||
prompt: string
|
||||
context_template: string
|
||||
temperature: number
|
||||
max_tokens: number
|
||||
}
|
||||
|
||||
export function getSystemInfo(): Promise<{ data: SystemInfo }> {
|
||||
return get('/api/v1/system/info')
|
||||
}
|
||||
@@ -49,3 +56,11 @@ export function getAgentConfig(): Promise<{ data: AgentConfig }> {
|
||||
export function updateAgentConfig(config: AgentConfig): Promise<{ data: AgentConfig }> {
|
||||
return put('/api/v1/tenants/kv/agent-config', config)
|
||||
}
|
||||
|
||||
export function getConversationConfig(): Promise<{ data: ConversationConfig }> {
|
||||
return get('/api/v1/tenants/kv/conversation-config')
|
||||
}
|
||||
|
||||
export function updateConversationConfig(config: ConversationConfig): Promise<{ data: ConversationConfig }> {
|
||||
return put('/api/v1/tenants/kv/conversation-config', config)
|
||||
}
|
||||
|
||||
@@ -132,6 +132,7 @@ export default {
|
||||
title: 'Settings',
|
||||
modelConfig: 'Model Settings',
|
||||
agentConfig: 'Agent Settings',
|
||||
conversationConfig: 'Conversation Settings',
|
||||
webSearchConfig: 'Web Search',
|
||||
mcpService: 'MCP Service',
|
||||
systemSettings: 'System Settings',
|
||||
@@ -1333,6 +1334,35 @@ export default {
|
||||
autoDisabled: 'Agent configuration incomplete. Agent mode has been disabled automatically'
|
||||
}
|
||||
},
|
||||
conversationSettings: {
|
||||
description: 'Configure default behavior and parameters for conversation modes, including Prompt settings for Agent mode and normal mode',
|
||||
agentMode: 'Agent Mode',
|
||||
normalMode: 'Normal Mode',
|
||||
contextTemplate: {
|
||||
label: 'Retrieval Result Summary Prompt',
|
||||
desc: 'Prompt template for generating answers based on retrieval results in normal mode',
|
||||
placeholder: 'Enter the prompt template for retrieval result summary...'
|
||||
},
|
||||
systemPrompt: {
|
||||
label: 'System Prompt',
|
||||
desc: 'System-level prompt for normal mode conversations',
|
||||
placeholder: 'Enter the system prompt...'
|
||||
},
|
||||
temperature: {
|
||||
label: 'Temperature',
|
||||
desc: 'Controls randomness in outputs. 0 is most deterministic; 1 is most random'
|
||||
},
|
||||
maxTokens: {
|
||||
label: 'Max Tokens',
|
||||
desc: 'Maximum number of tokens to generate in the response'
|
||||
},
|
||||
toasts: {
|
||||
contextTemplateSaved: 'Retrieval result summary prompt saved',
|
||||
systemPromptSaved: 'System prompt saved',
|
||||
temperatureSaved: 'Temperature saved',
|
||||
maxTokensSaved: 'Max tokens saved'
|
||||
}
|
||||
},
|
||||
// New: MCP Settings
|
||||
mcpSettings: {
|
||||
title: 'MCP Services',
|
||||
|
||||
@@ -223,6 +223,7 @@ export default {
|
||||
title: "设置",
|
||||
modelConfig: "模型配置",
|
||||
agentConfig: "Agent配置",
|
||||
conversationConfig: "对话设置",
|
||||
webSearchConfig: "网络搜索",
|
||||
mcpService: "MCP服务",
|
||||
systemSettings: "系统设置",
|
||||
@@ -1337,6 +1338,35 @@ export default {
|
||||
autoDisabled: "Agent 配置不完整,已自动关闭 Agent 模式",
|
||||
},
|
||||
},
|
||||
conversationSettings: {
|
||||
description: "配置对话模式的默认行为和参数,包括Agent模式和普通模式的Prompt设置",
|
||||
agentMode: "Agent模式",
|
||||
normalMode: "普通模式",
|
||||
contextTemplate: {
|
||||
label: "总结Prompt",
|
||||
desc: "用于普通模式下基于检索结果生成回答的Prompt模板",
|
||||
placeholder: "请输入检索结果总结的Prompt模板...",
|
||||
},
|
||||
systemPrompt: {
|
||||
label: "系统Prompt",
|
||||
desc: "用于普通模式对话的系统级Prompt",
|
||||
placeholder: "请输入系统Prompt...",
|
||||
},
|
||||
temperature: {
|
||||
label: "温度参数",
|
||||
desc: "控制模型输出的随机性,0最确定,1最随机",
|
||||
},
|
||||
maxTokens: {
|
||||
label: "最大Token数",
|
||||
desc: "生成回答的最大Token数量",
|
||||
},
|
||||
toasts: {
|
||||
contextTemplateSaved: "总结Prompt已保存",
|
||||
systemPromptSaved: "系统Prompt已保存",
|
||||
temperatureSaved: "温度参数已保存",
|
||||
maxTokensSaved: "最大Token数已保存",
|
||||
},
|
||||
},
|
||||
// 新增:MCP 设置
|
||||
mcpSettings: {
|
||||
title: "MCP 服务管理",
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
<template>
|
||||
<div class="agent-settings">
|
||||
<div class="section-header">
|
||||
<h2>{{ $t('agentSettings.title') }}</h2>
|
||||
<p class="section-description">{{ $t('agentSettings.description') }}</p>
|
||||
|
||||
<!-- Agent 状态显示 -->
|
||||
<div class="agent-status-row">
|
||||
<h2>{{ $t('settings.conversationConfig') }}</h2>
|
||||
<p class="section-description">{{ $t('conversationSettings.description') }}</p>
|
||||
</div>
|
||||
|
||||
<t-tabs v-model="activeTab" class="conversation-tabs">
|
||||
<!-- Agent 模式设置 Tab -->
|
||||
<t-tab-panel value="agent" :label="$t('conversationSettings.agentMode')">
|
||||
<div class="tab-content">
|
||||
<!-- Agent 状态显示 -->
|
||||
<div class="agent-status-row">
|
||||
<div class="status-label">
|
||||
<label>{{ $t('agentSettings.status.label') }}</label>
|
||||
</div>
|
||||
@@ -34,9 +39,8 @@
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="settings-group">
|
||||
|
||||
<!-- 最大迭代次数 -->
|
||||
<div class="setting-row">
|
||||
@@ -270,7 +274,91 @@
|
||||
</teleport>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</t-tab-panel>
|
||||
|
||||
<!-- 普通模式设置 Tab -->
|
||||
<t-tab-panel value="normal" :label="$t('conversationSettings.normalMode')">
|
||||
<div class="tab-content">
|
||||
<div class="settings-group">
|
||||
<!-- System Prompt -->
|
||||
<div class="setting-row vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('conversationSettings.systemPrompt.label') }}</label>
|
||||
<p class="desc">{{ $t('conversationSettings.systemPrompt.desc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control full-width">
|
||||
<t-textarea
|
||||
v-model="localSystemPromptNormal"
|
||||
:autosize="{ minRows: 10, maxRows: 20 }"
|
||||
:placeholder="$t('conversationSettings.systemPrompt.placeholder')"
|
||||
@blur="handleSystemPromptNormalChange"
|
||||
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 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>
|
||||
</div>
|
||||
<div class="setting-control full-width">
|
||||
<t-textarea
|
||||
v-model="localContextTemplate"
|
||||
:autosize="{ minRows: 15, maxRows: 30 }"
|
||||
:placeholder="$t('conversationSettings.contextTemplate.placeholder')"
|
||||
@blur="handleContextTemplateChange"
|
||||
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Temperature -->
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('conversationSettings.temperature.label') }}</label>
|
||||
<p class="desc">{{ $t('conversationSettings.temperature.desc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="slider-with-value">
|
||||
<t-slider
|
||||
v-model="localTemperatureNormal"
|
||||
:min="0"
|
||||
:max="1"
|
||||
:step="0.1"
|
||||
:marks="{ 0: '0', 0.5: '0.5', 1: '1' }"
|
||||
@change="handleTemperatureNormalChange"
|
||||
style="width: 200px;"
|
||||
/>
|
||||
<span class="value-display">{{ localTemperatureNormal.toFixed(1) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Max Tokens -->
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('conversationSettings.maxTokens.label') }}</label>
|
||||
<p class="desc">{{ $t('conversationSettings.maxTokens.desc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input-number
|
||||
v-model="localMaxTokens"
|
||||
:min="1"
|
||||
:max="100000"
|
||||
:step="100"
|
||||
@change="handleMaxTokensChange"
|
||||
style="width: 200px;"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</t-tab-panel>
|
||||
</t-tabs>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -281,13 +369,16 @@ import { useSettingsStore } from '@/stores/settings'
|
||||
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { listModels, type ModelConfig } from '@/api/model'
|
||||
import { getAgentConfig, updateAgentConfig, type AgentConfig, type ToolDefinition, type PlaceholderDefinition } from '@/api/system'
|
||||
import { getAgentConfig, updateAgentConfig, getConversationConfig, updateConversationConfig, type AgentConfig, type ConversationConfig, type ToolDefinition, type PlaceholderDefinition } from '@/api/system'
|
||||
|
||||
const settingsStore = useSettingsStore()
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
|
||||
// 本地状态
|
||||
// Tab 状态
|
||||
const activeTab = ref('agent')
|
||||
|
||||
// Agent 模式本地状态
|
||||
const localMaxIterations = ref(5)
|
||||
const localTemperature = ref(0.7)
|
||||
const localThinkingModelId = ref('')
|
||||
@@ -296,6 +387,17 @@ const localAllowedTools = ref<string[]>([])
|
||||
const localSystemPrompt = ref('')
|
||||
const localUseCustomSystemPrompt = ref(false)
|
||||
|
||||
// 普通模式本地状态
|
||||
const localContextTemplate = ref('')
|
||||
const localSystemPromptNormal = ref('')
|
||||
const localTemperatureNormal = ref(0.3)
|
||||
const localMaxTokens = ref(2048)
|
||||
const conversationConfigLoaded = ref(false)
|
||||
let savedContextTemplate = ''
|
||||
let savedSystemPromptNormal = ''
|
||||
let savedTemperatureNormal = 0.3
|
||||
let savedMaxTokens = 2048
|
||||
|
||||
// 计算 Agent 是否就绪
|
||||
const isAgentReady = computed(() => {
|
||||
// 必须有思考模型、Rerank 模型 且 至少选择一个工具
|
||||
@@ -496,6 +598,29 @@ onMounted(async () => {
|
||||
rerankModelId: config.rerank_model_id,
|
||||
allowedTools: config.allowed_tools || []
|
||||
})
|
||||
|
||||
// 加载普通模式配置
|
||||
if (!conversationConfigLoaded.value) {
|
||||
try {
|
||||
const convRes = await getConversationConfig()
|
||||
const convConfig = convRes.data
|
||||
|
||||
localContextTemplate.value = convConfig.context_template || ''
|
||||
savedContextTemplate = convConfig.context_template || ''
|
||||
localSystemPromptNormal.value = convConfig.prompt || ''
|
||||
savedSystemPromptNormal = convConfig.prompt || ''
|
||||
localTemperatureNormal.value = convConfig.temperature || 0.3
|
||||
savedTemperatureNormal = convConfig.temperature || 0.3
|
||||
localMaxTokens.value = convConfig.max_tokens || 2048
|
||||
savedMaxTokens = convConfig.max_tokens || 2048
|
||||
|
||||
conversationConfigLoaded.value = true
|
||||
} catch (error) {
|
||||
console.error('加载普通模式配置失败:', error)
|
||||
// 使用默认值
|
||||
conversationConfigLoaded.value = true
|
||||
}
|
||||
}
|
||||
|
||||
// 等待下一个 tick,确保所有响应式更新完成
|
||||
await nextTick()
|
||||
@@ -1145,6 +1270,95 @@ watch(isAgentReady, (newValue, oldValue) => {
|
||||
// 注意:配置从"未就绪"变为"就绪"时,不自动启用(让用户自己决定是否启用)
|
||||
}
|
||||
})
|
||||
|
||||
// 普通模式配置处理函数
|
||||
const handleContextTemplateChange = async () => {
|
||||
if (!conversationConfigLoaded.value) return
|
||||
|
||||
if (localContextTemplate.value === savedContextTemplate) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const config: ConversationConfig = {
|
||||
prompt: localSystemPromptNormal.value,
|
||||
context_template: localContextTemplate.value,
|
||||
temperature: localTemperatureNormal.value,
|
||||
max_tokens: localMaxTokens.value
|
||||
}
|
||||
|
||||
await updateConversationConfig(config)
|
||||
savedContextTemplate = localContextTemplate.value
|
||||
MessagePlugin.success(t('conversationSettings.toasts.contextTemplateSaved'))
|
||||
} catch (error) {
|
||||
console.error('保存Context Template失败:', error)
|
||||
MessagePlugin.error(getErrorMessage(error))
|
||||
}
|
||||
}
|
||||
|
||||
const handleSystemPromptNormalChange = async () => {
|
||||
if (!conversationConfigLoaded.value) return
|
||||
|
||||
if (localSystemPromptNormal.value === savedSystemPromptNormal) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const config: ConversationConfig = {
|
||||
prompt: localSystemPromptNormal.value,
|
||||
context_template: localContextTemplate.value,
|
||||
temperature: localTemperatureNormal.value,
|
||||
max_tokens: localMaxTokens.value
|
||||
}
|
||||
|
||||
await updateConversationConfig(config)
|
||||
savedSystemPromptNormal = localSystemPromptNormal.value
|
||||
MessagePlugin.success(t('conversationSettings.toasts.systemPromptSaved'))
|
||||
} catch (error) {
|
||||
console.error('保存System Prompt失败:', error)
|
||||
MessagePlugin.error(getErrorMessage(error))
|
||||
}
|
||||
}
|
||||
|
||||
const handleTemperatureNormalChange = async (value: number) => {
|
||||
if (!conversationConfigLoaded.value) return
|
||||
|
||||
try {
|
||||
const config: ConversationConfig = {
|
||||
prompt: localSystemPromptNormal.value,
|
||||
context_template: localContextTemplate.value,
|
||||
temperature: value,
|
||||
max_tokens: localMaxTokens.value
|
||||
}
|
||||
|
||||
await updateConversationConfig(config)
|
||||
savedTemperatureNormal = value
|
||||
MessagePlugin.success(t('conversationSettings.toasts.temperatureSaved'))
|
||||
} catch (error) {
|
||||
console.error('保存Temperature失败:', error)
|
||||
MessagePlugin.error(getErrorMessage(error))
|
||||
}
|
||||
}
|
||||
|
||||
const handleMaxTokensChange = async (value: number) => {
|
||||
if (!conversationConfigLoaded.value) return
|
||||
|
||||
try {
|
||||
const config: ConversationConfig = {
|
||||
prompt: localSystemPromptNormal.value,
|
||||
context_template: localContextTemplate.value,
|
||||
temperature: localTemperatureNormal.value,
|
||||
max_tokens: value
|
||||
}
|
||||
|
||||
await updateConversationConfig(config)
|
||||
savedMaxTokens = value
|
||||
MessagePlugin.success(t('conversationSettings.toasts.maxTokensSaved'))
|
||||
} catch (error) {
|
||||
console.error('保存Max Tokens失败:', error)
|
||||
MessagePlugin.error(getErrorMessage(error))
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@@ -1152,8 +1366,8 @@ watch(isAgentReady, (newValue, oldValue) => {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 32px;
|
||||
|
||||
h2 {
|
||||
font-size: 20px;
|
||||
@@ -1168,97 +1382,97 @@ watch(isAgentReady, (newValue, oldValue) => {
|
||||
margin: 0 0 20px 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.agent-status-row {
|
||||
.agent-status-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 20px 0;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
margin-top: 8px;
|
||||
|
||||
.status-label {
|
||||
flex: 1;
|
||||
max-width: 65%;
|
||||
padding-right: 24px;
|
||||
|
||||
label {
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
color: #333333;
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.status-control {
|
||||
flex-shrink: 0;
|
||||
min-width: 280px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 20px 0;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
margin-top: 8px;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
|
||||
.status-label {
|
||||
flex: 1;
|
||||
max-width: 65%;
|
||||
padding-right: 24px;
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 12px;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
|
||||
label {
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
color: #333333;
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
&.ready {
|
||||
background: #f0fdf4;
|
||||
color: #16a34a;
|
||||
|
||||
.status-icon {
|
||||
color: #16a34a;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
&:not(.ready) {
|
||||
background: #fff7ed;
|
||||
color: #ea580c;
|
||||
|
||||
.status-icon {
|
||||
color: #ea580c;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.status-text {
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.status-control {
|
||||
flex-shrink: 0;
|
||||
min-width: 280px;
|
||||
.status-hint {
|
||||
font-size: 13px;
|
||||
color: #666666;
|
||||
text-align: right;
|
||||
line-height: 1.5;
|
||||
max-width: 280px;
|
||||
}
|
||||
|
||||
.status-tip {
|
||||
margin: 8px 0 0 0;
|
||||
font-size: 12px;
|
||||
color: #999999;
|
||||
text-align: right;
|
||||
line-height: 1.5;
|
||||
max-width: 280px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
justify-content: flex-end;
|
||||
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 12px;
|
||||
border-radius: 4px;
|
||||
.tip-icon {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
|
||||
&.ready {
|
||||
background: #f0fdf4;
|
||||
color: #16a34a;
|
||||
|
||||
.status-icon {
|
||||
color: #16a34a;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
&:not(.ready) {
|
||||
background: #fff7ed;
|
||||
color: #ea580c;
|
||||
|
||||
.status-icon {
|
||||
color: #ea580c;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.status-text {
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.status-hint {
|
||||
font-size: 13px;
|
||||
color: #666666;
|
||||
text-align: right;
|
||||
line-height: 1.5;
|
||||
max-width: 280px;
|
||||
}
|
||||
|
||||
.status-tip {
|
||||
margin: 8px 0 0 0;
|
||||
font-size: 12px;
|
||||
color: #999999;
|
||||
text-align: right;
|
||||
line-height: 1.5;
|
||||
max-width: 280px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
justify-content: flex-end;
|
||||
|
||||
.tip-icon {
|
||||
font-size: 14px;
|
||||
color: #999999;
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ const navItems = computed(() => [
|
||||
]
|
||||
},
|
||||
{ key: 'ollama', icon: 'server', label: 'Ollama' },
|
||||
{ key: 'agent', icon: 'chat', label: t('settings.agentConfig') },
|
||||
{ key: 'agent', icon: 'chat', label: t('settings.conversationConfig') },
|
||||
{ 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') },
|
||||
|
||||
+62
-21
@@ -43,19 +43,23 @@ func formatDocSummary(summary string, maxLen int) string {
|
||||
|
||||
// RecentDocInfo contains brief information about a recently added document
|
||||
type RecentDocInfo struct {
|
||||
KnowledgeID string
|
||||
Title string
|
||||
Description string
|
||||
FileName string
|
||||
FileSize int64
|
||||
Type string
|
||||
CreatedAt string // Formatted time string
|
||||
KnowledgeID string
|
||||
Title string
|
||||
Description string
|
||||
FileName string
|
||||
FileSize int64
|
||||
Type string
|
||||
CreatedAt string // Formatted time string
|
||||
FAQStandardQuestion string
|
||||
FAQSimilarQuestions []string
|
||||
FAQAnswers []string
|
||||
}
|
||||
|
||||
// KnowledgeBaseInfo contains essential information about a knowledge base for agent prompt
|
||||
type KnowledgeBaseInfo struct {
|
||||
ID string
|
||||
Name string
|
||||
Type string // Knowledge base type: "document" or "faq"
|
||||
Description string
|
||||
DocCount int
|
||||
RecentDocs []RecentDocInfo // Recently added documents (up to 10)
|
||||
@@ -98,30 +102,67 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("\n")
|
||||
for i, kb := range kbInfos {
|
||||
// Display knowledge base name and ID
|
||||
builder.WriteString(fmt.Sprintf("%d. **%s** (knowledge_base_id: `%s`)\n", i+1, kb.Name, kb.ID))
|
||||
|
||||
// Display knowledge base type
|
||||
kbType := kb.Type
|
||||
if kbType == "" {
|
||||
kbType = "document" // Default type
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf(" - Type: %s\n", kbType))
|
||||
|
||||
if kb.Description != "" {
|
||||
builder.WriteString(fmt.Sprintf(" - Description: %s\n", kb.Description))
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf(" - Document count: %d\n", kb.DocCount))
|
||||
|
||||
// Display recent documents if available
|
||||
// For FAQ type knowledge bases, adjust the display format
|
||||
if len(kb.RecentDocs) > 0 {
|
||||
builder.WriteString(" - Recently added documents:\n\n")
|
||||
builder.WriteString(" | # | Document Name | Type | Created At | Knowledge ID | File Size | Summary |\n")
|
||||
builder.WriteString(" |---|---------------|------|------------|--------------|----------|---------|\n")
|
||||
for j, doc := range kb.RecentDocs {
|
||||
if j >= 10 { // Limit to 10 documents
|
||||
break
|
||||
if kbType == "faq" {
|
||||
// FAQ knowledge base: show Q&A pairs in a more compact format
|
||||
builder.WriteString(" - Recent FAQ entries:\n\n")
|
||||
builder.WriteString(" | # | Standard Question | Similar Questions | Answers | Entry ID | Created At |\n")
|
||||
builder.WriteString(" |---|-------------------|-------------------|---------|----------|------------|\n")
|
||||
for j, doc := range kb.RecentDocs {
|
||||
if j >= 10 { // Limit to 10 documents
|
||||
break
|
||||
}
|
||||
question := doc.FAQStandardQuestion
|
||||
if question == "" {
|
||||
question = doc.FileName
|
||||
}
|
||||
similar := "-"
|
||||
if len(doc.FAQSimilarQuestions) > 0 {
|
||||
similar = strings.Join(doc.FAQSimilarQuestions, "; ")
|
||||
}
|
||||
answers := "-"
|
||||
if len(doc.FAQAnswers) > 0 {
|
||||
answers = strings.Join(doc.FAQAnswers, " | ")
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s |\n",
|
||||
j+1, question, similar, answers, doc.KnowledgeID, doc.CreatedAt))
|
||||
}
|
||||
docName := doc.Title
|
||||
if docName == "" {
|
||||
docName = doc.FileName
|
||||
} else {
|
||||
// Document knowledge base: show documents in standard format
|
||||
builder.WriteString(" - Recently added documents:\n\n")
|
||||
builder.WriteString(" | # | Document Name | Type | Created At | Knowledge ID | File Size | Summary |\n")
|
||||
builder.WriteString(" |---|---------------|------|------------|--------------|----------|---------|\n")
|
||||
for j, doc := range kb.RecentDocs {
|
||||
if j >= 10 { // Limit to 10 documents
|
||||
break
|
||||
}
|
||||
docName := doc.Title
|
||||
if docName == "" {
|
||||
docName = doc.FileName
|
||||
}
|
||||
// Format file size
|
||||
fileSize := formatFileSize(doc.FileSize)
|
||||
summary := formatDocSummary(doc.Description, 120)
|
||||
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s | %s |\n",
|
||||
j+1, docName, doc.Type, doc.CreatedAt, doc.KnowledgeID, fileSize, summary))
|
||||
}
|
||||
// Format file size
|
||||
fileSize := formatFileSize(doc.FileSize)
|
||||
summary := formatDocSummary(doc.Description, 120)
|
||||
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s | %s |\n",
|
||||
j+1, docName, doc.Type, doc.CreatedAt, doc.KnowledgeID, fileSize, summary))
|
||||
}
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
@@ -19,14 +19,17 @@ import (
|
||||
// searchResultWithMeta wraps search result with metadata about which query matched it
|
||||
type searchResultWithMeta struct {
|
||||
*types.SearchResult
|
||||
SourceQuery string
|
||||
QueryType string // "vector" or "keyword"
|
||||
SourceQuery string
|
||||
QueryType string // "vector" or "keyword"
|
||||
KnowledgeBaseID string // ID of the knowledge base this result came from
|
||||
KnowledgeBaseType string // Type of the knowledge base (document, faq, etc.)
|
||||
}
|
||||
|
||||
// KnowledgeSearchTool searches knowledge bases with flexible query modes
|
||||
type KnowledgeSearchTool struct {
|
||||
BaseTool
|
||||
knowledgeService interfaces.KnowledgeBaseService
|
||||
chunkService interfaces.ChunkService
|
||||
tenantID uint
|
||||
allowedKBs []string
|
||||
rerankModel rerank.Reranker
|
||||
@@ -36,6 +39,7 @@ type KnowledgeSearchTool struct {
|
||||
// NewKnowledgeSearchTool creates a new knowledge search tool
|
||||
func NewKnowledgeSearchTool(
|
||||
knowledgeService interfaces.KnowledgeBaseService,
|
||||
chunkService interfaces.ChunkService,
|
||||
tenantID uint,
|
||||
allowedKBs []string,
|
||||
rerankModel rerank.Reranker,
|
||||
@@ -110,6 +114,7 @@ func NewKnowledgeSearchTool(
|
||||
return &KnowledgeSearchTool{
|
||||
BaseTool: NewBaseTool("knowledge_search", description),
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
tenantID: tenantID,
|
||||
allowedKBs: allowedKBs,
|
||||
rerankModel: rerankModel,
|
||||
@@ -327,8 +332,10 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
|
||||
// Execute concurrent search
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Starting concurrent search across %d KBs", len(kbIDs))
|
||||
kbTypeMap := t.getKnowledgeBaseTypes(ctx, kbIDs)
|
||||
|
||||
allResults := t.concurrentSearch(ctx, vectorQueries, keywordQueries, kbIDs,
|
||||
topK, vectorThreshold, keywordThreshold)
|
||||
topK, vectorThreshold, keywordThreshold, kbTypeMap)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Concurrent search completed: %d raw results", len(allResults))
|
||||
|
||||
// Filter by knowledge_ids if provided
|
||||
@@ -432,7 +439,7 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
|
||||
// Build output
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Formatting output with %d final results", len(deduplicatedResults))
|
||||
result, err := t.formatOutput(deduplicatedResults, vectorQueries, keywordQueries,
|
||||
result, err := t.formatOutput(ctx, deduplicatedResults, vectorQueries, keywordQueries,
|
||||
kbIDs, len(allResults), vectorThreshold, keywordThreshold, knowledgeIDsFilter, singleQuery)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][KnowledgeSearch] Failed to format output: %v", err)
|
||||
@@ -443,6 +450,30 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// getKnowledgeBaseTypes fetches knowledge base types for the given IDs
|
||||
func (t *KnowledgeSearchTool) getKnowledgeBaseTypes(ctx context.Context, kbIDs []string) map[string]string {
|
||||
kbTypeMap := make(map[string]string, len(kbIDs))
|
||||
|
||||
for _, kbID := range kbIDs {
|
||||
if kbID == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := kbTypeMap[kbID]; exists {
|
||||
continue
|
||||
}
|
||||
|
||||
kb, err := t.knowledgeService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to fetch knowledge base %s info: %v", kbID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
kbTypeMap[kbID] = kb.Type
|
||||
}
|
||||
|
||||
return kbTypeMap
|
||||
}
|
||||
|
||||
// concurrentSearch executes vector and keyword searches concurrently
|
||||
func (t *KnowledgeSearchTool) concurrentSearch(
|
||||
ctx context.Context,
|
||||
@@ -450,6 +481,7 @@ func (t *KnowledgeSearchTool) concurrentSearch(
|
||||
kbsToSearch []string,
|
||||
topK int,
|
||||
vectorThreshold, keywordThreshold float64,
|
||||
kbTypeMap map[string]string,
|
||||
) []*searchResultWithMeta {
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
@@ -461,7 +493,7 @@ func (t *KnowledgeSearchTool) concurrentSearch(
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
results := t.searchWithQueries(ctx, vectorQueries, kbsToSearch, topK,
|
||||
vectorThreshold, 1.0, "vector")
|
||||
vectorThreshold, 1.0, "vector", kbTypeMap)
|
||||
mu.Lock()
|
||||
allResults = append(allResults, results...)
|
||||
mu.Unlock()
|
||||
@@ -474,7 +506,7 @@ func (t *KnowledgeSearchTool) concurrentSearch(
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
results := t.searchWithQueries(ctx, keywordQueries, kbsToSearch, topK,
|
||||
1.0, keywordThreshold, "keyword")
|
||||
1.0, keywordThreshold, "keyword", kbTypeMap)
|
||||
mu.Lock()
|
||||
allResults = append(allResults, results...)
|
||||
mu.Unlock()
|
||||
@@ -493,6 +525,7 @@ func (t *KnowledgeSearchTool) searchWithQueries(
|
||||
topK int,
|
||||
vectorThreshold, keywordThreshold float64,
|
||||
queryType string,
|
||||
kbTypeMap map[string]string,
|
||||
) []*searchResultWithMeta {
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
@@ -503,7 +536,7 @@ func (t *KnowledgeSearchTool) searchWithQueries(
|
||||
go func(q string) {
|
||||
defer wg.Done()
|
||||
results := t.searchSingleQuery(ctx, q, kbsToSearch, topK,
|
||||
vectorThreshold, keywordThreshold, queryType)
|
||||
vectorThreshold, keywordThreshold, queryType, kbTypeMap)
|
||||
mu.Lock()
|
||||
allResults = append(allResults, results...)
|
||||
mu.Unlock()
|
||||
@@ -522,6 +555,7 @@ func (t *KnowledgeSearchTool) searchSingleQuery(
|
||||
topK int,
|
||||
vectorThreshold, keywordThreshold float64,
|
||||
queryType string,
|
||||
kbTypeMap map[string]string,
|
||||
) []*searchResultWithMeta {
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
@@ -549,9 +583,11 @@ func (t *KnowledgeSearchTool) searchSingleQuery(
|
||||
mu.Lock()
|
||||
for _, r := range kbResults {
|
||||
results = append(results, &searchResultWithMeta{
|
||||
SearchResult: r,
|
||||
SourceQuery: query,
|
||||
QueryType: queryType,
|
||||
SearchResult: r,
|
||||
SourceQuery: query,
|
||||
QueryType: queryType,
|
||||
KnowledgeBaseID: kb,
|
||||
KnowledgeBaseType: kbTypeMap[kb],
|
||||
})
|
||||
}
|
||||
mu.Unlock()
|
||||
@@ -594,18 +630,85 @@ func (t *KnowledgeSearchTool) rerankResults(
|
||||
query string,
|
||||
results []*searchResultWithMeta,
|
||||
) ([]*searchResultWithMeta, error) {
|
||||
// If chatModel is available, use LLM-based prompt scoring
|
||||
if t.chatModel != nil {
|
||||
return t.rerankWithLLM(ctx, query, results)
|
||||
// Separate FAQ and non-FAQ results. FAQ results keep original scores.
|
||||
faqResults := make([]*searchResultWithMeta, 0)
|
||||
nonFAQResults := make([]*searchResultWithMeta, 0, len(results))
|
||||
|
||||
for _, result := range results {
|
||||
if result.KnowledgeBaseType == types.KnowledgeBaseTypeFAQ {
|
||||
faqResults = append(faqResults, result)
|
||||
} else {
|
||||
nonFAQResults = append(nonFAQResults, result)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to rerank model if available
|
||||
if t.rerankModel != nil {
|
||||
return t.rerankWithModel(ctx, query, results)
|
||||
// If there are no non-FAQ results, return original list (already all FAQ)
|
||||
if len(nonFAQResults) == 0 {
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// No reranking available, return original results
|
||||
return results, nil
|
||||
var (
|
||||
rerankedNonFAQ []*searchResultWithMeta
|
||||
err error
|
||||
)
|
||||
|
||||
// Apply reranking only to non-FAQ results
|
||||
switch {
|
||||
case t.chatModel != nil:
|
||||
rerankedNonFAQ, err = t.rerankWithLLM(ctx, query, nonFAQResults)
|
||||
case t.rerankModel != nil:
|
||||
rerankedNonFAQ, err = t.rerankWithModel(ctx, query, nonFAQResults)
|
||||
default:
|
||||
rerankedNonFAQ = nonFAQResults
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Combine FAQ results (with original order) and reranked non-FAQ results
|
||||
combined := make([]*searchResultWithMeta, 0, len(results))
|
||||
combined = append(combined, faqResults...)
|
||||
combined = append(combined, rerankedNonFAQ...)
|
||||
|
||||
// Sort by score (descending) to keep consistent output order
|
||||
sort.Slice(combined, func(i, j int) bool {
|
||||
return combined[i].Score > combined[j].Score
|
||||
})
|
||||
|
||||
return combined, nil
|
||||
}
|
||||
|
||||
func (t *KnowledgeSearchTool) getFAQMetadata(
|
||||
ctx context.Context,
|
||||
chunkID string,
|
||||
cache map[string]*types.FAQChunkMetadata,
|
||||
) (*types.FAQChunkMetadata, error) {
|
||||
if chunkID == "" || t.chunkService == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if meta, ok := cache[chunkID]; ok {
|
||||
return meta, nil
|
||||
}
|
||||
|
||||
chunk, err := t.chunkService.GetChunkByID(ctx, chunkID)
|
||||
if err != nil {
|
||||
cache[chunkID] = nil
|
||||
return nil, err
|
||||
}
|
||||
if chunk == nil {
|
||||
cache[chunkID] = nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil {
|
||||
cache[chunkID] = nil
|
||||
return nil, err
|
||||
}
|
||||
cache[chunkID] = meta
|
||||
return meta, nil
|
||||
}
|
||||
|
||||
// rerankWithLLM uses LLM prompt to score and rerank search results
|
||||
@@ -906,6 +1009,7 @@ func (t *KnowledgeSearchTool) deduplicateResults(results []*searchResultWithMeta
|
||||
|
||||
// formatOutput formats the search results for display
|
||||
func (t *KnowledgeSearchTool) formatOutput(
|
||||
ctx context.Context,
|
||||
results []*searchResultWithMeta,
|
||||
vectorQueries, keywordQueries []string,
|
||||
kbsToSearch []string,
|
||||
@@ -992,7 +1096,19 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
formattedResults := make([]map[string]interface{}, 0, len(results))
|
||||
currentKB := ""
|
||||
|
||||
faqMetadataCache := make(map[string]*types.FAQChunkMetadata)
|
||||
|
||||
for i, result := range results {
|
||||
var faqMeta *types.FAQChunkMetadata
|
||||
if result.KnowledgeBaseType == types.KnowledgeBaseTypeFAQ {
|
||||
meta, err := t.getFAQMetadata(ctx, result.ID, faqMetadataCache)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to load FAQ metadata for chunk %s: %v", result.ID, err)
|
||||
} else {
|
||||
faqMeta = meta
|
||||
}
|
||||
}
|
||||
|
||||
// Group by knowledge base
|
||||
if result.KnowledgeID != currentKB {
|
||||
currentKB = result.KnowledgeID
|
||||
@@ -1013,18 +1129,47 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
output += fmt.Sprintf(" Content: %s\n", result.Content)
|
||||
output += fmt.Sprintf(" [chunk_id: %s - full content included above]\n", result.ID)
|
||||
|
||||
if faqMeta != nil {
|
||||
if faqMeta.StandardQuestion != "" {
|
||||
output += fmt.Sprintf(" FAQ Standard Question: %s\n", faqMeta.StandardQuestion)
|
||||
}
|
||||
if len(faqMeta.SimilarQuestions) > 0 {
|
||||
output += fmt.Sprintf(" FAQ Similar Questions: %s\n", strings.Join(faqMeta.SimilarQuestions, "; "))
|
||||
}
|
||||
if len(faqMeta.Answers) > 0 {
|
||||
output += " FAQ Answers:\n"
|
||||
for _, ans := range faqMeta.Answers {
|
||||
output += fmt.Sprintf(" - %s\n", ans)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
formattedResults = append(formattedResults, map[string]interface{}{
|
||||
"result_index": i + 1,
|
||||
"chunk_id": result.ID,
|
||||
"content": result.Content,
|
||||
"score": result.Score,
|
||||
"relevance_level": relevanceLevel,
|
||||
"knowledge_id": result.KnowledgeID,
|
||||
"knowledge_title": result.KnowledgeTitle,
|
||||
"match_type": result.MatchType,
|
||||
"source_query": result.SourceQuery,
|
||||
"query_type": result.QueryType,
|
||||
"result_index": i + 1,
|
||||
"chunk_id": result.ID,
|
||||
"content": result.Content,
|
||||
"score": result.Score,
|
||||
"relevance_level": relevanceLevel,
|
||||
"knowledge_id": result.KnowledgeID,
|
||||
"knowledge_title": result.KnowledgeTitle,
|
||||
"match_type": result.MatchType,
|
||||
"source_query": result.SourceQuery,
|
||||
"query_type": result.QueryType,
|
||||
"knowledge_base_type": result.KnowledgeBaseType,
|
||||
})
|
||||
|
||||
last := formattedResults[len(formattedResults)-1]
|
||||
if faqMeta != nil {
|
||||
if faqMeta.StandardQuestion != "" {
|
||||
last["faq_standard_question"] = faqMeta.StandardQuestion
|
||||
}
|
||||
if len(faqMeta.SimilarQuestions) > 0 {
|
||||
last["faq_similar_questions"] = faqMeta.SimilarQuestions
|
||||
}
|
||||
if len(faqMeta.Answers) > 0 {
|
||||
last["faq_answers"] = faqMeta.Answers
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// // Add usage guidance
|
||||
|
||||
@@ -208,7 +208,15 @@ func (s *agentService) registerTools(
|
||||
case "todo_write":
|
||||
registry.RegisterTool(tools.NewTodoWriteTool())
|
||||
case "knowledge_search":
|
||||
registry.RegisterTool(tools.NewKnowledgeSearchTool(s.knowledgeBaseService, tenantID, config.KnowledgeBases, rerankModel, chatModel))
|
||||
registry.RegisterTool(
|
||||
tools.NewKnowledgeSearchTool(
|
||||
s.knowledgeBaseService,
|
||||
s.chunkService,
|
||||
tenantID,
|
||||
config.KnowledgeBases,
|
||||
rerankModel,
|
||||
chatModel,
|
||||
))
|
||||
case "get_related_chunks":
|
||||
registry.RegisterTool(tools.NewGetRelatedChunksTool(s.chunkService, s.knowledgeBaseService))
|
||||
case "query_knowledge_graph":
|
||||
@@ -283,6 +291,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
|
||||
kbInfos = append(kbInfos, &agent.KnowledgeBaseInfo{
|
||||
ID: kbID,
|
||||
Name: kbID,
|
||||
Type: "document", // Default type
|
||||
Description: "",
|
||||
DocCount: 0,
|
||||
RecentDocs: []agent.RecentDocInfo{},
|
||||
@@ -294,37 +303,72 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
|
||||
docCount := 0
|
||||
recentDocs := []agent.RecentDocInfo{}
|
||||
|
||||
// Get recent documents using paged query (first 10, assumed to be sorted by created_at desc)
|
||||
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
})
|
||||
|
||||
if err == nil && pageResult != nil {
|
||||
docCount = int(pageResult.Total)
|
||||
|
||||
// Convert to Knowledge slice
|
||||
if knowledges, ok := pageResult.Data.([]*types.Knowledge); ok {
|
||||
for _, k := range knowledges {
|
||||
if len(recentDocs) >= 10 {
|
||||
break
|
||||
if kb.Type == types.KnowledgeBaseTypeFAQ {
|
||||
pageResult, err := s.knowledgeService.ListFAQEntries(ctx, kbID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
})
|
||||
if err == nil && pageResult != nil {
|
||||
docCount = int(pageResult.Total)
|
||||
if entries, ok := pageResult.Data.([]*types.FAQEntry); ok {
|
||||
for _, entry := range entries {
|
||||
if len(recentDocs) >= 10 {
|
||||
break
|
||||
}
|
||||
recentDocs = append(recentDocs, agent.RecentDocInfo{
|
||||
KnowledgeID: entry.ChunkID,
|
||||
Title: entry.StandardQuestion,
|
||||
Type: string(types.ChunkTypeFAQ),
|
||||
CreatedAt: entry.CreatedAt.Format("2006-01-02"),
|
||||
FAQStandardQuestion: entry.StandardQuestion,
|
||||
FAQSimilarQuestions: entry.SimilarQuestions,
|
||||
FAQAnswers: entry.Answers,
|
||||
})
|
||||
}
|
||||
}
|
||||
} else if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list FAQ entries for %s: %v", kbID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to generic knowledge listing when not FAQ or FAQ retrieval failed
|
||||
if kb.Type != types.KnowledgeBaseTypeFAQ || len(recentDocs) == 0 {
|
||||
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
})
|
||||
|
||||
if err == nil && pageResult != nil {
|
||||
docCount = int(pageResult.Total)
|
||||
|
||||
// Convert to Knowledge slice
|
||||
if knowledges, ok := pageResult.Data.([]*types.Knowledge); ok {
|
||||
for _, k := range knowledges {
|
||||
if len(recentDocs) >= 10 {
|
||||
break
|
||||
}
|
||||
recentDocs = append(recentDocs, agent.RecentDocInfo{
|
||||
KnowledgeID: k.ID,
|
||||
Title: k.Title,
|
||||
Description: k.Description,
|
||||
FileName: k.FileName,
|
||||
Type: k.FileType,
|
||||
CreatedAt: k.CreatedAt.Format("2006-01-02"),
|
||||
FileSize: k.FileSize,
|
||||
})
|
||||
}
|
||||
recentDocs = append(recentDocs, agent.RecentDocInfo{
|
||||
KnowledgeID: k.ID,
|
||||
Title: k.Title,
|
||||
Description: k.Description,
|
||||
FileName: k.FileName,
|
||||
Type: k.FileType,
|
||||
CreatedAt: k.CreatedAt.Format("2006-01-02"),
|
||||
FileSize: k.FileSize,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
kbType := kb.Type
|
||||
if kbType == "" {
|
||||
kbType = "document" // Default type
|
||||
}
|
||||
kbInfos = append(kbInfos, &agent.KnowledgeBaseInfo{
|
||||
ID: kb.ID,
|
||||
Name: kb.Name,
|
||||
Type: kbType,
|
||||
Description: kb.Description,
|
||||
DocCount: docCount,
|
||||
RecentDocs: recentDocs,
|
||||
|
||||
@@ -97,9 +97,9 @@ func (h *Handler) CreateSession(c *gin.Context) {
|
||||
if request.SessionStrategy.SummaryParameters != nil {
|
||||
createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters
|
||||
} else {
|
||||
createdSession.SummaryParameters = h.createDefaultSummaryConfig()
|
||||
createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx)
|
||||
}
|
||||
h.fillSummaryConfigDefaults(createdSession.SummaryParameters)
|
||||
h.fillSummaryConfigDefaults(ctx, createdSession.SummaryParameters)
|
||||
|
||||
logger.Debug(ctx, "Custom session strategy set")
|
||||
} else {
|
||||
@@ -113,7 +113,7 @@ func (h *Handler) CreateSession(c *gin.Context) {
|
||||
createdSession.VectorThreshold = h.config.Conversation.VectorThreshold
|
||||
createdSession.RerankThreshold = h.config.Conversation.RerankThreshold
|
||||
createdSession.RerankTopK = h.config.Conversation.RerankTopK
|
||||
createdSession.SummaryParameters = h.createDefaultSummaryConfig()
|
||||
createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx)
|
||||
|
||||
logger.Debug(ctx, "Using default session strategy")
|
||||
}
|
||||
|
||||
@@ -162,8 +162,13 @@ func getFloat64(m map[string]interface{}, key string) float64 {
|
||||
}
|
||||
|
||||
// createDefaultSummaryConfig creates a default summary configuration from config
|
||||
func (h *Handler) createDefaultSummaryConfig() *types.SummaryConfig {
|
||||
return &types.SummaryConfig{
|
||||
// It prioritizes tenant-level ConversationConfig, then falls back to config.yaml defaults
|
||||
func (h *Handler) createDefaultSummaryConfig(ctx context.Context) *types.SummaryConfig {
|
||||
// Try to get tenant from context
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
|
||||
// Initialize with config.yaml defaults
|
||||
cfg := &types.SummaryConfig{
|
||||
MaxTokens: h.config.Conversation.Summary.MaxTokens,
|
||||
TopP: h.config.Conversation.Summary.TopP,
|
||||
TopK: h.config.Conversation.Summary.TopK,
|
||||
@@ -177,17 +182,74 @@ func (h *Handler) createDefaultSummaryConfig() *types.SummaryConfig {
|
||||
Seed: h.config.Conversation.Summary.Seed,
|
||||
MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens,
|
||||
}
|
||||
|
||||
// Override with tenant-level conversation config if available
|
||||
if tenant != nil && tenant.ConversationConfig != nil {
|
||||
if tenant.ConversationConfig.Prompt != "" {
|
||||
cfg.Prompt = tenant.ConversationConfig.Prompt
|
||||
}
|
||||
if tenant.ConversationConfig.ContextTemplate != "" {
|
||||
cfg.ContextTemplate = tenant.ConversationConfig.ContextTemplate
|
||||
}
|
||||
if tenant.ConversationConfig.Temperature > 0 {
|
||||
cfg.Temperature = tenant.ConversationConfig.Temperature
|
||||
}
|
||||
if tenant.ConversationConfig.MaxTokens > 0 {
|
||||
cfg.MaxTokens = tenant.ConversationConfig.MaxTokens
|
||||
}
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
// fillSummaryConfigDefaults fills missing fields in summary config with defaults
|
||||
func (h *Handler) fillSummaryConfigDefaults(config *types.SummaryConfig) {
|
||||
// It prioritizes tenant-level ConversationConfig, then falls back to config.yaml defaults
|
||||
func (h *Handler) fillSummaryConfigDefaults(ctx context.Context, config *types.SummaryConfig) {
|
||||
// Try to get tenant from context
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
|
||||
// Determine default values: tenant config first, then config.yaml
|
||||
var defaultPrompt, defaultContextTemplate, defaultNoMatchPrefix string
|
||||
var defaultTemperature float64
|
||||
var defaultMaxTokens int
|
||||
|
||||
if tenant != nil && tenant.ConversationConfig != nil {
|
||||
// Use tenant-level config as defaults
|
||||
defaultPrompt = tenant.ConversationConfig.Prompt
|
||||
defaultContextTemplate = tenant.ConversationConfig.ContextTemplate
|
||||
defaultTemperature = tenant.ConversationConfig.Temperature
|
||||
defaultMaxTokens = tenant.ConversationConfig.MaxTokens
|
||||
}
|
||||
|
||||
// Fall back to config.yaml if tenant config is empty
|
||||
if defaultPrompt == "" {
|
||||
defaultPrompt = h.config.Conversation.Summary.Prompt
|
||||
}
|
||||
if defaultContextTemplate == "" {
|
||||
defaultContextTemplate = h.config.Conversation.Summary.ContextTemplate
|
||||
}
|
||||
if defaultTemperature == 0 {
|
||||
defaultTemperature = h.config.Conversation.Summary.Temperature
|
||||
}
|
||||
if defaultMaxTokens == 0 {
|
||||
defaultMaxTokens = h.config.Conversation.Summary.MaxTokens
|
||||
}
|
||||
defaultNoMatchPrefix = h.config.Conversation.Summary.NoMatchPrefix
|
||||
|
||||
// Fill missing fields
|
||||
if config.Prompt == "" {
|
||||
config.Prompt = h.config.Conversation.Summary.Prompt
|
||||
config.Prompt = defaultPrompt
|
||||
}
|
||||
if config.ContextTemplate == "" {
|
||||
config.ContextTemplate = h.config.Conversation.Summary.ContextTemplate
|
||||
config.ContextTemplate = defaultContextTemplate
|
||||
}
|
||||
if config.Temperature == 0 {
|
||||
config.Temperature = defaultTemperature
|
||||
}
|
||||
if config.MaxTokens == 0 {
|
||||
config.MaxTokens = defaultMaxTokens
|
||||
}
|
||||
if config.NoMatchPrefix == "" {
|
||||
config.NoMatchPrefix = h.config.Conversation.Summary.NoMatchPrefix
|
||||
config.NoMatchPrefix = defaultNoMatchPrefix
|
||||
}
|
||||
}
|
||||
|
||||
+110
-1
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -19,16 +20,19 @@ import (
|
||||
// through the REST API endpoints
|
||||
type TenantHandler struct {
|
||||
service interfaces.TenantService
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
// NewTenantHandler creates a new tenant handler instance with the provided service
|
||||
// Parameters:
|
||||
// - service: An implementation of the TenantService interface for business logic
|
||||
// - config: Application configuration
|
||||
//
|
||||
// Returns a pointer to the newly created TenantHandler
|
||||
func NewTenantHandler(service interfaces.TenantService) *TenantHandler {
|
||||
func NewTenantHandler(service interfaces.TenantService, config *config.Config) *TenantHandler {
|
||||
return &TenantHandler{
|
||||
service: service,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,6 +414,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
|
||||
case "web-search-config":
|
||||
h.GetTenantWebSearchConfig(c)
|
||||
return
|
||||
case "conversation-config":
|
||||
h.GetTenantConversationConfig(c)
|
||||
return
|
||||
default:
|
||||
logger.Info(ctx, "KV key not supported", "key", key)
|
||||
c.Error(errors.NewBadRequestError("unsupported key"))
|
||||
@@ -430,6 +437,9 @@ func (h *TenantHandler) UpdateTenantKV(c *gin.Context) {
|
||||
case "web-search-config":
|
||||
h.updateTenantWebSearchConfigInternal(c)
|
||||
return
|
||||
case "conversation-config":
|
||||
h.updateTenantConversationConfigInternal(c)
|
||||
return
|
||||
default:
|
||||
logger.Info(ctx, "KV key not supported", "key", key)
|
||||
c.Error(errors.NewBadRequestError("unsupported key"))
|
||||
@@ -499,3 +509,102 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
|
||||
"data": tenant.WebSearchConfig,
|
||||
})
|
||||
}
|
||||
|
||||
// GetTenantConversationConfig retrieves the conversation configuration for a tenant
|
||||
// This is the global conversation configuration that applies to normal mode sessions by default
|
||||
func (h *TenantHandler) GetTenantConversationConfig(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start retrieving tenant conversation config")
|
||||
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
logger.Error(ctx, "Tenant is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// If tenant has no conversation config, return defaults from config.yaml
|
||||
if tenant.ConversationConfig == nil {
|
||||
logger.Info(ctx, "Tenant has no conversation config, returning defaults")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"prompt": h.config.Conversation.Summary.Prompt,
|
||||
"context_template": h.config.Conversation.Summary.ContextTemplate,
|
||||
"temperature": h.config.Conversation.Summary.Temperature,
|
||||
"max_tokens": h.config.Conversation.Summary.MaxTokens,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieved tenant conversation config successfully, Tenant ID: %d", tenant.ID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"prompt": tenant.ConversationConfig.Prompt,
|
||||
"context_template": tenant.ConversationConfig.ContextTemplate,
|
||||
"temperature": tenant.ConversationConfig.Temperature,
|
||||
"max_tokens": tenant.ConversationConfig.MaxTokens,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// updateTenantConversationConfigInternal updates the conversation configuration for a tenant
|
||||
// This sets the global conversation configuration for normal mode sessions in this tenant
|
||||
func (h *TenantHandler) updateTenantConversationConfigInternal(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start updating tenant conversation config")
|
||||
|
||||
var req types.ConversationConfig
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Validate configuration
|
||||
if req.Temperature < 0 || req.Temperature > 2 {
|
||||
c.Error(errors.NewBadRequestError("temperature must be between 0 and 2"))
|
||||
return
|
||||
}
|
||||
if req.MaxTokens <= 0 || req.MaxTokens > 100000 {
|
||||
c.Error(errors.NewBadRequestError("max_tokens must be between 1 and 100000"))
|
||||
return
|
||||
}
|
||||
|
||||
// Get existing tenant
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
logger.Error(ctx, "Tenant is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// Update conversation configuration
|
||||
tenant.ConversationConfig = &req
|
||||
|
||||
updatedTenant, 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)
|
||||
c.Error(appErr)
|
||||
} else {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to update tenant conversation config").WithDetails(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Tenant conversation config updated successfully, Tenant ID: %d", tenant.ID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"prompt": updatedTenant.ConversationConfig.Prompt,
|
||||
"context_template": updatedTenant.ConversationConfig.ContextTemplate,
|
||||
"temperature": updatedTenant.ConversationConfig.Temperature,
|
||||
"max_tokens": updatedTenant.ConversationConfig.MaxTokens,
|
||||
},
|
||||
"message": "Conversation configuration updated successfully",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ type Tenant struct {
|
||||
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)
|
||||
ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
// Last updated time
|
||||
@@ -69,3 +71,35 @@ func (c *RetrieverEngines) Scan(value interface{}) error {
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// ConversationConfig represents the conversation configuration for normal mode
|
||||
type ConversationConfig struct {
|
||||
// Prompt is the system prompt
|
||||
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
|
||||
Temperature float64 `json:"temperature"`
|
||||
// MaxTokens is the maximum number of tokens to generate
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface, used to convert ConversationConfig to database value
|
||||
func (c *ConversationConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements the sql.Scanner interface, used to convert database value to ConversationConfig
|
||||
func (c *ConversationConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Add conversation_config column to tenants table
|
||||
-- This migration adds support for conversation configuration at tenant level
|
||||
-- Used for normal mode conversation settings (prompt, context_template, temperature, max_tokens)
|
||||
|
||||
ALTER TABLE tenants
|
||||
ADD COLUMN conversation_config JSON DEFAULT NULL COMMENT 'Conversation configuration for normal mode sessions (prompt, context_template, temperature, max_tokens)';
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Add conversation_config column to tenants table
|
||||
-- This migration adds support for conversation configuration at tenant level
|
||||
-- Used for normal mode conversation settings (prompt, context_template, temperature, max_tokens)
|
||||
|
||||
ALTER TABLE tenants
|
||||
ADD COLUMN conversation_config JSONB DEFAULT NULL;
|
||||
|
||||
Reference in New Issue
Block a user