Chroma 벡터스토어 통합

Chroma 벡터스토어 통합 (Chroma)

벡터 데이터베이스를 시작할 때는 인프라 부담이 없는 걸 고르는 게 편한데요, Chroma는 개발자 생산성과 만족감에 초점을 맞춘 AI 네이티브 오픈소스 벡터 데이터베이스라서 진입장벽이 낮아요. 자격 증명 없이도 쓸 수 있고, 로컬 인메모리부터 서버, 클라우드까지 단계적으로 확장할 수 있어요.

출처: 공식문서

Chroma는 Apache 2.0 라이선스의 오픈소스 벡터 데이터베이스예요. Chroma의 전체 문서는 이 페이지, LangChain 통합의 API 레퍼런스는 이 페이지에서 볼 수 있어요.

Chroma Cloud

Chroma Cloud는 완전관리형 서버리스 벡터 및 전문(full-text) 검색을 제공해요. 빠르고 비용 효율적이며 확장성 있고 설치도 간편하죠. \$5의 무료 크레딧으로 30초 안에 DB를 만들어 바로 써볼 수 있어요. Chroma Cloud 시작하기

설정

Chroma 벡터 스토어에 접근하려면 langchain-chroma 통합 패키지를 설치해야 해요.

pip install -qU "langchain-chroma>=0.1.2"

자격 증명

Chroma 벡터 스토어는 자격 증명 없이도 사용할 수 있어요. 위 패키지만 설치하면 충분해요!

Chroma Cloud 사용자라면 CHROMA_TENANT, CHROMA_DATABASE, CHROMA_API_KEY 환경 변수를 설정해요.

chromadb 패키지를 설치하면 Chroma CLI도 사용할 수 있어서, 이 값들을 자동으로 설정해 줄 수 있어요. 먼저 CLI로 로그인한 뒤 connect 명령을 사용해요.

chroma db connect [db_name] --env-file

모델 호출을 최고 수준으로 자동 트레이싱하고 싶다면 LangSmith API 키를 설정하고 트레이싱을 활성화해요.

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

초기화

기본 초기화

아래 예시는 Chroma용 임베딩 함수를 설정한 뒤, 벡터 데이터 저장을 위한 로컬 영속성을 구성하는 흐름이에요.

# | output: false
# | echo: false
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")

로컬 실행 (인메모리)

컬렉션 이름과 임베딩 프로바이더만 지정해 Chroma 인스턴스를 만들면 서버가 인메모리로 실행돼요.

from langchain_chroma import Chroma

vector_store = Chroma(
    collection_name="example_collection",
    embedding_function=embeddings,
)

데이터 영속성이 필요 없다면, LangChain으로 AI 앱을 만들면서 실험하기에 훌륭한 옵션이에요.

로컬 실행 (데이터 영속성 포함)

persist_directory 인자로 프로그램 실행 간 데이터를 저장할 수 있어요.

from langchain_chroma import Chroma

vector_store = Chroma(
    collection_name="example_collection",
    embedding_function=embeddings,
    persist_directory="./chroma_langchain_db",
)

Chroma 서버 연결

로컬에서 실행 중인 Chroma 서버가 있거나 직접 배포했다면, host 인자로 연결할 수 있어요.

예를 들어 chroma run으로 로컬 Chroma 서버를 시작한 뒤 host='localhost'로 연결할 수 있어요.

from langchain_chroma import Chroma

vector_store = Chroma(
    collection_name="example_collection",
    embedding_function=embeddings,
    host="localhost",
)

그 외 배포에서는 port, ssl, headers 인자로 연결을 커스터마이즈할 수 있어요.

Chroma Cloud

Chroma Cloud 사용자도 LangChain으로 빌드할 수 있어요. Chroma Cloud API 키, tenant, DB 이름을 Chroma 인스턴스에 전달하면 돼요.

from langchain_chroma import Chroma

vector_store = Chroma(
    collection_name="example_collection",
    embedding_function=embeddings,
    chroma_cloud_api_key=os.getenv("CHROMA_API_KEY"),
    tenant=os.getenv("CHROMA_TENANT"),
    database=os.getenv("CHROMA_DATABASE"),
)

클라이언트에서 초기화

Chroma 클라이언트에서도 초기화할 수 있는데, 기반 데이터베이스에 더 쉽게 접근하고 싶을 때 특히 유용해요.

로컬 실행 (인메모리)

import chromadb

client = chromadb.Client()

로컬 실행 (데이터 영속성 포함)

import chromadb

client = chromadb.PersistentClient(path="./chroma_langchain_db")

Chroma 서버 연결

chroma run으로 로컬 Chroma 서버를 실행 중이라면:

import chromadb

client = chromadb.HttpClient(host="localhost", port=8000, ssl=False)

Chroma Cloud

CHROMA_API_KEY, CHROMA_TENANT, CHROMA_DATABASE를 설정한 뒤 인스턴스화하면 돼요.

import chromadb

client = chromadb.CloudClient()

Chroma DB 접근

collection = client.get_or_create_collection("collection_name")
collection.add(ids=["1", "2", "3"], documents=["a", "b", "c"])

Chroma vectorstore 생성

vector_store_from_client = Chroma(
    client=client,
    collection_name="collection_name",
    embedding_function=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"},
    id=1,
)

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

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

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

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

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

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

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

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

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

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)

아이템 갱신

추가한 문서는 update_documents 함수로 갱신할 수 있어요.

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

updated_document_2 = Document(
    page_content="The weather forecast for tomorrow is sunny and warm, with a high of 82 degrees.",
    metadata={"source": "news"},
    id=2,
)

vector_store.update_document(document_id=uuids[0], document=updated_document_1)
# You can also update multiple documents at once
vector_store.update_documents(
    ids=uuids[:2], documents=[updated_document_1, updated_document_2]
)

아이템 삭제

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

벡터로 검색

results = vector_store.similarity_search_by_vector(
    embedding=embeddings.embed_query("I love green eggs and ham!"), k=1
)
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")

그 외 검색 메서드

MMR 검색처럼 이 문서에서 다루지 않은 검색 메서드가 다양해요. Chroma가 제공하는 검색 기능 전체 목록은 API 레퍼런스를 참고하세요.

리트리버로 변환해 쿼리

체인에서 더 쉽게 쓰려면 벡터 스토어를 리트리버로 변환할 수 있어요. 전달 가능한 검색 타입과 kwargs에 대한 자세한 내용은 Chroma API 레퍼런스를 방문해보세요.

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

RAG에서 사용하기

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

API 레퍼런스

Chroma 벡터 스토어의 모든 기능과 설정에 대한 자세한 문서는 API 레퍼런스를 참고하세요.

더 알아보기 (Learn more)