Skip to main content

最も簡単にAIアプリケーションを構築し拡張する

Weaviateは、開発者が信頼性のあるAIアプリケーションを作成するのをサポートするオープンソースのAI Nativeのベクトルデータベースです。

クイックスタート

1. Weaviate データベース作成

まずはじめに、Weaviate データベースを作成します。

本記事ではクラウドマネージド版のWeaviate Cloud Services(WCS)の無料プランを使用します。

クラウド環境のセットアップにあたっては、WCS クイックスタート も参考にしてください。

オープンソースのWeaviateは、DockerやKubernetesなどでローカルに立てることもできます。

2. Weaviate Clientライブラリのインストール

次はWeaviate Clientライブラリの準備をします。ライブラリは以下の言語をサポートしています。

  • Python
  • TypeScript/JavaScript
  • Go
  • Java

必要なパッケージをインストールしてください。

Add weaviate-client to your Python environment with pip. The v4 client requires Weaviate 1.23 or higher.

pip install -U weaviate-client

3. 簡単なデータの取り込み

Weaviateの接続情報をセットアップ

次はWeaviate Clientを初期化します。Weaviateの接続情報をセットアップには以下の情報が必要です。

  • 接続はWeaviateのURLとAPIキー (WCSの`Details` タブから)
  • EmbeddingはOpenAIを使用するのでOpenAIのAPIキー (登録はこちら).
import weaviate
import weaviate.classes as wvc
import os
import requests
import json

client = weaviate.connect_to_wcs(
cluster_url=os.getenv("WCS_URL"),
auth_credentials=weaviate.auth.AuthApiKey(os.getenv("WCS_API_KEY")),
headers={
"X-OpenAI-Api-Key": os.environ["OPENAI_APIKEY"] # Replace with your inference API key
}
)

try:
pass # Replace with your code. Close client gracefully in the finally block.

finally:
client.close() # Close client gracefully

サンプルデータ

今回用いるサンプルデータは、"Jeopardy!"データです。

 CategoryQuestionAnswer
0SCIENCEThis organ removes excess glucose from the blood & stores it as glycogenLiver
1ANIMALSIt's the only living mammal in the order ProboseideaElephant
2ANIMALSThe gavial looks very much like a crocodile except for this bodily featurethe nose or snout
3ANIMALSWeighing around a ton, the eland is the largest species of this animal in AfricaAntelope
4ANIMALSHeaviest of all poisonous snakes is this North American rattlesnakethe diamondback rattler
5SCIENCE2000 news: the Gunnison sage grouse isn't just another northern sage grouse, but a new one of this classificationspecies

データコレクションの定義

次は、クラスを作成してSchemaを定義します。

クラスは、オブジェクトを格納するデータコレクションです。

クラスのSchemaにモジュールを定義します。

  • Vectorizerモジュールにはtext2vec-openaiを使用します。
  • Generatorモジュールにはgenerative-openaiを使用します。
    questions = client.collections.create(
name="Question",
vectorizer_config=wvc.config.Configure.Vectorizer.text2vec_openai(), # If set to "none" you must always provide vectors yourself. Could be any other "text2vec-*" also.
generative_config=wvc.config.Configure.Generative.openai() # Ensure the `generative-openai` module is used for generative queries
)

データ登録

次はWeaviateのClientにデータを登録します。

事前にベクトル化する必要はなく、Vectorizerモジュールでベクトル化して取り込めます。

なので、ベクトルデータではなくデータオブジェクトをそのまま登録します。

内部的にはVectorizerのtext2vec-openaiモジュールが、OpenAPIのEmbeddings APIを実行してベクトルに変換しています。

    resp = requests.get('https://raw.githubusercontent.com/weaviate-tutorials/quickstart/main/data/jeopardy_tiny.json')
data = json.loads(resp.text) # Load data

question_objs = list()
for i, d in enumerate(data):
question_objs.append({
"answer": d["Answer"],
"question": d["Question"],
"category": d["Category"],
})

questions = client.collections.get("Question")
questions.data.insert_many(question_objs)

4. クエリ方法

Weaviateを使ってベクトル検索、キーワード検索とハイブリッド検索のクエリを実行できます。

Generatorモジュールを使って簡単に検索拡張生成もできます。

このチュートリアルではベクトル検索と検索拡張生成の方法を紹介させていただきます。

ベクトル検索

まずは、ベクトル検索のクエリを実行します。

クエリのnearTextで指定した文章に関連するデータオブジェクトが取得でます。

テキストを入力値として、類似度の高いデータを検索します。

import weaviate
import weaviate.classes as wvc
import os

client = weaviate.connect_to_wcs(
cluster_url=os.getenv("WCS_URL"),
auth_credentials=weaviate.auth.AuthApiKey(os.getenv("WCS_API_KEY")),
headers={
"X-OpenAI-Api-Key": os.environ["OPENAI_APIKEY"] # Replace with your inference API key
}
)

try:
pass # Replace with your code. Close client gracefully in the finally block.
questions = client.collections.get("Question")

response = questions.query.near_text(
query="biology",
limit=2
)

print(response.objects[0].properties) # Inspect the first object

finally:
client.close() # Close client gracefully

結果はこちら

{
    "data": {
        "Get": {
            "Question": [
                {
                    "answer": "DNA",
                    "category": "SCIENCE",
                    "question": "In 1953 Watson & Crick built a model of the molecular structure of this, the gene-carrying substance"
                },
                {
                    "answer": "Liver",
                    "category": "SCIENCE",
                    "question": "This organ removes excess glucose from the blood & stores it as glycogen"
                }
            ]
        }
    }
}

検索拡張生成 (RAG)

次は、検索拡張生成のクエリを実行します。

まずは、ベクトル検索のクエリと似たようにnearTextで検索します。

nearTextで検索したデータオブジェクトに対して、Generatorモジュールを使ってプロンプトで結果を加工することがでます。

    questions = client.collections.get("Question")

response = questions.generate.near_text(
query="biology",
limit=2,
single_prompt="Explain {answer} as you might to a five-year-old."
)

print(response.objects[0].generated) # Inspect the generated text

結果はこちら

{
    "data": {
        "Get": {
            "Question": [
                {
                    "_additional": {
                        "generate": {
                            "error": null,
                            "singleResult": "DNA is like a special code that tells our bodies how to grow and work. It's like a recipe book that has all the instructions for making you who you are. Just like a recipe book has different recipes for different foods, DNA has different instructions for making different parts of your body, like your eyes, hair, and even your personality! It's really amazing because it's what makes you unique and special."
                        }
                    },
                    "answer": "DNA",
                    "category": "SCIENCE",
                    "question": "In 1953 Watson & Crick built a model of the molecular structure of this, the gene-carrying substance"
                },
                {
                    "_additional": {
                        "generate": {
                            "error": null,
                            "singleResult": "Well, a species is a group of living things that are similar to each other in many ways. They have the same kind of body parts, like legs or wings, and they can have babies with other members of their species. For example, dogs are a species, and so are cats. They look different and act differently, but all dogs can have puppies with other dogs, and all cats can have kittens with other cats. So, a species is like a big family of animals or plants that are all related to each other in a special way."
                        }
                    },
                    "answer": "species",
                    "category": "SCIENCE",
                    "question": "2000 news: the Gunnison sage grouse isn't just another northern sage grouse, but a new one of this classification"
                }
            ]
        }
    }
}

お問い合わせ