AstrBot 3.5.6__py3-none-any.whl → 4.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. astrbot/api/__init__.py +16 -4
  2. astrbot/api/all.py +2 -1
  3. astrbot/api/event/__init__.py +5 -6
  4. astrbot/api/event/filter/__init__.py +37 -34
  5. astrbot/api/platform/__init__.py +7 -8
  6. astrbot/api/provider/__init__.py +8 -7
  7. astrbot/api/star/__init__.py +3 -4
  8. astrbot/api/util/__init__.py +2 -2
  9. astrbot/cli/__init__.py +1 -0
  10. astrbot/cli/__main__.py +18 -197
  11. astrbot/cli/commands/__init__.py +6 -0
  12. astrbot/cli/commands/cmd_conf.py +209 -0
  13. astrbot/cli/commands/cmd_init.py +56 -0
  14. astrbot/cli/commands/cmd_plug.py +245 -0
  15. astrbot/cli/commands/cmd_run.py +62 -0
  16. astrbot/cli/utils/__init__.py +18 -0
  17. astrbot/cli/utils/basic.py +76 -0
  18. astrbot/cli/utils/plugin.py +246 -0
  19. astrbot/cli/utils/version_comparator.py +90 -0
  20. astrbot/core/__init__.py +17 -19
  21. astrbot/core/agent/agent.py +14 -0
  22. astrbot/core/agent/handoff.py +38 -0
  23. astrbot/core/agent/hooks.py +30 -0
  24. astrbot/core/agent/mcp_client.py +385 -0
  25. astrbot/core/agent/message.py +175 -0
  26. astrbot/core/agent/response.py +14 -0
  27. astrbot/core/agent/run_context.py +22 -0
  28. astrbot/core/agent/runners/__init__.py +3 -0
  29. astrbot/core/agent/runners/base.py +65 -0
  30. astrbot/core/agent/runners/coze/coze_agent_runner.py +367 -0
  31. astrbot/core/agent/runners/coze/coze_api_client.py +324 -0
  32. astrbot/core/agent/runners/dashscope/dashscope_agent_runner.py +403 -0
  33. astrbot/core/agent/runners/dify/dify_agent_runner.py +336 -0
  34. astrbot/core/agent/runners/dify/dify_api_client.py +195 -0
  35. astrbot/core/agent/runners/tool_loop_agent_runner.py +400 -0
  36. astrbot/core/agent/tool.py +285 -0
  37. astrbot/core/agent/tool_executor.py +17 -0
  38. astrbot/core/astr_agent_context.py +19 -0
  39. astrbot/core/astr_agent_hooks.py +36 -0
  40. astrbot/core/astr_agent_run_util.py +80 -0
  41. astrbot/core/astr_agent_tool_exec.py +246 -0
  42. astrbot/core/astrbot_config_mgr.py +275 -0
  43. astrbot/core/config/__init__.py +2 -2
  44. astrbot/core/config/astrbot_config.py +60 -20
  45. astrbot/core/config/default.py +1972 -453
  46. astrbot/core/config/i18n_utils.py +110 -0
  47. astrbot/core/conversation_mgr.py +285 -75
  48. astrbot/core/core_lifecycle.py +167 -62
  49. astrbot/core/db/__init__.py +305 -102
  50. astrbot/core/db/migration/helper.py +69 -0
  51. astrbot/core/db/migration/migra_3_to_4.py +357 -0
  52. astrbot/core/db/migration/migra_45_to_46.py +44 -0
  53. astrbot/core/db/migration/migra_webchat_session.py +131 -0
  54. astrbot/core/db/migration/shared_preferences_v3.py +48 -0
  55. astrbot/core/db/migration/sqlite_v3.py +497 -0
  56. astrbot/core/db/po.py +259 -55
  57. astrbot/core/db/sqlite.py +773 -528
  58. astrbot/core/db/vec_db/base.py +73 -0
  59. astrbot/core/db/vec_db/faiss_impl/__init__.py +3 -0
  60. astrbot/core/db/vec_db/faiss_impl/document_storage.py +392 -0
  61. astrbot/core/db/vec_db/faiss_impl/embedding_storage.py +93 -0
  62. astrbot/core/db/vec_db/faiss_impl/sqlite_init.sql +17 -0
  63. astrbot/core/db/vec_db/faiss_impl/vec_db.py +204 -0
  64. astrbot/core/event_bus.py +26 -22
  65. astrbot/core/exceptions.py +9 -0
  66. astrbot/core/file_token_service.py +98 -0
  67. astrbot/core/initial_loader.py +19 -10
  68. astrbot/core/knowledge_base/chunking/__init__.py +9 -0
  69. astrbot/core/knowledge_base/chunking/base.py +25 -0
  70. astrbot/core/knowledge_base/chunking/fixed_size.py +59 -0
  71. astrbot/core/knowledge_base/chunking/recursive.py +161 -0
  72. astrbot/core/knowledge_base/kb_db_sqlite.py +301 -0
  73. astrbot/core/knowledge_base/kb_helper.py +642 -0
  74. astrbot/core/knowledge_base/kb_mgr.py +330 -0
  75. astrbot/core/knowledge_base/models.py +120 -0
  76. astrbot/core/knowledge_base/parsers/__init__.py +13 -0
  77. astrbot/core/knowledge_base/parsers/base.py +51 -0
  78. astrbot/core/knowledge_base/parsers/markitdown_parser.py +26 -0
  79. astrbot/core/knowledge_base/parsers/pdf_parser.py +101 -0
  80. astrbot/core/knowledge_base/parsers/text_parser.py +42 -0
  81. astrbot/core/knowledge_base/parsers/url_parser.py +103 -0
  82. astrbot/core/knowledge_base/parsers/util.py +13 -0
  83. astrbot/core/knowledge_base/prompts.py +65 -0
  84. astrbot/core/knowledge_base/retrieval/__init__.py +14 -0
  85. astrbot/core/knowledge_base/retrieval/hit_stopwords.txt +767 -0
  86. astrbot/core/knowledge_base/retrieval/manager.py +276 -0
  87. astrbot/core/knowledge_base/retrieval/rank_fusion.py +142 -0
  88. astrbot/core/knowledge_base/retrieval/sparse_retriever.py +136 -0
  89. astrbot/core/log.py +21 -15
  90. astrbot/core/message/components.py +413 -287
  91. astrbot/core/message/message_event_result.py +35 -24
  92. astrbot/core/persona_mgr.py +192 -0
  93. astrbot/core/pipeline/__init__.py +14 -14
  94. astrbot/core/pipeline/content_safety_check/stage.py +13 -9
  95. astrbot/core/pipeline/content_safety_check/strategies/__init__.py +1 -2
  96. astrbot/core/pipeline/content_safety_check/strategies/baidu_aip.py +13 -14
  97. astrbot/core/pipeline/content_safety_check/strategies/keywords.py +2 -1
  98. astrbot/core/pipeline/content_safety_check/strategies/strategy.py +6 -6
  99. astrbot/core/pipeline/context.py +7 -1
  100. astrbot/core/pipeline/context_utils.py +107 -0
  101. astrbot/core/pipeline/preprocess_stage/stage.py +63 -36
  102. astrbot/core/pipeline/process_stage/method/agent_request.py +48 -0
  103. astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py +464 -0
  104. astrbot/core/pipeline/process_stage/method/agent_sub_stages/third_party.py +202 -0
  105. astrbot/core/pipeline/process_stage/method/star_request.py +26 -32
  106. astrbot/core/pipeline/process_stage/stage.py +21 -15
  107. astrbot/core/pipeline/process_stage/utils.py +125 -0
  108. astrbot/core/pipeline/rate_limit_check/stage.py +34 -36
  109. astrbot/core/pipeline/respond/stage.py +142 -101
  110. astrbot/core/pipeline/result_decorate/stage.py +124 -57
  111. astrbot/core/pipeline/scheduler.py +21 -16
  112. astrbot/core/pipeline/session_status_check/stage.py +37 -0
  113. astrbot/core/pipeline/stage.py +11 -76
  114. astrbot/core/pipeline/waking_check/stage.py +69 -33
  115. astrbot/core/pipeline/whitelist_check/stage.py +10 -7
  116. astrbot/core/platform/__init__.py +6 -6
  117. astrbot/core/platform/astr_message_event.py +107 -129
  118. astrbot/core/platform/astrbot_message.py +32 -12
  119. astrbot/core/platform/manager.py +62 -18
  120. astrbot/core/platform/message_session.py +30 -0
  121. astrbot/core/platform/platform.py +16 -24
  122. astrbot/core/platform/platform_metadata.py +9 -4
  123. astrbot/core/platform/register.py +12 -7
  124. astrbot/core/platform/sources/aiocqhttp/aiocqhttp_message_event.py +136 -60
  125. astrbot/core/platform/sources/aiocqhttp/aiocqhttp_platform_adapter.py +126 -46
  126. astrbot/core/platform/sources/dingtalk/dingtalk_adapter.py +63 -31
  127. astrbot/core/platform/sources/dingtalk/dingtalk_event.py +30 -26
  128. astrbot/core/platform/sources/discord/client.py +129 -0
  129. astrbot/core/platform/sources/discord/components.py +139 -0
  130. astrbot/core/platform/sources/discord/discord_platform_adapter.py +473 -0
  131. astrbot/core/platform/sources/discord/discord_platform_event.py +313 -0
  132. astrbot/core/platform/sources/lark/lark_adapter.py +27 -18
  133. astrbot/core/platform/sources/lark/lark_event.py +39 -13
  134. astrbot/core/platform/sources/misskey/misskey_adapter.py +770 -0
  135. astrbot/core/platform/sources/misskey/misskey_api.py +964 -0
  136. astrbot/core/platform/sources/misskey/misskey_event.py +163 -0
  137. astrbot/core/platform/sources/misskey/misskey_utils.py +550 -0
  138. astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py +149 -33
  139. astrbot/core/platform/sources/qqofficial/qqofficial_platform_adapter.py +41 -26
  140. astrbot/core/platform/sources/qqofficial_webhook/qo_webhook_adapter.py +36 -17
  141. astrbot/core/platform/sources/qqofficial_webhook/qo_webhook_event.py +3 -1
  142. astrbot/core/platform/sources/qqofficial_webhook/qo_webhook_server.py +14 -8
  143. astrbot/core/platform/sources/satori/satori_adapter.py +792 -0
  144. astrbot/core/platform/sources/satori/satori_event.py +432 -0
  145. astrbot/core/platform/sources/slack/client.py +164 -0
  146. astrbot/core/platform/sources/slack/slack_adapter.py +416 -0
  147. astrbot/core/platform/sources/slack/slack_event.py +253 -0
  148. astrbot/core/platform/sources/telegram/tg_adapter.py +100 -43
  149. astrbot/core/platform/sources/telegram/tg_event.py +136 -36
  150. astrbot/core/platform/sources/webchat/webchat_adapter.py +72 -22
  151. astrbot/core/platform/sources/webchat/webchat_event.py +46 -22
  152. astrbot/core/platform/sources/webchat/webchat_queue_mgr.py +35 -0
  153. astrbot/core/platform/sources/wechatpadpro/wechatpadpro_adapter.py +926 -0
  154. astrbot/core/platform/sources/wechatpadpro/wechatpadpro_message_event.py +178 -0
  155. astrbot/core/platform/sources/wechatpadpro/xml_data_parser.py +159 -0
  156. astrbot/core/platform/sources/wecom/wecom_adapter.py +169 -27
  157. astrbot/core/platform/sources/wecom/wecom_event.py +162 -77
  158. astrbot/core/platform/sources/wecom/wecom_kf.py +279 -0
  159. astrbot/core/platform/sources/wecom/wecom_kf_message.py +196 -0
  160. astrbot/core/platform/sources/wecom_ai_bot/WXBizJsonMsgCrypt.py +297 -0
  161. astrbot/core/platform/sources/wecom_ai_bot/__init__.py +15 -0
  162. astrbot/core/platform/sources/wecom_ai_bot/ierror.py +19 -0
  163. astrbot/core/platform/sources/wecom_ai_bot/wecomai_adapter.py +472 -0
  164. astrbot/core/platform/sources/wecom_ai_bot/wecomai_api.py +417 -0
  165. astrbot/core/platform/sources/wecom_ai_bot/wecomai_event.py +152 -0
  166. astrbot/core/platform/sources/wecom_ai_bot/wecomai_queue_mgr.py +153 -0
  167. astrbot/core/platform/sources/wecom_ai_bot/wecomai_server.py +168 -0
  168. astrbot/core/platform/sources/wecom_ai_bot/wecomai_utils.py +209 -0
  169. astrbot/core/platform/sources/weixin_official_account/weixin_offacc_adapter.py +306 -0
  170. astrbot/core/platform/sources/weixin_official_account/weixin_offacc_event.py +186 -0
  171. astrbot/core/platform_message_history_mgr.py +49 -0
  172. astrbot/core/provider/__init__.py +2 -3
  173. astrbot/core/provider/entites.py +8 -8
  174. astrbot/core/provider/entities.py +154 -98
  175. astrbot/core/provider/func_tool_manager.py +446 -458
  176. astrbot/core/provider/manager.py +345 -207
  177. astrbot/core/provider/provider.py +188 -73
  178. astrbot/core/provider/register.py +9 -7
  179. astrbot/core/provider/sources/anthropic_source.py +295 -115
  180. astrbot/core/provider/sources/azure_tts_source.py +224 -0
  181. astrbot/core/provider/sources/bailian_rerank_source.py +236 -0
  182. astrbot/core/provider/sources/dashscope_tts.py +138 -14
  183. astrbot/core/provider/sources/edge_tts_source.py +24 -19
  184. astrbot/core/provider/sources/fishaudio_tts_api_source.py +58 -13
  185. astrbot/core/provider/sources/gemini_embedding_source.py +61 -0
  186. astrbot/core/provider/sources/gemini_source.py +310 -132
  187. astrbot/core/provider/sources/gemini_tts_source.py +81 -0
  188. astrbot/core/provider/sources/groq_source.py +15 -0
  189. astrbot/core/provider/sources/gsv_selfhosted_source.py +151 -0
  190. astrbot/core/provider/sources/gsvi_tts_source.py +14 -7
  191. astrbot/core/provider/sources/minimax_tts_api_source.py +159 -0
  192. astrbot/core/provider/sources/openai_embedding_source.py +40 -0
  193. astrbot/core/provider/sources/openai_source.py +241 -145
  194. astrbot/core/provider/sources/openai_tts_api_source.py +18 -7
  195. astrbot/core/provider/sources/sensevoice_selfhosted_source.py +13 -11
  196. astrbot/core/provider/sources/vllm_rerank_source.py +71 -0
  197. astrbot/core/provider/sources/volcengine_tts.py +115 -0
  198. astrbot/core/provider/sources/whisper_api_source.py +18 -13
  199. astrbot/core/provider/sources/whisper_selfhosted_source.py +19 -12
  200. astrbot/core/provider/sources/xinference_rerank_source.py +116 -0
  201. astrbot/core/provider/sources/xinference_stt_provider.py +197 -0
  202. astrbot/core/provider/sources/zhipu_source.py +6 -73
  203. astrbot/core/star/__init__.py +43 -11
  204. astrbot/core/star/config.py +17 -18
  205. astrbot/core/star/context.py +362 -138
  206. astrbot/core/star/filter/__init__.py +4 -3
  207. astrbot/core/star/filter/command.py +111 -35
  208. astrbot/core/star/filter/command_group.py +46 -34
  209. astrbot/core/star/filter/custom_filter.py +6 -5
  210. astrbot/core/star/filter/event_message_type.py +4 -2
  211. astrbot/core/star/filter/permission.py +4 -2
  212. astrbot/core/star/filter/platform_adapter_type.py +45 -12
  213. astrbot/core/star/filter/regex.py +4 -2
  214. astrbot/core/star/register/__init__.py +19 -15
  215. astrbot/core/star/register/star.py +41 -13
  216. astrbot/core/star/register/star_handler.py +236 -86
  217. astrbot/core/star/session_llm_manager.py +280 -0
  218. astrbot/core/star/session_plugin_manager.py +170 -0
  219. astrbot/core/star/star.py +36 -43
  220. astrbot/core/star/star_handler.py +47 -85
  221. astrbot/core/star/star_manager.py +442 -260
  222. astrbot/core/star/star_tools.py +167 -45
  223. astrbot/core/star/updator.py +17 -20
  224. astrbot/core/umop_config_router.py +106 -0
  225. astrbot/core/updator.py +38 -13
  226. astrbot/core/utils/astrbot_path.py +39 -0
  227. astrbot/core/utils/command_parser.py +1 -1
  228. astrbot/core/utils/io.py +119 -60
  229. astrbot/core/utils/log_pipe.py +1 -1
  230. astrbot/core/utils/metrics.py +11 -10
  231. astrbot/core/utils/migra_helper.py +73 -0
  232. astrbot/core/utils/path_util.py +63 -62
  233. astrbot/core/utils/pip_installer.py +37 -15
  234. astrbot/core/utils/session_lock.py +29 -0
  235. astrbot/core/utils/session_waiter.py +19 -20
  236. astrbot/core/utils/shared_preferences.py +174 -34
  237. astrbot/core/utils/t2i/__init__.py +4 -1
  238. astrbot/core/utils/t2i/local_strategy.py +386 -238
  239. astrbot/core/utils/t2i/network_strategy.py +109 -49
  240. astrbot/core/utils/t2i/renderer.py +29 -14
  241. astrbot/core/utils/t2i/template/astrbot_powershell.html +184 -0
  242. astrbot/core/utils/t2i/template_manager.py +111 -0
  243. astrbot/core/utils/tencent_record_helper.py +115 -1
  244. astrbot/core/utils/version_comparator.py +10 -13
  245. astrbot/core/zip_updator.py +112 -65
  246. astrbot/dashboard/routes/__init__.py +20 -13
  247. astrbot/dashboard/routes/auth.py +20 -9
  248. astrbot/dashboard/routes/chat.py +297 -141
  249. astrbot/dashboard/routes/config.py +652 -55
  250. astrbot/dashboard/routes/conversation.py +107 -37
  251. astrbot/dashboard/routes/file.py +26 -0
  252. astrbot/dashboard/routes/knowledge_base.py +1244 -0
  253. astrbot/dashboard/routes/log.py +27 -2
  254. astrbot/dashboard/routes/persona.py +202 -0
  255. astrbot/dashboard/routes/plugin.py +197 -139
  256. astrbot/dashboard/routes/route.py +27 -7
  257. astrbot/dashboard/routes/session_management.py +354 -0
  258. astrbot/dashboard/routes/stat.py +85 -18
  259. astrbot/dashboard/routes/static_file.py +5 -2
  260. astrbot/dashboard/routes/t2i.py +233 -0
  261. astrbot/dashboard/routes/tools.py +184 -120
  262. astrbot/dashboard/routes/update.py +59 -36
  263. astrbot/dashboard/server.py +96 -36
  264. astrbot/dashboard/utils.py +165 -0
  265. astrbot-4.7.0.dist-info/METADATA +294 -0
  266. astrbot-4.7.0.dist-info/RECORD +274 -0
  267. {astrbot-3.5.6.dist-info → astrbot-4.7.0.dist-info}/WHEEL +1 -1
  268. astrbot/core/db/plugin/sqlite_impl.py +0 -112
  269. astrbot/core/db/sqlite_init.sql +0 -50
  270. astrbot/core/pipeline/platform_compatibility/stage.py +0 -56
  271. astrbot/core/pipeline/process_stage/method/llm_request.py +0 -606
  272. astrbot/core/platform/sources/gewechat/client.py +0 -806
  273. astrbot/core/platform/sources/gewechat/downloader.py +0 -55
  274. astrbot/core/platform/sources/gewechat/gewechat_event.py +0 -255
  275. astrbot/core/platform/sources/gewechat/gewechat_platform_adapter.py +0 -103
  276. astrbot/core/platform/sources/gewechat/xml_data_parser.py +0 -110
  277. astrbot/core/provider/sources/dashscope_source.py +0 -203
  278. astrbot/core/provider/sources/dify_source.py +0 -281
  279. astrbot/core/provider/sources/llmtuner_source.py +0 -132
  280. astrbot/core/rag/embedding/openai_source.py +0 -20
  281. astrbot/core/rag/knowledge_db_mgr.py +0 -94
  282. astrbot/core/rag/store/__init__.py +0 -9
  283. astrbot/core/rag/store/chroma_db.py +0 -42
  284. astrbot/core/utils/dify_api_client.py +0 -152
  285. astrbot-3.5.6.dist-info/METADATA +0 -249
  286. astrbot-3.5.6.dist-info/RECORD +0 -158
  287. {astrbot-3.5.6.dist-info → astrbot-4.7.0.dist-info}/entry_points.txt +0 -0
  288. {astrbot-3.5.6.dist-info → astrbot-4.7.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,330 @@
1
+ import traceback
2
+ from pathlib import Path
3
+
4
+ from astrbot.core import logger
5
+ from astrbot.core.provider.manager import ProviderManager
6
+
7
+ # from .chunking.fixed_size import FixedSizeChunker
8
+ from .chunking.recursive import RecursiveCharacterChunker
9
+ from .kb_db_sqlite import KBSQLiteDatabase
10
+ from .kb_helper import KBHelper
11
+ from .models import KBDocument, KnowledgeBase
12
+ from .retrieval.manager import RetrievalManager, RetrievalResult
13
+ from .retrieval.rank_fusion import RankFusion
14
+ from .retrieval.sparse_retriever import SparseRetriever
15
+
16
+ FILES_PATH = "data/knowledge_base"
17
+ DB_PATH = Path(FILES_PATH) / "kb.db"
18
+ """Knowledge Base storage root directory"""
19
+ CHUNKER = RecursiveCharacterChunker()
20
+
21
+
22
+ class KnowledgeBaseManager:
23
+ kb_db: KBSQLiteDatabase
24
+ retrieval_manager: RetrievalManager
25
+
26
+ def __init__(
27
+ self,
28
+ provider_manager: ProviderManager,
29
+ ):
30
+ Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)
31
+ self.provider_manager = provider_manager
32
+ self._session_deleted_callback_registered = False
33
+
34
+ self.kb_insts: dict[str, KBHelper] = {}
35
+
36
+ async def initialize(self):
37
+ """初始化知识库模块"""
38
+ try:
39
+ logger.info("正在初始化知识库模块...")
40
+
41
+ # 初始化数据库
42
+ await self._init_kb_database()
43
+
44
+ # 初始化检索管理器
45
+ sparse_retriever = SparseRetriever(self.kb_db)
46
+ rank_fusion = RankFusion(self.kb_db)
47
+ self.retrieval_manager = RetrievalManager(
48
+ sparse_retriever=sparse_retriever,
49
+ rank_fusion=rank_fusion,
50
+ kb_db=self.kb_db,
51
+ )
52
+ await self.load_kbs()
53
+
54
+ except ImportError as e:
55
+ logger.error(f"知识库模块导入失败: {e}")
56
+ logger.warning("请确保已安装所需依赖: pypdf, aiofiles, Pillow, rank-bm25")
57
+ except Exception as e:
58
+ logger.error(f"知识库模块初始化失败: {e}")
59
+ logger.error(traceback.format_exc())
60
+
61
+ async def _init_kb_database(self):
62
+ self.kb_db = KBSQLiteDatabase(DB_PATH.as_posix())
63
+ await self.kb_db.initialize()
64
+ await self.kb_db.migrate_to_v1()
65
+ logger.info(f"KnowledgeBase database initialized: {DB_PATH}")
66
+
67
+ async def load_kbs(self):
68
+ """加载所有知识库实例"""
69
+ kb_records = await self.kb_db.list_kbs()
70
+ for record in kb_records:
71
+ kb_helper = KBHelper(
72
+ kb_db=self.kb_db,
73
+ kb=record,
74
+ provider_manager=self.provider_manager,
75
+ kb_root_dir=FILES_PATH,
76
+ chunker=CHUNKER,
77
+ )
78
+ await kb_helper.initialize()
79
+ self.kb_insts[record.kb_id] = kb_helper
80
+
81
+ async def create_kb(
82
+ self,
83
+ kb_name: str,
84
+ description: str | None = None,
85
+ emoji: str | None = None,
86
+ embedding_provider_id: str | None = None,
87
+ rerank_provider_id: str | None = None,
88
+ chunk_size: int | None = None,
89
+ chunk_overlap: int | None = None,
90
+ top_k_dense: int | None = None,
91
+ top_k_sparse: int | None = None,
92
+ top_m_final: int | None = None,
93
+ ) -> KBHelper:
94
+ """创建新的知识库实例"""
95
+ kb = KnowledgeBase(
96
+ kb_name=kb_name,
97
+ description=description,
98
+ emoji=emoji or "📚",
99
+ embedding_provider_id=embedding_provider_id,
100
+ rerank_provider_id=rerank_provider_id,
101
+ chunk_size=chunk_size if chunk_size is not None else 512,
102
+ chunk_overlap=chunk_overlap if chunk_overlap is not None else 50,
103
+ top_k_dense=top_k_dense if top_k_dense is not None else 50,
104
+ top_k_sparse=top_k_sparse if top_k_sparse is not None else 50,
105
+ top_m_final=top_m_final if top_m_final is not None else 5,
106
+ )
107
+ async with self.kb_db.get_db() as session:
108
+ session.add(kb)
109
+ await session.commit()
110
+ await session.refresh(kb)
111
+
112
+ kb_helper = KBHelper(
113
+ kb_db=self.kb_db,
114
+ kb=kb,
115
+ provider_manager=self.provider_manager,
116
+ kb_root_dir=FILES_PATH,
117
+ chunker=CHUNKER,
118
+ )
119
+ await kb_helper.initialize()
120
+ self.kb_insts[kb.kb_id] = kb_helper
121
+ return kb_helper
122
+
123
+ async def get_kb(self, kb_id: str) -> KBHelper | None:
124
+ """获取知识库实例"""
125
+ if kb_id in self.kb_insts:
126
+ return self.kb_insts[kb_id]
127
+
128
+ async def get_kb_by_name(self, kb_name: str) -> KBHelper | None:
129
+ """通过名称获取知识库实例"""
130
+ for kb_helper in self.kb_insts.values():
131
+ if kb_helper.kb.kb_name == kb_name:
132
+ return kb_helper
133
+ return None
134
+
135
+ async def delete_kb(self, kb_id: str) -> bool:
136
+ """删除知识库实例"""
137
+ kb_helper = await self.get_kb(kb_id)
138
+ if not kb_helper:
139
+ return False
140
+
141
+ await kb_helper.delete_vec_db()
142
+ async with self.kb_db.get_db() as session:
143
+ await session.delete(kb_helper.kb)
144
+ await session.commit()
145
+
146
+ self.kb_insts.pop(kb_id, None)
147
+ return True
148
+
149
+ async def list_kbs(self) -> list[KnowledgeBase]:
150
+ """列出所有知识库实例"""
151
+ kbs = [kb_helper.kb for kb_helper in self.kb_insts.values()]
152
+ return kbs
153
+
154
+ async def update_kb(
155
+ self,
156
+ kb_id: str,
157
+ kb_name: str,
158
+ description: str | None = None,
159
+ emoji: str | None = None,
160
+ embedding_provider_id: str | None = None,
161
+ rerank_provider_id: str | None = None,
162
+ chunk_size: int | None = None,
163
+ chunk_overlap: int | None = None,
164
+ top_k_dense: int | None = None,
165
+ top_k_sparse: int | None = None,
166
+ top_m_final: int | None = None,
167
+ ) -> KBHelper | None:
168
+ """更新知识库实例"""
169
+ kb_helper = await self.get_kb(kb_id)
170
+ if not kb_helper:
171
+ return None
172
+
173
+ kb = kb_helper.kb
174
+ if kb_name is not None:
175
+ kb.kb_name = kb_name
176
+ if description is not None:
177
+ kb.description = description
178
+ if emoji is not None:
179
+ kb.emoji = emoji
180
+ if embedding_provider_id is not None:
181
+ kb.embedding_provider_id = embedding_provider_id
182
+ kb.rerank_provider_id = rerank_provider_id # 允许设置为 None
183
+ if chunk_size is not None:
184
+ kb.chunk_size = chunk_size
185
+ if chunk_overlap is not None:
186
+ kb.chunk_overlap = chunk_overlap
187
+ if top_k_dense is not None:
188
+ kb.top_k_dense = top_k_dense
189
+ if top_k_sparse is not None:
190
+ kb.top_k_sparse = top_k_sparse
191
+ if top_m_final is not None:
192
+ kb.top_m_final = top_m_final
193
+ async with self.kb_db.get_db() as session:
194
+ session.add(kb)
195
+ await session.commit()
196
+ await session.refresh(kb)
197
+
198
+ return kb_helper
199
+
200
+ async def retrieve(
201
+ self,
202
+ query: str,
203
+ kb_names: list[str],
204
+ top_k_fusion: int = 20,
205
+ top_m_final: int = 5,
206
+ ) -> dict | None:
207
+ """从指定知识库中检索相关内容"""
208
+ kb_ids = []
209
+ kb_id_helper_map = {}
210
+ for kb_name in kb_names:
211
+ if kb_helper := await self.get_kb_by_name(kb_name):
212
+ kb_ids.append(kb_helper.kb.kb_id)
213
+ kb_id_helper_map[kb_helper.kb.kb_id] = kb_helper
214
+
215
+ if not kb_ids:
216
+ return {}
217
+
218
+ results = await self.retrieval_manager.retrieve(
219
+ query=query,
220
+ kb_ids=kb_ids,
221
+ kb_id_helper_map=kb_id_helper_map,
222
+ top_k_fusion=top_k_fusion,
223
+ top_m_final=top_m_final,
224
+ )
225
+ if not results:
226
+ return None
227
+
228
+ context_text = self._format_context(results)
229
+
230
+ results_dict = [
231
+ {
232
+ "chunk_id": r.chunk_id,
233
+ "doc_id": r.doc_id,
234
+ "kb_id": r.kb_id,
235
+ "kb_name": r.kb_name,
236
+ "doc_name": r.doc_name,
237
+ "chunk_index": r.metadata.get("chunk_index", 0),
238
+ "content": r.content,
239
+ "score": r.score,
240
+ "char_count": r.metadata.get("char_count", 0),
241
+ }
242
+ for r in results
243
+ ]
244
+
245
+ return {
246
+ "context_text": context_text,
247
+ "results": results_dict,
248
+ }
249
+
250
+ def _format_context(self, results: list[RetrievalResult]) -> str:
251
+ """格式化知识上下文
252
+
253
+ Args:
254
+ results: 检索结果列表
255
+
256
+ Returns:
257
+ str: 格式化的上下文文本
258
+
259
+ """
260
+ lines = ["以下是相关的知识库内容,请参考这些信息回答用户的问题:\n"]
261
+
262
+ for i, result in enumerate(results, 1):
263
+ lines.append(f"【知识 {i}】")
264
+ lines.append(f"来源: {result.kb_name} / {result.doc_name}")
265
+ lines.append(f"内容: {result.content}")
266
+ lines.append(f"相关度: {result.score:.2f}")
267
+ lines.append("")
268
+
269
+ return "\n".join(lines)
270
+
271
+ async def terminate(self):
272
+ """终止所有知识库实例,关闭数据库连接"""
273
+ for kb_id, kb_helper in self.kb_insts.items():
274
+ try:
275
+ await kb_helper.terminate()
276
+ except Exception as e:
277
+ logger.error(f"关闭知识库 {kb_id} 失败: {e}")
278
+
279
+ self.kb_insts.clear()
280
+
281
+ # 关闭元数据数据库
282
+ if hasattr(self, "kb_db") and self.kb_db:
283
+ try:
284
+ await self.kb_db.close()
285
+ except Exception as e:
286
+ logger.error(f"关闭知识库元数据数据库失败: {e}")
287
+
288
+ async def upload_from_url(
289
+ self,
290
+ kb_id: str,
291
+ url: str,
292
+ chunk_size: int = 512,
293
+ chunk_overlap: int = 50,
294
+ batch_size: int = 32,
295
+ tasks_limit: int = 3,
296
+ max_retries: int = 3,
297
+ progress_callback=None,
298
+ ) -> KBDocument:
299
+ """从 URL 上传文档到指定的知识库
300
+
301
+ Args:
302
+ kb_id: 知识库 ID
303
+ url: 要提取内容的网页 URL
304
+ chunk_size: 文本块大小
305
+ chunk_overlap: 文本块重叠大小
306
+ batch_size: 批处理大小
307
+ tasks_limit: 并发任务限制
308
+ max_retries: 最大重试次数
309
+ progress_callback: 进度回调函数
310
+
311
+ Returns:
312
+ KBDocument: 上传的文档对象
313
+
314
+ Raises:
315
+ ValueError: 如果知识库不存在或 URL 为空
316
+ IOError: 如果网络请求失败
317
+ """
318
+ kb_helper = await self.get_kb(kb_id)
319
+ if not kb_helper:
320
+ raise ValueError(f"Knowledge base with id {kb_id} not found.")
321
+
322
+ return await kb_helper.upload_from_url(
323
+ url=url,
324
+ chunk_size=chunk_size,
325
+ chunk_overlap=chunk_overlap,
326
+ batch_size=batch_size,
327
+ tasks_limit=tasks_limit,
328
+ max_retries=max_retries,
329
+ progress_callback=progress_callback,
330
+ )
@@ -0,0 +1,120 @@
1
+ import uuid
2
+ from datetime import datetime, timezone
3
+
4
+ from sqlmodel import Field, MetaData, SQLModel, Text, UniqueConstraint
5
+
6
+
7
+ class BaseKBModel(SQLModel, table=False):
8
+ metadata = MetaData()
9
+
10
+
11
+ class KnowledgeBase(BaseKBModel, table=True):
12
+ """知识库表
13
+
14
+ 存储知识库的基本信息和统计数据。
15
+ """
16
+
17
+ __tablename__ = "knowledge_bases" # type: ignore
18
+
19
+ id: int | None = Field(
20
+ primary_key=True,
21
+ sa_column_kwargs={"autoincrement": True},
22
+ default=None,
23
+ )
24
+ kb_id: str = Field(
25
+ max_length=36,
26
+ nullable=False,
27
+ unique=True,
28
+ default_factory=lambda: str(uuid.uuid4()),
29
+ index=True,
30
+ )
31
+ kb_name: str = Field(max_length=100, nullable=False)
32
+ description: str | None = Field(default=None, sa_type=Text)
33
+ emoji: str | None = Field(default="📚", max_length=10)
34
+ embedding_provider_id: str | None = Field(default=None, max_length=100)
35
+ rerank_provider_id: str | None = Field(default=None, max_length=100)
36
+ # 分块配置参数
37
+ chunk_size: int | None = Field(default=512, nullable=True)
38
+ chunk_overlap: int | None = Field(default=50, nullable=True)
39
+ # 检索配置参数
40
+ top_k_dense: int | None = Field(default=50, nullable=True)
41
+ top_k_sparse: int | None = Field(default=50, nullable=True)
42
+ top_m_final: int | None = Field(default=5, nullable=True)
43
+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
44
+ updated_at: datetime = Field(
45
+ default_factory=lambda: datetime.now(timezone.utc),
46
+ sa_column_kwargs={"onupdate": datetime.now(timezone.utc)},
47
+ )
48
+ doc_count: int = Field(default=0, nullable=False)
49
+ chunk_count: int = Field(default=0, nullable=False)
50
+
51
+ __table_args__ = (
52
+ UniqueConstraint(
53
+ "kb_name",
54
+ name="uix_kb_name",
55
+ ),
56
+ )
57
+
58
+
59
+ class KBDocument(BaseKBModel, table=True):
60
+ """文档表
61
+
62
+ 存储上传到知识库的文档元数据。
63
+ """
64
+
65
+ __tablename__ = "kb_documents" # type: ignore
66
+
67
+ id: int | None = Field(
68
+ primary_key=True,
69
+ sa_column_kwargs={"autoincrement": True},
70
+ default=None,
71
+ )
72
+ doc_id: str = Field(
73
+ max_length=36,
74
+ nullable=False,
75
+ unique=True,
76
+ default_factory=lambda: str(uuid.uuid4()),
77
+ index=True,
78
+ )
79
+ kb_id: str = Field(max_length=36, nullable=False, index=True)
80
+ doc_name: str = Field(max_length=255, nullable=False)
81
+ file_type: str = Field(max_length=20, nullable=False)
82
+ file_size: int = Field(nullable=False)
83
+ file_path: str = Field(max_length=512, nullable=False)
84
+ chunk_count: int = Field(default=0, nullable=False)
85
+ media_count: int = Field(default=0, nullable=False)
86
+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
87
+ updated_at: datetime = Field(
88
+ default_factory=lambda: datetime.now(timezone.utc),
89
+ sa_column_kwargs={"onupdate": datetime.now(timezone.utc)},
90
+ )
91
+
92
+
93
+ class KBMedia(BaseKBModel, table=True):
94
+ """多媒体资源表
95
+
96
+ 存储从文档中提取的图片、视频等多媒体资源。
97
+ """
98
+
99
+ __tablename__ = "kb_media" # type: ignore
100
+
101
+ id: int | None = Field(
102
+ primary_key=True,
103
+ sa_column_kwargs={"autoincrement": True},
104
+ default=None,
105
+ )
106
+ media_id: str = Field(
107
+ max_length=36,
108
+ nullable=False,
109
+ unique=True,
110
+ default_factory=lambda: str(uuid.uuid4()),
111
+ index=True,
112
+ )
113
+ doc_id: str = Field(max_length=36, nullable=False, index=True)
114
+ kb_id: str = Field(max_length=36, nullable=False, index=True)
115
+ media_type: str = Field(max_length=20, nullable=False)
116
+ file_name: str = Field(max_length=255, nullable=False)
117
+ file_path: str = Field(max_length=512, nullable=False)
118
+ file_size: int = Field(nullable=False)
119
+ mime_type: str = Field(max_length=100, nullable=False)
120
+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
@@ -0,0 +1,13 @@
1
+ """文档解析器模块"""
2
+
3
+ from .base import BaseParser, MediaItem, ParseResult
4
+ from .pdf_parser import PDFParser
5
+ from .text_parser import TextParser
6
+
7
+ __all__ = [
8
+ "BaseParser",
9
+ "MediaItem",
10
+ "PDFParser",
11
+ "ParseResult",
12
+ "TextParser",
13
+ ]
@@ -0,0 +1,51 @@
1
+ """文档解析器基类和数据结构
2
+
3
+ 定义了文档解析器的抽象接口和相关数据类。
4
+ """
5
+
6
+ from abc import ABC, abstractmethod
7
+ from dataclasses import dataclass
8
+
9
+
10
+ @dataclass
11
+ class MediaItem:
12
+ """多媒体项
13
+
14
+ 表示从文档中提取的多媒体资源。
15
+ """
16
+
17
+ media_type: str # image, video
18
+ file_name: str
19
+ content: bytes
20
+ mime_type: str
21
+
22
+
23
+ @dataclass
24
+ class ParseResult:
25
+ """解析结果
26
+
27
+ 包含解析后的文本内容和提取的多媒体资源。
28
+ """
29
+
30
+ text: str
31
+ media: list[MediaItem]
32
+
33
+
34
+ class BaseParser(ABC):
35
+ """文档解析器基类
36
+
37
+ 所有文档解析器都应该继承此类并实现 parse 方法。
38
+ """
39
+
40
+ @abstractmethod
41
+ async def parse(self, file_content: bytes, file_name: str) -> ParseResult:
42
+ """解析文档
43
+
44
+ Args:
45
+ file_content: 文件内容
46
+ file_name: 文件名
47
+
48
+ Returns:
49
+ ParseResult: 解析结果
50
+
51
+ """
@@ -0,0 +1,26 @@
1
+ import io
2
+ import os
3
+
4
+ from markitdown_no_magika import MarkItDown, StreamInfo
5
+
6
+ from astrbot.core.knowledge_base.parsers.base import (
7
+ BaseParser,
8
+ ParseResult,
9
+ )
10
+
11
+
12
+ class MarkitdownParser(BaseParser):
13
+ """解析 docx, xls, xlsx 格式"""
14
+
15
+ async def parse(self, file_content: bytes, file_name: str) -> ParseResult:
16
+ md = MarkItDown(enable_plugins=False)
17
+ bio = io.BytesIO(file_content)
18
+ stream_info = StreamInfo(
19
+ extension=os.path.splitext(file_name)[1].lower(),
20
+ filename=file_name,
21
+ )
22
+ result = md.convert(bio, stream_info=stream_info)
23
+ return ParseResult(
24
+ text=result.markdown,
25
+ media=[],
26
+ )
@@ -0,0 +1,101 @@
1
+ """PDF 文件解析器
2
+
3
+ 支持解析 PDF 文件中的文本和图片资源。
4
+ """
5
+
6
+ import io
7
+
8
+ from pypdf import PdfReader
9
+
10
+ from astrbot.core.knowledge_base.parsers.base import (
11
+ BaseParser,
12
+ MediaItem,
13
+ ParseResult,
14
+ )
15
+
16
+
17
+ class PDFParser(BaseParser):
18
+ """PDF 文档解析器
19
+
20
+ 提取 PDF 中的文本内容和嵌入的图片资源。
21
+ """
22
+
23
+ async def parse(self, file_content: bytes, file_name: str) -> ParseResult:
24
+ """解析 PDF 文件
25
+
26
+ Args:
27
+ file_content: 文件内容
28
+ file_name: 文件名
29
+
30
+ Returns:
31
+ ParseResult: 包含文本和图片的解析结果
32
+
33
+ """
34
+ pdf_file = io.BytesIO(file_content)
35
+ reader = PdfReader(pdf_file)
36
+
37
+ text_parts = []
38
+ media_items = []
39
+
40
+ # 提取文本
41
+ for page in reader.pages:
42
+ text = page.extract_text()
43
+ if text:
44
+ text_parts.append(text)
45
+
46
+ # 提取图片
47
+ image_counter = 0
48
+ for page_num, page in enumerate(reader.pages):
49
+ try:
50
+ # 安全检查 Resources
51
+ if "/Resources" not in page:
52
+ continue
53
+
54
+ resources = page["/Resources"]
55
+ if not resources or "/XObject" not in resources: # type: ignore
56
+ continue
57
+
58
+ xobjects = resources["/XObject"].get_object() # type: ignore
59
+ if not xobjects:
60
+ continue
61
+
62
+ for obj_name in xobjects:
63
+ try:
64
+ obj = xobjects[obj_name]
65
+
66
+ if obj.get("/Subtype") != "/Image":
67
+ continue
68
+
69
+ # 提取图片数据
70
+ image_data = obj.get_data()
71
+
72
+ # 确定格式
73
+ filter_type = obj.get("/Filter", "")
74
+ if filter_type == "/DCTDecode":
75
+ ext = "jpg"
76
+ mime_type = "image/jpeg"
77
+ elif filter_type == "/FlateDecode":
78
+ ext = "png"
79
+ mime_type = "image/png"
80
+ else:
81
+ ext = "png"
82
+ mime_type = "image/png"
83
+
84
+ image_counter += 1
85
+ media_items.append(
86
+ MediaItem(
87
+ media_type="image",
88
+ file_name=f"page_{page_num}_img_{image_counter}.{ext}",
89
+ content=image_data,
90
+ mime_type=mime_type,
91
+ ),
92
+ )
93
+ except Exception:
94
+ # 单个图片提取失败不影响整体
95
+ continue
96
+ except Exception:
97
+ # 页面处理失败不影响其他页面
98
+ continue
99
+
100
+ full_text = "\n\n".join(text_parts)
101
+ return ParseResult(text=full_text, media=media_items)
@@ -0,0 +1,42 @@
1
+ """文本文件解析器
2
+
3
+ 支持解析 TXT 和 Markdown 文件。
4
+ """
5
+
6
+ from astrbot.core.knowledge_base.parsers.base import BaseParser, ParseResult
7
+
8
+
9
+ class TextParser(BaseParser):
10
+ """TXT/MD 文本解析器
11
+
12
+ 支持多种字符编码的自动检测。
13
+ """
14
+
15
+ async def parse(self, file_content: bytes, file_name: str) -> ParseResult:
16
+ """解析文本文件
17
+
18
+ 尝试使用多种编码解析文件内容。
19
+
20
+ Args:
21
+ file_content: 文件内容
22
+ file_name: 文件名
23
+
24
+ Returns:
25
+ ParseResult: 解析结果,不包含多媒体资源
26
+
27
+ Raises:
28
+ ValueError: 如果无法解码文件
29
+
30
+ """
31
+ # 尝试多种编码
32
+ for encoding in ["utf-8", "gbk", "gb2312", "gb18030"]:
33
+ try:
34
+ text = file_content.decode(encoding)
35
+ break
36
+ except UnicodeDecodeError:
37
+ continue
38
+ else:
39
+ raise ValueError(f"无法解码文件: {file_name}")
40
+
41
+ # 文本文件无多媒体资源
42
+ return ParseResult(text=text, media=[])