Spaces:
Sleeping
Sleeping
File size: 1,458 Bytes
52addfa cf497d0 52addfa cf497d0 52addfa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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()
|