Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Import necessary libraries
|
2 |
+
import streamlit as st
|
3 |
+
import openai
|
4 |
+
import os
|
5 |
+
|
6 |
+
# Set the title for the Streamlit app
|
7 |
+
st.title("Simple Chatbot")
|
8 |
+
|
9 |
+
# Load the OpenAI API key from Hugging Face's environment variables
|
10 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
11 |
+
|
12 |
+
# Check if the API key is loaded
|
13 |
+
if openai_api_key is None:
|
14 |
+
st.error("API key not found. Please set the OpenAI API key in the environment.")
|
15 |
+
st.stop()
|
16 |
+
|
17 |
+
# Set the API key for OpenAI
|
18 |
+
openai.api_key = openai_api_key
|
19 |
+
|
20 |
+
# Define the template for the chatbot prompt
|
21 |
+
prompt_template = """
|
22 |
+
You are a helpful Assistant who answers users' questions
|
23 |
+
based on your general knowledge. Keep your answers short
|
24 |
+
and to the point.
|
25 |
+
"""
|
26 |
+
|
27 |
+
# Get the current prompt from the session state or set default
|
28 |
+
if "prompt" not in st.session_state:
|
29 |
+
st.session_state["prompt"] = [{"role": "system",
|
30 |
+
"content": prompt_template}]
|
31 |
+
prompt = st.session_state["prompt"]
|
32 |
+
|
33 |
+
# Display previous chat messages
|
34 |
+
for message in prompt:
|
35 |
+
if message["role"] != "system":
|
36 |
+
with st.chat_message(message["role"]):
|
37 |
+
st.write(message["content"])
|
38 |
+
|
39 |
+
# Get the user's question using Streamlit's chat input
|
40 |
+
question = st.chat_input("Ask anything")
|
41 |
+
|
42 |
+
# Handle the user's question
|
43 |
+
if question:
|
44 |
+
# Add the user's question to the prompt and display it
|
45 |
+
prompt.append({"role": "user", "content": question})
|
46 |
+
with st.chat_message("user"):
|
47 |
+
st.write(question)
|
48 |
+
|
49 |
+
# Display an empty assistant message while waiting for response
|
50 |
+
with st.chat_message("assistant"):
|
51 |
+
botmsg = st.empty()
|
52 |
+
|
53 |
+
# Define a function to interact with OpenAI API
|
54 |
+
def chat_gpt(messages):
|
55 |
+
response = openai.ChatCompletion.create(
|
56 |
+
model="gpt-3.5-turbo",
|
57 |
+
messages=messages
|
58 |
+
)
|
59 |
+
return response.choices[0].message['content'].strip()
|
60 |
+
|
61 |
+
# Call the chat_gpt function
|
62 |
+
result = chat_gpt(prompt)
|
63 |
+
|
64 |
+
# Display the assistant's response
|
65 |
+
botmsg.write(result)
|
66 |
+
|
67 |
+
# Add the assistant's response to the prompt
|
68 |
+
prompt.append({"role": "assistant", "content": result})
|
69 |
+
|
70 |
+
# Store the updated prompt in the session state
|
71 |
+
st.session_state["prompt"] = prompt
|