|
|
|
from openai import OpenAI |
|
import gradio as gr |
|
import os |
|
|
|
|
|
api_key = os.getenv("OPENAI_API_KEY") |
|
client = OpenAI(api_key=api_key) |
|
|
|
def chat_with_openai(user_input, history): |
|
if history is None: |
|
history = [] |
|
|
|
|
|
if len(history) == 0: |
|
history.append({"role": "user", "content": "You are a helpful assistant."}) |
|
|
|
|
|
history.append({"role": "user", "content": user_input}) |
|
|
|
|
|
completion = client.chat.completions.create( |
|
model="o1-preview", |
|
messages=history |
|
) |
|
|
|
|
|
assistant_message = completion.choices[0].message.content |
|
|
|
|
|
history.append({"role": "assistant", "content": assistant_message}) |
|
|
|
|
|
messages_to_display = [] |
|
for i in range(1, len(history)-1, 2): |
|
user_msg = history[i]["content"] |
|
assistant_msg = history[i+1]["content"] |
|
messages_to_display.append((user_msg, assistant_msg)) |
|
|
|
return messages_to_display, history |
|
|
|
with gr.Blocks() as demo: |
|
chatbot = gr.Chatbot() |
|
state = gr.State([]) |
|
|
|
with gr.Row(): |
|
txt = gr.Textbox( |
|
show_label=False, |
|
placeholder="メッセージを入力してください..." |
|
) |
|
btn = gr.Button("送信") |
|
|
|
def on_submit(user_input, history): |
|
messages, updated_history = chat_with_openai(user_input, history) |
|
return messages, updated_history, "" |
|
|
|
txt.submit(on_submit, [txt, state], [chatbot, state, txt]) |
|
btn.click(on_submit, [txt, state], [chatbot, state, txt]) |
|
|
|
demo.launch() |