Promotingai's picture
Update app.py
2487242 verified
from openai import OpenAI
import gradio as gr
import os
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=api_key)
def predict(message, history=""):
if history:
history_list = eval(history) # Convert string back to list
else:
history_list = []
# Append the new user message
history_list.append(("user", message))
# Prepare the message format for OpenAI API
messages = [{"role": "user" if role == "user" else "assistant", "content": content} for role, content in history_list]
# Call the OpenAI API
response = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=messages,
max_tokens=150,
temperature=0.5
)
# Extract response text
answer = response.choices[0].message['content']
history_list.append(("assistant", answer))
# Convert history list to string for display
history_text = str(history_list)
return history_text, answer
with gr.Blocks() as app:
with gr.Row():
with gr.Column():
message_input = gr.Textbox(label="Your Message")
history_input = gr.Textbox(label="History", lines=10, placeholder="Conversation history appears here...")
with gr.Column():
history_output = gr.Textbox(label="Updated History", lines=10)
response_output = gr.Textbox(label="Assistant's Response")
predict_button = gr.Button("Predict")
predict_button.click(predict, inputs=[message_input, history_input], outputs=[history_output, response_output])
app.launch()