feat: implement knowledge search feature with enhanced configuration and UI

- Updated `config.yaml` to adjust conversation parameters for improved search performance.
- Added a new `knowledgeSemanticSearch` API function for semantic search capabilities.
- Introduced new SVG icons for search functionality.
- Created `KnowledgeSearch.vue` component for the search interface, including query input and result display.
- Enhanced menu and routing to support navigation to the new knowledge search page.
- Updated internationalization files to include translations for the knowledge search feature.

This update provides users with a powerful tool to perform semantic searches across knowledge bases, improving content discoverability.
This commit is contained in:
wizardchen
2026-03-02 15:51:11 +08:00
committed by lyingbug
parent e595e9345e
commit 612b3f2c90
13 changed files with 884 additions and 18 deletions
+4 -4
View File
@@ -7,10 +7,10 @@ server:
conversation:
max_rounds: 5
keyword_threshold: 0.3
embedding_top_k: 10
vector_threshold: 0.5
rerank_threshold: 0.5
rerank_top_k: 5
embedding_top_k: 30
vector_threshold: 0.2
rerank_threshold: 0.3
rerank_top_k: 30
fallback_strategy: "model"
fallback_response: "抱歉,我无法回答这个问题。"
fallback_prompt: |
+8
View File
@@ -299,3 +299,11 @@ export function searchKnowledge(
if (options?.agent_id) query.set('agent_id', options.agent_id);
return get(`/api/v1/knowledge/search?${query.toString()}`);
}
export function knowledgeSemanticSearch(data: {
query: string;
knowledge_base_ids?: string[];
knowledge_ids?: string[];
}) {
return post('/api/v1/knowledge-search', data);
}
+4
View File
@@ -0,0 +1,4 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="9" cy="9" r="5.5" stroke="#07C05F" stroke-width="1.5"/>
<line x1="13.06" y1="13.06" x2="17" y2="17" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 280 B

+4
View File
@@ -0,0 +1,4 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="9" cy="9" r="5.5" stroke="#000000" stroke-opacity=".6" stroke-width="1.5"/>
<line x1="13.06" y1="13.06" x2="17" y2="17" stroke="#000000" stroke-opacity=".6" stroke-width="1.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 320 B

