Pinecone 벡터스토어 통합

Pinecone 벡터스토어 통합 (PineconeVectorStore)

RAG 애플리케이션을 만들다 보면 문서를 벡터로 바꿔 저장할 저장소가 필요해지는데요, Pinecone은 기능이 풍부한 벡터 데이터베이스로 이 역할을 톡톡히 해요. LangChain의 PineconeVectorStore를 쓰면 인덱스 만들기부터 문서 추가·삭제·검색까지 깔끔하게 처리할 수 있어요.

출처: 공식문서

Pinecone은 광범위한 기능을 갖춘 벡터 데이터베이스예요. 이 문서에서는 Pinecone 벡터 데이터베이스 관련 기능을 어떻게 쓰는지 살펴볼게요.

설정

PineconeVectorStore를 쓰려면 먼저 파트너 패키지와 이 문서에서 함께 사용할 다른 패키지들을 설치해야 해요.

pip install -qU langchain langchain-pinecone langchain-openai

마이그레이션 참고: langchain_community.vectorstores의 Pinecone 구현에서 마이그레이션하는 경우, langchain-pinecone을 설치하기 전에 pinecone-client v2 의존성을 제거해야 할 수 있어요. langchain-pineconepinecone-client v6에 의존하기 때문이에요.

자격 증명

새 Pinecone 계정을 만들거나 기존 계정으로 로그인한 뒤, API 키를 생성해서 사용해요.

import getpass
import os

from pinecone import Pinecone

if not os.getenv("PINECONE_API_KEY"):
    os.environ["PINECONE_API_KEY"] = getpass.getpass("Enter your Pinecone API key: ")

pinecone_api_key = os.environ.get("PINECONE_API_KEY")

pc = Pinecone(api_key=pinecone_api_key)

모델 호출을 자동으로 트레이싱하고 싶다면 LangSmith API 키도 설정할 수 있어요.

os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

초기화

벡터 스토어를 초기화하기 전에 먼저 Pinecone 인덱스에 연결해요. index_name이라는 이름의 인덱스가 없으면 자동으로 생성돼요.

from pinecone import ServerlessSpec

index_name = "langchain-test-index"  # change if desired

if not pc.has_index(index_name):
    pc.create_index(
        name=index_name,
        dimension=1536,
        metric="cosine",
        spec=ServerlessSpec(cloud="aws", region="us-east-1"),
    )

index = pc.Index(index_name)
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
from langchain_pinecone import PineconeVectorStore

vector_store = PineconeVectorStore(index=index, embedding=embeddings)

벡터 스토어 관리

벡터 스토어를 만들었다면 아이템을 추가하고 삭제하면서 상호작용할 수 있어요.

아이템 추가

add_documents 함수로 아이템을 추가해요.

from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
    page_content="I had chocolate chip pancakes and scrambled eggs for breakfast this morning.",
    metadata={"source": "tweet"},
)

document_2 = Document(
    page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
    metadata={"source": "news"},
)

document_3 = Document(
    page_content="Building an exciting new project with LangChain - come check it out!",
    metadata={"source": "tweet"},
)

document_4 = Document(
    page_content="Robbers broke into the city bank and stole $1 million in cash.",
    metadata={"source": "news"},
)

document_5 = Document(
    page_content="Wow! That was an amazing movie. I can't wait to see it again.",
    metadata={"source": "tweet"},
)

document_6 = Document(
    page_content="Is the new iPhone worth the price? Read this review to find out.",
    metadata={"source": "website"},
)

document_7 = Document(
    page_content="The top 10 soccer players in the world right now.",
    metadata={"source": "website"},
)

document_8 = Document(
    page_content="LangGraph is the best framework for building stateful, agentic applications!",
    metadata={"source": "tweet"},
)

document_9 = Document(
    page_content="The stock market is down 500 points today due to fears of a recession.",
    metadata={"source": "news"},
)

document_10 = Document(
    page_content="I have a bad feeling I am going to get deleted :(",
    metadata={"source": "tweet"},
)

documents = [
    document_1,
    document_2,
    document_3,
    document_4,
    document_5,
    document_6,
    document_7,
    document_8,
    document_9,
    document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]
vector_store.add_documents(documents=documents, ids=uuids)

아이템 삭제

vector_store.delete(ids=[uuids[-1]])

벡터 스토어 쿼리

벡터 스토어에 관련 문서를 추가했다면, 체인이나 에이전트가 실행되는 동안 이를 쿼리하고 싶을 거예요.

직접 쿼리

간단한 유사도 검색은 다음과 같이 해요.

results = vector_store.similarity_search(
    "LangChain provides abstractions to make working with LLMs easy",
    k=2,
    filter={"source": "tweet"},
)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")

스코어와 함께 검색

results = vector_store.similarity_search_with_score(
    "Will it be hot tomorrow?", k=1, filter={"source": "news"}
)
for res, score in results:
    print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")

그 외 검색 메서드

MMR 같은 검색 메서드가 더 있는데, 전체 목록은 API 레퍼런스를 참고하세요.

리트리버로 변환해 쿼리

체인에서 더 쉽게 쓰려면 벡터 스토어를 리트리버로 변환할 수 있어요.

retriever = vector_store.as_retriever(
    search_type="similarity_score_threshold",
    search_kwargs={"k": 1, "score_threshold": 0.4},
)
retriever.invoke("Stealing from the bank is a crime", filter={"source": "news"})

RAG에서 사용하기

이 벡터 스토어를 RAG에 어떻게 쓰는지에 대한 가이드는 아래 섹션을 참고하세요.

API 레퍼런스

모든 기능과 설정에 대한 자세한 문서는 API 레퍼런스에서 확인할 수 있어요.

더 알아보기 (Learn more)