3
6

More than 1 year has passed since last update.

Python StreamlitでOpenAIのGPT-3モデルを使ってチャットしてみる

Last updated at Posted at 2023-02-05

今回は、Python StreamlitでOpenAIのGPT-3モデルを使ってチャットをする一例を紹介します。Streamlitライブラリ、OpenAI APIが提供するライブラリopenaiライブラリをつかって、GPT-3を呼び出してテキスト生成や質問応答などのタスクを行うことができます。

  • 1. 2023年2月現在、OpenAI GPT-3をPythonから使うには、OpenAIが提供するopenaiパッケージを使用します。
  • 2. openapiを使うには別途OpenAIのAPIキーを取得する必要があります。APIキーを正しく設定することで、このコードを実行することができます。
  • 3. OpenAI APIキーを取得するには、OpenAIのWebサイトにアクセスしてアカウントを作成してください。アカウント作成後、APIキーを取得するためのページにアクセスできます。URLは次の通りです。
    https://platform.openai.com/account/api-keys
  • 4. openaiのライブラリーをインストールしておきます。
pip install openai
  • 5. streamlitのライブラリーをインストールしておきます。
pip install streamlit

それでは実際に、OpenAIのGPT-3モデルを使ってチャットができるコードを紹介します。

GPT.py
import openai
import streamlit as st

# Replace "YOUR_API_KEY" with your actual OpenAI API key
openai.api_key = "取得したAPIキー"

st.title("GPT3 Chatbot")

# Get the user's message
message = st.text_input("Enter your message:")

# Generate a response from GPT if the user has entered a message
if message:
  response = openai.Completion.create(
    engine="text-davinci-002",
    prompt=f"/japanese {message}",
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
  ).choices[0].text
  #Display the response from GPT
  st.write(f"GPT response: {response}")

2. 実行する

>  streamlit run GPT.py

run.png

Webブラウザで表示されているURLを開いてみる。

3. 結果

sample.png

結果、Strealit上のWebブラウザででチャットができています。

この情報が皆様のなんらかのお役に立てることを望んでおります。
皆さんも、お試しください。


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