Gorgefound commited on
Commit
52addfa
·
verified ·
1 Parent(s): d312ca6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -0
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import gradio as gr
3
+ import os
4
+
5
+ # Get OpenAI API key from environment variables
6
+ openai.api_key = os.getenv('OPENAI_API_KEY')
7
+
8
+ # Function to communicate with OpenAI GPT model and maintain chat history
9
+ def openai_chat(messages, user_input):
10
+ messages.append({"role": "user", "content": user_input})
11
+
12
+ response = openai.ChatCompletion.create(
13
+ model="gpt-4o", # or use "gpt-3.5-turbo"
14
+ messages=messages
15
+ )
16
+
17
+ bot_message = response['choices'][0]['message']['content']
18
+ messages.append({"role": "assistant", "content": bot_message})
19
+
20
+ # Prepare the chat history for display in the Gradio Chatbot
21
+ chat_history = [(msg['content'] if msg['role'] == 'user' else None,
22
+ msg['content'] if msg['role'] == 'assistant' else None) for msg in messages]
23
+
24
+ return chat_history, messages
25
+
26
+ # Creating Gradio UI
27
+ with gr.Blocks() as demo:
28
+ gr.Markdown("### OpenAI Chatbot with Gradio Chatbox")
29
+
30
+ chatbot = gr.Chatbot(label="Chat History")
31
+ user_input = gr.Textbox(label="Your Message")
32
+
33
+ # Keep track of the message history
34
+ state = gr.State([]) # Empty list to store the message history
35
+
36
+ # Submit button
37
+ submit_btn = gr.Button("Send")
38
+
39
+ # Define interaction logic
40
+ submit_btn.click(openai_chat,
41
+ inputs=[state, user_input],
42
+ outputs=[chatbot, state])
43
+
44
+ # Launch the interface
45
+ demo.launch()