feat: Add file type filtering to knowledge base search functionality, enhancing user experience and API capabilities

This commit is contained in:
wizardchen
2025-12-04 00:20:22 +08:00
parent bee699f5bf
commit e0d9be9405
12 changed files with 103 additions and 14 deletions
+4 -1
View File
@@ -54,7 +54,7 @@ export function createManualKnowledge(kbId: string, data: { title: string; conte
export function listKnowledgeFiles( export function listKnowledgeFiles(
kbId: string, kbId: string,
params: { page: number; page_size: number; tag_id?: string; keyword?: string }, params: { page: number; page_size: number; tag_id?: string; keyword?: string; file_type?: string },
) { ) {
const query = new URLSearchParams(); const query = new URLSearchParams();
query.append('page', String(params.page)); query.append('page', String(params.page));
@@ -65,6 +65,9 @@ export function listKnowledgeFiles(
if (params.keyword) { if (params.keyword) {
query.append('keyword', params.keyword); query.append('keyword', params.keyword);
} }
if (params.file_type) {
query.append('file_type', params.file_type);
}
const qs = query.toString(); const qs = query.toString();
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`); return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`);
} }
+1 -1
View File
@@ -28,7 +28,7 @@ export default function (knowledgeBaseId?: string) {
file_type: "" file_type: ""
}); });
const getKnowled = ( const getKnowled = (
query: { page: number; page_size: number; tag_id?: string; keyword?: string } = { page: 1, page_size: 35 }, query: { page: number; page_size: number; tag_id?: string; keyword?: string; file_type?: string } = { page: 1, page_size: 35 },
kbId?: string, kbId?: string,
) => { ) => {
const targetKbId = kbId || knowledgeBaseId; const targetKbId = kbId || knowledgeBaseId;
+2
View File
@@ -183,6 +183,8 @@ export default {
dragFileNotText: 'Please drag files instead of text or links', dragFileNotText: 'Please drag files instead of text or links',
searchPlaceholder: 'Search knowledge bases...', searchPlaceholder: 'Search knowledge bases...',
docSearchPlaceholder: 'Search document names...', docSearchPlaceholder: 'Search document names...',
fileTypeFilter: 'File Type',
allFileTypes: 'All Types',
noMatch: 'No matching knowledge base found', noMatch: 'No matching knowledge base found',
noKnowledge: 'No knowledge bases available', noKnowledge: 'No knowledge bases available',
loadingFailed: 'Failed to load knowledge bases' loadingFailed: 'Failed to load knowledge bases'
+2
View File
@@ -183,6 +183,8 @@ export default {
dragFileNotText: 'Пожалуйста, перетащите файлы, а не текст или ссылки', dragFileNotText: 'Пожалуйста, перетащите файлы, а не текст или ссылки',
searchPlaceholder: 'Поиск по базам знаний...', searchPlaceholder: 'Поиск по базам знаний...',
docSearchPlaceholder: 'Поиск документов...', docSearchPlaceholder: 'Поиск документов...',
fileTypeFilter: 'Тип файла',
allFileTypes: 'Все типы',
noMatch: 'Совпадающих баз знаний не найдено', noMatch: 'Совпадающих баз знаний не найдено',
noKnowledge: 'Нет доступных баз знаний', noKnowledge: 'Нет доступных баз знаний',
loadingFailed: 'Не удалось загрузить базы знаний' loadingFailed: 'Не удалось загрузить базы знаний'
+2
View File
@@ -186,6 +186,8 @@ export default {
dragFileNotText: "请拖拽文件而不是文本或链接", dragFileNotText: "请拖拽文件而不是文本或链接",
searchPlaceholder: "搜索知识库...", searchPlaceholder: "搜索知识库...",
docSearchPlaceholder: "搜索文档名称...", docSearchPlaceholder: "搜索文档名称...",
fileTypeFilter: "文件类型",
allFileTypes: "全部类型",
noMatch: "未找到匹配的知识库", noMatch: "未找到匹配的知识库",
noKnowledge: "暂无可用知识库", noKnowledge: "暂无可用知识库",
loadingFailed: "加载知识库失败", loadingFailed: "加载知识库失败",
+60 -4
View File
@@ -59,6 +59,17 @@ const tagTotal = ref(0);
let tagSearchDebounce: ReturnType<typeof setTimeout> | null = null; let tagSearchDebounce: ReturnType<typeof setTimeout> | null = null;
let docSearchDebounce: ReturnType<typeof setTimeout> | null = null; let docSearchDebounce: ReturnType<typeof setTimeout> | null = null;
const docSearchKeyword = ref(''); const docSearchKeyword = ref('');
const selectedFileType = ref('');
const fileTypeOptions = computed(() => [
{ content: t('knowledgeBase.allFileTypes') || '全部类型', value: '' },
{ content: 'PDF', value: 'pdf' },
{ content: 'DOCX', value: 'docx' },
{ content: 'DOC', value: 'doc' },
{ content: 'TXT', value: 'txt' },
{ content: 'MD', value: 'md' },
{ content: 'URL', value: 'url' },
{ content: t('knowledgeBase.typeManual') || '手动创建', value: 'manual' },
]);
type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>; type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>;
const tagDropdownOptions = computed(() => { const tagDropdownOptions = computed(() => {
const options = [ const options = [
@@ -150,6 +161,7 @@ const loadKnowledgeFiles = (kbIdValue: string) => {
page_size: pageSize, page_size: pageSize,
tag_id: selectedTagId.value || undefined, tag_id: selectedTagId.value || undefined,
keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined, keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined,
file_type: selectedFileType.value || undefined,
}, },
kbIdValue, kbIdValue,
); );
@@ -460,6 +472,15 @@ watch(docSearchKeyword, (newVal, oldVal) => {
}, 300); }, 300);
}); });
// 监听文件类型筛选变化
watch(selectedFileType, (newVal, oldVal) => {
if (newVal === oldVal) return;
if (kbId.value) {
page = 1;
loadKnowledgeFiles(kbId.value);
}
});
// 监听文件上传事件 // 监听文件上传事件
const handleFileUploaded = (event: CustomEvent) => { const handleFileUploaded = (event: CustomEvent) => {
const uploadedKbId = event.detail.kbId; const uploadedKbId = event.detail.kbId;
@@ -836,7 +857,7 @@ const handleScroll = () => {
if (scrollTop + clientHeight >= scrollHeight) { if (scrollTop + clientHeight >= scrollHeight) {
page++; page++;
if (cardList.value.length < total.value && page <= pageNum) { if (cardList.value.length < total.value && page <= pageNum) {
getKnowled({ page, page_size: pageSize, tag_id: selectedTagId.value || undefined, keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined }); getKnowled({ page, page_size: pageSize, tag_id: selectedTagId.value || undefined, keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined, file_type: selectedFileType.value || undefined });
} }
} }
} }
@@ -1125,12 +1146,13 @@ async function createNewSession(value: string): Promise<void> {
</aside> </aside>
<div class="tag-content"> <div class="tag-content">
<div class="doc-card-area"> <div class="doc-card-area">
<!-- 搜索栏 --> <!-- 搜索栏和筛选 -->
<div class="doc-search-bar"> <div class="doc-filter-bar">
<t-input <t-input
v-model.trim="docSearchKeyword" v-model.trim="docSearchKeyword"
:placeholder="$t('knowledgeBase.docSearchPlaceholder')" :placeholder="$t('knowledgeBase.docSearchPlaceholder')"
clearable clearable
class="doc-search-input"
@clear="loadKnowledgeFiles(kbId)" @clear="loadKnowledgeFiles(kbId)"
@keydown.enter="loadKnowledgeFiles(kbId)" @keydown.enter="loadKnowledgeFiles(kbId)"
> >
@@ -1138,6 +1160,13 @@ async function createNewSession(value: string): Promise<void> {
<t-icon name="search" size="16px" /> <t-icon name="search" size="16px" />
</template> </template>
</t-input> </t-input>
<t-select
v-model="selectedFileType"
:options="fileTypeOptions"
:placeholder="$t('knowledgeBase.fileTypeFilter')"
class="doc-type-select"
clearable
/>
</div> </div>
<div <div
class="doc-scroll-container" class="doc-scroll-container"
@@ -1781,9 +1810,21 @@ async function createNewSession(value: string): Promise<void> {
min-height: 0; min-height: 0;
} }
.doc-search-bar { .doc-filter-bar {
padding: 0px 0px 10px 0px; padding: 0px 0px 10px 0px;
flex-shrink: 0; flex-shrink: 0;
display: flex;
gap: 10px;
align-items: center;
.doc-search-input {
flex: 1;
}
.doc-type-select {
width: 140px;
flex-shrink: 0;
}
:deep(.t-input) { :deep(.t-input) {
font-size: 13px; font-size: 13px;
@@ -1798,6 +1839,21 @@ async function createNewSession(value: string): Promise<void> {
background-color: #fff; 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: #4080ff;
background-color: #fff;
}
}
}
} }
.doc-scroll-container { .doc-scroll-container {
@@ -63,6 +63,7 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
page *types.Pagination, page *types.Pagination,
tagID string, tagID string,
keyword string, keyword string,
fileType string,
) ([]*types.Knowledge, int64, error) { ) ([]*types.Knowledge, int64, error) {
var knowledges []*types.Knowledge var knowledges []*types.Knowledge
var total int64 var total int64
@@ -75,6 +76,15 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
if keyword != "" { if keyword != "" {
query = query.Where("file_name LIKE ?", "%"+keyword+"%") query = query.Where("file_name LIKE ?", "%"+keyword+"%")
} }
if fileType != "" {
if fileType == "manual" {
query = query.Where("type = ?", "manual")
} else if fileType == "url" {
query = query.Where("type = ?", "url")
} else {
query = query.Where("file_type = ?", fileType)
}
}
// Query total count first // Query total count first
if err := query.Count(&total).Error; err != nil { if err := query.Count(&total).Error; err != nil {
@@ -90,6 +100,15 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
if keyword != "" { if keyword != "" {
dataQuery = dataQuery.Where("file_name LIKE ?", "%"+keyword+"%") dataQuery = dataQuery.Where("file_name LIKE ?", "%"+keyword+"%")
} }
if fileType != "" {
if fileType == "manual" {
dataQuery = dataQuery.Where("type = ?", "manual")
} else if fileType == "url" {
dataQuery = dataQuery.Where("type = ?", "url")
} else {
dataQuery = dataQuery.Where("file_type = ?", fileType)
}
}
if err := dataQuery. if err := dataQuery.
Order("created_at DESC"). Order("created_at DESC").
@@ -331,7 +331,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{ pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
}, "", "") }, "", "", "")
if err == nil && pageResult != nil { if err == nil && pageResult != nil {
docCount = int(pageResult.Total) docCount = int(pageResult.Total)
+2 -2
View File
@@ -699,10 +699,10 @@ func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
// ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base // ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base
func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context, func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
kbID string, page *types.Pagination, tagID string, keyword string, kbID string, page *types.Pagination, tagID string, keyword string, fileType string,
) (*types.PageResult, error) { ) (*types.PageResult, error) {
knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx, knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx,
ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, tagID, keyword) ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, tagID, keyword, fileType)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+2 -2
View File
@@ -232,7 +232,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
kbIdStr, &types.Pagination{ kbIdStr, &types.Pagination{
Page: 1, Page: 1,
PageSize: 1, PageSize: 1,
}, "", "") }, "", "", "")
if err == nil && knowledgeList != nil && knowledgeList.Total > 0 { if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
logger.Error(ctx, "Cannot change embedding model when files exist") logger.Error(ctx, "Cannot change embedding model when files exist")
c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型")) c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型"))
@@ -1176,7 +1176,7 @@ func (h *InitializationHandler) GetCurrentConfigByKB(c *gin.Context) {
kbIdStr, &types.Pagination{ kbIdStr, &types.Pagination{
Page: 1, Page: 1,
PageSize: 1, PageSize: 1,
}, "", "") }, "", "", "")
hasFiles := err == nil && knowledgeList != nil && knowledgeList.Total > 0 hasFiles := err == nil && knowledgeList != nil && knowledgeList.Total > 0
// 构建配置响应 // 构建配置响应
+4 -2
View File
@@ -319,19 +319,21 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
tagID := c.Query("tag_id") tagID := c.Query("tag_id")
keyword := c.Query("keyword") keyword := c.Query("keyword")
fileType := c.Query("file_type")
logger.Infof( logger.Infof(
ctx, ctx,
"Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, page: %d, page size: %d", "Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, file_type: %s, page: %d, page size: %d",
secutils.SanitizeForLog(kbID), secutils.SanitizeForLog(kbID),
secutils.SanitizeForLog(tagID), secutils.SanitizeForLog(tagID),
secutils.SanitizeForLog(keyword), secutils.SanitizeForLog(keyword),
secutils.SanitizeForLog(fileType),
pagination.Page, pagination.Page,
pagination.PageSize, pagination.PageSize,
) )
// Retrieve paginated knowledge entries // Retrieve paginated knowledge entries
result, err := h.kgService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &pagination, tagID, keyword) result, err := h.kgService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &pagination, tagID, keyword, fileType)
if err != nil { if err != nil {
logger.ErrorWithFields(ctx, err, nil) logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error())) c.Error(errors.NewInternalServerError(err.Error()))
+4 -1
View File
@@ -46,12 +46,14 @@ type KnowledgeService interface {
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination. // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination.
// When tagID is non-empty, results are filtered by tag_id. // When tagID is non-empty, results are filtered by tag_id.
// When keyword is non-empty, results are filtered by file_name. // When keyword is non-empty, results are filtered by file_name.
// When fileType is non-empty, results are filtered by file_type or type.
ListPagedKnowledgeByKnowledgeBaseID( ListPagedKnowledgeByKnowledgeBaseID(
ctx context.Context, ctx context.Context,
kbID string, kbID string,
page *types.Pagination, page *types.Pagination,
tagID string, tagID string,
keyword string, keyword string,
fileType string,
) (*types.PageResult, error) ) (*types.PageResult, error)
// DeleteKnowledge deletes knowledge by ID. // DeleteKnowledge deletes knowledge by ID.
DeleteKnowledge(ctx context.Context, id string) error DeleteKnowledge(ctx context.Context, id string) error
@@ -115,8 +117,9 @@ type KnowledgeRepository interface {
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination. // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination.
// When tagID is non-empty, results are filtered by tag_id. // When tagID is non-empty, results are filtered by tag_id.
// When keyword is non-empty, results are filtered by file_name. // When keyword is non-empty, results are filtered by file_name.
// When fileType is non-empty, results are filtered by file_type or type.
ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context, ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
tenantID uint64, kbID string, page *types.Pagination, tagID string, keyword string, tenantID uint64, kbID string, page *types.Pagination, tagID string, keyword string, fileType string,
) ([]*types.Knowledge, int64, error) ) ([]*types.Knowledge, int64, error)
UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
// UpdateKnowledgeBatch updates knowledge items in batch // UpdateKnowledgeBatch updates knowledge items in batch