LoginSignup
0
0

【Python】openai と streamlit で AI チャットアプリ

Posted at

よくあるネタです。

コード

main.py
import streamlit as st
import pandas as pd
from openai import OpenAI

client = OpenAI()

class ChatPage:
  def setup(self):
    def post_completion(message):
      return client.completions.create(
        model="gpt-3.5-turbo",
        prompt="あなたは未知の言語 A で会話をするロボットです。ユーザへの返答は常に未知の言語 A を使って行ってください。\n\nユーザ: {message}\n\nロボット: "
      )[0].message["content"]
    self.post_completion = post_completion

  def components(self):
    st.title("Chat")
    user_input = st.text_input("メッセージを入力: ")
    if user_input:
      response = self.post_completion(user_input)
      st.text_area("返答: ", value=response, height=200)

page = ChatPage()
page.setup()
page.components()

これと同じタイプの実装です。
setup で関数を定義して components で定義したコンポーネントで呼び出しています。

OPENAI_API_KEY が環境変数にあれば、OpenAI の client は勝手にそのキーを使用します。

おわり

関心の分離が難しい。大きなアプリを作るのには向かないかもしれない。

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