使用 ChromaDB 建立向量資料庫

Introduction to Embeddings with the OpenAI API

Emmanuel Pire

Senior Software Engineer, DataCamp

安裝 ChromaDB

  • ChromaDB 是簡潔但強大的向量資料庫
  • 兩種模式:
    • 本機:適合開發與原型製作
    • 用戶端/伺服器:適用於正式環境

本機模式的 ChromaDB 與用戶端/伺服器模式的 ChromaDB。用戶端/伺服器模式中用戶端與伺服器分別為不同執行個體。

Introduction to Embeddings with the OpenAI API

連線到資料庫

import chromadb

client = chromadb.PersistentClient(path="/path/to/save/to")
  • 資料會持久化到磁碟
Introduction to Embeddings with the OpenAI API

建立集合

  • 集合(collection)類似資料表
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="..." )
)
  • 集合可自動建立 embeddings
Introduction to Embeddings with the OpenAI API

檢視集合

client.list_collections()
[Collection(name=my_collection)]
Introduction to Embeddings with the OpenAI API

插入 embeddings

單一文件

collection.add(ids=["my-doc"], documents=["This is the source text"])
  • 必須提供 ID
  • 集合會自動建立 embeddings!

多筆文件

collection.add(
  ids=["my-doc-1", "my-doc-2"], 
  documents=["This is document 1", "This is document 2"]
)
Introduction to Embeddings with the OpenAI API

檢視集合

計算集合中的文件數

collection.count()
3
Introduction to Embeddings with the OpenAI API

檢視集合

預覽前 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]}
Introduction to Embeddings with the OpenAI API

擷取項目

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}
Introduction to Embeddings with the OpenAI API

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
Introduction to Embeddings with the OpenAI API

估算 embedding 成本

  • Embedding 模型(text-embedding-3-small)費用為 $0.00002/1k tokens
cost = 0.00002 * len(tokens)/1000
  • 使用 tiktoken 函式庫計算 tokens
    • pip install tiktoken
1 https://openai.com/pricing
Introduction to Embeddings with the OpenAI API

估算 embedding 成本

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
Introduction to Embeddings with the OpenAI API

一起來練習吧!

Introduction to Embeddings with the OpenAI API

Preparing Video For Download...