OceanBaseデータベースは、ベクトル型データの格納、ベクトルインデックス、そしてembeddingベクトル検索機能を提供しています。これにより、ベクトル化されたデータをOceanBaseデータベースに保存し、その後の検索処理で直接利用することが可能になります。
CamelAIは、チーム間のデータやり取りの仕組みを根本から変革します。自然言語で質問するだけで、即座に正確なSQLクエリやインテリジェントな分析、そして可視化された結果を得ることができます。
前提条件
OceanBaseデータベースV4.3.3以降をデプロイし、MySQLモードのテナントを作成していること。テナントの作成後、以下の手順に従って操作します。
環境に使用可能なMySQLテナント、MySQLデータベース、およびアカウントが存在し、データベースアカウントに読み取り書き込み権限が付与されていること。
Python 3.11以降のバージョンがインストール済みであること。
依存関係のパッケージがインストール済みであること。
python3 -m pip install "unstructured[pdf]" camel-ai pyobvectorテナント内で
ob_vector_memory_limit_percentage構成パラメータを設定し、ベクトル検索機能を有効にしていることを確認してください。V4.3.5 BP3以前のバージョンでは、この値を30に設定することを推奨します。V4.3.5 BP3以降のバージョンでは、デフォルト値の0のままにすることを推奨します。この構成パラメータをより正確に設定する必要がある場合は、ob_vector_memory_limit_percentage参照してこの値を計算してください。
ステップ1:データベース接続情報を取得する
OceanBaseデータベースのデプロイ担当者または管理者から、該当するデータベース接続文字列を取得します。例:
obclient -h$host -P$port -u$user_name -p$password -D$database_name
パラメータの説明:
$host:OceanBaseデータベースへの接続IPアドレス。OceanBaseデータベースプロキシ(OceanBase Database Proxy、ODP)接続方式ではODPアドレスを使用し、直接接続方式ではOBServerノードのIPアドレスを使用します。$port:OceanBaseデータベースへの接続ポート。ODP接続方式のデフォルトポートは2883で、ODPデプロイ時にカスタマイズ可能です。直接接続方式のデフォルトポートは2881で、OceanBaseデータベースのデプロイ時にカスタマイズ可能です。$database_name:アクセス対象のデータベース名。注意
テナントに接続するユーザーには、そのデータベースに対する
CREATE、INSERT、DROP、およびSELECT権限が付与されている必要があります。ユーザー権限の詳細については、MySQLモードの権限分類を参照してください。$user_name:テナントの接続アカウント。ODP接続の一般的な形式:ユーザー名@テナント名#クラスタ名またはクラスタ名:テナント名:ユーザー名。直接接続方式の形式:ユーザー名@テナント名。$password:アカウントのパスワード。
その他の接続文字列の詳細については、OBClientを使用したOceanBaseテナントへの接続を参照してください。
ステップ2:AIアシスタントを構築する
環境変数の設定
Jina AI APIキーを取得し、OceanBase接続情報とともに環境変数に設定します。
export OCEANBASE_DATABASE_URL=YOUR_OCEANBASE_DATABASE_URL
export OCEANBASE_DATABASE_USER=YOUR_OCEANBASE_DATABASE_USER
export OCEANBASE_DATABASE_DB_NAME=YOUR_OCEANBASE_DATABASE_DB_NAME
export OCEANBASE_DATABASE_PASSWORD=YOUR_OCEANBASE_DATABASE_PASSWORD
export JINAAI_API_KEY=YOUR_JINAAI_API_KEY
データの読み込み
CamelAIはOpenAIEmbedding、VisionLanguageEmbedding、JinaEmbeddingなど、さまざまな埋め込みモデルをサポートしています。 ここでは、Jina Embeddingのjina-embeddings-v3を例に説明します。
import os
import requests
from camel.embeddings import JinaEmbedding
from camel.storages.vectordb_storages import (
OceanBaseStorage,
VectorDBQuery,
VectorRecord,
)
from camel.storages import OceanBaseStorage
from camel.retrievers import VectorRetriever
from camel.types import EmbeddingModelType
documents = [
"""Artificial Intelligence (AI) is a branch of computer science that aims to create systems capable of performing tasks that typically require human intelligence. AI encompasses multiple subfields including machine learning, deep learning, natural language processing, and computer vision.""",
"""Machine Learning is a subset of artificial intelligence that enables computers to learn and improve without being explicitly programmed. The main types of machine learning include supervised learning, unsupervised learning, and reinforcement learning.""",
"""Deep Learning is a branch of machine learning that uses multi-layered neural networks to simulate how the human brain works. Deep learning has achieved breakthrough progress in areas such as image recognition, speech recognition, and natural language processing.""",
"""Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on enabling computers to understand, interpret, and generate human language. NLP applications include machine translation, sentiment analysis, text summarization, and chatbots.""",
"""Computer Vision is a field of artificial intelligence that aims to enable computers to identify and understand content in digital images and videos. Applications include facial recognition, object detection, medical image analysis, and autonomous vehicles.""",
"""Reinforcement Learning is a machine learning method where an agent learns how to make decisions through interaction with an environment. The agent optimizes its behavioral strategy through trial and error and reward mechanisms.""",
"""Neural Networks are computational models inspired by biological neural systems, composed of interconnected nodes (neurons). Neural networks can learn complex patterns and relationships and serve as the foundation for deep learning.""",
"""Large Language Models (LLMs) are natural language processing models based on deep learning. These models are trained on vast amounts of text data and can generate human-like text and answer questions.""",
"""Transformer architecture is a neural network architecture that has revolutionized natural language processing. It uses attention mechanisms to process sequential data and forms the basis for models like GPT and BERT.""",
"""Generative AI refers to artificial intelligence systems that can create new content, including text, images, audio, and video. Examples include ChatGPT for text generation, DALL-E for image creation, and various AI tools for creative applications."""
]
JINAAI_API_KEY = os.getenv('JINAAI_API_KEY')
embedding = JinaEmbedding(
api_key=JINAAI_API_KEY,
model_type=EmbeddingModelType.JINA_EMBEDDINGS_V3)
OceanBaseクラスタに接続し、ベクトルテーブルの構造を定義して埋め込みベクトルをOceanBaseに同時に保存する
my_ob_vector_table という名前のテーブルを作成します。テーブル構造はid、embedding、metadataの3つに固定されます。Jina AI Embeddings APIを使用して、各テキストセグメントの埋め込みベクトルを生成し、OceanBaseに保存します。
OB_URI = os.getenv('OCEANBASE_DATABASE_URL')
OB_USER = os.getenv('OCEANBASE_DATABASE_USER')
OB_DB_NAME = os.getenv('OCEANBASE_DATABASE_DB_NAME')
OB_PASSWORD = os.getenv('OCEANBASE_DATABASE_PASSWORD')
# create table
ob_storage = OceanBaseStorage(
vector_dim=embedding.get_output_dim(),
table_name="my_ob_vector_table",
uri=OB_URI,
user=OB_USER,
password=OB_PASSWORD,
db_name=OB_DB_NAME,
distance="cosine"
)
vector_retriever = VectorRetriever(
embedding_model=embedding, storage=ob_storage
)
for i, doc in enumerate(documents):
print(f"Processing document {i+1}/{len(documents)}")
vector_retriever.process(content=doc)
セマンティック検索
Jina AI APIを使用してクエリテキストの埋め込みベクトルを生成し、その埋め込みベクトルとベクトルテーブル内の各埋め込みベクトルとのコサイン距離に基づいて、最も関連性の高いドキュメントを検索します。
retrieved_info = vector_retriever.query(query="What is generative AI?", top_k=1)
print(retrieved_info)
期待される結果
[{'similarity score': '0.8538218656447916', 'content path': 'Generative AI refers to artificial intelligence systems that can create new content, including text,', 'metadata': {'piece_num': 1}, 'extra_info': {}, 'text': 'Generative AI refers to artificial intelligence systems that can create new content, including text, images, audio, and video. Examples include ChatGPT for text generation, DALL-E for image creation, and various AI tools for creative applications.'}]