0
3

More than 1 year has passed since last update.

【ChatGPTに聞く】PythonでOpenAI API使って質問に返答できる簡単なアプリを作成してみた

Last updated at Posted at 2023-07-28

はじめに

今回はPythonを使用してOpenAI APIを活用した質問応答アプリを作成していきます。また、アプリのコードを今話題のChatGPTに質問してコードを書いていきたいと思います。

使用環境

動作環境によってはうまく動作してくれない可能性があるので、
念のため、動作環境を以下に記載します。
・Windows11
・Python 3.10.7

Pythonのバージョン確認は、ターミナルで以下のコマンドを実行します。

python --version

OpenAI APIキーの取得

では、さっそくAPIキーの取得をしていきます。
以下のURLからOpenAIのサイトにアクセスします。

OpenAIにサインアップします。
登録するメールアドレスを「Email address」に入力して「Continue」をクリックします。
Screenshot-2023_03_10-23_38_26.png

そして、パスワードを8文字以上で入力し、「Continue」をクリックします。
Overview-OpenAI-API-Google-Chrome-2023_03_11-0_01_50-1.png

すると、登録したメールアドレスへ、以下のようなアカウントの確認メールが届くので
「Verify email address」をクリックします。
Overview-OpenAI-API-Google-Chrome-2023_03_11-0_15_39-1.png

すると、無事にOpenAIにサインアップすることができました。
続いてAPIキーを取得していきます。

OpenAIのホーム画面から「プロフィール」→「View API keys」をクリックします。
Overview-OpenAI-API-Google-Chrome-2023_03_10-23_40_41-1536x739.png

こちらではすでにAPIキーは作成されてますが
今回は、新たにAPIキーを作成します。
「Create new secret key」をクリックします。
Overview-OpenAI-API-Google-Chrome-2023_03_10-23_40_51-1536x739.png

APIキーが無事に発行されたので、APIキーをコピーして、ターミナルで環境変数として設定していきます。 また、発行したAPIキーは厳重に保管してください。
※APIキーをコピーしないで「OK」をクリックすると、APIキーをコピーすることができなくなるため、その場合は再度「Create new secret key」を押してAPIキーを発行してください。また、コピーし忘れたAPIキーは削除してください。
Overview-OpenAI-API-Google-Chrome-2023_03_10-23_40_59-1536x741.png

APIキーを環境変数に設定するには、ターミナルで以下のコマンドを実行します。
今回は環境変数を「OPENAI_API_KEY」として設定していきます。

※macだとsetではなくexportでコマンドを実行できます。
※「set」コマンドを使用してコマンドプロンプトから環境変数に値を設定しても、その値は「set」コマンドを実行したコマンドプロンプト内でのみ有効です。他のコマンドプロンプトやプログラムからはアクセスできません。

set OPENAI_API_KEY = コピーしたAPIキー

ChatGPTに聞く

ここからは、PythonでOpenAIAPIを使ったアプリを作成していきますが
せっかくなのでコードを生成できるChatGPTに聞いてみます。
まずは、ChatGPTのサイトにアクセスします。

こちらではすでにアカウントが作成されており、ChatGPTを使用することができます。 しかし、アカウントを作成していない方は、新たにアカウントを作成する必要があります。
New-chat-Google-Chrome-2023_03_11-23_52_05-1536x741.png

今回は「PythonでOpenAPIを使用して、ユーザーからの質問に回答するシンプルなアプリ」と質問してみます。
New-chat-Google-Chrome-2023_03_10-21_56_07.png

すると、ChatAPIから以下のような答えが返ってきました。

はい、PythonでOpenAPIを使用してユーザーからの質問に回答するシンプルなアプリを作成することができます。以下は、OpenAIのGPT-3 APIを使用して自然言語処理に基づく質問応答アプリを作成するためのステップバイステップのガイドです。

