ChromaDB로 벡터 데이터베이스 만들기

OpenAI API로 시작하는 임베딩 Introduction

Emmanuel Pire

Senior Software Engineer, DataCamp

ChromaDB 설치

  • ChromaDB는 간단하면서도 강력한 벡터 데이터베이스
  • 두 가지 방식:
    • 로컬: 개발 및 프로토타이핑에 적합
    • 클라이언트/서버: 프로덕션용

로컬 모드의 ChromaDB와 클라이언트/서버 모드의 ChromaDB. 클라이언트/서버 모드에서는 클라이언트와 서버가 별도 인스턴스로 표시됩니다.

OpenAI API로 시작하는 임베딩 Introduction

데이터베이스 연결

import chromadb

client = chromadb.PersistentClient(path="/path/to/save/to")
  • 데이터가 디스크에 저장됩니다
OpenAI API로 시작하는 임베딩 Introduction

컬렉션 생성

  • 컬렉션은 테이블과 유사
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
collection = client.create_collection(
    name="my_collection",

embedding_function=OpenAIEmbeddingFunction( model_name="text-embedding-3-small", api_key="..." )
)
  • 컬렉션이 임베딩을 자동으로 생성
OpenAI API로 시작하는 임베딩 Introduction

컬렉션 검사

client.list_collections()
[Collection(name=my_collection)]
OpenAI API로 시작하는 임베딩 Introduction

임베딩 삽입

단일 문서

collection.add(ids=["my-doc"], documents=["This is the source text"])
  • ID를 반드시 제공해야 합니다
  • 임베딩은 컬렉션이 자동으로 생성합니다!

여러 문서

collection.add(
  ids=["my-doc-1", "my-doc-2"], 
  documents=["This is document 1", "This is document 2"]
)
OpenAI API로 시작하는 임베딩 Introduction

컬렉션 검사

컬렉션 내 문서 수 확인

collection.count()
3
OpenAI API로 시작하는 임베딩 Introduction

컬렉션 검사

처음 10개 항목 미리 보기

collection.peek()
{'ids': ['my-doc', 'my-doc-1', 'my-doc-2'],
 'embeddings': [[...], [...], [...]],
 'documents': ['This is the source text',
  'This is document 1',
  'This is document 2'],
 'metadatas': [None, None, None]}
OpenAI API로 시작하는 임베딩 Introduction

항목 조회

collection.get(ids=["s59"])
{'ids': ['s59'],
 'embeddings': None,
 'metadatas': [None],
 'documents': ['Title: Naruto Shippûden the Movie: The Will of Fire (Movie)\nDescription: When ...'],
 'uris': None,
 'data': None}
OpenAI API로 시작하는 임베딩 Introduction

Netflix 데이터셋

 

Title: Kota Factory (TV Show)
Description: In a city of coaching centers known to train India's finest...
Categories: International TV Shows, Romantic TV Shows, TV Comedies
Title: The Last Letter From Your Lover (Movie)
Description: After finding a trove of love letters from 1965, a reporter sets...
Categories: Dramas, Romantic Movies
OpenAI API로 시작하는 임베딩 Introduction

임베딩 비용 추정

  • 임베딩 모델(text-embedding-3-small) 비용: $0.00002/1k 토큰
cost = 0.00002 * len(tokens)/1000
  • tiktoken 라이브러리로 토큰 수 계산
    • pip install tiktoken
1 https://openai.com/pricing
OpenAI API로 시작하는 임베딩 Introduction

임베딩 비용 추정

import tiktoken

enc = tiktoken.encoding_for_model("text-embedding-3-small")

total_tokens = sum(len(enc.encode(text)) for text in documents)
cost_per_1k_tokens = 0.00002 print('Total tokens:', total_tokens) print('Cost:', cost_per_1k_tokens * total_tokens/1000)
Total tokens: 444463
Cost: 0.00888926
OpenAI API로 시작하는 임베딩 Introduction

연습해 봅시다!

OpenAI API로 시작하는 임베딩 Introduction

Preparing Video For Download...