AstrBot 4.6.0__py3-none-any.whl → 4.6.1__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.
@@ -4,7 +4,7 @@ import os
4
4
 
5
5
  from astrbot.core.utils.astrbot_path import get_astrbot_data_path
6
6
 
7
- VERSION = "4.6.0"
7
+ VERSION = "4.6.1"
8
8
  DB_PATH = os.path.join(get_astrbot_data_path(), "data_v4.db")
9
9
 
10
10
  # 默认配置
@@ -1308,6 +1308,19 @@ CONFIG_METADATA_2 = {
1308
1308
  "timeout": 20,
1309
1309
  "launch_model_if_not_running": False,
1310
1310
  },
1311
+ "阿里云百炼重排序": {
1312
+ "id": "bailian_rerank",
1313
+ "type": "bailian_rerank",
1314
+ "provider": "bailian",
1315
+ "provider_type": "rerank",
1316
+ "enable": True,
1317
+ "rerank_api_key": "",
1318
+ "rerank_api_base": "https://dashscope.aliyuncs.com/api/v1/services/rerank/text-rerank/text-rerank",
1319
+ "rerank_model": "qwen3-rerank",
1320
+ "timeout": 30,
1321
+ "return_documents": False,
1322
+ "instruct": "",
1323
+ },
1311
1324
  "Xinference STT": {
1312
1325
  "id": "xinference_stt",
1313
1326
  "type": "xinference_stt",
@@ -1342,6 +1355,16 @@ CONFIG_METADATA_2 = {
1342
1355
  "description": "重排序模型名称",
1343
1356
  "type": "string",
1344
1357
  },
1358
+ "return_documents": {
1359
+ "description": "是否在排序结果中返回文档原文",
1360
+ "type": "bool",
1361
+ "hint": "默认值false,以减少网络传输开销。",
1362
+ },
1363
+ "instruct": {
1364
+ "description": "自定义排序任务类型说明",
1365
+ "type": "string",
1366
+ "hint": "仅在使用 qwen3-rerank 模型时生效。建议使用英文撰写。",
1367
+ },
1345
1368
  "launch_model_if_not_running": {
1346
1369
  "description": "模型未运行时自动启动",
1347
1370
  "type": "bool",
@@ -25,7 +25,7 @@ async def migrate_webchat_session(db_helper: BaseDatabase):
25
25
  """
26
26
  # 检查是否已经完成迁移
27
27
  migration_done = await db_helper.get_preference(
28
- "global", "global", "migration_done_webchat_session"
28
+ "global", "global", "migration_done_webchat_session_1"
29
29
  )
30
30
  if migration_done:
31
31
  return
@@ -43,7 +43,7 @@ async def migrate_webchat_session(db_helper: BaseDatabase):
43
43
  func.max(PlatformMessageHistory.updated_at).label("latest"),
44
44
  )
45
45
  .where(col(PlatformMessageHistory.platform_id) == "webchat")
46
- .where(col(PlatformMessageHistory.sender_id) == "astrbot")
46
+ .where(col(PlatformMessageHistory.sender_id) != "bot")
47
47
  .group_by(col(PlatformMessageHistory.user_id))
48
48
  )
49
49
 
@@ -53,7 +53,7 @@ async def migrate_webchat_session(db_helper: BaseDatabase):
53
53
  if not webchat_users:
54
54
  logger.info("没有找到需要迁移的 WebChat 数据")
55
55
  await sp.put_async(
56
- "global", "global", "migration_done_webchat_session", True
56
+ "global", "global", "migration_done_webchat_session_1", True
57
57
  )
58
58
  return
59
59
 
@@ -124,7 +124,7 @@ async def migrate_webchat_session(db_helper: BaseDatabase):
124
124
  logger.info("没有新会话需要迁移")
125
125
 
126
126
  # 标记迁移完成
127
- await sp.put_async("global", "global", "migration_done_webchat_session", True)
127
+ await sp.put_async("global", "global", "migration_done_webchat_session_1", True)
128
128
 
129
129
  except Exception as e:
130
130
  logger.error(f"迁移过程中发生错误: {e}", exc_info=True)
@@ -331,6 +331,10 @@ class ProviderManager:
331
331
  from .sources.xinference_rerank_source import (
332
332
  XinferenceRerankProvider as XinferenceRerankProvider,
333
333
  )
334
+ case "bailian_rerank":
335
+ from .sources.bailian_rerank_source import (
336
+ BailianRerankProvider as BailianRerankProvider,
337
+ )
334
338
  except (ImportError, ModuleNotFoundError) as e:
335
339
  logger.critical(
336
340
  f"加载 {provider_config['type']}({provider_config['id']}) 提供商适配器失败:{e}。可能是因为有未安装的依赖。",
@@ -0,0 +1,236 @@
1
+ import os
2
+
3
+ import aiohttp
4
+
5
+ from astrbot import logger
6
+
7
+ from ..entities import ProviderType, RerankResult
8
+ from ..provider import RerankProvider
9
+ from ..register import register_provider_adapter
10
+
11
+
12
+ class BailianRerankError(Exception):
13
+ """百炼重排序服务异常基类"""
14
+
15
+ pass
16
+
17
+
18
+ class BailianAPIError(BailianRerankError):
19
+ """百炼API返回错误"""
20
+
21
+ pass
22
+
23
+
24
+ class BailianNetworkError(BailianRerankError):
25
+ """百炼网络请求错误"""
26
+
27
+ pass
28
+
29
+
30
+ @register_provider_adapter(
31
+ "bailian_rerank", "阿里云百炼文本排序适配器", provider_type=ProviderType.RERANK
32
+ )
33
+ class BailianRerankProvider(RerankProvider):
34
+ """阿里云百炼文本重排序适配器."""
35
+
36
+ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
37
+ super().__init__(provider_config, provider_settings)
38
+ self.provider_config = provider_config
39
+ self.provider_settings = provider_settings
40
+
41
+ # API配置
42
+ self.api_key = provider_config.get("rerank_api_key") or os.getenv(
43
+ "DASHSCOPE_API_KEY", ""
44
+ )
45
+ if not self.api_key:
46
+ raise ValueError("阿里云百炼 API Key 不能为空。")
47
+
48
+ self.model = provider_config.get("rerank_model", "qwen3-rerank")
49
+ self.timeout = provider_config.get("timeout", 30)
50
+ self.return_documents = provider_config.get("return_documents", False)
51
+ self.instruct = provider_config.get("instruct", "")
52
+
53
+ self.base_url = provider_config.get(
54
+ "rerank_api_base",
55
+ "https://dashscope.aliyuncs.com/api/v1/services/rerank/text-rerank/text-rerank",
56
+ )
57
+
58
+ # 设置HTTP客户端
59
+ headers = {
60
+ "Authorization": f"Bearer {self.api_key}",
61
+ "Content-Type": "application/json",
62
+ }
63
+
64
+ self.client = aiohttp.ClientSession(
65
+ headers=headers, timeout=aiohttp.ClientTimeout(total=self.timeout)
66
+ )
67
+
68
+ # 设置模型名称
69
+ self.set_model(self.model)
70
+
71
+ logger.info(f"AstrBot 百炼 Rerank 初始化完成。模型: {self.model}")
72
+
73
+ def _build_payload(
74
+ self, query: str, documents: list[str], top_n: int | None
75
+ ) -> dict:
76
+ """构建请求载荷
77
+
78
+ Args:
79
+ query: 查询文本
80
+ documents: 文档列表
81
+ top_n: 返回前N个结果,如果为None则返回所有结果
82
+
83
+ Returns:
84
+ 请求载荷字典
85
+ """
86
+ base = {"model": self.model, "input": {"query": query, "documents": documents}}
87
+
88
+ params = {
89
+ k: v
90
+ for k, v in [
91
+ ("top_n", top_n if top_n is not None and top_n > 0 else None),
92
+ ("return_documents", True if self.return_documents else None),
93
+ (
94
+ "instruct",
95
+ self.instruct
96
+ if self.instruct and self.model == "qwen3-rerank"
97
+ else None,
98
+ ),
99
+ ]
100
+ if v is not None
101
+ }
102
+
103
+ if params:
104
+ base["parameters"] = params
105
+
106
+ return base
107
+
108
+ def _parse_results(self, data: dict) -> list[RerankResult]:
109
+ """解析API响应结果
110
+
111
+ Args:
112
+ data: API响应数据
113
+
114
+ Returns:
115
+ 重排序结果列表
116
+
117
+ Raises:
118
+ BailianAPIError: API返回错误
119
+ KeyError: 结果缺少必要字段
120
+ """
121
+ # 检查响应状态
122
+ if data.get("code", "200") != "200":
123
+ raise BailianAPIError(
124
+ f"百炼 API 错误: {data.get('code')} – {data.get('message', '')}"
125
+ )
126
+
127
+ results = data.get("output", {}).get("results", [])
128
+ if not results:
129
+ logger.warning(f"百炼 Rerank 返回空结果: {data}")
130
+ return []
131
+
132
+ # 转换为RerankResult对象,使用.get()避免KeyError
133
+ rerank_results = []
134
+ for idx, result in enumerate(results):
135
+ try:
136
+ index = result.get("index", idx)
137
+ relevance_score = result.get("relevance_score", 0.0)
138
+
139
+ if relevance_score is None:
140
+ logger.warning(f"结果 {idx} 缺少 relevance_score,使用默认值 0.0")
141
+ relevance_score = 0.0
142
+
143
+ rerank_result = RerankResult(
144
+ index=index, relevance_score=relevance_score
145
+ )
146
+ rerank_results.append(rerank_result)
147
+ except Exception as e:
148
+ logger.warning(f"解析结果 {idx} 时出错: {e}, result={result}")
149
+ continue
150
+
151
+ return rerank_results
152
+
153
+ def _log_usage(self, data: dict) -> None:
154
+ """记录使用量信息
155
+
156
+ Args:
157
+ data: API响应数据
158
+ """
159
+ tokens = data.get("usage", {}).get("total_tokens", 0)
160
+ if tokens > 0:
161
+ logger.debug(f"百炼 Rerank 消耗 Token: {tokens}")
162
+
163
+ async def rerank(
164
+ self,
165
+ query: str,
166
+ documents: list[str],
167
+ top_n: int | None = None,
168
+ ) -> list[RerankResult]:
169
+ """
170
+ 对文档进行重排序
171
+
172
+ Args:
173
+ query: 查询文本
174
+ documents: 待排序的文档列表
175
+ top_n: 返回前N个结果,如果为None则使用配置中的默认值
176
+
177
+ Returns:
178
+ 重排序结果列表
179
+ """
180
+ if not documents:
181
+ logger.warning("文档列表为空,返回空结果")
182
+ return []
183
+
184
+ if not query.strip():
185
+ logger.warning("查询文本为空,返回空结果")
186
+ return []
187
+
188
+ # 检查限制
189
+ if len(documents) > 500:
190
+ logger.warning(
191
+ f"文档数量({len(documents)})超过限制(500),将截断前500个文档"
192
+ )
193
+ documents = documents[:500]
194
+
195
+ try:
196
+ # 构建请求载荷,如果top_n为None则返回所有重排序结果
197
+ payload = self._build_payload(query, documents, top_n)
198
+
199
+ logger.debug(
200
+ f"百炼 Rerank 请求: query='{query[:50]}...', 文档数量={len(documents)}"
201
+ )
202
+
203
+ # 发送请求
204
+ async with self.client.post(self.base_url, json=payload) as response:
205
+ response.raise_for_status()
206
+ response_data = await response.json()
207
+
208
+ # 解析结果并记录使用量
209
+ results = self._parse_results(response_data)
210
+ self._log_usage(response_data)
211
+
212
+ logger.debug(f"百炼 Rerank 成功返回 {len(results)} 个结果")
213
+
214
+ return results
215
+
216
+ except aiohttp.ClientError as e:
217
+ error_msg = f"网络请求失败: {e}"
218
+ logger.error(f"百炼 Rerank 网络请求失败: {e}")
219
+ raise BailianNetworkError(error_msg) from e
220
+ except BailianRerankError:
221
+ raise
222
+ except Exception as e:
223
+ error_msg = f"重排序失败: {e}"
224
+ logger.error(f"百炼 Rerank 处理失败: {e}")
225
+ raise BailianRerankError(error_msg) from e
226
+
227
+ async def terminate(self) -> None:
228
+ """关闭HTTP客户端会话."""
229
+ if self.client:
230
+ logger.info("关闭 百炼 Rerank 客户端会话")
231
+ try:
232
+ await self.client.close()
233
+ except Exception as e:
234
+ logger.error(f"关闭 百炼 Rerank 客户端时出错: {e}")
235
+ finally:
236
+ self.client = None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: AstrBot
3
- Version: 4.6.0
3
+ Version: 4.6.1
4
4
  Summary: Easy-to-use multi-platform LLM chatbot and development framework
5
5
  License-File: LICENSE
6
6
  Keywords: Astrbot,Astrbot Module,Astrbot Plugin
@@ -93,7 +93,7 @@ Description-Content-Type: text/markdown
93
93
  <a href="https://github.com/AstrBotDevs/AstrBot/issues">问题提交</a>
94
94
  </div>
95
95
 
96
- AstrBot 是一个开源的一站式 Agent 聊天机器人平台及开发框架。
96
+ AstrBot 是一个开源的一站式 Agent 聊天机器人平台,可无缝接入主流即时通讯软件,为个人、开发者和团队打造可靠、可扩展的对话式智能基础设施。无论是个人 AI 伙伴、智能客服、自动化助手,还是企业知识库,AstrBot 都能在你的即时通讯软件平台的工作流中快速构建生产可用的 AI 应用。
97
97
 
98
98
  ## 主要功能
99
99
 
@@ -51,14 +51,14 @@ astrbot/core/agent/runners/base.py,sha256=5vDPiI_65ZlmVpuak-A4K2NW4uVhVD6wYRERKb
51
51
  astrbot/core/agent/runners/tool_loop_agent_runner.py,sha256=1bbuYHBz7A3U68Rl-ubG_-u_l4qjVTufkotQdBrIO8M,16781
52
52
  astrbot/core/config/__init__.py,sha256=vZjtpC7vr-IvBgSUtbS04C0wpulmCG5tPmcEP1WYE_4,172
53
53
  astrbot/core/config/astrbot_config.py,sha256=nGyvHyR9VJH9Pk0XKYyeDFVxjwbyVb9u0lIsuvpe3fg,6276
54
- astrbot/core/config/default.py,sha256=lA-1SepLA11TV0LzmbKW_C2kSQVXJFuX3dkrb1ACllI,136327
54
+ astrbot/core/config/default.py,sha256=jKQ6gqwTB1bZLWQ_pZSk1YsKLtGAdZW45rk3wxvrF8M,137547
55
55
  astrbot/core/db/__init__.py,sha256=s4oIWazGk2U1-9dkr3bvq8M4g9nwOXy4e3f53zlvAJk,10326
56
56
  astrbot/core/db/po.py,sha256=w4NaoMc8112YMT3H3NBMOd0HQyuphZ5sTUjU8vZOHR8,9406
57
57
  astrbot/core/db/sqlite.py,sha256=F117PS3BIss6-NuXOeTWV_8CVkSDCjqGnLf3yuftQjg,30076
58
58
  astrbot/core/db/migration/helper.py,sha256=Kogq0FLJdvWTDuAVWLT1PlTGGJcWkDMWO37KM-G8lTk,2087
59
59
  astrbot/core/db/migration/migra_3_to_4.py,sha256=hNn_tMququot1qUg3cx_nzxODxcZSlf4M_7YtBgKl2o,15277
60
60
  astrbot/core/db/migration/migra_45_to_46.py,sha256=wQk8NUiCNgmpSczO9U-OW6mMRHPWtJDlKuTCOGF8-WY,1560
61
- astrbot/core/db/migration/migra_webchat_session.py,sha256=OXgosbb0d6cSQ-x_N_RRjLiy0SUAtUQ5GBL72xpEAH8,5249
61
+ astrbot/core/db/migration/migra_webchat_session.py,sha256=KN2MaT4RPgaHuwQMGoSR_h6hPGEnPbuy_sVlVISgyuE,5251
62
62
  astrbot/core/db/migration/shared_preferences_v3.py,sha256=91zq_MrdAMF1MH5fxLaFkZO19nPNIW4gwqCCRn9u2dQ,1241
63
63
  astrbot/core/db/migration/sqlite_v3.py,sha256=pBBS5UemoVqus0aLJ5avqb3HgoN-b_S4fN5m4tBVf_U,15051
64
64
  astrbot/core/db/vec_db/base.py,sha256=0YxoCPNj_zVprLMamUj-OkUHJDlywIfdN8Q0Kpslm3A,1759
@@ -171,11 +171,12 @@ astrbot/core/provider/__init__.py,sha256=0NVyKtTapnrUy0lkXVYWyM5KetwtDwXmTwBzqLG
171
171
  astrbot/core/provider/entites.py,sha256=0eYiQ-xttqFTb3WZR2b1oemdZy3d5sevELvj9FixJtE,388
172
172
  astrbot/core/provider/entities.py,sha256=AwD8KOG8dSlfQXSc1n8gx4xv2vW4niZDiaMoO1Y_dOw,12533
173
173
  astrbot/core/provider/func_tool_manager.py,sha256=28fOKbpWOxiclwfcNkmP6sHSBlK4cZKwPXyNhFjjXps,21181
174
- astrbot/core/provider/manager.py,sha256=OzoEniML-bxbIO1GG2IMnzVDZ-IlVGQCbBFB0MB4zZw,22592
174
+ astrbot/core/provider/manager.py,sha256=3nQXBwlIWt_Ds834vlfThunqu-GxnXttNZOODvNQqC8,22790
175
175
  astrbot/core/provider/provider.py,sha256=bMJBBZzNwHhVv8dEiO1tNUclzxS78Yb01vUbceHZXKA,10680
176
176
  astrbot/core/provider/register.py,sha256=0WMYrT9vbRjeq-72HD0oRT45kJmeKA96UgSItpTJbX8,1904
177
177
  astrbot/core/provider/sources/anthropic_source.py,sha256=kRbJk0K-li84mWwapxYezGlkEF03Lg1brZDZnjmGrQ8,15584
178
178
  astrbot/core/provider/sources/azure_tts_source.py,sha256=uhPr4Dja6XANesAmrfZiuINNIlXej0NV7Goo8ahMm14,9387
179
+ astrbot/core/provider/sources/bailian_rerank_source.py,sha256=-kxF2XRnQRikGggymOBS2aJHRi8Y-zZgc4ykmred9UQ,7451
179
180
  astrbot/core/provider/sources/coze_api_client.py,sha256=0k8pQsFsbjKdF-jkY91qZWsC8YSaSmwC98TMTK-zqw0,10853
180
181
  astrbot/core/provider/sources/coze_source.py,sha256=FXqhRUOjKXwBsUBfVXBlLm5pM--IQpzzFViIUFltX1M,25341
181
182
  astrbot/core/provider/sources/dashscope_source.py,sha256=DlvP4tkBLZGHl77LvWbjdtfNO0spr6y0nypPzwKN-n8,7369
@@ -262,8 +263,8 @@ astrbot/dashboard/routes/static_file.py,sha256=7KnNcOb1BVqSTft114LhGsDkfg69X2jHE
262
263
  astrbot/dashboard/routes/t2i.py,sha256=F6smxdL99MF7cRw3hqS6-2GErw8Zhsv0V0mfBUeEk-c,8931
263
264
  astrbot/dashboard/routes/tools.py,sha256=YsVFrwVIhxAI-Ikme7YPrHVnPVTkJ1IaH7n6ciREjdE,14663
264
265
  astrbot/dashboard/routes/update.py,sha256=qXiqQ_dbqRVftOzGgCQrvK8-qopVK6zKhhVVJ9SK26U,6648
265
- astrbot-4.6.0.dist-info/METADATA,sha256=xugOHJn1hx--yvwaSY3uBlEds-BOHTzEV2p7dGZ34XU,10069
266
- astrbot-4.6.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
267
- astrbot-4.6.0.dist-info/entry_points.txt,sha256=OEF09YmhBWYuViXrvTLLpstF4ccmNwDL8r7nnFD0pfI,53
268
- astrbot-4.6.0.dist-info/licenses/LICENSE,sha256=zPfQj5Mq8-gThIiBcxETr7t8gND9bZWOjTGQAr80TQI,34500
269
- astrbot-4.6.0.dist-info/RECORD,,
266
+ astrbot-4.6.1.dist-info/METADATA,sha256=RIhPkfOxwegvGss371jfFDGETbOLn05MEdc8qIvAycg,10370
267
+ astrbot-4.6.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
268
+ astrbot-4.6.1.dist-info/entry_points.txt,sha256=OEF09YmhBWYuViXrvTLLpstF4ccmNwDL8r7nnFD0pfI,53
269
+ astrbot-4.6.1.dist-info/licenses/LICENSE,sha256=zPfQj5Mq8-gThIiBcxETr7t8gND9bZWOjTGQAr80TQI,34500
270
+ astrbot-4.6.1.dist-info/RECORD,,