Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: Add file type filtering to knowledge base search functionality, enhancing user experience and API capabilities
wizardchene0d9be940582
diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.tsindex 5cc5fa6ee..8dd07d69b 100644--- a/frontend/src/api/knowledge-base/index.ts+++ b/frontend/src/api/knowledge-base/index.ts@@ -54,7 +54,7 @@ export function createManualKnowledge(kbId: string, data: { title: string; conteexport function listKnowledgeFiles(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();query.append('page', String(params.page));@@ -65,6 +65,9 @@ export function listKnowledgeFiles(if (params.keyword) {query.append('keyword', params.keyword);}+ if (params.file_type) {+ query.append('file_type', params.file_type);+ }const qs = query.toString();return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`);}diff --git a/frontend/src/hooks/useKnowledgeBase.ts b/frontend/src/hooks/useKnowledgeBase.tsindex 61774325e..19d636290 100644--- a/frontend/src/hooks/useKnowledgeBase.ts+++ b/frontend/src/hooks/useKnowledgeBase.ts@@ -28,7 +28,7 @@ export default function (knowledgeBaseId?: string) {file_type: ""});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,) => {const targetKbId = kbId || knowledgeBaseId;diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex e6de0007b..caead9054 100644--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -183,6 +183,8 @@ export default {dragFileNotText: 'Please drag files instead of text or links',searchPlaceholder: 'Search knowledge bases...',docSearchPlaceholder: 'Search document names...',+ fileTypeFilter: 'File Type',+ allFileTypes: 'All Types',noMatch: 'No matching knowledge base found',noKnowledge: 'No knowledge bases available',loadingFailed: 'Failed to load knowledge bases'diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 9d2dd25d6..8112eb7c4 100644--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -183,6 +183,8 @@ export default {dragFileNotText: 'Пожалуйста, перетащите файлы, а не текст или ссылки',searchPlaceholder: 'Поиск по базам знаний...',docSearchPlaceholder: 'Поиск документов...',+ fileTypeFilter: 'Тип файла',+ allFileTypes: 'Все типы',noMatch: 'Совпадающих баз знаний не найдено',noKnowledge: 'Нет доступных баз знаний',loadingFailed: 'Не удалось загрузить базы знаний'diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 2d28b46ef..ff5e2bc12 100644--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -186,6 +186,8 @@ export default {dragFileNotText: "请拖拽文件而不是文本或链接",searchPlaceholder: "搜索知识库...",docSearchPlaceholder: "搜索文档名称...",+ fileTypeFilter: "文件类型",+ allFileTypes: "全部类型",noMatch: "未找到匹配的知识库",noKnowledge: "暂无可用知识库",loadingFailed: "加载知识库失败",diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vueindex e576344d1..43e9c94d6 100644--- a/frontend/src/views/knowledge/KnowledgeBase.vue+++ b/frontend/src/views/knowledge/KnowledgeBase.vue@@ -59,6 +59,17 @@ const tagTotal = ref(0);let tagSearchDebounce: ReturnType<typeof setTimeout> | null = null;let docSearchDebounce: ReturnType<typeof setTimeout> | null = null;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 }>;const tagDropdownOptions = computed(() => {const options = [@@ -150,6 +161,7 @@ const loadKnowledgeFiles = (kbIdValue: string) => {page_size: pageSize,tag_id: selectedTagId.value || undefined,keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined,+ file_type: selectedFileType.value || undefined,},kbIdValue,);@@ -460,6 +472,15 @@ watch(docSearchKeyword, (newVal, oldVal) => {}, 300);});+// 监听文件类型筛选变化+watch(selectedFileType, (newVal, oldVal) => {+ if (newVal === oldVal) return;+ if (kbId.value) {+ page = 1;+ loadKnowledgeFiles(kbId.value);+ }+});+// 监听文件上传事件const handleFileUploaded = (event: CustomEvent) => {const uploadedKbId = event.detail.kbId;@@ -836,7 +857,7 @@ const handleScroll = () => {if (scrollTop + clientHeight >= scrollHeight) {page++;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><div class="tag-content"><div class="doc-card-area">- <!-- 搜索栏 -->- <div class="doc-search-bar">+ <!-- 搜索栏和筛选 -->+ <div class="doc-filter-bar"><t-inputv-model.trim="docSearchKeyword":placeholder="$t('knowledgeBase.docSearchPlaceholder')"clearable+ class="doc-search-input"@clear="loadKnowledgeFiles(kbId)"@keydown.enter="loadKnowledgeFiles(kbId)">@@ -1138,6 +1160,13 @@ async function createNewSession(value: string): Promise<void> {<t-icon name="search" size="16px" /></template></t-input>+ <t-select+ v-model="selectedFileType"+ :options="fileTypeOptions"+ :placeholder="$t('knowledgeBase.fileTypeFilter')"+ class="doc-type-select"+ clearable+ /></div><divclass="doc-scroll-container"@@ -1781,9 +1810,21 @@ async function createNewSession(value: string): Promise<void> {min-height: 0;}-.doc-search-bar {+.doc-filter-bar {padding: 0px 0px 10px 0px;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) {font-size: 13px;@@ -1798,6 +1839,21 @@ async function createNewSession(value: string): Promise<void> {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 {diff --git a/internal/application/repository/knowledge.go b/internal/application/repository/knowledge.goindex 165506a6b..fb5133f15 100644--- a/internal/application/repository/knowledge.go+++ b/internal/application/repository/knowledge.go@@ -63,6 +63,7 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(page *types.Pagination,tagID string,keyword string,+ fileType string,) ([]*types.Knowledge, int64, error) {var knowledges []*types.Knowledgevar total int64@@ -75,6 +76,15 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(if 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 firstif err := query.Count(&total).Error; err != nil {@@ -90,6 +100,15 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(if 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.Order("created_at DESC").diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 295b7bab2..ced67a1aa 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -331,7 +331,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []stringpageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{Page: 1,PageSize: 10,- }, "", "")+ }, "", "", "")if err == nil && pageResult != nil {docCount = int(pageResult.Total)diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.goindex 0c04c50c8..4dfb89805 100644--- a/internal/application/service/knowledge.go+++ b/internal/application/service/knowledge.go@@ -699,10 +699,10 @@ func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,// ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge basefunc (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) {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 {return nil, err}diff --git a/internal/handler/initialization.go b/internal/handler/initialization.goindex 8a1a7be45..a83ccf8d0 100644--- a/internal/handler/initialization.go+++ b/internal/handler/initialization.go@@ -232,7 +232,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {kbIdStr, &types.Pagination{Page: 1,PageSize: 1,- }, "", "")+ }, "", "", "")if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {logger.Error(ctx, "Cannot change embedding model when files exist")c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型"))@@ -1176,7 +1176,7 @@ func (h *InitializationHandler) GetCurrentConfigByKB(c *gin.Context) {kbIdStr, &types.Pagination{Page: 1,PageSize: 1,- }, "", "")+ }, "", "", "")hasFiles := err == nil && knowledgeList != nil && knowledgeList.Total > 0// 构建配置响应diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex 0f2790f1d..f2a300d26 100644--- a/internal/handler/knowledge.go+++ b/internal/handler/knowledge.go@@ -319,19 +319,21 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {tagID := c.Query("tag_id")keyword := c.Query("keyword")+ fileType := c.Query("file_type")logger.Infof(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(tagID),secutils.SanitizeForLog(keyword),+ secutils.SanitizeForLog(fileType),pagination.Page,pagination.PageSize,)// 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 {logger.ErrorWithFields(ctx, err, nil)c.Error(errors.NewInternalServerError(err.Error()))diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.goindex 22dcf65e5..893d0866e 100644--- a/internal/types/interfaces/knowledge.go+++ b/internal/types/interfaces/knowledge.go@@ -46,12 +46,14 @@ type KnowledgeService interface {// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination.// When tagID is non-empty, results are filtered by tag_id.// 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,kbID string,page *types.Pagination,tagID string,keyword string,+ fileType string,) (*types.PageResult, error)// DeleteKnowledge deletes knowledge by ID.DeleteKnowledge(ctx context.Context, id string) error@@ -115,8 +117,9 @@ type KnowledgeRepository interface {// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination.// When tagID is non-empty, results are filtered by tag_id.// 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,- 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)UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error// UpdateKnowledgeBatch updates knowledge items in batch