🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: refactor to use kb search tool (#10340)
Arvin Xu291ff3cc4239
diff --git a/locales/ar/plugin.json b/locales/ar/plugin.jsonindex e1fc545a1f8..c5b78ea9ce6 100644--- a/locales/ar/plugin.json+++ b/locales/ar/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "قراءة محتوى قاعدة المعرفة",+ "searchKnowledgeBase": "البحث في قاعدة المعرفة"+ },+ "title": "قاعدة المعرفة"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "تحرير الملف",+ "getCommandOutput": "الحصول على مخرجات الكود",+ "globLocalFiles": "البحث عن الملفات",+ "grepContent": "البحث في المحتوى",+ "killCommand": "إيقاف تنفيذ الكود",+ "listLocalFiles": "عرض قائمة الملفات",+ "moveLocalFiles": "نقل الملفات",+ "readLocalFile": "قراءة محتوى الملف",+ "renameLocalFile": "إعادة تسمية",+ "runCommand": "تنفيذ الكود",+ "searchLocalFiles": "البحث في الملفات",+ "writeLocalFile": "كتابة إلى الملف"+ },+ "title": "النظام المحلي"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "قراءة محتوى عدة صفحات",+ "crawlSinglePage": "قراءة محتوى الصفحة",+ "search": "البحث في الصفحات"+ },+ "title": "البحث عبر الإنترنت"+ }+ },"confirm": "تأكيد","debug": {"arguments": "معلمات الاستدعاء",@@ -251,23 +285,6 @@"content": "جارٍ استدعاء الإضافة...","plugin": "تشغيل الإضافة..."},- "localSystem": {- "apiName": {- "editLocalFile": "تحرير الملف",- "getCommandOutput": "الحصول على مخرجات الأوامر",- "globLocalFiles": "البحث عن الملفات المطابقة",- "grepContent": "البحث في المحتوى",- "killCommand": "إيقاف تنفيذ الأمر",- "listLocalFiles": "عرض قائمة الملفات",- "moveLocalFiles": "نقل الملفات",- "readLocalFile": "قراءة محتوى الملف",- "renameLocalFile": "إعادة تسمية",- "runCommand": "تشغيل الأمر",- "searchLocalFiles": "بحث في الملفات",- "writeLocalFile": "كتابة في الملف"- },- "title": "النظام المحلي"- },"mcpInstall": {"CHECKING_INSTALLATION": "جارٍ فحص بيئة التثبيت...","COMPLETED": "اكتمل التثبيت",@@ -375,11 +392,6 @@"warning": "⚠️ يرجى التأكد من ثقتك بمصدر هذه الإضافة، الإضافات الخبيثة قد تضر بأمان نظامك."},"search": {- "apiName": {- "crawlMultiPages": "قراءة محتوى عدة صفحات",- "crawlSinglePage": "قراءة محتوى الصفحة",- "search": "البحث في الصفحة"- },"config": {"addKey": "إضافة مفتاح","close": "حذف",diff --git a/locales/ar/tool.json b/locales/ar/tool.jsonindex ea05df3a495..2b7ee02889c 100644--- a/locales/ar/tool.json+++ b/locales/ar/tool.json@@ -14,6 +14,14 @@"images": "الصور:","prompt": "كلمة تلميح"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "عدد الأحرف",+ "lines": "عدد السطور"+ }+ }+ },"localFiles": {"editFile": {"newString": "استبدال بـ",diff --git a/locales/bg-BG/plugin.json b/locales/bg-BG/plugin.jsonindex 2ca85a4aa6c..f88849b9a26 100644--- a/locales/bg-BG/plugin.json+++ b/locales/bg-BG/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Прочети съдържанието на базата знания",+ "searchKnowledgeBase": "Търси в базата знания"+ },+ "title": "База знания"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Редактирай файл",+ "getCommandOutput": "Вземи изхода от кода",+ "globLocalFiles": "Търси съвпадащи файлове",+ "grepContent": "Търси съдържание",+ "killCommand": "Прекрати изпълнението на кода",+ "listLocalFiles": "Преглед на списъка с файлове",+ "moveLocalFiles": "Премести файлове",+ "readLocalFile": "Прочети съдържанието на файла",+ "renameLocalFile": "Преименувай",+ "runCommand": "Изпълни код",+ "searchLocalFiles": "Търси файлове",+ "writeLocalFile": "Запиши файл"+ },+ "title": "Локална система"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Прочети съдържание от няколко страници",+ "crawlSinglePage": "Прочети съдържание от страница",+ "search": "Търси страница"+ },+ "title": "Търсене в интернет"+ }+ },"confirm": "Потвърждавам","debug": {"arguments": "Параметри на извикване",@@ -251,23 +285,6 @@"content": "Извикване на плъгина...","plugin": "Плъгинът работи..."},- "localSystem": {- "apiName": {- "editLocalFile": "Редактиране на файл",- "getCommandOutput": "Получаване на изход от командата",- "globLocalFiles": "Търсене на съвпадащи файлове",- "grepContent": "Търсене на съдържание",- "killCommand": "Прекратяване на изпълнението на командата",- "listLocalFiles": "Преглед на списък с файлове",- "moveLocalFiles": "Преместване на файлове",- "readLocalFile": "Четене на съдържание на файл",- "renameLocalFile": "Преименуване",- "runCommand": "Изпълни код",- "searchLocalFiles": "Търсене на файлове",- "writeLocalFile": "Запис в файл"- },- "title": "Локална система"- },"mcpInstall": {"CHECKING_INSTALLATION": "Проверка на инсталационната среда...","COMPLETED": "Инсталацията е завършена",@@ -375,11 +392,6 @@"warning": "⚠️ Моля, уверете се, че имате доверие на източника на този плъгин, злонамерени плъгини могат да застрашат сигурността на вашата система."},"search": {- "apiName": {- "crawlMultiPages": "Четене на съдържание от множество страници",- "crawlSinglePage": "Четене на съдържание от страница",- "search": "Търсене на страници"- },"config": {"addKey": "Добавяне на ключ","close": "Изтриване",diff --git a/locales/bg-BG/tool.json b/locales/bg-BG/tool.jsonindex bbbdc59d633..84cb17ee4de 100644--- a/locales/bg-BG/tool.json+++ b/locales/bg-BG/tool.json@@ -14,6 +14,14 @@"images": "Изображения:","prompt": "подсказка"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Брой знаци",+ "lines": "Брой редове"+ }+ }+ },"localFiles": {"editFile": {"newString": "Замени с",diff --git a/locales/de-DE/plugin.json b/locales/de-DE/plugin.jsonindex 53d8d1086f6..c0c49f06035 100644--- a/locales/de-DE/plugin.json+++ b/locales/de-DE/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Wissensdatenbank lesen",+ "searchKnowledgeBase": "Wissensdatenbank durchsuchen"+ },+ "title": "Wissensdatenbank"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Datei bearbeiten",+ "getCommandOutput": "Codeausgabe abrufen",+ "globLocalFiles": "Dateien durchsuchen",+ "grepContent": "Inhalt durchsuchen",+ "killCommand": "Codeausführung beenden",+ "listLocalFiles": "Dateiliste anzeigen",+ "moveLocalFiles": "Dateien verschieben",+ "readLocalFile": "Dateiinhalt lesen",+ "renameLocalFile": "Datei umbenennen",+ "runCommand": "Code ausführen",+ "searchLocalFiles": "Dateien suchen",+ "writeLocalFile": "In Datei schreiben"+ },+ "title": "Lokales System"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Inhalte mehrerer Seiten lesen",+ "crawlSinglePage": "Seiteninhalt lesen",+ "search": "Seiten durchsuchen"+ },+ "title": "Websuche"+ }+ },"confirm": "Bestätigen","debug": {"arguments": "Aufrufparameter",@@ -251,23 +285,6 @@"content": "Plugin wird aufgerufen...","plugin": "Plugin läuft..."},- "localSystem": {- "apiName": {- "editLocalFile": "Datei bearbeiten",- "getCommandOutput": "Codeausgabe abrufen",- "globLocalFiles": "Dateien durchsuchen",- "grepContent": "Inhalt durchsuchen",- "killCommand": "Codeausführung beenden",- "listLocalFiles": "Dateiliste anzeigen",- "moveLocalFiles": "Dateien verschieben",- "readLocalFile": "Dateiinhalt lesen",- "renameLocalFile": "Datei umbenennen",- "runCommand": "Befehl ausführen",- "searchLocalFiles": "Dateien suchen",- "writeLocalFile": "Datei schreiben"- },- "title": "Lokales System"- },"mcpInstall": {"CHECKING_INSTALLATION": "Installationsumgebung wird geprüft...","COMPLETED": "Installation abgeschlossen",@@ -375,11 +392,6 @@"warning": "⚠️ Bitte stellen Sie sicher, dass Sie der Quelle dieses Plugins vertrauen. Bösartige Plugins können die Systemsicherheit gefährden."},"search": {- "apiName": {- "crawlMultiPages": "Mehrere Seiteninhalt lesen",- "crawlSinglePage": "Seiteninhalt lesen",- "search": "Seite durchsuchen"- },"config": {"addKey": "Schlüssel hinzufügen","close": "Löschen",diff --git a/locales/de-DE/tool.json b/locales/de-DE/tool.jsonindex 29fa17b0728..3f64270761a 100644--- a/locales/de-DE/tool.json+++ b/locales/de-DE/tool.json@@ -14,6 +14,14 @@"images": "Bilder:","prompt": "Hinweiswort"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Zeichenanzahl",+ "lines": "Zeilenzahl"+ }+ }+ },"localFiles": {"editFile": {"newString": "Ersetzen durch",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex a8fd88eacdc..41ffd9c5f51 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Read Knowledge Base Content",+ "searchKnowledgeBase": "Search Knowledge Base"+ },+ "title": "Knowledge Base"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Edit File",+ "getCommandOutput": "Get Command Output",+ "globLocalFiles": "Search Files by Pattern",+ "grepContent": "Search Content",+ "killCommand": "Terminate Command Execution",+ "listLocalFiles": "View File List",+ "moveLocalFiles": "Move Files",+ "readLocalFile": "Read File Content",+ "renameLocalFile": "Rename File",+ "runCommand": "Execute Command",+ "searchLocalFiles": "Search Files",+ "writeLocalFile": "Write to File"+ },+ "title": "Local System"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Read Multiple Pages",+ "crawlSinglePage": "Read Page Content",+ "search": "Search Web Pages"+ },+ "title": "Web Browsing"+ }+ },"confirm": "Confirm","debug": {"arguments": "Call Arguments",@@ -251,23 +285,6 @@"content": "Calling plugin...","plugin": "Plugin running..."},- "localSystem": {- "apiName": {- "getCommandOutput": "Get Code Output",- "globLocalFiles": "Match Files",- "grepContent": "Search Content",- "killCommand": "Kill Code Execution",- "listLocalFiles": "View File List",- "moveLocalFiles": "Move Files",- "readLocalFile": "Read File Content",- "renameLocalFile": "Rename",- "runCommand": "Run Code",- "searchLocalFiles": "Search Files",- "writeLocalFile": "Write File",- "editLocalFile": "Edit File"- },- "title": "Local System"- },"mcpInstall": {"CHECKING_INSTALLATION": "Checking installation environment...","COMPLETED": "Installation completed",@@ -375,11 +392,6 @@"warning": "⚠️ Please confirm you trust the source of this plugin. Malicious plugins may harm your system security."},"search": {- "apiName": {- "crawlMultiPages": "Read Multiple Pages Content",- "crawlSinglePage": "Read Page Content",- "search": "Search Pages"- },"config": {"addKey": "Add Key","close": "Delete",diff --git a/locales/en-US/tool.json b/locales/en-US/tool.jsonindex 1cf3ad8f427..55f00ab27d8 100644--- a/locales/en-US/tool.json+++ b/locales/en-US/tool.json@@ -14,6 +14,14 @@"images": "Images:","prompt": "Prompt"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Character Count",+ "lines": "Line Count"+ }+ }+ },"localFiles": {"editFile": {"newString": "Replace with",diff --git a/locales/es-ES/plugin.json b/locales/es-ES/plugin.jsonindex e8dcf7907fd..942d0c86b93 100644--- a/locales/es-ES/plugin.json+++ b/locales/es-ES/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Leer contenido de la base de conocimientos",+ "searchKnowledgeBase": "Buscar en la base de conocimientos"+ },+ "title": "Base de conocimientos"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Editar archivo",+ "getCommandOutput": "Obtener salida del código",+ "globLocalFiles": "Buscar archivos por patrón",+ "grepContent": "Buscar contenido",+ "killCommand": "Detener ejecución del código",+ "listLocalFiles": "Ver lista de archivos",+ "moveLocalFiles": "Mover archivos",+ "readLocalFile": "Leer contenido del archivo",+ "renameLocalFile": "Renombrar archivo",+ "runCommand": "Ejecutar código",+ "searchLocalFiles": "Buscar archivos",+ "writeLocalFile": "Escribir archivo"+ },+ "title": "Sistema local"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Leer contenido de múltiples páginas",+ "crawlSinglePage": "Leer contenido de la página",+ "search": "Buscar en la web"+ },+ "title": "Búsqueda en línea"+ }+ },"confirm": "Confirmar","debug": {"arguments": "Parámetros de llamada",@@ -251,23 +285,6 @@"content": "Llamando al plugin...","plugin": "Plugin en ejecución..."},- "localSystem": {- "apiName": {- "editLocalFile": "Editar archivo",- "getCommandOutput": "Obtener salida del código",- "globLocalFiles": "Buscar archivos coincidentes",- "grepContent": "Buscar contenido",- "killCommand": "Detener ejecución del código",- "listLocalFiles": "Ver lista de archivos",- "moveLocalFiles": "Mover archivos",- "readLocalFile": "Leer contenido del archivo",- "renameLocalFile": "Renombrar",- "runCommand": "Ejecutar código",- "searchLocalFiles": "Buscar archivos",- "writeLocalFile": "Escribir archivo"- },- "title": "Sistema local"- },"mcpInstall": {"CHECKING_INSTALLATION": "Verificando entorno de instalación...","COMPLETED": "Instalación completada",@@ -375,11 +392,6 @@"warning": "⚠️ Por favor confirme que confía en la fuente de este plugin, plugins maliciosos pueden comprometer la seguridad de su sistema."},"search": {- "apiName": {- "crawlMultiPages": "Leer contenido de múltiples páginas",- "crawlSinglePage": "Leer contenido de página",- "search": "Buscar página"- },"config": {"addKey": "Agregar clave","close": "Eliminar",diff --git a/locales/es-ES/tool.json b/locales/es-ES/tool.jsonindex af8a6f60397..12d4127955f 100644--- a/locales/es-ES/tool.json+++ b/locales/es-ES/tool.json@@ -14,6 +14,14 @@"images": "Imágenes:","prompt": "Palabra de aviso"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Número de caracteres",+ "lines": "Número de líneas"+ }+ }+ },"localFiles": {"editFile": {"newString": "Reemplazar con",diff --git a/locales/fa-IR/plugin.json b/locales/fa-IR/plugin.jsonindex 1300bc8e165..f0b1c989d0a 100644--- a/locales/fa-IR/plugin.json+++ b/locales/fa-IR/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "خواندن محتوای پایگاه دانش",+ "searchKnowledgeBase": "جستجو در پایگاه دانش"+ },+ "title": "پایگاه دانش"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "ویرایش فایل",+ "getCommandOutput": "دریافت خروجی کد",+ "globLocalFiles": "جستجوی فایلها با الگو",+ "grepContent": "جستجوی محتوا",+ "killCommand": "توقف اجرای کد",+ "listLocalFiles": "مشاهده فهرست فایلها",+ "moveLocalFiles": "انتقال فایلها",+ "readLocalFile": "خواندن محتوای فایل",+ "renameLocalFile": "تغییر نام فایل",+ "runCommand": "اجرای کد",+ "searchLocalFiles": "جستجوی فایلها",+ "writeLocalFile": "نوشتن در فایل"+ },+ "title": "سیستم محلی"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "خواندن محتوای چندین صفحه",+ "crawlSinglePage": "خواندن محتوای صفحه",+ "search": "جستجوی صفحات"+ },+ "title": "جستجوی آنلاین"+ }+ },"confirm": "تأیید","debug": {"arguments": "پارامترهای فراخوانی",@@ -251,23 +285,6 @@"content": "در حال فراخوانی افزونه...","plugin": "افزونه در حال اجرا..."},- "localSystem": {- "apiName": {- "editLocalFile": "ویرایش فایل",- "getCommandOutput": "دریافت خروجی کد",- "globLocalFiles": "جستجوی فایلها با الگو",- "grepContent": "جستجوی محتوا",- "killCommand": "متوقف کردن اجرای کد",- "listLocalFiles": "مشاهده لیست فایلها",- "moveLocalFiles": "جابجایی فایلها",- "readLocalFile": "خواندن محتوای فایل",- "renameLocalFile": "تغییر نام",- "runCommand": "اجرای کد",- "searchLocalFiles": "جستجوی فایلها",- "writeLocalFile": "نوشتن در فایل"- },- "title": "سیستم محلی"- },"mcpInstall": {"CHECKING_INSTALLATION": "در حال بررسی محیط نصب...","COMPLETED": "نصب کامل شد",@@ -375,11 +392,6 @@"warning": "⚠️ لطفاً اطمینان حاصل کنید که به منبع این افزونه اعتماد دارید، افزونههای مخرب ممکن است امنیت سیستم شما را به خطر بیندازند."},"search": {- "apiName": {- "crawlMultiPages": "خواندن محتوای چند صفحه",- "crawlSinglePage": "خواندن محتوای صفحه",- "search": "جستجوی صفحه"- },"config": {"addKey": "افزودن کلید","close": "حذف",diff --git a/locales/fa-IR/tool.json b/locales/fa-IR/tool.jsonindex 5e4397866f7..cb48a7dfc05 100644--- a/locales/fa-IR/tool.json+++ b/locales/fa-IR/tool.json@@ -14,6 +14,14 @@"images": "تصاویر:","prompt": "کلمات کلیدی"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "تعداد نویسهها",+ "lines": "تعداد خطوط"+ }+ }+ },"localFiles": {"editFile": {"newString": "جایگزین با",diff --git a/locales/fr-FR/plugin.json b/locales/fr-FR/plugin.jsonindex d9f2ac8397a..eda3c4777b9 100644--- a/locales/fr-FR/plugin.json+++ b/locales/fr-FR/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Lire le contenu de la base de connaissances",+ "searchKnowledgeBase": "Rechercher dans la base de connaissances"+ },+ "title": "Base de connaissances"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Modifier le fichier",+ "getCommandOutput": "Obtenir la sortie du code",+ "globLocalFiles": "Rechercher des fichiers correspondants",+ "grepContent": "Rechercher dans le contenu",+ "killCommand": "Arrêter l'exécution du code",+ "listLocalFiles": "Afficher la liste des fichiers",+ "moveLocalFiles": "Déplacer les fichiers",+ "readLocalFile": "Lire le contenu du fichier",+ "renameLocalFile": "Renommer",+ "runCommand": "Exécuter le code",+ "searchLocalFiles": "Rechercher des fichiers",+ "writeLocalFile": "Écrire dans le fichier"+ },+ "title": "Système local"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Lire le contenu de plusieurs pages",+ "crawlSinglePage": "Lire le contenu de la page",+ "search": "Rechercher sur la page"+ },+ "title": "Recherche en ligne"+ }+ },"confirm": "Confirmer","debug": {"arguments": "Arguments d'appel",@@ -251,23 +285,6 @@"content": "Appel du plugin en cours...","plugin": "Plugin en cours d'exécution..."},- "localSystem": {- "apiName": {- "editLocalFile": "Modifier le fichier",- "getCommandOutput": "Obtenir la sortie du code",- "globLocalFiles": "Rechercher des fichiers correspondants",- "grepContent": "Rechercher dans le contenu",- "killCommand": "Arrêter l'exécution du code",- "listLocalFiles": "Voir la liste des fichiers",- "moveLocalFiles": "Déplacer les fichiers",- "readLocalFile": "Lire le contenu du fichier",- "renameLocalFile": "Renommer",- "runCommand": "Exécuter le code",- "searchLocalFiles": "Rechercher des fichiers",- "writeLocalFile": "Écrire dans un fichier"- },- "title": "Système local"- },"mcpInstall": {"CHECKING_INSTALLATION": "Vérification de l'environnement d'installation...","COMPLETED": "Installation terminée",@@ -375,11 +392,6 @@"warning": "⚠️ Veuillez confirmer que vous faites confiance à la source de ce plugin, un plugin malveillant pourrait compromettre la sécurité de votre système."},"search": {- "apiName": {- "crawlMultiPages": "Lire le contenu de plusieurs pages",- "crawlSinglePage": "Lire le contenu de la page",- "search": "Rechercher sur la page"- },"config": {"addKey": "Ajouter une clé","close": "Supprimer",diff --git a/locales/fr-FR/tool.json b/locales/fr-FR/tool.jsonindex 08747373cc7..b224eb195f6 100644--- a/locales/fr-FR/tool.json+++ b/locales/fr-FR/tool.json@@ -14,6 +14,14 @@"images": "Images :","prompt": "Mot de rappel"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Nombre de caractères",+ "lines": "Nombre de lignes"+ }+ }+ },"localFiles": {"editFile": {"newString": "Remplacer par",diff --git a/locales/it-IT/plugin.json b/locales/it-IT/plugin.jsonindex 1eb2e08ce03..fb87a7ddb64 100644--- a/locales/it-IT/plugin.json+++ b/locales/it-IT/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Leggi contenuti della base di conoscenza",+ "searchKnowledgeBase": "Cerca nella base di conoscenza"+ },+ "title": "Base di conoscenza"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Modifica file",+ "getCommandOutput": "Ottieni output del codice",+ "globLocalFiles": "Cerca file corrispondenti",+ "grepContent": "Cerca contenuto",+ "killCommand": "Termina esecuzione del codice",+ "listLocalFiles": "Visualizza elenco file",+ "moveLocalFiles": "Sposta file",+ "readLocalFile": "Leggi contenuto del file",+ "renameLocalFile": "Rinomina",+ "runCommand": "Esegui codice",+ "searchLocalFiles": "Cerca file",+ "writeLocalFile": "Scrivi nel file"+ },+ "title": "Sistema locale"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Leggi contenuti da più pagine",+ "crawlSinglePage": "Leggi contenuto della pagina",+ "search": "Cerca nella pagina"+ },+ "title": "Ricerca online"+ }+ },"confirm": "Conferma","debug": {"arguments": "Parametri di chiamata",@@ -251,23 +285,6 @@"content": "Chiamata plugin in corso...","plugin": "Plugin in esecuzione..."},- "localSystem": {- "apiName": {- "editLocalFile": "Modifica file",- "getCommandOutput": "Ottieni output del codice",- "globLocalFiles": "Cerca file corrispondenti",- "grepContent": "Cerca contenuto",- "killCommand": "Termina esecuzione del codice",- "listLocalFiles": "Visualizza lista file",- "moveLocalFiles": "Sposta file",- "readLocalFile": "Leggi contenuto file",- "renameLocalFile": "Rinomina",- "runCommand": "Esegui codice",- "searchLocalFiles": "Cerca file",- "writeLocalFile": "Scrivi file"- },- "title": "Sistema locale"- },"mcpInstall": {"CHECKING_INSTALLATION": "Verifica ambiente di installazione...","COMPLETED": "Installazione completata",@@ -375,11 +392,6 @@"warning": "⚠️ Assicurati di fidarti della fonte di questo plugin, plugin malevoli possono compromettere la sicurezza del sistema."},"search": {- "apiName": {- "crawlMultiPages": "Leggi contenuti di più pagine",- "crawlSinglePage": "Leggi contenuto pagina",- "search": "Cerca pagina"- },"config": {"addKey": "Aggiungi chiave","close": "Elimina",diff --git a/locales/it-IT/tool.json b/locales/it-IT/tool.jsonindex 914e47866aa..e20556c18cf 100644--- a/locales/it-IT/tool.json+++ b/locales/it-IT/tool.json@@ -14,6 +14,14 @@"images": "Immagini:","prompt": "parola chiave"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Numero di caratteri",+ "lines": "Numero di righe"+ }+ }+ },"localFiles": {"editFile": {"newString": "Sostituisci con",diff --git a/locales/ja-JP/plugin.json b/locales/ja-JP/plugin.jsonindex 48bb63896bd..89e3f64e420 100644--- a/locales/ja-JP/plugin.json+++ b/locales/ja-JP/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "ナレッジベースの内容を読み取る",+ "searchKnowledgeBase": "ナレッジベースを検索する"+ },+ "title": "ナレッジベース"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "ファイルを編集する",+ "getCommandOutput": "コードの出力を取得する",+ "globLocalFiles": "ファイルを検索する",+ "grepContent": "内容を検索する",+ "killCommand": "コードの実行を停止する",+ "listLocalFiles": "ファイル一覧を表示する",+ "moveLocalFiles": "ファイルを移動する",+ "readLocalFile": "ファイルの内容を読み取る",+ "renameLocalFile": "ファイル名を変更する",+ "runCommand": "コードを実行する",+ "searchLocalFiles": "ファイルを検索する",+ "writeLocalFile": "ファイルに書き込む"+ },+ "title": "ローカルシステム"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "複数のページの内容を読み取る",+ "crawlSinglePage": "ページの内容を読み取る",+ "search": "ページを検索する"+ },+ "title": "ウェブ検索"+ }+ },"confirm": "確定","debug": {"arguments": "呼び出しパラメータ",@@ -251,23 +285,6 @@"content": "プラグインを呼び出し中...","plugin": "プラグイン実行中..."},- "localSystem": {- "apiName": {- "editLocalFile": "ファイルを編集",- "getCommandOutput": "コード出力を取得",- "globLocalFiles": "ファイルを検索",- "grepContent": "内容を検索",- "killCommand": "コードの実行を停止",- "listLocalFiles": "ファイル一覧を表示",- "moveLocalFiles": "ファイルを移動",- "readLocalFile": "ファイル内容を読み込み",- "renameLocalFile": "ファイル名を変更",- "runCommand": "コードを実行",- "searchLocalFiles": "ファイルを検索",- "writeLocalFile": "ファイルに書き込み"- },- "title": "ローカルシステム"- },"mcpInstall": {"CHECKING_INSTALLATION": "インストール環境を確認中...","COMPLETED": "インストール完了",@@ -375,11 +392,6 @@"warning": "⚠️ このプラグインの出所を信頼していることを確認してください。悪意のあるプラグインはシステムの安全を脅かす可能性があります。"},"search": {- "apiName": {- "crawlMultiPages": "複数ページの内容を読み込み",- "crawlSinglePage": "ページ内容を読み込み",- "search": "ページを検索"- },"config": {"addKey": "キーを追加","close": "削除",diff --git a/locales/ja-JP/tool.json b/locales/ja-JP/tool.jsonindex bfbcbc3da54..8b1d88d767a 100644--- a/locales/ja-JP/tool.json+++ b/locales/ja-JP/tool.json@@ -14,6 +14,14 @@"images": "画像:","prompt": "プロンプト"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "文字数",+ "lines": "行数"+ }+ }+ },"localFiles": {"editFile": {"newString": "置換後の文字列",diff --git a/locales/ko-KR/plugin.json b/locales/ko-KR/plugin.jsonindex 744885c18a2..90eb016d112 100644--- a/locales/ko-KR/plugin.json+++ b/locales/ko-KR/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "지식 베이스 내용 읽기",+ "searchKnowledgeBase": "지식 베이스 검색"+ },+ "title": "지식 베이스"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "파일 편집",+ "getCommandOutput": "코드 출력 가져오기",+ "globLocalFiles": "파일 검색",+ "grepContent": "내용 검색",+ "killCommand": "코드 실행 중지",+ "listLocalFiles": "파일 목록 보기",+ "moveLocalFiles": "파일 이동",+ "readLocalFile": "파일 내용 읽기",+ "renameLocalFile": "파일 이름 변경",+ "runCommand": "코드 실행",+ "searchLocalFiles": "파일 검색",+ "writeLocalFile": "파일 쓰기"+ },+ "title": "로컬 시스템"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "여러 페이지 내용 읽기",+ "crawlSinglePage": "페이지 내용 읽기",+ "search": "웹 페이지 검색"+ },+ "title": "인터넷 검색"+ }+ },"confirm": "확인","debug": {"arguments": "호출 인자",@@ -251,23 +285,6 @@"content": "플러그인 호출 중...","plugin": "플러그인 실행 중..."},- "localSystem": {- "apiName": {- "editLocalFile": "파일 편집",- "getCommandOutput": "코드 출력 가져오기",- "globLocalFiles": "파일 검색",- "grepContent": "내용 검색",- "killCommand": "코드 실행 중지",- "listLocalFiles": "파일 목록 보기",- "moveLocalFiles": "파일 이동",- "readLocalFile": "파일 내용 읽기",- "renameLocalFile": "파일 이름 변경",- "runCommand": "코드 실행",- "searchLocalFiles": "파일 검색",- "writeLocalFile": "파일 쓰기"- },- "title": "로컬 시스템"- },"mcpInstall": {"CHECKING_INSTALLATION": "설치 환경 확인 중...","COMPLETED": "설치 완료",@@ -375,11 +392,6 @@"warning": "⚠️ 이 플러그인의 출처를 신뢰할 수 있는지 확인해 주세요. 악성 플러그인은 시스템 보안에 위협이 될 수 있습니다."},"search": {- "apiName": {- "crawlMultiPages": "여러 페이지 내용 읽기",- "crawlSinglePage": "페이지 내용 읽기",- "search": "페이지 검색"- },"config": {"addKey": "API 키 추가","close": "삭제",diff --git a/locales/ko-KR/tool.json b/locales/ko-KR/tool.jsonindex ccedb3f2349..eecfe2db55d 100644--- a/locales/ko-KR/tool.json+++ b/locales/ko-KR/tool.json@@ -14,6 +14,14 @@"images": "이미지:","prompt": "프롬프트"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "문자 수",+ "lines": "줄 수"+ }+ }+ },"localFiles": {"editFile": {"newString": "다음으로 바꾸기",diff --git a/locales/nl-NL/plugin.json b/locales/nl-NL/plugin.jsonindex 24db58fdfca..b0fcae26e11 100644--- a/locales/nl-NL/plugin.json+++ b/locales/nl-NL/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Kennisbankinhoud lezen",+ "searchKnowledgeBase": "Kennisbank doorzoeken"+ },+ "title": "Kennisbank"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Bestand bewerken",+ "getCommandOutput": "Code-uitvoer ophalen",+ "globLocalFiles": "Bestanden zoeken met patroon",+ "grepContent": "Inhoud doorzoeken",+ "killCommand": "Code-uitvoering beëindigen",+ "listLocalFiles": "Bestandenlijst bekijken",+ "moveLocalFiles": "Bestanden verplaatsen",+ "readLocalFile": "Bestandsinhoud lezen",+ "renameLocalFile": "Bestand hernoemen",+ "runCommand": "Code uitvoeren",+ "searchLocalFiles": "Bestanden doorzoeken",+ "writeLocalFile": "Bestand schrijven"+ },+ "title": "Lokaal systeem"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Inhoud van meerdere pagina's lezen",+ "crawlSinglePage": "Pagina-inhoud lezen",+ "search": "Webpagina's doorzoeken"+ },+ "title": "Online zoeken"+ }+ },"confirm": "Bevestigen","debug": {"arguments": "Aanroepparameters",@@ -251,23 +285,6 @@"content": "Plugin aan het aanroepen...","plugin": "Plugin wordt uitgevoerd..."},- "localSystem": {- "apiName": {- "editLocalFile": "Bestand bewerken",- "getCommandOutput": "Code-uitvoer ophalen",- "globLocalFiles": "Bestanden zoeken",- "grepContent": "Inhoud doorzoeken",- "killCommand": "Code-uitvoering beëindigen",- "listLocalFiles": "Bestandslijst bekijken",- "moveLocalFiles": "Bestanden verplaatsen",- "readLocalFile": "Bestandsinhoud lezen",- "renameLocalFile": "Naam wijzigen",- "runCommand": "Code uitvoeren",- "searchLocalFiles": "Bestanden zoeken",- "writeLocalFile": "Bestand schrijven"- },- "title": "Lokaal systeem"- },"mcpInstall": {"CHECKING_INSTALLATION": "Installatieomgeving controleren...","COMPLETED": "Installatie voltooid",@@ -375,11 +392,6 @@"warning": "⚠️ Bevestig dat u deze pluginbron vertrouwt, kwaadaardige plugins kunnen uw systeem in gevaar brengen."},"search": {- "apiName": {- "crawlMultiPages": "Meerdere pagina's lezen",- "crawlSinglePage": "Pagina-inhoud lezen",- "search": "Pagina zoeken"- },"config": {"addKey": "Sleutel toevoegen","close": "Verwijderen",diff --git a/locales/nl-NL/tool.json b/locales/nl-NL/tool.jsonindex e2358bec8f8..3391586dc60 100644--- a/locales/nl-NL/tool.json+++ b/locales/nl-NL/tool.json@@ -14,6 +14,14 @@"images": "Afbeeldingen:","prompt": "prompt"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Aantal tekens",+ "lines": "Aantal regels"+ }+ }+ },"localFiles": {"editFile": {"newString": "Vervangen door",diff --git a/locales/pl-PL/plugin.json b/locales/pl-PL/plugin.jsonindex 01461763c1c..1e6e05d58b6 100644--- a/locales/pl-PL/plugin.json+++ b/locales/pl-PL/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Odczytaj zawartość bazy wiedzy",+ "searchKnowledgeBase": "Przeszukaj bazę wiedzy"+ },+ "title": "Baza wiedzy"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Edytuj plik",+ "getCommandOutput": "Pobierz wynik polecenia",+ "globLocalFiles": "Wyszukaj pliki",+ "grepContent": "Przeszukaj zawartość",+ "killCommand": "Zatrzymaj wykonywanie kodu",+ "listLocalFiles": "Wyświetl listę plików",+ "moveLocalFiles": "Przenieś pliki",+ "readLocalFile": "Odczytaj zawartość pliku",+ "renameLocalFile": "Zmień nazwę",+ "runCommand": "Wykonaj kod",+ "searchLocalFiles": "Wyszukaj pliki",+ "writeLocalFile": "Zapisz plik"+ },+ "title": "System lokalny"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Odczytaj zawartość wielu stron",+ "crawlSinglePage": "Odczytaj zawartość strony",+ "search": "Wyszukaj stronę"+ },+ "title": "Wyszukiwanie online"+ }+ },"confirm": "Potwierdź","debug": {"arguments": "Argumenty wywołania",@@ -251,23 +285,6 @@"content": "Wywoływanie wtyczki...","plugin": "Wtyczka działa..."},- "localSystem": {- "apiName": {- "editLocalFile": "Edytuj plik",- "getCommandOutput": "Pobierz wynik polecenia",- "globLocalFiles": "Wyszukaj pasujące pliki",- "grepContent": "Przeszukaj zawartość",- "killCommand": "Zatrzymaj wykonywanie polecenia",- "listLocalFiles": "Wyświetl listę plików",- "moveLocalFiles": "Przenieś pliki",- "readLocalFile": "Odczytaj zawartość pliku",- "renameLocalFile": "Zmień nazwę",- "runCommand": "Wykonaj kod",- "searchLocalFiles": "Wyszukaj pliki",- "writeLocalFile": "Zapisz do pliku"- },- "title": "System lokalny"- },"mcpInstall": {"CHECKING_INSTALLATION": "Sprawdzanie środowiska instalacji...","COMPLETED": "Instalacja zakończona",@@ -375,11 +392,6 @@"warning": "⚠️ Upewnij się, że ufasz źródłu tej wtyczki, złośliwe wtyczki mogą zagrozić bezpieczeństwu Twojego systemu."},"search": {- "apiName": {- "crawlMultiPages": "Odczytaj zawartość wielu stron",- "crawlSinglePage": "Odczytaj zawartość strony",- "search": "Wyszukaj stronę"- },"config": {"addKey": "Dodaj klucz","close": "Usuń",diff --git a/locales/pl-PL/tool.json b/locales/pl-PL/tool.jsonindex 5aa51024d76..df6ef886952 100644--- a/locales/pl-PL/tool.json+++ b/locales/pl-PL/tool.json@@ -14,6 +14,14 @@"images": "Obrazy:","prompt": "słowo kluczowe"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Liczba znaków",+ "lines": "Liczba wierszy"+ }+ }+ },"localFiles": {"editFile": {"newString": "Zamień na",diff --git a/locales/pt-BR/plugin.json b/locales/pt-BR/plugin.jsonindex 73c05d5f995..ab425e06180 100644--- a/locales/pt-BR/plugin.json+++ b/locales/pt-BR/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Ler conteúdo da base de conhecimento",+ "searchKnowledgeBase": "Pesquisar na base de conhecimento"+ },+ "title": "Base de Conhecimento"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Editar arquivo",+ "getCommandOutput": "Obter saída do código",+ "globLocalFiles": "Buscar arquivos correspondentes",+ "grepContent": "Pesquisar conteúdo",+ "killCommand": "Encerrar execução do código",+ "listLocalFiles": "Listar arquivos",+ "moveLocalFiles": "Mover arquivos",+ "readLocalFile": "Ler conteúdo do arquivo",+ "renameLocalFile": "Renomear",+ "runCommand": "Executar código",+ "searchLocalFiles": "Pesquisar arquivos",+ "writeLocalFile": "Escrever no arquivo"+ },+ "title": "Sistema Local"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Ler conteúdo de várias páginas",+ "crawlSinglePage": "Ler conteúdo da página",+ "search": "Pesquisar na web"+ },+ "title": "Pesquisa Online"+ }+ },"confirm": "Confirmar","debug": {"arguments": "Parâmetros de chamada",@@ -251,23 +285,6 @@"content": "Chamando plugin...","plugin": "Plugin em execução..."},- "localSystem": {- "apiName": {- "editLocalFile": "Editar arquivo",- "getCommandOutput": "Obter saída do código",- "globLocalFiles": "Buscar arquivos correspondentes",- "grepContent": "Procurar conteúdo",- "killCommand": "Encerrar execução do código",- "listLocalFiles": "Ver lista de arquivos",- "moveLocalFiles": "Mover arquivos",- "readLocalFile": "Ler conteúdo do arquivo",- "renameLocalFile": "Renomear",- "runCommand": "Executar código",- "searchLocalFiles": "Pesquisar arquivos",- "writeLocalFile": "Escrever arquivo"- },- "title": "Sistema Local"- },"mcpInstall": {"CHECKING_INSTALLATION": "Verificando ambiente de instalação...","COMPLETED": "Instalação concluída",@@ -375,11 +392,6 @@"warning": "⚠️ Por favor, confirme que confia na fonte deste plugin, plugins maliciosos podem comprometer a segurança do seu sistema."},"search": {- "apiName": {- "crawlMultiPages": "Ler conteúdo de várias páginas",- "crawlSinglePage": "Ler conteúdo da página",- "search": "Pesquisar página"- },"config": {"addKey": "Adicionar chave","close": "Remover",diff --git a/locales/pt-BR/tool.json b/locales/pt-BR/tool.jsonindex 82fa875f25f..7912bb01ce6 100644--- a/locales/pt-BR/tool.json+++ b/locales/pt-BR/tool.json@@ -14,6 +14,14 @@"images": "Imagens:","prompt": "Palavra-chave"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Número de caracteres",+ "lines": "Número de linhas"+ }+ }+ },"localFiles": {"editFile": {"newString": "Substituir por",diff --git a/locales/ru-RU/plugin.json b/locales/ru-RU/plugin.jsonindex 548feaf9df6..0f963c461e7 100644--- a/locales/ru-RU/plugin.json+++ b/locales/ru-RU/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Чтение содержимого базы знаний",+ "searchKnowledgeBase": "Поиск в базе знаний"+ },+ "title": "База знаний"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Редактировать файл",+ "getCommandOutput": "Получить вывод команды",+ "globLocalFiles": "Поиск файлов по шаблону",+ "grepContent": "Поиск по содержимому",+ "killCommand": "Остановить выполнение кода",+ "listLocalFiles": "Просмотр списка файлов",+ "moveLocalFiles": "Переместить файлы",+ "readLocalFile": "Чтение содержимого файла",+ "renameLocalFile": "Переименовать",+ "runCommand": "Выполнить код",+ "searchLocalFiles": "Поиск файлов",+ "writeLocalFile": "Запись в файл"+ },+ "title": "Локальная система"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Чтение содержимого нескольких страниц",+ "crawlSinglePage": "Чтение содержимого страницы",+ "search": "Поиск по страницам"+ },+ "title": "Поиск в интернете"+ }+ },"confirm": "Подтвердить","debug": {"arguments": "Аргументы вызова",@@ -251,23 +285,6 @@"content": "Вызов плагина...","plugin": "Плагин работает..."},- "localSystem": {- "apiName": {- "editLocalFile": "Редактировать файл",- "getCommandOutput": "Получить вывод команды",- "globLocalFiles": "Поиск файлов по шаблону",- "grepContent": "Поиск по содержимому",- "killCommand": "Прервать выполнение команды",- "listLocalFiles": "Просмотр списка файлов",- "moveLocalFiles": "Перемещение файлов",- "readLocalFile": "Чтение содержимого файла",- "renameLocalFile": "Переименование",- "runCommand": "Выполнить код",- "searchLocalFiles": "Поиск файлов",- "writeLocalFile": "Запись в файл"- },- "title": "Локальная система"- },"mcpInstall": {"CHECKING_INSTALLATION": "Проверка среды установки...","COMPLETED": "Установка завершена",@@ -375,11 +392,6 @@"warning": "⚠️ Пожалуйста, убедитесь, что вы доверяете источнику этого плагина, вредоносные плагины могут угрожать безопасности вашей системы."},"search": {- "apiName": {- "crawlMultiPages": "Чтение содержимого нескольких страниц",- "crawlSinglePage": "Чтение содержимого страницы",- "search": "Поиск по странице"- },"config": {"addKey": "Добавить ключ","close": "Удалить",diff --git a/locales/ru-RU/tool.json b/locales/ru-RU/tool.jsonindex f9008d031ce..9316b9cb320 100644--- a/locales/ru-RU/tool.json+++ b/locales/ru-RU/tool.json@@ -14,6 +14,14 @@"images": "Изображения:","prompt": "подсказка"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Количество символов",+ "lines": "Количество строк"+ }+ }+ },"localFiles": {"editFile": {"newString": "Заменить на",diff --git a/locales/tr-TR/plugin.json b/locales/tr-TR/plugin.jsonindex e4a3609337f..26b161a209f 100644--- a/locales/tr-TR/plugin.json+++ b/locales/tr-TR/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Bilgi tabanını oku",+ "searchKnowledgeBase": "Bilgi tabanında ara"+ },+ "title": "Bilgi Tabanı"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Dosyayı düzenle",+ "getCommandOutput": "Komut çıktısını al",+ "globLocalFiles": "Dosyaları desenle ara",+ "grepContent": "İçerikte ara",+ "killCommand": "Komut çalışmasını durdur",+ "listLocalFiles": "Dosya listesini görüntüle",+ "moveLocalFiles": "Dosyaları taşı",+ "readLocalFile": "Dosya içeriğini oku",+ "renameLocalFile": "Yeniden adlandır",+ "runCommand": "Komut çalıştır",+ "searchLocalFiles": "Dosyalarda ara",+ "writeLocalFile": "Dosyaya yaz"+ },+ "title": "Yerel Sistem"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Birden fazla sayfanın içeriğini oku",+ "crawlSinglePage": "Sayfa içeriğini oku",+ "search": "Sayfada ara"+ },+ "title": "İnternette Arama"+ }+ },"confirm": "Onayla","debug": {"arguments": "Çağrı parametreleri",@@ -251,23 +285,6 @@"content": "Eklenti çağrılıyor...","plugin": "Eklenti çalışıyor..."},- "localSystem": {- "apiName": {- "editLocalFile": "Dosyayı Düzenle",- "getCommandOutput": "Komut Çıktısını Al",- "globLocalFiles": "Dosyaları Ara",- "grepContent": "İçeriği Ara",- "killCommand": "Komut Yürütmesini Durdur",- "listLocalFiles": "Dosya listesini görüntüle",- "moveLocalFiles": "Dosya taşı",- "readLocalFile": "Dosya içeriğini oku",- "renameLocalFile": "Dosya adını değiştir",- "runCommand": "Komutu Çalıştır",- "searchLocalFiles": "Dosya ara",- "writeLocalFile": "Dosyaya yaz"- },- "title": "Yerel Sistem"- },"mcpInstall": {"CHECKING_INSTALLATION": "Kurulum ortamı kontrol ediliyor...","COMPLETED": "Kurulum tamamlandı",@@ -375,11 +392,6 @@"warning": "⚠️ Lütfen bu eklentinin kaynağına güvendiğinizden emin olun, kötü amaçlı eklentiler sistem güvenliğinizi tehlikeye atabilir."},"search": {- "apiName": {- "crawlMultiPages": "Birden fazla sayfa içeriği oku",- "crawlSinglePage": "Sayfa içeriği oku",- "search": "Sayfa ara"- },"config": {"addKey": "Anahtar ekle","close": "Sil",diff --git a/locales/tr-TR/tool.json b/locales/tr-TR/tool.jsonindex fd3d100af7b..f83127c7b95 100644--- a/locales/tr-TR/tool.json+++ b/locales/tr-TR/tool.json@@ -14,6 +14,14 @@"images": "Görseller:","prompt": "İpucu"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Karakter Sayısı",+ "lines": "Satır Sayısı"+ }+ }+ },"localFiles": {"editFile": {"newString": "Şununla değiştir",diff --git a/locales/vi-VN/plugin.json b/locales/vi-VN/plugin.jsonindex daa6208e5a2..9d4f8ead6e8 100644--- a/locales/vi-VN/plugin.json+++ b/locales/vi-VN/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "Đọc nội dung cơ sở tri thức",+ "searchKnowledgeBase": "Tìm kiếm trong cơ sở tri thức"+ },+ "title": "Cơ sở tri thức"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "Chỉnh sửa tệp",+ "getCommandOutput": "Lấy kết quả mã lệnh",+ "globLocalFiles": "Tìm kiếm tệp theo mẫu",+ "grepContent": "Tìm kiếm nội dung",+ "killCommand": "Dừng thực thi mã lệnh",+ "listLocalFiles": "Xem danh sách tệp",+ "moveLocalFiles": "Di chuyển tệp",+ "readLocalFile": "Đọc nội dung tệp",+ "renameLocalFile": "Đổi tên tệp",+ "runCommand": "Thực thi mã lệnh",+ "searchLocalFiles": "Tìm kiếm tệp",+ "writeLocalFile": "Ghi nội dung vào tệp"+ },+ "title": "Hệ thống cục bộ"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "Đọc nội dung nhiều trang",+ "crawlSinglePage": "Đọc nội dung trang",+ "search": "Tìm kiếm trang"+ },+ "title": "Tìm kiếm trực tuyến"+ }+ },"confirm": "Xác nhận","debug": {"arguments": "Tham số gọi",@@ -251,23 +285,6 @@"content": "Đang gọi plugin...","plugin": "Plugin đang chạy..."},- "localSystem": {- "apiName": {- "editLocalFile": "Chỉnh sửa tệp",- "getCommandOutput": "Lấy đầu ra mã lệnh",- "globLocalFiles": "Tìm kiếm tệp",- "grepContent": "Tìm kiếm nội dung",- "killCommand": "Dừng thực thi mã",- "listLocalFiles": "Xem danh sách tệp",- "moveLocalFiles": "Di chuyển tệp",- "readLocalFile": "Đọc nội dung tệp",- "renameLocalFile": "Đổi tên",- "runCommand": "Chạy mã",- "searchLocalFiles": "Tìm kiếm tệp",- "writeLocalFile": "Ghi tệp"- },- "title": "Hệ thống cục bộ"- },"mcpInstall": {"CHECKING_INSTALLATION": "Đang kiểm tra môi trường cài đặt...","COMPLETED": "Hoàn thành cài đặt",@@ -375,11 +392,6 @@"warning": "⚠️ Vui lòng xác nhận bạn tin tưởng nguồn plugin này, plugin độc hại có thể gây nguy hiểm cho hệ thống của bạn."},"search": {- "apiName": {- "crawlMultiPages": "Đọc nội dung nhiều trang",- "crawlSinglePage": "Đọc nội dung trang",- "search": "Tìm kiếm trang"- },"config": {"addKey": "Thêm khóa bí mật","close": "Xóa",diff --git a/locales/vi-VN/tool.json b/locales/vi-VN/tool.jsonindex e046cd99d6b..169fb1da058 100644--- a/locales/vi-VN/tool.json+++ b/locales/vi-VN/tool.json@@ -14,6 +14,14 @@"images": "Hình ảnh:","prompt": "Từ khóa"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "Số ký tự",+ "lines": "Số dòng"+ }+ }+ },"localFiles": {"editFile": {"newString": "Thay thế bằng",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 1350a4ae762..547458fa9e6 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "读取知识库内容",+ "searchKnowledgeBase": "搜索知识库"+ },+ "title": "知识库"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "编辑文件",+ "getCommandOutput": "获取代码输出",+ "globLocalFiles": "匹配搜索文件",+ "grepContent": "搜索内容",+ "killCommand": "终止代码执行",+ "listLocalFiles": "查看文件列表",+ "moveLocalFiles": "移动文件",+ "readLocalFile": "读取文件内容",+ "renameLocalFile": "重命名",+ "runCommand": "执行代码",+ "searchLocalFiles": "搜索文件",+ "writeLocalFile": "写入文件"+ },+ "title": "本地系统"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "读取多个页面内容",+ "crawlSinglePage": "读取页面内容",+ "search": "搜索页面"+ },+ "title": "联网搜索"+ }+ },"confirm": "确定","debug": {"arguments": "调用参数",@@ -251,23 +285,6 @@"content": "调用插件中...","plugin": "插件运行中..."},- "localSystem": {- "apiName": {- "editLocalFile": "编辑文件",- "getCommandOutput": "获取代码输出",- "globLocalFiles": "匹配搜索文件",- "grepContent": "搜索内容",- "killCommand": "终止代码执行",- "listLocalFiles": "查看文件列表",- "moveLocalFiles": "移动文件",- "readLocalFile": "读取文件内容",- "renameLocalFile": "重命名",- "runCommand": "执行代码",- "searchLocalFiles": "搜索文件",- "writeLocalFile": "写入文件"- },- "title": "本地系统"- },"mcpInstall": {"CHECKING_INSTALLATION": "检查安装环境...","COMPLETED": "安装完成",@@ -375,11 +392,6 @@"warning": "⚠️ 请确认您信任此插件的来源,恶意插件可能会危害您的系统安全。"},"search": {- "apiName": {- "crawlMultiPages": "读取多个页面内容",- "crawlSinglePage": "读取页面内容",- "search": "搜索页面"- },"config": {"addKey": "添加秘钥","close": "删除",diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.jsonindex f816360d11e..39fa95c10dc 100644--- a/locales/zh-CN/tool.json+++ b/locales/zh-CN/tool.json@@ -14,6 +14,14 @@"images": "图片:","prompt": "提示词"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "字符数",+ "lines": "行数"+ }+ }+ },"localFiles": {"editFile": {"newString": "替换为",diff --git a/locales/zh-TW/plugin.json b/locales/zh-TW/plugin.jsonindex 57e0b58a3ba..49a86b79b93 100644--- a/locales/zh-TW/plugin.json+++ b/locales/zh-TW/plugin.json@@ -1,4 +1,38 @@{+ "builtins": {+ "lobe-knowledge-base": {+ "apiName": {+ "readKnowledge": "讀取知識庫內容",+ "searchKnowledgeBase": "搜尋知識庫"+ },+ "title": "知識庫"+ },+ "lobe-local-system": {+ "apiName": {+ "editLocalFile": "編輯檔案",+ "getCommandOutput": "取得程式碼輸出",+ "globLocalFiles": "匹配搜尋檔案",+ "grepContent": "搜尋內容",+ "killCommand": "終止程式碼執行",+ "listLocalFiles": "查看檔案清單",+ "moveLocalFiles": "移動檔案",+ "readLocalFile": "讀取檔案內容",+ "renameLocalFile": "重新命名",+ "runCommand": "執行程式碼",+ "searchLocalFiles": "搜尋檔案",+ "writeLocalFile": "寫入檔案"+ },+ "title": "本機系統"+ },+ "lobe-web-browsing": {+ "apiName": {+ "crawlMultiPages": "讀取多個頁面內容",+ "crawlSinglePage": "讀取頁面內容",+ "search": "搜尋頁面"+ },+ "title": "網路搜尋"+ }+ },"confirm": "確定","debug": {"arguments": "調用參數",@@ -251,23 +285,6 @@"content": "調用插件中...","plugin": "插件運行中..."},- "localSystem": {- "apiName": {- "editLocalFile": "編輯檔案",- "getCommandOutput": "取得程式輸出",- "globLocalFiles": "匹配搜尋檔案",- "grepContent": "搜尋內容",- "killCommand": "終止程式執行",- "listLocalFiles": "查看檔案列表",- "moveLocalFiles": "移動檔案",- "readLocalFile": "讀取檔案內容",- "renameLocalFile": "重新命名",- "runCommand": "執行程式碼",- "searchLocalFiles": "搜尋檔案",- "writeLocalFile": "寫入檔案"- },- "title": "本機系統"- },"mcpInstall": {"CHECKING_INSTALLATION": "檢查安裝環境...","COMPLETED": "安裝完成",@@ -375,11 +392,6 @@"warning": "⚠️ 請確認您信任此插件的來源,惡意插件可能會危害您的系統安全。"},"search": {- "apiName": {- "crawlMultiPages": "讀取多個頁面內容",- "crawlSinglePage": "讀取頁面內容",- "search": "搜尋頁面"- },"config": {"addKey": "添加密鑰","close": "刪除",diff --git a/locales/zh-TW/tool.json b/locales/zh-TW/tool.jsonindex 328fab6ae7a..954c017bfea 100644--- a/locales/zh-TW/tool.json+++ b/locales/zh-TW/tool.json@@ -14,6 +14,14 @@"images": "圖片:","prompt": "提示詞"},+ "lobe-knowledge-base": {+ "readKnowledge": {+ "meta": {+ "chars": "字元數",+ "lines": "行數"+ }+ }+ },"localFiles": {"editFile": {"newString": "取代為",diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.tsnew file mode 100644index 00000000000..6e26359066e--- /dev/null+++ b/packages/database/src/models/__tests__/document.test.ts@@ -0,0 +1,149 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { documents, files, users } from '../../schemas';+import { LobeChatDatabase } from '../../type';+import { DocumentModel } from '../document';+import { FileModel } from '../file';+import { getTestDB } from './_util';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'document-model-test-user-id';+const userId2 = 'document-model-test-user-id-2';+const documentModel = new DocumentModel(serverDB, userId);+const documentModel2 = new DocumentModel(serverDB, userId2);+const fileModel = new FileModel(serverDB, userId);+const fileModel2 = new FileModel(serverDB, userId2);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);+});++afterEach(async () => {+ await serverDB.delete(users);+ await serverDB.delete(files);+ await serverDB.delete(documents);+});++// Helper to create a minimal valid document+const createTestDocument = async (model: DocumentModel, fModel: FileModel, content: string) => {+ const { id: fileId } = await fModel.create({+ fileType: 'text/plain',+ name: 'test.txt',+ size: 100,+ url: 'https://example.com/test.txt',+ });++ // Fetch the file to get complete data+ const file = await fModel.findById(fileId);+ if (!file) throw new Error('File not found after creation');++ const { id } = await model.create({+ content,+ fileId: file.id,+ fileType: 'text/plain',+ source: file.url,+ sourceType: 'file',+ totalCharCount: content.length,+ totalLineCount: content.split('\n').length,+ });++ return { documentId: id, file };+};++describe('DocumentModel', () => {+ describe('findByFileId', () => {+ it('should find document by fileId', async () => {+ const { documentId, file } = await createTestDocument(+ documentModel,+ fileModel,+ 'Test content for file',+ );++ const found = await documentModel.findByFileId(file.id);+ expect(found).toBeDefined();+ expect(found?.id).toBe(documentId);+ expect(found?.fileId).toBe(file.id);+ expect(found?.content).toBe('Test content for file');+ });++ it('should not find document from another user', async () => {+ const { file } = await createTestDocument(documentModel, fileModel, 'Test content');++ // Try to find with another user's model+ const found = await documentModel2.findByFileId(file.id);+ expect(found).toBeUndefined();+ });++ it('should return undefined for non-existent fileId', async () => {+ const found = await documentModel.findByFileId('non-existent-file-id');+ expect(found).toBeUndefined();+ });++ it('should return the first document when multiple documents exist for same file', async () => {+ const { id: fileId } = await fileModel.create({+ fileType: 'text/plain',+ name: 'test.txt',+ size: 100,+ url: 'https://example.com/test.txt',+ });++ const file = await fileModel.findById(fileId);+ if (!file) throw new Error('File not found after creation');++ const { id: firstId } = await documentModel.create({+ content: 'First document',+ fileId: file.id,+ fileType: 'text/plain',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 14,+ totalLineCount: 1,+ });++ await documentModel.create({+ content: 'Second document',+ fileId: file.id,+ fileType: 'text/plain',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 15,+ totalLineCount: 1,+ });++ const found = await documentModel.findByFileId(file.id);+ expect(found).toBeDefined();+ // Should return the first created document+ expect(found?.id).toBe(firstId);+ });++ it('should handle different file types', async () => {+ const { id: pdfFileId } = await fileModel.create({+ fileType: 'application/pdf',+ name: 'document.pdf',+ size: 5000,+ url: 'https://example.com/document.pdf',+ });++ const pdfFile = await fileModel.findById(pdfFileId);+ if (!pdfFile) throw new Error('File not found after creation');++ await documentModel.create({+ content: 'PDF content',+ fileId: pdfFile.id,+ fileType: 'application/pdf',+ source: pdfFile.url,+ sourceType: 'file',+ totalCharCount: 11,+ totalLineCount: 1,+ });++ const found = await documentModel.findByFileId(pdfFile.id);+ expect(found).toBeDefined();+ expect(found?.fileType).toBe('application/pdf');+ expect(found?.content).toBe('PDF content');+ });+ });+});diff --git a/packages/database/src/models/chunk.ts b/packages/database/src/models/chunk.tsindex 7324bd3197d..f5b0bb30dc3 100644--- a/packages/database/src/models/chunk.ts+++ b/packages/database/src/models/chunk.ts@@ -181,10 +181,12 @@ export class ChunkModel {semanticSearchForChat = async ({embedding,fileIds,+ topK = 15,}: {embedding: number[];fileIds: string[] | undefined;query: string;+ topK?: number;}) => {const similarity = sql<number>`1 - (${cosineDistance(embeddings.embeddings, embedding)})`;@@ -210,7 +212,7 @@ export class ChunkModel {.where(inArray(fileChunks.fileId, fileIds)).orderBy((t) => desc(t.similarity))// Relaxed to 15 for now- .limit(15);+ .limit(topK);return result.map((item) => {return {diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex a6f34a2fbd8..20cb1182015 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -40,7 +40,13 @@ export class DocumentModel {findById = async (id: string): Promise<DocumentItem | undefined> => {return this.db.query.documents.findFirst({- where: and(eq(documents.id, id), eq(documents.userId, this.userId)),+ where: and(eq(documents.userId, this.userId), eq(documents.id, id)),+ });+ };++ findByFileId = async (fileId: string) => {+ return this.db.query.documents.findFirst({+ where: and(eq(documents.userId, this.userId), eq(documents.fileId, fileId)),});};@@ -48,6 +54,6 @@ export class DocumentModel {return this.db.update(documents).set({ ...value, updatedAt: new Date() })- .where(and(eq(documents.id, id), eq(documents.userId, this.userId)));+ .where(and(eq(documents.userId, this.userId), eq(documents.id, id)));};}diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snapnew file mode 100644index 00000000000..151c5c163f6--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap@@ -0,0 +1,75 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`promptFileContents > should format multiple file contents 1`] = `+"<knowledge_base_files totalCount="3">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+<file id="file-001" name="auth-guide.md">+First file content about API authentication.+</file>+<file id="file-002" name="db-setup.md">+Second file content about database setup and configuration.+</file>+<file id="file-003" name="deployment.md">+Third file content with deployment instructions.+</file>+</knowledge_base_files>"+`;++exports[`promptFileContents > should format single file content 1`] = `+"<knowledge_base_files totalCount="1">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+<file id="file-001" name="document.md">+This is the file content with some important information.+</file>+</knowledge_base_files>"+`;++exports[`promptFileContents > should handle file with error 1`] = `+"<knowledge_base_files totalCount="1">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+<file id="file-404" name="missing.md" error="File not found" />+</knowledge_base_files>"+`;++exports[`promptFileContents > should handle file with long content 1`] = `+"<knowledge_base_files totalCount="1">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+<file id="file-long" name="comprehensive-guide.md">+# Comprehensive Guide++## Introduction+This is a very long document with multiple sections and detailed information.++## Section 1+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.++## Section 2+Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.++## Conclusion+Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.+</file>+</knowledge_base_files>"+`;++exports[`promptFileContents > should handle file with special characters in name 1`] = `+"<knowledge_base_files totalCount="1">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+<file id="file-special" name="FAQ: Q&A (2024).md">+Content from a file with special characters in the name.+</file>+</knowledge_base_files>"+`;++exports[`promptFileContents > should handle mixed successful and error files 1`] = `+"<knowledge_base_files totalCount="3">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+<file id="file-001" name="success.md">+Successfully loaded content from this file.+</file>+<file id="file-002" name="restricted.md" error="Permission denied" />+<file id="file-003" name="another-success.md">+Another successfully loaded file with more content.+</file>+</knowledge_base_files>"+`;diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatNoSearchResults.test.ts.snap b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatNoSearchResults.test.ts.snapnew file mode 100644index 00000000000..f92799b6c03--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatNoSearchResults.test.ts.snap@@ -0,0 +1,45 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`promptNoSearchResults > should format no search results with complex query 1`] = `+"<knowledge_base_search_results query="API authentication with OAuth 2.0" totalCount="0">+<instruction>No relevant files found in the knowledge base for this query.</instruction>+<suggestions>+<suggestion>Try rephrasing your question with different keywords</suggestion>+<suggestion>Check if the information exists in the uploaded documents</suggestion>+<suggestion>Ask the user to provide more context or upload relevant documents</suggestion>+</suggestions>+</knowledge_base_search_results>"+`;++exports[`promptNoSearchResults > should format no search results with non-English query 1`] = `+"<knowledge_base_search_results query="如何配置数据库连接" totalCount="0">+<instruction>No relevant files found in the knowledge base for this query.</instruction>+<suggestions>+<suggestion>Try rephrasing your question with different keywords</suggestion>+<suggestion>Check if the information exists in the uploaded documents</suggestion>+<suggestion>Ask the user to provide more context or upload relevant documents</suggestion>+</suggestions>+</knowledge_base_search_results>"+`;++exports[`promptNoSearchResults > should format no search results with simple query 1`] = `+"<knowledge_base_search_results query="how to install" totalCount="0">+<instruction>No relevant files found in the knowledge base for this query.</instruction>+<suggestions>+<suggestion>Try rephrasing your question with different keywords</suggestion>+<suggestion>Check if the information exists in the uploaded documents</suggestion>+<suggestion>Ask the user to provide more context or upload relevant documents</suggestion>+</suggestions>+</knowledge_base_search_results>"+`;++exports[`promptNoSearchResults > should format no search results with special characters 1`] = `+"<knowledge_base_search_results query="How to use fetchData<T> with async/await?" totalCount="0">+<instruction>No relevant files found in the knowledge base for this query.</instruction>+<suggestions>+<suggestion>Try rephrasing your question with different keywords</suggestion>+<suggestion>Check if the information exists in the uploaded documents</suggestion>+<suggestion>Ask the user to provide more context or upload relevant documents</suggestion>+</suggestions>+</knowledge_base_search_results>"+`;diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snapnew file mode 100644index 00000000000..6beb1298fa3--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap@@ -0,0 +1,82 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`formatSearchResults > should format file with special characters in name 1`] = `+"<knowledge_base_search_results query="password reset" totalCount="1">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+<file id="special-123" name="FAQ: Common Questions & Answers (2024).md" relevanceScore="0.88">+<chunk fileId="special-123" fileName="FAQ: Common Questions & Answers (2024).md" similarity="0.9">Q: How do I reset my password? A: Click on the "Forgot Password" link on the login page.</chunk>+</file>+</knowledge_base_search_results>"+`;++exports[`formatSearchResults > should format long text chunks without truncation 1`] = `+"<knowledge_base_search_results query="documentation details" totalCount="1">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+<file id="long-doc" name="Detailed Documentation.md" relevanceScore="0.91">+<chunk fileId="long-doc" fileName="Detailed Documentation.md" similarity="0.93">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</chunk>+</file>+</knowledge_base_search_results>"+`;++exports[`formatSearchResults > should format multiple files with varying relevance scores 1`] = `+"<knowledge_base_search_results query="API authentication security" totalCount="3">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+<file id="doc-001" name="API Reference.md" relevanceScore="0.95">+<chunk fileId="doc-001" fileName="API Reference.md" similarity="0.98">The Authentication API provides endpoints for user login, logout, and token refresh. All endpoints require HTTPS and proper API keys.</chunk>+<chunk fileId="doc-001" fileName="API Reference.md" similarity="0.92">To authenticate a user, send a POST request to /api/auth/login with username and password in the request body.</chunk>+</file>+<file id="doc-002" name="Security Best Practices.md" relevanceScore="0.87">+<chunk fileId="doc-002" fileName="Security Best Practices.md" similarity="0.89">Always use environment variables to store sensitive information like API keys and database credentials. Never commit these to version control.</chunk>+<chunk fileId="doc-002" fileName="Security Best Practices.md" similarity="0.85">Implement rate limiting on all public endpoints to prevent abuse and DDoS attacks.</chunk>+</file>+<file id="doc-003" name="Troubleshooting Guide.md" relevanceScore="0.73">+<chunk fileId="doc-003" fileName="Troubleshooting Guide.md" similarity="0.75">If you encounter authentication errors, first verify that your API key is valid and has not expired.</chunk>+</file>+</knowledge_base_search_results>"+`;++exports[`formatSearchResults > should format query with special characters 1`] = `+"<knowledge_base_search_results query="How to use fetchData<T> with async/await?" totalCount="1">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+<file id="code-sample" name="Code Examples.md" relevanceScore="0.94">+<chunk fileId="code-sample" fileName="Code Examples.md" similarity="0.96">Use the following TypeScript code: const result = await fetchData<T>({ url, params });</chunk>+</file>+</knowledge_base_search_results>"+`;++exports[`formatSearchResults > should format single file with multiple chunks 1`] = `+"<knowledge_base_search_results query="how to install the application" totalCount="1">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+<file id="file-123" name="Getting Started Guide.md" relevanceScore="0.92">+<chunk fileId="file-123" fileName="Getting Started Guide.md" similarity="0.95">To get started with the application, first install all dependencies using npm install or yarn install. Make sure you have Node.js version 16 or higher installed on your system.</chunk>+<chunk fileId="file-123" fileName="Getting Started Guide.md" similarity="0.88">After installation, you can run the development server with npm run dev. The application will be available at http://localhost:3000 by default.</chunk>+</file>+</knowledge_base_search_results>"+`;++exports[`formatSearchResults > should handle empty file results 1`] = `+"<knowledge_base_search_results query="no results query" totalCount="0">+<instruction>No relevant files found in the knowledge base for this query.</instruction>+</knowledge_base_search_results>"+`;++exports[`formatSearchResults > should handle file with multiple high-similarity chunks 1`] = `+"<knowledge_base_search_results query="project setup steps" totalCount="1">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+<file id="comprehensive-guide" name="Complete Tutorial.md" relevanceScore="0.96">+<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.98">Step 1: Initialize the project with the configuration file.</chunk>+<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.97">Step 2: Configure the environment variables for your deployment.</chunk>+<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.96">Step 3: Run the migration scripts to set up the database schema.</chunk>+<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.95">Step 4: Start the development server and verify everything is working.</chunk>+</file>+</knowledge_base_search_results>"+`;++exports[`formatSearchResults > should handle files with low relevance scores 1`] = `+"<knowledge_base_search_results query="specific technical query" totalCount="1">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+<file id="low-relevance" name="Tangentially Related.md" relevanceScore="0.32">+<chunk fileId="low-relevance" fileName="Tangentially Related.md" similarity="0.35">This document contains some loosely related information that might be helpful.</chunk>+</file>+</knowledge_base_search_results>"+`;diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.tsnew file mode 100644index 00000000000..e801d8bd458--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest';++import { promptFileContents } from './formatFileContents';+import type { FileContent } from './formatFileContents';++describe('promptFileContents', () => {+ it('should format single file content', () => {+ const fileContents: FileContent[] = [+ {+ content: 'This is the file content with some important information.',+ fileId: 'file-001',+ filename: 'document.md',+ },+ ];++ const result = promptFileContents(fileContents);+ expect(result).toMatchSnapshot();+ });++ it('should format multiple file contents', () => {+ const fileContents: FileContent[] = [+ {+ content: 'First file content about API authentication.',+ fileId: 'file-001',+ filename: 'auth-guide.md',+ },+ {+ content: 'Second file content about database setup and configuration.',+ fileId: 'file-002',+ filename: 'db-setup.md',+ },+ {+ content: 'Third file content with deployment instructions.',+ fileId: 'file-003',+ filename: 'deployment.md',+ },+ ];++ const result = promptFileContents(fileContents);+ expect(result).toMatchSnapshot();+ });++ it('should handle file with error', () => {+ const fileContents: FileContent[] = [+ {+ content: '',+ error: 'File not found',+ fileId: 'file-404',+ filename: 'missing.md',+ },+ ];++ const result = promptFileContents(fileContents);+ expect(result).toMatchSnapshot();+ });++ it('should handle mixed successful and error files', () => {+ const fileContents: FileContent[] = [+ {+ content: 'Successfully loaded content from this file.',+ fileId: 'file-001',+ filename: 'success.md',+ },+ {+ content: '',+ error: 'Permission denied',+ fileId: 'file-002',+ filename: 'restricted.md',+ },+ {+ content: 'Another successfully loaded file with more content.',+ fileId: 'file-003',+ filename: 'another-success.md',+ },+ ];++ const result = promptFileContents(fileContents);+ expect(result).toMatchSnapshot();+ });++ it('should handle file with special characters in name', () => {+ const fileContents: FileContent[] = [+ {+ content: 'Content from a file with special characters in the name.',+ fileId: 'file-special',+ filename: 'FAQ: Q&A (2024).md',+ },+ ];++ const result = promptFileContents(fileContents);+ expect(result).toMatchSnapshot();+ });++ it('should handle file with long content', () => {+ const fileContents: FileContent[] = [+ {+ content: `# Comprehensive Guide++## Introduction+This is a very long document with multiple sections and detailed information.++## Section 1+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.++## Section 2+Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.++## Conclusion+Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.`,+ fileId: 'file-long',+ filename: 'comprehensive-guide.md',+ },+ ];++ const result = promptFileContents(fileContents);+ expect(result).toMatchSnapshot();+ });+});diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.tsnew file mode 100644index 00000000000..62955ad64eb--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts@@ -0,0 +1,31 @@+export interface FileContent {+ content: string;+ error?: string;+ fileId: string;+ filename: string;+}++/**+ * Formats a single file content with XML tags+ */+const formatFileContent = (file: FileContent): string => {+ if (file.error) {+ return `<file id="${file.fileId}" name="${file.filename}" error="${file.error}" />`;+ }++ return `<file id="${file.fileId}" name="${file.filename}">+${file.content}+</file>`;+};++/**+ * Format file contents prompt for AI consumption using XML structure+ */+export const promptFileContents = (fileContents: FileContent[]): string => {+ const filesXml = fileContents.map((file) => formatFileContent(file)).join('\n');++ return `<knowledge_base_files totalCount="${fileContents.length}">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+${filesXml}+</knowledge_base_files>`;+};diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.test.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.test.tsnew file mode 100644index 00000000000..76f15cf41e8--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest';++import { promptNoSearchResults } from './formatNoSearchResults';++describe('promptNoSearchResults', () => {+ it('should format no search results with simple query', () => {+ const result = promptNoSearchResults('how to install');+ expect(result).toMatchSnapshot();+ });++ it('should format no search results with complex query', () => {+ const result = promptNoSearchResults('API authentication with OAuth 2.0');+ expect(result).toMatchSnapshot();+ });++ it('should format no search results with special characters', () => {+ const result = promptNoSearchResults('How to use fetchData<T> with async/await?');+ expect(result).toMatchSnapshot();+ });++ it('should format no search results with non-English query', () => {+ const result = promptNoSearchResults('如何配置数据库连接');+ expect(result).toMatchSnapshot();+ });+});diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.tsnew file mode 100644index 00000000000..f225f5d80e1--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.ts@@ -0,0 +1,13 @@+/**+ * Format prompt when no search results found using XML structure+ */+export const promptNoSearchResults = (query: string): string => {+ return `<knowledge_base_search_results query="${query}" totalCount="0">+<instruction>No relevant files found in the knowledge base for this query.</instruction>+<suggestions>+<suggestion>Try rephrasing your question with different keywords</suggestion>+<suggestion>Check if the information exists in the uploaded documents</suggestion>+<suggestion>Ask the user to provide more context or upload relevant documents</suggestion>+</suggestions>+</knowledge_base_search_results>`;+};diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.test.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.test.tsnew file mode 100644index 00000000000..1a284573e05--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.test.ts@@ -0,0 +1,191 @@+import { describe, expect, it } from 'vitest';++import { formatSearchResults } from './formatSearchResults';+import type { FileSearchResult } from './formatSearchResults';++describe('formatSearchResults', () => {+ it('should format single file with multiple chunks', () => {+ const fileResults: FileSearchResult[] = [+ {+ fileId: 'file-123',+ fileName: 'Getting Started Guide.md',+ relevanceScore: 0.92,+ topChunks: [+ {+ similarity: 0.95,+ text: 'To get started with the application, first install all dependencies using npm install or yarn install. Make sure you have Node.js version 16 or higher installed on your system.',+ },+ {+ similarity: 0.88,+ text: 'After installation, you can run the development server with npm run dev. The application will be available at http://localhost:3000 by default.',+ },+ ],+ },+ ];++ const result = formatSearchResults(fileResults, 'how to install the application');+ expect(result).toMatchSnapshot();+ });++ it('should format multiple files with varying relevance scores', () => {+ const fileResults: FileSearchResult[] = [+ {+ fileId: 'doc-001',+ fileName: 'API Reference.md',+ relevanceScore: 0.95,+ topChunks: [+ {+ similarity: 0.98,+ text: 'The Authentication API provides endpoints for user login, logout, and token refresh. All endpoints require HTTPS and proper API keys.',+ },+ {+ similarity: 0.92,+ text: 'To authenticate a user, send a POST request to /api/auth/login with username and password in the request body.',+ },+ ],+ },+ {+ fileId: 'doc-002',+ fileName: 'Security Best Practices.md',+ relevanceScore: 0.87,+ topChunks: [+ {+ similarity: 0.89,+ text: 'Always use environment variables to store sensitive information like API keys and database credentials. Never commit these to version control.',+ },+ {+ similarity: 0.85,+ text: 'Implement rate limiting on all public endpoints to prevent abuse and DDoS attacks.',+ },+ ],+ },+ {+ fileId: 'doc-003',+ fileName: 'Troubleshooting Guide.md',+ relevanceScore: 0.73,+ topChunks: [+ {+ similarity: 0.75,+ text: 'If you encounter authentication errors, first verify that your API key is valid and has not expired.',+ },+ ],+ },+ ];++ const result = formatSearchResults(fileResults, 'API authentication security');+ expect(result).toMatchSnapshot();+ });++ it('should format long text chunks without truncation', () => {+ const fileResults: FileSearchResult[] = [+ {+ fileId: 'long-doc',+ fileName: 'Detailed Documentation.md',+ relevanceScore: 0.91,+ topChunks: [+ {+ similarity: 0.93,+ text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',+ },+ ],+ },+ ];++ const result = formatSearchResults(fileResults, 'documentation details');+ expect(result).toMatchSnapshot();+ });++ it('should handle empty file results', () => {+ const fileResults: FileSearchResult[] = [];+ const result = formatSearchResults(fileResults, 'no results query');+ expect(result).toMatchSnapshot();+ });++ it('should format file with special characters in name', () => {+ const fileResults: FileSearchResult[] = [+ {+ fileId: 'special-123',+ fileName: 'FAQ: Common Questions & Answers (2024).md',+ relevanceScore: 0.88,+ topChunks: [+ {+ similarity: 0.9,+ text: 'Q: How do I reset my password? A: Click on the "Forgot Password" link on the login page.',+ },+ ],+ },+ ];++ const result = formatSearchResults(fileResults, 'password reset');+ expect(result).toMatchSnapshot();+ });++ it('should handle files with low relevance scores', () => {+ const fileResults: FileSearchResult[] = [+ {+ fileId: 'low-relevance',+ fileName: 'Tangentially Related.md',+ relevanceScore: 0.32,+ topChunks: [+ {+ similarity: 0.35,+ text: 'This document contains some loosely related information that might be helpful.',+ },+ ],+ },+ ];++ const result = formatSearchResults(fileResults, 'specific technical query');+ expect(result).toMatchSnapshot();+ });++ it('should format query with special characters', () => {+ const fileResults: FileSearchResult[] = [+ {+ fileId: 'code-sample',+ fileName: 'Code Examples.md',+ relevanceScore: 0.94,+ topChunks: [+ {+ similarity: 0.96,+ text: 'Use the following TypeScript code: const result = await fetchData<T>({ url, params });',+ },+ ],+ },+ ];++ const result = formatSearchResults(fileResults, 'How to use fetchData<T> with async/await?');+ expect(result).toMatchSnapshot();+ });++ it('should handle file with multiple high-similarity chunks', () => {+ const fileResults: FileSearchResult[] = [+ {+ fileId: 'comprehensive-guide',+ fileName: 'Complete Tutorial.md',+ relevanceScore: 0.96,+ topChunks: [+ {+ similarity: 0.98,+ text: 'Step 1: Initialize the project with the configuration file.',+ },+ {+ similarity: 0.97,+ text: 'Step 2: Configure the environment variables for your deployment.',+ },+ {+ similarity: 0.96,+ text: 'Step 3: Run the migration scripts to set up the database schema.',+ },+ {+ similarity: 0.95,+ text: 'Step 4: Start the development server and verify everything is working.',+ },+ ],+ },+ ];++ const result = formatSearchResults(fileResults, 'project setup steps');+ expect(result).toMatchSnapshot();+ });+});diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.tsnew file mode 100644index 00000000000..e19cfd23c5f--- /dev/null+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts@@ -0,0 +1,50 @@+export interface FileSearchResultChunk {+ similarity: number;+ text: string;+}++export interface FileSearchResult {+ fileId: string;+ fileName: string;+ relevanceScore: number;+ topChunks: FileSearchResultChunk[];+}++/**+ * Formats a single chunk with XML tags+ */+const formatChunk = (chunk: FileSearchResultChunk, fileId: string, fileName: string): string => {+ return `<chunk fileId="${fileId}" fileName="${fileName}" similarity="${chunk.similarity}">${chunk.text}</chunk>`;+};++/**+ * Formats a single file search result with XML tags+ */+const formatFile = (file: FileSearchResult): string => {+ const chunks = file.topChunks.map((chunk) => formatChunk(chunk, file.fileId, file.fileName));++ return `<file id="${file.fileId}" name="${file.fileName}" relevanceScore="${file.relevanceScore}">+${chunks.join('\n')}+</file>`;+};++/**+ * Formats knowledge base search results into an XML structure+ * @param fileResults - Array of file search results with relevance scores and chunks+ * @param query - The original search query+ * @returns Formatted XML string with search results+ */+export const formatSearchResults = (fileResults: FileSearchResult[], query: string): string => {+ if (fileResults.length === 0) {+ return `<knowledge_base_search_results query="${query}" totalCount="0">+<instruction>No relevant files found in the knowledge base for this query.</instruction>+</knowledge_base_search_results>`;+ }++ const filesXml = fileResults.map((file) => formatFile(file)).join('\n');++ return `<knowledge_base_search_results query="${query}" totalCount="${fileResults.length}">+<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>+${filesXml}+</knowledge_base_search_results>`;+};\ No newline at end of filediff --git a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts b/packages/prompts/src/prompts/knowledgeBaseQA/index.tsindex 4ceb566d995..e2aab5961b7 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/index.ts@@ -4,6 +4,12 @@ import { chunkPrompts } from './chunk';import { knowledgePrompts } from './knowledge';import { userQueryPrompt } from './userQuery';+export type { FileContent } from './formatFileContents';+export { promptFileContents } from './formatFileContents';+export { promptNoSearchResults } from './formatNoSearchResults';+export type { FileSearchResult, FileSearchResultChunk } from './formatSearchResults';+export { formatSearchResults } from './formatSearchResults';+export const knowledgeBaseQAPrompts = ({chunks,knowledge,diff --git a/packages/types/src/rag.ts b/packages/types/src/rag.tsindex b6c74376631..00bd1ca1639 100644--- a/packages/types/src/rag.ts+++ b/packages/types/src/rag.ts@@ -5,12 +5,21 @@ import { ChatSemanticSearchChunk } from './chunk';export const SemanticSearchSchema = z.object({fileIds: z.array(z.string()).optional(),knowledgeIds: z.array(z.string()).optional(),- messageId: z.string(),- model: z.string().optional(),- rewriteQuery: z.string(),- userQuery: z.string(),+ query: z.string(),+ topK: z.number().optional(),});export type SemanticSearchSchemaType = z.infer<typeof SemanticSearchSchema>;export type MessageSemanticSearchChunk = Pick<ChatSemanticSearchChunk, 'id' | 'similarity'>;++export interface FileSearchResult {+ fileId: string;+ fileName: string;+ relevanceScore: number;+ topChunks: Array<{+ id: string;+ similarity: number;+ text: string;+ }>;+}diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsxindex bec5c11ba74..66ce4f612ca 100644--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx@@ -6,7 +6,7 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { Center, Flexbox } from 'react-layout-kit';-import { createChatToolsEngine } from '@/helpers/toolEngineering';+import { createAgentToolsEngine } from '@/helpers/toolEngineering';import { useModelContextWindowTokens } from '@/hooks/useModelContextWindowTokens';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useTokenCount } from '@/hooks/useTokenCount';@@ -57,7 +57,7 @@ const Token = memo<TokenTagProps>(({ total: messageString }) => {const pluginIds = useAgentStore(agentSelectors.currentAgentPlugins);const toolsString = useToolStore((s) => {- const toolsEngine = createChatToolsEngine({ model, provider });+ const toolsEngine = createAgentToolsEngine({ model, provider });const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({model,diff --git a/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsx b/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsxindex be951d81bca..317cd3d39cf 100644--- a/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsx@@ -7,7 +7,7 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { Center, Flexbox } from 'react-layout-kit';-import { createChatToolsEngine } from '@/helpers/toolEngineering';+import { createAgentToolsEngine } from '@/helpers/toolEngineering';import { useModelContextWindowTokens } from '@/hooks/useModelContextWindowTokens';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useTokenCount } from '@/hooks/useTokenCount';@@ -76,7 +76,7 @@ const TokenTagForGroupChat = memo<TokenTagForGroupChatProps>(({ total: messageStconst pluginIds = allGroupPlugins.map((plugin) => plugin.id);const toolsString = useToolStore((s) => {- const toolsEngine = createChatToolsEngine({ model, provider });+ const toolsEngine = createAgentToolsEngine({ model, provider });const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({model,diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/ToolTitle.tsx b/src/features/ChatList/Messages/Group/Tool/Inspector/ToolTitle.tsxindex c9c6f0eaeb9..19346600a65 100644--- a/src/features/ChatList/Messages/Group/Tool/Inspector/ToolTitle.tsx+++ b/src/features/ChatList/Messages/Group/Tool/Inspector/ToolTitle.tsx@@ -2,15 +2,14 @@ import { Icon } from '@lobehub/ui';import { createStyles } from 'antd-style';import isEqual from 'fast-deep-equal';import { ChevronRight } from 'lucide-react';-import { memo, useMemo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import { Flexbox } from 'react-layout-kit';import { pluginHelpers, useToolStore } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';import { shinyTextStylish } from '@/styles/loading';-import { LocalSystemManifest } from '@/tools/local-system';-import { WebBrowsingManifest } from '@/tools/web-browsing';+import { builtinToolIdentifiers } from '@/tools/identifiers';import BuiltinPluginTitle from './BuiltinPluginTitle';@@ -49,33 +48,16 @@ const ToolTitle = memo<ToolTitleProps>(const pluginMeta = useToolStore(toolSelectors.getMetaById(identifier), isEqual);- const plugins = useMemo(- () => [- {- apiName: t(`search.apiName.${apiName}`, apiName),- id: WebBrowsingManifest.identifier,- title: t('search.title'),- },- {- apiName: t(`localSystem.apiName.${apiName}`, apiName),- id: LocalSystemManifest.identifier,- title: t('localSystem.title'),- },- ],- [],- );-- const builtinPluginTitle = plugins.find((item) => item.id === identifier);-- if (!!builtinPluginTitle) {+ if (builtinToolIdentifiers.includes(identifier)) {return (<BuiltinPluginTitle- {...builtinPluginTitle}+ apiName={t(`builtins.${identifier}.apiName.${apiName}`, apiName)}identifier={identifier}index={index}isExpanded={isExpanded}isLoading={isLoading}messageId={messageId}+ title={t(`builtins.${identifier}.title`, identifier)}toolCallId={toolCallId}/>);diff --git a/src/features/ChatList/Messages/Tool/Inspector/ToolTitle.tsx b/src/features/ChatList/Messages/Tool/Inspector/ToolTitle.tsxindex b3dee1358f4..f82c758e615 100644--- a/src/features/ChatList/Messages/Tool/Inspector/ToolTitle.tsx+++ b/src/features/ChatList/Messages/Tool/Inspector/ToolTitle.tsx@@ -2,15 +2,14 @@ import { Icon } from '@lobehub/ui';import { createStyles } from 'antd-style';import isEqual from 'fast-deep-equal';import { ChevronRight } from 'lucide-react';-import { memo, useMemo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import { Flexbox } from 'react-layout-kit';import { pluginHelpers, useToolStore } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';import { shinyTextStylish } from '@/styles/loading';-import { LocalSystemManifest } from '@/tools/local-system';-import { WebBrowsingManifest } from '@/tools/web-browsing';+import { builtinToolIdentifiers } from '@/tools/identifiers';import BuiltinPluginTitle from './BuiltinPluginTitle';@@ -43,33 +42,14 @@ const ToolTitle = memo<ToolTitleProps>(({ identifier, messageId, index, apiName,const pluginMeta = useToolStore(toolSelectors.getMetaById(identifier), isEqual);- const plugins = useMemo(- () => [- {- apiName: t(`search.apiName.${apiName}`, apiName),- // icon: <Icon icon={Globe} size={13} />,- id: WebBrowsingManifest.identifier,- title: t('search.title'),- },- {- apiName: t(`localSystem.apiName.${apiName}`, apiName),- // icon: <Icon icon={Laptop} size={13} />,- id: LocalSystemManifest.identifier,- title: t('localSystem.title'),- },- ],- [],- );-- const builtinPluginTitle = plugins.find((item) => item.id === identifier);-- if (!!builtinPluginTitle) {+ if (builtinToolIdentifiers.includes(identifier)) {return (<BuiltinPluginTitle- {...builtinPluginTitle}+ apiName={t(`builtins.${identifier}.apiName.${apiName}`, apiName)}identifier={identifier}index={index}messageId={messageId}+ title={t(`builtins.${identifier}.title`, identifier)}toolCallId={toolCallId}/>);diff --git a/src/features/PluginsUI/Render/BuiltinType/index.tsx b/src/features/PluginsUI/Render/BuiltinType/index.tsxindex a71f6bbd41c..b3b5c201c4f 100644--- a/src/features/PluginsUI/Render/BuiltinType/index.tsx+++ b/src/features/PluginsUI/Render/BuiltinType/index.tsx@@ -37,7 +37,7 @@ const BuiltinType = memo<BuiltinTypeProps>(return (<RenderapiName={apiName}- args={args}+ args={args || {}}content={data}identifier={identifier}messageId={id}diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.tsindex debebd4c173..17827f5ce9e 100644--- a/src/helpers/toolEngineering/index.test.ts+++ b/src/helpers/toolEngineering/index.test.ts@@ -1,7 +1,7 @@import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createChatToolsEngine, createToolsEngine, getEnabledTools } from './index';+import { createAgentToolsEngine, createToolsEngine, getEnabledTools } from './index';// Mock the store and helper dependenciesvi.mock('@/store/tool', () => ({@@ -137,7 +137,7 @@ describe('toolEngineering', () => {describe('createChatToolsEngine', () => {it('should include web browsing tool as default when no tools are provided', () => {- const toolsEngine = createChatToolsEngine({+ const toolsEngine = createAgentToolsEngine({model: 'gpt-4',provider: 'openai',});@@ -152,7 +152,7 @@ describe('toolEngineering', () => {});it('should include web browsing tool alongside user-provided tools', () => {- const toolsEngine = createChatToolsEngine({+ const toolsEngine = createAgentToolsEngine({model: 'gpt-4',provider: 'openai',});diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsindex 339936679ad..15ccf3bd276 100644--- a/src/helpers/toolEngineering/index.ts+++ b/src/helpers/toolEngineering/index.ts@@ -13,6 +13,9 @@ import { WebBrowsingManifest } from '@/tools/web-browsing';import { getSearchConfig } from '../getSearchConfig';import { isCanUseFC } from '../isCanUseFC';import { shouldEnableTool } from '../toolFilters';+import { KnowledgeBaseManifest } from '@/tools/knowledge-base';+import { getAgentStoreState } from '@/store/agent';+import { agentSelectors } from '@/store/agent/slices/chat';/*** Tools engine configuration options@@ -53,23 +56,33 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =});};-export const createChatToolsEngine = (workingModel: WorkingModel) =>+export const createAgentToolsEngine = (workingModel: WorkingModel) =>createToolsEngine({- // Add WebBrowsingManifest as default tool- defaultToolIds: [WebBrowsingManifest.identifier],+ // Add default tools based on configuration+ defaultToolIds: [+ WebBrowsingManifest.identifier,+ // Only add KnowledgeBase tool if knowledge is enabled+ KnowledgeBaseManifest.identifier,+ ],// Create search-aware enableChecker for this requestenableChecker: ({ pluginId }) => {// Check platform-specific constraints (e.g., LocalSystem desktop-only)if (!shouldEnableTool(pluginId)) {return false;}-// For WebBrowsingManifest, apply search logicif (pluginId === WebBrowsingManifest.identifier) {const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);return searchConfig.useApplicationBuiltinSearchTool;}+ // For KnowledgeBaseManifest, only enable if knowledge is enabled+ if (pluginId === KnowledgeBaseManifest.identifier) {+ const agentState = getAgentStoreState();++ return agentSelectors.hasEnabledKnowledge(agentState);+ }+// For all other plugins, enable by defaultreturn true;},diff --git a/src/libs/trpc/client/lambda.ts b/src/libs/trpc/client/lambda.tsindex c85d134141e..ecf05a63d17 100644--- a/src/libs/trpc/client/lambda.ts+++ b/src/libs/trpc/client/lambda.ts@@ -34,9 +34,6 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {// Don't show notifications for abort errorsif (showError && !isAbortError) {const { loginRequired } = await import('@/components/Error/loginRequiredNotification');- const { fetchErrorNotification } = await import(- '@/components/Error/fetchErrorNotification'- );switch (status) {case 401: {@@ -53,9 +50,6 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {default: {console.error(err);- if (fetchErrorNotification && status) {- fetchErrorNotification.error({ errorMessage: err.message, status });- }}}}diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex ee3cd92e611..e3e1acc3813 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -1,4 +1,38 @@export default {+ builtins: {+ 'lobe-knowledge-base': {+ apiName: {+ readKnowledge: '读取知识库内容',+ searchKnowledgeBase: '搜索知识库',+ },+ title: '知识库',+ },+ 'lobe-local-system': {+ apiName: {+ editLocalFile: '编辑文件',+ getCommandOutput: '获取代码输出',+ globLocalFiles: '匹配搜索文件',+ grepContent: '搜索内容',+ killCommand: '终止代码执行',+ listLocalFiles: '查看文件列表',+ moveLocalFiles: '移动文件',+ readLocalFile: '读取文件内容',+ renameLocalFile: '重命名',+ runCommand: '执行代码',+ searchLocalFiles: '搜索文件',+ writeLocalFile: '写入文件',+ },+ title: '本地系统',+ },+ 'lobe-web-browsing': {+ apiName: {+ crawlMultiPages: '读取多个页面内容',+ crawlSinglePage: '读取页面内容',+ search: '搜索页面',+ },+ title: '联网搜索',+ },+ },confirm: '确定',debug: {arguments: '调用参数',@@ -253,23 +287,6 @@ export default {content: '调用插件中...',plugin: '插件运行中...',},- localSystem: {- apiName: {- editLocalFile: '编辑文件',- getCommandOutput: '获取代码输出',- globLocalFiles: '匹配搜索文件',- grepContent: '搜索内容',- killCommand: '终止代码执行',- listLocalFiles: '查看文件列表',- moveLocalFiles: '移动文件',- readLocalFile: '读取文件内容',- renameLocalFile: '重命名',- runCommand: '执行代码',- searchLocalFiles: '搜索文件',- writeLocalFile: '写入文件',- },- title: '本地系统',- },mcpInstall: {CHECKING_INSTALLATION: '检查安装环境...',COMPLETED: '安装完成',@@ -378,11 +395,6 @@ export default {warning: '⚠️ 请确认您信任此插件的来源,恶意插件可能会危害您的系统安全。',},search: {- apiName: {- crawlMultiPages: '读取多个页面内容',- crawlSinglePage: '读取页面内容',- search: '搜索页面',- },config: {addKey: '添加秘钥',close: '删除',diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.tsindex 0140bc82297..e28bfff2f0c 100644--- a/src/locales/default/tool.ts+++ b/src/locales/default/tool.ts@@ -1,12 +1,12 @@export default {- codeInterpreter: {+ 'codeInterpreter': {error: '执行错误',executing: '执行中...',files: '文件:',output: '输出:',returnValue: '返回值:',},- dalle: {+ 'dalle': {autoGenerate: '自动生成',downloading: 'DallE3 生成的图片链接有效期仅1小时,正在缓存图片到本地...',generate: '生成',@@ -14,7 +14,15 @@ export default {images: '图片:',prompt: '提示词',},- localFiles: {+ 'lobe-knowledge-base': {+ readKnowledge: {+ meta: {+ chars: '字符数',+ lines: '行数',+ },+ },+ },+ 'localFiles': {editFile: {newString: '替换为',oldString: '查找内容',@@ -47,7 +55,7 @@ export default {truncated: '已截断',},},- search: {+ 'search': {createNewSearch: '创建新的搜索记录',emptyResult: '没有搜索到结果,请修改关键词后重试',genAiMessage: '创建助手消息',@@ -94,7 +102,7 @@ export default {summaryTooltip: '总结当前内容',viewMoreResults: '查看更多 {{results}} 个结果',},- updateArgs: {+ 'updateArgs': {duplicateKeyError: '字段键必须唯一',form: {add: '添加一项',diff --git a/src/server/routers/lambda/chunk.ts b/src/server/routers/lambda/chunk.tsindex ae95e238e00..cdaee195899 100644--- a/src/server/routers/lambda/chunk.ts+++ b/src/server/routers/lambda/chunk.ts@@ -1,32 +1,50 @@import { DEFAULT_FILE_EMBEDDING_MODEL_ITEM } from '@lobechat/const';-import { SemanticSearchSchema } from '@lobechat/types';+import {+ ChatSemanticSearchChunk,+ FileSearchResult,+ ProviderConfig,+ SemanticSearchSchema,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import { inArray } from 'drizzle-orm';+import pMap from 'p-map';import { z } from 'zod';import { AsyncTaskModel } from '@/database/models/asyncTask';import { ChunkModel } from '@/database/models/chunk';+import { DocumentModel } from '@/database/models/document';import { EmbeddingModel } from '@/database/models/embedding';import { FileModel } from '@/database/models/file';import { MessageModel } from '@/database/models/message';+import { AiInfraRepos } from '@/database/repositories/aiInfra';import { knowledgeBaseFiles } from '@/database/schemas';import { authedProcedure, router } from '@/libs/trpc/lambda';import { keyVaults, serverDatabase } from '@/libs/trpc/lambda/middleware';-import { getServerDefaultFilesConfig } from '@/server/globalConfig';+import { getServerDefaultFilesConfig, getServerGlobalConfig } from '@/server/globalConfig';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';import { ChunkService } from '@/server/services/chunk';+import { DocumentService } from '@/server/services/document';const chunkProcedure = authedProcedure.use(serverDatabase).use(keyVaults).use(async (opts) => {const { ctx } = opts;+ const { aiProvider } = await getServerGlobalConfig();return opts.next({ctx: {+ aiInfraRepos: new AiInfraRepos(+ ctx.serverDB,+ ctx.userId,+ aiProvider as Record<string, ProviderConfig>,+ ),asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),chunkModel: new ChunkModel(ctx.serverDB, ctx.userId),chunkService: new ChunkService(ctx.serverDB, ctx.userId),+ documentModel: new DocumentModel(ctx.serverDB, ctx.userId),+ documentService: new DocumentService(ctx.serverDB, ctx.userId),embeddingModel: new EmbeddingModel(ctx.serverDB, ctx.userId),fileModel: new FileModel(ctx.serverDB, ctx.userId),messageModel: new MessageModel(ctx.serverDB, ctx.userId),@@ -34,6 +52,50 @@ const chunkProcedure = authedProcedure});});+/**+ * Group chunks by file and calculate relevance scores+ */+const groupAndRankFiles = (chunks: ChatSemanticSearchChunk[], topK: number): FileSearchResult[] => {+ const fileMap = new Map<string, FileSearchResult>();++ // Group chunks by file+ for (const chunk of chunks) {+ const fileId = chunk.fileId || 'unknown';+ const fileName = chunk.fileName || `File ${fileId}`;++ if (!fileMap.has(fileId)) {+ fileMap.set(fileId, {+ fileId,+ fileName,+ relevanceScore: 0,+ topChunks: [],+ });+ }++ const fileResult = fileMap.get(fileId)!;+ fileResult.topChunks.push({+ id: chunk.id,+ similarity: chunk.similarity,+ text: chunk.text || '',+ });+ }++ // Calculate relevance score for each file (average of top 3 chunks)+ for (const fileResult of fileMap.values()) {+ fileResult.topChunks.sort((a, b) => b.similarity - a.similarity);+ const top3 = fileResult.topChunks.slice(0, 3);+ fileResult.relevanceScore =+ top3.reduce((sum, chunk) => sum + chunk.similarity, 0) / top3.length;+ // Keep only top chunks per file+ fileResult.topChunks = fileResult.topChunks.slice(0, 3);+ }++ // Sort files by relevance score and return top K+ return Array.from(fileMap.values())+ .sort((a, b) => b.relevanceScore - a.relevanceScore)+ .slice(0, topK);+};+export const chunkRouter = router({createEmbeddingChunksTask: chunkProcedure.input(@@ -78,6 +140,66 @@ export const chunkRouter = router({};}),+ getFileContents: chunkProcedure+ .input(+ z.object({+ fileIds: z.array(z.string()),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return await pMap(+ input.fileIds,+ async (fileId) => {+ // 1. Find file information+ const file = await ctx.fileModel.findById(fileId);+ if (!file) {+ return {+ content: '',+ error: 'File not found',+ fileId,+ filename: `Unknown file ${fileId}`,+ };+ }++ // 2. Find existing parsed document+ let document = await ctx.documentModel.findByFileId(fileId);++ // 3. If not exists, parse the file+ if (!document) {+ try {+ document = await ctx.documentService.parseFile(fileId);+ } catch (error) {+ return {+ content: '',+ error: `Failed to parse file: ${(error as Error).message}`,+ fileId,+ filename: file.name,+ };+ }+ }++ // 4. Calculate file statistics+ const content = document.content || '';+ const lines = content.split('\n');+ const totalLineCount = lines.length;+ const totalCharCount = content.length;+ const preview = lines.slice(0, 5).join('\n');++ // 5. Return content with details+ return {+ content,+ fileId,+ filename: file.name,+ metadata: document.metadata,+ preview,+ totalCharCount,+ totalLineCount,+ };+ },+ { concurrency: 3 },+ );+ }),+retryParseFileTask: chunkProcedure.input(z.object({@@ -117,7 +239,6 @@ export const chunkRouter = router({input: input.query,model,});- console.timeEnd('embedding');return ctx.chunkModel.semanticSearch({embedding: embeddings![0],@@ -130,47 +251,30 @@ export const chunkRouter = router({.input(SemanticSearchSchema).mutation(async ({ ctx, input }) => {try {- const item = await ctx.messageModel.findMessageQueriesById(input.messageId);const { model, provider } =getServerDefaultFilesConfig().embeddingModel || DEFAULT_FILE_EMBEDDING_MODEL_ITEM;let embedding: number[];- let ragQueryId: string;-- // if there is no message rag or it's embeddings, then we need to create one- if (!item || !item.embeddings) {- // TODO: need to support customize- const agentRuntime = await initModelRuntimeWithUserPayload(provider, ctx.jwtPayload);-- // slice content to make sure in the context window limit- const query =- input.rewriteQuery.length > 8000- ? input.rewriteQuery.slice(0, 8000)- : input.rewriteQuery;-- const embeddings = await agentRuntime.embeddings({- dimensions: 1024,- input: query,- model,- });- embedding = embeddings![0];- const embeddingsId = await ctx.embeddingModel.create({- embeddings: embedding,- model,- });+ const providerDetail = await ctx.aiInfraRepos.getAiProviderDetail(+ provider,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );- const result = await ctx.messageModel.createMessageQuery({- embeddingsId,- messageId: input.messageId,- rewriteQuery: input.rewriteQuery,- userQuery: input.userQuery,- });+ const modelRuntime = initModelRuntimeWithUserPayload(+ provider,+ providerDetail.keyVaults || {},+ );- ragQueryId = result.id;- } else {- embedding = item.embeddings;- ragQueryId = item.id;- }+ // slice content to make sure in the context window limit+ const query = input.query.length > 8000 ? input.query.slice(0, 8000) : input.query;++ const embeddings = await modelRuntime.embeddings({+ dimensions: 1024,+ input: query,+ model,+ });++ embedding = embeddings![0];let finalFileIds = input.fileIds ?? [];@@ -185,18 +289,41 @@ export const chunkRouter = router({const chunks = await ctx.chunkModel.semanticSearchForChat({embedding,fileIds: finalFileIds,- query: input.rewriteQuery,+ query: input.query,+ topK: input.topK,});+ // Group chunks by file and calculate relevance scores+ const fileResults = groupAndRankFiles(chunks, input.topK || 15);+// TODO: need to rerank the chunks- return { chunks, queryId: ragQueryId };+ return { chunks, fileResults };} catch (e) {console.error(e);+ const error = e as any;+ const errorType = error.errorType;++ // Map business error types to appropriate HTTP status codes+ if (errorType === 'InvalidProviderAPIKey') {+ throw new TRPCError({+ code: 'METHOD_NOT_SUPPORTED',+ message: error.message || 'Invalid API key for embedding provider',+ });+ }++ if (errorType === 'ProviderBizError') {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: error.message || 'Provider service error',+ });+ }++ // For unknown errors, still return 500 but with proper messagethrow new TRPCError({code: 'INTERNAL_SERVER_ERROR',- message: (e as any).errorType || JSON.stringify(e),+ message: error.message || errorType || 'Failed to perform semantic search',});}}),diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.tsindex bec7085ac1d..9c8c378bad1 100644--- a/src/services/chat/chat.test.ts+++ b/src/services/chat/chat.test.ts@@ -913,7 +913,7 @@ describe('ChatService', () => {enabledToolIds: [WebBrowsingManifest.identifier],}),};- vi.spyOn(toolEngineeringModule, 'createChatToolsEngine').mockReturnValue(+ vi.spyOn(toolEngineeringModule, 'createAgentToolsEngine').mockReturnValue(mockToolsEngine as any,);@@ -964,7 +964,7 @@ describe('ChatService', () => {enabledToolIds: [WebBrowsingManifest.identifier],}),};- vi.spyOn(toolEngineeringModule, 'createChatToolsEngine').mockReturnValue(+ vi.spyOn(toolEngineeringModule, 'createAgentToolsEngine').mockReturnValue(mockToolsEngine as any,);@@ -1009,7 +1009,7 @@ describe('ChatService', () => {enabledToolIds: [WebBrowsingManifest.identifier],}),};- vi.spyOn(toolEngineeringModule, 'createChatToolsEngine').mockReturnValue(+ vi.spyOn(toolEngineeringModule, 'createAgentToolsEngine').mockReturnValue(mockToolsEngine as any,);diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex 433e1ccd9e5..e1d5d950553 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -14,7 +14,7 @@ import { enableAuth } from '@/const/auth';import { DEFAULT_AGENT_CONFIG } from '@/const/settings';import { isDesktop } from '@/const/version';import { getSearchConfig } from '@/helpers/getSearchConfig';-import { createChatToolsEngine, createToolsEngine } from '@/helpers/toolEngineering';+import { createAgentToolsEngine, createToolsEngine } from '@/helpers/toolEngineering';import { getAgentStoreState } from '@/store/agent';import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';import { aiModelSelectors, aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';@@ -90,7 +90,7 @@ class ChatService {const pluginIds = [...(enabledPlugins || [])];- const toolsEngine = createChatToolsEngine({+ const toolsEngine = createAgentToolsEngine({model: payload.model,provider: payload.provider!,});diff --git a/src/services/rag.ts b/src/services/rag.tsindex c40db4043d6..a7f494b9214 100644--- a/src/services/rag.ts+++ b/src/services/rag.ts@@ -22,8 +22,12 @@ class RAGService {return lambdaClient.chunk.semanticSearch.mutate({ fileIds, query });};- semanticSearchForChat = async (params: SemanticSearchSchemaType) => {- return lambdaClient.chunk.semanticSearchForChat.mutate(params);+ semanticSearchForChat = async (params: SemanticSearchSchemaType, signal?: AbortSignal) => {+ return lambdaClient.chunk.semanticSearchForChat.mutate(params, { signal });+ };++ getFileContents = async (fileIds: string[], signal?: AbortSignal) => {+ return lambdaClient.chunk.getFileContents.mutate({ fileIds }, { signal });};deleteMessageRagQuery = async (id: string) => {diff --git a/src/store/chat/agents/createToolEngine.ts b/src/store/chat/agents/createToolEngine.tsdeleted file mode 100644index adc068867e4..00000000000--- a/src/store/chat/agents/createToolEngine.ts+++ /dev/null@@ -1,22 +0,0 @@-import { WorkingModel } from '@lobechat/types';--import { getSearchConfig } from '@/helpers/getSearchConfig';-import { createToolsEngine } from '@/helpers/toolEngineering';-import { WebBrowsingManifest } from '@/tools/web-browsing';--export const createAgentToolsEngine = (workingModel: WorkingModel) =>- createToolsEngine({- // Add WebBrowsingManifest as default tool- defaultToolIds: [WebBrowsingManifest.identifier],- // Create search-aware enableChecker for this request- enableChecker: ({ pluginId }) => {- // For WebBrowsingManifest, apply search logic- if (pluginId === WebBrowsingManifest.identifier) {- const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);- return searchConfig.useApplicationBuiltinSearchTool;- }-- // For all other plugins, enable by default- return true;- },- });diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.tsindex 055953f4d43..e2f1725488f 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts@@ -15,6 +15,17 @@ import {// Keep zustand mock as it's needed globallyvi.mock('zustand/traditional');+// Mock lambdaClient to prevent network requests+vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ session: {+ updateSession: {+ mutate: vi.fn().mockResolvedValue(undefined),+ },+ },+ },+}));+beforeEach(() => {resetTestEnvironment();setupMockSelectors();diff --git a/src/store/chat/slices/aiChat/actions/__tests__/rag.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/rag.test.tsindex 1d566be5792..16ee0334239 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/rag.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/rag.test.ts@@ -62,93 +62,6 @@ describe('chatRAG actions', () => {});});- describe('internal_retrieveChunks', () => {- it('should retrieve chunks with existing ragQuery', async () => {- const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';- const existingRagQuery = 'existing-query';- const userQuery = 'user-query';-- // Mock the message with existing ragQuery- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockReturnValue(- () =>- ({- id: messageId,- ragQuery: existingRagQuery,- }) as UIChatMessage,- );-- // Mock the semantic search response- (ragService.semanticSearchForChat as Mock).mockResolvedValue({- chunks: [{ id: 'chunk-1' }],- queryId: 'query-id',- });-- vi.spyOn(agentSelectors, 'currentKnowledgeIds').mockReturnValue({- fileIds: [],- knowledgeBaseIds: [],- });-- const result1 = await act(async () => {- return await result.current.internal_retrieveChunks(messageId, userQuery, []);- });-- expect(result1).toEqual({- chunks: [{ id: 'chunk-1' }],- queryId: 'query-id',- rewriteQuery: existingRagQuery,- });- expect(ragService.semanticSearchForChat).toHaveBeenCalledWith(- expect.objectContaining({- rewriteQuery: existingRagQuery,- userQuery,- }),- );- });-- it('should rewrite query if no existing ragQuery', async () => {- const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';- const userQuery = 'user-query';- const rewrittenQuery = 'rewritten-query';-- // Mock the message without ragQuery- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockReturnValue(- () =>- ({- id: messageId,- }) as UIChatMessage,- );-- // Mock the rewrite query function- vi.spyOn(result.current, 'internal_rewriteQuery').mockResolvedValueOnce(rewrittenQuery);-- // Mock the semantic search response- (ragService.semanticSearchForChat as Mock).mockResolvedValue({- chunks: [{ id: 'chunk-1' }],- queryId: 'query-id',- });-- vi.spyOn(agentSelectors, 'currentKnowledgeIds').mockReturnValue({- fileIds: [],- knowledgeBaseIds: [],- });-- const result2 = await act(async () => {- return await result.current.internal_retrieveChunks(messageId, userQuery, ['message']);- });-- expect(result2).toEqual({- chunks: [{ id: 'chunk-1' }],- queryId: 'query-id',- rewriteQuery: rewrittenQuery,- });- expect(result.current.internal_rewriteQuery).toHaveBeenCalledWith(messageId, userQuery, [- 'message',- ]);- });- });-describe('internal_rewriteQuery', () => {it('should return original content if query rewrite is disabled', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.tsindex 9540f2eb0ef..7d6e59be8db 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -712,75 +712,8 @@ describe('StreamingExecutor actions', () => {);});- // TODO: This test is complex to set up properly with agent runtime and message creation- // The functionality is verified in the implementation (streamingExecutor.ts:725-728)- it.skip('should pass context to optimisticUpdateMessageRAG', async () => {- act(() => {- useChatStore.setState({- internal_execAgentRuntime: realExecAgentRuntime,- activeId: 'active-session',- activeTopicId: 'active-topic',- });- });-- const { result } = renderHook(() => useChatStore());-- const contextSessionId = 'context-session';- const contextTopicId = 'context-topic';- const userMessage = {- id: TEST_IDS.USER_MESSAGE_ID,- role: 'user',- content: TEST_CONTENT.USER_MESSAGE,- sessionId: contextSessionId,- topicId: contextTopicId,- } as UIChatMessage;-- const ragMetadata = {- ragQueryId: 'query-id',- fileChunks: [{ id: 'chunk-1', similarity: 0.9 }],- };-- const assistantMessageId = 'assistant-msg-id';- const assistantMessage = {- id: assistantMessageId,- role: 'assistant',- content: TEST_CONTENT.AI_RESPONSE,- sessionId: contextSessionId,- topicId: contextTopicId,- } as UIChatMessage;-- // Mock createMessage to return the assistant message- vi.spyOn(messageService, 'createMessage').mockResolvedValue({- id: assistantMessageId,- messages: [userMessage, assistantMessage],- });-- const updateRAGSpy = vi.spyOn(result.current, 'optimisticUpdateMessageRAG');- const streamSpy = vi- .spyOn(chatService, 'createAssistantMessageStream')- .mockImplementation(async ({ onFinish }) => {- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});- });-- await act(async () => {- await result.current.internal_execAgentRuntime({- messages: [userMessage],- parentMessageId: userMessage.id,- parentMessageType: 'user',- sessionId: contextSessionId,- topicId: contextTopicId,- ragMetadata,- });- });-- // Verify optimisticUpdateMessageRAG was called with context- expect(updateRAGSpy).toHaveBeenCalledWith(expect.any(String), ragMetadata, {- sessionId: contextSessionId,- topicId: contextTopicId,- });-- streamSpy.mockRestore();- });+ // Note: RAG metadata functionality has been removed+ // RAG is now handled by Knowledge Base Tools (searchKnowledgeBase and readKnowledge)});describe('StreamingExecutor OptimisticUpdateContext isolation', () => {diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex b7a43032010..83e22a1f787 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -272,7 +272,6 @@ export const conversationLifecycle: StateCreator<sessionId: activeId,topicId: data.topicId ?? activeTopicId,parentOperationId: operationId, // Pass as parent operation- ragQuery: get().internal_shouldUseRAG() ? message : undefined,threadId: activeThreadId,skipCreateFirstMessage: true,});@@ -338,7 +337,6 @@ export const conversationLifecycle: StateCreator<sessionId: activeId,topicId: activeTopicId,traceId,- ragQuery: get().internal_shouldUseRAG() ? item.content : undefined,threadId: activeThreadId,parentOperationId: operationId,});diff --git a/src/store/chat/slices/aiChat/actions/rag.ts b/src/store/chat/slices/aiChat/actions/rag.tsindex 476a42a4202..070e9b74859 100644--- a/src/store/chat/slices/aiChat/actions/rag.ts+++ b/src/store/chat/slices/aiChat/actions/rag.ts@@ -10,18 +10,9 @@ import { dbMessageSelectors, displayMessageSelectors } from '@/store/chat/selectimport { toggleBooleanList } from '@/store/chat/utils';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';-import { ChatSemanticSearchChunk } from '@/types/chunk';export interface ChatRAGAction {deleteUserMessageRagQuery: (id: string) => Promise<void>;- /**- * Retrieve chunks from semantic search- */- internal_retrieveChunks: (- id: string,- userQuery: string,- messages: string[],- ) => Promise<{ chunks: ChatSemanticSearchChunk[]; queryId?: string; rewriteQuery?: string }>;/*** Rewrite user content to better RAG query*/@@ -35,7 +26,6 @@ export interface ChatRAGAction {rewriteQuery: (id: string) => Promise<void>;}-const knowledgeIds = () => agentSelectors.currentKnowledgeIds(useAgentStore.getState());const hasEnabledKnowledge = () => agentSelectors.hasEnabledKnowledge(useAgentStore.getState());export const chatRag: StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatRAGAction> = (@@ -58,43 +48,6 @@ export const chatRag: StateCreator<ChatStore, [['zustand/devtools', never]], [],await get().refreshMessages();},- internal_retrieveChunks: async (id, userQuery, messages) => {- get().internal_toggleMessageRAGLoading(true, id);-- const message = dbMessageSelectors.getDbMessageById(id)(get());-- // 1. get the rewrite query- let rewriteQuery = message?.ragQuery as string | undefined;-- // if there is no ragQuery and there is a chat history- // we need to rewrite the user message to get better results- if (!message?.ragQuery && messages.length > 0) {- rewriteQuery = await get().internal_rewriteQuery(id, userQuery, messages);- }-- // 2. retrieve chunks from semantic search- const files = dbMessageSelectors- .dbUserFiles(get())- .map((f) => f?.id)- .filter(Boolean) as string[];- try {- const { chunks, queryId } = await ragService.semanticSearchForChat({- fileIds: knowledgeIds().fileIds.concat(files),- knowledgeIds: knowledgeIds().knowledgeBaseIds,- messageId: id,- rewriteQuery: rewriteQuery || userQuery,- userQuery,- });-- get().internal_toggleMessageRAGLoading(false, id);-- return { chunks, queryId, rewriteQuery };- } catch {- get().internal_toggleMessageRAGLoading(false, id);-- return { chunks: [] };- }- },internal_rewriteQuery: async (id, content, messages) => {let rewriteQuery = content;diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 7b61598215c..5a5587077fa 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -2,7 +2,6 @@// Disable the auto sort key eslint rule to make the code more logic and readableimport { AgentRuntime, type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';import { isDesktop } from '@lobechat/const';-import { knowledgeBaseQAPrompts } from '@lobechat/prompts';import {ChatImageItem,ChatToolPayload,@@ -11,19 +10,18 @@ import {TraceNameMap,UIChatMessage,} from '@lobechat/types';-import type { MessageSemanticSearchChunk } from '@lobechat/types';import debug from 'debug';import { t } from 'i18next';import { throttle } from 'lodash-es';import { StateCreator } from 'zustand/vanilla';+import { createAgentToolsEngine } from '@/helpers/toolEngineering';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';import { getAgentStoreState } from '@/store/agent/store';import { GeneralChatAgent } from '@/store/chat/agents/GeneralChatAgent';import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';-import { createAgentToolsEngine } from '@/store/chat/agents/createToolEngine';import { ChatStore } from '@/store/chat/store';import { getFileStoreState } from '@/store/file/store';import { toolInterventionSelectors } from '@/store/user/selectors';@@ -104,15 +102,10 @@ export interface StreamingExecutorAction {*/parentOperationId?: string;inSearchWorkflow?: boolean;- /**- * the RAG query content, should be embedding and used in the semantic search- */- ragQuery?: string;threadId?: string;inPortalThread?: boolean;skipCreateFirstMessage?: boolean;traceId?: string;- ragMetadata?: { ragQueryId: string; fileChunks: MessageSemanticSearchChunk[] };/*** Initial agent state (for resuming execution from a specific point)*/@@ -624,59 +617,17 @@ export const streamingExecutor: StateCreator<const provider = agentConfigData.provider;// ===========================================- // Step 1: RAG Preprocessing (if enabled)+ // Step 1: Knowledge Base Tool Integration// ===========================================- // Skip RAG preprocessing if initialState is provided (messages already preprocessed)- if (params.ragQuery && parentMessageType === 'user') {- const userMessageId = parentMessageId;- log('[internal_execAgentRuntime] RAG preprocessing start');-- // Get relevant chunks from semantic search- const {- chunks,- queryId: ragQueryId,- rewriteQuery,- } = await get().internal_retrieveChunks(- userMessageId,- params.ragQuery,- // Skip the last message content when building context- messages.map((m) => m.content).slice(0, messages.length - 1),- );-- log('[internal_execAgentRuntime] RAG chunks retrieved: %d chunks', chunks.length);-- const lastMsg = messages.pop() as UIChatMessage;-- // Build RAG context and append to user query- const knowledgeBaseQAContext = knowledgeBaseQAPrompts({- chunks,- userQuery: lastMsg.content,- rewriteQuery,- knowledge: agentSelectors.currentEnabledKnowledge(agentStoreState),- });-- messages.push({- ...lastMsg,- content: (lastMsg.content + '\n\n' + knowledgeBaseQAContext).trim(),- });+ // RAG retrieval is now handled by the Knowledge Base Tool+ // The AI will decide when to call searchKnowledgeBase and readKnowledge tools+ // based on the conversation context and available knowledge bases- // Update assistant message with RAG metadata- const fileChunks: MessageSemanticSearchChunk[] = chunks.map((c) => ({- id: c.id,- similarity: c.similarity,- }));-- if (fileChunks.length > 0) {- // Note: RAG metadata will be updated after assistant message is created by call_llm executor- // Store RAG data temporarily in params for later use- params.ragMetadata = { ragQueryId: ragQueryId!, fileChunks };- }-- log('[internal_execAgentRuntime] RAG preprocessing completed');- }+ // TODO: Implement selected files full-text injection if needed+ // User-selected files should be handled differently from knowledge base files// ===========================================- // Step 3: Create and Execute Agent Runtime+ // Step 2: Create and Execute Agent Runtime// ===========================================log('[internal_execAgentRuntime] Creating agent runtime');@@ -829,18 +780,6 @@ export const streamingExecutor: StateCreator<stepCount,);- // Update RAG metadata if available- if (params.ragMetadata) {- const finalMessages = get().messagesMap[messageKey] || [];- const assistantMessage = finalMessages.findLast((m) => m.role === 'assistant');- if (assistantMessage) {- await get().optimisticUpdateMessageRAG(assistantMessage.id, params.ragMetadata, {- operationId,- });- log('[internal_execAgentRuntime] RAG metadata updated for assistant message');- }- }-// Complete operationif (state.status === 'done') {get().completeOperation(operationId);diff --git a/src/store/chat/slices/builtinTool/actions/index.ts b/src/store/chat/slices/builtinTool/actions/index.tsindex 3f3a3280ed3..0a751225bb2 100644--- a/src/store/chat/slices/builtinTool/actions/index.ts+++ b/src/store/chat/slices/builtinTool/actions/index.ts@@ -3,13 +3,15 @@ import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';import { ChatCodeInterpreterAction, codeInterpreterSlice } from './interpreter';+import { KnowledgeBaseAction, knowledgeBaseSlice } from './knowledgeBase';import { LocalFileAction, localSystemSlice } from './localSystem';import { SearchAction, searchSlice } from './search';export interface ChatBuiltinToolActionextends SearchAction,LocalFileAction,- ChatCodeInterpreterAction {}+ ChatCodeInterpreterAction,+ KnowledgeBaseAction {}export const chatToolSlice: StateCreator<ChatStore,@@ -20,4 +22,5 @@ export const chatToolSlice: StateCreator<...searchSlice(...params),...localSystemSlice(...params),...codeInterpreterSlice(...params),+ ...knowledgeBaseSlice(...params),});diff --git a/src/store/chat/slices/builtinTool/actions/knowledgeBase.ts b/src/store/chat/slices/builtinTool/actions/knowledgeBase.tsnew file mode 100644index 00000000000..b2dee86025b--- /dev/null+++ b/src/store/chat/slices/builtinTool/actions/knowledgeBase.ts@@ -0,0 +1,174 @@+import debug from 'debug';+import { StateCreator } from 'zustand/vanilla';++import { agentSelectors } from '@/store/agent/selectors';+import { getAgentStoreState } from '@/store/agent/store';+import { ChatStore } from '@/store/chat/store';+import { KnowledgeBaseExecutionRuntime } from '@/tools/knowledge-base/ExecutionRuntime';++import { dbMessageSelectors } from '../../message/selectors';++const log = debug('lobe-store:builtin-tool:knowledge-base');++export interface KnowledgeBaseAction {+ internal_triggerKnowledgeBaseToolCalling: (+ id: string,+ callingService: () => Promise<{ content: string; error?: any; state?: any; success: boolean }>,+ ) => Promise<boolean>;++ /**+ * Read full content of specific files from knowledge base+ */+ readKnowledge: (+ id: string,+ params: {+ fileIds: string[];+ },+ ) => Promise<boolean>;++ /**+ * Search knowledge base for relevant files and chunks+ */+ searchKnowledgeBase: (+ id: string,+ params: {+ query: string;+ topK?: number;+ },+ ) => Promise<boolean>;+}++const runtime = new KnowledgeBaseExecutionRuntime();++/* eslint-disable sort-keys-fix/sort-keys-fix */+export const knowledgeBaseSlice: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ KnowledgeBaseAction+> = (set, get) => ({+ readKnowledge: async (id, params) => {+ return get().internal_triggerKnowledgeBaseToolCalling(id, async () => {+ return await runtime.readKnowledge(params);+ });+ },++ searchKnowledgeBase: async (id, params) => {+ // Get knowledge base IDs and file IDs from agent store+ const agentState = getAgentStoreState();+ const knowledgeIds = agentSelectors.currentKnowledgeIds(agentState);++ // Get user-selected files from messages+ const userFiles = dbMessageSelectors+ .dbUserFiles(get())+ .map((f) => f?.id)+ .filter(Boolean) as string[];++ // Merge knowledge base files and user-selected files+ const options = {+ fileIds: [...knowledgeIds.fileIds, ...userFiles],+ knowledgeBaseIds: knowledgeIds.knowledgeBaseIds,+ };++ return get().internal_triggerKnowledgeBaseToolCalling(id, async () => {+ return await runtime.searchKnowledgeBase(params, {+ fileIds: options.fileIds,+ knowledgeBaseIds: options.knowledgeBaseIds,+ messageId: id,+ });+ });+ },++ // ==================== utils ====================++ internal_triggerKnowledgeBaseToolCalling: async (id, callingService) => {+ // Get parent operationId from messageOperationMap (should be executeToolCall)+ const parentOperationId = get().messageOperationMap[id];++ // Create child operation for knowledge base execution+ // Auto-associates message with this operation via messageId in context+ const { operationId: knowledgeBaseOpId, abortController } = get().startOperation({+ context: {+ messageId: id,+ },+ metadata: {+ startTime: Date.now(),+ },+ parentOperationId,+ type: 'builtinToolKnowledgeBase',+ });++ log(+ '[knowledgeBase] messageId=%s, parentOpId=%s, knowledgeBaseOpId=%s, aborted=%s',+ id,+ parentOperationId,+ knowledgeBaseOpId,+ abortController.signal.aborted,+ );++ const context = { operationId: knowledgeBaseOpId };++ try {+ const { state, content, success, error } = await callingService();++ // Complete knowledge base operation+ get().completeOperation(knowledgeBaseOpId);++ if (success) {+ if (state) {+ await get().optimisticUpdatePluginState(id, state, context);+ }+ await get().optimisticUpdateMessageContent(id, content, undefined, context);+ } else {+ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: error?.message || 'Operation failed',+ type: 'PluginServerError',+ },+ context,+ );+ // Still update content even if failed, to show error message+ await get().optimisticUpdateMessageContent(id, content, undefined, context);+ }++ return true;+ } catch (error) {+ const err = error as Error;++ log('[knowledgeBase] Error: messageId=%s, error=%s', id, err.message);++ // Check if it's an abort error+ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ log('[knowledgeBase] Request aborted: messageId=%s', id);+ // Fail knowledge base operation for abort+ get().failOperation(knowledgeBaseOpId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ // Don't update error message for user aborts+ return false;+ }++ // Fail knowledge base operation for other errors+ get().failOperation(knowledgeBaseOpId, {+ message: err.message,+ type: 'PluginServerError',+ });++ // For other errors, update message+ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return false;+ }+ },+});diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 52862c30336..98dd5ec3e52 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -36,6 +36,7 @@ export type OperationType =| 'builtinToolSearch' // Builtin tool: search| 'builtinToolInterpreter' // Builtin tool: code interpreter| 'builtinToolLocalSystem' // Builtin tool: local system+ | 'builtinToolKnowledgeBase' // Builtin tool: knowledge base// === Group Chat ===| 'supervisorDecision' // Supervisor decisiondiff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.tsindex 92d6c199e0f..133b520f1ab 100644--- a/src/store/chat/slices/thread/action.test.ts+++ b/src/store/chat/slices/thread/action.test.ts@@ -883,7 +883,6 @@ describe('thread action', () => {parentMessageId: 'new-msg-id',parentMessageType: 'user',inPortalThread: true,- ragQuery: 'test with rag',threadId: 'existing-thread-id',}),);diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.tsindex 01b0ec33695..663852de9c0 100644--- a/src/store/chat/slices/thread/action.ts+++ b/src/store/chat/slices/thread/action.ts@@ -178,7 +178,6 @@ export const chatThreadMessage: StateCreator<parentMessageType: 'user',sessionId: get().activeId,topicId: get().activeTopicId,- ragQuery: get().internal_shouldUseRAG() ? message : undefined,threadId: get().portalThreadId,inPortalThread: true,});diff --git a/src/tools/executionRuntimes.ts b/src/tools/executionRuntimes.tsindex de2b52cac22..2eec5debc91 100644--- a/src/tools/executionRuntimes.ts+++ b/src/tools/executionRuntimes.ts@@ -1,9 +1,12 @@+import { KnowledgeBaseManifest } from './knowledge-base';+import { KnowledgeBaseExecutionRuntime } from './knowledge-base/ExecutionRuntime';import { LocalSystemManifest } from './local-system';import { LocalSystemExecutionRuntime } from './local-system/ExecutionRuntime';import { WebBrowsingManifest } from './web-browsing';import { WebBrowsingExecutionRuntime } from './web-browsing/ExecutionRuntime';export const BuiltinToolServerRuntimes: Record<string, any> = {+ [KnowledgeBaseManifest.identifier]: KnowledgeBaseExecutionRuntime,[LocalSystemManifest.identifier]: LocalSystemExecutionRuntime,[WebBrowsingManifest.identifier]: WebBrowsingExecutionRuntime,};diff --git a/src/tools/identifiers.ts b/src/tools/identifiers.tsnew file mode 100644index 00000000000..a85a0029d3c--- /dev/null+++ b/src/tools/identifiers.ts@@ -0,0 +1,13 @@+import { ArtifactsManifest } from './artifacts';+import { CodeInterpreterManifest } from './code-interpreter';+import { KnowledgeBaseManifest } from './knowledge-base';+import { LocalSystemManifest } from './local-system';+import { WebBrowsingManifest } from './web-browsing';++export const builtinToolIdentifiers: string[] = [+ ArtifactsManifest.identifier,+ LocalSystemManifest.identifier,+ WebBrowsingManifest.identifier,+ KnowledgeBaseManifest.identifier,+ CodeInterpreterManifest.identifier,+];diff --git a/src/tools/index.ts b/src/tools/index.tsindex 51dcb12934a..3ed8525598e 100644--- a/src/tools/index.ts+++ b/src/tools/index.ts@@ -4,6 +4,7 @@ import { isDesktop } from '@/const/version';import { ArtifactsManifest } from './artifacts';import { CodeInterpreterManifest } from './code-interpreter';+import { KnowledgeBaseManifest } from './knowledge-base';import { LocalSystemManifest } from './local-system';import { WebBrowsingManifest } from './web-browsing';@@ -30,4 +31,10 @@ export const builtinTools: LobeBuiltinTool[] = [manifest: CodeInterpreterManifest,type: 'builtin',},+ {+ hidden: true,+ identifier: KnowledgeBaseManifest.identifier,+ manifest: KnowledgeBaseManifest,+ type: 'builtin',+ },];diff --git a/src/tools/knowledge-base/ExecutionRuntime/index.ts b/src/tools/knowledge-base/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..ae8330a1419--- /dev/null+++ b/src/tools/knowledge-base/ExecutionRuntime/index.ts@@ -0,0 +1,96 @@+import { formatSearchResults, promptFileContents, promptNoSearchResults } from '@lobechat/prompts';+import { BuiltinServerRuntimeOutput } from '@lobechat/types';++import { ragService } from '@/services/rag';++import { ReadKnowledgeState, SearchKnowledgeBaseArgs, SearchKnowledgeBaseState } from '../type';++export interface ReadKnowledgeArgs {+ fileIds: string[];+}++export class KnowledgeBaseExecutionRuntime {+ /**+ * Search knowledge base and return file summaries with relevant chunks+ */+ async searchKnowledgeBase(+ args: SearchKnowledgeBaseArgs,+ options?: {+ fileIds?: string[];+ knowledgeBaseIds?: string[];+ messageId?: string;+ signal?: AbortSignal;+ },+ ): Promise<BuiltinServerRuntimeOutput> {+ try {+ const { query, topK = 20 } = args;++ // Call the existing RAG service+ const { chunks, fileResults } = await ragService.semanticSearchForChat(+ { fileIds: options?.fileIds, knowledgeIds: options?.knowledgeBaseIds, query, topK },+ options?.signal,+ );++ if (chunks.length === 0) {+ const state: SearchKnowledgeBaseState = { chunks: [], fileResults: [], totalResults: 0 };++ return { content: promptNoSearchResults(query), state, success: true };+ }++ // Format search results for AI+ const formattedContent = formatSearchResults(fileResults, query);++ const state: SearchKnowledgeBaseState = { chunks, fileResults, totalResults: chunks.length };++ return { content: formattedContent, state, success: true };+ } catch (e) {+ return {+ content: `Error searching knowledge base: ${(e as Error).message}`,+ error: e,+ success: false,+ };+ }+ }++ /**+ * Read full content of specific files from knowledge base+ */+ async readKnowledge(+ args: ReadKnowledgeArgs,+ options?: { signal?: AbortSignal },+ ): Promise<BuiltinServerRuntimeOutput> {+ try {+ const { fileIds } = args;++ if (!fileIds || fileIds.length === 0) {+ return {+ content: 'Error: No file IDs provided',+ success: false,+ };+ }++ const fileContents = await ragService.getFileContents(fileIds, options?.signal);++ const formattedContent = promptFileContents(fileContents);++ const state: ReadKnowledgeState = {+ files: fileContents.map((file) => ({+ error: file.error,+ fileId: file.fileId,+ filename: file.filename,+ preview: file.preview,+ totalCharCount: file.totalCharCount,+ totalLineCount: file.totalLineCount,+ })),+ };++ return { content: formattedContent, state, success: true };+ } catch (e) {+ return {+ content: `Error reading knowledge: ${(e as Error).message}`,+ error: e,+ success: false,+ };+ }+ }+}diff --git a/src/tools/knowledge-base/Render/ReadKnowledge/FileCard.tsx b/src/tools/knowledge-base/Render/ReadKnowledge/FileCard.tsxnew file mode 100644index 00000000000..e9ff6f1d2f0--- /dev/null+++ b/src/tools/knowledge-base/Render/ReadKnowledge/FileCard.tsx@@ -0,0 +1,135 @@+'use client';++import { Alert, Text } from '@lobehub/ui';+import { Descriptions } from 'antd';+import { createStyles } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';++import FileIcon from '@/components/FileIcon';++import { FileContentDetail } from '../../type';++const useStyles = createStyles(({ token, css }) => {+ return {+ cardBody: css`+ padding-block: 12px 8px;+ padding-inline: 16px;+ `,+ container: css`+ overflow: hidden;++ min-width: 360px;+ max-width: 360px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: 12px;+ `,+ description: css`+ margin-block: 0 4px !important;+ color: ${token.colorTextTertiary};+ `,+ footer: css`+ padding-block: 8px;+ padding-inline: 16px;+ border-radius: 8px;++ text-align: center;++ background-color: ${token.colorFillQuaternary};+ `,+ footerText: css`+ font-size: 12px !important;+ color: ${token.colorTextTertiary} !important;+ `,+ icon: css`+ color: ${token.colorTextSecondary};+ `,+ preview: css`+ overflow: hidden;++ max-height: 80px;+ padding: 8px;+ border-radius: 6px;++ font-family: ${token.fontFamilyCode};+ font-size: 12px;+ line-height: 1.5;+ color: ${token.colorTextSecondary};+ `,+ title: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 1;++ margin-block-end: 0;+ `,+ titleRow: css`+ color: ${token.colorText};+ `,+ };+});++interface FileCardProps {+ file: FileContentDetail;+}++const FileCard = memo<FileCardProps>(({ file }) => {+ const { t } = useTranslation('tool');+ const { styles } = useStyles();++ if (file.error) {+ return (+ <Flexbox className={styles.container} gap={8}>+ <Flexbox className={styles.cardBody} gap={8}>+ <Flexbox align={'center'} className={styles.titleRow} gap={8} horizontal>+ <FileIcon fileName={file.filename} size={16} />+ <div className={styles.title}>{file.filename}</div>+ </Flexbox>+ </Flexbox>+ <div className={styles.footer}>+ <Alert message={file.error} type={'error'} variant={'borderless'} />+ </div>+ </Flexbox>+ );+ }++ return (+ <Flexbox className={styles.container} justify={'space-between'}>+ <Flexbox className={styles.cardBody} gap={8}>+ <Flexbox align={'center'} className={styles.titleRow} gap={8} horizontal>+ <FileIcon fileName={file.filename} size={16} />+ <div className={styles.title}>{file.filename}</div>+ </Flexbox>+ {file.preview && (+ <Text className={styles.preview} ellipsis={{ rows: 4 }}>+ {file.preview}...+ </Text>+ )}+ </Flexbox>+ <div className={styles.footer}>+ <Descriptions+ classNames={{+ content: styles.footerText,+ label: styles.footerText,+ }}+ column={2}+ items={[+ {+ children: file.totalCharCount?.toLocaleString(),+ label: t('lobe-knowledge-base.readKnowledge.meta.chars'),+ },+ {+ children: file.totalLineCount?.toLocaleString(),+ label: t('lobe-knowledge-base.readKnowledge.meta.lines'),+ },+ ]}+ size="small"+ />+ </div>+ </Flexbox>+ );+});++export default FileCard;diff --git a/src/tools/knowledge-base/Render/ReadKnowledge/index.tsx b/src/tools/knowledge-base/Render/ReadKnowledge/index.tsxnew file mode 100644index 00000000000..4b2a11df15a--- /dev/null+++ b/src/tools/knowledge-base/Render/ReadKnowledge/index.tsx@@ -0,0 +1,27 @@+import { BuiltinRenderProps } from '@lobechat/types';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { ReadKnowledgeArgs } from '../../ExecutionRuntime';+import { ReadKnowledgeState } from '../../type';+import FileCard from './FileCard';++const ReadKnowledge = memo<BuiltinRenderProps<ReadKnowledgeArgs, ReadKnowledgeState>>(+ ({ pluginState }) => {+ const { files } = pluginState || {};++ if (!files || files.length === 0) {+ return null;+ }++ return (+ <Flexbox gap={12} horizontal style={{ flexWrap: 'wrap' }}>+ {files.map((file) => (+ <FileCard file={file} key={file.fileId} />+ ))}+ </Flexbox>+ );+ },+);++export default ReadKnowledge;diff --git a/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/index.tsx b/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/index.tsxnew file mode 100644index 00000000000..19ba51b2280--- /dev/null+++ b/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/index.tsx@@ -0,0 +1,54 @@+import { FileSearchResult } from '@lobechat/types';+import { Text, Tooltip } from '@lobehub/ui';+import { memo } from 'react';+import { Center, Flexbox } from 'react-layout-kit';++import FileIcon from '@/components/FileIcon';+import { useIsMobile } from '@/hooks/useIsMobile';+import { useChatStore } from '@/store/chat';++import { useStyles } from './style';++export interface FileItemProps extends FileSearchResult {+ index: number;+}++const FileItem = memo<FileItemProps>(({ fileId, fileName, relevanceScore, topChunks }) => {+ const { styles, cx } = useStyles();+ const openFilePreview = useChatStore((s) => s.openFilePreview);++ const isMobile = useIsMobile();++ // Use the first chunk for preview+ const firstChunk = topChunks[0];++ return (+ <Flexbox+ align={'center'}+ className={cx(styles.container, isMobile && styles.mobile)}+ gap={4}+ horizontal+ key={fileId}+ onClick={(e) => {+ e.stopPropagation();+ if (firstChunk) {+ openFilePreview({+ chunkId: firstChunk.id,+ chunkText: firstChunk.text,+ fileId,+ });+ }+ }}+ >+ <FileIcon fileName={fileName} size={20} variant={'raw'} />+ <Flexbox gap={12} horizontal justify={'space-between'} style={{ maxWidth: 200 }}>+ <Text ellipsis>{fileName}</Text>+ <Tooltip title={`Relevance: ${(relevanceScore * 100).toFixed(1)}%`}>+ <Center className={styles.badge}>{relevanceScore.toFixed(2)}</Center>+ </Tooltip>+ </Flexbox>+ </Flexbox>+ );+});++export default FileItem;diff --git a/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/style.ts b/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/style.tsnew file mode 100644index 00000000000..2ffabe50e1f--- /dev/null+++ b/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/style.ts@@ -0,0 +1,51 @@+import { createStyles } from 'antd-style';+import { lighten } from 'polished';++export const useStyles = createStyles(({ css, token, isDarkMode }) => ({+ badge: css`+ padding-block: 4px;+ padding-inline: 6px;+ border-radius: 2222px;++ font-size: 12px;+ line-height: 12px;+ color: ${token.colorTextSecondary};++ background: ${token.colorFillSecondary};+ `,++ container: css`+ cursor: pointer;++ width: fit-content;+ padding-block: 6px;+ padding-inline: 8px;+ padding-inline-end: 12px;+ border-radius: 8px;++ color: ${token.colorText};++ background: ${lighten(0.1, token.colorBgElevated)};+ box-shadow: ${token.boxShadowTertiary};++ transition: all 0.2s;++ &:hover {+ background: ${isDarkMode ? lighten(0.15, token.colorBgElevated) : ''};+ box-shadow: ${token.boxShadowSecondary};+ }+ `,+ filename: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 1;++ font-size: 12px;+ text-overflow: ellipsis;+ `,++ mobile: css`+ width: 100%;+ `,+}));diff --git a/src/tools/knowledge-base/Render/SearchKnowledgeBase/index.tsx b/src/tools/knowledge-base/Render/SearchKnowledgeBase/index.tsxnew file mode 100644index 00000000000..b056c9c3e13--- /dev/null+++ b/src/tools/knowledge-base/Render/SearchKnowledgeBase/index.tsx@@ -0,0 +1,23 @@+import { BuiltinRenderProps } from '@lobechat/types';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { SearchKnowledgeBaseArgs, SearchKnowledgeBaseState } from '@/tools/knowledge-base/type';++import FileItem from './Item';++const SearchKnowledgeBase = memo<+ BuiltinRenderProps<SearchKnowledgeBaseArgs, SearchKnowledgeBaseState>+>(({ pluginState }) => {+ const { fileResults } = pluginState || {};++ return (+ <Flexbox gap={8} horizontal wrap={'wrap'}>+ {fileResults?.map((file, index) => {+ return <FileItem index={index} key={file.fileId} {...file} />;+ })}+ </Flexbox>+ );+});++export default SearchKnowledgeBase;diff --git a/src/tools/knowledge-base/Render/index.ts b/src/tools/knowledge-base/Render/index.tsnew file mode 100644index 00000000000..650bb4cad6b--- /dev/null+++ b/src/tools/knowledge-base/Render/index.ts@@ -0,0 +1,7 @@+import ReadKnowledge from './ReadKnowledge';+import SearchKnowledgeBase from './SearchKnowledgeBase';++export const KnowledgeBaseRenders = {+ readKnowledge: ReadKnowledge,+ searchKnowledgeBase: SearchKnowledgeBase,+};diff --git a/src/tools/knowledge-base/index.ts b/src/tools/knowledge-base/index.tsnew file mode 100644index 00000000000..b68d386241c--- /dev/null+++ b/src/tools/knowledge-base/index.ts@@ -0,0 +1,64 @@+import { BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';++export const KnowledgeBaseApiName = {+ readKnowledge: 'readKnowledge',+ searchKnowledgeBase: 'searchKnowledgeBase',+};++export const KnowledgeBaseManifest: BuiltinToolManifest = {+ api: [+ {+ description:+ 'Search through knowledge base using semantic vector search to find relevant files and chunks. Returns a summary of matching files with their relevance scores and brief excerpts. Use this first to discover which files contain relevant information. IMPORTANT: Since this uses vector-based search, always resolve pronouns and references to concrete entities (e.g., use "authentication system" instead of "it").',+ name: KnowledgeBaseApiName.searchKnowledgeBase,+ parameters: {+ properties: {+ query: {+ description:+ 'The search query to find relevant information. Be specific and use concrete entities. IMPORTANT: Resolve all pronouns and references (like "it", "that", "this") to actual entity names before searching, as this uses semantic vector search which works best with concrete terms.',+ type: 'string',+ },+ topK: {+ default: 15,+ description:+ 'Number of top relevant chunks to return (default: 15). Each file will include the most relevant chunks.',+ maximum: 100,+ minimum: 5,+ type: 'number',+ },+ },+ required: ['query'],+ type: 'object',+ },+ },+ {+ description:+ 'Read the full content of specific files from the knowledge base. Use this after searchKnowledgeBase to get complete information from relevant files. You can read multiple files at once.',+ name: KnowledgeBaseApiName.readKnowledge,+ parameters: {+ properties: {+ fileIds: {+ description:+ 'Array of file IDs to read. Get these IDs from searchKnowledgeBase results.',+ items: {+ type: 'string',+ },+ type: 'array',+ },+ },+ required: ['fileIds'],+ type: 'object',+ },+ },+ ],+ identifier: 'lobe-knowledge-base',+ meta: {+ avatar: '📚',+ description: 'Search and retrieve information from knowledge bases',+ title: 'Knowledge Base',+ },+ systemRole: systemPrompt,+ type: 'builtin',+};diff --git a/src/tools/knowledge-base/systemRole.ts b/src/tools/knowledge-base/systemRole.tsnew file mode 100644index 00000000000..e5123d1ad7c--- /dev/null+++ b/src/tools/knowledge-base/systemRole.ts@@ -0,0 +1,102 @@+export const systemPrompt = `You have access to a Knowledge Base tool with powerful semantic search and document retrieval capabilities. You can search through knowledge bases to find relevant information and read the full content of files.++<core_capabilities>+1. Search through knowledge base using semantic search (searchKnowledgeBase)+2. Read the full content of specific files from the knowledge base (readKnowledge)+</core_capabilities>++<workflow>+1. Understand the user's information need or question+2. Formulate a clear, specific search query+3. Use searchKnowledgeBase to discover relevant files and chunks+4. Review search results to identify the most relevant files+5. Use readKnowledge to retrieve full content from selected files+6. Synthesize information and answer the user's question+7. Always cite source files when providing information+</workflow>++<tool_selection_guidelines>+- **searchKnowledgeBase**: Use this first to discover which files contain relevant information+ - Uses semantic vector search to find relevant content+ - Returns file names, relevance scores, and brief excerpts+ - Helps you decide which files to read in full+ - You can adjust topK parameter (5-100, default: 15) based on how many results you need+ - **IMPORTANT**: Since this uses vector-based semantic search, always resolve references and use concrete entities in your query+ - BAD: "What does it do?" or "Tell me about that feature"+ - GOOD: "What does the authentication system do?" or "Tell me about the JWT authentication feature"++- **readKnowledge**: Use this after searching to get complete file content+ - Can read multiple files at once by providing their file IDs+ - Get file IDs from searchKnowledgeBase results+ - Provides complete context from the selected files+</tool_selection_guidelines>++<search_strategy_guidelines>+- **Coreference Resolution**: Always resolve pronouns and references to concrete entities before searching+ - Replace "it", "that", "this", "them" with the actual entity names+ - Use full names instead of abbreviations when first searching+ - Include relevant context in the query itself+ - Examples:+ - User asks: "What are its features?" (after discussing "authentication system")+ - Search query should be: "authentication system features" (NOT "its features")+ - User asks: "How does that work?"+ - Search query should include the specific topic being discussed+- Formulate clear and specific search queries that capture the core information need+- For broad topics, start with a general query then refine if needed+- For specific questions, use precise terminology+- You can perform multiple searches with different queries or perspectives if needed+- Adjust topK based on result quality - increase if you need more context, decrease for focused searches+- Review the relevance scores and excerpts to select the most pertinent files+</search_strategy_guidelines>++<reading_strategy_guidelines>+- Read only the files that are most relevant to avoid information overload+- You can read multiple files at once if they all contain relevant information+- Prioritize files with higher relevance scores from search results+- If search results show many relevant files, consider reading them in batches+</reading_strategy_guidelines>++<citation_requirements>+- Always cite the source files when providing information+- Reference file names clearly in your response+- If specific information comes from a particular file, mention it explicitly+- Help users understand which knowledge base files support your answers+</citation_requirements>++<response_format>+When providing information from the knowledge base:+1. Start with a direct answer to the user's question when possible+2. Provide relevant details and context from the knowledge base files+3. Clearly cite which files the information comes from+4. If information is insufficient or not found, inform the user clearly+5. Suggest related searches if the initial search doesn't yield good results+</response_format>++<best_practices>+- Always start with searchKnowledgeBase before reading files+- Don't read files blindly - review search results first+- Be selective about which files to read based on relevance+- If no relevant information is found, clearly inform the user+- Suggest alternative search queries if initial results are poor+- Respect the knowledge base's scope - it may not contain all information+- Combine information from multiple files when appropriate+- Maintain accuracy - only cite information actually present in the files+</best_practices>++<error_handling>+- If search returns no results:+ 1. Try reformulating the query with different keywords or broader terms+ 2. Suggest alternative search approaches to the user+ 3. Inform the user if the topic appears to be outside the knowledge base's scope++- If file reading fails:+ 1. Inform the user which files couldn't be accessed+ 2. Work with successfully retrieved files if any+ 3. Suggest searching again if necessary++- If search results are ambiguous:+ 1. Ask for clarification from the user+ 2. Provide a summary of what types of information were found+ 3. Let the user guide which direction to explore further+</error_handling>+`;diff --git a/src/tools/knowledge-base/type.ts b/src/tools/knowledge-base/type.tsnew file mode 100644index 00000000000..f98b600c95b--- /dev/null+++ b/src/tools/knowledge-base/type.ts@@ -0,0 +1,25 @@+import { ChatSemanticSearchChunk, FileSearchResult } from '@lobechat/types';+++export interface SearchKnowledgeBaseArgs {+ query: string;+ topK?: number;+}+export interface SearchKnowledgeBaseState {+ chunks: ChatSemanticSearchChunk[];+ fileResults: FileSearchResult[];+ totalResults: number;+}++export interface FileContentDetail {+ error?: string;+ fileId: string;+ filename: string;+ preview?: string;+ totalCharCount?: number;+ totalLineCount?: number;+}++export interface ReadKnowledgeState {+ files: FileContentDetail[];+}diff --git a/src/tools/local-system/Intervention/WriteFile/index.tsx b/src/tools/local-system/Intervention/WriteFile/index.tsxindex d6347692320..252613769a0 100644--- a/src/tools/local-system/Intervention/WriteFile/index.tsx+++ b/src/tools/local-system/Intervention/WriteFile/index.tsx@@ -11,7 +11,7 @@ import { LocalFile, LocalFolder } from '@/features/LocalFile';const WriteFile = memo<BuiltinInterventionProps<WriteLocalFileParams>>(({ args }) => {const { t } = useTranslation('tool');- const { base, dir, ext } = path.parse(args.path);+ const { base, dir, ext } = path.parse(args.path || '');// Detect language from file extensionconst language = useMemo(() => {diff --git a/src/tools/renders.ts b/src/tools/renders.tsindex 7714ff6aa9c..25380bff694 100644--- a/src/tools/renders.ts+++ b/src/tools/renders.ts@@ -2,6 +2,9 @@ import { BuiltinRender } from '@lobechat/types';import { CodeInterpreterManifest } from './code-interpreter';import CodeInterpreterRender from './code-interpreter/Render';+// knowledge-base+import { KnowledgeBaseManifest } from './knowledge-base';+import { KnowledgeBaseRenders } from './knowledge-base/Render';// local-systemimport { LocalSystemManifest } from './local-system';import { LocalSystemRenders } from './local-system/Render';@@ -16,6 +19,7 @@ import { WebBrowsingRenders } from './web-browsing/Render';const BuiltinToolsRenders: Record<string, Record<string, BuiltinRender>> = {[LocalSystemManifest.identifier]: LocalSystemRenders as Record<string, BuiltinRender>,[WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,+ [KnowledgeBaseManifest.identifier]: KnowledgeBaseRenders as Record<string, BuiltinRender>,[CodeInterpreterManifest.identifier]: {python: CodeInterpreterRender as BuiltinRender,},