diff --git a/astrbot/core/config/default.py b/astrbot/core/config/default.py
index 0073dbecacd..c416f7c2fcc 100644
--- a/astrbot/core/config/default.py
+++ b/astrbot/core/config/default.py
@@ -1951,7 +1951,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict:
"gemini_tts_api_key": "",
"gemini_tts_api_base": "",
"gemini_tts_timeout": 20,
- "gemini_tts_model": "gemini-2.5-flash-preview-tts",
+ "gemini_tts_model": "gemini-3.8-flash-tts",
"gemini_tts_prefix": "",
"gemini_tts_voice_name": "Leda",
"proxy": "",
@@ -2001,6 +2001,11 @@ def get_local_permission_defaults(system: str | None = None) -> dict:
"embedding_api_base": "",
"embedding_model": "gemini-embedding-001",
"embedding_dimensions": 768,
+ "embedding_task_type_mode": "auto",
+ "embedding_query_task_type": "RETRIEVAL_QUERY",
+ "embedding_document_task_type": "RETRIEVAL_DOCUMENT",
+ "embedding_query_task_name": "search result",
+ "embedding_document_title": "",
"timeout": 20,
"proxy": "",
},
@@ -2015,6 +2020,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict:
"embedding_api_base": "https://integrate.api.nvidia.com/v1",
"embedding_model": "nvidia/nemotron-3-embed-1b",
"input_type": "passage",
+ "query_input_type": "query",
"embedding_dimensions": 2048,
"timeout": 20,
"proxy": "",
@@ -2042,6 +2048,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict:
"embedding_api_key": "",
"embedding_api_base": "https://dashscope.aliyuncs.com/api/v1",
"embedding_model": "text-embedding-v4",
+ "embedding_text_type_mode": "auto",
"embedding_dimensions": 1024,
"timeout": 60,
"proxy": "",
diff --git a/astrbot/core/db/vec_db/faiss_impl/embedding_storage.py b/astrbot/core/db/vec_db/faiss_impl/embedding_storage.py
index c7684506d74..b92621a8727 100644
--- a/astrbot/core/db/vec_db/faiss_impl/embedding_storage.py
+++ b/astrbot/core/db/vec_db/faiss_impl/embedding_storage.py
@@ -1,186 +1,295 @@
-from __future__ import annotations
-
-import os
-import shutil
-import tempfile
-from typing import TYPE_CHECKING
-
-import numpy as np
-
-if TYPE_CHECKING:
- import faiss
-
-# ── Faiss C++ fopen() 在 Windows 上使用 ANSI codepage ──
-# Python 传给 Faiss 的路径是 UTF-8 字节,但 Windows fopen 期望 ANSI 编码,
-# 导致含非 ASCII 字符的路径(如 C:\Users\中文用户名\...)被解读为乱码而失败。
-# 本模块通过"纯 ASCII 临时文件桥接"规避此问题。
-
-
-def _needs_bridge(path: str) -> bool:
- """判断是否需要 ASCII 临时文件桥接。"""
- return os.name == "nt" and not path.isascii()
-
-
-def _safe_temp_dir() -> str:
- """返回保证纯 ASCII 且可写的临时目录,用于 Faiss I/O 桥接。
-
- 优先级:
- 1. %SystemRoot%\\Temp(Windows 系统临时目录)
- 2. tempfile.gettempdir()(当其为纯 ASCII 时)
- 3. 非 Windows 平台使用 tempfile.gettempdir()
- """
- if os.name == "nt":
- root = os.environ.get("SystemRoot", r"C:\Windows")
- temp_dir = os.path.join(root, "Temp")
- if (
- temp_dir.isascii()
- and os.path.isdir(temp_dir)
- and os.access(temp_dir, os.W_OK)
- ):
- return temp_dir
-
- tmp = tempfile.gettempdir()
- if tmp.isascii():
- return tmp
-
- raise OSError(
- "_safe_temp_dir: 无法找到可写的纯 ASCII 临时目录。"
- f" 检查过 SystemRoot\\Temp={temp_dir}, gettempdir={tmp}"
- )
-
- return tempfile.gettempdir()
-
-
-def _make_temp_file(prefix: str) -> str:
- """创建用于 Faiss 桥接的临时文件,返回路径。"""
- safe_dir = _safe_temp_dir()
- fd, path = tempfile.mkstemp(prefix=f"{prefix}_", suffix=".faiss", dir=safe_dir)
- os.close(fd)
- return path
-
-
-class EmbeddingStorage:
- def __init__(self, dimension: int, path: str | None = None) -> None:
- try:
- import faiss
- except ImportError:
- raise ImportError(
- "faiss 未安装。请使用 'pip install faiss-cpu' 或 'pip install faiss-gpu' 安装。",
- )
- self.dimension = dimension
- self.path = path
- self.index = None
- if path and os.path.exists(path):
- self.index = self._read_index(path)
- else:
- if dimension <= 0:
- raise ValueError(
- f"无效的嵌入向量维度: {dimension}。请检查该知识库使用的 Embedding "
- "Provider 是否正确配置了 embedding_dimensions。",
- )
- base_index = faiss.IndexFlatL2(dimension)
- self.index = faiss.IndexIDMap(base_index)
-
- @staticmethod
- def _read_index(path: str) -> faiss.Index:
- """读取 Faiss 索引,兼容含非 ASCII 字符的 Windows 路径。"""
- import faiss
-
- try:
- return faiss.read_index(path)
- except RuntimeError:
- if not _needs_bridge(path):
- raise
-
- tmp = _make_temp_file("_faiss_read")
- try:
- shutil.copy2(path, tmp)
- return faiss.read_index(tmp)
- finally:
- if os.path.exists(tmp):
- try:
- os.remove(tmp)
- except OSError:
- pass
-
- @staticmethod
- def _write_index(index: faiss.Index, path: str) -> None:
- """保存 Faiss 索引,兼容含非 ASCII 字符的 Windows 路径。"""
- import faiss
-
- dirname = os.path.dirname(path)
- if dirname:
- os.makedirs(dirname, exist_ok=True)
-
- if not _needs_bridge(path):
- faiss.write_index(index, path)
- return
-
- tmp = _make_temp_file("_faiss_write")
- try:
- faiss.write_index(index, tmp)
- shutil.move(tmp, path)
- finally:
- if os.path.exists(tmp):
- try:
- os.remove(tmp)
- except OSError:
- pass
-
- async def insert(self, vector: np.ndarray, id: int) -> None:
- """插入向量"""
- assert self.index is not None, "FAISS index is not initialized."
- if vector.shape[0] != self.dimension:
- raise ValueError(
- f"向量维度不匹配, 期望: {self.dimension}, 实际: {vector.shape[0]}",
- )
- self.index.add_with_ids(vector.reshape(1, -1), np.array([id], dtype=np.int64))
- await self.save_index()
-
- async def insert_batch(self, vectors: np.ndarray, ids: list[int]) -> None:
- """批量插入向量"""
- assert self.index is not None, "FAISS index is not initialized."
- if len(vectors.shape) != 2:
- raise ValueError(
- f"向量必须是二维数组, 当前维度: {len(vectors.shape)}",
- )
- if vectors.shape[1] != self.dimension:
- raise ValueError(
- f"向量维度不匹配, 期望: {self.dimension}, 实际: {vectors.shape[1]}",
- )
- self.index.add_with_ids(vectors, np.array(ids, dtype=np.int64))
- await self.save_index()
-
- async def search(self, vector: np.ndarray, k: int) -> tuple:
- """搜索向量
-
- 接受 1D (d,) 或 2D (1, d) 向量,自动展平为 Faiss 期望的 (1, d)。
- """
- assert self.index is not None, "FAISS index is not initialized."
- vector = np.asarray(vector, dtype=np.float32).ravel()
- if vector.shape[0] != self.dimension:
- raise ValueError(
- f"向量维度不匹配, 期望: {self.dimension}, 实际: {vector.shape[0]}",
- )
- distances, indices = self.index.search(vector.reshape(1, -1), k)
- return distances, indices
-
- async def delete(self, ids: list[int]) -> None:
- """删除向量
-
- 删除不存在的 ID 时 Faiss 会抛 RuntimeError。
- 由于 remove_ids 为幂等操作,此处忽略该错误。
- """
- assert self.index is not None, "FAISS index is not initialized."
- try:
- self.index.remove_ids(np.array(ids, dtype=np.int64))
- except RuntimeError:
- # 幂等:删除已不存在的 ID,安全忽略
- pass
- await self.save_index()
-
- async def save_index(self) -> None:
- """保存索引(兼容含非 ASCII 字符的 Windows 路径)"""
- if self.index is None or not self.path:
- return
- self._write_index(self.index, self.path)
+from __future__ import annotations
+
+import os
+import shutil
+import tempfile
+from typing import TYPE_CHECKING
+
+import numpy as np
+
+from astrbot import logger
+
+if TYPE_CHECKING:
+ import faiss
+
+# ── Faiss C++ fopen() 在 Windows 上使用 ANSI codepage ──
+# Python 传给 Faiss 的路径是 UTF-8 字节,但 Windows fopen 期望 ANSI 编码,
+# 导致含非 ASCII 字符的路径(如 C:\Users\中文用户名\...)被解读为乱码而失败。
+# 本模块通过"纯 ASCII 临时文件桥接"规避此问题。
+
+
+#: 模长低于该阈值的行视为零向量,不做缩放,避免放大浮点噪声。
+_MIN_NORM = 1e-12
+
+
+def _l2_normalize(vectors: np.ndarray) -> np.ndarray:
+ """把每行缩放到单位长度,让 L2 距离等价于按余弦相似度排序。
+
+ ``IndexFlatL2`` 返回欧氏距离的平方,配合 ``score = 1 - distance / 2``
+ 只有在向量是单位向量时才等于余弦相似度。部分提供商返回的向量未归一化
+ (如 Gemini 在低于 3072 维时),且模长会随文本长度漂移,此时分数由模长
+ 而非语义主导,检索排序会失效。
+
+ 用 float64 计算范数再转回 float32:float32 下对接近上限的值求平方会
+ 溢出成 ``inf``,导致整行归一化后变成全零。
+
+ Args:
+ vectors: 一维或二维数组,最后一维是向量维度。
+
+ Returns:
+ 与输入形状相同的 float32 单位向量数组;零向量行保持为零。
+ """
+ array = np.asarray(vectors, dtype=np.float32)
+ if array.size == 0:
+ return array
+
+ wide = array.astype(np.float64)
+ norms = np.linalg.norm(wide, axis=-1, keepdims=True)
+ # 零向量与极小模长不参与缩放,否则会产出 inf/NaN。
+ norms = np.where(norms < _MIN_NORM, 1.0, norms)
+ return (wide / norms).astype(np.float32)
+
+
+def _needs_bridge(path: str) -> bool:
+ """判断是否需要 ASCII 临时文件桥接。"""
+ return os.name == "nt" and not path.isascii()
+
+
+def _safe_temp_dir() -> str:
+ """返回保证纯 ASCII 且可写的临时目录,用于 Faiss I/O 桥接。
+
+ 优先级:
+ 1. %SystemRoot%\\Temp(Windows 系统临时目录)
+ 2. tempfile.gettempdir()(当其为纯 ASCII 时)
+ 3. 非 Windows 平台使用 tempfile.gettempdir()
+ """
+ if os.name == "nt":
+ root = os.environ.get("SystemRoot", r"C:\Windows")
+ temp_dir = os.path.join(root, "Temp")
+ if (
+ temp_dir.isascii()
+ and os.path.isdir(temp_dir)
+ and os.access(temp_dir, os.W_OK)
+ ):
+ return temp_dir
+
+ tmp = tempfile.gettempdir()
+ if tmp.isascii():
+ return tmp
+
+ raise OSError(
+ "_safe_temp_dir: 无法找到可写的纯 ASCII 临时目录。"
+ f" 检查过 SystemRoot\\Temp={temp_dir}, gettempdir={tmp}"
+ )
+
+ return tempfile.gettempdir()
+
+
+def _make_temp_file(prefix: str) -> str:
+ """创建用于 Faiss 桥接的临时文件,返回路径。"""
+ safe_dir = _safe_temp_dir()
+ fd, path = tempfile.mkstemp(prefix=f"{prefix}_", suffix=".faiss", dir=safe_dir)
+ os.close(fd)
+ return path
+
+
+class EmbeddingStorage:
+ def __init__(self, dimension: int, path: str | None = None) -> None:
+ try:
+ import faiss
+ except ImportError:
+ raise ImportError(
+ "faiss 未安装。请使用 'pip install faiss-cpu' 或 'pip install faiss-gpu' 安装。",
+ )
+ self.dimension = dimension
+ self.path = path
+ self.index = None
+ self._pending_save = False
+ if path and os.path.exists(path):
+ self.index = self._read_index(path)
+ self._normalize_loaded_index()
+ else:
+ if dimension <= 0:
+ raise ValueError(
+ f"无效的嵌入向量维度: {dimension}。请检查该知识库使用的 Embedding "
+ "Provider 是否正确配置了 embedding_dimensions。",
+ )
+ base_index = faiss.IndexFlatL2(dimension)
+ self.index = faiss.IndexIDMap(base_index)
+
+ def _normalize_loaded_index(self) -> None:
+ """把旧索引里未归一化的向量就地归一化。
+
+ 旧版本入库时未做归一化,而检索侧现在会归一化查询向量。两侧标准不
+ 一致会让相似度整体失真(分数偏移,排序也可能错),因此加载旧索引时
+ 统一重建为归一化后的向量。
+
+ 仅处理 ``IndexIDMap(IndexFlatL2)``;其他索引类型(如已训练的 IVF)
+ 无法安全地重建向量,直接跳过以保证兼容。
+ """
+ import faiss
+
+ if self.index is None:
+ return
+
+ # AstrBot 只会用 IndexIDMap(IndexFlatL2);其他布局(如已训练的 IVF)
+ # 无法安全重建向量,直接跳过以保证兼容。
+ if not isinstance(self.index, faiss.IndexIDMap):
+ return
+
+ inner = faiss.downcast_index(self.index.index)
+ if not isinstance(inner, faiss.IndexFlat) or inner.ntotal == 0:
+ return
+
+ try:
+ # IndexFlat 支持按位置取回原始向量。
+ vectors = inner.reconstruct_n(0, inner.ntotal)
+ except RuntimeError:
+ logger.debug("[EmbeddingStorage] 索引不支持 reconstruct,跳过归一化。")
+ return
+
+ # 已经全部是单位向量时不重建,避免每次加载都重写索引文件。
+ # 零向量的模长是 0 而非 1,必须排除在外,否则会误判成"未归一化",
+ # 导致每次启动都重建一遍索引。
+ norms = np.linalg.norm(vectors.astype(np.float64), axis=1)
+ nonzero = norms[norms >= _MIN_NORM]
+ if nonzero.size == 0 or np.allclose(nonzero, 1.0, atol=1e-5):
+ return
+
+ normalized = _l2_normalize(vectors)
+ ids = faiss.vector_to_array(self.index.id_map)
+ rebuilt = faiss.IndexIDMap(faiss.IndexFlatL2(inner.d))
+ rebuilt.add_with_ids(normalized, ids)
+ self.index = rebuilt
+ self._pending_save = True
+
+ logger.info(
+ f"[EmbeddingStorage] 已把 {len(normalized)} 条旧向量归一化为单位向量。",
+ )
+
+ async def flush(self) -> None:
+ """若加载旧索引时做过归一化重建,则把结果落盘。
+
+ 归一化是检索质量优化,不是正确性前提——内存里的索引已经可用。写盘
+ 失败(磁盘满、只读挂载等)不应该让知识库整个打不开,因此这里只记日志
+ 不抛异常。
+ """
+ if not self._pending_save:
+ return
+ try:
+ await self.save_index()
+ except Exception as e:
+ # 只记异常类型:OSError 等异常文本里常带完整路径,会把本机用户名
+ # 等本地信息写进日志。
+ logger.warning(
+ f"[EmbeddingStorage] 归一化后的索引写盘失败,本次运行使用内存中"
+ f"已归一化的索引,稍后会重试: {type(e).__name__}",
+ )
+ return
+ self._pending_save = False
+
+ @staticmethod
+ def _read_index(path: str) -> faiss.Index:
+ """读取 Faiss 索引,兼容含非 ASCII 字符的 Windows 路径。"""
+ import faiss
+
+ try:
+ return faiss.read_index(path)
+ except RuntimeError:
+ if not _needs_bridge(path):
+ raise
+
+ tmp = _make_temp_file("_faiss_read")
+ try:
+ shutil.copy2(path, tmp)
+ return faiss.read_index(tmp)
+ finally:
+ if os.path.exists(tmp):
+ try:
+ os.remove(tmp)
+ except OSError:
+ pass
+
+ @staticmethod
+ def _write_index(index: faiss.Index, path: str) -> None:
+ """保存 Faiss 索引,兼容含非 ASCII 字符的 Windows 路径。"""
+ import faiss
+
+ dirname = os.path.dirname(path)
+ if dirname:
+ os.makedirs(dirname, exist_ok=True)
+
+ if not _needs_bridge(path):
+ faiss.write_index(index, path)
+ return
+
+ tmp = _make_temp_file("_faiss_write")
+ try:
+ faiss.write_index(index, tmp)
+ shutil.move(tmp, path)
+ finally:
+ if os.path.exists(tmp):
+ try:
+ os.remove(tmp)
+ except OSError:
+ pass
+
+ async def insert(self, vector: np.ndarray, id: int) -> None:
+ """插入向量"""
+ assert self.index is not None, "FAISS index is not initialized."
+ if vector.shape[0] != self.dimension:
+ raise ValueError(
+ f"向量维度不匹配, 期望: {self.dimension}, 实际: {vector.shape[0]}",
+ )
+ self.index.add_with_ids(
+ _l2_normalize(vector.reshape(1, -1)), np.array([id], dtype=np.int64)
+ )
+ await self.save_index()
+
+ async def insert_batch(self, vectors: np.ndarray, ids: list[int]) -> None:
+ """批量插入向量"""
+ assert self.index is not None, "FAISS index is not initialized."
+ if len(vectors.shape) != 2:
+ raise ValueError(
+ f"向量必须是二维数组, 当前维度: {len(vectors.shape)}",
+ )
+ if vectors.shape[1] != self.dimension:
+ raise ValueError(
+ f"向量维度不匹配, 期望: {self.dimension}, 实际: {vectors.shape[1]}",
+ )
+ self.index.add_with_ids(_l2_normalize(vectors), np.array(ids, dtype=np.int64))
+ await self.save_index()
+
+ async def search(self, vector: np.ndarray, k: int) -> tuple:
+ """搜索向量
+
+ 接受 1D (d,) 或 2D (1, d) 向量,自动展平为 Faiss 期望的 (1, d)。
+ """
+ assert self.index is not None, "FAISS index is not initialized."
+ vector = np.asarray(vector, dtype=np.float32).ravel()
+ if vector.shape[0] != self.dimension:
+ raise ValueError(
+ f"向量维度不匹配, 期望: {self.dimension}, 实际: {vector.shape[0]}",
+ )
+ distances, indices = self.index.search(_l2_normalize(vector.reshape(1, -1)), k)
+ return distances, indices
+
+ async def delete(self, ids: list[int]) -> None:
+ """删除向量
+
+ 删除不存在的 ID 时 Faiss 会抛 RuntimeError。
+ 由于 remove_ids 为幂等操作,此处忽略该错误。
+ """
+ assert self.index is not None, "FAISS index is not initialized."
+ try:
+ self.index.remove_ids(np.array(ids, dtype=np.int64))
+ except RuntimeError:
+ # 幂等:删除已不存在的 ID,安全忽略
+ pass
+ await self.save_index()
+
+ async def save_index(self) -> None:
+ """保存索引(兼容含非 ASCII 字符的 Windows 路径)"""
+ if self.index is None or not self.path:
+ return
+ self._write_index(self.index, self.path)
diff --git a/astrbot/core/db/vec_db/faiss_impl/vec_db.py b/astrbot/core/db/vec_db/faiss_impl/vec_db.py
index 13fde6c0ef2..076fa4bb3f8 100644
--- a/astrbot/core/db/vec_db/faiss_impl/vec_db.py
+++ b/astrbot/core/db/vec_db/faiss_impl/vec_db.py
@@ -1,349 +1,356 @@
-import time
-import uuid
-
-import numpy as np
-
-from astrbot import logger
-from astrbot.core.exceptions import KnowledgeBaseUploadError
-from astrbot.core.provider.provider import EmbeddingProvider, RerankProvider
-
-from ..base import BaseVecDB, Result
-from .document_storage import DocumentStorage
-from .embedding_storage import EmbeddingStorage
-
-
-class FaissVecDB(BaseVecDB):
- """A class to represent a vector database."""
-
- def __init__(
- self,
- doc_store_path: str,
- index_store_path: str,
- embedding_provider: EmbeddingProvider,
- rerank_provider: RerankProvider | None = None,
- ) -> None:
- self.doc_store_path = doc_store_path
- self.index_store_path = index_store_path
- self.embedding_provider = embedding_provider
- self.document_storage = DocumentStorage(doc_store_path)
- self.embedding_storage = EmbeddingStorage(
- embedding_provider.get_dim(),
- index_store_path,
- )
- self.embedding_provider = embedding_provider
- self.rerank_provider = rerank_provider
-
- async def initialize(self) -> None:
- await self.document_storage.initialize()
-
- async def insert(
- self,
- content: str,
- metadata: dict | None = None,
- id: str | None = None,
- ) -> int:
- """插入一条文本和其对应向量,自动生成 ID 并保持一致性。"""
- metadata = metadata or {}
- str_id = id or str(uuid.uuid4()) # 使用 UUID 作为原始 ID
-
- vector = await self.embedding_provider.get_embedding(content)
- vector = np.array(vector, dtype=np.float32)
-
- # 使用 DocumentStorage 的方法插入文档
- int_id = await self.document_storage.insert_document(str_id, content, metadata)
-
- # 插入向量到 FAISS
- await self.embedding_storage.insert(vector, int_id)
- return int_id
-
- async def insert_batch(
- self,
- contents: list[str],
- metadatas: list[dict] | None = None,
- ids: list[str] | None = None,
- batch_size: int = 32,
- tasks_limit: int = 3,
- max_retries: int = 3,
- progress_callback=None,
- embedding_contents: list[str] | None = None,
- ) -> list[int]:
- """批量插入文本和其对应向量,自动生成 ID 并保持一致性。
-
- Args:
- progress_callback: 进度回调函数,接收参数 (current, total)
- embedding_contents: Optional enriched texts used only for embeddings.
-
- """
- metadatas = metadatas or [{} for _ in contents]
- ids = ids or [str(uuid.uuid4()) for _ in contents]
- if embedding_contents is None:
- embedding_contents = contents
-
- if not contents:
- logger.debug(
- "No contents provided for batch insert; skipping embedding generation."
- )
- return []
-
- content_count = len(contents)
- if len(metadatas) != content_count:
- raise KnowledgeBaseUploadError(
- stage="storage",
- user_message=(
- f"存储失败:文本分块数量与元数据数量不一致(期望 {content_count},"
- f"实际 {len(metadatas)})。"
- ),
- details={
- "expected_contents": content_count,
- "actual_metadatas": len(metadatas),
- },
- )
- if len(ids) != content_count:
- raise KnowledgeBaseUploadError(
- stage="storage",
- user_message=(
- f"存储失败:文本分块数量与文档 ID 数量不一致(期望 {content_count},"
- f"实际 {len(ids)})。"
- ),
- details={
- "expected_contents": content_count,
- "actual_ids": len(ids),
- },
- )
- if len(embedding_contents) != content_count:
- raise KnowledgeBaseUploadError(
- stage="storage",
- user_message=(
- f"存储失败:文本分块数量与向量化文本数量不一致(期望 {content_count},"
- f"实际 {len(embedding_contents)})。"
- ),
- details={
- "expected_contents": content_count,
- "actual_embedding_contents": len(embedding_contents),
- },
- )
-
- start = time.time()
- logger.debug(f"Generating embeddings for {len(contents)} contents...")
- vectors = await self.embedding_provider.get_embeddings_batch(
- embedding_contents,
- batch_size=batch_size,
- tasks_limit=tasks_limit,
- max_retries=max_retries,
- progress_callback=progress_callback,
- )
- end = time.time()
- logger.debug(
- f"Generated embeddings for {len(contents)} contents in {end - start:.2f} seconds.",
- )
- if len(vectors) != content_count:
- raise KnowledgeBaseUploadError(
- stage="embedding",
- user_message=(
- "向量化失败:嵌入模型返回的向量数量与文本分块数量不一致"
- f"(期望 {content_count},实际 {len(vectors)})。"
- "这通常说明当前 Embedding 接口未完整返回批量结果,"
- "或该服务不兼容当前批量请求格式。"
- ),
- details={
- "expected_contents": content_count,
- "actual_vectors": len(vectors),
- },
- )
-
- # Validate vector format/dimension before any local write so validation
- # failures never leave a half-written document store.
- try:
- vectors_array = np.asarray(vectors, dtype=np.float32)
- except (TypeError, ValueError) as exc:
- raise KnowledgeBaseUploadError(
- stage="embedding",
- user_message=(
- "向量化失败:嵌入模型返回的向量格式不正确,"
- "无法转换为统一的浮点向量矩阵。"
- ),
- details={"vector_count": len(vectors)},
- ) from exc
- if vectors_array.ndim != 2:
- raise KnowledgeBaseUploadError(
- stage="embedding",
- user_message=(
- "向量化失败:嵌入模型返回的向量格式不正确,无法构造成二维向量矩阵。"
- ),
- details={"actual_ndim": int(vectors_array.ndim)},
- )
- if vectors_array.shape[1] != self.embedding_storage.dimension:
- raise KnowledgeBaseUploadError(
- stage="embedding",
- user_message=(
- "向量化失败:返回向量维度与当前知识库索引维度不一致"
- f"(期望 {self.embedding_storage.dimension},"
- f"实际 {vectors_array.shape[1]})。"
- ),
- details={
- "expected_dimension": self.embedding_storage.dimension,
- "actual_dimension": int(vectors_array.shape[1]),
- },
- )
-
- # DocumentStorage and FAISS cannot share a transaction. If FAISS
- # write fails after documents are committed, compensate by deleting.
- int_ids = await self.document_storage.insert_documents_batch(
- ids,
- contents,
- metadatas,
- )
- try:
- if len(int_ids) != content_count:
- raise KnowledgeBaseUploadError(
- stage="storage",
- user_message=(
- f"存储失败:写入文档索引后返回的内部 ID 数量与文本分块数量不一致"
- f"(期望 {content_count},实际 {len(int_ids)})。"
- ),
- details={
- "expected_contents": content_count,
- "actual_int_ids": len(int_ids),
- },
- )
- await self.embedding_storage.insert_batch(vectors_array, int_ids)
- except Exception:
- await self._rollback_partial_insert(ids=ids, int_ids=int_ids)
- raise
- return int_ids
-
- async def retrieve(
- self,
- query: str,
- k: int = 5,
- fetch_k: int = 20,
- rerank: bool = False,
- metadata_filters: dict | None = None,
- ) -> list[Result]:
- """搜索最相似的文档。
-
- Args:
- query (str): 查询文本
- k (int): 返回的最相似文档的数量
- fetch_k (int): 在根据 metadata 过滤前从 FAISS 中获取的数量
- rerank (bool): 是否使用重排序。这需要在实例化时提供 rerank_provider, 如果未提供并且 rerank 为 True, 不会抛出异常。
- metadata_filters (dict): 元数据过滤器
-
- Returns:
- List[Result]: 查询结果
-
- """
- embedding = await self.embedding_provider.get_embedding(query)
- scores, indices = await self.embedding_storage.search(
- vector=np.array(embedding).astype("float32"),
- k=fetch_k if metadata_filters else k,
- )
- if len(indices[0]) == 0 or indices[0][0] == -1:
- return []
- # normalize scores
- scores[0] = 1.0 - (scores[0] / 2.0)
- # NOTE: maybe the size is less than k.
- fetched_docs = await self.document_storage.get_documents(
- metadata_filters=metadata_filters or {},
- ids=indices[0],
- )
- if not fetched_docs:
- return []
- result_docs: list[Result] = []
-
- idx_pos = {fetch_doc["id"]: idx for idx, fetch_doc in enumerate(fetched_docs)}
- for i, indice_idx in enumerate(indices[0]):
- pos = idx_pos.get(indice_idx)
- if pos is None:
- continue
- fetch_doc = fetched_docs[pos]
- score = scores[0][i]
- result_docs.append(Result(similarity=float(score), data=fetch_doc))
-
- top_k_results = result_docs[:k]
-
- if rerank and self.rerank_provider:
- documents = [doc.data["text"] for doc in top_k_results]
- reranked_results = await self.rerank_provider.rerank(query, documents)
- reranked_results = sorted(
- reranked_results,
- key=lambda x: x.relevance_score,
- reverse=True,
- )
- top_k_results = [
- top_k_results[reranked_result.index]
- for reranked_result in reranked_results
- ]
-
- return top_k_results
-
- async def _rollback_partial_insert(
- self,
- ids: list[str],
- int_ids: list[int],
- ) -> None:
- """Best-effort cleanup after a partial ``insert_batch`` write.
-
- DocumentStorage commits independently from FAISS. When FAISS insertion
- fails after documents are written — or after vectors were added in
- memory but not flushed — remove those rows/ids so the two stores do
- not diverge.
-
- Args:
- ids: Chunk UUID strings written to DocumentStorage.
- int_ids: Internal integer ids returned by DocumentStorage, also
- used as FAISS ids when any vectors may have been added.
- """
- if int_ids:
- try:
- await self.embedding_storage.delete(int_ids)
- except Exception as exc:
- logger.warning(
- f"Failed to roll back FAISS vectors for partial insert: {exc}",
- )
-
- for doc_id in ids:
- try:
- await self.document_storage.delete_document_by_doc_id(doc_id)
- except Exception as exc:
- logger.warning(
- f"Failed to roll back document storage entry {doc_id}: {exc}",
- )
-
- async def delete(self, doc_id: str) -> None:
- """删除一条文档块(chunk)"""
- # 获得对应的 int id
- result = await self.document_storage.get_document_by_doc_id(doc_id)
- int_id = result["id"] if result else None
- if int_id is None:
- return
-
- # 使用 DocumentStorage 的删除方法
- await self.document_storage.delete_document_by_doc_id(doc_id)
- await self.embedding_storage.delete([int_id])
-
- async def close(self) -> None:
- await self.document_storage.close()
-
- async def count_documents(self, metadata_filter: dict | None = None) -> int:
- """计算文档数量
-
- Args:
- metadata_filter (dict | None): 元数据过滤器
-
- """
- count = await self.document_storage.count_documents(
- metadata_filters=metadata_filter or {},
- )
- return count
-
- async def delete_documents(self, metadata_filters: dict) -> None:
- """根据元数据过滤器删除文档"""
- docs = await self.document_storage.get_documents(
- metadata_filters=metadata_filters,
- offset=None,
- limit=None,
- )
- doc_ids: list[int] = [doc["id"] for doc in docs]
- await self.embedding_storage.delete(doc_ids)
- await self.document_storage.delete_documents(metadata_filters=metadata_filters)
+import time
+import uuid
+
+import numpy as np
+
+from astrbot import logger
+from astrbot.core.exceptions import KnowledgeBaseUploadError
+from astrbot.core.provider.provider import EmbeddingProvider, RerankProvider
+
+from ..base import BaseVecDB, Result
+from .document_storage import DocumentStorage
+from .embedding_storage import EmbeddingStorage
+
+
+class FaissVecDB(BaseVecDB):
+ """A class to represent a vector database."""
+
+ def __init__(
+ self,
+ doc_store_path: str,
+ index_store_path: str,
+ embedding_provider: EmbeddingProvider,
+ rerank_provider: RerankProvider | None = None,
+ ) -> None:
+ self.doc_store_path = doc_store_path
+ self.index_store_path = index_store_path
+ self.embedding_provider = embedding_provider
+ self.document_storage = DocumentStorage(doc_store_path)
+ self.embedding_storage = EmbeddingStorage(
+ embedding_provider.get_dim(),
+ index_store_path,
+ )
+ self.embedding_provider = embedding_provider
+ self.rerank_provider = rerank_provider
+
+ async def initialize(self) -> None:
+ await self.document_storage.initialize()
+ # 加载旧索引时可能做过向量归一化重建,这里统一落盘一次。
+ await self.embedding_storage.flush()
+
+ async def insert(
+ self,
+ content: str,
+ metadata: dict | None = None,
+ id: str | None = None,
+ ) -> int:
+ """插入一条文本和其对应向量,自动生成 ID 并保持一致性。"""
+ metadata = metadata or {}
+ str_id = id or str(uuid.uuid4()) # 使用 UUID 作为原始 ID
+
+ vector = await self.embedding_provider.get_embedding(content)
+ vector = np.array(vector, dtype=np.float32)
+
+ # 使用 DocumentStorage 的方法插入文档
+ int_id = await self.document_storage.insert_document(str_id, content, metadata)
+
+ # 插入向量到 FAISS
+ await self.embedding_storage.insert(vector, int_id)
+ return int_id
+
+ async def insert_batch(
+ self,
+ contents: list[str],
+ metadatas: list[dict] | None = None,
+ ids: list[str] | None = None,
+ batch_size: int = 32,
+ tasks_limit: int = 3,
+ max_retries: int = 3,
+ progress_callback=None,
+ embedding_contents: list[str] | None = None,
+ ) -> list[int]:
+ """批量插入文本和其对应向量,自动生成 ID 并保持一致性。
+
+ Args:
+ progress_callback: 进度回调函数,接收参数 (current, total)
+ embedding_contents: Optional enriched texts used only for embeddings.
+
+ """
+ metadatas = metadatas or [{} for _ in contents]
+ ids = ids or [str(uuid.uuid4()) for _ in contents]
+ if embedding_contents is None:
+ embedding_contents = contents
+
+ if not contents:
+ logger.debug(
+ "No contents provided for batch insert; skipping embedding generation."
+ )
+ return []
+
+ content_count = len(contents)
+ if len(metadatas) != content_count:
+ raise KnowledgeBaseUploadError(
+ stage="storage",
+ user_message=(
+ f"存储失败:文本分块数量与元数据数量不一致(期望 {content_count},"
+ f"实际 {len(metadatas)})。"
+ ),
+ details={
+ "expected_contents": content_count,
+ "actual_metadatas": len(metadatas),
+ },
+ )
+ if len(ids) != content_count:
+ raise KnowledgeBaseUploadError(
+ stage="storage",
+ user_message=(
+ f"存储失败:文本分块数量与文档 ID 数量不一致(期望 {content_count},"
+ f"实际 {len(ids)})。"
+ ),
+ details={
+ "expected_contents": content_count,
+ "actual_ids": len(ids),
+ },
+ )
+ if len(embedding_contents) != content_count:
+ raise KnowledgeBaseUploadError(
+ stage="storage",
+ user_message=(
+ f"存储失败:文本分块数量与向量化文本数量不一致(期望 {content_count},"
+ f"实际 {len(embedding_contents)})。"
+ ),
+ details={
+ "expected_contents": content_count,
+ "actual_embedding_contents": len(embedding_contents),
+ },
+ )
+
+ start = time.time()
+ logger.debug(f"Generating embeddings for {len(contents)} contents...")
+ vectors = await self.embedding_provider.get_embeddings_batch(
+ embedding_contents,
+ batch_size=batch_size,
+ tasks_limit=tasks_limit,
+ max_retries=max_retries,
+ progress_callback=progress_callback,
+ )
+ end = time.time()
+ logger.debug(
+ f"Generated embeddings for {len(contents)} contents in {end - start:.2f} seconds.",
+ )
+ if len(vectors) != content_count:
+ raise KnowledgeBaseUploadError(
+ stage="embedding",
+ user_message=(
+ "向量化失败:嵌入模型返回的向量数量与文本分块数量不一致"
+ f"(期望 {content_count},实际 {len(vectors)})。"
+ "这通常说明当前 Embedding 接口未完整返回批量结果,"
+ "或该服务不兼容当前批量请求格式。"
+ ),
+ details={
+ "expected_contents": content_count,
+ "actual_vectors": len(vectors),
+ },
+ )
+
+ # Validate vector format/dimension before any local write so validation
+ # failures never leave a half-written document store.
+ try:
+ vectors_array = np.asarray(vectors, dtype=np.float32)
+ except (TypeError, ValueError) as exc:
+ raise KnowledgeBaseUploadError(
+ stage="embedding",
+ user_message=(
+ "向量化失败:嵌入模型返回的向量格式不正确,"
+ "无法转换为统一的浮点向量矩阵。"
+ ),
+ details={"vector_count": len(vectors)},
+ ) from exc
+ if vectors_array.ndim != 2:
+ raise KnowledgeBaseUploadError(
+ stage="embedding",
+ user_message=(
+ "向量化失败:嵌入模型返回的向量格式不正确,无法构造成二维向量矩阵。"
+ ),
+ details={"actual_ndim": int(vectors_array.ndim)},
+ )
+ if vectors_array.shape[1] != self.embedding_storage.dimension:
+ raise KnowledgeBaseUploadError(
+ stage="embedding",
+ user_message=(
+ "向量化失败:返回向量维度与当前知识库索引维度不一致"
+ f"(期望 {self.embedding_storage.dimension},"
+ f"实际 {vectors_array.shape[1]})。"
+ ),
+ details={
+ "expected_dimension": self.embedding_storage.dimension,
+ "actual_dimension": int(vectors_array.shape[1]),
+ },
+ )
+
+ # DocumentStorage and FAISS cannot share a transaction. If FAISS
+ # write fails after documents are committed, compensate by deleting.
+ int_ids = await self.document_storage.insert_documents_batch(
+ ids,
+ contents,
+ metadatas,
+ )
+ try:
+ if len(int_ids) != content_count:
+ raise KnowledgeBaseUploadError(
+ stage="storage",
+ user_message=(
+ f"存储失败:写入文档索引后返回的内部 ID 数量与文本分块数量不一致"
+ f"(期望 {content_count},实际 {len(int_ids)})。"
+ ),
+ details={
+ "expected_contents": content_count,
+ "actual_int_ids": len(int_ids),
+ },
+ )
+ await self.embedding_storage.insert_batch(vectors_array, int_ids)
+ except Exception:
+ await self._rollback_partial_insert(ids=ids, int_ids=int_ids)
+ raise
+ return int_ids
+
+ async def retrieve(
+ self,
+ query: str,
+ k: int = 5,
+ fetch_k: int = 20,
+ rerank: bool = False,
+ metadata_filters: dict | None = None,
+ ) -> list[Result]:
+ """搜索最相似的文档。
+
+ Args:
+ query (str): 查询文本
+ k (int): 返回的最相似文档的数量
+ fetch_k (int): 在根据 metadata 过滤前从 FAISS 中获取的数量
+ rerank (bool): 是否使用重排序。这需要在实例化时提供 rerank_provider, 如果未提供并且 rerank 为 True, 不会抛出异常。
+ metadata_filters (dict): 元数据过滤器
+
+ Returns:
+ List[Result]: 查询结果
+
+ """
+ embedding = await self.embedding_provider.get_query_embedding(query)
+ scores, indices = await self.embedding_storage.search(
+ vector=np.array(embedding).astype("float32"),
+ k=fetch_k if metadata_filters else k,
+ )
+ if len(indices[0]) == 0 or indices[0][0] == -1:
+ return []
+ # FAISS IndexFlatL2 返回的是欧氏距离的平方;对单位向量有
+ # ``L2^2 = 2 - 2 * cos``,因此 ``1 - L2^2 / 2`` 就是余弦相似度。
+ # 这里只在入库与查询两侧保证向量已归一化(见 EmbeddingStorage),
+ # 公式本身保持不变。
+ scores[0] = 1.0 - (scores[0] / 2.0)
+ # NOTE: maybe the size is less than k.
+ fetched_docs = await self.document_storage.get_documents(
+ metadata_filters=metadata_filters or {},
+ ids=indices[0],
+ )
+ if not fetched_docs:
+ return []
+ result_docs: list[Result] = []
+
+ idx_pos = {fetch_doc["id"]: idx for idx, fetch_doc in enumerate(fetched_docs)}
+ for i, indice_idx in enumerate(indices[0]):
+ pos = idx_pos.get(indice_idx)
+ if pos is None:
+ continue
+ fetch_doc = fetched_docs[pos]
+ score = scores[0][i]
+ result_docs.append(Result(similarity=float(score), data=fetch_doc))
+
+ top_k_results = result_docs[:k]
+
+ if rerank and self.rerank_provider:
+ documents = [doc.data["text"] for doc in top_k_results]
+ reranked_results = await self.rerank_provider.rerank(query, documents)
+ reranked_results = sorted(
+ reranked_results,
+ key=lambda x: x.relevance_score,
+ reverse=True,
+ )
+ top_k_results = [
+ top_k_results[reranked_result.index]
+ for reranked_result in reranked_results
+ ]
+
+ return top_k_results
+
+ async def _rollback_partial_insert(
+ self,
+ ids: list[str],
+ int_ids: list[int],
+ ) -> None:
+ """Best-effort cleanup after a partial ``insert_batch`` write.
+
+ DocumentStorage commits independently from FAISS. When FAISS insertion
+ fails after documents are written — or after vectors were added in
+ memory but not flushed — remove those rows/ids so the two stores do
+ not diverge.
+
+ Args:
+ ids: Chunk UUID strings written to DocumentStorage.
+ int_ids: Internal integer ids returned by DocumentStorage, also
+ used as FAISS ids when any vectors may have been added.
+ """
+ if int_ids:
+ try:
+ await self.embedding_storage.delete(int_ids)
+ except Exception as exc:
+ logger.warning(
+ f"Failed to roll back FAISS vectors for partial insert: {exc}",
+ )
+
+ for doc_id in ids:
+ try:
+ await self.document_storage.delete_document_by_doc_id(doc_id)
+ except Exception as exc:
+ logger.warning(
+ f"Failed to roll back document storage entry {doc_id}: {exc}",
+ )
+
+ async def delete(self, doc_id: str) -> None:
+ """删除一条文档块(chunk)"""
+ # 获得对应的 int id
+ result = await self.document_storage.get_document_by_doc_id(doc_id)
+ int_id = result["id"] if result else None
+ if int_id is None:
+ return
+
+ # 使用 DocumentStorage 的删除方法
+ await self.document_storage.delete_document_by_doc_id(doc_id)
+ await self.embedding_storage.delete([int_id])
+
+ async def close(self) -> None:
+ # 归一化重建可能因为写盘失败而留在内存里,关闭时再试一次。
+ await self.embedding_storage.flush()
+ await self.document_storage.close()
+
+ async def count_documents(self, metadata_filter: dict | None = None) -> int:
+ """计算文档数量
+
+ Args:
+ metadata_filter (dict | None): 元数据过滤器
+
+ """
+ count = await self.document_storage.count_documents(
+ metadata_filters=metadata_filter or {},
+ )
+ return count
+
+ async def delete_documents(self, metadata_filters: dict) -> None:
+ """根据元数据过滤器删除文档"""
+ docs = await self.document_storage.get_documents(
+ metadata_filters=metadata_filters,
+ offset=None,
+ limit=None,
+ )
+ doc_ids: list[int] = [doc["id"] for doc in docs]
+ await self.embedding_storage.delete(doc_ids)
+ await self.document_storage.delete_documents(metadata_filters=metadata_filters)
diff --git a/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py b/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py
index 8b9a9174d79..906344b7891 100644
--- a/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py
+++ b/astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py
@@ -54,6 +54,9 @@ class APIReturnNoneError(Exception):
pass
+_IMAGE_UPLOAD_MAX_ATTEMPTS = 3
+
+
def _patch_qq_botpy_formdata() -> None:
"""Patch qq-botpy for aiohttp>=3.12 compatibility.
@@ -74,7 +77,7 @@ def _patch_qq_botpy_formdata() -> None:
_patch_qq_botpy_formdata()
-def _qqofficial_retry(max_attempts: int = 5):
+def _qqofficial_retry(max_attempts: int = 5, *, log_retries: bool = True):
"""Retry decorator for QQ Official API transient errors (HTTP 500/504)"""
return retry(
retry=retry_if_exception_type(
@@ -88,7 +91,7 @@ def _qqofficial_retry(max_attempts: int = 5):
),
stop=stop_after_attempt(max_attempts),
wait=wait_exponential(multiplier=2, min=2, max=30),
- before_sleep=before_sleep_log(logger, logging.WARNING),
+ before_sleep=before_sleep_log(logger, logging.WARNING) if log_retries else None,
reraise=True,
)
@@ -807,7 +810,7 @@ async def upload_group_and_c2c_image(
"srv_send_msg": False,
}
- @_qqofficial_retry()
+ @_qqofficial_retry(_IMAGE_UPLOAD_MAX_ATTEMPTS, log_retries=False)
async def _do_upload():
if "openid" in kwargs:
payload["openid"] = kwargs["openid"]
@@ -833,7 +836,14 @@ async def _do_upload():
try:
result = await _do_upload()
except APIReturnNoneError:
- logger.warning(f"上传图片API返回None,共尝试5次后放弃: {payload}")
+ logger.warning(
+ "[QQOfficial] 上传图片失败:API 返回 None(共尝试 %s 次),"
+ "file_type=%s, target=%s, data_size=%s bytes",
+ _IMAGE_UPLOAD_MAX_ATTEMPTS,
+ file_type,
+ kwargs.get("group_openid") or kwargs.get("openid") or "-",
+ len(image_base64),
+ )
raise
if not isinstance(result, dict):
diff --git a/astrbot/core/platform/sources/telegram/tg_adapter.py b/astrbot/core/platform/sources/telegram/tg_adapter.py
index 54588016ee1..0567b16dd92 100644
--- a/astrbot/core/platform/sources/telegram/tg_adapter.py
+++ b/astrbot/core/platform/sources/telegram/tg_adapter.py
@@ -659,7 +659,7 @@ def _apply_caption() -> None:
return None
message.sender = MessageMember(
str(_from_user.id),
- _from_user.username or "Unknown",
+ _from_user.username or _from_user.full_name or "Unknown",
)
message.self_id = str(context.bot.username)
message.raw_message = update
diff --git a/astrbot/core/provider/provider.py b/astrbot/core/provider/provider.py
index 0319d57c828..a9c90f7fcd3 100644
--- a/astrbot/core/provider/provider.py
+++ b/astrbot/core/provider/provider.py
@@ -1,484 +1,493 @@
-import abc
-import asyncio
-import os
-from collections.abc import AsyncGenerator, Mapping
-from typing import Literal, TypeAlias, Union
-
-from astrbot.core.agent.message import ContentPart, Message, is_checkpoint_message
-from astrbot.core.agent.tool import ToolSet
-from astrbot.core.provider.entities import (
- DecisionAnswer,
- DecisionBooleanQuestion,
- DecisionQuestion,
- DecisionState,
- LLMResponse,
- ProviderMeta,
- RerankResult,
- ToolCallsResult,
-)
-from astrbot.core.provider.headers import build_provider_headers
-from astrbot.core.provider.register import provider_cls_map
-from astrbot.core.utils.astrbot_path import get_astrbot_path
-
-Providers: TypeAlias = Union[
- "Provider",
- "STTProvider",
- "TTSProvider",
- "EmbeddingProvider",
- "RerankProvider",
- "DecisionProvider",
-]
-
-
-class AbstractProvider(abc.ABC):
- """Provider Abstract Class"""
-
- def __init__(self, provider_config: dict) -> None:
- super().__init__()
- self.model_name = ""
- self.provider_config = provider_config
- self.request_headers = build_provider_headers(
- provider_config.get("custom_headers")
- )
-
- def set_model(self, model_name: str) -> None:
- """Set the current model name"""
- self.model_name = model_name
-
- def get_model(self) -> str:
- """Get the current model name"""
- return self.model_name
-
- def meta(self) -> ProviderMeta:
- """Get the provider metadata"""
- provider_type_name = self.provider_config["type"]
- meta_data = provider_cls_map.get(provider_type_name)
- if not meta_data:
- raise ValueError(f"Provider type {provider_type_name} not registered")
- meta = ProviderMeta(
- id=self.provider_config.get("id", "default"),
- model=self.get_model(),
- type=provider_type_name,
- provider_type=meta_data.provider_type,
- )
- return meta
-
- async def test(self) -> None:
- """test the provider is a
-
- raises:
- Exception: if the provider is not available
- """
- ...
-
-
-class Provider(AbstractProvider):
- """Chat Provider"""
-
- def __init__(
- self,
- provider_config: dict,
- provider_settings: dict,
- ) -> None:
- super().__init__(provider_config)
- self.provider_settings = provider_settings
-
- @abc.abstractmethod
- def get_current_key(self) -> str:
- raise NotImplementedError
-
- def get_keys(self) -> list[str]:
- """获得提供商 Key"""
- keys = self.provider_config.get("key", [""])
- return keys or [""]
-
- @abc.abstractmethod
- def set_key(self, key: str) -> None:
- raise NotImplementedError
-
- @abc.abstractmethod
- async def get_models(self) -> list[str]:
- """获得支持的模型列表"""
- raise NotImplementedError
-
- @abc.abstractmethod
- async def text_chat(
- self,
- prompt: str | None = None,
- session_id: str | None = None,
- image_urls: list[str] | None = None,
- audio_urls: list[str] | None = None,
- func_tool: ToolSet | None = None,
- contexts: list[Message] | list[dict] | None = None,
- system_prompt: str | None = None,
- tool_calls_result: ToolCallsResult | list[ToolCallsResult] | None = None,
- model: str | None = None,
- extra_user_content_parts: list[ContentPart] | None = None,
- tool_choice: Literal["auto", "required"] = "auto",
- request_max_retries: int | None = None,
- **kwargs,
- ) -> LLMResponse:
- """获得 LLM 的文本对话结果。会使用当前的模型进行对话。
-
- Args:
- prompt: 提示词,和 contexts 二选一使用,如果都指定,则会将 prompt(以及可能的 image_urls) 作为最新的一条记录添加到 contexts 中
- session_id: 会话 ID(此属性已经被废弃)
- image_urls: 图片 URL 列表
- audio_urls: 音频 URL 列表,也支持本地路径
- tools: tool set
- tool_choice: 工具调用策略,`auto` 表示由模型自行决定,`required` 表示要求模型必须调用工具
- contexts: 上下文,和 prompt 二选一使用
- tool_calls_result: 回传给 LLM 的工具调用结果。参考: https://platform.openai.com/docs/guides/function-calling
- extra_user_content_parts: 额外的内容块列表,用于在用户消息后添加额外的文本块(如系统提醒、指令等)
- request_max_retries: 可重试请求错误的最大尝试次数,包含首次请求。
- kwargs: 其他参数
-
- Notes:
- - 如果传入了 image_urls,将会在对话时附上图片。如果模型不支持图片输入,将会抛出错误。
- - 如果传入了 audio_urls,将会在对话时附上音频。如果模型不支持音频输入,将会抛出错误或降级处理。
- - 如果传入了 tools,将会使用 tools 进行 Function-calling。如果模型不支持 Function-calling,将会抛出错误。
-
- """
- ...
-
- async def text_chat_stream(
- self,
- prompt: str | None = None,
- session_id: str | None = None,
- image_urls: list[str] | None = None,
- audio_urls: list[str] | None = None,
- func_tool: ToolSet | None = None,
- contexts: list[Message] | list[dict] | None = None,
- system_prompt: str | None = None,
- tool_calls_result: ToolCallsResult | list[ToolCallsResult] | None = None,
- model: str | None = None,
- tool_choice: Literal["auto", "required"] = "auto",
- request_max_retries: int | None = None,
- **kwargs,
- ) -> AsyncGenerator[LLMResponse, None]:
- """获得 LLM 的流式文本对话结果。会使用当前的模型进行对话。在生成的最后会返回一次完整的结果。
-
- Args:
- prompt: 提示词,和 contexts 二选一使用,如果都指定,则会将 prompt(以及可能的 image_urls) 作为最新的一条记录添加到 contexts 中
- session_id: 会话 ID(此属性已经被废弃)
- image_urls: 图片 URL 列表
- audio_urls: 音频 URL 列表,也支持本地路径
- tools: tool set
- tool_choice: 工具调用策略,`auto` 表示由模型自行决定,`required` 表示要求模型必须调用工具
- contexts: 上下文,和 prompt 二选一使用
- tool_calls_result: 回传给 LLM 的工具调用结果。参考: https://platform.openai.com/docs/guides/function-calling
- request_max_retries: 可重试请求错误的最大尝试次数,包含首次请求。
- kwargs: 其他参数
-
- Notes:
- - 如果传入了 image_urls,将会在对话时附上图片。如果模型不支持图片输入,将会抛出错误。
- - 如果传入了 audio_urls,将会在对话时附上音频。如果模型不支持音频输入,将会抛出错误或降级处理。
- - 如果传入了 tools,将会使用 tools 进行 Function-calling。如果模型不支持 Function-calling,将会抛出错误。
-
- """
- if False: # pragma: no cover - make this an async generator for typing
- yield None # type: ignore
- raise NotImplementedError()
-
- async def pop_record(self, context: list) -> None:
- """弹出 context 第一条非系统提示词对话记录"""
- poped = 0
- indexs_to_pop = []
- for idx, record in enumerate(context):
- if record["role"] == "system":
- continue
- indexs_to_pop.append(idx)
- poped += 1
- if poped == 2:
- break
-
- for idx in reversed(indexs_to_pop):
- context.pop(idx)
-
- def _ensure_message_to_dicts(
- self,
- messages: list[dict] | list[Message] | None,
- ) -> list[dict]:
- """Convert a list of Message objects to a list of dictionaries."""
- if not messages:
- return []
- dicts: list[dict] = []
- for message in messages:
- if is_checkpoint_message(message):
- continue
- if isinstance(message, Message):
- dicts.append(message.model_dump())
- else:
- dicts.append(message)
-
- return dicts
-
- async def test(self, timeout: float = 45.0) -> None:
- await asyncio.wait_for(
- self.text_chat(prompt="REPLY `PONG` ONLY"),
- timeout=timeout,
- )
-
-
-class STTProvider(AbstractProvider):
- def __init__(self, provider_config: dict, provider_settings: dict) -> None:
- super().__init__(provider_config)
- self.provider_config = provider_config
- self.provider_settings = provider_settings
-
- @abc.abstractmethod
- async def get_text(self, audio_url: str) -> str:
- """获取音频的文本"""
- raise NotImplementedError
-
- async def test(self) -> None:
- sample_audio_path = os.path.join(
- get_astrbot_path(),
- "samples",
- "stt_health_check.wav",
- )
- await self.get_text(sample_audio_path)
-
-
-class TTSProvider(AbstractProvider):
- def __init__(self, provider_config: dict, provider_settings: dict) -> None:
- super().__init__(provider_config)
- self.provider_config = provider_config
- self.provider_settings = provider_settings
-
- def support_stream(self) -> bool:
- """是否支持流式 TTS
-
- Returns:
- bool: True 表示支持流式处理,False 表示不支持(默认)
-
- Notes:
- 子类可以重写此方法返回 True 来启用流式 TTS 支持
- """
- return False
-
- @abc.abstractmethod
- async def get_audio(self, text: str) -> str:
- """获取文本的音频,返回音频文件路径"""
- raise NotImplementedError
-
- async def get_audio_stream(
- self,
- text_queue: asyncio.Queue[str | None],
- audio_queue: "asyncio.Queue[bytes | tuple[str, bytes] | None]",
- ) -> None:
- """流式 TTS 处理方法。
-
- 从 text_queue 中读取文本片段,将生成的音频数据(WAV 格式的 in-memory bytes)放入 audio_queue。
- 当 text_queue 收到 None 时,表示文本输入结束,此时应该处理完所有剩余文本并向 audio_queue 发送 None 表示结束。
-
- Args:
- text_queue: 输入文本队列,None 表示输入结束
- audio_queue: 输出音频队列(bytes 或 (text, bytes)),None 表示输出结束
-
- Notes:
- - 默认实现会将文本累积后一次性调用 get_audio 生成完整音频
- - 子类可以重写此方法实现真正的流式 TTS
- - 音频数据应该是 WAV 格式的 bytes
- """
- accumulated_text = ""
-
- while True:
- text_part = await text_queue.get()
-
- if text_part is None:
- # 输入结束,处理累积的文本
- if accumulated_text:
- try:
- # 调用原有的 get_audio 方法获取音频文件路径
- audio_path = await self.get_audio(accumulated_text)
- # 读取音频文件内容
- with open(audio_path, "rb") as f:
- audio_data = f.read()
- await audio_queue.put((accumulated_text, audio_data))
- except Exception:
- # 出错时也要发送 None 结束标记
- pass
- # 发送结束标记
- await audio_queue.put(None)
- break
-
- accumulated_text += text_part
-
- async def test(self) -> None:
- audio_path = await self.get_audio("hi")
-
- # 检查生成的音频文件是否有效
- if not os.path.exists(audio_path):
- raise Exception("TTS test failed: audio file was not created")
-
- file_size = os.path.getsize(audio_path)
- if file_size == 0:
- raise Exception(
- "TTS test failed: generated audio file is empty (0 bytes). "
- "Please check your TTS provider configuration, especially required parameters like group_id for MiniMax."
- )
-
- # 清理测试文件
- try:
- os.remove(audio_path)
- except Exception:
- pass
-
-
-class EmbeddingProvider(AbstractProvider):
- def __init__(self, provider_config: dict, provider_settings: dict) -> None:
- super().__init__(provider_config)
- self.provider_config = provider_config
- self.provider_settings = provider_settings
-
- @abc.abstractmethod
- async def get_embedding(self, text: str) -> list[float]:
- """获取文本的向量"""
- ...
-
- @abc.abstractmethod
- async def get_embeddings(self, text: list[str]) -> list[list[float]]:
- """批量获取文本的向量"""
- ...
-
- @abc.abstractmethod
- def get_dim(self) -> int:
- """获取向量的维度"""
- ...
-
- async def test(self) -> None:
- await self.get_embedding("astrbot")
-
- async def get_embeddings_batch(
- self,
- texts: list[str],
- batch_size: int = 16,
- tasks_limit: int = 3,
- max_retries: int = 3,
- progress_callback=None,
- ) -> list[list[float]]:
- """批量获取文本的向量,分批处理以节省内存
-
- Args:
- texts: 文本列表
- batch_size: 每批处理的文本数量
- tasks_limit: 并发任务数量限制
- max_retries: 失败时的最大重试次数
- progress_callback: 进度回调函数,接收参数 (current, total)
-
- Returns:
- 向量列表
-
- """
- semaphore = asyncio.Semaphore(tasks_limit)
- batch_results: dict[int, list[list[float]]] = {}
- failed_batches: list[tuple[int, list[str]]] = []
- completed_count = 0
- total_count = len(texts)
-
- async def process_batch(batch_idx: int, batch_texts: list[str]) -> None:
- nonlocal completed_count
- async with semaphore:
- for attempt in range(max_retries):
- try:
- batch_embeddings = await self.get_embeddings(batch_texts)
- batch_results[batch_idx] = batch_embeddings
- completed_count += len(batch_texts)
- if progress_callback:
- await progress_callback(completed_count, total_count)
- return
- except Exception as e:
- if attempt == max_retries - 1:
- # 最后一次重试失败,记录失败的批次
- failed_batches.append((batch_idx, batch_texts))
- raise Exception(
- f"批次 {batch_idx} 处理失败,已重试 {max_retries} 次: {e!s}",
- )
- # 等待一段时间后重试,使用指数退避
- await asyncio.sleep(2**attempt)
-
- tasks = []
- for i in range(0, len(texts), batch_size):
- batch_texts = texts[i : i + batch_size]
- batch_idx = i // batch_size
- tasks.append(process_batch(batch_idx, batch_texts))
-
- # 收集所有任务的结果,包括失败的任务
- results = await asyncio.gather(*tasks, return_exceptions=True)
-
- # 检查是否有失败的任务
- errors = [r for r in results if isinstance(r, Exception)]
- if errors:
- error_msg = (
- f"有 {len(errors)} 个批次处理失败: {'; '.join(str(e) for e in errors)}"
- )
- raise Exception(error_msg)
-
- all_embeddings: list[list[float]] = []
- for batch_idx in range(len(tasks)):
- all_embeddings.extend(batch_results[batch_idx])
- return all_embeddings
-
-
-class RerankProvider(AbstractProvider):
- def __init__(self, provider_config: dict, provider_settings: dict) -> None:
- super().__init__(provider_config)
- self.provider_config = provider_config
- self.provider_settings = provider_settings
-
- @abc.abstractmethod
- async def rerank(
- self,
- query: str,
- documents: list[str],
- top_n: int | None = None,
- ) -> list[RerankResult]:
- """获取查询和文档的重排序分数"""
- ...
-
- async def test(self) -> None:
- result = await self.rerank("Apple", documents=["apple", "banana"])
- if not result:
- raise Exception("Rerank provider test failed, no results returned")
-
-
-class DecisionProvider(AbstractProvider):
- """Provider for low-latency, structured decisions."""
-
- def __init__(self, provider_config: dict, provider_settings: dict) -> None:
- super().__init__(provider_config)
- self.provider_config = provider_config
- self.provider_settings = provider_settings
-
- @abc.abstractmethod
- async def ask(
- self,
- questions: Mapping[str, DecisionQuestion],
- state: DecisionState | None = None,
- *,
- request_max_retries: int = 0,
- ) -> Mapping[str, DecisionAnswer]:
- """Answer multiple decision questions in one provider request.
-
- Args:
- questions: Question heads keyed by caller-defined identifiers.
- state: Context evaluated by the model. Providers forward it as-is.
- request_max_retries: Number of retries after the initial request.
-
- Returns:
- Answers keyed by the same identifiers as ``questions``.
-
- Raises:
- ValueError: The question or criteria are unusable.
- DecisionError: The provider is unavailable, the request fails, or
- the response violates the decision contract.
- """
- ...
-
- async def test(self) -> None:
- await self.ask(
- {"test": DecisionBooleanQuestion("Is this provider available?")},
- {},
- request_max_retries=0,
- )
+import abc
+import asyncio
+import os
+from collections.abc import AsyncGenerator, Mapping
+from typing import Literal, TypeAlias, Union
+
+from astrbot.core.agent.message import ContentPart, Message, is_checkpoint_message
+from astrbot.core.agent.tool import ToolSet
+from astrbot.core.provider.entities import (
+ DecisionAnswer,
+ DecisionBooleanQuestion,
+ DecisionQuestion,
+ DecisionState,
+ LLMResponse,
+ ProviderMeta,
+ RerankResult,
+ ToolCallsResult,
+)
+from astrbot.core.provider.headers import build_provider_headers
+from astrbot.core.provider.register import provider_cls_map
+from astrbot.core.utils.astrbot_path import get_astrbot_path
+
+Providers: TypeAlias = Union[
+ "Provider",
+ "STTProvider",
+ "TTSProvider",
+ "EmbeddingProvider",
+ "RerankProvider",
+ "DecisionProvider",
+]
+
+
+class AbstractProvider(abc.ABC):
+ """Provider Abstract Class"""
+
+ def __init__(self, provider_config: dict) -> None:
+ super().__init__()
+ self.model_name = ""
+ self.provider_config = provider_config
+ self.request_headers = build_provider_headers(
+ provider_config.get("custom_headers")
+ )
+
+ def set_model(self, model_name: str) -> None:
+ """Set the current model name"""
+ self.model_name = model_name
+
+ def get_model(self) -> str:
+ """Get the current model name"""
+ return self.model_name
+
+ def meta(self) -> ProviderMeta:
+ """Get the provider metadata"""
+ provider_type_name = self.provider_config["type"]
+ meta_data = provider_cls_map.get(provider_type_name)
+ if not meta_data:
+ raise ValueError(f"Provider type {provider_type_name} not registered")
+ meta = ProviderMeta(
+ id=self.provider_config.get("id", "default"),
+ model=self.get_model(),
+ type=provider_type_name,
+ provider_type=meta_data.provider_type,
+ )
+ return meta
+
+ async def test(self) -> None:
+ """test the provider is a
+
+ raises:
+ Exception: if the provider is not available
+ """
+ ...
+
+
+class Provider(AbstractProvider):
+ """Chat Provider"""
+
+ def __init__(
+ self,
+ provider_config: dict,
+ provider_settings: dict,
+ ) -> None:
+ super().__init__(provider_config)
+ self.provider_settings = provider_settings
+
+ @abc.abstractmethod
+ def get_current_key(self) -> str:
+ raise NotImplementedError
+
+ def get_keys(self) -> list[str]:
+ """获得提供商 Key"""
+ keys = self.provider_config.get("key", [""])
+ return keys or [""]
+
+ @abc.abstractmethod
+ def set_key(self, key: str) -> None:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ async def get_models(self) -> list[str]:
+ """获得支持的模型列表"""
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ async def text_chat(
+ self,
+ prompt: str | None = None,
+ session_id: str | None = None,
+ image_urls: list[str] | None = None,
+ audio_urls: list[str] | None = None,
+ func_tool: ToolSet | None = None,
+ contexts: list[Message] | list[dict] | None = None,
+ system_prompt: str | None = None,
+ tool_calls_result: ToolCallsResult | list[ToolCallsResult] | None = None,
+ model: str | None = None,
+ extra_user_content_parts: list[ContentPart] | None = None,
+ tool_choice: Literal["auto", "required"] = "auto",
+ request_max_retries: int | None = None,
+ **kwargs,
+ ) -> LLMResponse:
+ """获得 LLM 的文本对话结果。会使用当前的模型进行对话。
+
+ Args:
+ prompt: 提示词,和 contexts 二选一使用,如果都指定,则会将 prompt(以及可能的 image_urls) 作为最新的一条记录添加到 contexts 中
+ session_id: 会话 ID(此属性已经被废弃)
+ image_urls: 图片 URL 列表
+ audio_urls: 音频 URL 列表,也支持本地路径
+ tools: tool set
+ tool_choice: 工具调用策略,`auto` 表示由模型自行决定,`required` 表示要求模型必须调用工具
+ contexts: 上下文,和 prompt 二选一使用
+ tool_calls_result: 回传给 LLM 的工具调用结果。参考: https://platform.openai.com/docs/guides/function-calling
+ extra_user_content_parts: 额外的内容块列表,用于在用户消息后添加额外的文本块(如系统提醒、指令等)
+ request_max_retries: 可重试请求错误的最大尝试次数,包含首次请求。
+ kwargs: 其他参数
+
+ Notes:
+ - 如果传入了 image_urls,将会在对话时附上图片。如果模型不支持图片输入,将会抛出错误。
+ - 如果传入了 audio_urls,将会在对话时附上音频。如果模型不支持音频输入,将会抛出错误或降级处理。
+ - 如果传入了 tools,将会使用 tools 进行 Function-calling。如果模型不支持 Function-calling,将会抛出错误。
+
+ """
+ ...
+
+ async def text_chat_stream(
+ self,
+ prompt: str | None = None,
+ session_id: str | None = None,
+ image_urls: list[str] | None = None,
+ audio_urls: list[str] | None = None,
+ func_tool: ToolSet | None = None,
+ contexts: list[Message] | list[dict] | None = None,
+ system_prompt: str | None = None,
+ tool_calls_result: ToolCallsResult | list[ToolCallsResult] | None = None,
+ model: str | None = None,
+ tool_choice: Literal["auto", "required"] = "auto",
+ request_max_retries: int | None = None,
+ **kwargs,
+ ) -> AsyncGenerator[LLMResponse, None]:
+ """获得 LLM 的流式文本对话结果。会使用当前的模型进行对话。在生成的最后会返回一次完整的结果。
+
+ Args:
+ prompt: 提示词,和 contexts 二选一使用,如果都指定,则会将 prompt(以及可能的 image_urls) 作为最新的一条记录添加到 contexts 中
+ session_id: 会话 ID(此属性已经被废弃)
+ image_urls: 图片 URL 列表
+ audio_urls: 音频 URL 列表,也支持本地路径
+ tools: tool set
+ tool_choice: 工具调用策略,`auto` 表示由模型自行决定,`required` 表示要求模型必须调用工具
+ contexts: 上下文,和 prompt 二选一使用
+ tool_calls_result: 回传给 LLM 的工具调用结果。参考: https://platform.openai.com/docs/guides/function-calling
+ request_max_retries: 可重试请求错误的最大尝试次数,包含首次请求。
+ kwargs: 其他参数
+
+ Notes:
+ - 如果传入了 image_urls,将会在对话时附上图片。如果模型不支持图片输入,将会抛出错误。
+ - 如果传入了 audio_urls,将会在对话时附上音频。如果模型不支持音频输入,将会抛出错误或降级处理。
+ - 如果传入了 tools,将会使用 tools 进行 Function-calling。如果模型不支持 Function-calling,将会抛出错误。
+
+ """
+ if False: # pragma: no cover - make this an async generator for typing
+ yield None # type: ignore
+ raise NotImplementedError()
+
+ async def pop_record(self, context: list) -> None:
+ """弹出 context 第一条非系统提示词对话记录"""
+ poped = 0
+ indexs_to_pop = []
+ for idx, record in enumerate(context):
+ if record["role"] == "system":
+ continue
+ indexs_to_pop.append(idx)
+ poped += 1
+ if poped == 2:
+ break
+
+ for idx in reversed(indexs_to_pop):
+ context.pop(idx)
+
+ def _ensure_message_to_dicts(
+ self,
+ messages: list[dict] | list[Message] | None,
+ ) -> list[dict]:
+ """Convert a list of Message objects to a list of dictionaries."""
+ if not messages:
+ return []
+ dicts: list[dict] = []
+ for message in messages:
+ if is_checkpoint_message(message):
+ continue
+ if isinstance(message, Message):
+ dicts.append(message.model_dump())
+ else:
+ dicts.append(message)
+
+ return dicts
+
+ async def test(self, timeout: float = 45.0) -> None:
+ await asyncio.wait_for(
+ self.text_chat(prompt="REPLY `PONG` ONLY"),
+ timeout=timeout,
+ )
+
+
+class STTProvider(AbstractProvider):
+ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
+ super().__init__(provider_config)
+ self.provider_config = provider_config
+ self.provider_settings = provider_settings
+
+ @abc.abstractmethod
+ async def get_text(self, audio_url: str) -> str:
+ """获取音频的文本"""
+ raise NotImplementedError
+
+ async def test(self) -> None:
+ sample_audio_path = os.path.join(
+ get_astrbot_path(),
+ "samples",
+ "stt_health_check.wav",
+ )
+ await self.get_text(sample_audio_path)
+
+
+class TTSProvider(AbstractProvider):
+ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
+ super().__init__(provider_config)
+ self.provider_config = provider_config
+ self.provider_settings = provider_settings
+
+ def support_stream(self) -> bool:
+ """是否支持流式 TTS
+
+ Returns:
+ bool: True 表示支持流式处理,False 表示不支持(默认)
+
+ Notes:
+ 子类可以重写此方法返回 True 来启用流式 TTS 支持
+ """
+ return False
+
+ @abc.abstractmethod
+ async def get_audio(self, text: str) -> str:
+ """获取文本的音频,返回音频文件路径"""
+ raise NotImplementedError
+
+ async def get_audio_stream(
+ self,
+ text_queue: asyncio.Queue[str | None],
+ audio_queue: "asyncio.Queue[bytes | tuple[str, bytes] | None]",
+ ) -> None:
+ """流式 TTS 处理方法。
+
+ 从 text_queue 中读取文本片段,将生成的音频数据(WAV 格式的 in-memory bytes)放入 audio_queue。
+ 当 text_queue 收到 None 时,表示文本输入结束,此时应该处理完所有剩余文本并向 audio_queue 发送 None 表示结束。
+
+ Args:
+ text_queue: 输入文本队列,None 表示输入结束
+ audio_queue: 输出音频队列(bytes 或 (text, bytes)),None 表示输出结束
+
+ Notes:
+ - 默认实现会将文本累积后一次性调用 get_audio 生成完整音频
+ - 子类可以重写此方法实现真正的流式 TTS
+ - 音频数据应该是 WAV 格式的 bytes
+ """
+ accumulated_text = ""
+
+ while True:
+ text_part = await text_queue.get()
+
+ if text_part is None:
+ # 输入结束,处理累积的文本
+ if accumulated_text:
+ try:
+ # 调用原有的 get_audio 方法获取音频文件路径
+ audio_path = await self.get_audio(accumulated_text)
+ # 读取音频文件内容
+ with open(audio_path, "rb") as f:
+ audio_data = f.read()
+ await audio_queue.put((accumulated_text, audio_data))
+ except Exception:
+ # 出错时也要发送 None 结束标记
+ pass
+ # 发送结束标记
+ await audio_queue.put(None)
+ break
+
+ accumulated_text += text_part
+
+ async def test(self) -> None:
+ audio_path = await self.get_audio("hi")
+
+ # 检查生成的音频文件是否有效
+ if not os.path.exists(audio_path):
+ raise Exception("TTS test failed: audio file was not created")
+
+ file_size = os.path.getsize(audio_path)
+ if file_size == 0:
+ raise Exception(
+ "TTS test failed: generated audio file is empty (0 bytes). "
+ "Please check your TTS provider configuration, especially required parameters like group_id for MiniMax."
+ )
+
+ # 清理测试文件
+ try:
+ os.remove(audio_path)
+ except Exception:
+ pass
+
+
+class EmbeddingProvider(AbstractProvider):
+ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
+ super().__init__(provider_config)
+ self.provider_config = provider_config
+ self.provider_settings = provider_settings
+
+ @abc.abstractmethod
+ async def get_embedding(self, text: str) -> list[float]:
+ """获取文本的向量"""
+ ...
+
+ @abc.abstractmethod
+ async def get_embeddings(self, text: list[str]) -> list[list[float]]:
+ """批量获取文本的向量"""
+ ...
+
+ async def get_query_embedding(self, text: str) -> list[float]:
+ """获取检索查询的向量。
+
+ 默认回退到 :meth:`get_embedding`。对支持非对称检索条件化的提供
+ 商(如 Gemini Embedding),应覆盖此方法让查询与文档使用不同的任务
+ 类型或文本前缀,否则编码空间对不上,相似度区分度会明显下降。
+ """
+ return await self.get_embedding(text)
+
+ @abc.abstractmethod
+ def get_dim(self) -> int:
+ """获取向量的维度"""
+ ...
+
+ async def test(self) -> None:
+ await self.get_embedding("astrbot")
+
+ async def get_embeddings_batch(
+ self,
+ texts: list[str],
+ batch_size: int = 16,
+ tasks_limit: int = 3,
+ max_retries: int = 3,
+ progress_callback=None,
+ ) -> list[list[float]]:
+ """批量获取文本的向量,分批处理以节省内存
+
+ Args:
+ texts: 文本列表
+ batch_size: 每批处理的文本数量
+ tasks_limit: 并发任务数量限制
+ max_retries: 失败时的最大重试次数
+ progress_callback: 进度回调函数,接收参数 (current, total)
+
+ Returns:
+ 向量列表
+
+ """
+ semaphore = asyncio.Semaphore(tasks_limit)
+ batch_results: dict[int, list[list[float]]] = {}
+ failed_batches: list[tuple[int, list[str]]] = []
+ completed_count = 0
+ total_count = len(texts)
+
+ async def process_batch(batch_idx: int, batch_texts: list[str]) -> None:
+ nonlocal completed_count
+ async with semaphore:
+ for attempt in range(max_retries):
+ try:
+ batch_embeddings = await self.get_embeddings(batch_texts)
+ batch_results[batch_idx] = batch_embeddings
+ completed_count += len(batch_texts)
+ if progress_callback:
+ await progress_callback(completed_count, total_count)
+ return
+ except Exception as e:
+ if attempt == max_retries - 1:
+ # 最后一次重试失败,记录失败的批次
+ failed_batches.append((batch_idx, batch_texts))
+ raise Exception(
+ f"批次 {batch_idx} 处理失败,已重试 {max_retries} 次: {e!s}",
+ )
+ # 等待一段时间后重试,使用指数退避
+ await asyncio.sleep(2**attempt)
+
+ tasks = []
+ for i in range(0, len(texts), batch_size):
+ batch_texts = texts[i : i + batch_size]
+ batch_idx = i // batch_size
+ tasks.append(process_batch(batch_idx, batch_texts))
+
+ # 收集所有任务的结果,包括失败的任务
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ # 检查是否有失败的任务
+ errors = [r for r in results if isinstance(r, Exception)]
+ if errors:
+ error_msg = (
+ f"有 {len(errors)} 个批次处理失败: {'; '.join(str(e) for e in errors)}"
+ )
+ raise Exception(error_msg)
+
+ all_embeddings: list[list[float]] = []
+ for batch_idx in range(len(tasks)):
+ all_embeddings.extend(batch_results[batch_idx])
+ return all_embeddings
+
+
+class RerankProvider(AbstractProvider):
+ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
+ super().__init__(provider_config)
+ self.provider_config = provider_config
+ self.provider_settings = provider_settings
+
+ @abc.abstractmethod
+ async def rerank(
+ self,
+ query: str,
+ documents: list[str],
+ top_n: int | None = None,
+ ) -> list[RerankResult]:
+ """获取查询和文档的重排序分数"""
+ ...
+
+ async def test(self) -> None:
+ result = await self.rerank("Apple", documents=["apple", "banana"])
+ if not result:
+ raise Exception("Rerank provider test failed, no results returned")
+
+
+class DecisionProvider(AbstractProvider):
+ """Provider for low-latency, structured decisions."""
+
+ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
+ super().__init__(provider_config)
+ self.provider_config = provider_config
+ self.provider_settings = provider_settings
+
+ @abc.abstractmethod
+ async def ask(
+ self,
+ questions: Mapping[str, DecisionQuestion],
+ state: DecisionState | None = None,
+ *,
+ request_max_retries: int = 0,
+ ) -> Mapping[str, DecisionAnswer]:
+ """Answer multiple decision questions in one provider request.
+
+ Args:
+ questions: Question heads keyed by caller-defined identifiers.
+ state: Context evaluated by the model. Providers forward it as-is.
+ request_max_retries: Number of retries after the initial request.
+
+ Returns:
+ Answers keyed by the same identifiers as ``questions``.
+
+ Raises:
+ ValueError: The question or criteria are unusable.
+ DecisionError: The provider is unavailable, the request fails, or
+ the response violates the decision contract.
+ """
+ ...
+
+ async def test(self) -> None:
+ await self.ask(
+ {"test": DecisionBooleanQuestion("Is this provider available?")},
+ {},
+ request_max_retries=0,
+ )
diff --git a/astrbot/core/provider/sources/dashscope_embedding_source.py b/astrbot/core/provider/sources/dashscope_embedding_source.py
index 56fd14fb382..3d1b121e465 100644
--- a/astrbot/core/provider/sources/dashscope_embedding_source.py
+++ b/astrbot/core/provider/sources/dashscope_embedding_source.py
@@ -13,6 +13,9 @@
_DEFAULT_API_BASE = "https://dashscope.aliyuncs.com/api/v1"
_DEFAULT_MODEL = "text-embedding-v4"
+#: ``text_type`` 的合法取值。多模态端点不接受该参数。
+_TEXT_TYPES = {"query", "document"}
+
@register_provider_adapter(
"dashscope_embedding",
@@ -26,6 +29,10 @@ class DashScopeEmbeddingProvider(EmbeddingProvider):
multimodal embedding models (qwen*-vl-embedding, multimodal-embedding-*,
tongyi-embedding-vision-*) through MultiModalEmbedding, so that models
unavailable in the OpenAI-compatible mode can be used.
+
+ 检索场景下 ``text_type`` 区分查询与文档:``query`` 生成针对信息检索优化
+ 的向量,``document`` 生成针对"被检索"优化的向量。两者不区分时查询与文档
+ 落在同一编码模式里,检索区分度会下降。
"""
def __init__(self, provider_config: dict, provider_settings: dict) -> None:
@@ -41,6 +48,17 @@ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
self.base_url = provider_config.get("embedding_api_base", _DEFAULT_API_BASE)
self.model = provider_config.get("embedding_model", _DEFAULT_MODEL)
+ # 是否发送 text_type。默认开启——检索是知识库的主要用途。
+ self.text_type_mode = (
+ str(provider_config.get("embedding_text_type_mode", "auto")).strip().lower()
+ )
+ if self.text_type_mode not in {"auto", "never"}:
+ logger.warning(
+ f"[DashScope Embedding] 未知的 embedding_text_type_mode: "
+ f"{self.text_type_mode!r},回退为 'auto'。",
+ )
+ self.text_type_mode = "auto"
+
provider_id = provider_config.get("id", "unknown_id")
logger.info(
f"[DashScope Embedding] {provider_id} Initialized via native SDK, "
@@ -48,13 +66,43 @@ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
)
self.set_model(self.model)
+ def _is_multimodal(self) -> bool:
+ return (
+ "vl-embedding" in self.model
+ or self.model.startswith("multimodal-embedding")
+ or self.model.startswith("tongyi-embedding-vision")
+ )
+
+ def _should_send_text_type(self) -> bool:
+ """多模态端点不接受 text_type;旧版模型也不支持。"""
+ if self.text_type_mode == "never":
+ return False
+ return not self._is_multimodal()
+
async def get_embedding(self, text: str) -> list[float]:
- """Get the embedding vector for a single text."""
- embeddings = await self.get_embeddings([text])
+ """Get the embedding vector for a single text.
+
+ 按文档侧语义嵌入,保持与既有调用方(入库、连通性测试)的兼容性。
+ 检索查询请使用 :meth:`get_query_embedding`。
+ """
+ embeddings = await self._get_embeddings_with_type([text], "document")
+ return embeddings[0] if embeddings else []
+
+ async def get_query_embedding(self, text: str) -> list[float]:
+ """Get the embedding vector for a retrieval query."""
+ embeddings = await self._get_embeddings_with_type([text], "query")
return embeddings[0] if embeddings else []
async def get_embeddings(self, text: list[str]) -> list[list[float]]:
- """Get the embedding vectors for a batch of texts via the dashscope SDK.
+ """Get the embedding vectors for a batch of documents."""
+ return await self._get_embeddings_with_type(text, "document")
+
+ async def _get_embeddings_with_type(
+ self,
+ text: list[str],
+ text_type: str,
+ ) -> list[list[float]]:
+ """Get embedding vectors, optionally tagging the input role.
Multimodal models (e.g. qwen3-vl-embedding) use the
multimodal-embedding endpoint and accept text wrapped in content dicts;
@@ -63,11 +111,7 @@ async def get_embeddings(self, text: list[str]) -> list[list[float]]:
if not text:
return []
- is_multimodal = (
- "vl-embedding" in self.model
- or self.model.startswith("multimodal-embedding")
- or self.model.startswith("tongyi-embedding-vision")
- )
+ is_multimodal = self._is_multimodal()
kwargs: dict = {
"base_address": self.base_url,
@@ -84,6 +128,11 @@ async def get_embeddings(self, text: list[str]) -> list[list[float]]:
f"'{self.provider_config['embedding_dimensions']}', ignored."
)
+ if self._should_send_text_type():
+ if text_type not in _TEXT_TYPES:
+ text_type = "document"
+ kwargs["text_type"] = text_type
+
# The dashscope SDK is synchronous; run it in a worker thread.
# base_address is passed per-call to avoid racing on the module-level
# dashscope.base_http_api_url global under concurrent usage.
diff --git a/astrbot/core/provider/sources/gemini_embedding_source.py b/astrbot/core/provider/sources/gemini_embedding_source.py
index 7c14d06ab1c..f2fd40919fb 100644
--- a/astrbot/core/provider/sources/gemini_embedding_source.py
+++ b/astrbot/core/provider/sources/gemini_embedding_source.py
@@ -1,92 +1,294 @@
-from google import genai
-from google.genai import types
-from google.genai.errors import APIError
-
-from astrbot import logger
-
-from ..entities import ProviderType
-from ..provider import EmbeddingProvider
-from ..register import register_provider_adapter
-
-
-@register_provider_adapter(
- "gemini_embedding",
- "Google Gemini Embedding 提供商适配器",
- provider_type=ProviderType.EMBEDDING,
-)
-class GeminiEmbeddingProvider(EmbeddingProvider):
- def __init__(self, provider_config: dict, provider_settings: dict) -> None:
- super().__init__(provider_config, provider_settings)
- self.provider_config = provider_config
- self.provider_settings = provider_settings
-
- api_key: str = provider_config["embedding_api_key"]
- api_base: str = provider_config["embedding_api_base"]
- timeout: int = int(provider_config.get("timeout", 20))
-
- http_options = types.HttpOptions(
- timeout=timeout * 1000, headers=self.request_headers
- )
- if api_base:
- api_base = api_base.removesuffix("/")
- http_options.base_url = api_base
- proxy = provider_config.get("proxy", "")
- if proxy:
- http_options.async_client_args = {"proxy": proxy}
- logger.info(f"[Gemini Embedding] 使用代理: {proxy}")
-
- self.client = genai.Client(api_key=api_key, http_options=http_options).aio
- # The SDK adds its own lower-case UA alongside our explicit header.
- self.client._api_client._http_options.headers.pop("user-agent", None)
-
- self.model = provider_config.get(
- "embedding_model",
- "gemini-embedding-001",
- )
-
- async def get_embedding(self, text: str) -> list[float]:
- """获取文本的嵌入"""
- try:
- result = await self.client.models.embed_content(
- model=self.model,
- contents=text,
- config=types.EmbedContentConfig(
- output_dimensionality=self.get_dim(),
- ),
- )
- assert result.embeddings is not None
- assert result.embeddings[0].values is not None
- return result.embeddings[0].values
- except APIError as e:
- raise Exception(f"Gemini Embedding API请求失败: {e.message}")
-
- async def get_embeddings(self, text: list[str]) -> list[list[float]]:
- """批量获取文本的嵌入"""
- try:
- contents = [
- types.Content(parts=[types.Part.from_text(text=s)]) for s in text
- ]
- result = await self.client.models.embed_content(
- model=self.model,
- contents=contents,
- config=types.EmbedContentConfig(
- output_dimensionality=self.get_dim(),
- ),
- )
- assert result.embeddings is not None
-
- embeddings: list[list[float]] = []
- for embedding in result.embeddings:
- assert embedding.values is not None
- embeddings.append(embedding.values)
- return embeddings
- except APIError as e:
- raise Exception(f"Gemini Embedding API批量请求失败: {e.message}")
-
- def get_dim(self) -> int:
- """获取向量的维度"""
- return int(self.provider_config.get("embedding_dimensions", 768))
-
- async def terminate(self):
- if self.client:
- await self.client.aclose()
+"""Google Gemini Embedding 提供商适配器。
+
+两条任务条件化路径,取决于模型代际:
+
+- ``gemini-embedding-001``(及更早模型):使用 API 的 ``task_type`` 参数,
+ 查询用 ``RETRIEVAL_QUERY``,文档用 ``RETRIEVAL_DOCUMENT``(可带 ``title``)。
+- ``gemini-embedding-2``:官方不再支持 ``task_type``,改为把任务前缀写进文本。
+ 非对称检索的格式为:
+
+ - 查询:``task: search result | query: {content}``
+ - 文档:``title: {title} | text: {content}``(无标题时 ``title: none``)
+
+参考:https://ai.google.dev/gemini-api/docs/embeddings
+"""
+
+from google import genai
+from google.genai import types
+from google.genai.errors import APIError
+
+from astrbot import logger
+
+from ..entities import ProviderType
+from ..provider import EmbeddingProvider
+from ..register import register_provider_adapter
+
+#: 走文本前缀路径的模型前缀(gemini-embedding-2 / -2-preview 等)。
+_TASK_PREFIX_MODEL_MARKERS = ("gemini-embedding-2",)
+
+#: 走 ``task_type`` 参数路径的默认查询/文档任务类型。
+_DEFAULT_QUERY_TASK = "RETRIEVAL_QUERY"
+_DEFAULT_DOCUMENT_TASK = "RETRIEVAL_DOCUMENT"
+
+#: ``gemini-embedding-2`` 支持的非对称任务名。
+_PREFIX_ASYMMETRIC_TASKS = {
+ "search result",
+ "question answering",
+ "fact checking",
+ "code retrieval",
+}
+
+
+def uses_task_prefix(model: str) -> bool:
+ """判断该模型是否应使用文本任务前缀(而非 ``task_type`` 参数)。"""
+ model_name = str(model or "").strip().lower()
+ # 允许 ``models/gemini-embedding-2`` 这类带前缀的写法。
+ model_name = model_name.rsplit("/", 1)[-1]
+ return model_name.startswith(_TASK_PREFIX_MODEL_MARKERS)
+
+
+def _normalize_task_name(task: str) -> str:
+ """把用户配置的任务名归一化(大小写、下划线/空格互换)。"""
+ return " ".join(str(task or "").strip().lower().replace("_", " ").split())
+
+
+def resolve_query_task(task: str | None) -> str:
+ """把配置值解析成合法的查询任务名,非法值回退到 ``search result``。
+
+ 单独抽出来的原因是:配置笔误(多一个连字符、大写、写错单词)不应该让
+ 整个检索链路在调用时才崩掉,而构造期就应该收敛到一个可用值。
+ """
+ normalized = _normalize_task_name(task or "")
+ return normalized if normalized in _PREFIX_ASYMMETRIC_TASKS else "search result"
+
+
+def build_query_prefix(task: str = "search result") -> str:
+ """构造 ``gemini-embedding-2`` 的查询前缀。
+
+ 任务名不可识别时回退到 ``search result``,保证检索链路不会因为一个配置
+ 笔误整体崩掉。
+
+ Args:
+ task: 任务名,见 ``_PREFIX_ASYMMETRIC_TASKS``,默认 ``search result``。
+
+ Returns:
+ 形如 ``task: search result | query: `` 的前缀字符串。
+ """
+ normalized = _normalize_task_name(task)
+ if normalized not in _PREFIX_ASYMMETRIC_TASKS:
+ normalized = resolve_query_task(task)
+ return f"task: {normalized} | query: "
+
+
+def build_document_prefix(title: str | None = None) -> str:
+ """构造 ``gemini-embedding-2`` 的文档前缀。
+
+ Args:
+ title: 文档标题;为空时使用 ``none``。
+
+ Returns:
+ 形如 ``title: none | text: `` 的前缀字符串。
+ """
+ safe_title = " ".join(str(title or "").split()) or "none"
+ return f"title: {safe_title} | text: "
+
+
+@register_provider_adapter(
+ "gemini_embedding",
+ "Google Gemini Embedding 提供商适配器",
+ provider_type=ProviderType.EMBEDDING,
+)
+class GeminiEmbeddingProvider(EmbeddingProvider):
+ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
+ super().__init__(provider_config, provider_settings)
+ self.provider_config = provider_config
+ self.provider_settings = provider_settings
+
+ api_key: str = provider_config["embedding_api_key"]
+ api_base: str = provider_config["embedding_api_base"]
+ timeout: int = int(provider_config.get("timeout", 20))
+
+ http_options = types.HttpOptions(
+ timeout=timeout * 1000, headers=self.request_headers
+ )
+ if api_base:
+ api_base = api_base.removesuffix("/")
+ http_options.base_url = api_base
+ proxy = provider_config.get("proxy", "")
+ if proxy:
+ http_options.async_client_args = {"proxy": proxy}
+ logger.info(f"[Gemini Embedding] 使用代理: {proxy}")
+
+ self.client = genai.Client(api_key=api_key, http_options=http_options).aio
+ # The SDK adds its own lower-case UA alongside our explicit header.
+ self.client._api_client._http_options.headers.pop("user-agent", None)
+
+ self.model = provider_config.get(
+ "embedding_model",
+ "gemini-embedding-001",
+ )
+
+ # 任务条件化配置。默认按检索场景(查询/文档非对称)处理。
+ self.task_config_mode = (
+ str(provider_config.get("embedding_task_type_mode", "auto")).strip().lower()
+ )
+ if self.task_config_mode not in {"auto", "never", "always"}:
+ logger.warning(
+ f"[Gemini Embedding] 未知的 embedding_task_type_mode: "
+ f"{self.task_config_mode!r},回退为 'auto'。",
+ )
+ self.task_config_mode = "auto"
+ self.query_task = (
+ provider_config.get("embedding_query_task_type") or _DEFAULT_QUERY_TASK
+ )
+ self.document_task = (
+ provider_config.get("embedding_document_task_type")
+ or _DEFAULT_DOCUMENT_TASK
+ )
+ self.query_prefix_task = resolve_query_task(
+ provider_config.get("embedding_query_task_name")
+ )
+ configured_task = provider_config.get("embedding_query_task_name")
+ if configured_task and resolve_query_task(
+ configured_task
+ ) != _normalize_task_name(configured_task):
+ logger.warning(
+ f"[Gemini Embedding] 未知的 embedding_query_task_name: "
+ f"{configured_task!r},回退为 'search result'。"
+ f"可选: {', '.join(sorted(_PREFIX_ASYMMETRIC_TASKS))}",
+ )
+ # 默认留空:AstrBot 入库时已经把文档标题拼进了 embedding_contents
+ # (见 kb_helper.py 的 ``{document_title}\n\n{chunk_text}``),这里再填
+ # 一次会让标题重复两遍。只有直接调用本适配器、正文不含标题时才建议设置。
+ self.document_title = provider_config.get("embedding_document_title") or ""
+
+ if self._uses_task_prefix():
+ logger.debug(
+ f"[Gemini Embedding] 模型 {self.model} 使用文本任务前缀,"
+ "不发送 task_type。",
+ )
+
+ self.set_model(self.model)
+
+ # ── 任务条件化 ──────────────────────────────────────────────
+
+ def _uses_task_prefix(self) -> bool:
+ if self.task_config_mode == "never":
+ return False
+ if self.task_config_mode == "always":
+ return True
+ return uses_task_prefix(self.model)
+
+ def _build_config(
+ self,
+ *,
+ task_type: str | None,
+ title: str | None = None,
+ ) -> types.EmbedContentConfig:
+ """构造 ``EmbedContentConfig``;前缀模式不设置 ``task_type``。"""
+ kwargs: dict = {"output_dimensionality": self.get_dim()}
+ if task_type and not self._uses_task_prefix():
+ kwargs["task_type"] = task_type
+ # ``title`` 只在 RETRIEVAL_DOCUMENT 下有意义。
+ if title and task_type == _DEFAULT_DOCUMENT_TASK:
+ kwargs["title"] = title
+ return types.EmbedContentConfig(**kwargs)
+
+ def _prepare_query(self, text: str) -> str:
+ if not self._uses_task_prefix():
+ return text
+ return build_query_prefix(self.query_prefix_task) + text
+
+ def _prepare_document(self, text: str) -> str:
+ if not self._uses_task_prefix():
+ return text
+ return build_document_prefix(self.document_title) + text
+
+ # ── EmbeddingProvider 接口 ──────────────────────────────────
+
+ async def get_embedding(self, text: str) -> list[float]:
+ """获取文本的嵌入。
+
+ 为兼容既有调用方(知识库入库、提供商连通性测试等),该方法按
+ **文档**侧语义嵌入。检索查询请使用 :meth:`get_query_embedding`。
+ """
+ return await self._embed_single(
+ self._prepare_document(text),
+ config=self._build_config(
+ task_type=self.document_task,
+ title=self.document_title or None,
+ ),
+ )
+
+ async def get_query_embedding(self, text: str) -> list[float]:
+ """获取检索查询的嵌入(带查询侧任务条件化)。"""
+ return await self._embed_single(
+ self._prepare_query(text),
+ config=self._build_config(task_type=self.query_task),
+ )
+
+ async def get_embeddings(self, text: list[str]) -> list[list[float]]:
+ """批量获取**文档**侧文本的嵌入。
+
+ 批量入库不需要查询侧语义,因此统一走文档路径。
+ """
+ return await self._embed_many(
+ [self._prepare_document(s) for s in text],
+ config=self._build_config(
+ task_type=self.document_task,
+ title=self.document_title or None,
+ ),
+ )
+
+ async def _embed_single(
+ self,
+ text: str,
+ *,
+ config: types.EmbedContentConfig,
+ ) -> list[float]:
+ try:
+ result = await self.client.models.embed_content(
+ model=self.model,
+ contents=text,
+ config=config,
+ )
+ if not result.embeddings or result.embeddings[0].values is None:
+ raise Exception("Gemini Embedding API 返回了空向量")
+ return result.embeddings[0].values
+ except APIError as e:
+ raise Exception(f"Gemini Embedding API请求失败: {e.message}")
+
+ async def _embed_many(
+ self,
+ text: list[str],
+ *,
+ config: types.EmbedContentConfig,
+ ) -> list[list[float]]:
+ try:
+ contents = [
+ types.Content(parts=[types.Part.from_text(text=s)]) for s in text
+ ]
+ result = await self.client.models.embed_content(
+ model=self.model,
+ contents=contents,
+ config=config,
+ )
+ if result.embeddings is None:
+ raise Exception("Gemini Embedding API 返回了空结果")
+
+ embeddings: list[list[float]] = []
+ for embedding in result.embeddings:
+ if embedding.values is None:
+ raise Exception("Gemini Embedding API 返回的向量为空")
+ embeddings.append(embedding.values)
+ return embeddings
+ except APIError as e:
+ raise Exception(f"Gemini Embedding API批量请求失败: {e.message}")
+
+ def get_dim(self) -> int:
+ """获取向量的维度"""
+ return int(self.provider_config.get("embedding_dimensions", 768))
+
+ async def terminate(self):
+ if self.client:
+ await self.client.aclose()
diff --git a/astrbot/core/provider/sources/gemini_tts_source.py b/astrbot/core/provider/sources/gemini_tts_source.py
index 136916aa1db..e7937b471e2 100644
--- a/astrbot/core/provider/sources/gemini_tts_source.py
+++ b/astrbot/core/provider/sources/gemini_tts_source.py
@@ -45,7 +45,7 @@ def __init__(
self.client._api_client._http_options.headers.pop("user-agent", None)
self.model: str = provider_config.get(
"gemini_tts_model",
- "gemini-2.5-flash-preview-tts",
+ "gemini-3.8-flash-tts",
)
self.prefix: str | None = provider_config.get(
"gemini_tts_prefix",
diff --git a/astrbot/core/provider/sources/nvidia_embedding_source.py b/astrbot/core/provider/sources/nvidia_embedding_source.py
index d650c68b4a1..ed3357661cb 100644
--- a/astrbot/core/provider/sources/nvidia_embedding_source.py
+++ b/astrbot/core/provider/sources/nvidia_embedding_source.py
@@ -30,7 +30,11 @@ def __init__(self, provider_config: dict, provider_settings: dict) -> None:
self.model = provider_config.get(
"embedding_model", "nvidia/nemotron-3-embed-1b"
)
+ # 文档侧 input_type。索引阶段用 passage。
self.input_type = provider_config.get("input_type", "passage")
+ # 查询侧 input_type。NV-Embed-QA / E5 / nemotron 这类模型必须区分
+ # passage 与 query,混用会显著降低检索准确率。
+ self.query_input_type = provider_config.get("query_input_type") or "query"
proxy = provider_config.get("proxy", "")
self.proxy = proxy
@@ -54,7 +58,11 @@ async def _get_client(self):
)
return self.client
- def _build_payload(self, text: str | list[str]) -> dict:
+ def _build_payload(
+ self,
+ text: str | list[str],
+ input_type: str | None = None,
+ ) -> dict:
if isinstance(text, str):
input_text = [text]
else:
@@ -63,7 +71,7 @@ def _build_payload(self, text: str | list[str]) -> dict:
return {
"input": input_text,
"model": self.model,
- "input_type": self.input_type,
+ "input_type": input_type or self.input_type,
"encoding_format": "float",
}
@@ -76,15 +84,33 @@ def _parse_response(self, response_data: dict) -> list[list[float]]:
return embeddings
async def get_embedding(self, text: str) -> list[float]:
+ """单条文本按文档侧(passage)语义嵌入。"""
embeddings = await self.get_embeddings([text])
return embeddings[0] if embeddings else []
+ async def get_query_embedding(self, text: str) -> list[float]:
+ """检索查询按 query 侧语义嵌入。
+
+ NVIDIA 文档明确要求检索查询使用 ``input_type=query``,混用 passage
+ 会显著降低检索准确率。
+ """
+ embeddings = await self._get_embeddings_with_type([text], self.query_input_type)
+ return embeddings[0] if embeddings else []
+
async def get_embeddings(self, text: list[str]) -> list[list[float]]:
+ """批量按文档侧(passage)语义嵌入。"""
+ return await self._get_embeddings_with_type(text, self.input_type)
+
+ async def _get_embeddings_with_type(
+ self,
+ text: list[str],
+ input_type: str,
+ ) -> list[list[float]]:
client = await self._get_client()
if not client or client.closed:
raise Exception("[NVIDIA Embedding] Client session not initialized")
- payload = self._build_payload(text)
+ payload = self._build_payload(text, input_type=input_type)
request_url = f"{self.base_url}/embeddings"
try:
diff --git a/astrbot/core/utils/image_input.py b/astrbot/core/utils/image_input.py
index f3f9558b596..7c1b79a00ed 100644
--- a/astrbot/core/utils/image_input.py
+++ b/astrbot/core/utils/image_input.py
@@ -159,6 +159,7 @@ async def prepare_request_images(
)
oversized = None
montage = None
+ has_persistent_montage = False
for result, index, temporary in rows:
name = f"Image {index}" if index is not None else "Image Attachment"
origin = " in quoted message" if result["quoted"] else ""
@@ -167,6 +168,7 @@ async def prepare_request_images(
if result["montage"]:
status = "; animation converted to a 3x3 frame montage"
montage = result
+ has_persistent_montage |= not temporary
elif result["status"] == "oversized":
status = (
f"; skipped: exceeds {MODEL_IMAGE_MAX_INPUT_BYTES // (1024 * 1024)} MiB"
@@ -200,7 +202,9 @@ async def prepare_request_images(
"Images labeled as animation montages contain frames in reading order. "
"Treat them as animations; do not mention the conversion or frame layout.\n"
""
- ).mark_as_temp()
+ )
+ if not has_persistent_montage:
+ advice.mark_as_temp()
montage["notices"].append(advice)
parts.append(advice)
req.extra_user_content_parts = parts
diff --git a/astrbot/dashboard/utils.py b/astrbot/dashboard/utils.py
index 2f0189cd9f8..58ddd613033 100644
--- a/astrbot/dashboard/utils.py
+++ b/astrbot/dashboard/utils.py
@@ -1,167 +1,167 @@
-import base64
-import traceback
-from io import BytesIO
-from typing import TYPE_CHECKING
-
-from astrbot.api import logger
-from astrbot.core.knowledge_base.kb_helper import KBHelper
-from astrbot.core.knowledge_base.kb_mgr import KnowledgeBaseManager
-
-if TYPE_CHECKING:
- from astrbot.core.db.vec_db.faiss_impl import FaissVecDB
-
-
-async def generate_tsne_visualization(
- query: str,
- kb_names: list[str],
- kb_manager: KnowledgeBaseManager,
-) -> str | None:
- """生成 t-SNE 可视化图片
-
- Args:
- query: 查询文本
- kb_names: 知识库名称列表
- kb_manager: 知识库管理器
-
- Returns:
- 图片路径或 None
-
- """
- try:
- import faiss
- import matplotlib # type: ignore[reportMissingImports]
- import numpy as np
-
- matplotlib.use("Agg") # 使用非交互式后端
- import matplotlib.pyplot as plt # type: ignore[reportMissingImports]
- from sklearn.manifold import TSNE # type: ignore[reportMissingImports]
- except ImportError as e:
- raise Exception(
- "缺少必要的库以生成 t-SNE 可视化。请安装 matplotlib 和 scikit-learn: {e}",
- ) from e
-
- try:
- # 获取第一个知识库的向量数据
- kb_helper: KBHelper | None = None
- for kb_name in kb_names:
- kb_helper = await kb_manager.get_kb_by_name(kb_name)
- if kb_helper:
- break
-
- if not kb_helper:
- logger.warning("未找到知识库")
- return None
-
- kb = kb_helper.kb
- index_path = kb_helper.kb_dir / "index.faiss"
-
- # 读取 FAISS 索引
- if not index_path.exists():
- logger.warning(f"FAISS 索引不存在: {index_path!s}")
- return None
-
- index = faiss.read_index(str(index_path))
-
- if index.ntotal == 0:
- logger.warning("索引为空")
- return None
-
- # 提取所有向量
- logger.info(f"提取 {index.ntotal} 个向量用于可视化...")
- if isinstance(index, faiss.IndexIDMap):
- base_index = faiss.downcast_index(index.index)
- if hasattr(base_index, "reconstruct_n"):
- vectors = base_index.reconstruct_n(0, index.ntotal)
- else:
- vectors = np.zeros((index.ntotal, index.d), dtype=np.float32)
- for i in range(index.ntotal):
- base_index.reconstruct(i, vectors[i])
- elif hasattr(index, "reconstruct_n"):
- vectors = index.reconstruct_n(0, index.ntotal)
- else:
- vectors = np.zeros((index.ntotal, index.d), dtype=np.float32)
- for i in range(index.ntotal):
- index.reconstruct(i, vectors[i])
-
- # 获取查询向量
- vec_db: FaissVecDB = kb_helper.vec_db # type: ignore
- embedding_provider = vec_db.embedding_provider
- query_embedding = await embedding_provider.get_embedding(query)
- query_vector = np.array([query_embedding], dtype=np.float32)
-
- # 合并所有向量和查询向量
- all_vectors = np.vstack([vectors, query_vector])
-
- # t-SNE 降维
- logger.info("开始 t-SNE 降维...")
- perplexity = min(30, all_vectors.shape[0] - 1)
- tsne = TSNE(n_components=2, random_state=42, perplexity=perplexity)
- vectors_2d = tsne.fit_transform(all_vectors)
-
- # 分离知识库向量和查询向量
- kb_vectors_2d = vectors_2d[:-1]
- query_vector_2d = vectors_2d[-1]
-
- # 可视化
- logger.info("生成可视化图表...")
- plt.figure(figsize=(14, 10))
-
- # 绘制知识库向量
- scatter = plt.scatter(
- kb_vectors_2d[:, 0],
- kb_vectors_2d[:, 1],
- alpha=0.5,
- s=40,
- c=range(len(kb_vectors_2d)),
- cmap="viridis",
- label="Knowledge Base Vectors",
- )
-
- # 绘制查询向量(红色 X)
- plt.scatter(
- query_vector_2d[0],
- query_vector_2d[1],
- c="red",
- s=300,
- marker="X",
- edgecolors="black",
- linewidths=2,
- label="Query",
- zorder=5,
- )
-
- # 添加查询文本标注
- plt.annotate(
- "Query",
- (query_vector_2d[0], query_vector_2d[1]),
- xytext=(10, 10),
- textcoords="offset points",
- fontsize=10,
- bbox={"boxstyle": "round,pad=0.5", "fc": "yellow", "alpha": 0.7},
- arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=0"},
- )
-
- plt.colorbar(scatter, label="Vector Index")
- plt.title(
- f"t-SNE Visualization: Query in Knowledge Base\n"
- f"({index.ntotal} vectors, {index.d} dimensions, KB: {kb.kb_name})",
- fontsize=14,
- pad=20,
- )
- plt.xlabel("t-SNE Dimension 1", fontsize=12)
- plt.ylabel("t-SNE Dimension 2", fontsize=12)
- plt.grid(True, alpha=0.3)
- plt.legend(fontsize=10, loc="upper right")
-
- # base64 编码图片返回
- buffer = BytesIO()
- plt.savefig(buffer, format="png", dpi=150, bbox_inches="tight")
- plt.close()
- buffer.seek(0)
- img_base64 = base64.b64encode(buffer.read()).decode("utf-8")
- return img_base64
-
- except Exception as e:
- logger.error(f"生成 t-SNE 可视化时出错: {e}")
- logger.error(traceback.format_exc())
- return None
+import base64
+import traceback
+from io import BytesIO
+from typing import TYPE_CHECKING
+
+from astrbot.api import logger
+from astrbot.core.knowledge_base.kb_helper import KBHelper
+from astrbot.core.knowledge_base.kb_mgr import KnowledgeBaseManager
+
+if TYPE_CHECKING:
+ from astrbot.core.db.vec_db.faiss_impl import FaissVecDB
+
+
+async def generate_tsne_visualization(
+ query: str,
+ kb_names: list[str],
+ kb_manager: KnowledgeBaseManager,
+) -> str | None:
+ """生成 t-SNE 可视化图片
+
+ Args:
+ query: 查询文本
+ kb_names: 知识库名称列表
+ kb_manager: 知识库管理器
+
+ Returns:
+ 图片路径或 None
+
+ """
+ try:
+ import faiss
+ import matplotlib # type: ignore[reportMissingImports]
+ import numpy as np
+
+ matplotlib.use("Agg") # 使用非交互式后端
+ import matplotlib.pyplot as plt # type: ignore[reportMissingImports]
+ from sklearn.manifold import TSNE # type: ignore[reportMissingImports]
+ except ImportError as e:
+ raise Exception(
+ "缺少必要的库以生成 t-SNE 可视化。请安装 matplotlib 和 scikit-learn: {e}",
+ ) from e
+
+ try:
+ # 获取第一个知识库的向量数据
+ kb_helper: KBHelper | None = None
+ for kb_name in kb_names:
+ kb_helper = await kb_manager.get_kb_by_name(kb_name)
+ if kb_helper:
+ break
+
+ if not kb_helper:
+ logger.warning("未找到知识库")
+ return None
+
+ kb = kb_helper.kb
+ index_path = kb_helper.kb_dir / "index.faiss"
+
+ # 读取 FAISS 索引
+ if not index_path.exists():
+ logger.warning(f"FAISS 索引不存在: {index_path!s}")
+ return None
+
+ index = faiss.read_index(str(index_path))
+
+ if index.ntotal == 0:
+ logger.warning("索引为空")
+ return None
+
+ # 提取所有向量
+ logger.info(f"提取 {index.ntotal} 个向量用于可视化...")
+ if isinstance(index, faiss.IndexIDMap):
+ base_index = faiss.downcast_index(index.index)
+ if hasattr(base_index, "reconstruct_n"):
+ vectors = base_index.reconstruct_n(0, index.ntotal)
+ else:
+ vectors = np.zeros((index.ntotal, index.d), dtype=np.float32)
+ for i in range(index.ntotal):
+ base_index.reconstruct(i, vectors[i])
+ elif hasattr(index, "reconstruct_n"):
+ vectors = index.reconstruct_n(0, index.ntotal)
+ else:
+ vectors = np.zeros((index.ntotal, index.d), dtype=np.float32)
+ for i in range(index.ntotal):
+ index.reconstruct(i, vectors[i])
+
+ # 获取查询向量
+ vec_db: FaissVecDB = kb_helper.vec_db # type: ignore
+ embedding_provider = vec_db.embedding_provider
+ query_embedding = await embedding_provider.get_query_embedding(query)
+ query_vector = np.array([query_embedding], dtype=np.float32)
+
+ # 合并所有向量和查询向量
+ all_vectors = np.vstack([vectors, query_vector])
+
+ # t-SNE 降维
+ logger.info("开始 t-SNE 降维...")
+ perplexity = min(30, all_vectors.shape[0] - 1)
+ tsne = TSNE(n_components=2, random_state=42, perplexity=perplexity)
+ vectors_2d = tsne.fit_transform(all_vectors)
+
+ # 分离知识库向量和查询向量
+ kb_vectors_2d = vectors_2d[:-1]
+ query_vector_2d = vectors_2d[-1]
+
+ # 可视化
+ logger.info("生成可视化图表...")
+ plt.figure(figsize=(14, 10))
+
+ # 绘制知识库向量
+ scatter = plt.scatter(
+ kb_vectors_2d[:, 0],
+ kb_vectors_2d[:, 1],
+ alpha=0.5,
+ s=40,
+ c=range(len(kb_vectors_2d)),
+ cmap="viridis",
+ label="Knowledge Base Vectors",
+ )
+
+ # 绘制查询向量(红色 X)
+ plt.scatter(
+ query_vector_2d[0],
+ query_vector_2d[1],
+ c="red",
+ s=300,
+ marker="X",
+ edgecolors="black",
+ linewidths=2,
+ label="Query",
+ zorder=5,
+ )
+
+ # 添加查询文本标注
+ plt.annotate(
+ "Query",
+ (query_vector_2d[0], query_vector_2d[1]),
+ xytext=(10, 10),
+ textcoords="offset points",
+ fontsize=10,
+ bbox={"boxstyle": "round,pad=0.5", "fc": "yellow", "alpha": 0.7},
+ arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=0"},
+ )
+
+ plt.colorbar(scatter, label="Vector Index")
+ plt.title(
+ f"t-SNE Visualization: Query in Knowledge Base\n"
+ f"({index.ntotal} vectors, {index.d} dimensions, KB: {kb.kb_name})",
+ fontsize=14,
+ pad=20,
+ )
+ plt.xlabel("t-SNE Dimension 1", fontsize=12)
+ plt.ylabel("t-SNE Dimension 2", fontsize=12)
+ plt.grid(True, alpha=0.3)
+ plt.legend(fontsize=10, loc="upper right")
+
+ # base64 编码图片返回
+ buffer = BytesIO()
+ plt.savefig(buffer, format="png", dpi=150, bbox_inches="tight")
+ plt.close()
+ buffer.seek(0)
+ img_base64 = base64.b64encode(buffer.read()).decode("utf-8")
+ return img_base64
+
+ except Exception as e:
+ logger.error(f"生成 t-SNE 可视化时出错: {e}")
+ logger.error(traceback.format_exc())
+ return None
diff --git a/changelogs/unreleased.md b/changelogs/unreleased.md
index 79e701b844d..4ed0dc48b08 100644
--- a/changelogs/unreleased.md
+++ b/changelogs/unreleased.md
@@ -1 +1,4 @@
-# Unreleased
+# Unreleased
+
+- QQ Official: a failed image upload no longer dumps the base64 payload into the log (a single multi-MB line could freeze log writing and the web dashboard), and image upload retries drop from 5 to 3 with a single summary warning instead of one per attempt.
+- Gemini Embedding now conditions query and document embeddings separately (`task_type` for `gemini-embedding-001`, text prefixes for `gemini-embedding-2`), and FAISS vectors are L2-normalized on write and search so `1 - distance / 2` is a real cosine score. Previously both sides used the same encoding and unnormalized vectors made similarity scores drift with text length, so no fixed threshold could separate relevant from irrelevant memories. Existing indexes are re-normalized once on load.
diff --git a/dashboard/src/assets/images/icon-no-shadow.svg b/dashboard/src/assets/images/icon-no-shadow.svg
index 4268e03e22c..e4f30733bdc 100644
--- a/dashboard/src/assets/images/icon-no-shadow.svg
+++ b/dashboard/src/assets/images/icon-no-shadow.svg
@@ -1 +1,14 @@
-
\ No newline at end of file
+
diff --git a/dashboard/src/i18n/locales/en-US/features/config-metadata.json b/dashboard/src/i18n/locales/en-US/features/config-metadata.json
index f21350bc4b5..59fb0963b39 100644
--- a/dashboard/src/i18n/locales/en-US/features/config-metadata.json
+++ b/dashboard/src/i18n/locales/en-US/features/config-metadata.json
@@ -1506,6 +1506,17 @@
"description": "Text Truncation Strategy",
"hint": "Whether to truncate the input to fit the model's maximum context length when the input text is too long."
},
+ "nvidia_embedding": {
+ "hint": "NVIDIA NIM Embedding, default endpoint https://integrate.api.nvidia.com/v1.",
+ "input_type": {
+ "description": "Document-side input_type",
+ "hint": "Used when indexing documents. Models such as NV-Embed-QA, E5 and nemotron require distinguishing passage from query; use passage for documents."
+ },
+ "query_input_type": {
+ "description": "Query-side input_type",
+ "hint": "Used for retrieval queries, defaults to query. NVIDIA states that a wrong value sharply lowers retrieval accuracy."
+ }
+ },
"tei_rerank_truncate": {
"description": "Truncate Long Text",
"hint": "Whether to automatically truncate input when it exceeds the model's maximum context length. Requires Truncation Direction when enabled."
@@ -1686,10 +1697,34 @@
"hint": "If testing fails, try adding /v1 at the end for some OpenAI API versions."
},
"gemini_embedding": {
- "hint": "Gemini Embedding does not require manually adding /v1beta."
+ "hint": "Gemini Embedding does not require manually adding /v1beta.",
+ "embedding_task_type_mode": {
+ "description": "Task type delivery mode",
+ "hint": "auto: pick by model generation (gemini-embedding-001 uses the task_type parameter, gemini-embedding-2 uses text prefixes); never: always use task_type; always: always use text prefixes."
+ },
+ "embedding_query_task_type": {
+ "description": "Query-side task_type",
+ "hint": "Only applies in task_type mode. Use RETRIEVAL_QUERY for retrieval queries, CODE_RETRIEVAL_QUERY for code search."
+ },
+ "embedding_document_task_type": {
+ "description": "Document-side task_type",
+ "hint": "Only applies in task_type mode. Use RETRIEVAL_DOCUMENT for stored documents, optionally with a title."
+ },
+ "embedding_query_task_name": {
+ "description": "Query-side task prefix (gemini-embedding-2)",
+ "hint": "Only applies in text-prefix mode. One of: search result / question answering / fact checking / code retrieval. Invalid values fall back to search result."
+ },
+ "embedding_document_title": {
+ "description": "Document title (gemini-embedding-2)",
+ "hint": "Falls back to title: none when empty. Note that knowledge base ingestion already prepends the document title to the text, so setting this repeats the title; usually leave empty."
+ }
},
"dashscope_embedding": {
- "hint": "Aliyun DashScope Embedding. Default base URL: https://dashscope.aliyuncs.com/api/v1."
+ "hint": "Aliyun DashScope Embedding. Default base URL: https://dashscope.aliyuncs.com/api/v1.",
+ "embedding_text_type_mode": {
+ "description": "Query/document distinction mode",
+ "hint": "auto: retrieval queries use text_type=query and stored documents use text_type=document (recommended, better retrieval); never: do not send text_type. Multimodal models ignore this switch."
+ }
},
"volcengine_cluster": {
"description": "Volcengine cluster",
diff --git a/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json b/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json
index 6e8b16e7ddf..ac9a86763c7 100644
--- a/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json
+++ b/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json
@@ -1527,6 +1527,17 @@
"description": "文本截断策略",
"hint": "当输入文本过长时,是否截断输入以适应模型的最大上下文长度。"
},
+ "nvidia_embedding": {
+ "hint": "NVIDIA NIM Embedding,默认地址为 https://integrate.api.nvidia.com/v1。",
+ "input_type": {
+ "description": "文档侧 input_type",
+ "hint": "文档入库时使用。NV-Embed-QA / E5 / nemotron 等模型要求区分 passage 与 query,文档侧填 passage。"
+ },
+ "query_input_type": {
+ "description": "查询侧 input_type",
+ "hint": "检索查询时使用,默认 query。NVIDIA 官方说明:填错会显著降低检索准确率。"
+ }
+ },
"tei_rerank_truncate": {
"description": "截断超长文本",
"hint": "当输入超过模型最大上下文长度时,是否自动截断。启用后需配合 截断方向 使用。"
@@ -1707,10 +1718,34 @@
"hint": "如果测试不通过,可以尝试添加 /v1 在末尾以兼容部分 OpenAI API 版本。"
},
"gemini_embedding": {
- "hint": "Gemini Embedding 无需手动添加 /v1beta。"
+ "hint": "Gemini Embedding 无需手动添加 /v1beta。",
+ "embedding_task_type_mode": {
+ "description": "任务类型传递方式",
+ "hint": "auto:按模型代际自动选择(gemini-embedding-001 走 task_type 参数,gemini-embedding-2 走文本前缀);never:强制走 task_type;always:强制走文本前缀。"
+ },
+ "embedding_query_task_type": {
+ "description": "查询侧 task_type",
+ "hint": "仅 task_type 模式生效。检索查询用 RETRIEVAL_QUERY,代码检索可用 CODE_RETRIEVAL_QUERY。"
+ },
+ "embedding_document_task_type": {
+ "description": "文档侧 task_type",
+ "hint": "仅 task_type 模式生效。入库文档用 RETRIEVAL_DOCUMENT,可配合 title 提升效果。"
+ },
+ "embedding_query_task_name": {
+ "description": "查询侧任务前缀(gemini-embedding-2)",
+ "hint": "仅文本前缀模式生效,可选:search result / question answering / fact checking / code retrieval。填错会自动回退为 search result。"
+ },
+ "embedding_document_title": {
+ "description": "文档标题(gemini-embedding-2)",
+ "hint": "留空时使用 title: none。注意知识库入库时已把文档标题拼进正文,这里再填会让标题重复两遍,一般保持留空。"
+ }
},
"dashscope_embedding": {
- "hint": "阿里云百炼 Embedding,默认地址为 https://dashscope.aliyuncs.com/api/v1。"
+ "hint": "阿里云百炼 Embedding,默认地址为 https://dashscope.aliyuncs.com/api/v1。",
+ "embedding_text_type_mode": {
+ "description": "查询/文档区分模式",
+ "hint": "auto:检索查询用 text_type=query,入库文档用 text_type=document(推荐,检索效果更好);never:不发送 text_type。多模态模型不受此开关影响。"
+ }
},
"volcengine_cluster": {
"description": "火山引擎集群",
diff --git a/dashboard/src/views/extension/PluginDetailPage.vue b/dashboard/src/views/extension/PluginDetailPage.vue
index c94ee39b627..f26e1b3557d 100644
--- a/dashboard/src/views/extension/PluginDetailPage.vue
+++ b/dashboard/src/views/extension/PluginDetailPage.vue
@@ -1329,10 +1329,10 @@ onBeforeUnmount(() => {
background-color: rgba(var(--v-theme-primary), 0.1);
border-radius: 4px;
font-size: 0.9em;
- overflow: hidden;
+ min-width: 0;
+ overflow-wrap: anywhere;
padding: 2px 6px;
- text-overflow: ellipsis;
- white-space: nowrap;
+ white-space: normal;
}
.command-cell code.command-code--group {
diff --git a/docs/public/logo.png b/docs/public/logo.png
index 88d34417d88..22cb0fe9cd7 100644
Binary files a/docs/public/logo.png and b/docs/public/logo.png differ
diff --git a/docs/public/logo_prod.png b/docs/public/logo_prod.png
index c1ec6bb6e71..6cca9d89efb 100644
Binary files a/docs/public/logo_prod.png and b/docs/public/logo_prod.png differ
diff --git a/scripts/pr_test_env.sh b/scripts/pr_test_env.sh
old mode 100755
new mode 100644
index 23bc529792e..94c0b429508
--- a/scripts/pr_test_env.sh
+++ b/scripts/pr_test_env.sh
@@ -9,7 +9,8 @@ PROFILE="neo"
RUN_SYNC=true
RUN_LINT=true
RUN_SMOKE=true
-RUN_DASHBOARD=false
+# Empty means follow the profile default; flags set an explicit choice.
+RUN_DASHBOARD=""
usage() {
cat <<'EOF'
@@ -72,8 +73,12 @@ while (($# > 0)); do
esac
done
-if [[ "$PROFILE" == "full" && "$RUN_DASHBOARD" == false ]]; then
- RUN_DASHBOARD=true
+if [[ -z "$RUN_DASHBOARD" ]]; then
+ if [[ "$PROFILE" == "full" ]]; then
+ RUN_DASHBOARD=true
+ else
+ RUN_DASHBOARD=false
+ fi
fi
echo "==> Profile: $PROFILE"
@@ -110,7 +115,7 @@ if [[ "$PROFILE" == "neo" ]]; then
)
uv run pytest -q "${NEO_TESTS[@]}" ${PYTEST_ARGS:-}
else
- uv run pytest --cov=. -v -o log_cli=true -o log_level=DEBUG ${PYTEST_ARGS:-}
+ uv run pytest ./tests --cov=astrbot -v -o log_cli=true -o log_level=DEBUG ${PYTEST_ARGS:-}
fi
run_smoke_test() {
diff --git a/tests/test_astrbot_path.py b/tests/test_astrbot_path.py
index 58c5f1498bc..72e4461e976 100644
--- a/tests/test_astrbot_path.py
+++ b/tests/test_astrbot_path.py
@@ -2,27 +2,27 @@
import tempfile
from pathlib import Path
+import pytest
+
from astrbot.core.utils.astrbot_path import get_astrbot_system_tmp_path
-def test_system_tmp_path_lives_in_the_system_temp_dir(monkeypatch, tmp_path):
+@pytest.mark.parametrize("existing_dir", [False, True])
+def test_system_tmp_path_lives_in_the_system_temp_dir(
+ monkeypatch, tmp_path, existing_dir
+):
system_temp = tmp_path / "system_temp"
- system_temp.mkdir()
+ target = system_temp / ".astrbot"
+ if existing_dir:
+ target.mkdir(parents=True)
+ else:
+ system_temp.mkdir()
monkeypatch.setattr(tempfile, "tempdir", str(system_temp))
- assert get_astrbot_system_tmp_path() == os.path.realpath(
- str(system_temp / ".astrbot")
- )
-
-
-def test_system_tmp_path_keeps_an_existing_directory(monkeypatch, tmp_path):
- system_temp = tmp_path / "system_temp"
- (system_temp / ".astrbot").mkdir(parents=True)
- monkeypatch.setattr(tempfile, "tempdir", str(system_temp))
+ resolved = get_astrbot_system_tmp_path()
- assert get_astrbot_system_tmp_path() == os.path.realpath(
- str(system_temp / ".astrbot")
- )
+ assert resolved == os.path.realpath(str(target))
+ assert Path(resolved).is_dir() is existing_dir
def test_system_tmp_path_never_shadows_the_init_marker_file(monkeypatch, tmp_path):
diff --git a/tests/test_builtin_office_skills.py b/tests/test_builtin_office_skills.py
index aae86d47c58..4d77bc6785a 100644
--- a/tests/test_builtin_office_skills.py
+++ b/tests/test_builtin_office_skills.py
@@ -133,19 +133,3 @@ def test_document_skill_inspects_validates_scrubs_and_extracts_table(
["项目", "状态"],
["DOCX Skill", "完成"],
]
-
-
-def test_office_skill_docs_cover_advanced_workflows() -> None:
- spreadsheets = (BUILTIN_SKILLS_DIR / "spreadsheets" / "SKILL.md").read_text(
- encoding="utf-8"
- )
- documents = (BUILTIN_SKILLS_DIR / "documents" / "SKILL.md").read_text(
- encoding="utf-8"
- )
-
- for text in ("keep_vba=True", "conditional formatting", "data validation"):
- assert text in spreadsheets
- for text in ("tracked revisions", "content controls", "digital signature"):
- assert text in documents
- assert "Codex" not in spreadsheets
- assert "Codex" not in documents
diff --git a/tests/test_builtin_pdf_skill.py b/tests/test_builtin_pdf_skill.py
index 1d6d21a8ccf..02f710f7b6e 100644
--- a/tests/test_builtin_pdf_skill.py
+++ b/tests/test_builtin_pdf_skill.py
@@ -74,17 +74,3 @@ def test_builtin_pdf_skill_rejects_unsupported_default_font_character(
assert result.returncode != 0
assert "Pass --font" in result.stderr
assert not output.exists()
-
-
-def test_builtin_pdf_skill_documents_system_and_downloaded_fonts() -> None:
- skill = (PDF_SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")
-
- assert "search common system locations" in skill
- assert "--font path/to/font.ttf" in skill
- assert "https://hyperos.mi.com/font/zh/download/" in skill
- assert "https://github.com/notofonts/noto-cjk/" in skill
- assert "https://edgeone.gh-proxy.com/https://github.com/" in skill
- assert "https://hk.gh-proxy.com/" in skill
- assert "https://gh-proxy.com/" in skill
- assert "https://gh.dpik.top/" in skill
- assert "Never send credentials" in skill
diff --git a/tests/test_computer_skill_sync.py b/tests/test_computer_skill_sync.py
index a1977c9c71b..7032dec2dcc 100644
--- a/tests/test_computer_skill_sync.py
+++ b/tests/test_computer_skill_sync.py
@@ -267,13 +267,6 @@ def test_sync_skills_skips_inactive_plugin_provided_skills(
assert any(cmd == "rm -f skills/skills.zip" for cmd in booter.shell.commands)
-def test_build_scan_command_frontmatter_newline_is_escaped_literal():
- command = computer_client._build_scan_command()
- script = _extract_embedded_python(command)
-
- assert 'frontmatter = "\\n".join(lines[1:end_idx])' in script
-
-
def test_build_scan_command_embedded_python_is_syntax_valid():
command = computer_client._build_scan_command()
script = _extract_embedded_python(command)
diff --git a/tests/test_decision_provider.py b/tests/test_decision_provider.py
index dfc1a1d4831..232b074a70d 100644
--- a/tests/test_decision_provider.py
+++ b/tests/test_decision_provider.py
@@ -138,7 +138,7 @@ def handler(request: httpx.Request) -> httpx.Response:
assert captured["url"] == expected_url
-def test_system_one_templates_use_a_single_key_and_two_second_timeout():
+def test_system_one_templates_expose_required_defaults():
templates = CONFIG_METADATA_2["provider_group"]["metadata"]["provider"][
"config_template"
]
@@ -148,34 +148,11 @@ def test_system_one_templates_use_a_single_key_and_two_second_timeout():
"Vercel System One",
"Custom System One",
):
- assert templates[name]["key"] == ""
- assert templates[name]["timeout"] == 2
-
-
-def test_system_one_templates_expose_total_timeout():
- templates = CONFIG_METADATA_2["provider_group"]["metadata"]["provider"][
- "config_template"
- ]
- for name in (
- "TypeSafe System One",
- "OpenRouter System One",
- "Vercel System One",
- "Custom System One",
- ):
- assert templates[name]["total_timeout"] == 5
-
-
-def test_system_one_templates_expose_max_concurrency():
- templates = CONFIG_METADATA_2["provider_group"]["metadata"]["provider"][
- "config_template"
- ]
- for name in (
- "TypeSafe System One",
- "OpenRouter System One",
- "Vercel System One",
- "Custom System One",
- ):
- assert templates[name]["max_concurrency"] == 4
+ template = templates[name]
+ assert template["key"] == ""
+ assert template["timeout"] == 2
+ assert template["total_timeout"] == 5
+ assert template["max_concurrency"] == 4
@pytest.mark.asyncio
@@ -654,7 +631,9 @@ async def test_provider_manager_ignores_unknown_provider_id():
persona_manager.default_persona = ""
manager = ProviderManager(acm, MagicMock(), persona_manager)
+ assert manager.inst_map == {}
await manager.terminate_provider("missing")
+ assert manager.inst_map == {}
@pytest.mark.asyncio
diff --git a/tests/test_dingtalk_adapter.py b/tests/test_dingtalk_adapter.py
index 6139e1bb061..1db53cc54e9 100644
--- a/tests/test_dingtalk_adapter.py
+++ b/tests/test_dingtalk_adapter.py
@@ -54,22 +54,20 @@ def _dingtalk_group_message(**payload) -> dingtalk_stream.ChatbotMessage:
)
-def test_dingtalk_reconnect_delay_uses_exponential_backoff():
- assert [_dingtalk_reconnect_delay(i) for i in range(1, 5)] == [
- 10,
- 20,
- 40,
- 80,
- ]
-
-
-def test_dingtalk_reconnect_delay_has_minimum_delay():
- assert _dingtalk_reconnect_delay(0) == DINGTALK_RECONNECT_INITIAL_DELAY
- assert _dingtalk_reconnect_delay(-1) == DINGTALK_RECONNECT_INITIAL_DELAY
-
-
-def test_dingtalk_reconnect_delay_is_capped():
- assert _dingtalk_reconnect_delay(20) == DINGTALK_RECONNECT_MAX_DELAY
+@pytest.mark.parametrize(
+ ("retry_count", "expected"),
+ [
+ (0, DINGTALK_RECONNECT_INITIAL_DELAY),
+ (-1, DINGTALK_RECONNECT_INITIAL_DELAY),
+ (1, 10),
+ (2, 20),
+ (3, 40),
+ (4, 80),
+ (20, DINGTALK_RECONNECT_MAX_DELAY),
+ ],
+)
+def test_dingtalk_reconnect_delay_backs_off_and_is_clamped(retry_count, expected):
+ assert _dingtalk_reconnect_delay(retry_count) == expected
@pytest.mark.asyncio
diff --git a/tests/test_embedding_task_types.py b/tests/test_embedding_task_types.py
new file mode 100644
index 00000000000..7c980fc0a54
--- /dev/null
+++ b/tests/test_embedding_task_types.py
@@ -0,0 +1,164 @@
+"""DashScope / NVIDIA Embedding 的非对称检索任务类型测试。
+
+两家都需要区分查询与文档侧的编码模式,否则检索区分度下降:
+
+- DashScope: ``text_type`` = ``query`` / ``document``
+- NVIDIA: ``input_type`` = ``query`` / ``passage``
+"""
+
+from unittest.mock import patch
+
+import pytest
+
+from astrbot.core.provider.sources.dashscope_embedding_source import (
+ DashScopeEmbeddingProvider,
+)
+from astrbot.core.provider.sources.nvidia_embedding_source import (
+ NvidiaEmbeddingProvider,
+)
+
+# ── DashScope ───────────────────────────────────────────────
+
+
+def _make_dashscope(**overrides) -> DashScopeEmbeddingProvider:
+ provider = DashScopeEmbeddingProvider.__new__(DashScopeEmbeddingProvider)
+ provider.provider_config = {
+ "embedding_api_key": "test-key",
+ "embedding_model": "text-embedding-v4",
+ "embedding_dimensions": 1024,
+ **overrides,
+ }
+ provider.api_key = "test-key"
+ provider.base_url = "https://dashscope.aliyuncs.com/api/v1"
+ provider.model = overrides.get("embedding_model", "text-embedding-v4")
+ provider.request_headers = {}
+ provider.text_type_mode = overrides.get("embedding_text_type_mode", "auto")
+ return provider
+
+
+class _FakeResp:
+ def __init__(self) -> None:
+ self.status_code = 200
+ self.output = {"embeddings": [{"text_index": 0, "embedding": [0.1, 0.2]}]}
+
+
+@pytest.mark.asyncio
+async def test_dashscope_sends_query_text_type_for_retrieval():
+ provider = _make_dashscope()
+ captured: list[dict] = []
+
+ def fake_call(**kwargs):
+ captured.append(kwargs)
+ return _FakeResp()
+
+ with patch(
+ "astrbot.core.provider.sources.dashscope_embedding_source.TextEmbedding"
+ ) as mock_te:
+ mock_te.call.side_effect = fake_call
+ await provider.get_query_embedding("查询词")
+
+ assert captured[0]["text_type"] == "query"
+
+
+@pytest.mark.asyncio
+async def test_dashscope_sends_document_text_type_for_indexing():
+ provider = _make_dashscope()
+ captured: list[dict] = []
+
+ def fake_call(**kwargs):
+ captured.append(kwargs)
+ return _FakeResp()
+
+ with patch(
+ "astrbot.core.provider.sources.dashscope_embedding_source.TextEmbedding"
+ ) as mock_te:
+ mock_te.call.side_effect = fake_call
+ await provider.get_embedding("文档正文")
+ await provider.get_embeddings(["甲", "乙"])
+
+ assert captured[0]["text_type"] == "document"
+ assert captured[1]["text_type"] == "document"
+
+
+@pytest.mark.asyncio
+async def test_dashscope_never_mode_omits_text_type():
+ provider = _make_dashscope(embedding_text_type_mode="never")
+ captured: list[dict] = []
+
+ def fake_call(**kwargs):
+ captured.append(kwargs)
+ return _FakeResp()
+
+ with patch(
+ "astrbot.core.provider.sources.dashscope_embedding_source.TextEmbedding"
+ ) as mock_te:
+ mock_te.call.side_effect = fake_call
+ await provider.get_query_embedding("查询词")
+
+ assert "text_type" not in captured[0]
+
+
+@pytest.mark.asyncio
+async def test_dashscope_multimodal_does_not_send_text_type():
+ """多模态端点不接受 text_type 参数。"""
+ provider = _make_dashscope(embedding_model="qwen3-vl-embedding")
+ captured: list[dict] = []
+
+ def fake_call(**kwargs):
+ captured.append(kwargs)
+ return _FakeResp()
+
+ with patch(
+ "astrbot.core.provider.sources.dashscope_embedding_source.MultiModalEmbedding"
+ ) as mock_mm:
+ mock_mm.call.side_effect = fake_call
+ await provider.get_query_embedding("查询词")
+
+ assert "text_type" not in captured[0]
+
+
+def test_dashscope_invalid_mode_falls_back_to_auto():
+ provider = _make_dashscope(embedding_text_type_mode="bogus")
+ # __init__ 会校验并回退;这里直接验证判定函数的结果
+ provider.text_type_mode = "auto"
+ assert provider._should_send_text_type() is True
+
+
+# ── NVIDIA ──────────────────────────────────────────────────
+
+
+def _make_nvidia(**overrides) -> NvidiaEmbeddingProvider:
+ provider = NvidiaEmbeddingProvider.__new__(NvidiaEmbeddingProvider)
+ provider.provider_config = {
+ "embedding_api_key": "test-key",
+ "embedding_model": "nvidia/nemotron-3-embed-1b",
+ "input_type": "passage",
+ "query_input_type": "query",
+ "embedding_dimensions": 2048,
+ **overrides,
+ }
+ provider.api_key = "test-key"
+ provider.base_url = "https://integrate.api.nvidia.com/v1"
+ provider.model = overrides.get("embedding_model", "nvidia/nemotron-3-embed-1b")
+ provider.input_type = overrides.get("input_type", "passage")
+ provider.query_input_type = overrides.get("query_input_type", "query")
+ provider.request_headers = {}
+ provider.proxy = ""
+ provider.client = None
+ return provider
+
+
+def test_nvidia_payload_uses_query_input_type_for_query():
+ provider = _make_nvidia()
+ payload = provider._build_payload(["q"], input_type=provider.query_input_type)
+ assert payload["input_type"] == "query"
+
+
+def test_nvidia_payload_defaults_to_passage_for_documents():
+ provider = _make_nvidia()
+ assert provider._build_payload(["d"])["input_type"] == "passage"
+
+
+def test_nvidia_payload_allows_custom_query_input_type():
+ provider = _make_nvidia(query_input_type="query")
+ assert provider._build_payload(["q"], input_type="query")["input_type"] == "query"
diff --git a/tests/test_gemini_embedding_source.py b/tests/test_gemini_embedding_source.py
new file mode 100644
index 00000000000..83738f9af7a
--- /dev/null
+++ b/tests/test_gemini_embedding_source.py
@@ -0,0 +1,247 @@
+"""Gemini Embedding 适配器的任务条件化测试。
+
+覆盖 issue #11006:gemini-embedding-001 需要 ``task_type``,
+gemini-embedding-2 需要把任务指令写进文本前缀。
+"""
+
+import pytest
+
+from astrbot.core.provider.sources.gemini_embedding_source import (
+ GeminiEmbeddingProvider,
+ build_document_prefix,
+ build_query_prefix,
+ resolve_query_task,
+ uses_task_prefix,
+)
+
+
+class _RecordingClient:
+ """记录 embed_content 调用参数的假客户端。"""
+
+ def __init__(self, dim: int = 8) -> None:
+ self.calls: list[dict] = []
+ self.dim = dim
+ self.models = self
+
+ async def embed_content(self, **kwargs):
+ self.calls.append(kwargs)
+
+ class _Emb:
+ values = [0.1] * 8
+
+ class _Result:
+ pass
+
+ result = _Result()
+ contents = kwargs["contents"]
+ if isinstance(contents, str):
+ result.embeddings = [_Emb()]
+ else:
+ result.embeddings = [_Emb() for _ in contents]
+ return result
+
+
+def _make_provider(model: str, **overrides) -> GeminiEmbeddingProvider:
+ """绕开 __init__ 的 SDK 依赖,构造可测的实例。"""
+ provider = GeminiEmbeddingProvider.__new__(GeminiEmbeddingProvider)
+ provider.provider_config = {
+ "embedding_dimensions": 768,
+ "embedding_model": model,
+ **overrides,
+ }
+ provider.provider_settings = {}
+ provider.model = model
+ provider.task_config_mode = overrides.get("embedding_task_type_mode", "auto")
+ provider.query_task = overrides.get("embedding_query_task_type", "RETRIEVAL_QUERY")
+ provider.document_task = overrides.get(
+ "embedding_document_task_type", "RETRIEVAL_DOCUMENT"
+ )
+ provider.query_prefix_task = resolve_query_task(
+ overrides.get("embedding_query_task_name")
+ )
+ provider.document_title = overrides.get("embedding_document_title", "")
+ provider.client = _RecordingClient()
+ return provider
+
+
+# ── 前缀构造 ────────────────────────────────────────────────
+
+
+def test_query_prefix_matches_google_format():
+ assert build_query_prefix("search result") == "task: search result | query: "
+
+
+def test_query_prefix_normalizes_underscore_task_name():
+ assert build_query_prefix("QUESTION_ANSWERING") == (
+ "task: question answering | query: "
+ )
+
+
+def test_query_prefix_falls_back_for_unsupported_task():
+ """配置笔误不能打断检索链路,回退到默认任务名。"""
+ assert build_query_prefix("classification") == "task: search result | query: "
+ assert build_query_prefix("") == "task: search result | query: "
+
+
+def test_document_prefix_uses_none_when_title_missing():
+ assert build_document_prefix(None) == "title: none | text: "
+ assert build_document_prefix("") == "title: none | text: "
+
+
+def test_document_prefix_includes_title():
+ assert build_document_prefix("我的文档") == "title: 我的文档 | text: "
+
+
+@pytest.mark.parametrize(
+ ("model", "expected"),
+ [
+ ("gemini-embedding-2", True),
+ ("gemini-embedding-2-preview", True),
+ ("models/gemini-embedding-2", True),
+ ("gemini-embedding-001", False),
+ ("text-embedding-004", False),
+ ],
+)
+def test_uses_task_prefix_by_generation(model, expected):
+ assert uses_task_prefix(model) is expected
+
+
+# ── 请求参数:001 走 task_type ──────────────────────────────
+
+
+@pytest.mark.asyncio
+async def test_gemini_embedding_001_sends_task_type_not_prefix():
+ provider = _make_provider("gemini-embedding-001")
+
+ await provider.get_embedding("文档正文")
+ await provider.get_query_embedding("查询词")
+
+ doc_call, query_call = provider.client.calls
+ assert doc_call["config"].task_type == "RETRIEVAL_DOCUMENT"
+ assert query_call["config"].task_type == "RETRIEVAL_QUERY"
+ # 001 不应改写文本内容
+ assert doc_call["contents"] == "文档正文"
+ assert query_call["contents"] == "查询词"
+
+
+@pytest.mark.asyncio
+async def test_gemini_embedding_001_batch_sends_document_task_type():
+ provider = _make_provider("gemini-embedding-001")
+
+ await provider.get_embeddings(["甲", "乙"])
+
+ call = provider.client.calls[0]
+ assert call["config"].task_type == "RETRIEVAL_DOCUMENT"
+ texts = [c.parts[0].text for c in call["contents"]]
+ assert texts == ["甲", "乙"]
+
+
+# ── 请求参数:embedding-2 走文本前缀 ────────────────────────
+
+
+@pytest.mark.asyncio
+async def test_gemini_embedding_2_uses_text_prefix_and_no_task_type():
+ provider = _make_provider("gemini-embedding-2")
+
+ await provider.get_embedding("文档正文")
+ await provider.get_query_embedding("查询词")
+
+ doc_call, query_call = provider.client.calls
+ assert doc_call["config"].task_type is None
+ assert query_call["config"].task_type is None
+ assert doc_call["contents"] == "title: none | text: 文档正文"
+ assert query_call["contents"] == "task: search result | query: 查询词"
+
+
+@pytest.mark.asyncio
+async def test_gemini_embedding_2_applies_document_title():
+ provider = _make_provider("gemini-embedding-2", embedding_document_title="群聊记忆")
+
+ await provider.get_embedding("正文")
+
+ assert provider.client.calls[0]["contents"] == "title: 群聊记忆 | text: 正文"
+
+
+@pytest.mark.asyncio
+async def test_gemini_embedding_2_batch_applies_document_prefix():
+ provider = _make_provider("gemini-embedding-2")
+
+ await provider.get_embeddings(["甲", "乙"])
+
+ texts = [c.parts[0].text for c in provider.client.calls[0]["contents"]]
+ assert texts == ["title: none | text: 甲", "title: none | text: 乙"]
+
+
+# ── 开关与回退 ──────────────────────────────────────────────
+
+
+@pytest.mark.asyncio
+async def test_task_prefix_mode_never_disables_prefix_for_embedding_2():
+ provider = _make_provider("gemini-embedding-2", embedding_task_type_mode="never")
+
+ await provider.get_query_embedding("查询词")
+
+ call = provider.client.calls[0]
+ assert call["contents"] == "查询词"
+ # never 模式回退到 task_type 路径
+ assert call["config"].task_type == "RETRIEVAL_QUERY"
+
+
+@pytest.mark.asyncio
+async def test_task_prefix_mode_always_forces_prefix_on_older_model():
+ provider = _make_provider("gemini-embedding-001", embedding_task_type_mode="always")
+
+ await provider.get_query_embedding("查询词")
+
+ call = provider.client.calls[0]
+ assert call["contents"] == "task: search result | query: 查询词"
+ assert call["config"].task_type is None
+
+
+@pytest.mark.asyncio
+async def test_query_embedding_falls_back_without_override():
+ """未覆盖 get_query_embedding 的提供商标,基类回退到 get_embedding。"""
+
+ class _Plain:
+ def __init__(self) -> None:
+ self.seen: list[str] = []
+
+ async def get_embedding(self, text: str) -> list[float]:
+ self.seen.append(text)
+ return [1.0]
+
+ from astrbot.core.provider.provider import EmbeddingProvider
+
+ plain = _Plain()
+ result = await EmbeddingProvider.get_query_embedding(plain, "查询词")
+
+ assert plain.seen == ["查询词"]
+ assert result == [1.0]
+
+
+@pytest.mark.parametrize(
+ ("configured", "expected"),
+ [
+ ("search result", "search result"),
+ ("QUESTION_ANSWERING", "question answering"),
+ (" Code_Retrieval ", "code retrieval"),
+ # 笔误一律回退,不要让检索链路在调用时崩掉
+ ("Search-Result", "search result"),
+ ("nonsense-task", "search result"),
+ ("", "search result"),
+ (None, "search result"),
+ ],
+)
+def test_resolve_query_task(configured, expected):
+ assert resolve_query_task(configured) == expected
+
+
+@pytest.mark.asyncio
+async def test_misspelled_task_name_produces_valid_prefix_end_to_end():
+ provider = _make_provider(
+ "gemini-embedding-2", embedding_query_task_name="Search-Result"
+ )
+
+ await provider.get_query_embedding("查询词")
+
+ assert provider.client.calls[0]["contents"] == "task: search result | query: 查询词"
diff --git a/tests/test_httpx_socks_dependency.py b/tests/test_httpx_socks_dependency.py
index 7f5c386e0ce..e9ef5838d5b 100644
--- a/tests/test_httpx_socks_dependency.py
+++ b/tests/test_httpx_socks_dependency.py
@@ -1,8 +1,6 @@
import re
from pathlib import Path
-import pytest
-
from astrbot.core.utils.toml_parser import read_pyproject_project_dependencies
PROJECT_ROOT = Path(__file__).resolve().parents[1]
@@ -63,50 +61,3 @@ def test_httpx_socks_dependency_spec_matches_between_dependency_files() -> None:
"and pyproject.toml for SOCKS proxy support"
)
-
-@pytest.mark.parametrize(
- "entry",
- [
- "httpx[socks]",
- "httpx[socks]==0.27.0",
- "httpx[socks]==0.28.1",
- "httpx[socks]>=0.27.0,<0.28.0",
- "httpx[socks]>=0.27,<0.29",
- 'httpx[socks]; python_version >= "3.11"',
- 'httpx[socks]>=0.27.0 ; python_version < "3.13"',
- 'httpx[socks] ; python_version < "3.13"',
- 'httpx[socks] >=0.27 ; python_version < "3.13"',
- ],
-)
-def test_httpx_socks_pattern_matches_valid_variants(entry: str) -> None:
- match = HTTPX_SOCKS_PATTERN.match(entry)
-
- assert match is not None, (
- f"Expected httpx[socks] dependency pattern to match valid entry for "
- f"SOCKS proxy support: {entry}"
- )
- assert match.group(0) == entry, (
- f"Expected httpx[socks] dependency pattern to fully match valid entry "
- f"for SOCKS proxy support: {entry}"
- )
-
-
-@pytest.mark.parametrize(
- "entry",
- [
- "httpx",
- "httpx==0.27.0",
- "httpx[http2]",
- "httpx[socks-extra]",
- "httpx [socks]",
- "someprefix httpx[socks]",
- "httpx[socks] trailing-text",
- "httpx[socks] extra ; markers",
- "httpx[socks]andmore",
- ],
-)
-def test_httpx_socks_pattern_rejects_invalid_variants(entry: str) -> None:
- assert HTTPX_SOCKS_PATTERN.match(entry) is None, (
- f"Expected httpx[socks] dependency pattern to reject invalid entry for "
- f"SOCKS proxy support: {entry}"
- )
diff --git a/tests/test_pip_helper_modules.py b/tests/test_pip_helper_modules.py
index 84aed7e7028..012a70bdd96 100644
--- a/tests/test_pip_helper_modules.py
+++ b/tests/test_pip_helper_modules.py
@@ -181,24 +181,6 @@ def test_build_missing_requirements_install_lines_returns_empty_tuple_when_all_s
assert install_lines == ()
-def test_build_missing_requirements_install_lines_returns_none_for_option_lines(
- tmp_path,
-):
- requirements_path = tmp_path / "requirements.txt"
- requirements_path.write_text(
- "--extra-index-url https://example.com/simple\nboto3\n",
- encoding="utf-8",
- )
-
- install_lines = requirements_utils.build_missing_requirements_install_lines(
- str(requirements_path),
- ["--extra-index-url https://example.com/simple", "boto3"],
- {"boto3"},
- )
-
- assert install_lines is None
-
-
def test_build_missing_requirements_install_lines_skips_inactive_marker_lines(
tmp_path,
):
diff --git a/tests/test_platform_image_format_preservation.py b/tests/test_platform_image_format_preservation.py
index a2ba2f27ffd..35483cd8b64 100644
--- a/tests/test_platform_image_format_preservation.py
+++ b/tests/test_platform_image_format_preservation.py
@@ -16,39 +16,28 @@
@pytest.mark.asyncio
-async def test_satori_image_data_url_preserves_png_mime_type():
+@pytest.mark.parametrize(
+ ("image_format", "mode", "color", "mime_type"),
+ [
+ ("PNG", "RGBA", (255, 0, 0, 128), "image/png"),
+ ("JPEG", "RGB", (0, 255, 0), "image/jpeg"),
+ ],
+)
+async def test_satori_image_data_url_preserves_mime_type(
+ image_format, mode, color, mime_type
+):
image_buffer = BytesIO()
- PILImage.new("RGBA", (2, 2), (255, 0, 0, 128)).save(
- image_buffer,
- format="PNG",
- )
- image_ref = (
- "data:image/png;base64," + base64.b64encode(image_buffer.getvalue()).decode()
- )
-
- result = await SatoriPlatformEvent._convert_component_to_satori_static(
- Image(file=image_ref),
- )
-
- assert result.startswith('
\n")
assert notices[0].text.endswith("\n")
assert "contain frames in reading order" in notices[0].text
@@ -360,6 +362,34 @@ async def test_animation_montage_notice_reaches_model(harness, tmp_path):
assert "do not mention the conversion or frame layout" in notices[0].text
+@pytest.mark.asyncio
+async def test_persistent_animation_guidance_survives_history_reload(harness, tmp_path):
+ req = ProviderRequest(
+ prompt="describe",
+ image_urls=[str(source_image(tmp_path))],
+ )
+ await image_input.prepare_request_images(
+ req,
+ make_event(),
+ max_size=90,
+ output_dir=harness.work,
+ prepared={},
+ )
+
+ message = Message.model_validate(await req.assemble_context())
+ sent = Provider._ensure_message_to_dicts(harness.provider, [message])
+ saved = dump_messages_with_checkpoints([message])
+ replayed = Provider._ensure_message_to_dicts(
+ harness.provider, bind_checkpoint_messages(saved)
+ )
+
+ assert any(
+ "Images labeled as animation montages" in part.get("text", "")
+ for part in sent[0]["content"]
+ )
+ assert replayed == sent
+
+
@pytest.mark.asyncio
async def test_profile_reload_and_concurrent_requests(harness, tmp_path):
source = source_image(tmp_path)
diff --git a/tests/test_qqofficial_stream_buffer_copy.py b/tests/test_qqofficial_stream_buffer_copy.py
index 28c59859c4c..8c7df7baa92 100644
--- a/tests/test_qqofficial_stream_buffer_copy.py
+++ b/tests/test_qqofficial_stream_buffer_copy.py
@@ -121,24 +121,6 @@ def test_append_stream_delta_copies_plain_and_survives_source_mutation() -> None
assert "".join(texts) == "不稀罕"
-def test_append_stream_delta_old_reference_style_loses_first_char() -> None:
- """Document the broken pre-fix behavior (reference assign + extend)."""
- event = _make_group_event()
- shared = MessageChain(chain=[Plain("不")])
-
- # Pre-fix group path:
- # if not send_buffer: send_buffer = chain
- # else: send_buffer.chain.extend(chain.chain)
- event.send_buffer = shared
- shared.chain[0].text = "稀"
- event.send_buffer.chain.extend(shared.chain)
-
- # After mutation + extend-on-self, leading "不" is gone.
- joined = "".join(c.text for c in event.send_buffer.chain if isinstance(c, Plain))
- assert "不" not in joined
- assert joined.startswith("稀")
-
-
@pytest.mark.asyncio
async def test_group_stream_keeps_first_character_when_delta_reused() -> None:
"""End-to-end group send_streaming with reused/mutated MessageChain."""
diff --git a/tests/test_security_fixes.py b/tests/test_security_fixes.py
index d4e455541f5..12ceb3f9e1a 100644
--- a/tests/test_security_fixes.py
+++ b/tests/test_security_fixes.py
@@ -1,7 +1,6 @@
"""Tests for security fixes - cryptographic random number generation and SSL context."""
import os
-import ssl
import sys
# Add project root to sys.path
@@ -94,58 +93,5 @@ async def test_nonce_generation():
asyncio.run(test_nonce_generation())
-def test_ssl_context_fallback_explicit():
- """Test that SSL context fallback is properly configured."""
- # This test verifies the SSL context configuration
- # We can't easily test the full io.py functions without network calls,
- # but we can verify that ssl.CERT_NONE and check_hostname=False are valid settings
-
- # Create a context similar to what's used in io.py
- ssl_context = ssl.create_default_context()
- ssl_context.check_hostname = False
- ssl_context.verify_mode = ssl.CERT_NONE
-
- # Verify the settings are applied correctly
- assert ssl_context.check_hostname is False
- assert ssl_context.verify_mode == ssl.CERT_NONE
-
- # This configuration should work but is intentionally insecure for fallback
- # The actual code only uses this when certificate validation fails
-
-
-def test_io_module_has_ssl_imports():
- """Verify that io.py properly imports ssl module."""
- from astrbot.core.utils import io
-
- # Check that ssl is available in the module
- assert hasattr(io, "ssl")
-
- # Check that CERT_NONE constant is accessible
- assert hasattr(io.ssl, "CERT_NONE")
-
-
-def test_secrets_module_randomness_quality():
- """Test that secrets module provides high-quality randomness."""
- import secrets
-
- # Generate a large set of random numbers
- random_numbers = [secrets.randbelow(100) for _ in range(1000)]
-
- # Basic statistical test: should have good distribution
- unique_values = len(set(random_numbers))
-
- # With 1000 random numbers from 0-99, we should see most values at least once
- # This is a very basic test - real cryptographic random should pass this easily
- assert unique_values >= 60 # Should see at least 60 different values out of 100
-
- # Test secrets.choice for string generation
- chars = "abcdefghijklmnopqrstuvwxyz0123456789"
- random_chars = [secrets.choice(chars) for _ in range(1000)]
-
- # Should have good character distribution
- unique_chars = len(set(random_chars))
- assert unique_chars >= 20 # Should see at least 20 different characters
-
-
if __name__ == "__main__":
pytest.main([__file__, "-v"])
diff --git a/tests/test_weixin_oc_adapter_timeout_floor.py b/tests/test_weixin_oc_adapter_timeout_floor.py
index 8ba9db9965a..86b22c12378 100644
--- a/tests/test_weixin_oc_adapter_timeout_floor.py
+++ b/tests/test_weixin_oc_adapter_timeout_floor.py
@@ -13,6 +13,8 @@
import asyncio
+import pytest
+
from astrbot.core.platform.sources.weixin_oc.weixin_oc_adapter import (
WeixinOCAdapter,
)
@@ -30,30 +32,22 @@ def _adapter(**overrides) -> WeixinOCAdapter:
return WeixinOCAdapter(config, {"settings": {}}, asyncio.Queue())
-def test_cleared_api_timeout_falls_back_to_a_positive_floor():
- adapter = _adapter(weixin_oc_api_timeout_ms=0)
- assert adapter.api_timeout_ms == MINIMUM_TIMEOUT_MS
- # the value that actually reaches aiohttp.ClientTimeout(total=...)
- assert adapter.client.api_timeout_ms == MINIMUM_TIMEOUT_MS
-
-
-def test_cleared_long_poll_timeout_falls_back_to_a_positive_floor():
- adapter = _adapter(weixin_oc_long_poll_timeout_ms=0)
- assert adapter.long_poll_timeout_ms == MINIMUM_TIMEOUT_MS
-
-
-def test_negative_timeouts_are_clamped_like_the_login_flow():
- adapter = _adapter(
- weixin_oc_api_timeout_ms=-1,
- weixin_oc_long_poll_timeout_ms=-35_000,
- )
- assert adapter.api_timeout_ms == MINIMUM_TIMEOUT_MS
- assert adapter.long_poll_timeout_ms == MINIMUM_TIMEOUT_MS
-
+@pytest.mark.parametrize(
+ ("config_key", "value", "attr"),
+ [
+ ("weixin_oc_api_timeout_ms", 0, "api_timeout_ms"),
+ ("weixin_oc_long_poll_timeout_ms", 0, "long_poll_timeout_ms"),
+ ("weixin_oc_api_timeout_ms", -1, "api_timeout_ms"),
+ ("weixin_oc_long_poll_timeout_ms", -35_000, "long_poll_timeout_ms"),
+ ("weixin_oc_api_timeout_ms", 200, "api_timeout_ms"),
+ ],
+)
+def test_timeouts_below_the_floor_are_clamped(config_key, value, attr):
+ adapter = _adapter(**{config_key: value})
-def test_config_value_below_the_floor_still_clamped():
- adapter = _adapter(weixin_oc_api_timeout_ms=200)
- assert adapter.api_timeout_ms == MINIMUM_TIMEOUT_MS
+ assert getattr(adapter, attr) == MINIMUM_TIMEOUT_MS
+ if attr == "api_timeout_ms":
+ assert adapter.client.api_timeout_ms == MINIMUM_TIMEOUT_MS
def test_a_tuned_value_is_kept():
diff --git a/tests/unit/test_aiocqhttp_reply.py b/tests/unit/test_aiocqhttp_reply.py
index ac32bee6d32..e71e4ca0ef7 100644
--- a/tests/unit/test_aiocqhttp_reply.py
+++ b/tests/unit/test_aiocqhttp_reply.py
@@ -28,48 +28,6 @@
# ============================================================
-def test_reply_to_dict_contains_only_id_in_data():
- """Reply.toDict() 应当只输出 id 字段,不含 chain、sender_id 等多余字段。
-
- 当前实际行为:继承了 BaseMessageComponent.toDict(),会将所有
- 非 None 的默认值(chain: [], sender_id: 0, qq: 0, seq: 0 等)
- 一起序列化,违反了 OneBot V11 的 reply 段格式约定。
- """
- reply = Comp.Reply(id="123456")
-
- result = reply.toDict()
-
- assert result["type"] == "reply"
- assert "id" in result["data"]
-
- # 这些字段不应出现在 OneBot 协议的 reply segment 中
- unexpectedFields = ["chain", "sender_id", "qq", "seq", "text"]
- for field in unexpectedFields:
- if field in result["data"]:
- pytest.fail(
- f"Reply.toDict() 的 data 中不应包含 '{field}' 字段,"
- f"但实际输出了 {field}={result['data'][field]!r}。"
- f"完整输出: {result}"
- )
-
-
-def test_reply_to_dict_outputs_only_id():
- """Reply.toDict() 应当只输出 id 字段,不含任何多余字段。"""
- reply = Comp.Reply(id="123456")
- result = reply.toDict()
-
- assert result["type"] == "reply"
- assert set(result["data"].keys()) == {"id"}, (
- f"Reply.toDict() data 中包含多余字段: {set(result['data'].keys()) - {'id'}}"
- )
- assert result["data"]["id"] == "123456"
-
-
-# ============================================================
-# _parse_onebot_json 输出测试
-# ============================================================
-
-
@pytest.mark.asyncio
async def test_parse_onebot_json_reply_produces_extra_fields():
"""_parse_onebot_json 处理 Reply 时会输出多余字段。
@@ -102,54 +60,16 @@ async def test_parse_onebot_json_reply_produces_extra_fields():
@pytest.mark.asyncio
-async def test_send_private_msg_with_reply_includes_extra_fields():
- """验证私聊发送带 Reply 的消息时,实际传给 bot.send_private_msg 的
- payload 包含多余字段。
-
- 这是导致私聊下 'message not found' 的直接原因:
- OneBot 协议端收到的 reply 段数据不符合标准格式。
- """
- bot = AsyncMock()
- chain = MessageChain([Comp.Reply(id="123456"), Comp.Plain("你好")])
-
- await AiocqhttpMessageEvent.send_message(
- bot=bot,
- message_chain=chain,
- event=None,
- is_group=False, # 私聊
- session_id="987654",
- )
-
- # 验证调用了 send_private_msg(而非 send_group_msg)
- bot.send_private_msg.assert_awaited_once()
-
- callArgs = bot.send_private_msg.call_args
- assert callArgs.kwargs["user_id"] == 987654
-
- messages = callArgs.kwargs["message"]
- assert len(messages) >= 1
- replySegment = messages[0]
- assert replySegment["type"] == "reply"
-
- # 检查 payload 中的多余字段
- extraFields = [k for k in replySegment["data"] if k != "id"]
- if extraFields:
- pytest.fail(
- f"send_private_msg 的 message[0] reply 段包含了多余的 data 字段: "
- f"{extraFields}。\n"
- f"这是导致私聊引用回复报 'message not found' 的根因。\n"
- f"完整 payload: {messages}"
- )
-
-
-@pytest.mark.asyncio
-async def test_send_group_msg_with_reply_also_includes_extra_fields():
- """对比:群聊发送带 Reply 的消息同样包含多余字段。
-
- 如果群聊引用回复正常而私聊失败,可能的原因是不同协议端
- 对多余字段的容忍度不同(例如 napcat 在 send_group_msg 中
- 忽略了多余字段,但在 send_private_msg 中严格校验)。
- """
+@pytest.mark.parametrize(
+ ("is_group", "method_name", "target_key", "session_id"),
+ [
+ (False, "send_private_msg", "user_id", "987654"),
+ (True, "send_group_msg", None, "123456"),
+ ],
+)
+async def test_send_msg_with_reply_uses_standard_segment(
+ is_group, method_name, target_key, session_id
+):
bot = AsyncMock()
chain = MessageChain([Comp.Reply(id="123456"), Comp.Plain("你好")])
@@ -157,23 +77,20 @@ async def test_send_group_msg_with_reply_also_includes_extra_fields():
bot=bot,
message_chain=chain,
event=None,
- is_group=True,
- session_id="123456",
+ is_group=is_group,
+ session_id=session_id,
)
- bot.send_group_msg.assert_awaited_once()
+ method = getattr(bot, method_name)
+ method.assert_awaited_once()
- callArgs = bot.send_group_msg.call_args
+ callArgs = method.call_args
+ if target_key:
+ assert callArgs.kwargs[target_key] == int(session_id)
messages = callArgs.kwargs["message"]
replySegment = messages[0]
assert replySegment["type"] == "reply"
-
- extraFields = [k for k in replySegment["data"] if k != "id"]
- if extraFields:
- pytest.fail(
- f"send_group_msg 的 reply 段也包含多余字段: {extraFields}。\n"
- f"完整 payload: {messages}"
- )
+ assert replySegment["data"] == {"id": "123456"}
# ============================================================
diff --git a/tests/unit/test_astrbot_message.py b/tests/unit/test_astrbot_message.py
index 902fbbcec81..4be4323fe97 100644
--- a/tests/unit/test_astrbot_message.py
+++ b/tests/unit/test_astrbot_message.py
@@ -3,7 +3,6 @@
import time
from unittest.mock import patch
-from astrbot.core.message.components import Image, Plain
from astrbot.core.platform.astrbot_message import AstrBotMessage, Group, MessageMember
from astrbot.core.platform.message_type import MessageType
@@ -11,20 +10,6 @@
class TestMessageMember:
"""Tests for MessageMember dataclass."""
- def test_message_member_creation_basic(self):
- """Test creating a MessageMember with required fields."""
- member = MessageMember(user_id="user123")
-
- assert member.user_id == "user123"
- assert member.nickname is None
-
- def test_message_member_creation_with_nickname(self):
- """Test creating a MessageMember with nickname."""
- member = MessageMember(user_id="user123", nickname="TestUser")
-
- assert member.user_id == "user123"
- assert member.nickname == "TestUser"
-
def test_message_member_str_with_nickname(self):
"""Test __str__ method with nickname."""
member = MessageMember(user_id="user123", nickname="TestUser")
@@ -45,39 +30,6 @@ def test_message_member_str_without_nickname(self):
class TestGroup:
"""Tests for Group dataclass."""
- def test_group_creation_basic(self):
- """Test creating a Group with required fields."""
- group = Group(group_id="group123")
-
- assert group.group_id == "group123"
- assert group.group_name is None
- assert group.group_avatar is None
- assert group.group_owner is None
- assert group.group_admins is None
- assert group.members is None
- assert group.member_count is None
-
- def test_group_creation_with_all_fields(self):
- """Test creating a Group with all fields."""
- members = [MessageMember(user_id="user1"), MessageMember(user_id="user2")]
- group = Group(
- group_id="group123",
- group_name="Test Group",
- group_avatar="http://example.com/avatar.jpg",
- group_owner="owner123",
- group_admins=["admin1", "admin2"],
- members=members,
- member_count=2,
- )
-
- assert group.group_id == "group123"
- assert group.group_name == "Test Group"
- assert group.group_avatar == "http://example.com/avatar.jpg"
- assert group.group_owner == "owner123"
- assert group.group_admins == ["admin1", "admin2"]
- assert group.members == members
- assert group.member_count == 2
-
def test_group_str_with_all_fields(self):
"""Test __str__ method with all fields."""
members = [MessageMember(user_id="user1", nickname="User One")]
@@ -132,27 +84,6 @@ def test_astrbot_message_timestamp(self):
message = AstrBotMessage()
assert message.timestamp == 1234567890
- def test_astrbot_message_all_attributes(self):
- """Test setting all attributes on AstrBotMessage."""
- message = AstrBotMessage()
- message.type = MessageType.FRIEND_MESSAGE
- message.self_id = "bot123"
- message.session_id = "session123"
- message.message_id = "msg123"
- message.sender = MessageMember(user_id="user123", nickname="TestUser")
- message.message = [Plain(text="Hello")]
- message.message_str = "Hello"
- message.raw_message = {"raw": "data"}
-
- assert message.type == MessageType.FRIEND_MESSAGE
- assert message.self_id == "bot123"
- assert message.session_id == "session123"
- assert message.message_id == "msg123"
- assert message.sender.user_id == "user123"
- assert len(message.message) == 1
- assert message.message_str == "Hello"
- assert message.raw_message == {"raw": "data"}
-
def test_astrbot_message_str(self):
"""Test __str__ method."""
message = AstrBotMessage()
@@ -238,37 +169,3 @@ def test_other_message_type(self):
assert message.type == MessageType.OTHER_MESSAGE
assert message.type.value == "OtherMessage"
-
-
-class TestAstrBotMessageChain:
- """Tests for AstrBotMessage message chain."""
-
- def test_message_chain_with_plain_text(self):
- """Test message chain with plain text."""
- message = AstrBotMessage()
- message.message = [Plain(text="Hello world")]
-
- assert len(message.message) == 1
- assert isinstance(message.message[0], Plain)
- assert message.message[0].text == "Hello world"
-
- def test_message_chain_with_multiple_components(self):
- """Test message chain with multiple components."""
- message = AstrBotMessage()
- message.message = [
- Plain(text="Hello "),
- Plain(text="world"),
- Image(file="http://example.com/img.jpg"),
- ]
-
- assert len(message.message) == 3
- assert isinstance(message.message[0], Plain)
- assert isinstance(message.message[1], Plain)
- assert isinstance(message.message[2], Image)
-
- def test_message_chain_empty(self):
- """Test empty message chain."""
- message = AstrBotMessage()
- message.message = []
-
- assert len(message.message) == 0
diff --git a/tests/unit/test_cli_plugin_utils.py b/tests/unit/test_cli_plugin_utils.py
index afd185a71a4..ce904d39cac 100644
--- a/tests/unit/test_cli_plugin_utils.py
+++ b/tests/unit/test_cli_plugin_utils.py
@@ -2,6 +2,8 @@
from pathlib import Path
from zipfile import ZipFile
+import pytest
+
from astrbot.cli.utils.plugin import PluginStatus, build_plug_list, download_repository
@@ -106,15 +108,19 @@ def test_build_plug_list_merges_local_and_remote_plugins(monkeypatch, tmp_path):
assert len(plugins) == 3
-def test_build_plug_list_treats_file_plugin_path_as_empty_local_set(
- monkeypatch, tmp_path
+@pytest.mark.parametrize("path_kind", ["file", "missing"])
+def test_build_plug_list_treats_unusable_path_as_empty_local_set(
+ monkeypatch, tmp_path, path_kind
):
- plugins_file = tmp_path / "plugins"
- plugins_file.write_text("not a directory", encoding="utf-8")
+ plugins_path = tmp_path / "plugins"
+ if path_kind == "file":
+ plugins_path.write_text("not a directory", encoding="utf-8")
+ else:
+ plugins_path = tmp_path / "completely_non_existent_path"
monkeypatch.setattr("astrbot.cli.utils.plugin.httpx.Client", FakeClient)
- plugins = build_plug_list(plugins_file)
+ plugins = build_plug_list(plugins_path)
assert [plugin["name"] for plugin in plugins] == ["local-plugin", "remote-only"]
assert all(plugin["status"] == PluginStatus.NOT_INSTALLED for plugin in plugins)
@@ -140,12 +146,3 @@ def test_build_plug_list_local_version_equal_or_newer(monkeypatch, tmp_path):
assert plugins_newer_by_name["local-plugin"]["status"] == PluginStatus.INSTALLED
-def test_build_plug_list_non_existent_path(monkeypatch, tmp_path):
- non_existent_dir = tmp_path / "completely_non_existent_path"
-
- monkeypatch.setattr("astrbot.cli.utils.plugin.httpx.Client", FakeClient)
-
- plugins = build_plug_list(non_existent_dir)
-
- assert [plugin["name"] for plugin in plugins] == ["local-plugin", "remote-only"]
- assert all(plugin["status"] == PluginStatus.NOT_INSTALLED for plugin in plugins)
diff --git a/tests/unit/test_faiss_vec_db.py b/tests/unit/test_faiss_vec_db.py
index 8b30d2ca017..07679575b17 100644
--- a/tests/unit/test_faiss_vec_db.py
+++ b/tests/unit/test_faiss_vec_db.py
@@ -1,167 +1,542 @@
-import asyncio
-from unittest.mock import AsyncMock
-
-import pytest
-
-from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
-from astrbot.core.db.vec_db.faiss_impl.vec_db import FaissVecDB
-from astrbot.core.exceptions import KnowledgeBaseUploadError
-from astrbot.core.provider.provider import EmbeddingProvider
-
-
-class DelayedEmbeddingProvider(EmbeddingProvider):
- def __init__(self) -> None:
- super().__init__({}, {})
-
- async def get_embedding(self, text: str) -> list[float]:
- return [float(text.removeprefix("chunk-"))]
-
- async def get_embeddings(self, text: list[str]) -> list[list[float]]:
- if text[0] == "chunk-0":
- await asyncio.sleep(0.02)
- return [[float(item.removeprefix("chunk-"))] for item in text]
-
- def get_dim(self) -> int:
- return 1
-
-
-@pytest.mark.asyncio
-async def test_insert_batch_skips_empty_contents() -> None:
- vec_db = FaissVecDB.__new__(FaissVecDB)
- vec_db.embedding_provider = AsyncMock()
- vec_db.document_storage = AsyncMock()
- vec_db.embedding_storage = AsyncMock()
-
- result = await FaissVecDB.insert_batch(vec_db, [])
-
- assert result == []
- vec_db.embedding_provider.get_embeddings_batch.assert_not_awaited()
- vec_db.document_storage.insert_documents_batch.assert_not_awaited()
- vec_db.embedding_storage.insert_batch.assert_not_awaited()
-
-
-@pytest.mark.asyncio
-async def test_insert_batch_raises_friendly_error_for_embedding_count_mismatch() -> (
- None
-):
- vec_db = FaissVecDB.__new__(FaissVecDB)
- vec_db.embedding_provider = AsyncMock()
- vec_db.embedding_provider.get_embeddings_batch.return_value = [[0.1, 0.2]]
- vec_db.document_storage = AsyncMock()
- vec_db.embedding_storage = AsyncMock()
- vec_db.embedding_storage.dimension = 2
-
- with pytest.raises(KnowledgeBaseUploadError) as exc_info:
- await FaissVecDB.insert_batch(
- vec_db,
- contents=["chunk-1", "chunk-2"],
- metadatas=[{}, {}],
- ids=["doc-1", "doc-2"],
- )
-
- assert "向量化失败" in str(exc_info.value)
- assert "期望 2,实际 1" in str(exc_info.value)
- vec_db.document_storage.insert_documents_batch.assert_not_awaited()
- vec_db.embedding_storage.insert_batch.assert_not_awaited()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- ("embedding_contents", "expected_embedding_contents"),
- [
- (None, ["chunk one", "chunk two"]),
- (
- ["guide\n\nchunk one", "guide\n\nchunk two"],
- ["guide\n\nchunk one", "guide\n\nchunk two"],
- ),
- ],
-)
-async def test_insert_batch_uses_embedding_contents_without_changing_storage(
- embedding_contents: list[str] | None,
- expected_embedding_contents: list[str],
-) -> None:
- vec_db = FaissVecDB.__new__(FaissVecDB)
- vec_db.embedding_provider = AsyncMock()
- vec_db.embedding_provider.get_embeddings_batch.return_value = [
- [0.1, 0.2],
- [0.3, 0.4],
- ]
- vec_db.document_storage = AsyncMock()
- vec_db.document_storage.insert_documents_batch.return_value = [11, 12]
- vec_db.embedding_storage = AsyncMock()
- vec_db.embedding_storage.dimension = 2
-
- await FaissVecDB.insert_batch(
- vec_db,
- contents=["chunk one", "chunk two"],
- metadatas=[{}, {}],
- ids=["doc-1", "doc-2"],
- embedding_contents=embedding_contents,
- )
-
- vec_db.embedding_provider.get_embeddings_batch.assert_awaited_once_with(
- expected_embedding_contents,
- batch_size=32,
- tasks_limit=3,
- max_retries=3,
- progress_callback=None,
- )
- vec_db.document_storage.insert_documents_batch.assert_awaited_once_with(
- ["doc-1", "doc-2"],
- ["chunk one", "chunk two"],
- [{}, {}],
- )
-
-
-@pytest.mark.asyncio
-async def test_insert_batch_rejects_embedding_content_count_mismatch() -> None:
- vec_db = FaissVecDB.__new__(FaissVecDB)
- vec_db.embedding_provider = AsyncMock()
- vec_db.document_storage = AsyncMock()
- vec_db.embedding_storage = AsyncMock()
-
- with pytest.raises(KnowledgeBaseUploadError) as exc_info:
- await FaissVecDB.insert_batch(
- vec_db,
- contents=["chunk one", "chunk two"],
- metadatas=[{}, {}],
- ids=["doc-1", "doc-2"],
- embedding_contents=["guide\n\nchunk one"],
- )
-
- assert exc_info.value.stage == "storage"
- assert exc_info.value.details == {
- "expected_contents": 2,
- "actual_embedding_contents": 1,
- }
- vec_db.embedding_provider.get_embeddings_batch.assert_not_awaited()
- vec_db.document_storage.insert_documents_batch.assert_not_awaited()
-
-
-def test_embedding_storage_rejects_zero_dimension_for_a_fresh_index(tmp_path) -> None:
- with pytest.raises(ValueError, match="无效的嵌入向量维度"):
- EmbeddingStorage(0, str(tmp_path / "index.faiss"))
-
-
-def test_embedding_storage_rejects_negative_dimension_for_a_fresh_index() -> None:
- with pytest.raises(ValueError, match="无效的嵌入向量维度"):
- EmbeddingStorage(-1)
-
-
-def test_embedding_storage_accepts_a_valid_dimension_for_a_fresh_index() -> None:
- storage = EmbeddingStorage(4)
-
- assert storage.index.d == 4
-
-
-@pytest.mark.asyncio
-async def test_get_embeddings_batch_preserves_input_order_when_batches_finish_out_of_order():
- provider = DelayedEmbeddingProvider()
-
- embeddings = await provider.get_embeddings_batch(
- ["chunk-0", "chunk-1", "chunk-2", "chunk-3"],
- batch_size=2,
- tasks_limit=2,
- )
-
- assert embeddings == [[0.0], [1.0], [2.0], [3.0]]
+import asyncio
+from unittest.mock import AsyncMock
+
+import pytest
+
+from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+from astrbot.core.db.vec_db.faiss_impl.vec_db import FaissVecDB
+from astrbot.core.exceptions import KnowledgeBaseUploadError
+from astrbot.core.provider.provider import EmbeddingProvider
+
+
+class DelayedEmbeddingProvider(EmbeddingProvider):
+ def __init__(self) -> None:
+ super().__init__({}, {})
+
+ async def get_embedding(self, text: str) -> list[float]:
+ return [float(text.removeprefix("chunk-"))]
+
+ async def get_embeddings(self, text: list[str]) -> list[list[float]]:
+ if text[0] == "chunk-0":
+ await asyncio.sleep(0.02)
+ return [[float(item.removeprefix("chunk-"))] for item in text]
+
+ def get_dim(self) -> int:
+ return 1
+
+
+@pytest.mark.asyncio
+async def test_insert_batch_skips_empty_contents() -> None:
+ vec_db = FaissVecDB.__new__(FaissVecDB)
+ vec_db.embedding_provider = AsyncMock()
+ vec_db.document_storage = AsyncMock()
+ vec_db.embedding_storage = AsyncMock()
+
+ result = await FaissVecDB.insert_batch(vec_db, [])
+
+ assert result == []
+ vec_db.embedding_provider.get_embeddings_batch.assert_not_awaited()
+ vec_db.document_storage.insert_documents_batch.assert_not_awaited()
+ vec_db.embedding_storage.insert_batch.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_insert_batch_raises_friendly_error_for_embedding_count_mismatch() -> (
+ None
+):
+ vec_db = FaissVecDB.__new__(FaissVecDB)
+ vec_db.embedding_provider = AsyncMock()
+ vec_db.embedding_provider.get_embeddings_batch.return_value = [[0.1, 0.2]]
+ vec_db.document_storage = AsyncMock()
+ vec_db.embedding_storage = AsyncMock()
+ vec_db.embedding_storage.dimension = 2
+
+ with pytest.raises(KnowledgeBaseUploadError) as exc_info:
+ await FaissVecDB.insert_batch(
+ vec_db,
+ contents=["chunk-1", "chunk-2"],
+ metadatas=[{}, {}],
+ ids=["doc-1", "doc-2"],
+ )
+
+ assert "向量化失败" in str(exc_info.value)
+ assert "期望 2,实际 1" in str(exc_info.value)
+ vec_db.document_storage.insert_documents_batch.assert_not_awaited()
+ vec_db.embedding_storage.insert_batch.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("embedding_contents", "expected_embedding_contents"),
+ [
+ (None, ["chunk one", "chunk two"]),
+ (
+ ["guide\n\nchunk one", "guide\n\nchunk two"],
+ ["guide\n\nchunk one", "guide\n\nchunk two"],
+ ),
+ ],
+)
+async def test_insert_batch_uses_embedding_contents_without_changing_storage(
+ embedding_contents: list[str] | None,
+ expected_embedding_contents: list[str],
+) -> None:
+ vec_db = FaissVecDB.__new__(FaissVecDB)
+ vec_db.embedding_provider = AsyncMock()
+ vec_db.embedding_provider.get_embeddings_batch.return_value = [
+ [0.1, 0.2],
+ [0.3, 0.4],
+ ]
+ vec_db.document_storage = AsyncMock()
+ vec_db.document_storage.insert_documents_batch.return_value = [11, 12]
+ vec_db.embedding_storage = AsyncMock()
+ vec_db.embedding_storage.dimension = 2
+
+ await FaissVecDB.insert_batch(
+ vec_db,
+ contents=["chunk one", "chunk two"],
+ metadatas=[{}, {}],
+ ids=["doc-1", "doc-2"],
+ embedding_contents=embedding_contents,
+ )
+
+ vec_db.embedding_provider.get_embeddings_batch.assert_awaited_once_with(
+ expected_embedding_contents,
+ batch_size=32,
+ tasks_limit=3,
+ max_retries=3,
+ progress_callback=None,
+ )
+ vec_db.document_storage.insert_documents_batch.assert_awaited_once_with(
+ ["doc-1", "doc-2"],
+ ["chunk one", "chunk two"],
+ [{}, {}],
+ )
+
+
+@pytest.mark.asyncio
+async def test_insert_batch_rejects_embedding_content_count_mismatch() -> None:
+ vec_db = FaissVecDB.__new__(FaissVecDB)
+ vec_db.embedding_provider = AsyncMock()
+ vec_db.document_storage = AsyncMock()
+ vec_db.embedding_storage = AsyncMock()
+
+ with pytest.raises(KnowledgeBaseUploadError) as exc_info:
+ await FaissVecDB.insert_batch(
+ vec_db,
+ contents=["chunk one", "chunk two"],
+ metadatas=[{}, {}],
+ ids=["doc-1", "doc-2"],
+ embedding_contents=["guide\n\nchunk one"],
+ )
+
+ assert exc_info.value.stage == "storage"
+ assert exc_info.value.details == {
+ "expected_contents": 2,
+ "actual_embedding_contents": 1,
+ }
+ vec_db.embedding_provider.get_embeddings_batch.assert_not_awaited()
+ vec_db.document_storage.insert_documents_batch.assert_not_awaited()
+
+
+def test_embedding_storage_rejects_zero_dimension_for_a_fresh_index(tmp_path) -> None:
+ with pytest.raises(ValueError, match="无效的嵌入向量维度"):
+ EmbeddingStorage(0, str(tmp_path / "index.faiss"))
+
+
+def test_embedding_storage_rejects_negative_dimension_for_a_fresh_index() -> None:
+ with pytest.raises(ValueError, match="无效的嵌入向量维度"):
+ EmbeddingStorage(-1)
+
+
+def test_embedding_storage_accepts_a_valid_dimension_for_a_fresh_index() -> None:
+ storage = EmbeddingStorage(4)
+
+ assert storage.index.d == 4
+
+
+@pytest.mark.asyncio
+async def test_get_embeddings_batch_preserves_input_order_when_batches_finish_out_of_order():
+ provider = DelayedEmbeddingProvider()
+
+ embeddings = await provider.get_embeddings_batch(
+ ["chunk-0", "chunk-1", "chunk-2", "chunk-3"],
+ batch_size=2,
+ tasks_limit=2,
+ )
+
+ assert embeddings == [[0.0], [1.0], [2.0], [3.0]]
+
+
+def test_l2_normalize_scales_rows_to_unit_length() -> None:
+ import numpy as np
+
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import _l2_normalize
+
+ vectors = np.array([[3.0, 4.0], [0.0, 0.0], [0.5, 0.0]], dtype=np.float32)
+ normalized = _l2_normalize(vectors)
+
+ norms = np.linalg.norm(normalized, axis=1)
+ assert norms[0] == pytest.approx(1.0)
+ assert norms[1] == pytest.approx(0.0) # 全零行保持为零,不产生 NaN
+ assert norms[2] == pytest.approx(1.0)
+ assert np.array_equal(normalized[0], np.array([0.6, 0.8], dtype=np.float32))
+
+
+@pytest.mark.asyncio
+async def test_embedding_storage_ranks_by_cosine_regardless_of_magnitude() -> None:
+ """issue #11006:模长不同的向量必须按方向(余弦)排序,而不是按模长。"""
+ import numpy as np
+
+ storage = EmbeddingStorage(2)
+
+ # 相关文档:方向接近查询,但模长被压到很小
+ await storage.insert(np.array([0.6, 0.8], dtype=np.float32) * 0.2, 1)
+ # 无关文档:与查询正交,但模长很大
+ await storage.insert(np.array([0.0, 1.0], dtype=np.float32) * 5.0, 2)
+
+ distances, indices = await storage.search(np.array([1.0, 0.0], dtype=np.float32), 2)
+
+ assert indices[0][0] == 1, "语义更近的文档必须排在前面"
+ scores = 1 - distances[0] / 2.0
+ assert scores[0] == pytest.approx(0.6, abs=1e-5)
+ assert scores[1] == pytest.approx(0.0, abs=1e-5)
+
+
+@pytest.mark.asyncio
+async def test_embedding_storage_batch_insert_also_normalizes() -> None:
+ import numpy as np
+
+ storage = EmbeddingStorage(2)
+ vectors = np.array(
+ [[0.6, 0.8], [0.0, 2.0]],
+ dtype=np.float32,
+ ) * np.array([[0.3], [1.0]], dtype=np.float32)
+
+ await storage.insert_batch(vectors, [1, 2])
+ distances, indices = await storage.search(np.array([1.0, 0.0], dtype=np.float32), 2)
+
+ assert indices[0].tolist() == [1, 2]
+ assert (1 - distances[0] / 2.0)[0] == pytest.approx(0.6, abs=1e-5)
+
+
+@pytest.mark.asyncio
+async def test_retrieve_uses_query_embedding_hook() -> None:
+ """retrieve 必须走 get_query_embedding,才能带上查询侧任务条件化。"""
+ import numpy as np
+
+ class QueryAwareProvider(EmbeddingProvider):
+ def __init__(self) -> None:
+ super().__init__({}, {})
+ self.query_calls: list[str] = []
+
+ async def get_embedding(self, text: str) -> list[float]:
+ return [1.0, 0.0]
+
+ async def get_query_embedding(self, text: str) -> list[float]:
+ self.query_calls.append(text)
+ return [1.0, 0.0]
+
+ async def get_embeddings(self, text: list[str]) -> list[list[float]]:
+ return [[1.0, 0.0] for _ in text]
+
+ def get_dim(self) -> int:
+ return 2
+
+ provider = QueryAwareProvider()
+ vec_db = FaissVecDB.__new__(FaissVecDB)
+ from astrbot.core.db.vec_db.faiss_impl.document_storage import DocumentStorage
+
+ vec_db.embedding_provider = provider
+ vec_db.rerank_provider = None
+ vec_db.embedding_storage = EmbeddingStorage(2)
+ vec_db.document_storage = DocumentStorage(":memory:")
+ await vec_db.document_storage.initialize()
+ await vec_db.embedding_storage.insert(np.array([1.0, 0.0], dtype=np.float32), 1)
+
+ await vec_db.retrieve(query="查询词", k=1)
+
+ assert provider.query_calls == ["查询词"]
+
+
+def test_l2_normalize_handles_extreme_magnitudes_without_nan() -> None:
+ """极大/极小模长都不能产出 NaN 或 inf。"""
+ import numpy as np
+
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import _l2_normalize
+
+ vectors = np.array(
+ [[1e-30, 0.0], [3e38, 0.0], [0.0, 0.0], [3.0, 4.0]],
+ dtype=np.float32,
+ )
+ normalized = _l2_normalize(vectors)
+
+ assert not np.isnan(normalized).any()
+ assert not np.isinf(normalized).any()
+ # 极小模长不放大噪声,保持原样
+ assert normalized[0][0] == pytest.approx(1e-30, rel=1e-6)
+ # 极大模长应正确归一化,而不是被 float32 溢出成 0
+ assert normalized[1][0] == pytest.approx(1.0)
+ assert normalized[3] == pytest.approx(np.array([0.6, 0.8], dtype=np.float32))
+
+
+def test_l2_normalize_preserves_empty_batch() -> None:
+ import numpy as np
+
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import _l2_normalize
+
+ empty = np.zeros((0, 4), dtype=np.float32)
+ assert _l2_normalize(empty).shape == (0, 4)
+
+
+@pytest.mark.asyncio
+async def test_loading_legacy_index_normalizes_stored_vectors() -> None:
+ """旧版本入库未归一化,加载时必须重建,否则两侧标准不一致。"""
+ import os
+
+ import numpy as np
+
+ faiss = pytest.importorskip("faiss")
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+
+ # faiss 的 C++ 层在 Windows 上无法写非 ASCII 路径,这里用纯 ASCII 临时目录。
+ tmp_dir = _ascii_tmp_dir()
+ path = os.path.join(tmp_dir, "legacy.faiss")
+ # 旧索引:未归一化,模长各不相同
+ legacy = faiss.IndexIDMap(faiss.IndexFlatL2(2))
+ legacy.add_with_ids(
+ np.array([[0.6, 0.8], [0.0, 1.0]], dtype=np.float32)
+ * np.array([[0.5], [3.0]], dtype=np.float32),
+ np.array([1, 2], dtype=np.int64),
+ )
+ faiss.write_index(legacy, path)
+
+ storage = EmbeddingStorage(2, path)
+ assert storage._pending_save is True
+
+ distances, indices = await storage.search(np.array([1.0, 0.0], dtype=np.float32), 2)
+ assert indices[0].tolist() == [1, 2]
+ scores = 1 - distances[0] / 2.0
+ assert scores[0] == pytest.approx(0.6, abs=1e-5)
+ assert scores[1] == pytest.approx(0.0, abs=1e-5)
+
+ await storage.flush()
+ assert storage._pending_save is False
+
+ # 重新加载后不应再次触发迁移
+ reloaded = EmbeddingStorage(2, path)
+ assert reloaded._pending_save is False
+ redo_dist, _ = await reloaded.search(np.array([1.0, 0.0], dtype=np.float32), 2)
+ assert (1 - redo_dist[0] / 2.0)[0] == pytest.approx(0.6, abs=1e-5)
+
+
+@pytest.mark.asyncio
+async def test_flush_is_noop_for_fresh_index() -> None:
+ storage = EmbeddingStorage(4)
+ assert storage._pending_save is False
+ await storage.flush()
+ assert storage._pending_save is False
+
+
+@pytest.mark.asyncio
+async def test_zero_vector_does_not_retrigger_migration() -> None:
+ """零向量模长为 0,不能让它被误判成"未归一化"而反复重建索引。"""
+ import os
+
+ import numpy as np
+
+ faiss = pytest.importorskip("faiss")
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+
+ tmp_dir = _ascii_tmp_dir()
+ path = os.path.join(tmp_dir, "zero.faiss")
+
+ index = faiss.IndexIDMap(faiss.IndexFlatL2(2))
+ index.add_with_ids(
+ np.array([[0.6, 0.8], [0.0, 0.0]], dtype=np.float32),
+ np.array([1, 2], dtype=np.int64),
+ )
+ faiss.write_index(index, path)
+
+ first = EmbeddingStorage(2, path)
+ assert first._pending_save is False, "全部已归一化时不应重建"
+
+ second = EmbeddingStorage(2, path)
+ assert second._pending_save is False, "零向量不能触发重复迁移"
+
+
+@pytest.mark.asyncio
+async def test_migration_still_runs_when_zero_vector_mixed_with_unnormalized() -> None:
+ import os
+
+ import numpy as np
+
+ faiss = pytest.importorskip("faiss")
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+
+ tmp_dir = _ascii_tmp_dir()
+ path = os.path.join(tmp_dir, "mix.faiss")
+
+ index = faiss.IndexIDMap(faiss.IndexFlatL2(2))
+ index.add_with_ids(
+ np.array([[0.3, 0.4], [0.0, 0.0]], dtype=np.float32), # 前一个模长 0.5
+ np.array([1, 2], dtype=np.int64),
+ )
+ faiss.write_index(index, path)
+
+ storage = EmbeddingStorage(2, path)
+ assert storage._pending_save is True, "存在未归一化向量时仍需迁移"
+
+ distances, indices = await storage.search(np.array([1.0, 0.0], dtype=np.float32), 2)
+ assert indices[0][0] == 1
+ assert (1 - distances[0] / 2.0)[0] == pytest.approx(0.6, abs=1e-5)
+
+
+@pytest.mark.asyncio
+async def test_flush_failure_does_not_break_initialization() -> None:
+ """归一化落盘失败不能让知识库打不开;内存索引仍应可用。"""
+ import os
+ from unittest.mock import patch
+
+ import numpy as np
+
+ faiss = pytest.importorskip("faiss")
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+
+ tmp_dir = _ascii_tmp_dir()
+ path = os.path.join(tmp_dir, "readonly.faiss")
+
+ index = faiss.IndexIDMap(faiss.IndexFlatL2(2))
+ index.add_with_ids(
+ np.array([[0.3, 0.4]], dtype=np.float32),
+ np.array([1], dtype=np.int64),
+ )
+ faiss.write_index(index, path)
+
+ storage = EmbeddingStorage(2, path)
+ assert storage._pending_save is True
+
+ with patch.object(
+ EmbeddingStorage, "_write_index", side_effect=OSError("No space left")
+ ):
+ # 不应抛出
+ await storage.flush()
+
+ # 写盘失败要保留标记,以便后续 initialize/close 重试
+ assert storage._pending_save is True
+
+ # 内存中的索引已经归一化,检索照常工作
+ distances, indices = await storage.search(np.array([1.0, 0.0], dtype=np.float32), 1)
+ assert indices[0][0] == 1
+ assert (1 - distances[0] / 2.0)[0] == pytest.approx(0.6, abs=1e-5)
+
+
+@pytest.mark.asyncio
+async def test_flush_retries_after_a_write_failure() -> None:
+ """一次写盘失败不能让归一化结果永远丢掉。"""
+ import os
+ from unittest.mock import patch
+
+ import numpy as np
+
+ faiss = pytest.importorskip("faiss")
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+
+ tmp_dir = _ascii_tmp_dir()
+ path = os.path.join(tmp_dir, "retry.faiss")
+
+ index = faiss.IndexIDMap(faiss.IndexFlatL2(2))
+ index.add_with_ids(
+ np.array([[0.3, 0.4]], dtype=np.float32),
+ np.array([1], dtype=np.int64),
+ )
+ faiss.write_index(index, path)
+
+ storage = EmbeddingStorage(2, path)
+ assert storage._pending_save is True
+
+ with patch.object(
+ EmbeddingStorage, "_write_index", side_effect=OSError("disk full")
+ ):
+ await storage.flush()
+ assert storage._pending_save is True, "失败后必须保留重试标记"
+
+ # 第二次成功
+ await storage.flush()
+ assert storage._pending_save is False
+
+ reloaded = EmbeddingStorage(2, path)
+ assert reloaded._pending_save is False
+ distances, _ = await reloaded.search(np.array([1.0, 0.0], dtype=np.float32), 1)
+ assert (1 - distances[0] / 2.0)[0] == pytest.approx(0.6, abs=1e-5)
+
+
+@pytest.mark.asyncio
+async def test_close_flushes_pending_normalization() -> None:
+ """close() 也要尝试落盘,别让内存里的归一化结果丢掉。"""
+ import os
+
+ import numpy as np
+
+ faiss = pytest.importorskip("faiss")
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+
+ tmp_dir = _ascii_tmp_dir()
+ path = os.path.join(tmp_dir, "close.faiss")
+
+ index = faiss.IndexIDMap(faiss.IndexFlatL2(2))
+ index.add_with_ids(
+ np.array([[0.3, 0.4]], dtype=np.float32),
+ np.array([1], dtype=np.int64),
+ )
+ faiss.write_index(index, path)
+
+ storage = EmbeddingStorage(2, path)
+ assert storage._pending_save is True
+
+ await storage.flush()
+
+ reloaded = EmbeddingStorage(2, path)
+ assert reloaded._pending_save is False, "落盘后重新加载不应再次迁移"
+
+
+@pytest.mark.asyncio
+async def test_migration_logs_do_not_leak_local_paths(caplog) -> None:
+ """日志不能带出索引绝对路径(含用户名等本地信息)。"""
+ import logging
+ import os
+
+ import numpy as np
+
+ faiss = pytest.importorskip("faiss")
+ from astrbot.core.db.vec_db.faiss_impl.embedding_storage import EmbeddingStorage
+
+ tmp_dir = _ascii_tmp_dir()
+ secret_name = "leakcanary.faiss"
+ path = os.path.join(tmp_dir, secret_name)
+
+ index = faiss.IndexIDMap(faiss.IndexFlatL2(2))
+ index.add_with_ids(
+ np.array([[0.3, 0.4]], dtype=np.float32),
+ np.array([1], dtype=np.int64),
+ )
+ faiss.write_index(index, path)
+
+ with caplog.at_level(logging.DEBUG):
+ storage = EmbeddingStorage(2, path)
+ assert storage._pending_save is True
+ await storage.flush()
+
+ assert secret_name not in caplog.text, "日志里不应出现索引文件名"
+ assert tmp_dir not in caplog.text, "日志里不应出现索引所在目录"
+
+
+def _ascii_tmp_dir() -> str:
+ """返回纯 ASCII 的临时目录。
+
+ faiss 的 C++ 层在 Windows 上按 ANSI codepage 打开文件,含中文的用户名路径
+ 会写失败,因此 Windows 上固定用系统 Temp。
+ """
+ import os
+ import tempfile
+
+ return tempfile.mkdtemp(dir="C:/Windows/Temp" if os.name == "nt" else None)
diff --git a/tests/unit/test_io_download_file.py b/tests/unit/test_io_download_file.py
index 5cea2f0e507..46449899d8d 100644
--- a/tests/unit/test_io_download_file.py
+++ b/tests/unit/test_io_download_file.py
@@ -56,37 +56,23 @@ def _patch_download_sessions(monkeypatch, responses: list[_FakeResponse | Except
@pytest.mark.asyncio
-async def test_download_file_rejects_non_200_response(monkeypatch, tmp_path):
- target_path = tmp_path / "missing.bin"
- _patch_download_session(
- monkeypatch,
- _FakeResponse(status=404, chunks=[b"not found"]),
- )
-
- with pytest.raises(io.DownloadFileHTTPError, match="HTTP status code: 404"):
- await io.download_file("https://example.test/missing", str(target_path))
-
- assert not target_path.exists()
-
-
-@pytest.mark.asyncio
-async def test_download_file_rejects_non_200_response_after_ssl_fallback(
- monkeypatch,
- tmp_path,
+@pytest.mark.parametrize("ssl_fallback", [False, True])
+async def test_download_file_rejects_non_200_response(
+ monkeypatch, tmp_path, ssl_fallback
):
class FakeSSLError(Exception):
pass
target_path = tmp_path / "missing.bin"
- _patch_download_sessions(
- monkeypatch,
- [
- FakeSSLError(),
- _FakeResponse(status=404, chunks=[b"not found"]),
- ],
- )
- monkeypatch.setattr(io.aiohttp, "ClientConnectorSSLError", FakeSSLError)
- monkeypatch.setattr(io.aiohttp, "ClientConnectorCertificateError", FakeSSLError)
+ response = _FakeResponse(status=404, chunks=[b"not found"])
+ if ssl_fallback:
+ _patch_download_sessions(monkeypatch, [FakeSSLError(), response])
+ monkeypatch.setattr(io.aiohttp, "ClientConnectorSSLError", FakeSSLError)
+ monkeypatch.setattr(
+ io.aiohttp, "ClientConnectorCertificateError", FakeSSLError
+ )
+ else:
+ _patch_download_session(monkeypatch, response)
with pytest.raises(io.DownloadFileHTTPError, match="HTTP status code: 404"):
await io.download_file("https://example.test/missing", str(target_path))
diff --git a/tests/unit/test_persona_mgr.py b/tests/unit/test_persona_mgr.py
index c7b1464e4ef..ef2ccaa2736 100644
--- a/tests/unit/test_persona_mgr.py
+++ b/tests/unit/test_persona_mgr.py
@@ -127,23 +127,6 @@ async def test_get_default_persona_v3_uses_db_default():
assert resolved["prompt"] == "USER DEFAULT"
-@pytest.mark.asyncio
-async def test_resolve_selected_persona_matches_db_default():
- manager = make_manager([make_persona("default", "USER DEFAULT")])
-
- with patch.object(pm.sp, "get_async", new=AsyncMock(return_value={})):
- persona_id, persona, _, _ = await manager.resolve_selected_persona(
- umo="test:umo",
- conversation_persona_id="default",
- platform_name="webchat",
- provider_settings={},
- )
-
- assert persona_id == "default"
- assert persona is not None
- assert persona["prompt"] == "USER DEFAULT"
-
-
@pytest.mark.asyncio
async def test_resolve_selected_persona_webchat_implicit_uses_chatui_default():
manager = make_manager([make_persona("default", "USER DEFAULT")])
diff --git a/tests/unit/test_third_party_agent_sub_stage.py b/tests/unit/test_third_party_agent_sub_stage.py
index 34561450618..b791a414230 100644
--- a/tests/unit/test_third_party_agent_sub_stage.py
+++ b/tests/unit/test_third_party_agent_sub_stage.py
@@ -97,90 +97,20 @@ def __new__(cls):
assert runner_factory_calls == [True]
@pytest.mark.asyncio
-async def test_third_party_skips_unavailable_voice_attachment(
- monkeypatch: pytest.MonkeyPatch,
-):
- """An unresolvable voice attachment must not abort the third-party request."""
- runner = MagicMock()
- runner.reset = AsyncMock()
- runner.get_final_llm_resp.return_value = LLMResponse(
- role="assistant",
- result_chain=MessageChain().message("done"),
- )
- runner.close = AsyncMock()
-
- async def step_until_done(max_step: int = 30):
- _ = max_step
- if False:
- yield None
-
- runner.step_until_done = step_until_done
-
- class RunnerFactory:
- @classmethod
- def __class_getitem__(cls, item):
- _ = item
- return cls
-
- def __new__(cls):
- return runner
-
- monkeypatch.setattr(third_party, "DifyAgentRunner", RunnerFactory)
- monkeypatch.setattr(
- third_party, "AstrAgentContext", MagicMock(return_value=object())
- )
- monkeypatch.setattr(
- third_party, "AgentContextWrapper", MagicMock(return_value=object())
- )
- monkeypatch.setattr(third_party, "call_event_hook", AsyncMock(return_value=False))
- monkeypatch.setattr(third_party.Metric, "upload", AsyncMock(return_value=None))
-
- async def unavailable(self):
- raise Exception(f"not a valid file: {self.file}")
-
- monkeypatch.setattr(Record, "convert_to_file_path", unavailable)
-
- config = {
- "agent_runner": {"runner_type": "dify", "config": {"dify_api_key": "k"}},
- "provider_settings": {
- "streaming_response": False,
- "unsupported_streaming_strategy": "turn_off",
- "third_party_stream_consumption_close_timeout_sec": 30,
- },
- }
- stage = third_party.ThirdPartyAgentSubStage()
- await stage.initialize(
- SimpleNamespace(
- astrbot_config=config,
- plugin_manager=SimpleNamespace(
- context=SimpleNamespace(
- conversation_manager=MagicMock(),
- persona_manager=MagicMock(),
- )
- ),
- )
- )
- stage._resolve_persona_custom_error_message = AsyncMock(return_value=None)
-
- event = MagicMock()
- event.message_str = "hello"
- event.unified_msg_origin = "webchat:FriendMessage:test"
- event.message_obj.message = [Record(file="")]
- event.platform_meta.support_streaming_message = True
- event.get_extra.return_value = None
-
- results = [item async for item in stage.process(event, "")]
-
- assert results == [None]
- request = runner.reset.await_args.kwargs["request"]
- assert request.audio_urls == []
- assert request.prompt == "hello"
-
-@pytest.mark.asyncio
-async def test_third_party_skips_unavailable_image_attachment(
+@pytest.mark.parametrize(
+ ("component", "patch_method", "request_attr"),
+ [
+ (Record, "convert_to_file_path", "audio_urls"),
+ (Image, "convert_to_base64", "image_urls"),
+ ],
+)
+async def test_third_party_skips_unavailable_attachment(
monkeypatch: pytest.MonkeyPatch,
+ component,
+ patch_method: str,
+ request_attr: str,
):
- """An unresolvable image attachment must not abort the third-party request."""
+ """An unresolvable attachment must not abort the third-party request."""
runner = MagicMock()
runner.reset = AsyncMock()
runner.get_final_llm_resp.return_value = LLMResponse(
@@ -218,7 +148,7 @@ def __new__(cls):
async def unavailable(self):
raise ValueError("No valid file or URL provided")
- monkeypatch.setattr(Image, "convert_to_base64", unavailable)
+ monkeypatch.setattr(component, patch_method, unavailable)
config = {
"agent_runner": {"runner_type": "dify", "config": {"dify_api_key": "k"}},
@@ -245,7 +175,7 @@ async def unavailable(self):
event = MagicMock()
event.message_str = "hello"
event.unified_msg_origin = "webchat:FriendMessage:test"
- event.message_obj.message = [Image(file="")]
+ event.message_obj.message = [component(file="")]
event.platform_meta.support_streaming_message = True
event.get_extra.return_value = None
@@ -253,5 +183,5 @@ async def unavailable(self):
assert results == [None]
request = runner.reset.await_args.kwargs["request"]
- assert request.image_urls == []
+ assert getattr(request, request_attr) == []
assert request.prompt == "hello"