MemoryVectorStore 통합
MemoryVectorStore 통합
LangChain JavaScript로 MemoryVectorStore와 통합해요.
LangChain은 임베딩을 메모리에 저장하고 가장 유사한 임베딩에 대해 정확한(exact) 선형 검색을 수행하는 인메모리, 임시(ephemeral) 벡터스토어를 제공해요. 기본 유사도 지표는 코사인 유사도이지만, ml-distance가 지원하는 유사도 지표 중 어떤 것으로도 바꿀 수 있어요.
데모용으로 설계됐기 때문에 아직 id나 삭제를 지원하지 않아요.
이 가이드는 MemoryVectorStore 벡터 스토어 시작을 위한 빠른 개요를 제공해요.
개요 (Overview)
통합 세부 정보 (Integration details)
| 클래스 | 패키지 | PY 지원 | 버전 |
|---|---|---|---|
MemoryVectorStore |
langchain |
❌ |
설정 (Setup)
인메모리 벡터 스토어를 사용하려면 langchain 패키지를 설치해야 해요:
이 가이드는 또한 OpenAI 임베딩을 사용하며, 이를 위해 @langchain/openai 통합 패키지를 설치해야 해요. 원한다면 다른 지원 임베딩 모델을 사용할 수도 있어요.
yarn add langchain @langchain/openai @langchain/core
pnpm add langchain @langchain/openai @langchain/core
자격 증명 (Credentials)
인메모리 벡터 스토어를 사용하는 데 필수 자격 증명은 없어요.
이 가이드에서 OpenAI 임베딩을 사용한다면 OpenAI 키도 설정해야 해요:
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
모델 호출의 자동 추적을 받으려면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
인스턴스화 (Instantiation)
import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
});
const vectorStore = new MemoryVectorStore(embeddings);
벡터 스토어 관리 (Manage vector store)
벡터 스토어에 항목 추가 (Add items to vector store)
import type { Document } from "@langchain/core/documents";
const document1: Document = {
pageContent: "The powerhouse of the cell is the mitochondria",
metadata: { source: "https://example.com" }
};
const document2: Document = {
pageContent: "Buildings are made out of brick",
metadata: { source: "https://example.com" }
};
const document3: Document = {
pageContent: "Mitochondria are made out of lipids",
metadata: { source: "https://example.com" }
};
const documents = [document1, document2, document3];
await vectorStore.addDocuments(documents);
벡터 스토어 쿼리 (Query vector store)
직접 쿼리 (Query directly)
간단한 유사도 검색은 다음과 같이 수행할 수 있어요:
const filter = (doc) => doc.metadata.source === "https://example.com";
const similaritySearchResults = await vectorStore.similaritySearch("biology", 2, filter)
for (const doc of similaritySearchResults) {
console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* Mitochondria are made out of lipids [{"source":"https://example.com"}]
filter는 선택 사항이며, 문서를 입력으로 받아 그 문서를 반환해야 하는지에 따라 true 또는 false를 반환하는 술어(predicate) 함수여야 해요.
유사도 검색을 실행하고 대응하는 점수를 받으려면 다음을 실행할 수 있어요:
const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("biology", 2, filter)
for (const [doc, score] of similaritySearchWithScoreResults) {
console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
* [SIM=0.165] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=0.148] Mitochondria are made out of lipids [{"source":"https://example.com"}]
리트리버로 변환해 쿼리 (Query by turning into retriever)
벡터 스토어를 리트리버로 변환해 체인에서 더 쉽게 사용할 수도 있어요:
const retriever = vectorStore.asRetriever({
// Optional filter
filter: filter,
k: 2,
});
await retriever.invoke("biology");
[
Document {
pageContent: 'The powerhouse of the cell is the mitochondria',
metadata: { source: 'https://example.com' },
id: undefined
},
Document {
pageContent: 'Mitochondria are made out of lipids',
metadata: { source: 'https://example.com' },
id: undefined
}
]
최대 한계 관련성 (Maximal marginal relevance)
이 벡터 스토어는 고전적인 유사도 검색으로 먼저 더 많은 결과(searchKwargs.fetchK로 지정)를 가져온 뒤, 다양성을 위해 재정렬해 상위 k 결과를 반환하는 최대 한계 관련성(MMR)도 지원해요. 이는 중복 정보를 방지하는 데 도움이 돼요:
const mmrRetriever = vectorStore.asRetriever({
searchType: "mmr",
searchKwargs: {
fetchK: 10,
},
// Optional filter
filter: filter,
k: 2,
});
await mmrRetriever.invoke("biology");
검색 증강 생성(RAG) 사용법 (Usage for retrieval-augmented generation)
이 벡터 스토어를 검색 증강 생성(RAG)에 사용하는 방법에 대한 가이드는 다음 섹션을 참고하세요:
출처: 문서
본문
MemoryVectorStore는 임베딩을 메모리에 저장하고 정확한 선형 검색으로 유사도를 계산하는 인메모리 벡터 스토어예요. @langchain/classic/vectorstores/memory에서 가져와 임베딩으로 인스턴스화하고, 문서 추가·유사도 검색·asRetriever()(filter·k·MMR 지원)를 사용할 수 있어요. 데모용으로 id·삭제를 지원하지 않으며, 기본 지표는 코사인 유사도예요.