Spaces:
Sleeping
Sleeping
import openai | |
import gradio as gr | |
import os | |
# Get OpenAI API key from environment variables | |
openai.api_key = os.getenv('OPENAI_API_KEY') | |
# Function to communicate with OpenAI GPT model and maintain chat history | |
def openai_chat(messages, user_input): | |
messages.append({"role": "user", "content": user_input}) | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=messages | |
) | |
bot_message = response['choices'][0]['message']['content'] | |
messages.append({"role": "assistant", "content": bot_message}) | |
# Prepare the chat history for display in the Gradio Chatbot | |
chat_history = [(msg['content'] if msg['role'] == 'user' else None, | |
msg['content'] if msg['role'] == 'assistant' else None) for msg in messages] | |
return chat_history, messages | |
# Creating Gradio UI | |
with gr.Blocks(theme="Hev832/niceandsimple") as demo: | |
gr.Markdown("### OpenAI Chatbot with Gradio Chatbox") | |
chatbot = gr.Chatbot(label="Chat History") | |
user_input = gr.Textbox(label="Your Message") | |
# Keep track of the message history | |
state = gr.State([]) # Empty list to store the message history | |
# Submit button | |
submit_btn = gr.Button("Send") | |
# Define interaction logic | |
submit_btn.click(openai_chat, | |
inputs=[state, user_input], | |
outputs=[chatbot, state]) | |
# Launch the interface | |
demo.launch() | |