最も簡単にAIアプリケーションを構築し拡張する
Weaviateは、開発者が信頼性のあるAIアプリケーションを作成するのをサポートするオープンソースのAI Nativeのベクトルデータベースです。
クイックスタート
1. Weaviate データベース作成
まずはじめに、Weaviate データベースを作成します。
本記事ではクラウドマネージド版のWeaviate Cloud (WCD)の無料プランを使用します。
クラウド環境のセットアップにあたっては、WCD クイックスタート も参考にしてください。
オープンソースのWeaviateは、DockerやKubernetesなどでローカルに立てることもできます。
2. Weaviate Clientライブラリのインストール
次はWeaviate Clientライブラリの準備をします。ライブラリは以下の言語をサポートしています。
- Python
- TypeScript/JavaScript
- Go
- Java
必要なパッケージをインストールしてください。
- Python
- JS/TS
- Go
- Java
Install the latest, Python client v4
, by adding weaviate-client
to your Python environment with pip
:
pip install -U weaviate-client
Install the latest, JS/TS client v3
, by adding weaviate-client
to your project with npm
:
npm install weaviate-client
Add weaviate-go-client
to your project with go get
:
go get github.com/weaviate/weaviate-go-client/v4
Add this dependency to your project:
<dependency>
<groupId>io.weaviate</groupId>
<artifactId>client</artifactId>
<version>4.8.3</version> <!-- Check latest version: https://github.com/weaviate/java-client -->
</dependency>
3. 簡単なデータの取り込み
Weaviateの接続情報をセットアップ
次はWeaviate Clientを初期化します。Weaviateの接続情報をセットアップには以下の情報が必要です。
- 接続はWeaviateのURLとAPIキー (WCDの`Details` タブから)
- EmbeddingはOpenAIを使用するのでOpenAIのAPIキー (登録はこちら).
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Go
- Curl
import weaviate
import weaviate.classes as wvc
import os
# Best practice: store your credentials in environment variables
wcd_url = os.environ["WCD_DEMO_URL"]
wcd_api_key = os.environ["WCD_DEMO_RO_KEY"]
openai_api_key = os.environ["OPENAI_APIKEY"]
client = weaviate.connect_to_weaviate_cloud(
cluster_url=wcd_url, # Replace with your Weaviate Cloud URL
auth_credentials=wvc.init.Auth.api_key(wcd_api_key), # Replace with your Weaviate Cloud key
headers={"X-OpenAI-Api-Key": openai_api_key} # Replace with appropriate header key/value pair for the required API
)
try:
pass # Work with the client. Close client gracefully in the finally block.
finally:
client.close() # Close client gracefully
import weaviate
import json
client = weaviate.Client(
url = "https://WEAVIATE_INSTANCE_URL", # Replace with your Weaviate endpoint
auth_client_secret=weaviate.auth.AuthApiKey(api_key="YOUR-WEAVIATE-API-KEY"), # Replace with your Weaviate instance API key
additional_headers = {
"X-OpenAI-Api-Key": "YOUR-OPENAI-API-KEY" # Replace with your inference API key
}
)
import weaviate, { WeaviateClient } from 'weaviate-client';
const weaviateURL = process.env.WEAVIATE_URL as string
const weaviateKey = process.env.WEAVIATE_ADMIN_KEY as string
const openaiKey = process.env.OPENAI_API_KEY as string
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(weaviateURL, {
authCredentials: new weaviate.ApiKey(weaviateKey),
headers: {
'X-OpenAI-Api-Key': openaiKey, // Replace with your inference API key
}
})
import weaviate, { WeaviateClient, ObjectsBatcher, ApiKey } from 'weaviate-ts-client';
import fetch from 'node-fetch';
const client: WeaviateClient = weaviate.client({
scheme: 'https',
host: 'WEAVIATE_INSTANCE_URL', // Replace with your Weaviate endpoint
apiKey: new ApiKey('YOUR-WEAVIATE-API-KEY'), // Replace with your Weaviate instance API key
headers: { 'X-OpenAI-Api-Key': 'YOUR-OPENAI-API-KEY' }, // Replace with your inference API key
});
// Set these environment variables
// WEAVIATE_URL your Weaviate instance URL, without https prefix
// WEAVIATE_API_KEY your Weaviate instance API key
// OPENAI_API_KEY your OpenAI API key
package main
import (
"context"
"fmt"
"os"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/weaviate/auth"
)
// Create the client
func CreateClient() {
cfg := weaviate.Config{
Host: os.Getenv("WEAVIATE_URL"),
Scheme: "https",
AuthConfig: auth.ApiKey{Value: os.Getenv("WEAVIATE_API_KEY")},
Headers: map[string]string{
"X-OpenAI-Api-Key": os.Getenv("OPENAI_API_KEY"),
},
}
client, err := weaviate.NewClient(cfg)
if err != nil {
fmt.Println(err)
}
// Check the connection
live, err := client.Misc().LiveChecker().Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("%v", live)
}
func main() {
CreateClient()
}
- With
curl
, add the API key to the header as shown below:
echo '{
"query": "<QUERY>"
}' | curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR-WEAVIATE-API-KEY" \
-H "X-OpenAI-Api-Key: $OPENAI_API_KEY" \
-d @- \
https://WEAVIATE_INSTANCE_URL/v1/graphql # Replace WEAVIATE_INSTANCE_URL with your instance URL
サンプルデータ
今回用いるサンプルデータは、"Jeopardy!"データです。
Category | Question | Answer | |
---|---|---|---|
0 | SCIENCE | This organ removes excess glucose from the blood & stores it as glycogen | Liver |
1 | ANIMALS | It's the only living mammal in the order Proboseidea | Elephant |
2 | ANIMALS | The gavial looks very much like a crocodile except for this bodily feature | the nose or snout |
3 | ANIMALS | Weighing around a ton, the eland is the largest species of this animal in Africa | Antelope |
4 | ANIMALS | Heaviest of all poisonous snakes is this North American rattlesnake | the diamondback rattler |
5 | SCIENCE | 2000 news: the Gunnison sage grouse isn't just another northern sage grouse, but a new one of this classification | species |
データコレクションの定義
次は、クラスを作成してSchemaを定義します。
クラスは、オブジェクトを格納するデータコレクションです。
クラスのSchemaにモジュールを定義します。
- Vectorizerモジュールには
text2vec-openai
を使用します。 - Generatorモジュールには
generative-openai
を使用します。
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Go
- Curl
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
)
class_obj = {
"class": "Question",
"vectorizer": "text2vec-openai", # If set to "none" you must always provide vectors yourself. Could be any other "text2vec-*" also.
"moduleConfig": {
"text2vec-openai": {},
"generative-openai": {} # Ensure the `generative-openai` module is used for generative queries
}
}
client.schema.create_class(class_obj)
import { vectorizer, generative } from 'weaviate-client'
async function createCollection() {
const questions = await client.collections.create({
name: 'Question',
vectorizers: vectorizer.text2VecOpenAI(),
generative: generative.openAI(),
})
console.log(`Collection ${questions.name} created!`);
}
await createCollection();
const classObj = {
'class': 'Question',
'vectorizer': 'text2vec-openai', // If set to "none" you must always provide vectors yourself. Could be any other "text2vec-*" also.
'moduleConfig': {
'text2vec-openai': {},
'generative-openai': {} // Ensure the `generative-openai` module is used for generative queries
},
};
async function addSchema() {
const res = await client.schema.classCreator().withClass(classObj).do();
console.log(res);
}
await addSchema();
// Set these environment variables
// WEAVIATE_URL your Weaviate instance URL, without https prefix
// WEAVIATE_API_KEY your Weaviate instance API key
// OPENAI_API_KEY your OpenAI API key
package main
import (
"context"
"fmt"
"os"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/weaviate/auth"
"github.com/weaviate/weaviate/entities/models"
)
func main() {
// Create the client
cfg := weaviate.Config{
Host: os.Getenv("WEAVIATE_URL"),
Scheme: "https",
AuthConfig: auth.ApiKey{Value: os.Getenv("WEAVIATE_API_KEY")},
Headers: map[string]string{
"X-OpenAI-Api-Key": os.Getenv("OPENAI_API_KEY"),
},
}
client, err := weaviate.NewClient(cfg)
if err != nil {
fmt.Println(err)
}
classObj := &models.Class{
Class: "Question",
Vectorizer: "text2vec-openai", // If "none" you must always provide vectors yourself. Could be any other "text2vec-*" also.
ModuleConfig: map[string]interface{}{
"text2vec-openai": map[string]interface{}{},
"generative-openai": map[string]interface{}{},
},
}
// add the schema
err = client.Schema().ClassCreator().WithClass(classObj).Do(context.Background())
if err != nil {
panic(err)
}
}
echo '{
"class": "Question",
"vectorizer": "text2vec-openai",
"moduleConfig": {
"text2vec-openai": {},
"generative-openai": {}
}
}' | curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $WEAVIATE_API_KEY" \
-d @- \
https://WEAVIATE_INSTANCE_URL/v1/schema # Replace WEAVIATE_INSTANCE_URL with your instance URL
データ登録
次はWeaviateのClientにデータを登録します。
事前にベクトル化する必要はなく、Vectorizerモジュールでベクトル化して取り込めます。
なので、ベクトルデータではなくデータオブジェクトをそのまま登録します。
内部的にはVectorizerのtext2vec-openai
モジュールが、OpenAPIのEmbeddings APIを実行してベクトルに変換しています。
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Go
- Curl
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)
import requests
import json
resp = requests.get('https://raw.githubusercontent.com/weaviate-tutorials/quickstart/main/data/jeopardy_tiny.json')
data = json.loads(resp.text) # Load data
client.batch.configure(batch_size=100) # Configure batch
with client.batch as batch: # Initialize a batch process
for i, d in enumerate(data): # Batch import data
print(f"importing question: {i+1}")
properties = {
"answer": d["Answer"],
"question": d["Question"],
"category": d["Category"],
}
batch.add_data_object(
data_object=properties,
class_name="Question"
)
async function getJsonData() {
const file = await fetch('https://raw.githubusercontent.com/weaviate-tutorials/quickstart/main/data/jeopardy_tiny.json');
return file.json();
}
async function importQuestions() {
// Get the questions directly from the URL
const questions = client.collections.get('Question');
const data = await getJsonData();
const result = await questions.data.insertMany(data)
console.log('We just bulk inserted',result);
}
await importQuestions();
async function getJsonData() {
const file = await fetch('https://raw.githubusercontent.com/weaviate-tutorials/quickstart/main/data/jeopardy_tiny.json');
return file.json();
}
async function importQuestions() {
// Get the questions directly from the URL
const data = await getJsonData();
// Prepare a batcher
let batcher: ObjectsBatcher = client.batch.objectsBatcher();
let counter = 0;
const batchSize = 100;
for (const question of data) {
// Construct an object with a class and properties 'answer' and 'question'
const obj = {
class: 'Question',
properties: {
answer: question.Answer,
question: question.Question,
category: question.Category,
},
};
// add the object to the batch queue
batcher = batcher.withObject(obj);
// When the batch counter reaches batchSize, push the objects to Weaviate
if (counter++ == batchSize) {
// flush the batch queue
const res = await batcher.do();
console.log(res);
// restart the batch queue
counter = 0;
batcher = client.batch.objectsBatcher();
}
}
// Flush the remaining objects
const res = await batcher.do();
console.log(res);
}
await importQuestions();
// Set these environment variables
// WEAVIATE_URL your Weaviate instance URL, without https prefix
// WEAVIATE_API_KEY your Weaviate instance API key
// OPENAI_API_KEY your OpenAI API key
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/weaviate/auth"
"github.com/weaviate/weaviate/entities/models"
)
func main() {
// Create the client
cfg := weaviate.Config{
Host: os.Getenv("WEAVIATE_URL"),
Scheme: "https",
AuthConfig: auth.ApiKey{Value: os.Getenv("WEAVIATE_API_KEY")},
Headers: map[string]string{
"X-OpenAI-Api-Key": os.Getenv("OPENAI_API_KEY"),
},
}
client, err := weaviate.NewClient(cfg)
if err != nil {
fmt.Println(err)
}
// Retrieve the data
data, err := http.DefaultClient.Get("https://raw.githubusercontent.com/weaviate-tutorials/quickstart/main/data/jeopardy_tiny.json")
if err != nil {
panic(err)
}
defer data.Body.Close()
// Decode the data
var items []map[string]string
if err := json.NewDecoder(data.Body).Decode(&items); err != nil {
panic(err)
}
// convert items into a slice of models.Object
objects := make([]*models.Object, len(items))
for i := range items {
objects[i] = &models.Object{
Class: "Question",
Properties: map[string]any{
"category": items[i]["Category"],
"question": items[i]["Question"],
"answer": items[i]["Answer"],
},
}
}
// batch write items
batchRes, err := client.Batch().ObjectsBatcher().WithObjects(objects...).Do(context.Background())
if err != nil {
panic(err)
}
for _, res := range batchRes {
if res.Result.Errors != nil {
panic(res.Result.Errors.Error)
}
}
}
# Replace with your Weaviate endpoint
API_URL="http://WEAVIATE_INSTANCE_URL/v1/batch/objects"
# Replace with your Inference API token
OPENAI_API_TOKEN="<OpenAI-API-Token>"
# Set batch size
BATCH_SIZE=100
# Read the JSON file and loop through its entries
lines_processed=0
batch_data="{\"objects\": ["
cat jeopardy_tiny.json | jq -c '.[]' | while read line; do
# Concatenate lines
line=$(echo "$line" | jq "{class: \"Question\", properties: {answer: .Answer, question: .Question, category: .Category}}")
if [ $lines_processed -eq 0 ]; then
batch_data+=$line
else
batch_data+=",$line"
fi
lines_processed=$((lines_processed + 1))
# If the batch is full, send it to the API using curl
if [ $lines_processed -eq $BATCH_SIZE ]; then
batch_data+="]}"
curl -X POST "$API_URL" \
-H "Content-Type: application/json" \
-H "X-OpenAI-Api-Key: $OPENAI_API_TOKEN" \
-d "$batch_data"
echo "" # Print a newline for better output formatting
# Reset the batch data and counter
lines_processed=0
batch_data="{\"objects\": ["
fi
done
# Send the remaining data (if any) to the API using curl
if [ $lines_processed -ne 0 ]; then
batch_data+="]}"
curl -X POST "$API_URL" \
-H "Content-Type: application/json" \
-H "X-OpenAI-Api-Key: $OPENAI_API_TOKEN" \
-d "$batch_data"
echo "" # Print a newline for better output formatting
fi
4. クエリ方法
Weaviateを使ってベクトル検索、キーワード検索とハイブリッド検索のクエリを実行できます。
Generatorモジュールを使って簡単に検索拡張生成もできます。
このチュートリアルではベクトル検索と検索拡張生成の方法を紹介させていただきます。
ベクトル検索
まずは、ベクトル検索のクエリを実行します。
クエリのnearText
で指定した文章に関連するデータオブジェクトが取得でます。
テキストを入力値として、類似度の高いデータを検索します。
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Go
- Curl
import weaviate
import weaviate.classes as wvc
import os
# Best practice: store your credentials in environment variables
wcd_url = os.environ["WCD_DEMO_URL"]
wcd_api_key = os.environ["WCD_DEMO_RO_KEY"]
openai_api_key = os.environ["OPENAI_APIKEY"]
client = weaviate.connect_to_weaviate_cloud(
cluster_url=wcd_url, # Replace with your Weaviate Cloud URL
auth_credentials=wvc.init.Auth.api_key(wcd_api_key), # Replace with your Weaviate Cloud key
headers={"X-OpenAI-Api-Key": openai_api_key} # Replace with appropriate header key/value pair for the required API
)
try:
pass # Work with the client. 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
import weaviate
import json
client = weaviate.Client(
url = "https://WEAVIATE_INSTANCE_URL", # Replace with your Weaviate endpoint
auth_client_secret=weaviate.auth.AuthApiKey(api_key="YOUR-WEAVIATE-API-KEY"), # Replace with your Weaviate instance API key
additional_headers = {
"X-OpenAI-Api-Key": "YOUR-OPENAI-API-KEY" # Replace with your inference API key
}
)
response = (
client.query
.get("Question", ["question", "answer", "category"])
.with_near_text({"concepts": ["biology"]})
.with_limit(2)
.do()
)
print(json.dumps(response, indent=4))
import weaviate, { WeaviateClient } from 'weaviate-client';
const weaviateURL = process.env.WEAVIATE_URL as string
const weaviateKey = process.env.WEAVIATE_ADMIN_KEY as string
const openaiKey = process.env.OPENAI_API_KEY as string
const client: WeaviateClient = await weaviate.connectToWeaviateCloud(weaviateURL, {
authCredentials: new weaviate.ApiKey(weaviateKey),
headers: {
'X-OpenAI-Api-Key': openaiKey, // Replace with your inference API key
}
})
async function nearTextQuery() {
const questions = client.collections.get('Question');
const result = await questions.query.nearText('biology', {
limit:2
});
for (let object of result.objects) {
console.log(JSON.stringify(object.properties, null, 2));
}
return result;
}
await nearTextQuery();
import weaviate, { WeaviateClient, ObjectsBatcher, ApiKey } from 'weaviate-ts-client';
import fetch from 'node-fetch';
const client: WeaviateClient = weaviate.client({
scheme: 'https',
host: 'WEAVIATE_INSTANCE_URL', // Replace with your Weaviate endpoint
apiKey: new ApiKey('YOUR-WEAVIATE-API-KEY'), // Replace with your Weaviate instance API key
headers: { 'X-OpenAI-Api-Key': 'YOUR-OPENAI-API-KEY' }, // Replace with your inference API key
});
async function nearTextQuery() {
const res = await client.graphql
.get()
.withClassName('Question')
.withFields('question answer category')
.withNearText({concepts: ['biology']})
.withLimit(2)
.do();
console.log(JSON.stringify(res, null, 2));
return res;
}
await nearTextQuery();
await nearTextWhereQuery();
// Set these environment variables
// WEAVIATE_URL your Weaviate instance URL, without https prefix
// WEAVIATE_API_KEY your Weaviate instance API key
// OPENAI_API_KEY your OpenAI API key
package main
import (
"context"
"fmt"
"os"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/weaviate/auth"
"github.com/weaviate/weaviate-go-client/v4/weaviate/graphql"
)
func main() {
// Create the client
cfg := weaviate.Config{
Host: os.Getenv("WEAVIATE_URL"),
Scheme: "https",
AuthConfig: auth.ApiKey{Value: os.Getenv("WEAVIATE_API_KEY")},
Headers: map[string]string{
"X-OpenAI-Api-Key": os.Getenv("OPENAI_API_KEY"),
},
}
client, err := weaviate.NewClient(cfg)
if err != nil {
fmt.Println(err)
}
fields := []graphql.Field{
{Name: "question"},
{Name: "answer"},
{Name: "category"},
}
nearText := client.GraphQL().
NearTextArgBuilder().
WithConcepts([]string{"biology"})
result, err := client.GraphQL().Get().
WithClassName("Question").
WithFields(fields...).
WithNearText(nearText).
WithLimit(2).
Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("%v", result)
}
echo '{
"query": "{
Get {
Question (
limit: 2
nearText: {
concepts: [\"biology\"],
}
) {
question
answer
category
}
}
}"
}' | tr -d "\n" | curl \
-X POST \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $WEAVIATE_API_KEY" \
-H "X-OpenAI-Api-Key: $OPENAI_API_KEY" \
-d @- \
https://WEAVIATE_INSTANCE_URL/v1/graphql # Replace WEAVIATE_INSTANCE_URL with your instance URL # Replace this with your endpoint
結果はこちら
{
"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モジュールを使ってプロンプトで結果を加工することがでます。
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Go
- Curl
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
response = (
client.query
.get("Question", ["question", "answer", "category"])
.with_near_text({"concepts": ["biology"]})
.with_generate(single_prompt="Explain {answer} as you might to a five-year-old.")
.with_limit(2)
.do()
)
print(json.dumps(response, indent=4))
async function generativeSearchQuery() {
const questions = client.collections.get('Question');
const result = await questions.generate.nearText('biology',
{ singlePrompt: `Explain {answer} as you might to a five-year-old.` },
{ limit: 2 }
);
for (let object of result.objects) {
console.log(JSON.stringify(object.properties, null, 2));
console.log(object.generated);
}
return result;
}
await generativeSearchQuery();
import weaviate, { WeaviateClient, ObjectsBatcher, ApiKey } from 'weaviate-ts-client';
import fetch from 'node-fetch';
const client: WeaviateClient = weaviate.client({
scheme: 'https',
host: 'WEAVIATE_INSTANCE_URL', // Replace with your Weaviate endpoint
apiKey: new ApiKey('YOUR-WEAVIATE-API-KEY'), // Replace with your Weaviate instance API key
headers: { 'X-OpenAI-Api-Key': 'YOUR-OPENAI-API-KEY' }, // Replace with your inference API key
});
async function generativeSearchQuery() {
const res = await client.graphql
.get()
.withClassName('Question')
.withFields('question answer category')
.withNearText({concepts: ['biology']})
.withGenerate({singlePrompt: 'Explain {answer} as you might to a five-year-old.'})
.withLimit(2)
.do();
console.log(JSON.stringify(res, null, 2));
return res;
}
await generativeSearchQuery();
// Set these environment variables
// WEAVIATE_URL your Weaviate instance URL, without https prefix
// WEAVIATE_API_KEY your Weaviate instance API key
// OPENAI_API_KEY your OpenAI API key
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/weaviate/auth"
"github.com/weaviate/weaviate-go-client/v4/weaviate/graphql"
)
func main() {
// Create the client
cfg := weaviate.Config{
Host: os.Getenv("WEAVIATE_URL"),
Scheme: "https",
AuthConfig: auth.ApiKey{Value: os.Getenv("WEAVIATE_API_KEY")},
Headers: map[string]string{
"X-OpenAI-Api-Key": os.Getenv("OPENAI_API_KEY"),
},
}
client, err := weaviate.NewClient(cfg)
if err != nil {
fmt.Println(err)
}
fields := []graphql.Field{
{Name: "question"},
{Name: "answer"},
{Name: "category"},
}
nearText := client.GraphQL().
NearTextArgBuilder().
WithConcepts([]string{"biology"})
generativeSearch := graphql.NewGenerativeSearch().SingleResult("Explain {answer} as you might to a five-year-old.")
result, err := client.GraphQL().Get().
WithClassName("Question").
WithFields(fields...).
WithNearText(nearText).
WithLimit(2).
WithGenerativeSearch(generativeSearch).
Do(context.Background())
if err != nil {
panic(err)
}
jsonOutput, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(jsonOutput))
}
echo '{
"query": "{
Get {
Question (
limit: 2
nearText: {
concepts: [\"biology\"],
}
) {
question
answer
category
_additional {
generate(
singleResult: {
prompt: \"\"\"
Explain {answer} as you might to a five-year-old.
\"\"\"
}
) {
singleResult
error
}
}
}
}
}"
}' | curl \
-X POST \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $WEAVIATE_API_KEY" \
-H "X-OpenAI-Api-Key: $OPENAI_API_KEY" \
-d @- \
https://WEAVIATE_INSTANCE_URL/v1/graphql # Replace WEAVIATE_INSTANCE_URL with your instance URL # Replace this with your endpoint
結果はこちら
{
"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"
}
]
}
}
}