이 노트북은 Chroma vector store를 시작하는 방법을 다룹니다.
Chroma는 개발자 생산성과 만족도에 중점을 둔 AI 네이티브 오픈소스 vector database입니다. Chroma는 Apache 2.0 라이선스로 제공됩니다. Chroma의 전체 문서는 이 페이지에서 확인할 수 있으며, LangChain 통합을 위한 API 레퍼런스는 이 페이지에서 찾을 수 있습니다.
Chroma CloudChroma Cloud는 서버리스 vector 및 full-text search를 지원합니다. 매우 빠르고, 비용 효율적이며, 확장 가능하고 간편합니다. 30초 이내에 DB를 생성하고 $5의 무료 크레딧으로 사용해보세요.Chroma Cloud 시작하기

Setup

Chroma vector store에 액세스하려면 langchain-chroma 통합 패키지를 설치해야 합니다.
pip install -qU "langchain-chroma>=0.1.2"

Credentials

위의 패키지만 설치하면 자격 증명 없이도 Chroma vector store를 사용할 수 있습니다! Chroma Cloud 사용자인 경우, CHROMA_TENANT, CHROMA_DATABASE, CHROMA_API_KEY 환경 변수를 설정하세요. chromadb 패키지를 설치하면 Chroma CLI에도 액세스할 수 있으며, 이를 통해 이러한 값을 설정할 수 있습니다. 먼저 CLI를 통해 로그인한 다음 connect 명령을 사용하세요:
chroma db connect [db_name] --env-file
모델 호출에 대한 최고 수준의 자동 추적을 원하는 경우 아래 주석을 해제하여 LangSmith API key를 설정할 수도 있습니다:
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

Initialization

Basic Initialization

다음은 데이터를 로컬에 저장하기 위한 디렉토리 사용을 포함한 기본 초기화입니다.
# | output: false
# | echo: false
from langchain_openai import OpenAIEmbeddings

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

Running Locally (In-Memory)

collection 이름과 embeddings provider만으로 Chroma 인스턴스를 생성하여 메모리에서 실행되는 Chroma 서버를 얻을 수 있습니다:
from langchain_chroma import Chroma

vector_store = Chroma(
    collection_name="example_collection",
    embedding_function=embeddings,
)
데이터 지속성이 필요하지 않다면, LangChain으로 AI 애플리케이션을 구축하는 동안 실험하기에 좋은 옵션입니다.

Running Locally (with Data Persistence)

프로그램의 여러 실행에 걸쳐 데이터를 저장하려면 persist_directory 인수를 제공할 수 있습니다:
from langchain_chroma import Chroma

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

Connecting to a Chroma Server

로컬에서 실행 중인 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 인스턴스에 Chroma Cloud API key, tenant, DB 이름을 제공하세요:
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"),
)

Initialization from client

Chroma client에서 초기화할 수도 있으며, 이는 기본 데이터베이스에 더 쉽게 액세스하려는 경우 특히 유용합니다.

Running Locally (In-Memory)

import chromadb

client = chromadb.Client()

Running Locally (with Data Persistence)

import chromadb

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

Connecting to a Chroma Server

예를 들어, 로컬에서 Chroma 서버를 실행하는 경우(chroma run 사용):
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()

Access your Chroma DB

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

Create a Chroma Vectorstore

vector_store_from_client = Chroma(
    client=client,
    collection_name="collection_name",
    embedding_function=embeddings,
)

Manage vector store

vector store를 생성한 후에는 다양한 항목을 추가하고 삭제하여 상호 작용할 수 있습니다.

Add items to vector store

add_documents 함수를 사용하여 vector store에 항목을 추가할 수 있습니다.
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 items in vector store

이제 vector store에 문서를 추가했으므로 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]
)

Delete items from vector store

다음과 같이 vector store에서 항목을 삭제할 수도 있습니다:
vector_store.delete(ids=uuids[-1])

Query vector store

vector store가 생성되고 관련 문서가 추가되면 chain이나 agent를 실행하는 동안 쿼리하고 싶을 것입니다.

Query directly

간단한 similarity search는 다음과 같이 수행할 수 있습니다:
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}]")

Similarity search with score

similarity search를 실행하고 해당 점수를 받으려면 다음을 실행할 수 있습니다:
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}]")

Search by vector

vector로 검색할 수도 있습니다:
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}]")

Other search methods

이 노트북에서 다루지 않는 MMR search나 vector로 검색하는 것과 같은 다양한 다른 검색 방법이 있습니다. AstraDBVectorStore에서 사용 가능한 검색 기능의 전체 목록은 API reference를 확인하세요.

Query by turning into retriever

vector store를 retriever로 변환하여 chain에서 더 쉽게 사용할 수도 있습니다. 전달할 수 있는 다양한 검색 유형과 kwargs에 대한 자세한 내용은 여기 API reference를 참조하세요.
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"})

Usage for retrieval-augmented generation

retrieval-augmented generation (RAG)에 이 vector store를 사용하는 방법에 대한 가이드는 다음 섹션을 참조하세요:

API reference

모든 Chroma vector store 기능 및 구성에 대한 자세한 문서는 API reference를 참조하세요: python.langchain.com/api_reference/chroma/vectorstores/langchain_chroma.vectorstores.Chroma.html
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I