OpenAI APIキーを入手する
まず、OpenAI APIのアクセスキーを入手する必要があります。OpenAIのAPIを使用するには、OpenAIのWebサイトでアカウントを作成し、APIキーを取得する必要があります。
必要なPythonライブラリをインストールする
OpenAI APIをPythonで使用するには、OpenAI APIをサポートするPythonライブラリをインストールする必要があります。以下のコマンドを使用して、openaiライブラリをインストールします。

pip install openai

アプリのスクリプトを作成する
次に、Pythonスクリプトを作成して、OpenAI APIを使用してユーザーからの質問に回答するアプリを実装します。以下は、このアプリの例です。

import openai
openai.api_key = "YOUR_API_KEY"

def ask(question):
   prompt = (f"I have a question: {question}\n"
             "Answer:")
   response = openai.Completion.create(
       engine="davinci",
       prompt=prompt,
       max_tokens=1024,
       n=1,
       stop=None,
       temperature=0.7,
   )
   answer = response.choices[0].text.strip()
   return answer

このスクリプトは、OpenAI APIにアクセスするためにAPIキーを設定し、質問を受け取ってOpenAIのGPT-3エンジンを>使用して回答を生成します。回答は、ユーザーが入力した質問に基づいて生成されます。

アプリを実行する
最後に、上記のスクリプトを使用して、アプリを実行することができます。以下は、Pythonの対話型シェルでの使用例>です。

>>>from app import ask
>>>question = "What is the capital of France?"
>>>answer = ask(question)
>>>print(answer)
"Paris"

この例では、質問として「フランスの首都は何ですか?」を与え、アプリが回答を生成し、それを出力しています。

これで、PythonでOpenAPIを使用して、ユーザーからの質問に回答するシンプルなアプリを作成することができました。

まずは、ChatGPIの返答のとおりに、以下のコマンドを実行します。

pip install openai

いよいよPythonのスクリプトファイルを作成しますが、APIキーを環境変数に設定したため「”YOUR_API_KEY”」を「os.environ[“OPENAI_API_KEY”]」に修正します。
また、実行方法として対話型ではなく、スクリプトとして実行するため以下のようにコードを修正してapp.pyとして、ファイルを保存します。

app.py
import openai
import os

openai.api_key = os.environ["OPENAI_API_KEY"]


def ask(question):
    prompt = (f"I have a question: {question}\n"
              "Answer:")
    response = openai.Completion.create(
        engine="davinci",
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.7,
    )
    answer = response.choices[0].text.strip()
    return answer


if __name__ == "__main__":
    question = input("質問を入力してください。:")
    answer = ask(question)
    print(answer)

作成した「app.py」ファイルがあるフォルダに移動して以下のコマンドを入力して「app.py」を実行します。
※環境変数に値を設定するために「set」コマンドを使用したターミナル以外からコマンドを実行すると、環境変数に値が設定されていないためエラーが発生します。その場合はもう一度「set」コマンドで環境変数を設定してから以下のコマンドをしてください。

python app.py

すると、「質問を入力してください。:」と出るので「What is the capital of France?」(フランスの首都はどこですか?)と入力してEnterキーを押します。

質問を入力してください。:What is the capital of France?

すると以下のようなレスポンスが返ってきました。
一行目の部分だけは質問に対しての答えになってますが、それから下の行はよくわからない感じになっています。

