😴

Llama-index / Milvus / OpenAI

2024/03/06に公開

概要

llama-index / milvus を調査し、個人の備忘録として残す
基本的には本家サイトのチュートリアルレベルで、以下を簡単な仕様とする

  1. 我が家で使用する家電の PDF を milvus で永続化
  2. 上記データを元に GPT-4 で質問し、解答を得る(テレビの使い方など)

対象 / 留意事項

この記事の対象となる方は以下

  • llama-index に興味があるが使った事がない
  • milvus に興味があるが使った事がない
  • OpenAI API のアカウントを持っている

留意事項として OpenAI API をコールするので有料となる (sk- で始まるキーが必要)

調査 / マニュアル

英語ではあるが、マニュアルがしっかりとしているので、それほど困る事はない

https://docs.llamaindex.ai/en/stable/
https://milvus.io/docs
https://platform.openai.com/docs/api-reference

PDF データの取得

我が家の家電ラインナップは以下 (テレビは Netflix / Youtube 専用)

テレビはソニーブラビア75インチ
https://www.sony.jp/ServiceArea/impdf/manual/50258280XRJ-85X95J.html

冷蔵庫はプラズマクラスター
https://jp.sharp/support/download/members/?productId=SJ-GS46C

洗濯機はビートウォッシュ12kg
https://kadenfan.hitachi.co.jp/support/wash/item/BW-DKX120G/manual.html

これらを取得し、適当な場所へ保存する (ここでは input 以下へ配置)

実装

ライブラリインストール

多分これだけで依存関係までインストールされたはず

  • llama-index
  • llama-index-vector-stores-milvus
  • llama-index-llms-openai
  • openai
 $ pip install llama-index
 $ pin install llama-index-vector-stores-milvus
 $ pip install llama-index-llms-openai
 $ pip install openai 

mivlus 本体のインストール

取得した起動スクリプトは内部的に docker を sudo で実行するので
一般ユーザーで起動させたい場合は2行目も実行する (sed でもいいが私は perl)

 $ curl https://raw.githubusercontent.com/milvus-io/milvus/master/scripts/standalone_embed.sh > standalone_embed.sh
 $ perl -pi -e 's/sudo //g' standalone_embed.sh

milvus の起動

 $ bash standalone_embed.sh start

書き込みと読み込み

何をしているのかを分かりやすく為に、それぞれでコードを分けた

write_milvus.py

  • llama-index ライブラリ経由で我が家で使用する家電の PDF を milvus に永続化
import logging
import sys 

from llama_index.vector_stores.milvus import MilvusVectorStore
from llama_index.core import (
        VectorStoreIndex,
        SimpleDirectoryReader,
        StorageContext,
)

# Uncomment to see debug logs
# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))

documents = SimpleDirectoryReader("input").load_data()

vector_store = MilvusVectorStore(uri="http://localhost:19530", dim=1536, overwrite=True)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context
)

read_milvus.py

  • 上記データを元に GPT-4 に質問し、解答を得る(テレビの再起動方法)
import logging
import sys 
import os
import openai

from llama_index.vector_stores.milvus import MilvusVectorStore
from llama_index.llms.openai import OpenAI
from llama_index.core import (
        VectorStoreIndex,
        Settings,
        StorageContext,
)

# Uncomment to see debug logs
# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))

openai.api_key = os.getenv("OPENAI_API_KEY")
Settings.llm = OpenAI(model='gpt-4', temperature=0, max_tokens=1024)

vector_store = MilvusVectorStore(uri="http://localhost:19530", dim=1536, overwrite=False)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

index = VectorStoreIndex.from_vector_store(
    vector_store, storage_context=storage_context
)

query_engine = index.as_query_engine()
response = query_engine.query("テレビの再起動方法")
print(response)

実行 / 結果

上記コードを実行する

 $ python write_milvus.py
 $ python read_milvus.py

結果は以下となり、PDF の内容と合っている
質問を洗濯機や冷蔵庫の使い方に変えてみても正しい解答を得る事が出来た

テレビの再起動方法は次の通りです。まず、リモコンの電源ボタンを電源が切れるまで押し続けてください。これには5秒以上かかる場合があります。その後、自動で電源が入るまで1分程度待つ必要があります。それでも
問題が解決しない場合は、テレビの電源プラグを抜き、テレビの電源ボタンを1回押してください。その後、2分間待ってからテレビの電源を再度入れてください。または、テレビの電源ボタンを電源が切れるまで押し続け
てください。これには40秒以上かかる場合があります。

ここで調査を終了し、何かを実装してみようと思う

まとめ

llama-index

LLMs are trained on enormous bodies of data but they aren’t trained on your data. Retrieval-Augmented Generation (RAG) solves this problem by adding your data to the data LLMs already have access to. You will see references to RAG frequently in this documentation.

In RAG, your data is loaded and prepared for queries or “indexed”. User queries act on the index, which filters your data down to the most relevant context. This context and your query then go to the LLM along with a prompt, and the LLM provides a response.

Even if what you’re building is a chatbot or an agent, you’ll want to know RAG techniques for getting data into your application.

Milvus

Milvus was created in 2019 with a singular goal: store, index, and manage massive embedding vectors generated by deep neural networks and other machine learning (ML) models.

As a database specifically designed to handle queries over input vectors, it is capable of indexing vectors on a trillion scale. Unlike existing relational databases which mainly deal with structured data following a pre-defined pattern, Milvus is designed from the bottom-up to handle embedding vectors converted from unstructured data.

As the Internet grew and evolved, unstructured data became more and more common, including emails, papers, IoT sensor data, Facebook photos, protein structures, and much more. In order for computers to understand and process unstructured data, these are converted into vectors using embedding techniques. Milvus stores and indexes these vectors. Milvus is able to analyze the correlation between two vectors by calculating their similarity distance. If the two embedding vectors are very similar, it means that the original data sources are similar as well.

https://milvus.io/docs/overview.md より

Discussion