4月6日(RAG系统)
2026/4/6 10:31:13 网站建设 项目流程
RAG内存效率提高32倍使用二进制量化技术使RAG的内存效率提高32倍工作流程摄许文档并生成二进制嵌入向量创建二进制向量索引并将嵌入向量存储在向量数据库检索与用户查询相似度最高的前K个文档大模型基于补充上下文生成回复加载数据我们使用LlamaIndex的目录读取工具来导入文档。该工具能够读取多种数据格式from llama_index.core import SimpleDirectoryReader loader SimpleDirectoryReader( input_dirdocs_dir, required_exts[.pdf], recursiveTrue ) docs loader.load_data() documents [doc.text for doc in docs]生成二进制嵌入接下来我们生成浮点32位格式的文本嵌入向量并将其转换为二进制向量从而使内存占用与存储空间缩减至原来的32分之1import numpy as np from llama_index.embeddings.huggingface import HuggingFaceEmbedding embed_model HuggingFaceEmbedding( model_nameBAAI/bge-large-en-v1.5, trust_remote_codeTrue, cache_folder./hf_cache ) for context in batch_iterate(documents, batch_size512): # Generate float32 vector embeddings batch_embeds embed_model.get_text_embedding_batch(context) # Convert float32 vectors to binary vectors embeds_array np.array(batch_embeds) binary_embeds np.where(embeds_array 0, 1, 0).astype(np.uint8) # Convert to bytes array packed_embeds np.packbits(binary_embeds, axis1) byte_embeds [vec.tobytes() for vec in packed_embeds] binary_embeddings.extend(byte_embeds)这被称为二进制量化向量索引完成二进制量化后我们将向量存储到向量数据库中以便更高效的检索from pymilvus import MilvusClient, DataType # Initialize client and schema client MilvusClient(milvus_binary_quantized.db) schema client.create_schema(auto_idTrue, enable_dynamic_fieldsTrue) # Add fields to schema schema.add_field(field_namecontext, datatypeDataType.VARCHAR) schema.add_field(field_namebinary_vector, datatypeDataType.BINARY_VECTOR) # Create index parameters for binary vectors index_params client.prepare_index_params() index_params.add_index( field_namebinary_vector, index_namebinary_vector_index, index_typeBIN_FLAT, # Exact search for binary vectors metric_typeHAMMING # Hamming distance for binary vectors ) # Create collection with schema and index client.create_collection( collection_namefastest-rag, schemaschema, index_paramsindex_params ) # Insert data to index client.insert( collection_namefastest-rag, data[ {context: context, binary_vector: binary_embedding} for context, binary_embedding in zip(batch_context, binary_embeddings) ] )检索在检索阶段我们执行以下操作对用户查询进行嵌入处理并将其转化为二进制量化采用汉明间距作为向量度量指标来对比二进质量化检索出相似度最高的前5个文本块并将检索到的文本块添加至上下文信息中# Generate float32 query embedding query_embedding embed_model.get_query_embedding(query) # Apply binary quantization to query binary_query binary_quantize(query_embedding) # Perform similarity search using Milvus search_results client.search( collection_namefastest-rag, data[binary_query], anns_fieldbinary_vector, search_params{metric_type: HAMMING}, output_fields[context], limit5 # Retrieve top 5 similar chunks ) # Store retrieved context full_context [] for res in search_results: context res[payload][context] full_context.append(context)生成接下来我们利用指令模型构建生成流程我们将查询与检索到的上下文内容一同写入提示词模板再传给大语言模型from llama_index.llms.groq import Groq from llama_index.core.base.llms.types import ( ChatMessage, MessageRole ) llm Groq( modelmoonshotai/kimi-k2-instruct, api_keygroq_api_key, temperature0.5, max_tokens1000 ) prompt_template ( Context information is below.\n ---------------------\n CONTEXT: {context}\n ---------------------\n Given the context information above think step by step to answer the users query in a crisp and concise manner. In case you dont know the answer say I dont know!.\n QUERY: {query}\n ANSWER: ) query Provide concise breakdown of the document prompt prompt_template.format(contextfull_context, queryquery) user_msg ChatMessage(roleMessageRole.USER, contentprompt) # Stream response from LLM streaming_response llm.stream_complete(user_msg.content)Kimi-K2 作为 LLM 在 Groq托管上托管经过这一套流程我们可以得到在30毫秒钟内完成3600万加向量检索一秒内生成回复我们构建了速度最快的RAG技术栈借助二进制量化BQ实现高效检索代码仓库https://github.com/patchy631/ai-engineering-hub/tree/main/fastest-rag-milvus-groqRAG高阶技巧如何实现窗口上下文检索基础RAG存在的问题及解决方案RAG是一种结合了检索和生成的AI应用落地方案它可以根据给定的问题生成回答同时利用外部知识库来增强生成和质量的多样性。RA的核心思想是将问题和知识库中的文档进行匹配然后将匹配到的文档作为生成模型的输入从而生成更加相关和丰富的回答RAG的检索流程RAG的检索流程可以分为以下几个步骤加载文档将各种格式的文档加载后转换为文档例如PDF加载为文本数据或者将表格转换为多个键值对将文档拆分为适合存储的向量单元以便于向量存储以及检索时文档的匹配将文档用向量表示将向量化后的分块数据存入数据库根据问题和文档向量计算它们之间的相似度然后根据相似度的高低选择最相关的文档作为检索结果将解索到的文档作为生成模型的输入根据问题生成回答问题如果我们分块拆的太大同一块中非相关的内容就越多对问题的检索匹配度影响越大会导致检索的不准确如果分块拆的最小检索匹配度会提高。然而在最后的查询环节给大语言提供的上下文信息支撑较少导致回答不准确解决方案窗口上下文检索解决这个问题一般采用的方案是在拆分时尽量将文本切分到最小的语义单元。这样在检索时不直接使用匹配到的文档而是通过匹配到的文档扩展及上下文整合在一起再投递给大语言使用。这样既可以提高检索精度又可以保证上下文准确性从而提高生成质量和多样性具体步骤在拆分时将文本拆分为最小的语义单元在检索时根据问题和文档向量计算它们之间的相似度然后选择最相关的文档作为检索结果同时记录下他们的编号在查询时根据检索结果的编号从文本中获取他们的上下文信息然后将它们拼接成一个完整的文档作为生成模型的输入。根据问题生成答案窗口上下文检索实践分块编码并写入原数据检索时通过元数据中的顺序分块编码来查找上下文

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询