5
3
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

ローカル環境で生成AIモデルの回答結果を得る

Last updated at Posted at 2024-01-01

生成AI=ChatGPT?

API経由で生成AIを呼び出すWebアプリを作ろうと思った時に、今まではOpenAIのAPIを呼び出していたが、もし思うようにOpenAIのAPIが使えなくなると今後Webアプリ開発などで支障が出る可能性がある。
そこで、ローカル環境でLLMモデルを使う方法について整理した。

TL;DR

  1. WSL2環境(ubuntu)にllama-cpp-pythonを入れる。
  2. モデルファイル(gguf)をhuggingfaceからダウンロードする。
  3. pythonでLLMモデルにクエリを投げるコードを書く。

実行環境用意

実行環境はWSL2上のubuntuで、python3が入っている。
以下コマンドでllama-cpp-pythonを入れる。

pip3 install llama-cpp-python

モデルファイルのダウンロード

huggingfaceのサイトからモデルファイルをダウンロードする。拡張子が「.bin」でなく、「.gguf」であるものをダウンロードすることに注意。
今回は以下のモデルファイルをダウンロードした。
Llama-2-7B-Chat-GGUF

モデルファイルをダウンロードする時は、モデルファイルのフロントページにアクセスして「Files and versions」タブを選択し、一番下のggufファイルをダウンロードする。
ダウンロードボタンのアクセスリンクをコピーして以下のようにwgetする。

wget -O llama-2-7b-chat.Q8_0.gguf https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF/resolve/main/llama-2-7b-chat.Q8_0.gguf?download=true

生成AIモデルと対話するコード

LLMモデルに問いかけ、応答を確認するコード。

from llama_cpp import Llama

model_name = "llama-2-7b-chat.Q8_0.gguf"
llm = Llama(model_path="./models/" + model_name)

while True:
    text = input("What is your question? [type 'exit' to end]: ")
    if text == "exit":
        break
    query = "Q: " + text + " A: "
    output = llm(query, max_tokens=64, stop=["Q:", "\n"], echo=True)
    print(output)

このコードを実行すると、コンソールが入力待機状態になる。そこで、質問を入力するとダウンロードしたLLMモデルを使って回答が得られる。会話を終了する場合は「exit」と入力する。
以下は会話の例。
「Why is dinosaur extinct?」と入力。WSL2に16GBメモリ、2コアCPUを割り振ったローカル環境での応答時間は5秒程度だった。

What is your question? [type 'exit' to end]: Why is dinosaur extinct?
〜〜〜
{
    'id': 'cmpl-993fec40-c6f5-4d0f-876b-3b7bfdae0095',
  'object': 'text_completion',
  'created': 1704121983,
  'model': './models/llama-2-7b-chat.Q8_0.gguf',
  'choices': [
    {
    'text': 'Q: Why is dinosaur extinct? A:  Dinosaurs are not actually extinct.  In fact, many species of dinosaurs are still alive today and can be found in the modern world. For example, birds are direct descendants of certain species of theropod dinosaurs and share many similarities with them. So, while the last of',
    'index': 0,
    'logprobs': None,
    'finish_reason': 'length'
   }
  ],
  'usage': {
    'prompt_tokens': 14,
    'completion_tokens': 64,
    'total_tokens': 78
  }
}

まとめ

ローカル環境でLLMモデルファイルを使い、簡単に生成AIとやりとりするpythonコードを作成することができた。
このコードをAPIサーバー中に組み込めば簡単に生成AIの結果を返すAPIを作成することができるとわかった。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3