- Paris
You are now ready to use the program. Just press enter, and the program will read you the question. Then, you'll have to answer it by typing in a, b, c, or d. If you're right, the program will congratulate you; if you're wrong, it will tell you the correct answer.
Notes about the program:
- Don't use Caps Lock, that could screw up the program.
- Make sure you have your sound card on.
- If you don't have the right answer, the program will tell you.
- If you get the right answer, the program should tell you.
- You can't use "?" as a response.
- You may have to change the program so that it accepts "a," "b," "c," or "d."
- The computer will not accept "e," "f," "g," or "h."
- If you use the computer's "backspace" key, the response will be cleared.
- If you use the computer's arrow keys, the response will be cleared.
- If you are on a laptop, and you press a key, the response will be cleared.
- If you press the "Enter" key, the response will be cleared.
- If you open the program, and press a key on the keyboard, the response will be cleared.
- If you press the "Escape" key, the response will be cleared.
- If you press the "Delete" key, the response will be cleared.
- If you press the "Home" key, the response will be cleared.
- If you press the "End" key, the response will be cleared.
- If you press the "Page Up" key, the response will be cleared.
- If you press the "Page Down" key, the response will be cleared.
- If you press the "Esc" key, the response will be cleared.
- If you press the "Up Arrow" key, the response will be cleared.
- If you press the "Down Arrow" key, the response will be cleared.
- If you press the "Left Arrow" key, the response will be cleared.
- If you press the "Right Arrow" key, the response will be cleared.
- If you press the "Insert" key, the response will be cleared.
- If you press the "Delete" key, the response will be cleared.
- If you press the "Home" key, the response will be cleared.
- If you press the "End" key, the response will be cleared.
- If you press the "Page Up" key, the response will be cleared.
- If you press the "Page Down" key, the response will be cleared.
- If you press the "Esc" key, the response will be cleared.
- If you press the "Up Arrow" key, the response will be cleared.
- If you press the "Down Arrow" key, the response will be cleared.
- If you press the "Left Arrow" key, the response will be cleared.
- If you press the "Right Arrow" key, the response will be cleared.
- If you press the "Insert" key, the response will be cleared.
- If you press the "Delete" key, the response will be cleared.
- If you press the "Home" key, the response will be cleared.
- If you press the "End" key, the response will be cleared.
- If you press the "Page Up" key, the response will be cleared.
- If you press the "Page Down" key, the response will be cleared.
- If you press the "Esc" key, the response will be cleared.
- If you press the "Up Arrow" key, the response will be cleared.
- If you press the "Down Arrow" key, the response will be cleared.
- If you press the "Left Arrow" key, the response will be cleared.
- If you press the "Right Arrow" key, the response will be cleared.
- If you press the "Insert" key, the response will be cleared.
- If you press the "Delete" key, the response will be cleared.
- If you press the "Home" key, the response will be cleared.
- If you press the "End" key, the response will be cleared.
- If you press the "Page Up" key, the response will be cleared.
- If you press the "Page Down" key, the response will be cleared.
- If you press the "Esc" key, the response will be cleared.
- If you press the "Up Arrow" key, the response will be cleared.
- If you press the "Down Arrow" key, the response will be cleared 

ここでOpenAIの公式ドキュメントを見てみます。

どうやらChatGPTのような、チャットのコンテキストに基づいて応答を生成するには下記のメソッドを使うみたいです。

openai.Completion.create

また、APIレスポンスに対する応答形式を見ると、以下のコードを使用して質問に対する回答を抽出できるようです。

response['choices'][0]['message']['content']

以上を踏まえ、「app.py」コードを以下のように修正します。

app.py
import openai
import os

openai.api_key = os.environ["OPENAI_API_KEY"]


def ask(question):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
                {"role": "user", "content": f'{question}'}
            ]
    )
    answer = response['choices'][0]['message']['content']
    return answer


if __name__ == "__main__":
    question = input("質問を入力してください。:")
    answer = ask(question)
    print(answer)

これでようやく質問に対して回答するようになっているはずです。
「app.py」を実行して、「What is the capital of France?」と質問してみます。
14f68569a8b8fc2035a387721abec4eb.png

すると下記のような回答が返ってきました。
5d022bd3af007562380bdad0e188fe35.png

「フランスの首都はどこですか?」という問いに対して「フランスの首都はパリです。」と正しい回答が返ってきていることがわかります。

終わりに

今後もOpenAI APIを活用した新しいサービスや技術が続々と登場してくると思うと、楽しみです。

参考

この記事は以下のリンクを参考にしました。

0
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
0
3