Opensourcetechブログ

OpensourcetechによるNGINX/Kubernetes/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

OpenAIのAPIを使ってみる


LinuCエヴァンジェリスト・Open Source Summit Japan 2022ボランティアリーダー鯨井貴博@opensourcetechです。


はじめに
今回はOpenAIのAPIを使ったPythonの簡単な対話型プログラムを作ってみようと思います。


前提
APIを使うためのKeyの発行に、OpenAIの有料アカウント(サブスクリプション)が必要となります。
また、APIの利用にはそのサブスクリプションと別で料金が発生するので注意が必要です。
https://openai.com/pricing
https://help.openai.com/en/articles/7039783-how-can-i-access-the-chatgpt-api
※5ドルのフリートライアルが用意されている模様。


APIKeyの発行
まず、APIを使うためのAPIKeyを発行します。
openaiのサイトへログインして、API → 右上のメニュからView API KeysCreate new secret keyとすれば発行できます。





<対話型プログラムの作成/span>
まず、環境変数として先ほど作成したAPIKeyを定義します。
※Pythonのプログラム中で定義する方法もある。

export OPENAI_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'


Pythonコード。
python3 question_answer.py "質問内容"という形式で実行できます。

import os
import sys
import openai

openai.api_key = os.getenv('OPENAI_API_KEY')

def get_answer(question):
    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": question}
      ]
    )
    return response.choices[0].message.content

if len(sys.argv) > 1:
    question = sys.argv[1]
    answer = get_answer(question)
    print("Answer:", answer)
else:
    print("Please provide a question as a command line argument.")

https://github.com/kujiraitakahiro/python/blob/master/question_answer.py


プログラムの実行
では、実行してみます。
サンプルとして、おいしいコーヒーゼリーの作り方を聞いてみました。

ubuntu@ubuntuserver:~/openai_test$ python3 question_answer.py "Can you provide a delicious coffee jelly recipe?"
Answer: Certainly! Here's a recipe for coffee jelly:

Ingredients:
- 1 1/2 cups brewed coffee
- 1/2 cup granulated sugar
- 2 tablespoons unflavored gelatin powder
- 1 1/2 cups boiling water
- 1/2 cup milk

Instructions:
1. Brew a pot of coffee and measure out 1 1/2 cups. Add the granulated sugar and stir until completely dissolved. Set aside.
2. In a separate bowl, sprinkle the unflavored gelatin powder over the boiling water and stir until completely dissolved.
3. Add the coffee mixture to the gelatin mixture and stir to fully combine.
4. Pour the mixture into a rectangular dish (8x8 inch or similar) and refrigerate until firm (about 4 hours).
5. Once the coffee jelly is firm, cut it into cubes.
6. Pour the milk into a small saucepan and warm it over low heat.
7. Add the coffee jelly cubes to serving dishes and pour the warm milk over the top.

Enjoy!

ubuntu@ubuntuserver:~/openai_test$ python3 question_answer.py "おいしいコーヒーゼリーの作り方を教えてください"
Answer: コーヒーゼリーの作り方を教えます。

【材料】
・グラニュー糖 …… 80g
・コーヒー粉 …… 15g
・水 …… 600ml
・粉ゼラチン …… 10g
・牛乳 …… 200ml

【作り方】
1.鍋にグラニュー糖、コーヒー粉、水を入れ、火にかけて、混ぜながら沸騰させます。
2.火を止め、粉ゼラチンを入れ、しっかりと溶かします。
3.牛乳を入れ、かき混ぜます。
4.①を型に入れ、冷蔵庫で冷やし固めます。

完成です。お好みで、生クリームなどを添えて召し上がってください。


それっぽい回答が出てきますねw


APIの利用料金
APIの利用料金ですが、Usageから確認出来るようになっています。


下の方に”Free trial usage”とあるので、そのなかで利用する分には追加料金なしとなるようです。


おわりに
今回はOpenAIのAPIを使ったプログラムを作成してみましたが、
毎度のことながら気づきが多くありました。
・API利用は、別料金。ただし、フリートライアルあり。
・APIの生成や管理方法
・Pythonのコード自体は、APIKeyを使ってOpenAIに投げつけてやればいいのでむっちゃシンプル

また、AIを使った処理をさせることはそんなにハードルは高くないのですが、
何をやらせたいか、どのモデルを利用するか(もしくは自前で構築するか)など検討する要素が多くあるなぁと感じた次第です。

もっともっと学習しないといけないですねw

Opensourcetech by Takahiro Kujirai