|
import os |
|
import openai |
|
import gradio as gr |
|
|
|
|
|
openai.api_key = os.getenv("OPENAI_API_KEY") |
|
|
|
def chat_with_openai(user_input, history): |
|
if history is None: |
|
history = [] |
|
|
|
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}) |
|
|
|
|
|
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() |