jukutest / app.py
ochyai's picture
Update app.py
1338dd1 verified
raw
history blame
1.66 kB
import os
import openai
import gradio as gr
# OpenAI APIキーの設定(環境変数から取得)
openai.api_key = os.getenv("OPENAI_API_KEY")
def chat_with_openai(user_input, history):
if history is None:
history = []
# OpenAI APIに送信するメッセージの構築
messages = []
for human, assistant in history:
messages.append({"role": "user", "content": human})
if assistant:
messages.append({"role": "assistant", "content": assistant})
messages.append({"role": "user", "content": user_input})
# OpenAI APIへのリクエスト
response = openai.ChatCompletion.create(
model="o1-preview",
messages=messages
)
assistant_message = response['choices'][0]['message']['content']
# 履歴に新しいメッセージを追加
history.append((user_input, assistant_message))
return history, history
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
state = gr.State([])
with gr.Row():
with gr.Column(scale=8):
txt = gr.Textbox(
show_label=False,
placeholder="メッセージを入力してください...",
lines=1,
container=False
)
with gr.Column(scale=2, min_width=0):
btn = gr.Button("送信")
def on_submit(user_input, chat_history):
updated_history, updated_state = chat_with_openai(user_input, chat_history)
return updated_history, updated_state, ""
txt.submit(on_submit, [txt, state], [chatbot, state, txt])
btn.click(on_submit, [txt, state], [chatbot, state, txt])
demo.launch()