> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # createVectorQueryTool() `createVectorQueryTool()` 函数会创建一个在 vector store 上运行语意搜索的 Tool。它支持筛选、重新排序、数据库特定设置,以及与 vector store backend 集成。 ## 基本用法 ```typescript import { createVectorQueryTool } from '@mastra/rag' import { ModelRouterEmbeddingModel } from '@mastra/core/llm' const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) ``` ## 参数 > **备注:** **参数需求:** 大多数字段都可在创建时设为默认值。部分字段可在运行阶段通过 request context 或输入覆写。若创建时与运行阶段都未提供必要字段,系统将掷回错误。请注意,`model`、`id` 与 `description` 只能在创建时设置。 **id** (`string`): 自订 Tool ID。缺省为:'VectorQuery {vectorStoreName} {indexName} Tool'。(只能在创建时设置。) **description** (`string`): 自订 Tool 说明。缺省为:'Access the knowledge base to find information needed to answer user questions'(只能在创建时设置。) **model** (`EmbeddingModel`): 用于矢量搜索的 embedding 模型。(只能在创建时设置。) **vectorStoreName** (`string`): 要查找的 vector store 名称。(可在创建时设置,或在运行阶段覆写。) **indexName** (`string`): vector store 中的索引名称。(可在创建时设置,或在运行阶段覆写。) **enableFilter** (`boolean`): 激活根据中继数据筛选结果的功能。(只能在创建时设置,但若 request context 提供 filter,则会自动激活。) (Default: `false`) **includeVectors** (`boolean`): 在结果中包含 embedding 矢量。(可在创建时设置,或在运行阶段覆写。) (Default: `false`) **includeSources** (`boolean`): 在结果中包含完整截取对象。(可在创建时设置,或在运行阶段覆写。) (Default: `true`) **reranker** (`RerankConfig`): 重新排序结果的选项。(可在创建时设置,或在运行阶段覆写。) **reranker.model** (`MastraLanguageModel`): 用于重新排序的语言模型 **reranker.options** (`RerankerOptions`): 重新排序进程的选项 **reranker.options.weights** (`WeightConfig`): 各评分组成部分的权重(semantic:0.4、vector:0.4、position:0.2) **reranker.options.topK** (`number`): 要回传的最高排名结果数量 **databaseConfig** (`DatabaseConfig`): 用于优化查找的数据库特定设置选项。(可在创建时设置,或在运行阶段覆写。) **databaseConfig.pinecone** (`PineconeConfig`): Pinecone vector store 的特定设置 **databaseConfig.pinecone.namespace** (`string`): 用于整理矢量的 Pinecone namespace **databaseConfig.pinecone.sparseVector** (`{ indices: number[]; values: number[]; }`): 用于混合搜索的 sparse vector **databaseConfig.pgvector** (`PgVectorConfig`): 使用 pgvector 扩展之 PostgreSQL 的特定设置 **databaseConfig.pgvector.minScore** (`number`): 结果的最低相似度分数门槛 **databaseConfig.pgvector.ef** (`number`): HNSW 搜索参数,用于控制准确度与速度的取舍 **databaseConfig.pgvector.probes** (`number`): IVFFlat probe 参数,即搜索期间要造访的 cell 数量 **databaseConfig.chroma** (`ChromaConfig`): Chroma vector store 的特定设置 **databaseConfig.chroma.where** (`Record`): 中继数据筛选条件 **databaseConfig.chroma.whereDocument** (`Record`): 文档内容筛选条件 **providerOptions** (`Record>`): embedding 模型的 Provider 特定选项(例如 outputDimensionality)。仅适用于 AI SDK EmbeddingModelV2 模型。若使用 V1 模型,请在创建模型本身时设置选项。 **vectorStore** (`MastraVector | VectorStoreResolver`): 直接提供 vector store instance,或提供用于动态选取的 resolver function。多租户应用程序可使用函数,根据 request context 选取 vector store。提供此值后,vectorStoreName 会变成选填。 ## 回传值 此 Tool 会回传具有下列字段的对象: **relevantContext** (`string`): 由最相关文档区块合并而成的文本 **sources** (`QueryResult[]`): 完整截取结果对象的数组。每个对象都包含参照原始文档、区块与相似度分数所需的全部信息。 ### `QueryResult` 对象结构 ```typescript { id: string; // Unique chunk/document identifier metadata: any; // All metadata fields (document ID, etc.) vector: number[]; // Embedding vector (if available) score: number; // Similarity score for this retrieval document: string; // Full chunk/document text (if available) } ``` ## 缺省 Tool 说明 缺省说明着重于: - 从保存的知识中找出相关信息 - 回答用户问题 - 截取事实内容 ## 结果处理 此 Tool 会根据用户的查找决定回传的结果数量,缺省为 10 笔。可依查找需求调整此数量。 ## 使用 filter 的范例 ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), enableFilter: true, }) ``` 激活筛选后,此 Tool 会处理查找以建构中继数据 filter,再与语意搜索结合。进程如下: 1. 用户提出具有特定筛选需求的查找,例如「寻找 `version` 字段大于 2.0 的内容」 2. Agent 分析查找并建构适当的 filter: ```typescript { "version": { "$gt": 2.0 } } ``` 这种由 Agent 驱动的方法会: - 将自然语言查找处理成 filter 规格 - 实作 vector store 特定的 filter 语法 - 将查找词汇转换为 filter operator 如需 filter 语法与 store 特定功能的详细信息,请参阅 [Metadata filter](https://mastra.zisheng.pro/reference/rag/metadata-filters) 文档。 如需 Agent 驱动筛选的运作范例,请参阅 [Agent 驱动的中继数据筛选](https://github.com/mastra-ai/mastra/tree/main/examples/basics/rag/filter-rag)范例。 ## 重新排序范例 ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'milvus', indexName: 'documentation', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), reranker: { model: 'openai/gpt-5.6-sol', options: { weights: { semantic: 0.5, // Semantic relevance weight vector: 0.3, // Vector similarity weight position: 0.2, // Original position weight }, topK: 5, }, }, }) ``` 重新排序会结合下列因素,以提升结果品质: - 语意相关性:使用以 LLM 为基础的文本相似度评分 - 矢量相似度:原始矢量距离分数 - 位置偏差:考量原始结果排序 - 查找分析:根据查找特性进行调整 Reranker 会处理初始矢量搜索结果,并回传针对相关性优化后重新排序的清单。 ## 自订说明范例 ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), description: 'Search through document archives to find relevant information for answering questions about company policies and procedures', }) ``` 此范例示范如何针对特定使用情境自订 Tool 说明,同时保留信息截取的内核用途。 ## 数据库特定设置范例 `databaseConfig` 参数让你能使用各矢量数据库的特定功能与优化。这些设置会在运行查找时自动套用。 **Pinecone**: ### Pinecone 设置 ```typescript const pineconeQueryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { pinecone: { namespace: 'production', // Organize vectors by environment sparseVector: { // Enable hybrid search indices: [0, 1, 2, 3], values: [0.1, 0.2, 0.15, 0.05], }, }, }, }) ``` **Pinecone 功能:** - **Namespace**:在同一个索引中隔离不同数据集 - **Sparse Vector**:结合 dense 与 sparse embedding,以提升搜索品质 - **使用情境**:多租户应用程序、混合语意搜索 **pgVector**: ### pgVector 设置 ```typescript const pgVectorQueryTool = createVectorQueryTool({ vectorStoreName: 'postgres', indexName: 'embeddings', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { pgvector: { minScore: 0.7, // Only return results above 70% similarity ef: 200, // Higher value = better accuracy, slower search probes: 10, // For IVFFlat: more probes = better recall }, }, }) ``` **pgVector 功能:** - **minScore**:筛除低品质的相符结果 - **ef (HNSW)**:控制 HNSW 索引的准确度与速度取舍 - **probes (IVFFlat)**:控制 IVFFlat 索引的召回率与速度取舍 - **使用情境**:性能调校、品质筛选 **Chroma**: ### Chroma 设置 ```typescript const chromaQueryTool = createVectorQueryTool({ vectorStoreName: 'chroma', indexName: 'documents', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { chroma: { where: { // Metadata filtering category: 'technical', status: 'published', }, whereDocument: { // Document content filtering $contains: 'API', }, }, }, }) ``` **Chroma 功能:** - **where**:依中继数据字段筛选 - **whereDocument**:依文档内容筛选 - **使用情境**:高端筛选、内容式搜索 **Turbopuffer**: ### Turbopuffer 设置 ```typescript const turbopufferQueryTool = createVectorQueryTool({ vectorStoreName: 'turbopuffer', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { turbopuffer: { consistency: 'eventual', // Lower latency, recently written data may not be visible yet }, }, }) ``` **Turbopuffer 功能:** - **consistency**:选择 `strong`(缺省,可读取自己的写入)或 `eventual`(延迟较低) - **使用情境**:可接受数据稍旧、但对延迟敏感的查找 **多项设置**: ### 多数据库设置 ```typescript // Configure for multiple databases (useful for dynamic stores) const multiDbQueryTool = createVectorQueryTool({ vectorStoreName: 'dynamic-store', // Will be set at runtime indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { pinecone: { namespace: 'default', }, pgvector: { minScore: 0.8, ef: 150, }, chroma: { where: { type: 'documentation' }, }, }, }) ``` **多项设置的优点:** - 使用单一 Tool 支持多个 vector store - 自动套用数据库特定优化 - 弹性的部署情境 ### 覆写运行阶段设置 你可以在运行阶段覆写数据库设置,以配合不同情境: ```typescript import { RequestContext } from '@mastra/core/request-context' const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), databaseConfig: { pinecone: { namespace: 'development', }, }, }) // Override at runtime const requestContext = new RequestContext() requestContext.set('databaseConfig', { pinecone: { namespace: 'production', // Switch to production namespace }, }) const response = await agent.generate('Find information about deployment', { requestContext, }) ``` 此方法可让你: - 在不同环境间切换(dev/staging/prod) - 根据负载调整性能参数 - 为每个请求套用不同的筛选策略 ## 范例:使用 request context ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) ``` 使用 request context 时,请在运行阶段通过 request context 提供必要参数: ```typescript const requestContext = new RequestContext<{ vectorStoreName: string indexName: string topK: number filter: VectorFilter databaseConfig: DatabaseConfig }>() requestContext.set('vectorStoreName', 'my-store') requestContext.set('indexName', 'my-index') requestContext.set('topK', 5) requestContext.set('filter', { category: 'docs' }) requestContext.set('databaseConfig', { pinecone: { namespace: 'runtime-namespace' }, }) requestContext.set('model', 'openai/text-embedding-3-small') const response = await agent.generate('Find documentation from the knowledge base.', { requestContext, }) ``` 如需 request context 的详细信息,请参阅: - [Agent Request Context](https://mastra.zisheng.pro/docs/server/request-context) - [Request Context](https://mastra.zisheng.pro/docs/server/request-context) ## 不使用 Mastra server 此 Tool 可单独使用,以截取符合查找的文档: ```typescript import { RequestContext } from '@mastra/core/request-context' import { createVectorQueryTool } from '@mastra/rag' import { PgVector } from '@mastra/pg' const pgVector = new PgVector({ id: 'pg-vector', connectionString: process.env.POSTGRES_CONNECTION_STRING!, }) const vectorQueryTool = createVectorQueryTool({ vectorStoreName: 'pgVector', // optional since we're passing in a store vectorStore: pgVector, indexName: 'embeddings', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) const requestContext = new RequestContext() const queryResult = await vectorQueryTool.execute({ queryText: 'foo', topK: 1 }, { requestContext }) console.log(queryResult.sources) ``` ## 多租户应用程序的动态 vector store 若多租户应用程序会隔离各租户的数据(例如各自使用不同 PostgreSQL schema),你可以传入 resolver function,而不是静态 vector store instance。此函数会接收 request context,并可回传目前租户适用的 vector store: ```typescript import { createVectorQueryTool, VectorStoreResolver } from '@mastra/rag' import { PgVector } from '@mastra/pg' // Cache for tenant-specific vector stores const vectorStoreCache = new Map() // Resolver function that returns the correct vector store based on tenant const vectorStoreResolver: VectorStoreResolver = async ({ requestContext }) => { const tenantId = requestContext?.get('tenantId') if (!tenantId) { throw new Error('tenantId is required in request context') } // Return cached instance or create new one if (!vectorStoreCache.has(tenantId)) { vectorStoreCache.set( tenantId, new PgVector({ id: `pg-vector-${tenantId}`, connectionString: process.env.POSTGRES_CONNECTION_STRING!, schemaName: `tenant_${tenantId}`, // Each tenant has their own schema }), ) } return vectorStoreCache.get(tenantId)! } const vectorQueryTool = createVectorQueryTool({ indexName: 'embeddings', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), vectorStore: vectorStoreResolver, // Dynamic resolution! }) // Usage with tenant context const requestContext = new RequestContext() requestContext.set('tenantId', 'acme-corp') const result = await vectorQueryTool.execute( { queryText: 'company policies', topK: 5 }, { requestContext }, ) ``` 此模式类似 `Agent.memory` 支持运行阶段定义设置的方式,并提供下列能力: - **Schema 隔离**:将各租户的数据放在不同 PostgreSQL schema 中 - **数据库隔离**:将各租户路由至不同的 database instance - **动态设置**:根据 request context 调整 vector store 设置 ## Tool 详细信息 此 Tool 会使用下列设置创建: - **ID**: `VectorQuery {vectorStoreName} {indexName} Tool` - **输入 schema**:需要 queryText 与 filter 对象 - **输出 schema**:回传 relevantContext 字符串 ## 相关内容 - [rerank()](https://mastra.zisheng.pro/reference/rag/rerank) - [createGraphRAGTool](https://mastra.zisheng.pro/reference/tools/graph-rag-tool)