ChromaDBによるベクターデータベースの作成

OpenAI API ではじめる Embeddings 入門

Emmanuel Pire

Senior Software Engineer, DataCamp

ChromaDBのインストール

  • ChromaDB はシンプルかつ強力なベクターデータベース
  • 2つのモード:
    • ローカル: 開発・プロトタイピングに最適
    • クライアント/サーバー: 本番環境向け

ローカルモードのChromaDBと、クライアント/サーバーモードのChromaDB。クライアント/サーバーモードでは、クライアントとサーバーが別々のインスタンスで示されている。

OpenAI API ではじめる Embeddings 入門

データベースへの接続

import chromadb

client = chromadb.PersistentClient(path="/path/to/save/to")
  • データはディスクに保存される
OpenAI API ではじめる Embeddings 入門

コレクションの作成

  • コレクションはテーブルに相当する
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 ではじめる Embeddings 入門

コレクションの確認

client.list_collections()
[Collection(name=my_collection)]
OpenAI API ではじめる Embeddings 入門

埋め込みの挿入

単一ドキュメント

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 ではじめる Embeddings 入門

コレクションの検査

コレクション内のドキュメント数を確認する

collection.count()
3
OpenAI API ではじめる Embeddings 入門

コレクションの検査

最初の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 ではじめる Embeddings 入門

アイテムの取得

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 ではじめる Embeddings 入門

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 ではじめる Embeddings 入門

埋め込みコストの見積もり

  • 埋め込みモデル(text-embedding-3-small)のコストは$0.00002/1kトークン
cost = 0.00002 * len(tokens)/1000
  • tiktokenライブラリでトークン数を計算する
    • pip install tiktoken
1 https://openai.com/pricing
OpenAI API ではじめる Embeddings 入門

埋め込みコストの見積もり

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 ではじめる Embeddings 入門

練習しましょう!

OpenAI API ではじめる Embeddings 入門

Preparing Video For Download...