見出し画像

Azure OpenAI x Pinecone x TeamsでFAQ検索ボットを作成する~Pineconeアップロード編


この記事について

この記事ではPineconeへのアップロードが行えるところまでを解説しています。ところどころソースは載せていますが、常に最新とはいかないので、参考までにしてください。

手順

1.Pineconeへの登録


無料で大丈夫です。やり方は他のサイトに譲りますが、公式からいっても大して手間はないです。pineconeの公式のQuickStartを再掲します。
How to get started with the Pinecone vector database.

2.pinecone.init()


import pinecone

pinecone.init(
    api_key = '自分のapikey'
    environment = '自分の環境'
)

一方で次のように書いてpineconeを返すこともできました。

def init():
    pinecone.init(
        api_key = '自分のapikey',
        environment = '自分の環境'
    )
    return pinecone


3.pinecone.create_index()


pineconeの無料プランはindexが一つだけ作れます。一つで十分という話はあります。

pinecone.create_index(
    index_name = 'index_of_faq',
    dimension = 1536,
    metric='cosine' 
)

こちらも同様に

def create_index(pinecone,index_name,dimension):
    if index_name not in pinecone.list_indexes():
        index = pinecone.create_index(
            index_name=index_name,
            dimension=dimension,
            metric='cosine' 
        )
        return index

のように関数を書くこともできました。indexがない場合はindexを作成するというものです。indexの作成が時間が少々かかるので、一連の処理を続けるか別出しするかは設計次第かなと

4.pinecone.upsert()


pinecone_index.upsert(
    vectors = zip(updata.id,updata.vector,updata.drop(columns=['id','vector']).to_dict(orient='records'))
)

updataは今回はpandasのデータフレームにしておいて、FAQ取得関数の内部で、

#textdataはFAQシステムから取得したQデータ
embeddings = embedded.embedding(textdata)
embeds = [record['embedding'] for record in embeddings['data']]

tempdata = pd.DataFrame(
    data={
        'id' : str(id),
        'vector' : [embeds],
        'url' : url[0:200,
       'text' : textdata.replace('\n','')[0:1000],
         'title' : title[0:100],
    }
 )
 updata = pd.concat([updata,tempdata])

このようにconcatを使ってデータを結合してもらっています。話をupsertに戻しますが、zipをしないとうまくいかなかったので、zipをしております。また、metadataはidとvectorのカラムをdropしないといけなかったです。
ここでの工夫のポイントはFAQのIDをそのままupsertのIDにすることによって、vector化してしまった文書の元データーをデータベースから探せるようにしていることです。
一方、embedding関数は自作ライブラリで外部ファイルになっておりまして、下記のようになっています。

#embedded.py

import openai

openai.api_type = 'azure'
openai.api_key = '自分のキー'
openai.api_base = '自分のエンドポイント'
openai.api_version = "2023-05-15"

def embedding(textdata):
    response = openai.Embedding.create(
        input=textdata,
        engine = 'text-embedding-ada-002-it',
        
    )
    return(response)

内容はこのようなシンプルなのものです。AzureOpenAIのportal上でキーとエンドポイントは確認できます。Azure OpenAIで作成したAzure OpenAIを開くと(名前がややこしいですね。。。)左のリソース管理に「キーとエンドポイント」があります。

5.pinecone.query()

本当に入ったかどうかは検索するのが一番です。

#pinesearch.py

import pinecone

def search(keyword):
    embeddings = embedded.embedding(keyword)
    embeds = [record['embedding'] for record in embeddings['data']]
    response = pinecone.query(
        top_k=3,
        vector=embeds
    )
    return(response)
#呼び出し元
import pinesearch

pinecone.init()
pcnindex = pinecone.Index(index_name='index_of_faq')
results = pinesearch.search(pcnindex,chat)

for res in results["matches"]:
    print(res['id'],res['score'])

コピペをしても動かないと思いますが、基本的なところはすべて押さえているとは思います。queryの解説は公式が一番参考になりました。よく見ると右側にcurlやpythonなどの言語切替ができるようになっています。今回はquery内でtop_k=3にしていますので、上位3つが返ってきています。

相互リンク

概要編

postgresqlアップロード編

pineconeにqueryを投げる+LLMで回答を作成する編

Logic App作成編



この記事が気に入ったらサポートをしてみませんか?