OceanBaseデータベースは、ベクトル型データの格納、ベクトルインデックス、そしてembeddingベクトル検索機能を提供しています。これにより、ベクトル化したデータをOceanBaseデータベースに保存し、次の検索処理で利用することが可能です。
LangChainは、言語モデルを活用したアプリケーションを開発するためのフレームワークです。これにより、アプリケーションは以下の機能を備えることができます:
- コンテキスト認識:言語モデルをコンテキストソース(ヒント指示、少量の例、応答が必要な内容など)に接続します。
- 推論機能:言語モデルに推論を依存させます(提供されたコンテキストに基づいてどのように回答するか、どのようなアクションを取るかなど)。
このチュートリアルでは、通義千問APIを組み合わせて、OceanBaseデータベースのベクトル検索機能、通義千問とLangChainを統合し、ドキュメント質問応答を実現する方法を説明します。
前提条件
OceanBaseデータベースV4.4.0以降をデプロイし、MySQLテナントを作成していること。テナントの作成後、以下の手順を参照して操作してください。
環境に使用可能なMySQLテナント、MySQLデータベース、およびアカウントが存在し、データベースアカウントに読み書き権限が付与されていること。
Python 3.9以降をインストールしていること。
依存関係をインストールしていること。
python3 -m pip install -U langchain-oceanbase python3 -m pip install langchain_community python3 -m pip install dashscopeベクトル検索機能を有効にするために、テナントで
ob_vector_memory_limit_percentageパラメータが設定されていることを確認してください。V4.4.1以前のバージョンでは値を30に設定することを推奨しますが、V4.4.1以降のバージョンではデフォルト値の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アシスタントを構築する
Qwen APIキーの環境変数を設定する
Qwen APIキーを取得し、APIキーを環境変数に設定します。
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
ドキュメントの読み込みと分割
サンプルデータをダウンロードし、CharacterTextSplitterを使用して約1000文字ごとのブロックに分割します。
from langchain_community.document_loaders import TextLoader
from langchain_community.embeddings import DashScopeEmbeddings
from langchain_text_splitters import CharacterTextSplitter
from langchain_oceanbase.vectorstores import OceanbaseVectorStore
import os
import requests
DASHSCOPE_API = os.environ.get("DASHSCOPE_API_KEY", "")
embeddings = DashScopeEmbeddings(
model="text-embedding-v1", dashscope_api_key=DASHSCOPE_API
)
url = "https://raw.githubusercontent.com/GITHUBear/langchain/refs/heads/master/docs/docs/how_to/state_of_the_union.txt"
res = requests.get(url)
with open("state_of_the_union.txt", "w") as f:
f.write(res.text)
loader = TextLoader('./state_of_the_union.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
データをOceanBaseデータベースに挿入する
connection_args = {
"host": "127.0.0.1",
"port": "2881",
"user": "root@sun",
"password": "",
"db_name": "test",
}
DEMO_TABLE_NAME = "demo_ann"
ob = OceanbaseVectorStore(
embedding_function=embeddings,
table_name=DEMO_TABLE_NAME,
connection_args=connection_args,
drop_old=True,
normalize=True,
)
res = ob.add_documents(documents=docs)
ベクトル検索
この手順では、ドキュメント state_of_the_union.txt から “What did the president say about Ketanji Brown Jackson” を検索する方法を示します。
query = "What did the president say about Ketanji Brown Jackson"
docs_with_score = ob.similarity_search_with_score(query, k=3)
for doc, score in docs_with_score:
print("-" * 80)
print("Score: ", score)
print(doc.page_content)
print("-" * 80)
期待される出力:
--------------------------------------------------------------------------------
Score: 1.204783671324283
Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.
Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.
One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.
And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Score: 1.2146663629717394
It is going to transform America and put us on a path to win the economic competition of the 21st Century that we face with the rest of the world—particularly with China.
As I’ve told Xi Jinping, it is never a good bet to bet against the American people.
We’ll create good jobs for millions of Americans, modernizing roads, airports, ports, and waterways all across America.
And we’ll do it all to withstand the devastating effects of the climate crisis and promote environmental justice.
We’ll build a national network of 500,000 electric vehicle charging stations, begin to replace poisonous lead pipes—so every child—and every American—has clean water to drink at home and at school, provide affordable high-speed internet for every American—urban, suburban, rural, and tribal communities.
4,000 projects have already been announced.
And tonight, I’m announcing that this year we will start fixing over 65,000 miles of highway and 1,500 bridges in disrepair.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Score: 1.2193955178945004
Vice President Harris and I ran for office with a new economic vision for America.
Invest in America. Educate Americans. Grow the workforce. Build the economy from the bottom up
and the middle out, not from the top down.
Because we know that when the middle class grows, the poor have a ladder up and the wealthy do very well.
America used to have the best roads, bridges, and airports on Earth.
Now our infrastructure is ranked 13th in the world.
We won’t be able to compete for the jobs of the 21st Century if we don’t fix that.
That’s why it was so important to pass the Bipartisan Infrastructure Law—the most sweeping investment to rebuild America in history.
This was a bipartisan effort, and I want to thank the members of both parties who worked to make it happen.
We’re done talking about infrastructure weeks.
We’re going to have an infrastructure decade.
--------------------------------------------------------------------------------