自動埋め込みの例
この例では、pytidb クライアントで 自動埋め込み 機能を使用する方法を示します。
pytidbクライアントを使用して TiDB に接続します。- 自動埋め込み用に設定された VectorField を持つテーブルを定義します。
- プレーンテキストデータを挿入します。埋め込みはバックグラウンドで自動的に設定されます。
- 自然言語クエリでベクトル検索を実行します。埋め込みは透過的に生成されます。
前提条件
開始する前に、以下を確認してください。
- Python (>=3.10): Python 3.10 以降のバージョンをインストールします。
- TiDB Cloud Starter インスタンス: TiDB Cloud で無料の TiDB Cloud Starter インスタンスを作成できます。
実行方法
Step 1. pytidb リポジトリをクローンする
git clone https://github.com/pingcap/pytidb.git
cd pytidb/examples/auto_embedding/
Step 2. 必要なパッケージをインストールする
python -m venv .venv
source .venv/bin/activate
pip install -r reqs.txt
Step 3. 環境変数を設定する
- TiDB Cloud コンソール で My TiDB ページに移動し、対象の TiDB Cloud Starter インスタンス名をクリックして概要ページを開きます。
- 右上隅の Connect をクリックします。接続ダイアログが表示され、接続パラメータが一覧表示されます。
- 以下のように、接続パラメータに従って環境変数を設定します。
cat > .env <<EOF
TIDB_HOST={gateway-region}.prod.aws.tidbcloud.com
TIDB_PORT=4000
TIDB_USERNAME={prefix}.root
TIDB_PASSWORD={password}
TIDB_DATABASE=test
# Using TiDB Cloud Free embedding model by default, which does not require setting up any API key
EMBEDDING_PROVIDER=tidbcloud_free
EOF
Step 4. デモを実行する
python main.py
想定される出力:
=== Define embedding function ===
Embedding function (model id: tidbcloud_free/amazon/titan-embed-text-v2) defined
=== Define table schema ===
Table created
=== Truncate table ===
Table truncated
=== Insert sample data ===
Inserted 3 chunks
=== Perform vector search ===
id: 1, text: TiDB is a distributed database that supports OLTP, OLAP, HTAP and AI workloads., distance: 0.30373281240458805
id: 2, text: PyTiDB is a Python library for developers to connect to TiDB., distance: 0.422506501973434
id: 3, text: LlamaIndex is a Python library for building AI-powered applications., distance: 0.5267239638442787
関連リソース
- ソースコード: GitHub で見る