본문으로 건너뛰기

createVectorQueryTool()

그만큼createVectorQueryTool()함수는 벡터 저장소에 대한 의미 검색 Tool을 만듭니다. 필터링, 순위 재지정, 데이터베이스별 구성을 지원하고 벡터 저장소 백엔드와 통합됩니다.

기본 사용법
기본 사용법에 대한 직접 링크

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
= false
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.)

includeVectors?:

boolean
= false
Include the embedding vectors in the results. (Can be set at creation or overridden at runtime.)

includeSources?:

boolean
= true
Include the full retrieval objects in the results. (Can be set at creation or overridden at runtime.)

reranker?:

RerankConfig
Options for reranking results. (Can be set at creation or overridden at runtime.)
RerankConfig

model:

MastraLanguageModel
Language model to use for reranking

options?:

RerankerOptions
Options for the reranking process
RerankerOptions

weights?:

WeightConfig
Weights for scoring components (semantic: 0.4, vector: 0.4, position: 0.2)

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
PineconeConfig

namespace?:

string
Pinecone namespace for organizing vectors

sparseVector?:

{ indices: number[]; values: number[]; }
Sparse vector for hybrid search

pgvector?:

PgVectorConfig
Configuration specific to PostgreSQL with pgvector extension
PgVectorConfig

minScore?:

number
Minimum similarity score threshold for results

ef?:

number
HNSW search parameter - controls accuracy vs speed tradeoff

probes?:

number
IVFFlat probe parameter - number of cells to visit during search

chroma?:

ChromaConfig
Configuration specific to Chroma vector store
ChromaConfig

where?:

Record<string, any>
Metadata filtering conditions

whereDocument?:

Record<string, any>
Document content filtering conditions

providerOptions?:

Record<string, Record<string, any>>
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객체 구조
queryresult-object-structure에 대한 직접 링크

{
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 설명에 대한 직접 링크

기본 설명은 다음에 중점을 둡니다.

  • 저장된 지식에서 관련 정보 찾기
  • 사용자 질문에 답변하기
  • 사실에 근거한 콘텐츠 검색

결과 처리
결과 처리에 대한 직접 링크

이 Tool은 사용자의 쿼리를 기반으로 반환할 결과 수를 결정하며 기본값은 10개입니다. 이는 쿼리 요구 사항에 따라 조정될 수 있습니다.

필터의 예
필터의 예에 대한 직접 링크

const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
enableFilter: true,
})

필터링이 활성화되면 Tool은 쿼리를 처리하여 의미 체계 검색과 결합되는 메타데이터 필터를 구성합니다. 프로세스는 다음과 같이 작동합니다.

  1. 사용자가 "'버전' 필드가 2.0보다 큰 콘텐츠 찾기"와 같은 특정 필터 요구 사항을 사용하여 쿼리를 수행합니다.
  2. Agent는 쿼리를 분석하고 적절한 필터를 구성합니다.
    {
    "version": { "$gt": 2.0 }
    }

이 Agent 중심 접근 방식은 다음과 같습니다.

  • 자연어 쿼리를 필터 사양으로 처리합니다.
  • 벡터 저장소별 필터 구문을 구현합니다.
  • 검색어를 필터 연산자로 변환합니다.

자세한 필터 구문 및 매장별 기능은 다음을 참조하세요.Metadata Filters documentation.

Agent 기반 필터링의 작동 방식에 대한 예는 다음을 참조하세요.Agent-Driven Metadata Filtering example.

재순위 예시
재순위 예시에 대한 직접 링크

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는 초기 벡터 검색 결과를 처리하고 관련성에 최적화된 재정렬된 목록을 반환합니다.

사용자 정의 설명의 예
사용자 정의 설명의 예에 대한 직접 링크

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 매개변수를 사용하면 각 벡터 데이터베이스에 특화된 기능과 최적화를 사용할 수 있습니다. 이러한 구성은 쿼리 실행 중 자동으로 적용됩니다.

솔방울 구성
솔방울 구성에 대한 직접 링크

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],
},
},
},
})

솔방울 특징:

  • 네임스페이스: 동일한 인덱스 내에서 서로 다른 데이터 세트를 분리합니다.
  • 희소 벡터: 향상된 검색 품질을 위해 조밀한 임베딩과 희소 임베딩을 결합합니다.
  • 사용 사례: 멀티 테넌트 애플리케이션, 하이브리드 의미 검색

런타임 구성 재정의
런타임 구성 재정의에 대한 직접 링크

런타임 시 데이터베이스 구성을 재정의하여 다양한 시나리오에 적응할 수 있습니다.

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)
  • 부하에 따라 성능 매개변수 조정
  • 요청별로 다른 필터링 전략 적용

예: 요청 컨텍스트 사용
예: 요청 컨텍스트 사용에 대한 직접 링크

const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
})

요청 컨텍스트를 사용하는 경우 요청 컨텍스트를 통해 실행 시 필수 매개변수를 제공하세요.

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,
})

요청 컨텍스트에 대한 자세한 내용은 다음을 참조하세요.

Mastra 서버 없이 사용
Mastra 서버 없이 사용에 대한 직접 링크

이 Tool은 쿼리와 일치하는 문서를 검색하는 데 단독으로 사용될 수 있습니다.

src/index.ts
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 스키마)가 있는 다중 테넌트 애플리케이션의 경우 정적 벡터 저장소 인스턴스 대신 확인자 함수를 전달할 수 있습니다. 이 함수는 요청 컨텍스트를 수신하고 현재 테넌트에 대한 적절한 벡터 저장소를 반환할 수 있습니다.

src/index.ts
import { createVectorQueryTool, VectorStoreResolver } from '@mastra/rag'
import { PgVector } from '@mastra/pg'

// Cache for tenant-specific vector stores
const vectorStoreCache = new Map<string, PgVector>()

// 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 세부정보에 대한 직접 링크

이 Tool은 다음을 사용하여 생성됩니다.

  • ID: VectorQuery {vectorStoreName} {indexName} Tool
  • 입력 스키마: queryText 및 필터 객체가 필요합니다.
  • 출력 스키마: 관련 컨텍스트 문자열을 반환합니다.