+11
View File
@@ -5,6 +5,7 @@ import { onBeforeRouteUpdate } from 'vue-router';
import { MessagePlugin } from "tdesign-vue-next";
import { useSettingsStore } from '@/stores/settings';
import { useUIStore } from '@/stores/ui';
import { useMenuStore } from '@/stores/menu';
import { listKnowledgeBases, searchKnowledge, batchQueryKnowledge } from '@/api/knowledge-base';
import { stopSession } from '@/api/chat';
import { useOrganizationStore } from '@/stores/organization';
@@ -23,6 +24,7 @@ const router = useRouter();
const settingsStore = useSettingsStore();
const uiStore = useUIStore();
const orgStore = useOrganizationStore();
const menuStore = useMenuStore();
const { t } = useI18n();
let query = ref("");
@@ -1216,6 +1218,15 @@ onMounted(() => {
settingsStore.addKnowledgeBase(kbId);
}
const prefill = menuStore.consumePrefillQuery();
if (prefill) {
query.value = prefill;
nextTick(() => {
const textarea = getTextareaEl();
if (textarea) textarea.focus();
});
}
// 监听点击外部关闭下拉菜单
document.addEventListener('click', closeAgentModeSelector);
document.addEventListener('click', closeModelSelector);
+15 -7
View File
@@ -16,7 +16,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 == 'agent' ? agentIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
<img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'search' ? searchIcon : item.icon == 'agent' ? agentIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)" alt="">
</div>
<span class="menu_title" :title="item.title">{{ item.title }}</span>
<span v-if="item.path === 'organizations' && orgStore.totalPendingJoinRequestCount > 0" class="menu-pending-badge" :title="t('organization.settings.pendingJoinRequestsBadge')">{{ orgStore.totalPendingJoinRequestCount }}</span>
@@ -174,6 +174,8 @@ const isMenuItemActive = (itemPath: string): boolean => {
return currentRoute === 'knowledgeBaseList' ||
currentRoute === 'knowledgeBaseDetail' ||
currentRoute === 'knowledgeBaseSettings';
case 'knowledge-search':
return currentRoute === 'knowledgeSearch';
case 'agents':
return currentRoute === 'agentList';
case 'organizations':
@@ -206,13 +208,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 === 'agents' || item.path === 'organizations' || item.path === 'creatChat'
item.path === 'knowledge-bases' || item.path === 'knowledge-search' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat'
);
});
const bottomMenuItems = computed<MenuItem[]>(() => {
return (menuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => {
if (item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat') {
if (item.path === 'knowledge-bases' || item.path === 'knowledge-search' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat') {
return false;
}
return true;
@@ -534,11 +536,12 @@ watch([() => route.name, () => route.params], (newvalue, oldvalue) => {
}
});
let knowledgeIcon = ref('zhishiku-green.svg');
let searchIcon = ref('search.svg');
let prefixIcon = ref('prefixIcon.svg');
let logoutIcon = ref('logout.svg');
let settingIcon = ref('setting.svg'); // 设置图标
let agentIcon = ref('agent.svg'); // 智能体图标
let organizationIcon = ref('organization.svg'); // 组织图标
let settingIcon = ref('setting.svg');
let agentIcon = ref('agent.svg');
let organizationIcon = ref('organization.svg');
let pathPrefix = ref(route.name)
const getIcon = (path: string) => {
// 根据当前路由状态更新所有图标
@@ -547,10 +550,14 @@ let pathPrefix = ref(route.name)
const settingsActiveState = getIconActiveState('settings');
const agentsActiveState = route.name === 'agentList';
const organizationsActiveState = route.name === 'organizationList';
const knowledgeSearchActiveState = route.name === 'knowledgeSearch';
// 知识库图标:只在知识库页面显示绿色
knowledgeIcon.value = kbActiveState.isKbActive ? 'zhishiku-green.svg' : 'zhishiku.svg';
// 知识搜索图标:只在知识搜索页面显示绿色
searchIcon.value = knowledgeSearchActiveState ? 'search-green.svg' : 'search.svg';
// 智能体图标:只在智能体页面显示绿色
agentIcon.value = agentsActiveState ? 'agent-green.svg' : 'agent.svg';
@@ -578,8 +585,9 @@ const handleMenuClick = async (path: string) => {
} else {
router.push('/platform/knowledge-bases')
}
} else if (path === 'knowledge-search') {
router.push('/platform/knowledge-search')
} else if (path === 'agents') {
// 智能体菜单项:跳转到智能体列表
router.push('/platform/agents')
} else if (path === 'organizations') {
// 组织菜单项:跳转到组织列表
+27 -1
View File
@@ -13,7 +13,8 @@ export default {
batchManage: 'Batch Manage',
newSession: 'New Chat',
confirmLogout: 'Are you sure you want to logout?',
systemInfo: 'System Information'
systemInfo: 'System Information',
knowledgeSearch: 'Knowledge Search',
},
batchManage: {
title: 'Manage Conversations',
@@ -2719,4 +2720,29 @@ export default {
unsupported: 'This file type does not support online preview',
unsupportedHint: 'Please download and open with a local application',
},
knowledgeSearch: {
title: 'Knowledge Search',
subtitle: 'Semantic search across knowledge bases to find relevant content',
placeholder: 'Enter search query...',
searchBtn: 'Search',
selectKb: 'Select Knowledge Base',
allKb: 'All Knowledge Bases',
noResults: 'No results found',
resultCount: '{count} results found',
score: 'Relevance',
matchType: 'Match Type',
matchTypeVector: 'Vector Match',
matchTypeKeyword: 'Keyword Match',
emptyHint: 'Enter keywords to search for relevant content chunks in knowledge bases',
searching: 'Searching...',
source: 'Source',
chunk: 'chunks',
expand: 'Expand',
collapse: 'Collapse',
fileCount: 'files',
viewDetail: 'View Detail',
startChat: 'Start Chat',
chatWithFile: 'Chat',
newChatTitle: 'Search: {query}',
},
}
+26
View File
@@ -14,6 +14,7 @@ export default {
newSession: "새 세션",
confirmLogout: "정말 로그아웃 하시겠습니까?",
systemInfo: "시스템 정보",
knowledgeSearch: "지식 검색",
},
batchManage: {
title: "대화 관리",
@@ -2795,4 +2796,29 @@ export default {
unsupported: '이 파일 유형은 온라인 미리보기를 지원하지 않습니다',
unsupportedHint: '파일을 다운로드하여 로컬 앱으로 열어주세요',
},
knowledgeSearch: {
title: '지식 검색',
subtitle: '지식베이스에서 시맨틱 검색으로 관련 콘텐츠를 빠르게 찾으세요',
placeholder: '검색어를 입력하세요...',
searchBtn: '검색',
selectKb: '지식베이스 선택',
allKb: '모든 지식베이스',
noResults: '관련 결과를 찾을 수 없습니다',
resultCount: '총 {count}개 결과',
score: '관련도',
matchType: '매칭 유형',
matchTypeVector: '벡터 매칭',
matchTypeKeyword: '키워드 매칭',
emptyHint: '키워드를 입력하여 지식베이스에서 관련 콘텐츠를 검색하세요',
searching: '검색 중...',
source: '출처',
chunk: '개 청크',
expand: '펼치기',
collapse: '접기',
fileCount: '개 파일',
viewDetail: '상세보기',
startChat: '대화 시작',
chatWithFile: '대화',
newChatTitle: '검색: {query}',
},
};
+27 -1
View File
@@ -11,7 +11,8 @@ export default {
batchManage: 'Пакетное управление',
newSession: 'Новый диалог',
confirmLogout: 'Вы уверены, что хотите выйти?',
systemInfo: 'Информация о системе'
systemInfo: 'Информация о системе',
knowledgeSearch: 'Поиск знаний',
},
batchManage: {
title: 'Управление диалогами',
@@ -1863,4 +1864,29 @@ export default {
unsupported: 'Этот тип файла не поддерживает онлайн-просмотр',
unsupportedHint: 'Скачайте файл и откройте локально',
},
knowledgeSearch: {
title: 'Поиск знаний',
subtitle: 'Семантический поиск по базам знаний для быстрого нахождения релевантного контента',
placeholder: 'Введите поисковый запрос...',
searchBtn: 'Поиск',
selectKb: 'Выбрать базу знаний',
allKb: 'Все базы знаний',
noResults: 'Результаты не найдены',
resultCount: 'Найдено {count} результатов',
score: 'Релевантность',
matchType: 'Тип совпадения',
matchTypeVector: 'Векторное совпадение',
matchTypeKeyword: 'Совпадение по ключевым словам',
emptyHint: 'Введите ключевые слова для поиска релевантного контента в базах знаний',
searching: 'Поиск...',
source: 'Источник',
chunk: 'фрагм.',
expand: 'Развернуть',
collapse: 'Свернуть',
fileCount: 'файлов',
viewDetail: 'Подробнее',
startChat: 'Начать чат',
chatWithFile: 'Чат',
newChatTitle: 'Поиск: {query}',
},
}
+26
View File
@@ -14,6 +14,7 @@ export default {
newSession: "新会话",
confirmLogout: "确定要退出登录吗?",
systemInfo: "系统信息",
knowledgeSearch: "知识搜索",
},
batchManage: {
title: "管理对话记录",
@@ -2724,4 +2725,29 @@ export default {
unsupported: "该文件类型暂不支持在线预览",
unsupportedHint: "请下载文件后使用本地应用查看",
},
knowledgeSearch: {
title: "知识搜索",
subtitle: "在知识库中进行语义检索,快速查找相关内容",
placeholder: "输入搜索内容...",
searchBtn: "搜索",
selectKb: "选择知识库",
allKb: "全部知识库",
noResults: "未找到相关结果",
resultCount: "共找到 {count} 条结果",
score: "相关度",
matchType: "匹配类型",
matchTypeVector: "向量匹配",
matchTypeKeyword: "关键词匹配",
emptyHint: "输入关键词,在知识库中搜索相关内容片段",
searching: "搜索中...",
source: "来源",
chunk: "个片段",
expand: "展开",
collapse: "收起",
fileCount: "个文件",
viewDetail: "查看详情",
startChat: "进入对话",
chatWithFile: "对话",
newChatTitle: "搜索: {query}",
},
};
+6
View File
@@ -64,6 +64,12 @@ const router = createRouter({
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-search",
name: "knowledgeSearch",
component: () => import("../views/knowledge/KnowledgeSearch.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "agents",
name: "agentList",
+22 -5
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.knowledgeSearch', icon: 'search', path: 'knowledge-search' },
{ title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents' },
{ title: '', titleKey: 'menu.organizations', icon: 'organization', path: 'organizations' },
{
@@ -36,6 +37,7 @@ export const useMenuStore = defineStore('menuStore', () => {
const firstQuery = ref('')
const firstMentionedItems = ref<any[]>([])
const firstModelId = ref('')
const prefillQuery = ref('')
const applyMenuTranslations = () => {
menuArr.forEach(item => {
@@ -54,15 +56,17 @@ export const useMenuStore = defineStore('menuStore', () => {
}
)
const chatMenuIndex = menuArr.findIndex(item => item.path === 'creatChat')
const clearMenuArr = () => {
const chatMenu = menuArr[3]
const chatMenu = menuArr[chatMenuIndex]
if (chatMenu && chatMenu.children) {
chatMenu.children = createMenuChildren()
}
}
const updatemenuArr = (obj: any) => {
const chatMenu = menuArr[3]
const chatMenu = menuArr[chatMenuIndex]
if (!chatMenu.children) {
chatMenu.children = createMenuChildren()
}
@@ -73,7 +77,7 @@ export const useMenuStore = defineStore('menuStore', () => {
}
const updataMenuChildren = (item: MenuChild) => {
const chatMenu = menuArr[3]
const chatMenu = menuArr[chatMenuIndex]
if (!chatMenu.children) {
chatMenu.children = createMenuChildren()
}
@@ -81,7 +85,7 @@ export const useMenuStore = defineStore('menuStore', () => {
}
const updatasessionTitle = (sessionId: string, title: string) => {
const chatMenu = menuArr[3]
const chatMenu = menuArr[chatMenuIndex]
chatMenu.children?.forEach((item: MenuChild) => {
if (item.id === sessionId) {
item.title = title
@@ -100,17 +104,30 @@ export const useMenuStore = defineStore('menuStore', () => {
firstModelId.value = modelId
}
const setPrefillQuery = (q: string) => {
prefillQuery.value = q
}
const consumePrefillQuery = () => {
const q = prefillQuery.value
prefillQuery.value = ''
return q
}
return {
menuArr,
isFirstSession,
firstQuery,
firstMentionedItems,
firstModelId,
prefillQuery,
clearMenuArr,
updatemenuArr,
updataMenuChildren,
updatasessionTitle,
changeIsFirstSession,
changeFirstQuery
changeFirstQuery,
setPrefillQuery,
consumePrefillQuery
}
})
@@ -0,0 +1,704 @@
<template>
<div class="ks-container">
<div class="ks-content">
<div class="header">
<div class="header-title">
<h2>{{ $t('knowledgeSearch.title') }}</h2>
<p class="header-subtitle">{{ $t('knowledgeSearch.subtitle') }}</p>
</div>
</div>
<div class="search-bar">
<t-input
v-model="query"
:placeholder="$t('knowledgeSearch.placeholder')"
clearable
class="search-input"
@enter="handleSearch"
>
<template #prefixIcon>
<t-icon name="search" />
</template>
</t-input>
<t-select
v-model="selectedKbIds"
:placeholder="$t('knowledgeSearch.allKb')"
multiple
clearable
filterable
class="kb-filter"
:loading="kbLoading"
>
<t-option
v-for="kb in knowledgeBases"
:key="kb.id"
:value="kb.id"
:label="kb.name"
>
<div class="kb-option-row">
<span class="kb-option-name">{{ kb.name }}</span>
<span :class="['kb-type-badge', kb.type === 'faq' ? 'faq' : 'doc']">
{{ kb.type === 'faq' ? 'FAQ' : 'DOC' }}
</span>
</div>
</t-option>
</t-select>
<t-button
theme="primary"
:loading="loading"
:disabled="!query.trim()"
class="search-btn"
@click="handleSearch"
>
{{ $t('knowledgeSearch.searchBtn') }}
</t-button>
</div>
<div class="ks-main">
<!-- Before search -->
<div v-if="!hasSearched && !loading" class="empty-hint">
<div class="empty-hint-icon">
<t-icon name="search" size="36px" />
</div>
<p>{{ $t('knowledgeSearch.emptyHint') }}</p>
</div>
<!-- Loading -->
<div v-else-if="loading" class="empty-hint">
<t-loading size="small" :text="$t('knowledgeSearch.searching')" />
</div>
<!-- No results -->
<div v-else-if="hasSearched && groupedResults.length === 0" class="empty-hint">
<div class="empty-hint-icon muted">
<t-icon name="info-circle" size="36px" />
</div>
<p>{{ $t('knowledgeSearch.noResults') }}</p>
</div>
<!-- Results grouped by file -->
<template v-else>
<div class="results-summary">
<span>
{{ $t('knowledgeSearch.resultCount', { count: totalChunks }) }}
<span class="results-file-count">&middot; {{ groupedResults.length }} {{ $t('knowledgeSearch.fileCount') }}</span>
</span>
<span class="start-chat-link" @click="startChat()">
<t-icon name="chat" size="14px" />
{{ $t('knowledgeSearch.startChat') }}
</span>
</div>
<div class="file-groups">
<div
v-for="(group, gIdx) in groupedResults"
:key="group.knowledgeId"
class="file-group"
>
<div class="file-group-header" @click="toggleFileExpand(gIdx)">
<div class="file-group-left">
<svg class="file-icon" width="16" height="16" viewBox="0 0 24 24" fill="none">
<path d="M14 2H6C5.46957 2 4.96086 2.21071 4.58579 2.58579C4.21071 2.96086 4 3.46957 4 4V20C4 20.5304 4.21071 21.0391 4.58579 21.4142C4.96086 21.7893 5.46957 22 6 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V8L14 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 2V8H20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<span class="file-group-title">{{ group.title }}</span>
<span class="file-group-kb" v-if="group.kbName">{{ group.kbName }}</span>
</div>
<div class="file-group-right">
<span class="chunk-count">{{ group.chunks.length }} {{ $t('knowledgeSearch.chunk') }}</span>
<span
class="go-detail-link"
@click.stop="startChat(group)"
>
<t-icon name="chat" size="14px" />
{{ $t('knowledgeSearch.chatWithFile') }}
</span>
<span
v-if="group.kbId"
class="go-detail-link"
@click.stop="goToDetail(group)"
>
{{ $t('knowledgeSearch.viewDetail') }}
<t-icon name="jump" size="14px" />
</span>
<t-icon :name="expandedFiles.has(gIdx) ? 'chevron-up' : 'chevron-down'" size="16px" />
</div>
</div>
<div v-if="expandedFiles.has(gIdx)" class="file-group-chunks">
<div
v-for="(chunk, cIdx) in group.chunks"
:key="chunk.id || cIdx"
class="chunk-item"
>
<div class="chunk-item-meta">
<span class="chunk-index">#{{ chunk.chunk_index }}</span>
<span :class="['match-badge', chunk.match_type === 'vector' ? 'vector' : 'keyword']">
{{ chunk.match_type === 'vector' ? $t('knowledgeSearch.matchTypeVector') : $t('knowledgeSearch.matchTypeKeyword') }}
</span>
<span class="chunk-score">{{ (chunk.score * 100).toFixed(1) }}%</span>
</div>
<div
class="chunk-content"
:class="{ expanded: expandedChunks.has(`${gIdx}-${cIdx}`) }"
@click="toggleChunkExpand(gIdx, cIdx)"
>
{{ chunk.matched_content || chunk.content }}
</div>
</div>
</div>
</div>
</div>
</template>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import { listKnowledgeBases, knowledgeSemanticSearch } from '@/api/knowledge-base'
import { useMenuStore } from '@/stores/menu'
import { useSettingsStore } from '@/stores/settings'
const { t } = useI18n()
const router = useRouter()
const menuStore = useMenuStore()
const settingsStore = useSettingsStore()
const query = ref('')
const loading = ref(false)
const kbLoading = ref(false)
const hasSearched = ref(false)
const selectedKbIds = ref<string[]>([])
const results = ref<any[]>([])
const expandedFiles = reactive(new Set<number>())
const expandedChunks = reactive(new Set<string>())
const knowledgeBases = ref<any[]>([])
interface FileGroup {
knowledgeId: string
kbId: string
title: string
kbName: string
chunks: any[]
}
const groupedResults = computed<FileGroup[]>(() => {
const map = new Map<string, FileGroup>()
for (const item of results.value) {
const kid = item.knowledge_id || 'unknown'
if (!map.has(kid)) {
map.set(kid, {
knowledgeId: kid,
kbId: item.knowledge_base_id || '',
title: item.knowledge_title || item.knowledge_filename || kid,
kbName: getKbName(item.knowledge_base_id),
chunks: [],
})
}
map.get(kid)!.chunks.push(item)
}
return Array.from(map.values())
})
const totalChunks = computed(() => results.value.length)
const fetchKnowledgeBases = async () => {
kbLoading.value = true
try {
const res: any = await listKnowledgeBases()
if (res?.data) {
knowledgeBases.value = res.data
}
} catch (e) {
console.error('Failed to load knowledge bases', e)
} finally {
kbLoading.value = false
}
}
const handleSearch = async () => {
const q = query.value.trim()
if (!q) return
loading.value = true
hasSearched.value = true
expandedFiles.clear()
expandedChunks.clear()
try {
const kbIds = selectedKbIds.value.length > 0
? selectedKbIds.value
: knowledgeBases.value.map((kb: any) => kb.id)
const res: any = await knowledgeSemanticSearch({
query: q,
knowledge_base_ids: kbIds,
})
if (res?.success && res.data) {
results.value = res.data
} else {
results.value = []
}
} catch (e: any) {
console.error('Search failed', e)
MessagePlugin.error(e?.message || 'Search failed')
results.value = []
} finally {
loading.value = false
}
}
const toggleFileExpand = (idx: number) => {
if (expandedFiles.has(idx)) {
expandedFiles.delete(idx)
} else {
expandedFiles.add(idx)
}
}
const toggleChunkExpand = (gIdx: number, cIdx: number) => {
const key = `${gIdx}-${cIdx}`
if (expandedChunks.has(key)) {
expandedChunks.delete(key)
} else {
expandedChunks.add(key)
}
}
const goToDetail = (group: FileGroup) => {
if (!group.kbId) return
router.push({
path: `/platform/knowledge-bases/${group.kbId}`,
query: { knowledge_id: group.knowledgeId },
})
}
const startChat = (group?: FileGroup) => {
const q = query.value.trim()
if (!q) return
let kbIds: string[] = []
let fileIds: string[] = []
if (group) {
if (group.kbId) {
kbIds = [group.kbId]
}
fileIds = [group.knowledgeId]
} else {
kbIds = selectedKbIds.value.length > 0
? selectedKbIds.value
: knowledgeBases.value.map((kb: any) => kb.id)
}
settingsStore.selectKnowledgeBases(kbIds)
for (const fid of fileIds) {
settingsStore.addFile(fid)
}
menuStore.setPrefillQuery(q)
router.push('/platform/creatChat')
}
const getKbName = (kbId: string): string => {
if (!kbId) return ''
const kb = knowledgeBases.value.find((k: any) => k.id === kbId)
return kb?.name || ''
}
onMounted(() => {
fetchKnowledgeBases()
})
</script>
<style lang="less" scoped>
.ks-container {
margin: 0 16px 0 0;
height: calc(100vh);
box-sizing: border-box;
flex: 1;
display: flex;
position: relative;
min-height: 0;
}
.ks-content {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
padding: 24px 32px 0 32px;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
.header-title {
display: flex;
flex-direction: column;
gap: 4px;
}
h2 {
margin: 0;
color: #000000e6;
font-family: "PingFang SC", -apple-system, sans-serif;
font-size: 24px;
font-weight: 600;
line-height: 32px;
}
}
.header-subtitle {
margin: 0;
color: #00000099;
font-family: "PingFang SC", -apple-system, sans-serif;
font-size: 14px;
font-weight: 400;
line-height: 20px;
}
.search-bar {
display: flex;
gap: 10px;
align-items: center;
margin-bottom: 20px;
:deep(.t-input) {
font-size: 13px;
background-color: #f7f9fc;
border-color: #e5e9f2;
border-radius: 6px;
&:hover,
&:focus,
&.t-is-focused {
border-color: #07C05F;
background-color: #fff;
}
}
:deep(.t-select .t-input) {
font-size: 13px;
background-color: #f7f9fc;
border-color: #e5e9f2;
border-radius: 6px;
&:hover,
&.t-is-focused {
border-color: #07C05F;
background-color: #fff;
}
}
}
.search-input {
flex: 1;
min-width: 0;
}
.kb-filter {
width: 200px;
flex-shrink: 0;
}
.search-btn {
flex-shrink: 0;
background: linear-gradient(135deg, #07c05f 0%, #00a67e 100%);
border: none;
color: #fff;
border-radius: 6px;
&:hover {
background: linear-gradient(135deg, #05a04f 0%, #008a6a 100%);
}
}
.kb-option-row {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
gap: 8px;
}
.kb-option-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kb-type-badge {
font-size: 10px;
padding: 1px 5px;
border-radius: 3px;
font-weight: 500;
flex-shrink: 0;
&.doc {
background: rgba(7, 192, 95, 0.1);
color: #07c05f;
}
&.faq {
background: rgba(255, 152, 0, 0.1);
color: #e8a735;
}
}
.ks-main {
flex: 1;
min-height: 0;
overflow-y: auto;
padding-bottom: 24px;
}
.empty-hint {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 100px 0 60px;
gap: 12px;
color: #00000066;
font-size: 14px;
p {
margin: 0;
}
}
.empty-hint-icon {
width: 64px;
height: 64px;
border-radius: 50%;
background: #f5f7fa;
display: flex;
align-items: center;
justify-content: center;
color: #c0c4cc;
&.muted {
color: #dcdfe6;
}
}
.results-summary {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 13px;
color: #00000099;
margin-bottom: 16px;
padding: 0 2px;
}
.start-chat-link {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 13px;
color: #07c05f;
cursor: pointer;
padding: 4px 10px;
border-radius: 6px;
border: 1px solid rgba(7, 192, 95, 0.3);
transition: all 0.15s;
&:hover {
background: rgba(7, 192, 95, 0.08);
border-color: #07c05f;
}
}
.results-file-count {
color: #00000066;
}
.file-groups {
display: flex;
flex-direction: column;
gap: 12px;
}
.file-group {
border: 1px solid #f0f0f0;
border-radius: 10px;
background: #fff;
overflow: hidden;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
transition: box-shadow 0.2s;
&:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
}
.file-group-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 18px;
cursor: pointer;
user-select: none;
transition: background 0.15s;
&:hover {
background: #fafbfc;
}
}
.file-group-left {
display: flex;
align-items: center;
gap: 10px;
flex: 1;
min-width: 0;
}
.file-icon {
flex-shrink: 0;
color: #07c05f;
}
.file-group-title {
font-size: 14px;
font-weight: 600;
color: #1d2129;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-group-kb {
font-size: 12px;
color: #00000066;
padding: 1px 8px;
background: #f5f7fa;
border-radius: 4px;
flex-shrink: 0;
max-width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-group-right {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
color: #00000066;
}
.chunk-count {
font-size: 12px;
color: #00000066;
}
.go-detail-link {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: 12px;
color: #07c05f;
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
transition: all 0.15s;
&:hover {
background: rgba(7, 192, 95, 0.08);
color: #05a04f;
}
}
.file-group-chunks {
border-top: 1px solid #f0f0f0;
}
.chunk-item {
padding: 12px 18px 12px 44px;
border-bottom: 1px solid #f8f8f8;
&:last-child {
border-bottom: none;
}
}
.chunk-item-meta {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
.chunk-index {
font-size: 11px;
color: #00000066;
font-weight: 600;
font-family: "SF Mono", "Monaco", monospace;
}
.match-badge {
font-size: 10px;
padding: 1px 6px;
border-radius: 3px;
font-weight: 500;
&.vector {
background: rgba(22, 119, 255, 0.08);
color: #1677ff;
}
&.keyword {
background: rgba(255, 152, 0, 0.08);
color: #e8a735;
}
}
.chunk-score {
font-size: 11px;
color: #00000044;
font-family: "SF Mono", "Monaco", monospace;
}
.chunk-content {
font-size: 13px;
color: #000000cc;
line-height: 1.7;
white-space: pre-wrap;
word-break: break-word;
max-height: 66px;
overflow: hidden;
cursor: pointer;
position: relative;
transition: max-height 0.3s ease;
&::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 24px;
background: linear-gradient(transparent, #fff);
pointer-events: none;
}
&.expanded {
max-height: none;
&::after {
display: none;
}
}
}
</style>