> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # createVectorQueryTool() 그만큼`createVectorQueryTool()`함수는 벡터 저장소에 대한 의미 검색 Tool을 만듭니다. 필터링, 순위 재지정, 데이터베이스별 구성을 지원하고 벡터 저장소 백엔드와 통합됩니다. ## 기본 사용법 ```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'), }) ``` ## 매개변수 > **노트:** **매개변수 요구사항:**대부분의 필드는 생성 시 기본값으로 설정할 수 있습니다. 일부 필드는 요청 컨텍스트 또는 입력을 통해 런타임 시 재정의될 수 있습니다. 만약에 생성 및 런타임 모두에서 필수 필드가 누락되었습니다. 오류가 발생합니다. 던져졌다. 참고하세요`model`, `id`, and `description` can only be set at creation time. **id** (`string`): Custom ID for the tool. By default: 'VectorQuery {vectorStoreName} {indexName} Tool'. (Set at creation only.) **description** (`string`): Custom description for the tool. By default: 'Access the knowledge base to find information needed to answer user questions' (Set at creation only.) **model** (`EmbeddingModel`): Embedding model to use for vector search. (Set at creation only.) **vectorStoreName** (`string`): Name of the vector store to query. (Can be set at creation or overridden at runtime.) **indexName** (`string`): Name of the index within the vector store. (Can be set at creation or overridden at runtime.) **enableFilter** (`boolean`): Enable filtering of results based on metadata. (Set at creation only, but will be automatically enabled if a filter is provided in the request context.) (Default: `false`) **includeVectors** (`boolean`): Include the embedding vectors in the results. (Can be set at creation or overridden at runtime.) (Default: `false`) **includeSources** (`boolean`): Include the full retrieval objects in the results. (Can be set at creation or overridden at runtime.) (Default: `true`) **reranker** (`RerankConfig`): Options for reranking results. (Can be set at creation or overridden at runtime.) **reranker.model** (`MastraLanguageModel`): Language model to use for reranking **reranker.options** (`RerankerOptions`): Options for the reranking process **reranker.options.weights** (`WeightConfig`): Weights for scoring components (semantic: 0.4, vector: 0.4, position: 0.2) **reranker.options.topK** (`number`): Number of top results to return **databaseConfig** (`DatabaseConfig`): Database-specific configuration options for optimizing queries. (Can be set at creation or overridden at runtime.) **databaseConfig.pinecone** (`PineconeConfig`): Configuration specific to Pinecone vector store **databaseConfig.pinecone.namespace** (`string`): Pinecone namespace for organizing vectors **databaseConfig.pinecone.sparseVector** (`{ indices: number[]; values: number[]; }`): Sparse vector for hybrid search **databaseConfig.pgvector** (`PgVectorConfig`): Configuration specific to PostgreSQL with pgvector extension **databaseConfig.pgvector.minScore** (`number`): Minimum similarity score threshold for results **databaseConfig.pgvector.ef** (`number`): HNSW search parameter - controls accuracy vs speed tradeoff **databaseConfig.pgvector.probes** (`number`): IVFFlat probe parameter - number of cells to visit during search **databaseConfig.chroma** (`ChromaConfig`): Configuration specific to Chroma vector store **databaseConfig.chroma.where** (`Record`): Metadata filtering conditions **databaseConfig.chroma.whereDocument** (`Record`): Document content filtering conditions **providerOptions** (`Record>`): Provider-specific options for the embedding model (e.g., outputDimensionality). Only works with AI SDK EmbeddingModelV2 models. For V1 models, configure options when creating the model itself. **vectorStore** (`MastraVector | VectorStoreResolver`): Direct vector store instance or a resolver function for dynamic selection. Use a function for multi-tenant applications where the vector store is selected based on request context. When provided, vectorStoreName becomes optional. ## 보고 이 Tool은 다음을 포함하는 개체를 반환합니다. **relevantContext** (`string`): Combined text from the most relevant document chunks **sources** (`QueryResult[]`): Array of full retrieval result objects. Each object contains all information needed to reference the original document, chunk, and similarity score. ### `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개입니다. 이는 쿼리 요구 사항에 따라 조정될 수 있습니다. ## 필터의 예 ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), enableFilter: true, }) ``` 필터링이 활성화되면 Tool은 쿼리를 처리하여 의미 체계 검색과 결합되는 메타데이터 필터를 구성합니다. 프로세스는 다음과 같이 작동합니다. 1. 사용자가 "'버전' 필드가 2.0보다 큰 콘텐츠 찾기"와 같은 특정 필터 요구 사항을 사용하여 쿼리를 수행합니다. 2. Agent는 쿼리를 분석하고 적절한 필터를 구성합니다. ```typescript { "version": { "$gt": 2.0 } } ``` 이 Agent 중심 접근 방식은 다음과 같습니다. - 자연어 쿼리를 필터 사양으로 처리합니다. - 벡터 저장소별 필터 구문을 구현합니다. - 검색어를 필터 연산자로 변환합니다. 자세한 필터 구문 및 매장별 기능은 다음을 참조하세요.[Metadata Filters](https://mastra.zisheng.pro/ko/reference/rag/metadata-filters) documentation. Agent 기반 필터링의 작동 방식에 대한 예는 다음을 참조하세요.[Agent-Driven Metadata Filtering](https://github.com/mastra-ai/mastra/tree/main/examples/basics/rag/filter-rag) example. ## 재순위 예시 ```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**: ### 솔방울 구성 ```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], }, }, }, }) ``` **솔방울 특징:** - **네임스페이스**: 동일한 인덱스 내에서 서로 다른 데이터 세트를 분리합니다. - **희소 벡터**: 향상된 검색 품질을 위해 조밀한 임베딩과 희소 임베딩을 결합합니다. - **사용 사례**: 멀티 테넌트 애플리케이션, 하이브리드 의미 검색 **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 기능:** - **최소점수**: 품질이 낮은 일치 항목을 필터링합니다. - **ef (HNSW)**: HNSW 지수의 정확도와 속도 제어 - **프로브(IVFFlat)**: IVFFlat 지수의 재현율과 속도 제어 - **사용 사례**: 성능 튜닝, 품질 필터링 **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', }, }, }, }) ``` **크로마 기능:** - **어디**: 메타데이터 필드로 필터링 - **어디에문서**: 문서 내용으로 필터링 - **사용 사례**: 고급 필터링, 콘텐츠 기반 검색 **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 }, }, }) ``` **터보퍼퍼 기능:** - **일관성**: 중에서 선택하세요`strong` (default, read-your-writes) and `eventual` (lower latency) - **사용 사례**: 약간 오래된 데이터가 허용되는 지연 시간에 민감한 쿼리 **Multiple Configs**: ### 다중 데이터베이스 구성 ```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로 여러 벡터 저장소 지원 - 데이터베이스별 최적화가 자동으로 적용됩니다. - 유연한 배포 시나리오 ### 런타임 구성 재정의 런타임 시 데이터베이스 구성을 재정의하여 다양한 시나리오에 적응할 수 있습니다. ```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) - 부하에 따라 성능 매개변수 조정 - 요청별로 다른 필터링 전략 적용 ## 예: 요청 컨텍스트 사용 ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) ``` 요청 컨텍스트를 사용하는 경우 요청 컨텍스트를 통해 실행 시 필수 매개변수를 제공하세요. ```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, }) ``` 요청 컨텍스트에 대한 자세한 내용은 다음을 참조하세요. - [Agent 요청 컨텍스트](https://mastra.zisheng.pro/ko/docs/server/request-context) - [요청 컨텍스트](https://mastra.zisheng.pro/ko/docs/server/request-context) ## Mastra 서버 없이 사용 이 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) ``` ## 다중 테넌트 애플리케이션을 위한 동적 벡터 저장소 각 테넌트에 격리된 데이터(예: 별도의 PostgreSQL 스키마)가 있는 다중 테넌트 애플리케이션의 경우 정적 벡터 저장소 인스턴스 대신 확인자 함수를 전달할 수 있습니다. 이 함수는 요청 컨텍스트를 수신하고 현재 테넌트에 대한 적절한 벡터 저장소를 반환할 수 있습니다. ```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` supports runtime-defined configuration and enables: - **스키마 격리**: 별도의 PostgreSQL 스키마에 있는 각 테넌트의 데이터 - **데이터베이스 격리**: 테넌트별로 다른 데이터베이스 인스턴스로 라우팅 - **동적 구성**: 요청 컨텍스트에 따라 벡터 저장소 설정을 조정합니다. ## Tool 세부정보 이 Tool은 다음을 사용하여 생성됩니다. - **ID**: `VectorQuery {vectorStoreName} {indexName} Tool` - **입력 스키마**: queryText 및 필터 객체가 필요합니다. - **출력 스키마**: 관련 컨텍스트 문자열을 반환합니다. ## 관련된 - [순위 재지정()](https://mastra.zisheng.pro/ko/reference/rag/rerank) - [createGraphRAGTool](https://mastra.zisheng.pro/ko/reference/tools/graph-rag-tool)