FEATURED · 精选文章

使用 LlamaIndex 接入 Vertex AI Endpoint 自定义 Embedding 模型:VertexEndpointEmbedding 全解析

发布时间 / 2026/9/8 18:48:27
来源 / 创域科博编辑部
栏目 / 资讯中心
使用 LlamaIndex 接入 Vertex AI Endpoint 自定义 Embedding 模型:VertexEndpointEmbedding 全解析 使用 LlamaIndex 接入 Vertex AI Endpoint 自定义 Embedding 模型VertexEndpointEmbedding 全解析【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index导读VertexEndpointEmbedding 是 LlamaIndex 为 Google Cloud Vertex AI Endpoint 提供的 Embedding 集成类用于把部署在 Vertex AI 上的自定义/私有化文本嵌入模型无缝接入 LlamaIndex 的检索与索引体系。阅读本文你将掌握如何安装与初始化该组件、每个构造参数的含义与默认值、同步与异步两种推理路径的实现原理、输入输出如何通过IOHandler进行序列化适配以及它如何被纳入 LlamaIndex 文档级源码与测试验证的完整链路。一、为什么需要VertexEndpointEmbeddingGoogle Cloud 的 Vertex AI Endpoint 允许用户部署经过微调或自定义训练的模型并通过统一的predict接口对外提供推理服务。对于不在 LlamaIndex 官方模型列表中的私有 embedding 模型用户需要一种方式让 LlamaIndex 的VectorStoreIndex、检索器等上层能力直接消费该端点的输出向量。VertexEndpointEmbedding的作用正是建立这条桥接通道它在内部持有google.cloud.aiplatform.Endpoint客户端把 LlamaIndex 的BaseEmbedding抽象请求翻译成对 Vertex AI Endpoint 的预测调用再返回标准化的向量结果。从测试可见其设计完全遵循 LlamaIndex 的嵌入抽象——test_embeddings_vertex_endpoint.py 通过遍历VertexEndpointEmbedding.__mro__断言BaseEmbedding是其基类之一从继承关系上确认了它属于标准的 LlamaIndex Embedding 体系。二、安装与包结构该集成作为独立包发布安装命令如下pip install llama-index-embeddings-vertex-endpoint根据 pyproject.toml 中的依赖声明它依赖两个关键运行库依赖版本约束用途google-cloud-aiplatform1.69.0,2创建aiplatform.Endpoint客户端并发送预测请求llama-index-core0.13.0,0.15提供BaseEmbedding、CallbackManager等核心抽象包本身要求python 3.10,4.0采用 MIT 许可证。包的导入路径在 pyproject.toml 中注册为llama_index.embeddings.vertex_endpoint顶层的init.py 只导出一个公开符号from llama_index.embeddings.vertex_endpoint.base import VertexEndpointEmbedding __all__ [VertexEndpointEmbedding]对应的文档页 vertex_endpoint.md 也正是以VertexEndpointEmbedding为唯一公开成员生成 API 参考因此使用时代码写作from llama_index.embeddings.vertex_endpoint import VertexEndpointEmbedding三、构造参数详解字段与默认值VertexEndpointEmbedding的核心入口是__init__构造函数见 base.py。所有关键参数同时以 PydanticField形式声明为类属性base.py既保证参数可校验、可序列化也方便后续作为 LlamaIndex 组件被保存与恢复。3.1 必填参数参数类型说明endpoint_idstrVertex AI Endpoint 的 ID用于定位已部署的模型端点project_idstr承载该 Endpoint 的 GCP 项目 IDlocationstrVertex AI 所在 GCP 区域Region如us-central1这三个值在__init__中被直接用于构造客户端self._client aiplatform.Endpoint( endpoint_nameendpoint_id, projectproject_id, locationlocation, credentialscredentials, )3.2 请求级参数参数类型默认值说明endpoint_kwargsDict[str, Any]{}传给predict请求的附加关键字参数model_kwargsDict[str, Any]{}传给模型的参数映射为 Vertex AI 的parameterstimeoutfloat60.0API 请求超时时间秒Pydantic 约束ge0即不可为负embed_batch_sizeintDEFAULT_EMBED_BATCH_SIZE每次批量送入模型的文本条数来自 llama_index.core.constants 体系的默认批大小常量3.3 凭据与高级参数参数类型默认值说明service_account_filestr \| NoneNone服务账号 JSON 文件路径service_account_infoDict[str, str] \| NoneNone直接以字典形式提供服务账号凭据内容content_handlerBaseIOHandlerIOHandler()负责输入序列化与输出反序列化的处理器callback_managerCallbackManager \| NoneNoneLlamaIndex 回调管理器接入可观测体系verboseboolFalse是否开启调试输出保存在私有属性_verbose中3.4 凭据解析优先级构造函数的凭据处理逻辑清晰base.py若传入了service_account_file调用service_account.Credentials.from_service_account_file(file)从 JSON 文件加载凭据否则若传入了service_account_info调用service_account.Credentials.from_service_account_info(info)直接从字典加载两者都未提供时credentials None回退使用 Google 默认应用凭据Application Default Credentials, ADC例如通过gcloud auth application-default login或环境变量注入的身份。客户端创建若失败异常会被包装为ValueError(Please verify the provided credentials.)抛出——这说明该项目的大多数连接问题根源都在凭据环节排查时应优先检查以上三种凭据来源是否有效。四、IOHandler输入输出适配的关键不同模型端点对请求体和返回体的格式约定并不一致。为此源码在 utils.py 中定义了可插拔的 I/O 处理器抽象4.1 抽象基类BaseIOHandler它通过abc.ABCMeta定义了协议同时用__subclasshook__支持结构化鸭子类型——任何同时实现了serialize_input与deserialize_output两个可调用方法的类都会被视为其子类不必显式继承抽象方法签名职责serialize_input(request: List[str]) - ...把待嵌入的文本列表转换为端点期望的请求实例结构deserialize_output(response: Any) - List[List[float]]从端点返回的预测结果中抽取向量列表4.2 默认实现IOHandler默认处理器实现的输入/输出约定为def serialize_input(self, request: List[str]) - List[Dict[str, Any]]: return [{inputs: text} for text in request] def deserialize_output(self, response: Any) - List[List[float]]: return [prediction[0] for prediction in response.predictions]即每个文本被包装成{inputs: text}一条实例发送返回时逐条读取response.predictions并取出每条 prediction 的第 0 个元素作为该文本的嵌入向量。若你的自建模型使用不同的字段名例如text代替inputs或输出结构不同就应当自定义一个BaseIOHandler子类并通过content_handler传入。模块级默认实例在 base.py 中创建DEFAULT_IO_HANDLER IOHandler()五、核心推理链路同步与异步_get_embedding方法base.py是所有调用的汇聚点def _get_embedding(self, payload: List[str], **kwargs: Any) - List[Embedding]: # 合并 endpoint 级参数始终附加超时时间 endpoint_kwargs {**self.endpoint_kwargs, **{timeout: self.timeout}} # 合并模型参数传入的方法 kwargs 拥有更高优先级 model_kwargs {**self.model_kwargs, **kwargs} response self._client.predict( instancesself.content_handler.serialize_input(payload), parametersmodel_kwargs, **endpoint_kwargs, ) return self.content_handler.deserialize_output(response)可以拆解出三层参数合并规则端点参数endpoint_kwargs与自动注入的timeout合并作为predict的关键字参数模型参数model_kwargs与每次调用额外传入的**kwargs合并作为 Vertex AI 的parameters调用级参数可覆盖构造时的默认模型参数实例数据payload文本列表先经content_handler.serialize_input转换再作为instances传入。对应的异步版本_aget_embeddingbase.py逻辑完全一致仅把_client.predict替换为_client.predict_async并await其返回。这一对方法由BaseEmbedding基类的同步/异步公共 API 分派调用。5.1 四种嵌入方法及文本预处理类内实现了BaseEmbedding要求的六个方法。其中四个查询/文本单条方法以及两条批量路径base.py在调用底层推理前统一执行了一条预处理规则text text.replace(\n, )将文本中的换行符替换为空格降低换行对嵌入质量与批次格式的干扰方法签名用途_get_query_embedding(query: str) - Embedding生成查询向量同步_get_text_embedding(text: str) - Embedding生成单条文档向量同步_get_text_embeddings(texts: List[str]) - List[Embedding]批量生成文档向量同步_aget_query_embedding(query: str) - Embedding查询向量异步_aget_text_embedding(text: str) - Embedding单条文档向量异步_aget_text_embeddings(texts: List[str]) - List[Embedding]批量文档向量异步此外class_name()类方法base.py返回VertexEndpointEmbedding这是 LlamaIndex 系列组件在序列化、日志与类型识别上的约定接口。六、完整使用示例6.1 基础用法走默认凭据from llama_index.embeddings.vertex_endpoint import VertexEndpointEmbedding from llama_index.core import VectorStoreIndex # 前提已在对应 GCP 项目的 us-central1 部署好 embedding 端点 # 且当前环境具备默认应用凭据ADC。 embed_model VertexEndpointEmbedding( endpoint_idprojects/123456789012/locations/us-central1/endpoints/987654321, project_idmy-gcp-project, locationus-central1, )6.2 指定服务账号文件embed_model VertexEndpointEmbedding( endpoint_idmy-endpoint-id, project_idmy-gcp-project, locationus-central1, service_account_file/path/to/service-account.json, timeout120.0, # 覆盖默认 60 秒超时 embed_batch_size32, verboseTrue, )初始化完成后该对象即可作为 LlamaIndex 全体系的标准 embedding 使用from llama_index.core import Settings Settings.embed_model embed_model # 全局生效 index VectorStoreIndex.from_documents(documents) # 索引阶段自动调用批量嵌入 retriever index.as_retriever(similarity_top_k5)6.3 针对自定义端点格式定制 IOHandler若模型端点的输入字段是text而非inputs自定义处理器并传入即可from llama_index.embeddings.vertex_endpoint import VertexEndpointEmbedding from llama_index.embeddings.vertex_endpoint.utils import BaseIOHandler class MyHandler(BaseIOHandler): def serialize_input(self, request): return [{text: text} for text in request] def deserialize_output(self, response): return [prediction[embedding] for prediction in response.predictions] embed_model VertexEndpointEmbedding( endpoint_id..., project_id..., location..., content_handlerMyHandler(), )得益于__subclasshook__MyHandler无需显式继承BaseIOHandler也会被接受只要它实现了上述两个方法。七、源码质量与集成验证该集成虽小但保持了与 LlamaIndex 核心一致的工程质量类型标注完整全部方法均带类型注解mypy配置disallow_untyped_defs truepyproject.toml测试回归tests/test_embeddings_vertex_endpoint.py 验证类层次符合 LlamaIndexBaseEmbedding抽象契约防止未来核心 API 变更导致集成失效文档集成API 参考页 vertex_endpoint.md 通过 mkdocstrings 指令自动渲染VertexEndpointEmbedding的字段与方法签名保证文档与源码同步演进编排规范在 LlamaIndex 的集成目录体系中位于llama-index-integrations/embeddings/llama-index-embeddings-vertex-endpoint/遵循统一的包命名、Makefile与uv.lock工作流便于按官方方式构建与发布。八、注意事项与限制端点必须已部署且可访问VertexEndpointEmbedding只负责调用不负责模型部署使用前需在 Vertex AI 控制台或通过aiplatform完成模型的线上部署并拿到 endpoint。凭据错误提示较宽泛客户端创建失败统一报Please verify the provided credentials.无法区分网络、项目或端点名错误需要借助verboseTrue与 GCP 日志进一步排查。换行符会被替换文本中的\n在进入模型前统一替换为空格对依赖原始换行的场景如代码嵌入需自行评估影响。返回结构依赖端点实现默认IOHandler假定predictions每个元素的第一项即向量若端点返回多输出结构务必自定义deserialize_output。版本前提以当前仓库为准该包面向llama-index-core 0.130.15与google-cloud-aiplatform 1.x设计升级大版本前请核对兼容性约束。【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
RELATED — 相关阅读

相关资讯

LATEST — 最新资讯

最新发布

TODAY — 本日精选

新闻

WEEKLY — 本周精选

新闻

MONTHLY — 本月精选

新闻