From 25fdaed8ca1788d1f36f444f5cd3f836676de7c3 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Sat, 15 Nov 2025 01:30:17 +0800 Subject: [PATCH] feat: Implement FAQ functionality in Knowledge Base - Added support for creating and managing FAQ knowledge bases, including new API endpoints for listing, upserting, updating, and deleting FAQ entries. - Enhanced the frontend to allow users to create FAQ knowledge bases and manage FAQ entries with a dedicated interface. - Introduced new types and configurations for FAQ handling in the backend, ensuring proper indexing and retrieval of FAQ entries. - Updated localization files to include new strings related to FAQ management in multiple languages. - Refactored existing components to accommodate the new FAQ features, improving user experience and functionality. --- client/knowledgebase.go | 7 + frontend/package-lock.json | 106 +- frontend/package.json | 3 +- frontend/src/api/knowledge-base/index.ts | 41 + frontend/src/i18n/locales/en-US.ts | 82 +- frontend/src/i18n/locales/ru-RU.ts | 82 +- frontend/src/i18n/locales/zh-CN.ts | 78 + frontend/src/stores/ui.ts | 6 +- frontend/src/utils/request.ts | 4 +- .../src/views/knowledge/KnowledgeBase.vue | 206 +- .../knowledge/KnowledgeBaseEditorModal.vue | 191 +- .../src/views/knowledge/KnowledgeBaseList.vue | 67 +- .../knowledge/components/FAQEntryManager.vue | 2452 +++++++++++++++++ go.mod | 14 +- go.sum | 35 +- internal/agent/prompts.go | 6 + internal/agent/tools/knowledge_search.go | 167 +- internal/application/repository/chunk.go | 10 +- internal/application/service/knowledge.go | 662 +++++ internal/application/service/knowledgebase.go | 270 +- .../keywords_vector_hybrid_indexer.go | 2 +- internal/application/service/session.go | 6 +- internal/common/tools.go | 34 + internal/container/container.go | 1 + internal/handler/faq.go | 135 + internal/router/router.go | 17 + internal/types/chunk.go | 4 + internal/types/faq.go | 130 + internal/types/interfaces/knowledge.go | 10 + internal/types/knowledge.go | 1 + internal/types/knowledgebase.go | 81 + internal/types/retriever.go | 5 + internal/types/search.go | 10 +- migrations/mysql/08_add_faq_support.sql | 10 + migrations/paradedb/08_add_faq_support.sql | 12 + .../versioned/000008_add_faq_support.down.sql | 12 + .../versioned/000008_add_faq_support.up.sql | 17 + 37 files changed, 4778 insertions(+), 198 deletions(-) create mode 100644 frontend/src/views/knowledge/components/FAQEntryManager.vue create mode 100644 internal/handler/faq.go create mode 100644 internal/types/faq.go create mode 100644 migrations/mysql/08_add_faq_support.sql create mode 100644 migrations/paradedb/08_add_faq_support.sql create mode 100644 migrations/versioned/000008_add_faq_support.down.sql create mode 100644 migrations/versioned/000008_add_faq_support.up.sql diff --git a/client/knowledgebase.go b/client/knowledgebase.go index 63aa921a..54a59c80 100644 --- a/client/knowledgebase.go +++ b/client/knowledgebase.go @@ -16,10 +16,12 @@ import ( type KnowledgeBase struct { ID string `json:"id"` Name string `json:"name"` // Name must be unique within the same tenant + Type string `json:"type"` Description string `json:"description"` TenantID uint `json:"tenant_id"` // Changed to uint type ChunkingConfig ChunkingConfig `json:"chunking_config"` ImageProcessingConfig ImageProcessingConfig `json:"image_processing_config"` + FAQConfig *FAQConfig `json:"faq_config"` EmbeddingModelID string `json:"embedding_model_id"` SummaryModelID string `json:"summary_model_id"` // Summary model ID CreatedAt time.Time `json:"created_at"` @@ -40,6 +42,11 @@ type ChunkingConfig struct { EnableMultimodal bool `json:"enable_multimodal"` // Whether to enable multimodal processing } +// FAQConfig represents faq-specific configuration +type FAQConfig struct { + IndexMode string `json:"index_mode"` +} + // ImageProcessingConfig represents image processing configuration type ImageProcessingConfig struct { ModelID string `json:"model_id"` // Multimodal model ID diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0df5164d..0f410ce5 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -21,7 +21,8 @@ "vue": "^3.5.13", "vue-i18n": "^11.1.12", "vue-router": "^4.5.0", - "webpack": "^5.94.0" + "webpack": "^5.94.0", + "xlsx": "^0.18.5" }, "devDependencies": { "@tsconfig/node22": "^22.0.1", @@ -1894,6 +1895,15 @@ "acorn": "^8.14.0" } }, + "node_modules/adler-32": { + "version": "1.3.1", + "resolved": "https://mirrors.tencent.com/npm/adler-32/-/adler-32-1.3.1.tgz", + "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/ajv": { "version": "8.17.1", "resolved": "https://mirrors.tencent.com/npm/ajv/-/ajv-8.17.1.tgz", @@ -2065,6 +2075,19 @@ ], "license": "CC-BY-4.0" }, + "node_modules/cfb": { + "version": "1.2.2", + "resolved": "https://mirrors.tencent.com/npm/cfb/-/cfb-1.2.2.tgz", + "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/chrome-trace-event": { "version": "1.0.4", "resolved": "https://mirrors.tencent.com/npm/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", @@ -2074,6 +2097,15 @@ "node": ">=6.0" } }, + "node_modules/codepage": { + "version": "1.15.0", + "resolved": "https://mirrors.tencent.com/npm/codepage/-/codepage-1.15.0.tgz", + "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://mirrors.tencent.com/npm/combined-stream/-/combined-stream-1.0.8.tgz", @@ -2110,6 +2142,18 @@ "url": "https://github.com/sponsors/mesqueeb" } }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://mirrors.tencent.com/npm/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://mirrors.tencent.com/npm/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -2479,6 +2523,15 @@ "node": ">= 6" } }, + "node_modules/frac": { + "version": "1.1.2", + "resolved": "https://mirrors.tencent.com/npm/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://mirrors.tencent.com/npm/fsevents/-/fsevents-2.3.3.tgz", @@ -3398,6 +3451,18 @@ "node": ">=0.10.0" } }, + "node_modules/ssf": { + "version": "0.11.2", + "resolved": "https://mirrors.tencent.com/npm/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", + "dependencies": { + "frac": "~1.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/superjson": { "version": "2.2.2", "resolved": "https://mirrors.tencent.com/npm/superjson/-/superjson-2.2.2.tgz", @@ -3904,6 +3969,45 @@ "node": "^18.17.0 || >=20.5.0" } }, + "node_modules/wmf": { + "version": "1.0.2", + "resolved": "https://mirrors.tencent.com/npm/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word": { + "version": "0.3.0", + "resolved": "https://mirrors.tencent.com/npm/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/xlsx": { + "version": "0.18.5", + "resolved": "https://mirrors.tencent.com/npm/xlsx/-/xlsx-0.18.5.tgz", + "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "cfb": "~1.2.1", + "codepage": "~1.15.0", + "crc-32": "~1.2.1", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://mirrors.tencent.com/npm/yallist/-/yallist-3.1.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 6ef65894..8d88fe55 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -25,7 +25,8 @@ "vue": "^3.5.13", "vue-i18n": "^11.1.12", "vue-router": "^4.5.0", - "webpack": "^5.94.0" + "webpack": "^5.94.0", + "xlsx": "^0.18.5" }, "devDependencies": { "@tsconfig/node22": "^22.0.1", diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index c0aec622..41b7efb9 100644 --- a/frontend/src/api/knowledge-base/index.ts +++ b/frontend/src/api/knowledge-base/index.ts @@ -8,6 +8,7 @@ export function listKnowledgeBases() { export function createKnowledgeBase(data: { name: string; description?: string; + type?: 'document' | 'faq'; chunking_config?: any; embedding_model_id?: string; summary_model_id?: string; @@ -16,6 +17,7 @@ export function createKnowledgeBase(data: { vlm_config?: any; cos_config?: any; extract_config?: any; + faq_config?: { index_mode: string; question_index_mode?: string }; }) { return post(`/api/v1/knowledge-bases`, data); } @@ -76,4 +78,43 @@ export function getKnowledgeDetailsCon(id: string, page: number) { // Get chunk by chunk_id only (new endpoint - to be added to backend) export function getChunkByIdOnly(chunkId: string) { return get(`/api/v1/chunks/by-id/${chunkId}`); +} + +const buildQuery = (params?: Record) => { + if (!params) return ''; + const query = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (value === undefined || value === null || value === '') return; + query.append(key, String(value)); + }); + const queryString = query.toString(); + return queryString ? `?${queryString}` : ''; +}; + +export function listFAQEntries(kbId: string, params?: { page?: number; page_size?: number }) { + const query = buildQuery(params); + return get(`/api/v1/knowledge-bases/${kbId}/faq/entries${query}`); +} + +export function upsertFAQEntries(kbId: string, data: { entries: any[]; mode: 'append' | 'replace' }) { + return post(`/api/v1/knowledge-bases/${kbId}/faq/entries`, data); +} + +export function updateFAQEntry(kbId: string, entryId: string, data: any) { + return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/${entryId}`, data); +} + +export function deleteFAQEntries(kbId: string, ids: string[]) { + return del(`/api/v1/knowledge-bases/${kbId}/faq/entries`, { ids }); +} + +export function searchFAQEntries( + kbId: string, + data: { + query_text: string + vector_threshold?: number + match_count?: number + } +) { + return post(`/api/v1/knowledge-bases/${kbId}/faq/search`, data); } \ No newline at end of file diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index e332bee1..fb33a254 100644 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -482,6 +482,7 @@ export default { refresh: 'Refresh', loading: 'Loading...', noData: 'No data', + noMoreData: 'All content loaded', error: 'Error', success: 'Success', warning: 'Warning', @@ -658,6 +659,7 @@ export default { }, knowledgeList: { create: 'Create Knowledge Base', + createFAQ: 'Create FAQ Knowledge Base', uninitializedBanner: 'Some knowledge bases are not initialized. Configure model information in settings before adding documents.', empty: { title: 'No knowledge bases yet', @@ -680,11 +682,16 @@ export default { basic: 'Basic Information', models: 'Model Configuration', chunking: 'Chunking Settings', - advanced: 'Advanced Settings' + advanced: 'Advanced Settings', + faq: 'FAQ Settings' }, basic: { title: 'Basic Information', description: 'Configure the knowledge base name and description', + typeLabel: 'Knowledge Base Type', + typeDocument: 'Document-based', + typeFAQ: 'FAQ Q&A', + typeDescription: 'FAQ suits structured Q&A datasets; document type supports file parsing and chunking.', nameLabel: 'Knowledge Base Name', namePlaceholder: 'Enter knowledge base name', descriptionLabel: 'Knowledge Base Description', @@ -706,7 +713,78 @@ export default { createFailed: 'Failed to create knowledge base', missingId: 'Knowledge base ID is missing', buildDataFailed: 'Failed to construct submission data', - updateSuccess: 'Configuration saved successfully' + updateSuccess: 'Configuration saved successfully', + indexModeRequired: 'Please select an indexing mode for FAQ knowledge bases' + }, + faq: { + title: 'FAQ Configuration', + description: 'Configure indexing strategy and guidance for FAQ-style knowledge bases', + indexModeLabel: 'Indexing Mode', + indexModeDescription: 'Question-only indexing improves precision, question+answer improves recall.', + questionIndexModeLabel: 'Question Indexing Mode', + questionIndexModeDescription: 'Combined: Standard and similar questions are indexed together. Separate: Each question is indexed independently for more precise retrieval but requires more storage.', + entryGuide: 'Each FAQ entry contains a primary question, similar questions, negative examples, and multiple answers. Manage them in the FAQ knowledge base detail view.', + modes: { + questionOnly: 'Questions only', + questionAnswer: 'Question + answer', + combined: 'Combined', + separate: 'Separate' + }, + standardQuestion: 'Primary Question', + answers: 'Answers', + similarQuestions: 'Similar Questions', + negativeQuestions: 'Negative Examples', + editorCreate: 'Create FAQ Entry', + editorEdit: 'Edit FAQ Entry', + addAnswer: 'Add Answer', + answerPlaceholder: 'Enter answer content, supports multi-line text, press Ctrl+Enter or click button to add', + similarPlaceholder: 'Enter similar question and click plus icon to add', + negativePlaceholder: 'Enter negative example and click plus icon to add', + answerRequired: 'Please provide at least one answer', + noAnswer: 'No answers', + noSimilar: 'No similar questions', + noNegative: 'No negative examples', + emptyTitle: 'No FAQ entries', + emptyDesc: 'Click "Create FAQ Entry" above to get started', + searchTest: 'Search Test', + searchTestTitle: 'FAQ Search Test', + queryLabel: 'Query', + queryPlaceholder: 'Enter a question to search', + vectorThresholdLabel: 'Vector Similarity Threshold', + vectorThresholdDesc: 'Range 0-1, default 0.7', + keywordThresholdLabel: 'Keyword Match Threshold', + keywordThresholdDesc: 'Range 0-1, default 0.5', + matchCountLabel: 'Result Count', + matchCountDesc: 'Range 1-50, default 10', + searchButton: 'Search', + searching: 'Searching...', + searchResults: 'Search Results', + noResults: 'No matching FAQ entries found', + score: 'Similarity', + matchType: 'Match Type', + matchTypeEmbedding: 'Vector Match', + matchTypeKeywords: 'Keyword Match', + similarityThresholdLabel: 'Similarity Threshold', + }, + faqImport: { + title: 'Batch Import FAQ', + modeLabel: 'Import Mode', + appendMode: 'Append', + replaceMode: 'Replace existing entries', + fileLabel: 'Select File', + fileTip: 'Supports JSON / CSV / Excel with fields standard_question, answers, similar_questions, negative_questions', + clickToUpload: 'Click to upload file', + dragDropTip: 'or drag and drop file here', + importButton: 'Import FAQ', + deleteSelected: 'Delete Selected', + deleteSuccess: 'Selected entries deleted', + previewCount: '{count} entries parsed', + previewMore: '{count} more entries not shown', + importSuccess: 'Import completed', + parseFailed: 'Failed to parse file', + invalidJSON: 'Invalid JSON format', + unsupportedFormat: 'Unsupported file format', + selectFile: 'Please select a file to import first', }, models: { title: 'Model Configuration', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 5fa68623..40f2e4b5 100644 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -481,6 +481,7 @@ export default { refresh: 'Обновить', loading: 'Загрузка...', noData: 'Нет данных', + noMoreData: 'Весь контент загружен', error: 'Ошибка', success: 'Успешно', warning: 'Предупреждение', @@ -747,6 +748,7 @@ export default { }, knowledgeList: { create: 'Создать базу знаний', + createFAQ: 'Создать FAQ-базу', uninitializedBanner: 'Некоторые базы знаний не инициализированы. Сначала настройте модели в разделе настроек, чтобы добавлять документы.', empty: { title: 'Базы знаний отсутствуют', @@ -769,11 +771,16 @@ export default { basic: 'Основная информация', models: 'Конфигурация моделей', chunking: 'Настройки разбиения', - advanced: 'Дополнительные настройки' + advanced: 'Дополнительные настройки', + faq: 'FAQ настройки' }, basic: { title: 'Основная информация', description: 'Укажите название и описание базы знаний', + typeLabel: 'Тип базы знаний', + typeDocument: 'Документальная', + typeFAQ: 'FAQ (вопрос-ответ)', + typeDescription: 'FAQ подходит для структурированных Q&A; документальный тип поддерживает загрузку файлов и разбиение.', nameLabel: 'Название базы знаний', namePlaceholder: 'Введите название базы знаний', descriptionLabel: 'Описание базы знаний', @@ -795,7 +802,78 @@ export default { createFailed: 'Не удалось создать базу знаний', missingId: 'Отсутствует ID базы знаний', buildDataFailed: 'Не удалось сформировать данные для отправки', - updateSuccess: 'Настройки сохранены' + updateSuccess: 'Настройки сохранены', + indexModeRequired: 'Выберите режим индексации для FAQ базы знаний' + }, + faq: { + title: 'Настройки FAQ', + description: 'Определите стратегию индексации и общие правила для FAQ-базы знаний', + indexModeLabel: 'Режим индексации', + indexModeDescription: 'Только вопросы дают более высокую точность, вопросы+ответы повышают полноту выдачи.', + questionIndexModeLabel: 'Режим индексации вопросов', + questionIndexModeDescription: 'Объединенная: стандартные и похожие вопросы индексируются вместе. Раздельная: каждый вопрос индексируется независимо для более точного поиска, но требует больше места.', + entryGuide: 'Каждый FAQ включает основной вопрос, похожие вопросы, негативные примеры и несколько ответов. Управляйте ими в деталях FAQ-базы.', + modes: { + questionOnly: 'Только вопросы', + questionAnswer: 'Вопрос + ответ', + combined: 'Объединенная', + separate: 'Раздельная' + }, + standardQuestion: 'Основной вопрос', + answers: 'Ответы', + similarQuestions: 'Похожие вопросы', + negativeQuestions: 'Негативные примеры', + editorCreate: 'Создать FAQ запись', + editorEdit: 'Редактировать FAQ запись', + addAnswer: 'Добавить ответ', + answerPlaceholder: 'Введите содержимое ответа, поддерживается многострочный текст, нажмите Ctrl+Enter или нажмите кнопку для добавления', + similarPlaceholder: 'Введите похожий вопрос и нажмите значок плюса для добавления', + negativePlaceholder: 'Введите негативный пример и нажмите значок плюса для добавления', + answerRequired: 'Добавьте хотя бы один ответ', + noAnswer: 'Ответы отсутствуют', + noSimilar: 'Похожие вопросы отсутствуют', + noNegative: 'Нет негативных примеров', + emptyTitle: 'Нет записей FAQ', + emptyDesc: 'Нажмите "Создать FAQ запись" выше, чтобы начать', + searchTest: 'Тест поиска', + searchTestTitle: 'Тест поиска FAQ', + queryLabel: 'Запрос', + queryPlaceholder: 'Введите вопрос для поиска', + vectorThresholdLabel: 'Порог векторного сходства', + vectorThresholdDesc: 'Диапазон 0-1, по умолчанию 0.7', + keywordThresholdLabel: 'Порог совпадения ключевых слов', + keywordThresholdDesc: 'Диапазон 0-1, по умолчанию 0.5', + matchCountLabel: 'Количество результатов', + matchCountDesc: 'Диапазон 1-50, по умолчанию 10', + searchButton: 'Начать поиск', + searching: 'Поиск...', + searchResults: 'Результаты поиска', + noResults: 'Совпадающих записей FAQ не найдено', + score: 'Сходство', + matchType: 'Тип совпадения', + matchTypeEmbedding: 'Векторное совпадение', + matchTypeKeywords: 'Совпадение ключевых слов', + similarityThresholdLabel: 'Порог сходства', + }, + faqImport: { + title: 'Пакетный импорт FAQ', + modeLabel: 'Режим импорта', + appendMode: 'Добавить', + replaceMode: 'Заменить существующие записи', + fileLabel: 'Выберите файл', + fileTip: 'Поддерживаются JSON / CSV / Excel. Поля: standard_question, answers, similar_questions, negative_questions', + clickToUpload: 'Нажмите для загрузки файла', + dragDropTip: 'или перетащите файл сюда', + importButton: 'Импортировать FAQ', + deleteSelected: 'Удалить выбранные', + deleteSuccess: 'Выбранные записи удалены', + previewCount: 'Разобрано записей: {count}', + previewMore: 'Ещё {count} записей не показано', + importSuccess: 'Импорт завершён', + parseFailed: 'Не удалось разобрать файл', + invalidJSON: 'Неверный формат JSON', + unsupportedFormat: 'Формат файла не поддерживается', + selectFile: 'Сначала выберите файл для импорта', }, models: { title: 'Конфигурация моделей', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index eac299cb..debad4af 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -566,6 +566,7 @@ export default { refresh: "刷新", loading: "加载中...", noData: "暂无数据", + noMoreData: "已加载全部内容", error: "错误", success: "成功", warning: "警告", @@ -970,6 +971,7 @@ export default { }, knowledgeList: { create: "新建知识库", + createFAQ: "新建 FAQ 知识库", uninitializedBanner: "部分知识库尚未初始化,需要先在设置中配置模型信息才能添加知识文档", empty: { @@ -994,10 +996,15 @@ export default { models: "模型配置", chunking: "分块设置", advanced: "高级设置", + faq: "FAQ 设置", }, basic: { title: "基本信息", description: "设置知识库的名称和描述信息", + typeLabel: "知识库类型", + typeDocument: "文档型", + typeFAQ: "FAQ 问答", + typeDescription: "FAQ 类型适合结构化问答数据;文档型支持文件解析与分块。", nameLabel: "知识库名称", namePlaceholder: "请输入知识库名称", descriptionLabel: "知识库描述", @@ -1020,6 +1027,77 @@ export default { missingId: "缺少知识库 ID", buildDataFailed: "数据构建失败", updateSuccess: "配置保存成功", + indexModeRequired: "请选择 FAQ 的索引方式", + }, + faq: { + title: "FAQ 配置", + description: "设置 FAQ 知识库的索引策略和问答组织方式", + indexModeLabel: "索引方式", + indexModeDescription: "仅索引问题可提升精度,索引问答可提高召回率", + questionIndexModeLabel: "问题索引方式", + questionIndexModeDescription: "一起索引:标准问和相似问合并索引;分别索引:标准问和每个相似问独立索引,检索更精确但需要更多存储", + entryGuide: "FAQ 条目由标准问、相似问、反例和多个答案组成,可在知识库详情中批量导入、编辑。", + modes: { + questionOnly: "仅标准问/相似问", + questionAnswer: "标准问 + 答案", + combined: "一起索引", + separate: "分别索引", + }, + standardQuestion: "标准问", + answers: "答案", + similarQuestions: "相似问", + negativeQuestions: "反例", + editorCreate: "新增 FAQ 条目", + editorEdit: "编辑 FAQ 条目", + addAnswer: "添加答案", + answerPlaceholder: "请输入答案内容,支持多行文本,按 Ctrl+Enter 或点击按钮添加", + similarPlaceholder: "输入相似问题后点击加号添加", + negativePlaceholder: "输入反例后点击加号添加", + answerRequired: "请至少填写一个答案", + noAnswer: "暂无答案", + noSimilar: "暂无相似问", + noNegative: "暂无反例", + emptyTitle: "暂无 FAQ 条目", + emptyDesc: "点击上方“新增 FAQ 条目”按钮开始创建", + searchTest: "检索测试", + searchTestTitle: "FAQ 检索测试", + queryLabel: "查询内容", + queryPlaceholder: "请输入要检索的问题", + vectorThresholdLabel: "向量相似度阈值", + vectorThresholdDesc: "范围 0-1,默认 0.7", + keywordThresholdLabel: "关键词匹配阈值", + keywordThresholdDesc: "范围 0-1,默认 0.5", + matchCountLabel: "结果数量", + matchCountDesc: "范围 1-50,默认 10", + searchButton: "开始检索", + searching: "检索中...", + searchResults: "检索结果", + noResults: "未找到匹配的 FAQ 条目", + score: "相似度", + matchType: "匹配类型", + matchTypeEmbedding: "向量匹配", + matchTypeKeywords: "关键词匹配", + similarityThresholdLabel: "相似度阈值", + }, + faqImport: { + title: "批量导入 FAQ", + modeLabel: "导入模式", + appendMode: "追加导入", + replaceMode: "替换现有条目", + fileLabel: "选择文件", + fileTip: "支持 JSON / CSV / Excel,字段包含 standard_question、answers、similar_questions、negative_questions", + clickToUpload: "点击上传文件", + dragDropTip: "或拖拽文件到此处", + importButton: "导入 FAQ", + deleteSelected: "批量删除", + deleteSuccess: "选中条目已删除", + previewCount: "共解析 {count} 条记录", + previewMore: "还有 {count} 条未展示", + importSuccess: "导入成功", + parseFailed: "解析文件失败", + invalidJSON: "JSON 文件格式不正确", + unsupportedFormat: "暂不支持该文件格式", + selectFile: "请先选择需要导入的文件", }, models: { title: "模型配置", diff --git a/frontend/src/stores/ui.ts b/frontend/src/stores/ui.ts index c8a5c741..0b79bbaf 100644 --- a/frontend/src/stores/ui.ts +++ b/frontend/src/stores/ui.ts @@ -6,6 +6,7 @@ export const useUIStore = defineStore('ui', { showKBEditorModal: false, kbEditorMode: 'create' as 'create' | 'edit', currentKBId: null as string | null, + kbEditorType: 'document' as 'document' | 'faq', kbEditorInitialSection: null as string | null, settingsInitialSection: null as string | null, settingsInitialSubSection: null as string | null, @@ -39,6 +40,7 @@ export const useUIStore = defineStore('ui', { openKBSettings(kbId: string, initialSection?: string) { this.currentKBId = kbId this.kbEditorMode = 'edit' + this.kbEditorType = 'document' this.kbEditorInitialSection = initialSection || null this.showKBEditorModal = true }, @@ -47,9 +49,10 @@ export const useUIStore = defineStore('ui', { this.openKBSettings(kbId, initialSection) }, - openCreateKB() { + openCreateKB(type: 'document' | 'faq' = 'document') { this.currentKBId = null this.kbEditorMode = 'create' + this.kbEditorType = type this.kbEditorInitialSection = null this.showKBEditorModal = true }, @@ -58,6 +61,7 @@ export const useUIStore = defineStore('ui', { this.showKBEditorModal = false this.currentKBId = null this.kbEditorInitialSection = null + this.kbEditorType = 'document' }, openManualEditor(options: { diff --git a/frontend/src/utils/request.ts b/frontend/src/utils/request.ts index 0d644fba..8062c101 100644 --- a/frontend/src/utils/request.ts +++ b/frontend/src/utils/request.ts @@ -193,6 +193,6 @@ export function put(url: string, data = {}) { return instance.put(url, data); } -export function del(url: string) { - return instance.delete(url); +export function del(url: string, data?: any) { + return instance.delete(url, { data }); } diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index 9fb362a3..9e7d5f85 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -15,12 +15,17 @@ const router = useRouter(); import { batchQueryKnowledge, listKnowledgeFiles, + getKnowledgeBaseById, } from "@/api/knowledge-base/index"; +import FAQEntryManager from './components/FAQEntryManager.vue'; import { formatStringDate } from "@/utils/index"; import { useI18n } from 'vue-i18n'; const route = useRoute(); const { t } = useI18n(); const kbId = computed(() => (route.params as any).kbId as string || ''); +const kbInfo = ref(null); +const kbLoading = ref(false); +const isFAQ = computed(() => (kbInfo.value?.type || '') === 'faq'); let { cardList, total, moreIndex, details, getKnowled, delKnowledge, openMore, onVisibleChange, getCardDetails, getfDetails } = useKnowledgeBase(kbId.value) let isCardDetails = ref(false); let timeout: ReturnType | null = null; @@ -76,10 +81,34 @@ const loadKnowledgeFiles = async (kbIdValue: string) => { } }; +const loadKnowledgeBaseInfo = async (targetKbId: string) => { + if (!targetKbId) { + kbInfo.value = null; + return; + } + kbLoading.value = true; + try { + const res: any = await getKnowledgeBaseById(targetKbId); + kbInfo.value = res?.data || null; + if (!isFAQ.value) { + getKnowled({ page: 1, page_size: pageSize }, targetKbId); + loadKnowledgeFiles(targetKbId); + } else { + cardList.value = []; + total.value = 0; + } + } catch (error) { + console.error('Failed to load knowledge base info:', error); + kbInfo.value = null; + } finally { + kbLoading.value = false; + } +}; + // 监听路由参数变化,重新获取知识库内容 watch(() => kbId.value, (newKbId, oldKbId) => { if (newKbId && newKbId !== oldKbId) { - loadKnowledgeFiles(newKbId); + loadKnowledgeBaseInfo(newKbId); } }, { immediate: false }); @@ -87,7 +116,7 @@ watch(() => kbId.value, (newKbId, oldKbId) => { const handleFileUploaded = (event: CustomEvent) => { const uploadedKbId = event.detail.kbId; console.log('接收到文件上传事件,上传的知识库ID:', uploadedKbId, '当前知识库ID:', kbId.value); - if (uploadedKbId && uploadedKbId === kbId.value) { + if (uploadedKbId && uploadedKbId === kbId.value && !isFAQ.value) { console.log('匹配当前知识库,开始刷新文件列表'); // 如果上传的文件属于当前知识库,使用 loadKnowledgeFiles 刷新文件列表 loadKnowledgeFiles(uploadedKbId); @@ -95,7 +124,7 @@ const handleFileUploaded = (event: CustomEvent) => { }; onMounted(() => { - getKnowled({ page: 1, page_size: pageSize }); + loadKnowledgeBaseInfo(kbId.value); // 监听文件上传事件 window.addEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener); @@ -105,6 +134,7 @@ onUnmounted(() => { window.removeEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener); }); watch(() => cardList.value, (newValue) => { + if (isFAQ.value) return; let analyzeList = []; analyzeList = newValue.filter(item => { return item.parse_status == 'pending' || item.parse_status == 'processing'; @@ -172,12 +202,13 @@ const delCard = (index: number, item: KnowledgeCard) => { }; const manualEditorSuccess = ({ kbId: savedKbId }: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) => { - if (savedKbId === kbId.value) { + if (savedKbId === kbId.value && !isFAQ.value) { loadKnowledgeFiles(savedKbId); } }; const handleManualEdit = (index: number, item: KnowledgeCard) => { + if (isFAQ.value) return; if (cardList.value[index]) { cardList.value[index].isMore = false; } @@ -190,6 +221,7 @@ const handleManualEdit = (index: number, item: KnowledgeCard) => { }; const handleScroll = () => { + if (isFAQ.value) return; const element = knowledgeScroll.value; if (element) { let pageNum = Math.ceil(total.value / pageSize) @@ -256,95 +288,103 @@ async function createNewSession(value: string): Promise {