AstrBot
AstrBot copied to clipboard
[Bug] 使用 gemini-embedding-2 进行批量向量化时触发 IndexError: list index out of range
1. 问题描述
当使用 Google Gemini 的新版嵌入模型 gemini-embedding-2 进行批量文本嵌入时(例如同步记忆索引)会触发 IndexError: list index out of range。
2. 报错堆栈 (Traceback)
[components.faiss_memory_index:250]: [FAISS向量索引] 开始 任务名=批量向量化 index=memory_index provider_id=gemini_embedding embedding_model=gemini_embedding 条数=32
[services.memory_vector_sync_service:38]: [FAISS向量索引] 失败 任务名=记忆索引同步 阶段=同步FAISS 异常=list index out of range
Traceback (most recent call last):
File "astrbot/core/provider/sources/gemini_embedding_source.py", line 64, in get_embeddings
result = await self.client.models.embed_content(
File "llm_memory/components/embedding_provider.py", line 766, in _map_embeddings_back
embedding = unique_embeddings[unique_idx]
IndexError: list index out of range
3. 原因分析
在使用新版 google-genai SDK 请求 gemini-embedding-2(和 gemini-embedding-2-preview)模型时,如果直接给 contents 参数传入字符串列表 contents=text,SDK 会将该列表解析为同一个 Content 对象的多个 parts,从而把它们当成一个整体文本合并向量化,最终只返回 1 个向量,导致返回的 embeddings 长度为 1,而在 _map_embeddings_back 映射回原索引时越界。
根据 Google 官方关于 gemini-embedding-2* 批量向量化的适配说明,需要显式将每个文本字符串包装为独立的 types.Content 对象:
contents = [types.Content(parts=[types.Part.from_text(text=s)]) for s in text]
4. 解决方案 (Code Diff)
在 astrbot/core/provider/sources/gemini_embedding_source.py 中,对 get_embeddings 方法进行如下包装:
async def get_embeddings(self, text: list[str]) -> list[list[float]]:
"""批量获取文本的嵌入"""
try:
- result = await self.client.models.embed_content(
- model=self.model,
- contents=cast(types.ContentListUnion, text),
- config=types.EmbedContentConfig(
- output_dimensionality=self.get_dim(),
- ),
- )
+ 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
Duplicate of #8534. Closing this automated duplicate submission.