ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

用 Feast 构建 RAG 检索管线:Milvus 向量在线存储与 retrieve_online_documents_v2 实战指南

用 Feast 构建 RAG 检索管线:Milvus 向量在线存储与 retrieve_online_documents_v2 实战指南 用 Feast 构建 RAG 检索管线Milvus 向量在线存储与 retrieve_online_documents_v2 实战指南【免费下载链接】feastThe Open Source Feature Store for AI/ML项目地址: https://gitcode.com/GitHub_Trending/fe/feast本文以 Feast 仓库中 examples/rag 官方向导为主体讲解如何用 Feast 的 Feature View、向量在线存储Milvus Lite与大语言模型搭建一条完整的检索增强生成RAG管线从声明式定义带向量索引的文档特征、将预计算 embedding 物化到在线存储到用retrieve_online_documents_v2做余弦相似度检索并把上下文注入 LLM 提示词最终得到有据可依的问答结果。RAG 架构与 Feast 的角色RAGRetrieval-Augmented Generation将向量检索文档与大语言模型的上下文内学习In-Context-Learning结合先用向量相似度从文档库中找出与用户问题最相关的片段再把这些结构化/非结构化上下文拼入提示词让 LLM 基于证据作答。examples/rag/README.md 给出该示例选择 Feast 的五个理由在线实时检索特征对预计算好的文档 embedding 与其他结构化数据提供实时访问声明式特征定义数据科学家只需在一个 Python 文件中定义 feature view 和实体即可复用 Feast 的全部工程化能力版本管理、可发现的数据管线等向量检索能力依托 Feast 对 Milvus 等向量数据库的集成按余弦等相似度度量查找相关文档结构化与非结构化上下文混合一次检索同时拿到 embedding 与传统特征字段向 LLM 提示词注入更丰富的上下文版本化与可复用性跨团队协作时使用可发现、带版本的数据管线。值得注意的是Feast 的向量数据库能力目前处于 Alpha 阶段该能力已知稳定但仍有打磨空间且retrieve_online_documentsv1已建议弃用官方推荐迁移到retrieve_online_documents_v2v2。本示例正是 v2 用法docs/reference/alpha-vector-database.md 中的支持矩阵显示Milvus 是少数同时具备 Retrieval、Indexing、V2 支持与 Online Read 能力的后端之一。示例项目结构示例代码位于 examples/rag/feature_repo/各文件职责如下文件作用feature_repo/data/city_wikipedia_summaries_with_embeddings.parquet演示数据各城市 Wikipedia 摘要及已预计算的句向量Parquet 文件feature_repo/example_repo.py定义 Feast 的 Feature View 与实体feature_repo/feature_store.yaml配置离线/在线存储本地文件 Milvus Litefeature_repo/test_workflow.py演示定义、写入、检索特征的完整工作流examples/rag/milvus-quickstart.ipynb端到端 Notebook含 LLM 生成环节环境准备在仓库 examples/rag 中给出的依赖安装命令为pip install feast torch transformers openai由于在线存储选用 Milvus还需要安装 Feast 的 Milvus 扩展docs/reference/alpha-vector-database.md 中给出的官方安装方式仓库sdk/python/requirements下的锁定文件也确认了pymilvus/milvus-lite依赖pip install feast[milvus]本示例使用 Milvus 的本地文件实现Lite 模式数据落盘为data/online_store.db无需独立部署 Milvus 集群适合快速验证。定义向量特征视图example_repo.py 逐行解析整个检索能力的关键就在 feature_repo/example_repo.py 中不到 40 行的声明式定义from datetime import timedelta from feast import FeatureView, Field, FileSource from feast.data_format import ParquetFormat from feast.types import Float32, Array, String, ValueType from feast import Entity item Entity( nameitem_id, descriptionItem ID, value_typeValueType.INT64, ) parquet_file_path ./data/city_wikipedia_summaries_with_embeddings.parquet source FileSource( file_formatParquetFormat(), pathparquet_file_path, timestamp_fieldevent_timestamp, ) city_embeddings_feature_view FeatureView( namecity_embeddings, entities[item], schema[ Field( namevector, dtypeArray(Float32), vector_indexTrue, vector_search_metricCOSINE, ), Field(namestate, dtypeString), Field(namesentence_chunks, dtypeString), Field(namewiki_summary, dtypeString), ], sourcesource, ttltimedelta(hours2), )各要素说明Entityitem_id文档主键INT64用于标识每条摘要FileSource ParquetFormat离线数据源直接指向本地 Parquet 文件timestamp_fieldevent_timestamp指定事件时间列支撑 Feast 的时间语义vector字段dtypeArray(Float32)表示一个 384 维 float32 向量vector_indexTrue是一键开启向量索引的开关——从 SDK 源码结构看FeatureView会校验每个特征视图最多只能有一个vector_indexTrue的字段见 sdk/python/feast/feature_view.pyvector_search_metricCOSINE声明该索引使用余弦距离结构化伴随字段state州、sentence_chunks句子分块、wiki_summary摘要都是普通 String 特征。v2 API 的核心价值正在于此——检索命中向量后能同时返回这些非向量字段直接作为 LLM 上下文ttltimedelta(hours2)在线存储中特征的两小时过期时间对文档型数据可按需放大。定义好特征后在 feature_repo 目录下执行feast apply完成注册与基础设施初始化本示例中会创建 Milvus 集合并建立向量索引。在线存储配置feature_store.yaml 参数详解feature_repo/feature_store.yaml 的完整配置project: rag provider: local registry: data/registry.db online_store: type: milvus path: data/online_store.db vector_enabled: true embedding_dim: 384 index_type: FLAT metric_type: COSINE offline_store: type: file entity_key_serialization_version: 3 # By default, no_auth for authentication and authorization, other possible values kubernetes and oidc. auth: type: no_auth参数取值说明projectrag项目名参与集合命名与向量库标识providerlocal本地 Provider不部署 K8s/Helm 基础设施registrydata/registry.dbSQLite 注册表路径online_store.typemilvus在线存储使用 Milvuspath指向 Lite 模式数据文件无需独立服务vector_enabledtrue开启向量检索。Milvus 实现中若未开启会直接抛错Vector search is not enabled in the online store config见 milvus.py且 embedding 建索引与查询字段均依赖该开关milvus.py、L786-L881embedding_dim384向量维度必须与所选 embedding 模型输出一致。本例的sentence-transformers/all-MiniLM-L6-v2输出恰好是 384 维源码中该配置默认值为 128见 milvus.pyindex_typeFLAT暴力检索索引数据量小时精度优先metric_typeCOSINE与 Feature View 中vector_search_metric保持一致offline_store.typefile离线存储即本地文件Parquetentity_key_serialization_version3实体键序列化版本跨版本迁移时需关注auth.typeno_auth本地演示关闭认证可选kubernetes、oidc写入在线存储write_to_online_store演示脚本 feature_repo/test_workflow.py 的写入流程store FeatureStore(repo_path.) df pd.read_parquet(./data/city_wikipedia_summaries_with_embeddings.parquet) embedding_length len(df[vector][0]) print(fembedding length {embedding_length}) # 384 store.apply([city_embeddings_feature_view, item]) fields ( [f.name for f in city_embeddings_feature_view.features] city_embeddings_feature_view.entities [city_embeddings_feature_view.batch_source.timestamp_field] ) store.write_to_online_store(city_embeddings, df[fields][0:3])几个实操要点写入前对齐字段DataFrame 必须同时包含特征列vector、state、sentence_chunks、wiki_summary、实体列item_id与时间戳列event_timestamp脚本通过遍历 feature view 的features/entities/batch_source.timestamp_field自动拼出该列集避免手写列名出错store.apply(...)亦可走 Python SDK除了 README 中feast apply命令外test_workflow.py 展示了等价的 SDK 调用store.apply([city_embeddings_feature_view, item])增量写入示例只写入了df[fields][0:3]前 3 行验证链路时可按需放大行数底层行为从 Milvus 在线存储源码看feast apply/update阶段会对保留的每张表调用_get_or_create_collection确保集合存在删除的表会连同_v{N}版本兄弟集合一起清理milvus.py因此反复 apply 是幂等安全的。查询侧句向量生成与 retrieve_online_documents_v2 检索1. 生成问题 embeddingtest_workflow.py用与离线索引完全相同的模型sentence-transformers/all-MiniLM-L6-v2对问题文本做 embedding保证查询向量与文档向量在同一语义空间TOKENIZER sentence-transformers/all-MiniLM-L6-v2 MODEL sentence-transformers/all-MiniLM-L6-v2 def mean_pooling(model_output, attention_mask): token_embeddings model_output[0] input_mask_expanded ( attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() ) return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp( input_mask_expanded.sum(1), min1e-9 ) def run_model(sentences, tokenizer, model): encoded_input tokenizer(sentences, paddingTrue, truncationTrue, return_tensorspt) with torch.no_grad(): model_output model(**encoded_input) sentence_embeddings mean_pooling(model_output, encoded_input[attention_mask]) sentence_embeddings F.normalize(sentence_embeddings, p2, dim1) return sentence_embeddings这里有两处工程细节值得注意mean_pooling对 token 级输出做均值池化得到句向量F.normalize(..., p2, dim1)做 L2 归一化——对余弦距离而言归一化后的向量做内积即等价于余弦相似度这也是选择COSINE度量的配套做法。2. 向量相似度检索question the most populous city in the state of New York is New York query_embedding run_model(question, tokenizer, model) query query_embedding.detach().cpu().numpy().tolist()[0] features store.retrieve_online_documents_v2( features[ city_embeddings:vector, city_embeddings:item_id, city_embeddings:state, city_embeddings:sentence_chunks, city_embeddings:wiki_summary, ], queryquery, top_k3, ) print(features.to_df())retrieve_online_documents_v2是 Feast 面向向量检索的核心 APISDK 签名 还支持示例未用到的进阶能力query_string文本查询、query_image_bytes图像相似度检索、combine_with_text/text_weight/image_weight/combine_strategy多模态融合检索以及 OpenAI 风格的filters元数据过滤比较/复合过滤器。distance_metric参数默认为L2README 的检索示例中显式传入了distance_metricCOSINE以匹配索引度量。从源码结构看其执行链路SDK 层校验query/query_image_bytes/query_string至少提供其一后委托给在线存储实现Milvus 后端milvus.py会按project feature_view以及版本化开关计算集合名取不到 embedding 与 query_string 时抛出ValueError(Either embedding or query_string must be provided)组装output_fields [复合主键] 请求的特征列 [created_ts, event_ts]并断言所有字段都存在于集合 schema 中在集合字段中定位FLOAT_VECTOR/BINARY_VECTOR类型的向量列作为 ANN 检索字段load_collection后执行相似度搜索若携带filters且包含数值比较会检查集合字段是否具备原生数值类型对应 alpha-vector-database 文档 中提到的数值存储要求。返回的OnlineResponse.to_df()即得到如下结构示例输出节选每行包含命中文档的vector、item_id、state、sentence_chunks、wiki_summary以及event_timestamp等元数据列可直接作为提示词上下文。与 LLM 联动生成回答检索到 top-K 文档后将上下文格式化为提示词并交给 LLM。milvus-quickstart.ipynb 与 docs/reference/alpha-vector-database.md 给出了标准做法FULL_PROMPT format_documents(rag_context_data, BASE_PROMPT) from openai import OpenAI client OpenAI(api_keyos.environ.get(OPENAI_API_KEY)) response client.chat.completions.create( modelgpt-4o-mini, messages[ {role: system, content: FULL_PROMPT}, {role: user, content: question}, ], ) print(\n.join([c.message.content for c in response.choices]))对于问题 Which city has the largest population in New York?示例给出的模型回答为The largest city in New York is New York City, often referred to as NYC. It is the most populous city in the United States, with an estimated population of 8,335,897 in 2022.进阶方向与实践要点v1 → v2 迁移retrieve_online_documents已被官方标记为将来弃用建议新项目直接使用 v2——向量索引配置收敛到 Feature View 字段上且能同时检索非向量特征。长期规划是二者最终统一为get_online_features语义见 alpha-vector-database 文档其他向量后端支持矩阵中 PostgreSQLpgvector、Elasticsearch、Qdrant、ScyllaDB、SQLitesqlite-vec等各有取舍其中 Milvus、SQLite、ScyllaDB 实现了 v2 API。安装对应扩展如pip install feast[elasticsearch]、pip install feast[sqlite_vec]后修改feature_store.yaml的online_store段即可切换OpenAI 兼容的向量库 API若希望把 Feast 的向量库暴露给 Agent/工具调用框架可参考 alpha-vector-database 文档 中/v1/vector_stores系列端点任何含vector_indexTrue字段的 feature view 会自动获得确定性的vs_{hash}标识客户端可用纯文本查询触发服务端 embedding无需自己产出向量一致性提醒embedding_dim、vector_search_metricFeature View 侧与metric_type在线存储侧三处必须与 embedding 模型互相匹配本例统一为 384 维 COSINE数据规模与索引FLAT索引适合演示与小规模数据规模化时应评估 IVF 类索引与真实 Milvus 集群的替换演示数据边界示例数据是各城市 Wikipedia 摘要Parquet 文件位于 feature_repo/data/向量已预计算适合离线验证生产环境通常需要在管线中增加文档切分chunking与批量 embedding 步骤。小结本示例展示了 Feast 作为 RAG 基础设施的完整闭环用不到 40 行声明式 Python 定义带向量索引的特征视图example_repo.py用一份 YAML 把 Milvus Lite 配置为向量在线存储feature_store.yamlwrite_to_online_store物化文档 embeddingretrieve_online_documents_v2按余弦相似度取回 top-K 文档及其结构化字段最后注入 LLM 提示词生成有据可依的回答test_workflow.py。相比裸用向量数据库这条路线让文档检索纳入 Feast 统一的特征治理体系——声明式定义、版本化、在线实时读取——为在 RAG 场景中融合业务特征与文档语义留出了扩展空间。【免费下载链接】feastThe Open Source Feature Store for AI/ML项目地址: https://gitcode.com/GitHub_Trending/fe/feast创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表