@lobehub/chat 1.11.9 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/release.yml +2 -1
- package/.github/workflows/test.yml +2 -1
- package/CHANGELOG.md +50 -0
- package/Dockerfile.database +2 -0
- package/docs/self-hosting/advanced/knowledge-base.zh-CN.mdx +65 -0
- package/locales/ar/chat.json +13 -3
- package/locales/ar/components.json +2 -0
- package/locales/bg-BG/chat.json +13 -3
- package/locales/bg-BG/components.json +2 -0
- package/locales/de-DE/chat.json +13 -3
- package/locales/de-DE/components.json +2 -0
- package/locales/en-US/chat.json +13 -3
- package/locales/en-US/components.json +2 -0
- package/locales/es-ES/chat.json +13 -3
- package/locales/es-ES/components.json +2 -0
- package/locales/fr-FR/chat.json +13 -3
- package/locales/fr-FR/components.json +2 -0
- package/locales/it-IT/chat.json +13 -3
- package/locales/it-IT/components.json +2 -0
- package/locales/ja-JP/chat.json +13 -3
- package/locales/ja-JP/components.json +2 -0
- package/locales/ko-KR/chat.json +13 -3
- package/locales/ko-KR/components.json +2 -0
- package/locales/nl-NL/chat.json +13 -3
- package/locales/nl-NL/components.json +2 -0
- package/locales/pl-PL/chat.json +13 -3
- package/locales/pl-PL/components.json +2 -0
- package/locales/pt-BR/chat.json +13 -3
- package/locales/pt-BR/components.json +2 -0
- package/locales/ru-RU/chat.json +13 -3
- package/locales/ru-RU/components.json +2 -0
- package/locales/tr-TR/chat.json +13 -3
- package/locales/tr-TR/components.json +2 -0
- package/locales/vi-VN/chat.json +13 -3
- package/locales/vi-VN/components.json +2 -0
- package/locales/zh-CN/chat.json +13 -3
- package/locales/zh-CN/components.json +2 -0
- package/locales/zh-TW/chat.json +13 -3
- package/locales/zh-TW/components.json +2 -0
- package/package.json +3 -2
- package/scripts/migrateServerDB/docker.cjs +6 -0
- package/scripts/migrateServerDB/errorHint.js +17 -0
- package/scripts/migrateServerDB/index.ts +6 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/FilePreview/FileItem/Content.tsx +37 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/FilePreview/FileItem/index.tsx +87 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/FilePreview/FileItem/style.ts +4 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/FilePreview/FileItem/utils.ts +28 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/FilePreview/FileList.tsx +41 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/FilePreview/index.tsx +40 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/Footer/SendMore.tsx +1 -1
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/Footer/index.tsx +7 -22
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/TextArea.tsx +1 -1
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/index.tsx +2 -4
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/Files/FileItem/File.tsx +72 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/Files/FileItem/Image.tsx +74 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/Files/FileItem/index.tsx +39 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/Files/FileItem/style.ts +1 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/Files/index.tsx +33 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/InputArea/Container.tsx +41 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/InputArea/index.tsx +154 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/Send.tsx +34 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/index.tsx +24 -11
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/components/UploadDetail/UploadStatus.tsx +71 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/components/UploadDetail/index.tsx +49 -0
- package/src/app/(main)/chat/(workspace)/@portal/FilePreview/index.tsx +26 -0
- package/src/app/(main)/chat/(workspace)/@portal/Home/Files/FileList/Item.tsx +53 -0
- package/src/app/(main)/chat/(workspace)/@portal/Home/Files/FileList/index.tsx +50 -0
- package/src/app/(main)/chat/(workspace)/@portal/Home/Files/index.tsx +21 -0
- package/src/app/(main)/chat/(workspace)/@portal/Home/index.tsx +2 -0
- package/src/app/(main)/chat/(workspace)/@portal/router.tsx +4 -0
- package/src/app/(main)/chat/(workspace)/_layout/Desktop/ChatHeader/KnowledgeTag.tsx +41 -0
- package/src/app/(main)/chat/(workspace)/_layout/Desktop/ChatHeader/Tags.tsx +7 -2
- package/src/app/(main)/chat/(workspace)/_layout/Desktop/HotKeys.tsx +1 -1
- package/src/app/(main)/files/(content)/@menu/default.tsx +27 -0
- package/src/app/(main)/files/(content)/@menu/features/FileMenu/index.tsx +97 -0
- package/src/app/(main)/files/(content)/@menu/features/KnowledgeBase/EmptyStatus.tsx +53 -0
- package/src/app/(main)/files/(content)/@menu/features/KnowledgeBase/Item/Content.tsx +175 -0
- package/src/app/(main)/files/(content)/@menu/features/KnowledgeBase/Item/index.tsx +69 -0
- package/src/app/(main)/files/(content)/@menu/features/KnowledgeBase/KnowledgeBaseList.tsx +30 -0
- package/src/app/(main)/files/(content)/@menu/features/KnowledgeBase/SkeletonList.tsx +57 -0
- package/src/app/(main)/files/(content)/@menu/features/KnowledgeBase/index.tsx +54 -0
- package/src/app/(main)/files/(content)/@modal/(.)[id]/FileDetail.tsx +16 -0
- package/src/app/(main)/files/(content)/@modal/(.)[id]/FilePreview.tsx +15 -0
- package/src/app/(main)/files/(content)/@modal/(.)[id]/FullscreenModal.tsx +85 -0
- package/src/app/(main)/files/(content)/@modal/(.)[id]/page.tsx +19 -0
- package/src/app/(main)/files/(content)/@modal/default.tsx +3 -0
- package/src/app/(main)/files/(content)/NotSupportClient.tsx +152 -0
- package/src/app/(main)/files/(content)/_layout/Desktop/index.tsx +28 -0
- package/src/app/(main)/files/(content)/_layout/Mobile.tsx +47 -0
- package/src/app/(main)/files/(content)/_layout/type.ts +7 -0
- package/src/app/(main)/files/(content)/layout.tsx +18 -0
- package/src/app/(main)/files/(content)/page.tsx +14 -0
- package/src/app/(main)/files/[id]/Header.tsx +63 -0
- package/src/app/(main)/files/[id]/page.tsx +44 -0
- package/src/app/(main)/files/features/FileDetail.tsx +93 -0
- package/src/app/(main)/files/hooks/useFileCategory.ts +9 -0
- package/src/app/(main)/files/layout.tsx +12 -0
- package/src/app/(main)/files/loading.tsx +21 -0
- package/src/app/(main)/repos/[id]/@menu/Head/index.tsx +33 -0
- package/src/app/(main)/repos/[id]/@menu/Menu/index.tsx +56 -0
- package/src/app/(main)/repos/[id]/@menu/default.tsx +25 -0
- package/src/app/(main)/repos/[id]/_layout/Desktop/index.tsx +25 -0
- package/src/app/(main)/repos/[id]/_layout/Mobile.tsx +47 -0
- package/src/app/(main)/repos/[id]/_layout/type.ts +6 -0
- package/src/app/(main)/repos/[id]/hooks/useKnowledgeItem.ts +7 -0
- package/src/app/(main)/repos/[id]/layout.tsx +13 -0
- package/src/app/(main)/repos/[id]/page.tsx +18 -0
- package/src/app/(main)/repos/layout.tsx +13 -0
- package/src/app/(main)/repos/page.tsx +5 -0
- package/src/app/trpc/async/[trpc]/route.ts +28 -0
- package/src/chains/abstractChunk.ts +19 -0
- package/src/chains/answerWithContext.ts +34 -0
- package/src/chains/rewriteQuery.ts +22 -0
- package/src/components/DragUpload/index.tsx +6 -99
- package/src/components/DragUpload/useDragUpload.tsx +146 -0
- package/src/components/FeatureList/index.tsx +64 -0
- package/src/components/FileParsingStatus/index.tsx +230 -0
- package/src/components/ImageItem/index.tsx +10 -2
- package/src/components/KnowledgeIcon/index.tsx +28 -0
- package/src/config/app.ts +6 -1
- package/src/config/featureFlags/schema.ts +1 -1
- package/src/const/file.ts +1 -0
- package/src/const/url.ts +1 -0
- package/src/database/client/models/file.ts +8 -2
- package/src/database/server/migrations/0005_pgvector.sql +2 -0
- package/src/database/server/migrations/0006_add_knowledge_base.sql +307 -0
- package/src/database/server/migrations/0007_fix_embedding_table.sql +18 -0
- package/src/database/server/migrations/meta/0005_snapshot.json +2119 -0
- package/src/database/server/migrations/meta/0006_snapshot.json +3006 -0
- package/src/database/server/migrations/meta/0007_snapshot.json +3012 -0
- package/src/database/server/migrations/meta/_journal.json +21 -0
- package/src/database/server/models/__tests__/_test_template.ts +155 -0
- package/src/database/server/models/__tests__/agent.test.ts +226 -0
- package/src/database/server/models/__tests__/asyncTask.test.ts +176 -0
- package/src/database/server/models/__tests__/chunk.test.ts +336 -0
- package/src/database/server/models/__tests__/file.test.ts +317 -29
- package/src/database/server/models/__tests__/fixtures/embedding.ts +568 -0
- package/src/database/server/models/__tests__/knowledgeBase.test.ts +132 -0
- package/src/database/server/models/__tests__/message.test.ts +7 -4
- package/src/database/server/models/_template.ts +10 -1
- package/src/database/server/models/agent.ts +165 -0
- package/src/database/server/models/asyncTask.ts +96 -0
- package/src/database/server/models/chunk.ts +203 -0
- package/src/database/server/models/embedding.ts +50 -0
- package/src/database/server/models/file.ts +231 -12
- package/src/database/server/models/knowledgeBase.ts +94 -0
- package/src/database/server/models/message.ts +156 -30
- package/src/database/server/models/user.ts +12 -1
- package/src/database/server/schemas/lobechat/agent.ts +93 -0
- package/src/database/server/schemas/lobechat/discover.ts +1 -1
- package/src/database/server/schemas/lobechat/file.ts +118 -1
- package/src/database/server/schemas/lobechat/index.ts +5 -1
- package/src/database/server/schemas/lobechat/message.ts +169 -0
- package/src/database/server/schemas/lobechat/rag.ts +53 -0
- package/src/database/server/schemas/lobechat/relations.ts +68 -48
- package/src/database/server/schemas/lobechat/session.ts +77 -0
- package/src/database/server/schemas/lobechat/topic.ts +32 -0
- package/src/database/server/schemas/lobechat/user.ts +40 -25
- package/src/database/server/utils/idGenerator.ts +1 -0
- package/src/features/ChatInput/ActionBar/Clear.tsx +1 -1
- package/src/features/ChatInput/ActionBar/Knowledge/Dropdown.tsx +160 -0
- package/src/features/ChatInput/ActionBar/Knowledge/ListItem.tsx +52 -0
- package/src/features/ChatInput/ActionBar/Knowledge/index.tsx +54 -0
- package/src/features/ChatInput/ActionBar/Tools/index.tsx +1 -1
- package/src/features/ChatInput/ActionBar/Upload/ClientMode.tsx +52 -0
- package/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx +104 -0
- package/src/features/ChatInput/ActionBar/Upload/index.tsx +8 -0
- package/src/features/ChatInput/ActionBar/config.ts +14 -5
- package/src/features/ChatInput/useSend.ts +16 -7
- package/src/features/Conversation/Messages/Assistant/FileChunks/Item/index.tsx +51 -0
- package/src/features/Conversation/Messages/Assistant/FileChunks/Item/style.ts +38 -0
- package/src/features/Conversation/Messages/Assistant/FileChunks/index.tsx +76 -0
- package/src/features/Conversation/Messages/Assistant/index.tsx +13 -4
- package/src/features/Conversation/Messages/Default.tsx +4 -0
- package/src/features/Conversation/Messages/User/BelowMessage.tsx +78 -0
- package/src/features/Conversation/Messages/User/FileListViewer/Item.tsx +53 -0
- package/src/features/Conversation/Messages/User/FileListViewer/index.tsx +21 -0
- package/src/{components/FileList/FileListViewer.tsx → features/Conversation/Messages/User/ImageFileListViewer.tsx} +10 -2
- package/src/features/Conversation/Messages/{User.tsx → User/index.tsx} +11 -2
- package/src/features/Conversation/Messages/index.ts +8 -3
- package/src/features/Conversation/components/ChatItem/index.tsx +33 -10
- package/src/features/Conversation/components/InboxWelcome/QuestionSuggest.tsx +1 -1
- package/src/features/Conversation/types/index.tsx +1 -0
- package/src/features/FileManager/ChunkDrawer/ChunkList/ChunkItem.tsx +61 -0
- package/src/features/FileManager/ChunkDrawer/ChunkList/index.tsx +42 -0
- package/src/features/FileManager/ChunkDrawer/Content.tsx +38 -0
- package/src/features/FileManager/ChunkDrawer/Loading/index.tsx +16 -0
- package/src/features/FileManager/ChunkDrawer/SimilaritySearchList/Item.tsx +62 -0
- package/src/features/FileManager/ChunkDrawer/SimilaritySearchList/index.tsx +31 -0
- package/src/features/FileManager/ChunkDrawer/index.tsx +48 -0
- package/src/features/FileManager/FileList/EmptyStatus.tsx +153 -0
- package/src/features/FileManager/FileList/FileListItem/ChunkTag.tsx +35 -0
- package/src/features/FileManager/FileList/FileListItem/DropdownMenu.tsx +150 -0
- package/src/features/FileManager/FileList/FileListItem/index.tsx +211 -0
- package/src/features/FileManager/FileList/FileSkeleton.tsx +25 -0
- package/src/features/FileManager/FileList/ToolBar/Config.tsx +28 -0
- package/src/features/FileManager/FileList/ToolBar/MultiSelectActions.tsx +152 -0
- package/src/features/FileManager/FileList/ToolBar/index.tsx +114 -0
- package/src/features/FileManager/FileList/index.tsx +143 -0
- package/src/features/FileManager/FileList/useCheckTaskStatus.ts +27 -0
- package/src/features/FileManager/Header/FilesSearchBar.tsx +41 -0
- package/src/features/FileManager/Header/UploadFileButton.tsx +79 -0
- package/src/features/FileManager/Header/index.tsx +39 -0
- package/src/features/FileManager/UploadDock/Item.tsx +124 -0
- package/src/features/FileManager/UploadDock/index.tsx +183 -0
- package/src/features/FileManager/index.tsx +38 -0
- package/src/features/FileSidePanel/index.tsx +79 -0
- package/src/features/FileViewer/NotSupport/index.tsx +54 -0
- package/src/features/FileViewer/PDFViewer/HighlightLayer.tsx +81 -0
- package/src/features/FileViewer/PDFViewer/index.tsx +93 -0
- package/src/features/FileViewer/PDFViewer/style.ts +20 -0
- package/src/features/FileViewer/PDFViewer/useResizeObserver.ts +33 -0
- package/src/features/FileViewer/TXTViewer/index.tsx +41 -0
- package/src/features/FileViewer/index.tsx +45 -0
- package/src/features/KnowledgeBaseModal/AddFilesToKnowledgeBase/SelectForm.tsx +115 -0
- package/src/features/KnowledgeBaseModal/AddFilesToKnowledgeBase/index.tsx +43 -0
- package/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/Action.tsx +103 -0
- package/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/EditCustomPlugin.tsx +55 -0
- package/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/PluginTag.tsx +58 -0
- package/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/index.tsx +70 -0
- package/src/features/KnowledgeBaseModal/AssignKnowledgeBase/List.tsx +49 -0
- package/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Loading.tsx +13 -0
- package/src/features/KnowledgeBaseModal/AssignKnowledgeBase/index.tsx +39 -0
- package/src/features/KnowledgeBaseModal/CreateNew/CreateForm.tsx +73 -0
- package/src/features/KnowledgeBaseModal/CreateNew/index.tsx +35 -0
- package/src/features/KnowledgeBaseModal/index.ts +3 -0
- package/src/libs/langchain/loaders/pdf/index.ts +2 -2
- package/src/libs/trpc/async/asyncAuth.ts +24 -0
- package/src/libs/trpc/async/index.ts +10 -0
- package/src/libs/trpc/async/init.ts +11 -0
- package/src/libs/trpc/client/async.ts +14 -0
- package/src/libs/trpc/client/index.ts +1 -0
- package/src/libs/trpc/client/lambda.ts +9 -0
- package/src/libs/trpc/middleware/keyVaults.ts +18 -0
- package/src/libs/unstructured/__tests__/index.test.ts +0 -10
- package/src/libs/unstructured/index.ts +6 -11
- package/src/locales/default/chat.ts +47 -3
- package/src/locales/default/common.ts +1 -0
- package/src/locales/default/components.ts +2 -0
- package/src/locales/default/error.ts +6 -1
- package/src/locales/default/file.ts +92 -0
- package/src/locales/default/index.ts +4 -0
- package/src/locales/default/knowledgeBase.ts +31 -0
- package/src/locales/default/portal.ts +1 -0
- package/src/middleware.ts +3 -0
- package/src/server/asyncContext.ts +40 -0
- package/src/server/modules/ContentChunk/index.ts +135 -0
- package/src/server/modules/S3/index.ts +30 -5
- package/src/server/routers/async/caller.ts +27 -0
- package/src/server/routers/async/file.ts +247 -0
- package/src/server/routers/async/index.ts +12 -0
- package/src/server/routers/lambda/_template.ts +77 -0
- package/src/server/routers/lambda/agent.ts +159 -0
- package/src/server/routers/lambda/chunk.ts +189 -0
- package/src/server/routers/lambda/file.ts +129 -5
- package/src/server/routers/lambda/index.ts +6 -0
- package/src/server/routers/lambda/knowledgeBase.ts +79 -0
- package/src/server/routers/lambda/message.ts +6 -0
- package/src/server/routers/lambda/session.ts +0 -25
- package/src/server/routers/lambda/user.ts +5 -1
- package/src/server/services/chunk/index.ts +74 -0
- package/src/server/utils/files.ts +9 -0
- package/src/services/__tests__/chat.test.ts +18 -20
- package/src/services/__tests__/{upload.test.ts → upload_legacy.test.ts} +1 -1
- package/src/services/agent.ts +45 -0
- package/src/services/chat.ts +17 -15
- package/src/services/file/client.test.ts +1 -50
- package/src/services/file/client.ts +12 -25
- package/src/services/file/server.ts +25 -3
- package/src/services/file/type.ts +7 -4
- package/src/services/knowledgeBase.ts +34 -0
- package/src/services/message/client.test.ts +1 -1
- package/src/services/message/client.ts +29 -3
- package/src/services/message/index.ts +0 -2
- package/src/services/message/server.ts +9 -3
- package/src/services/message/type.ts +1 -13
- package/src/services/rag.ts +29 -0
- package/src/services/session/server.ts +1 -1
- package/src/services/upload.ts +89 -84
- package/src/services/upload_legacy.ts +104 -0
- package/src/services/user/client.ts +7 -2
- package/src/services/user/server.ts +6 -2
- package/src/services/user/type.ts +3 -2
- package/src/store/agent/slices/chat/action.ts +90 -18
- package/src/store/agent/slices/chat/initialState.ts +1 -0
- package/src/store/agent/slices/chat/selectors.ts +58 -0
- package/src/store/chat/slices/builtinTool/action.test.ts +2 -2
- package/src/store/chat/slices/builtinTool/action.ts +2 -2
- package/src/store/chat/slices/message/action.test.ts +2 -1
- package/src/store/chat/slices/message/action.ts +102 -26
- package/src/store/chat/slices/message/actions/rag.ts +148 -0
- package/src/store/chat/slices/message/initialState.ts +7 -0
- package/src/store/chat/slices/message/reducer.ts +6 -2
- package/src/store/chat/slices/message/selectors.ts +38 -3
- package/src/store/chat/slices/plugin/action.ts +8 -2
- package/src/store/chat/slices/portal/action.ts +8 -0
- package/src/store/chat/slices/portal/initialState.ts +3 -0
- package/src/store/chat/slices/portal/selectors.ts +8 -2
- package/src/store/file/initialState.ts +5 -1
- package/src/store/file/reducers/uploadFileList.ts +133 -0
- package/src/store/file/selectors.ts +3 -0
- package/src/store/file/slices/chat/action.test.ts +90 -90
- package/src/store/file/slices/chat/action.ts +164 -109
- package/src/store/file/slices/chat/initialState.ts +7 -2
- package/src/store/file/slices/chat/selectors.test.ts +84 -61
- package/src/store/file/slices/chat/selectors.ts +22 -32
- package/src/store/file/slices/chunk/action.ts +36 -0
- package/src/store/file/slices/chunk/index.ts +3 -0
- package/src/store/file/slices/chunk/initialState.ts +15 -0
- package/src/store/file/slices/chunk/selectors.ts +10 -0
- package/src/store/file/slices/fileManager/action.ts +187 -0
- package/src/store/file/slices/fileManager/index.ts +3 -0
- package/src/store/file/slices/fileManager/initialState.ts +18 -0
- package/src/store/file/slices/fileManager/selectors.ts +58 -0
- package/src/store/file/slices/tts/action.test.ts +1 -1
- package/src/store/file/slices/tts/action.ts +2 -2
- package/src/store/file/slices/upload/action.ts +164 -0
- package/src/store/file/store.ts +12 -1
- package/src/store/knowledgeBase/index.ts +2 -0
- package/src/store/knowledgeBase/initialState.ts +7 -0
- package/src/store/knowledgeBase/selectors.ts +1 -0
- package/src/store/knowledgeBase/slices/content/action.ts +27 -0
- package/src/store/knowledgeBase/slices/content/index.ts +1 -0
- package/src/store/knowledgeBase/slices/crud/action.ts +78 -0
- package/src/store/knowledgeBase/slices/crud/index.ts +3 -0
- package/src/store/knowledgeBase/slices/crud/initialState.ts +12 -0
- package/src/store/knowledgeBase/slices/crud/selectors.ts +7 -0
- package/src/store/knowledgeBase/store.ts +30 -0
- package/src/store/serverConfig/selectors.test.ts +1 -1
- package/src/store/user/slices/preference/selectors.ts +8 -0
- package/src/store/user/slices/settings/selectors/systemAgent.ts +2 -0
- package/src/tools/dalle/Render/Item/ImageFileItem.tsx +3 -23
- package/src/types/agent/index.ts +9 -0
- package/src/types/asyncTask.ts +31 -0
- package/src/types/chunk/document.ts +9 -0
- package/src/types/chunk/index.ts +52 -0
- package/src/types/files/index.ts +35 -0
- package/src/types/files/list.ts +44 -0
- package/src/types/files/upload.ts +91 -0
- package/src/types/knowledgeBase/index.ts +45 -0
- package/src/types/message/index.ts +54 -5
- package/src/types/rag.ts +16 -0
- package/src/utils/filter.test.ts +2 -0
- package/src/utils/server/auth.ts +23 -0
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Desktop/LocalFiles.tsx +0 -46
- package/src/app/(main)/chat/(workspace)/@conversation/features/ChatInput/Mobile/Files.tsx +0 -19
- package/src/components/FileList/EditableFileList.tsx +0 -47
- package/src/components/FileList/index.ts +0 -2
- package/src/components/FileList/type.tsx +0 -7
- package/src/database/server/schemas/lobechat/chat.ts +0 -331
- package/src/features/ChatInput/ActionBar/FileUpload.tsx +0 -69
- package/src/features/ChatInput/useChatInput.ts +0 -45
- package/src/features/FileList/EditableFileList.tsx +0 -31
- package/src/features/FileList/FileListPreviewer.tsx +0 -17
- package/src/features/FileList/index.tsx +0 -2
- package/src/types/files.ts +0 -42
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
import { eq } from 'drizzle-orm';
|
|
3
|
+
import { desc } from 'drizzle-orm/expressions';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
|
|
6
|
+
import { getTestDBInstance } from '@/database/server/core/dbForTest';
|
|
7
|
+
|
|
8
|
+
import { NewKnowledgeBase, knowledgeBases, users } from '../../schemas/lobechat';
|
|
9
|
+
import { KnowledgeBaseModel } from '../knowledgeBase';
|
|
10
|
+
|
|
11
|
+
let serverDB = await getTestDBInstance();
|
|
12
|
+
|
|
13
|
+
vi.mock('@/database/server/core/db', async () => ({
|
|
14
|
+
get serverDB() {
|
|
15
|
+
return serverDB;
|
|
16
|
+
},
|
|
17
|
+
}));
|
|
18
|
+
|
|
19
|
+
const userId = 'session-group-model-test-user-id';
|
|
20
|
+
const knowledgeBaseModel = new KnowledgeBaseModel(userId);
|
|
21
|
+
|
|
22
|
+
beforeEach(async () => {
|
|
23
|
+
await serverDB.delete(users);
|
|
24
|
+
await serverDB.insert(users).values([{ id: userId }, { id: 'user2' }]);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
afterEach(async () => {
|
|
28
|
+
await serverDB.delete(users).where(eq(users.id, userId));
|
|
29
|
+
await serverDB.delete(knowledgeBases).where(eq(knowledgeBases.userId, userId));
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe('KnowledgeBaseModel', () => {
|
|
33
|
+
describe('create', () => {
|
|
34
|
+
it('should create a new knowledge base', async () => {
|
|
35
|
+
const params = {
|
|
36
|
+
name: 'Test Group',
|
|
37
|
+
} as NewKnowledgeBase;
|
|
38
|
+
|
|
39
|
+
const result = await knowledgeBaseModel.create(params);
|
|
40
|
+
expect(result.id).toBeDefined();
|
|
41
|
+
expect(result).toMatchObject({ ...params, userId });
|
|
42
|
+
|
|
43
|
+
const group = await serverDB.query.knowledgeBases.findFirst({
|
|
44
|
+
where: eq(knowledgeBases.id, result.id),
|
|
45
|
+
});
|
|
46
|
+
expect(group).toMatchObject({ ...params, userId });
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
describe('delete', () => {
|
|
50
|
+
it('should delete a knowledge base by id', async () => {
|
|
51
|
+
const { id } = await knowledgeBaseModel.create({ name: 'Test Group' });
|
|
52
|
+
|
|
53
|
+
await knowledgeBaseModel.delete(id);
|
|
54
|
+
|
|
55
|
+
const group = await serverDB.query.knowledgeBases.findFirst({
|
|
56
|
+
where: eq(knowledgeBases.id, id),
|
|
57
|
+
});
|
|
58
|
+
expect(group).toBeUndefined();
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
describe('deleteAll', () => {
|
|
62
|
+
it('should delete all knowledge bases for the user', async () => {
|
|
63
|
+
await knowledgeBaseModel.create({ name: 'Test Group 1' });
|
|
64
|
+
await knowledgeBaseModel.create({ name: 'Test Group 2' });
|
|
65
|
+
|
|
66
|
+
await knowledgeBaseModel.deleteAll();
|
|
67
|
+
|
|
68
|
+
const userGroups = await serverDB.query.knowledgeBases.findMany({
|
|
69
|
+
where: eq(knowledgeBases.userId, userId),
|
|
70
|
+
});
|
|
71
|
+
expect(userGroups).toHaveLength(0);
|
|
72
|
+
});
|
|
73
|
+
it('should only delete knowledge bases for the user, not others', async () => {
|
|
74
|
+
await knowledgeBaseModel.create({ name: 'Test Group 1' });
|
|
75
|
+
await knowledgeBaseModel.create({ name: 'Test Group 333' });
|
|
76
|
+
|
|
77
|
+
const anotherSessionGroupModel = new KnowledgeBaseModel('user2');
|
|
78
|
+
await anotherSessionGroupModel.create({ name: 'Test Group 2' });
|
|
79
|
+
|
|
80
|
+
await knowledgeBaseModel.deleteAll();
|
|
81
|
+
|
|
82
|
+
const userGroups = await serverDB.query.knowledgeBases.findMany({
|
|
83
|
+
where: eq(knowledgeBases.userId, userId),
|
|
84
|
+
});
|
|
85
|
+
const total = await serverDB.query.knowledgeBases.findMany();
|
|
86
|
+
expect(userGroups).toHaveLength(0);
|
|
87
|
+
expect(total).toHaveLength(1);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
describe('query', () => {
|
|
92
|
+
it('should query knowledge bases for the user', async () => {
|
|
93
|
+
await knowledgeBaseModel.create({ name: 'Test Group 1' });
|
|
94
|
+
await knowledgeBaseModel.create({ name: 'Test Group 2' });
|
|
95
|
+
|
|
96
|
+
const userGroups = await knowledgeBaseModel.query();
|
|
97
|
+
expect(userGroups).toHaveLength(2);
|
|
98
|
+
expect(userGroups[0].name).toBe('Test Group 2');
|
|
99
|
+
expect(userGroups[1].name).toBe('Test Group 1');
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe('findById', () => {
|
|
104
|
+
it('should find a knowledge base by id', async () => {
|
|
105
|
+
const { id } = await knowledgeBaseModel.create({ name: 'Test Group' });
|
|
106
|
+
|
|
107
|
+
const group = await knowledgeBaseModel.findById(id);
|
|
108
|
+
expect(group).toMatchObject({
|
|
109
|
+
id,
|
|
110
|
+
name: 'Test Group',
|
|
111
|
+
userId,
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
describe('update', () => {
|
|
117
|
+
it('should update a knowledge base', async () => {
|
|
118
|
+
const { id } = await knowledgeBaseModel.create({ name: 'Test Group' });
|
|
119
|
+
|
|
120
|
+
await knowledgeBaseModel.update(id, { name: 'Updated Test Group' });
|
|
121
|
+
|
|
122
|
+
const updatedGroup = await serverDB.query.knowledgeBases.findFirst({
|
|
123
|
+
where: eq(knowledgeBases.id, id),
|
|
124
|
+
});
|
|
125
|
+
expect(updatedGroup).toMatchObject({
|
|
126
|
+
id,
|
|
127
|
+
name: 'Updated Test Group',
|
|
128
|
+
userId,
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
});
|
|
@@ -5,11 +5,11 @@ import { getTestDBInstance } from '@/database/server/core/dbForTest';
|
|
|
5
5
|
|
|
6
6
|
import {
|
|
7
7
|
files,
|
|
8
|
-
filesToMessages,
|
|
9
8
|
messagePlugins,
|
|
10
9
|
messageTTS,
|
|
11
10
|
messageTranslates,
|
|
12
11
|
messages,
|
|
12
|
+
messagesFiles,
|
|
13
13
|
sessions,
|
|
14
14
|
topics,
|
|
15
15
|
users,
|
|
@@ -202,7 +202,7 @@ describe('MessageModel', () => {
|
|
|
202
202
|
.insert(messageTTS)
|
|
203
203
|
.values([{ id: '1' }, { id: '2', voice: 'a', fileId: 'f-1', contentMd5: 'abc' }]);
|
|
204
204
|
|
|
205
|
-
await trx.insert(
|
|
205
|
+
await trx.insert(messagesFiles).values([
|
|
206
206
|
{ fileId: 'f-0', messageId: '1' },
|
|
207
207
|
{ fileId: 'f-3', messageId: '1' },
|
|
208
208
|
]);
|
|
@@ -214,10 +214,13 @@ describe('MessageModel', () => {
|
|
|
214
214
|
// 断言结果
|
|
215
215
|
expect(result).toHaveLength(2);
|
|
216
216
|
expect(result[0].id).toBe('1');
|
|
217
|
-
expect(result[0].
|
|
217
|
+
expect(result[0].imageList).toEqual([
|
|
218
|
+
{ alt: 'file-1', id: 'f-0', url: expect.stringContaining('/abc') },
|
|
219
|
+
{ alt: 'file-3', id: 'f-3', url: expect.stringContaining('/abc') },
|
|
220
|
+
]);
|
|
218
221
|
|
|
219
222
|
expect(result[1].id).toBe('2');
|
|
220
|
-
expect(result[1].
|
|
223
|
+
expect(result[1].imageList).toEqual([]);
|
|
221
224
|
});
|
|
222
225
|
|
|
223
226
|
it('should include translate, tts and other extra fields in query result', async () => {
|
|
@@ -13,7 +13,12 @@ export class TemplateModel {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
create = async (params: NewSessionGroup) => {
|
|
16
|
-
|
|
16
|
+
const [result] = await serverDB
|
|
17
|
+
.insert(sessionGroups)
|
|
18
|
+
.values({ ...params, userId: this.userId })
|
|
19
|
+
.returning();
|
|
20
|
+
|
|
21
|
+
return result;
|
|
17
22
|
};
|
|
18
23
|
|
|
19
24
|
delete = async (id: string) => {
|
|
@@ -22,6 +27,10 @@ export class TemplateModel {
|
|
|
22
27
|
.where(and(eq(sessionGroups.id, id), eq(sessionGroups.userId, this.userId)));
|
|
23
28
|
};
|
|
24
29
|
|
|
30
|
+
deleteAll = async () => {
|
|
31
|
+
return serverDB.delete(sessionGroups).where(eq(sessionGroups.userId, this.userId));
|
|
32
|
+
};
|
|
33
|
+
|
|
25
34
|
query = async () => {
|
|
26
35
|
return serverDB.query.sessionGroups.findMany({
|
|
27
36
|
orderBy: [desc(sessionGroups.updatedAt)],
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { inArray } from 'drizzle-orm';
|
|
2
|
+
import { and, desc, eq } from 'drizzle-orm/expressions';
|
|
3
|
+
|
|
4
|
+
import { serverDB } from '@/database/server';
|
|
5
|
+
import {
|
|
6
|
+
agents,
|
|
7
|
+
agentsFiles,
|
|
8
|
+
agentsKnowledgeBases,
|
|
9
|
+
agentsToSessions,
|
|
10
|
+
files,
|
|
11
|
+
knowledgeBases,
|
|
12
|
+
} from '@/database/server/schemas/lobechat';
|
|
13
|
+
|
|
14
|
+
export class AgentModel {
|
|
15
|
+
private userId: string;
|
|
16
|
+
constructor(userId: string) {
|
|
17
|
+
this.userId = userId;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async getAgentConfigById(id: string) {
|
|
21
|
+
const agent = await serverDB.query.agents.findFirst({ where: eq(agents.id, id) });
|
|
22
|
+
|
|
23
|
+
const knowledge = await this.getAgentAssignedKnowledge(id);
|
|
24
|
+
|
|
25
|
+
return { ...agent, ...knowledge };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async getAgentAssignedKnowledge(id: string) {
|
|
29
|
+
const knowledgeBaseResult = await serverDB
|
|
30
|
+
.select({ enabled: agentsKnowledgeBases.enabled, knowledgeBases })
|
|
31
|
+
.from(agentsKnowledgeBases)
|
|
32
|
+
.where(eq(agentsKnowledgeBases.agentId, id))
|
|
33
|
+
.orderBy(desc(agentsKnowledgeBases.createdAt))
|
|
34
|
+
.leftJoin(knowledgeBases, eq(knowledgeBases.id, agentsKnowledgeBases.knowledgeBaseId));
|
|
35
|
+
|
|
36
|
+
const fileResult = await serverDB
|
|
37
|
+
.select({ enabled: agentsFiles.enabled, files })
|
|
38
|
+
.from(agentsFiles)
|
|
39
|
+
.where(eq(agentsFiles.agentId, id))
|
|
40
|
+
.orderBy(desc(agentsFiles.createdAt))
|
|
41
|
+
.leftJoin(files, eq(files.id, agentsFiles.fileId));
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
files: fileResult.map((item) => ({
|
|
45
|
+
...item.files,
|
|
46
|
+
enabled: item.enabled,
|
|
47
|
+
})),
|
|
48
|
+
knowledgeBases: knowledgeBaseResult.map((item) => ({
|
|
49
|
+
...item.knowledgeBases,
|
|
50
|
+
enabled: item.enabled,
|
|
51
|
+
})),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Find agent by session id
|
|
57
|
+
*/
|
|
58
|
+
async findBySessionId(sessionId: string) {
|
|
59
|
+
const item = await serverDB.query.agentsToSessions.findFirst({
|
|
60
|
+
where: eq(agentsToSessions.sessionId, sessionId),
|
|
61
|
+
});
|
|
62
|
+
if (!item) return;
|
|
63
|
+
|
|
64
|
+
const agentId = item.agentId;
|
|
65
|
+
|
|
66
|
+
return this.getAgentConfigById(agentId);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
createAgentKnowledgeBase = async (
|
|
70
|
+
agentId: string,
|
|
71
|
+
knowledgeBaseId: string,
|
|
72
|
+
enabled: boolean = true,
|
|
73
|
+
) => {
|
|
74
|
+
return serverDB
|
|
75
|
+
.insert(agentsKnowledgeBases)
|
|
76
|
+
.values({
|
|
77
|
+
agentId,
|
|
78
|
+
enabled,
|
|
79
|
+
knowledgeBaseId,
|
|
80
|
+
userId: this.userId,
|
|
81
|
+
})
|
|
82
|
+
.execute();
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
deleteAgentKnowledgeBase = async (agentId: string, knowledgeBaseId: string) => {
|
|
86
|
+
return serverDB
|
|
87
|
+
.delete(agentsKnowledgeBases)
|
|
88
|
+
.where(
|
|
89
|
+
and(
|
|
90
|
+
eq(agentsKnowledgeBases.agentId, agentId),
|
|
91
|
+
eq(agentsKnowledgeBases.knowledgeBaseId, knowledgeBaseId),
|
|
92
|
+
eq(agentsKnowledgeBases.userId, this.userId),
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
.execute();
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
toggleKnowledgeBase = async (agentId: string, knowledgeBaseId: string, enabled?: boolean) => {
|
|
99
|
+
return serverDB
|
|
100
|
+
.update(agentsKnowledgeBases)
|
|
101
|
+
.set({ enabled })
|
|
102
|
+
.where(
|
|
103
|
+
and(
|
|
104
|
+
eq(agentsKnowledgeBases.agentId, agentId),
|
|
105
|
+
eq(agentsKnowledgeBases.knowledgeBaseId, knowledgeBaseId),
|
|
106
|
+
eq(agentsKnowledgeBases.userId, this.userId),
|
|
107
|
+
),
|
|
108
|
+
)
|
|
109
|
+
.execute();
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
createAgentFiles = async (agentId: string, fileIds: string[], enabled: boolean = true) => {
|
|
113
|
+
// Exclude the fileIds that already exist in agentsFiles, and then insert them
|
|
114
|
+
const existingFiles = await serverDB
|
|
115
|
+
.select({ id: agentsFiles.fileId })
|
|
116
|
+
.from(agentsFiles)
|
|
117
|
+
.where(
|
|
118
|
+
and(
|
|
119
|
+
eq(agentsFiles.agentId, agentId),
|
|
120
|
+
eq(agentsFiles.userId, this.userId),
|
|
121
|
+
inArray(agentsFiles.fileId, fileIds),
|
|
122
|
+
),
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
const existingFilesIds = new Set(existingFiles.map((item) => item.id));
|
|
126
|
+
|
|
127
|
+
const needToInsertFileIds = fileIds.filter((fileId) => !existingFilesIds.has(fileId));
|
|
128
|
+
|
|
129
|
+
if (needToInsertFileIds.length === 0) return;
|
|
130
|
+
|
|
131
|
+
return serverDB
|
|
132
|
+
.insert(agentsFiles)
|
|
133
|
+
.values(
|
|
134
|
+
needToInsertFileIds.map((fileId) => ({ agentId, enabled, fileId, userId: this.userId })),
|
|
135
|
+
)
|
|
136
|
+
.execute();
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
deleteAgentFile = async (agentId: string, fileId: string) => {
|
|
140
|
+
return serverDB
|
|
141
|
+
.delete(agentsFiles)
|
|
142
|
+
.where(
|
|
143
|
+
and(
|
|
144
|
+
eq(agentsFiles.agentId, agentId),
|
|
145
|
+
eq(agentsFiles.fileId, fileId),
|
|
146
|
+
eq(agentsFiles.userId, this.userId),
|
|
147
|
+
),
|
|
148
|
+
)
|
|
149
|
+
.execute();
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
toggleFile = async (agentId: string, fileId: string, enabled?: boolean) => {
|
|
153
|
+
return serverDB
|
|
154
|
+
.update(agentsFiles)
|
|
155
|
+
.set({ enabled })
|
|
156
|
+
.where(
|
|
157
|
+
and(
|
|
158
|
+
eq(agentsFiles.agentId, agentId),
|
|
159
|
+
eq(agentsFiles.fileId, fileId),
|
|
160
|
+
eq(agentsFiles.userId, this.userId),
|
|
161
|
+
),
|
|
162
|
+
)
|
|
163
|
+
.execute();
|
|
164
|
+
};
|
|
165
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { eq, inArray, lt } from 'drizzle-orm';
|
|
2
|
+
import { and } from 'drizzle-orm/expressions';
|
|
3
|
+
|
|
4
|
+
import { serverDB } from '@/database/server';
|
|
5
|
+
import {
|
|
6
|
+
AsyncTaskError,
|
|
7
|
+
AsyncTaskErrorType,
|
|
8
|
+
AsyncTaskStatus,
|
|
9
|
+
AsyncTaskType,
|
|
10
|
+
} from '@/types/asyncTask';
|
|
11
|
+
|
|
12
|
+
import { AsyncTaskSelectItem, NewAsyncTaskItem, asyncTasks } from '../schemas/lobechat';
|
|
13
|
+
|
|
14
|
+
// set timeout to about 5 minutes, and give 2s padding time
|
|
15
|
+
export const ASYNC_TASK_TIMEOUT = 298 * 1000;
|
|
16
|
+
|
|
17
|
+
export class AsyncTaskModel {
|
|
18
|
+
private userId: string;
|
|
19
|
+
|
|
20
|
+
constructor(userId: string) {
|
|
21
|
+
this.userId = userId;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
create = async (params: Pick<NewAsyncTaskItem, 'type' | 'status'>): Promise<string> => {
|
|
25
|
+
const data = await serverDB
|
|
26
|
+
.insert(asyncTasks)
|
|
27
|
+
.values({ ...params, userId: this.userId })
|
|
28
|
+
.returning();
|
|
29
|
+
|
|
30
|
+
return data[0].id;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
delete = async (id: string) => {
|
|
34
|
+
return serverDB
|
|
35
|
+
.delete(asyncTasks)
|
|
36
|
+
.where(and(eq(asyncTasks.id, id), eq(asyncTasks.userId, this.userId)));
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
findById = async (id: string) => {
|
|
40
|
+
return serverDB.query.asyncTasks.findFirst({ where: and(eq(asyncTasks.id, id)) });
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
update(taskId: string, value: Partial<AsyncTaskSelectItem>) {
|
|
44
|
+
return serverDB
|
|
45
|
+
.update(asyncTasks)
|
|
46
|
+
.set({ ...value, updatedAt: new Date() })
|
|
47
|
+
.where(and(eq(asyncTasks.id, taskId)));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
findByIds = async (taskIds: string[], type: AsyncTaskType): Promise<AsyncTaskSelectItem[]> => {
|
|
51
|
+
let chunkTasks: AsyncTaskSelectItem[] = [];
|
|
52
|
+
|
|
53
|
+
if (taskIds.length > 0) {
|
|
54
|
+
await this.checkTimeoutTasks(taskIds);
|
|
55
|
+
chunkTasks = await serverDB.query.asyncTasks.findMany({
|
|
56
|
+
where: and(inArray(asyncTasks.id, taskIds), eq(asyncTasks.type, type)),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return chunkTasks;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* make the task status to be `error` if the task is not finished in 20 seconds
|
|
65
|
+
*/
|
|
66
|
+
async checkTimeoutTasks(ids: string[]) {
|
|
67
|
+
const tasks = await serverDB
|
|
68
|
+
.select({ id: asyncTasks.id })
|
|
69
|
+
.from(asyncTasks)
|
|
70
|
+
.where(
|
|
71
|
+
and(
|
|
72
|
+
inArray(asyncTasks.id, ids),
|
|
73
|
+
eq(asyncTasks.status, AsyncTaskStatus.Processing),
|
|
74
|
+
lt(asyncTasks.createdAt, new Date(Date.now() - ASYNC_TASK_TIMEOUT)),
|
|
75
|
+
),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
if (tasks.length > 0) {
|
|
79
|
+
await serverDB
|
|
80
|
+
.update(asyncTasks)
|
|
81
|
+
.set({
|
|
82
|
+
error: {
|
|
83
|
+
body: { detail: 'chunking task is timeout, please try again' },
|
|
84
|
+
name: AsyncTaskErrorType.Timeout,
|
|
85
|
+
} as AsyncTaskError,
|
|
86
|
+
status: AsyncTaskStatus.Error,
|
|
87
|
+
})
|
|
88
|
+
.where(
|
|
89
|
+
inArray(
|
|
90
|
+
asyncTasks.id,
|
|
91
|
+
tasks.map((item) => item.id),
|
|
92
|
+
),
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { asc, cosineDistance, count, eq, inArray, sql } from 'drizzle-orm';
|
|
2
|
+
import { and, desc } from 'drizzle-orm/expressions';
|
|
3
|
+
|
|
4
|
+
import { serverDB } from '@/database/server';
|
|
5
|
+
import { ChunkMetadata, FileChunk, SemanticSearchChunk } from '@/types/chunk';
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
NewChunkItem,
|
|
9
|
+
NewUnstructuredChunkItem,
|
|
10
|
+
chunks,
|
|
11
|
+
embeddings,
|
|
12
|
+
fileChunks,
|
|
13
|
+
files,
|
|
14
|
+
unstructuredChunks,
|
|
15
|
+
} from '../schemas/lobechat';
|
|
16
|
+
|
|
17
|
+
export class ChunkModel {
|
|
18
|
+
private userId: string;
|
|
19
|
+
|
|
20
|
+
constructor(userId: string) {
|
|
21
|
+
this.userId = userId;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
bulkCreate = async (params: NewChunkItem[], fileId: string) => {
|
|
25
|
+
return serverDB.transaction(async (trx) => {
|
|
26
|
+
const result = await trx.insert(chunks).values(params).returning();
|
|
27
|
+
|
|
28
|
+
const fileChunksData = result.map((chunk) => ({ chunkId: chunk.id, fileId }));
|
|
29
|
+
|
|
30
|
+
if (fileChunksData.length > 0) {
|
|
31
|
+
await trx.insert(fileChunks).values(fileChunksData);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return result;
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
bulkCreateUnstructuredChunks = async (params: NewUnstructuredChunkItem[]) => {
|
|
39
|
+
return serverDB.insert(unstructuredChunks).values(params);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
delete = async (id: string) => {
|
|
43
|
+
return serverDB.delete(chunks).where(and(eq(chunks.id, id), eq(chunks.userId, this.userId)));
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
findById = async (id: string) => {
|
|
47
|
+
return serverDB.query.chunks.findFirst({
|
|
48
|
+
where: and(eq(chunks.id, id)),
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
async findByFileId(id: string, page = 0) {
|
|
53
|
+
const data = await serverDB
|
|
54
|
+
.select({
|
|
55
|
+
abstract: chunks.abstract,
|
|
56
|
+
createdAt: chunks.createdAt,
|
|
57
|
+
id: chunks.id,
|
|
58
|
+
index: chunks.index,
|
|
59
|
+
metadata: chunks.metadata,
|
|
60
|
+
text: chunks.text,
|
|
61
|
+
type: chunks.type,
|
|
62
|
+
updatedAt: chunks.updatedAt,
|
|
63
|
+
})
|
|
64
|
+
.from(chunks)
|
|
65
|
+
.innerJoin(fileChunks, eq(chunks.id, fileChunks.chunkId))
|
|
66
|
+
.where(and(eq(fileChunks.fileId, id), eq(chunks.userId, this.userId)))
|
|
67
|
+
.limit(20)
|
|
68
|
+
.offset(page * 20)
|
|
69
|
+
.orderBy(asc(chunks.index));
|
|
70
|
+
|
|
71
|
+
return data.map((item) => {
|
|
72
|
+
const metadata = item.metadata as ChunkMetadata;
|
|
73
|
+
|
|
74
|
+
return { ...item, metadata, pageNumber: metadata?.pageNumber } as FileChunk;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async getChunksTextByFileId(id: string): Promise<{ id: string; text: string }[]> {
|
|
79
|
+
const data = await serverDB
|
|
80
|
+
.select()
|
|
81
|
+
.from(chunks)
|
|
82
|
+
.innerJoin(fileChunks, eq(chunks.id, fileChunks.chunkId))
|
|
83
|
+
.where(eq(fileChunks.fileId, id));
|
|
84
|
+
|
|
85
|
+
return data
|
|
86
|
+
.map((item) => item.chunks)
|
|
87
|
+
.map((chunk) => ({ id: chunk.id, text: this.mapChunkText(chunk) }))
|
|
88
|
+
.filter((chunk) => chunk.text) as { id: string; text: string }[];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async countByFileIds(ids: string[]) {
|
|
92
|
+
if (ids.length === 0) return [];
|
|
93
|
+
|
|
94
|
+
return serverDB
|
|
95
|
+
.select({
|
|
96
|
+
count: count(fileChunks.chunkId),
|
|
97
|
+
id: fileChunks.fileId,
|
|
98
|
+
})
|
|
99
|
+
.from(fileChunks)
|
|
100
|
+
.where(inArray(fileChunks.fileId, ids))
|
|
101
|
+
.groupBy(fileChunks.fileId);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async countByFileId(ids: string) {
|
|
105
|
+
const data = await serverDB
|
|
106
|
+
.select({
|
|
107
|
+
count: count(fileChunks.chunkId),
|
|
108
|
+
id: fileChunks.fileId,
|
|
109
|
+
})
|
|
110
|
+
.from(fileChunks)
|
|
111
|
+
.where(eq(fileChunks.fileId, ids))
|
|
112
|
+
.groupBy(fileChunks.fileId);
|
|
113
|
+
|
|
114
|
+
return data[0]?.count ?? 0;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async semanticSearch({
|
|
118
|
+
embedding,
|
|
119
|
+
fileIds,
|
|
120
|
+
}: {
|
|
121
|
+
embedding: number[];
|
|
122
|
+
fileIds: string[] | undefined;
|
|
123
|
+
query: string;
|
|
124
|
+
}) {
|
|
125
|
+
const similarity = sql<number>`1 - (${cosineDistance(embeddings.embeddings, embedding)})`;
|
|
126
|
+
|
|
127
|
+
const data = await serverDB
|
|
128
|
+
.select({
|
|
129
|
+
id: chunks.id,
|
|
130
|
+
index: chunks.index,
|
|
131
|
+
metadata: chunks.metadata,
|
|
132
|
+
similarity,
|
|
133
|
+
text: chunks.text,
|
|
134
|
+
type: chunks.type,
|
|
135
|
+
})
|
|
136
|
+
.from(chunks)
|
|
137
|
+
.leftJoin(embeddings, eq(chunks.id, embeddings.chunkId))
|
|
138
|
+
.leftJoin(fileChunks, eq(chunks.id, fileChunks.chunkId))
|
|
139
|
+
.where(fileIds ? inArray(fileChunks.fileId, fileIds) : undefined)
|
|
140
|
+
.orderBy((t) => desc(t.similarity))
|
|
141
|
+
.limit(30);
|
|
142
|
+
|
|
143
|
+
return data.map(
|
|
144
|
+
(item): SemanticSearchChunk => ({
|
|
145
|
+
...item,
|
|
146
|
+
metadata: item.metadata as ChunkMetadata,
|
|
147
|
+
}),
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async semanticSearchForChat({
|
|
152
|
+
embedding,
|
|
153
|
+
fileIds,
|
|
154
|
+
}: {
|
|
155
|
+
embedding: number[];
|
|
156
|
+
fileIds: string[] | undefined;
|
|
157
|
+
query: string;
|
|
158
|
+
}) {
|
|
159
|
+
const similarity = sql<number>`1 - (${cosineDistance(embeddings.embeddings, embedding)})`;
|
|
160
|
+
|
|
161
|
+
const result = await serverDB
|
|
162
|
+
.select({
|
|
163
|
+
fileId: files.id,
|
|
164
|
+
filename: files.name,
|
|
165
|
+
id: chunks.id,
|
|
166
|
+
index: chunks.index,
|
|
167
|
+
metadata: chunks.metadata,
|
|
168
|
+
similarity,
|
|
169
|
+
text: chunks.text,
|
|
170
|
+
type: chunks.type,
|
|
171
|
+
})
|
|
172
|
+
.from(chunks)
|
|
173
|
+
.leftJoin(embeddings, eq(chunks.id, embeddings.chunkId))
|
|
174
|
+
.leftJoin(fileChunks, eq(chunks.id, fileChunks.chunkId))
|
|
175
|
+
.leftJoin(files, eq(files.id, fileChunks.fileId))
|
|
176
|
+
.where(and(fileIds && fileIds.length > 0 ? inArray(fileChunks.fileId, fileIds) : undefined))
|
|
177
|
+
.orderBy((t) => desc(t.similarity))
|
|
178
|
+
.limit(5);
|
|
179
|
+
|
|
180
|
+
return result.map((item) => {
|
|
181
|
+
return {
|
|
182
|
+
id: item.id,
|
|
183
|
+
index: item.index,
|
|
184
|
+
similarity: item.similarity,
|
|
185
|
+
text: this.mapChunkText(item),
|
|
186
|
+
};
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private mapChunkText = (chunk: { metadata: any; text: string | null; type: string | null }) => {
|
|
191
|
+
let text = chunk.text;
|
|
192
|
+
|
|
193
|
+
if (chunk.type === 'Table') {
|
|
194
|
+
text = `${chunk.text}
|
|
195
|
+
|
|
196
|
+
content in Table html is below:
|
|
197
|
+
${(chunk.metadata as ChunkMetadata).text_as_html}
|
|
198
|
+
`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return text;
|
|
202
|
+
};
|
|
203
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { eq } from 'drizzle-orm';
|
|
2
|
+
import { and } from 'drizzle-orm/expressions';
|
|
3
|
+
|
|
4
|
+
import { serverDB } from '@/database/server';
|
|
5
|
+
|
|
6
|
+
import { NewEmbeddingsItem, embeddings } from '../schemas/lobechat';
|
|
7
|
+
|
|
8
|
+
export class EmbeddingModel {
|
|
9
|
+
private userId: string;
|
|
10
|
+
|
|
11
|
+
constructor(userId: string) {
|
|
12
|
+
this.userId = userId;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
create = async (value: Omit<NewEmbeddingsItem, 'userId'>) => {
|
|
16
|
+
const [item] = await serverDB
|
|
17
|
+
.insert(embeddings)
|
|
18
|
+
.values({ ...value, userId: this.userId })
|
|
19
|
+
.returning();
|
|
20
|
+
|
|
21
|
+
return item.id as string;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
bulkCreate = async (values: Omit<NewEmbeddingsItem, 'userId'>[]) => {
|
|
25
|
+
return serverDB
|
|
26
|
+
.insert(embeddings)
|
|
27
|
+
.values(values.map((item) => ({ ...item, userId: this.userId })))
|
|
28
|
+
.onConflictDoNothing({
|
|
29
|
+
target: [embeddings.chunkId],
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
delete = async (id: string) => {
|
|
34
|
+
return serverDB
|
|
35
|
+
.delete(embeddings)
|
|
36
|
+
.where(and(eq(embeddings.id, id), eq(embeddings.userId, this.userId)));
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
query = async () => {
|
|
40
|
+
return serverDB.query.embeddings.findMany({
|
|
41
|
+
where: eq(embeddings.userId, this.userId),
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
findById = async (id: string) => {
|
|
46
|
+
return serverDB.query.embeddings.findFirst({
|
|
47
|
+
where: and(eq(embeddings.id, id), eq(embeddings.userId, this.userId)),
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
}
|