> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # RAG 系统中的检索 存储嵌入后,需要检索相关数据块来回答用户查询。 Mastra 提供灵活的检索选项,支持语义搜索、过滤和重排序。 ## 检索的工作原理 1. 使用生成文档嵌入时的同一模型,将用户查询转换为嵌入 2. 通过向量相似度将该嵌入与存储的嵌入进行比较 3. 检索最相似的数据块,并可以选择: - 按 metadata 过滤 - 重排序以提高相关性 - 通过知识图谱处理 ## 基本检索 最简单的方法是直接进行语义搜索。此方法使用向量相似度查找语义上与查询相似的数据块: ```ts import { embed } from 'ai' import { PgVector } from '@mastra/pg' import { ModelRouterEmbeddingModel } from '@mastra/core/llm' // Convert query to embedding const { embedding } = await embed({ value: 'What are the main points in the article?', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) // Query vector store const pgVector = new PgVector({ id: 'pg-vector', connectionString: process.env.POSTGRES_CONNECTION_STRING, }) const results = await pgVector.query({ indexName: 'embeddings', queryVector: embedding, topK: 10, }) // Display results console.log(results) ``` `topK` 参数指定向量搜索最多返回多少个最相似结果。 结果同时包含文本内容和相似度分数: ```ts [ { text: 'Climate change poses significant challenges...', score: 0.89, metadata: { source: 'article1.txt' }, }, { text: 'Rising temperatures affect crop yields...', score: 0.82, metadata: { source: 'article1.txt' }, }, ] ``` ## 高级检索选项 ### Metadata 过滤 根据 metadata 字段过滤结果,以缩小搜索范围。这种将向量相似度搜索与 metadata 过滤器结合的方法有时称为混合向量搜索,因为它融合了语义搜索和结构化过滤条件。 当文档来自不同来源、不同时间段或具有特定属性时,此功能很有用。Mastra 提供统一的 MongoDB 风格查询语法,适用于所有受支持的向量存储。 有关可用运算符和语法的详细信息,请参阅 [Metadata 过滤器参考](https://mastra.zisheng.pro/reference/rag/metadata-filters)。 基本过滤示例: ```ts // Simple equality filter const results = await pgVector.query({ indexName: 'embeddings', queryVector: embedding, topK: 10, filter: { source: 'article1.txt', }, }) // Numeric comparison const results = await pgVector.query({ indexName: 'embeddings', queryVector: embedding, topK: 10, filter: { price: { $gt: 100 }, }, }) // Multiple conditions const results = await pgVector.query({ indexName: 'embeddings', queryVector: embedding, topK: 10, filter: { category: 'electronics', price: { $lt: 1000 }, inStock: true, }, }) // Array operations const results = await pgVector.query({ indexName: 'embeddings', queryVector: embedding, topK: 10, filter: { tags: { $in: ['sale', 'new'] }, }, }) // Logical operators const results = await pgVector.query({ indexName: 'embeddings', queryVector: embedding, topK: 10, filter: { $or: [{ category: 'electronics' }, { category: 'accessories' }], $and: [{ price: { $gt: 50 } }, { price: { $lt: 200 } }], }, }) ``` Metadata 过滤的常见用例: - 按文档来源或类型过滤 - 按日期范围过滤 - 按特定类别或标签过滤 - 按数值范围过滤(例如价格、评分) - 组合多个条件进行精确查询 - 按文档属性过滤(例如语言、作者) ### Vector Query Tool 有时需要让 Agent 直接查询向量数据库。Vector Query Tool 让 Agent 负责检索决策,并根据 Agent 对用户需求的理解,将语义搜索与可选的过滤和重排序结合起来。 ```ts import { createVectorQueryTool } from '@mastra/rag' import { ModelRouterEmbeddingModel } from '@mastra/core/llm' const vectorQueryTool = createVectorQueryTool({ vectorStoreName: 'pgVector', indexName: 'embeddings', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) ``` 创建 Tool 时,请特别注意其名称和描述,它们帮助 Agent 理解何时以及如何使用检索能力。例如,可以将其命名为 "SearchKnowledgeBase",并描述为“搜索我们的文档,查找有关 X 主题的相关信息”。 这在以下情况下尤其有用: - Agent 需要在运行时决定检索哪些信息 - 检索过程需要复杂的决策 - 希望 Agent 根据上下文组合多种检索策略 #### 数据库特定配置 Vector Query Tool 支持数据库特定配置,可使用不同向量存储的独特功能和优化。 > **备注:** 这些配置用于命名空间、性能调优和过滤等**查询时选项**,而不是数据库连接设置。 > > 连接凭据(URL、身份验证 token)在实例化向量存储类时配置(例如 `new LibSQLVector({ url: '...' })`)。 ```ts import { createVectorQueryTool } from '@mastra/rag' import { ModelRouterEmbeddingModel } from '@mastra/core/llm' // Pinecone with namespace const pineconeQueryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { pinecone: { namespace: 'production', // Isolate data by environment }, }, }) // pgVector with performance tuning const pgVectorQueryTool = createVectorQueryTool({ vectorStoreName: 'postgres', indexName: 'embeddings', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { pgvector: { minScore: 0.7, // Filter low-quality results ef: 200, // HNSW search parameter probes: 10, // IVFFlat probe parameter }, }, }) // Chroma with advanced filtering const chromaQueryTool = createVectorQueryTool({ vectorStoreName: 'chroma', indexName: 'documents', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { chroma: { where: { category: 'technical' }, whereDocument: { $contains: 'API' }, }, }, }) // LanceDB with table specificity const lanceQueryTool = createVectorQueryTool({ vectorStoreName: 'lance', indexName: 'documents', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { lance: { tableName: 'myVectors', // Specify which table to query includeAllColumns: true, // Include all metadata columns in results }, }, }) ``` **主要优势:** - **Pinecone 命名空间**:按租户、环境或数据类型组织向量 - **pgVector 优化**:使用 ef/probes 参数控制搜索准确度和速度 - **质量过滤**:设置最低相似度阈值,提高结果相关性 - **LanceDB 表**:将数据分隔到不同表中,以改善组织方式和性能 - **运行时灵活性**:根据上下文在运行时覆盖配置 **常见用例:** - 使用 Pinecone 命名空间的多租户应用 - 高负载场景中的性能优化 - 特定于环境的配置(dev/staging/prod) - 经过质量门控的搜索结果 - 使用 LanceDB 的嵌入式文件型向量存储,适用于边缘部署场景 还可以使用请求上下文在运行时覆盖这些配置: ```ts import { RequestContext } from '@mastra/core/request-context' const requestContext = new RequestContext() requestContext.set('databaseConfig', { pinecone: { namespace: 'runtime-namespace', }, }) await pineconeQueryTool.execute({ queryText: 'search query' }, { mastra, requestContext }) ``` 有关详细配置选项和高级用法,请参阅 [Vector Query Tool 参考](https://mastra.zisheng.pro/reference/tools/vector-query-tool)。 ### 向量存储提示词 向量存储提示词为每种向量数据库实现定义查询模式和过滤能力。 实现过滤时,必须在 Agent 的 instructions 中加入这些提示词,以指定各向量存储实现的有效运算符和语法。 **pgVector**: ```ts import { PGVECTOR_PROMPT } from '@mastra/pg' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${PGVECTOR_PROMPT} `, tools: { vectorQueryTool }, }) ``` **Pinecone**: ```ts import { PINECONE_PROMPT } from '@mastra/pinecone' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${PINECONE_PROMPT} `, tools: { vectorQueryTool }, }) ``` **Qdrant**: ```ts import { QDRANT_PROMPT } from '@mastra/qdrant' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${QDRANT_PROMPT} `, tools: { vectorQueryTool }, }) ``` **Chroma**: ```ts import { CHROMA_PROMPT } from '@mastra/chroma' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${CHROMA_PROMPT} `, tools: { vectorQueryTool }, }) ``` **Astra**: ```ts import { ASTRA_PROMPT } from '@mastra/astra' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${ASTRA_PROMPT} `, tools: { vectorQueryTool }, }) ``` **libSQL**: ```ts import { LIBSQL_PROMPT } from '@mastra/libsql' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${LIBSQL_PROMPT} `, tools: { vectorQueryTool }, }) ``` **Upstash**: ```ts import { UPSTASH_PROMPT } from '@mastra/upstash' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${UPSTASH_PROMPT} `, tools: { vectorQueryTool }, }) ``` **Vectorize**: ```ts import { VECTORIZE_PROMPT } from '@mastra/vectorize' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${VECTORIZE_PROMPT} `, tools: { vectorQueryTool }, }) ``` **MongoDB**: ```ts import { MONGODB_PROMPT } from '@mastra/mongodb' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${MONGODB_PROMPT} `, tools: { vectorQueryTool }, }) ``` **OpenSearch**: ```ts import { OPENSEARCH_PROMPT } from '@mastra/opensearch' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${OPENSEARCH_PROMPT} `, tools: { vectorQueryTool }, }) ``` **OracleDB**: ```ts import { ORACLEDB_PROMPT } from '@mastra/oracledb' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${ORACLEDB_PROMPT} `, tools: { vectorQueryTool }, }) ``` **S3Vectors**: ```ts import { S3VECTORS_PROMPT } from '@mastra/s3vectors' export const ragAgent = new Agent({ id: 'rag-agent', name: 'RAG Agent', model: 'openai/gpt-5.6-sol', instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${S3VECTORS_PROMPT} `, tools: { vectorQueryTool }, }) ``` ### 重排序 初始向量相似度搜索有时会忽略细粒度相关性。重排序需要更多计算资源,但算法更准确,可通过以下方式改善结果: - 考虑词序和精确匹配 - 应用更高级的相关性评分 - 在查询和文档之间使用称为 cross-attention 的方法 重排序的用法如下: ```ts import { rerankWithScorer as rerank, MastraAgentRelevanceScorer } from '@mastra/rag' // Get initial results from vector search const initialResults = await pgVector.query({ indexName: 'embeddings', queryVector: queryEmbedding, topK: 10, }) // Create a relevance scorer const relevanceProvider = new MastraAgentRelevanceScorer( 'relevance-scorer', 'openai/gpt-5.6-sol', ) // Re-rank the results const rerankedResults = await rerank({ results: initialResults, query, scorer: relevanceProvider, options: { weights: { semantic: 0.5, // How well the content matches the query semantically vector: 0.3, // Original vector similarity score position: 0.2, // Preserves original result ordering }, topK: 10, }, }) ``` 权重控制不同因素对最终排序的影响: - `semantic`:值越高,越优先考虑语义理解和与查询的相关性 - `vector`:值越高,越倾向原始向量相似度分数 - `position`:值越高,越有助于保持结果的原始顺序 > **备注:** 要让语义评分在重排序期间正常工作,每个结果的 `metadata.text` 字段都必须包含文本内容。 也可以使用 Cohere 或 ZeroEntropy 等其他相关性评分 Provider: ```ts const relevanceProvider = new CohereRelevanceScorer('rerank-v3.5') ``` ```ts const relevanceProvider = new ZeroEntropyRelevanceScorer('zerank-1') ``` 重排序结果将向量相似度与语义理解结合,以提高检索质量。 有关重排序的更多详细信息,请参阅 [rerank()](https://mastra.zisheng.pro/reference/rag/rerankWithScorer) 方法。 有关沿数据块之间连接进行的图检索,请参阅 [GraphRAG](https://mastra.zisheng.pro/guides/rag/graph-rag) 文档。