Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import openai
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# Set up OpenAI API key
|
| 6 |
+
openai.api_key = os.getenv("OPENAI_API_KEY") # Replace with your OpenAI API key if not using an environment variable
|
| 7 |
+
|
| 8 |
+
# Function to query OpenAI
|
| 9 |
+
def query_openai(prompt, model="gpt-3.5-turbo"):
|
| 10 |
+
try:
|
| 11 |
+
response = openai.ChatCompletion.create(
|
| 12 |
+
model=model,
|
| 13 |
+
messages=prompt,
|
| 14 |
+
max_tokens=200,
|
| 15 |
+
temperature=0.7,
|
| 16 |
+
)
|
| 17 |
+
return response["choices"][0]["message"]["content"]
|
| 18 |
+
except Exception as e:
|
| 19 |
+
return f"Error: {e}"
|
| 20 |
+
|
| 21 |
+
# Streamlit app
|
| 22 |
+
st.title("Simple OpenAI Chatbot")
|
| 23 |
+
|
| 24 |
+
# Initialize the chat history
|
| 25 |
+
if "messages" not in st.session_state:
|
| 26 |
+
st.session_state.messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 27 |
+
|
| 28 |
+
# Display chat history
|
| 29 |
+
for message in st.session_state.messages:
|
| 30 |
+
if message["role"] == "user":
|
| 31 |
+
st.markdown(f"**You:** {message['content']}")
|
| 32 |
+
elif message["role"] == "assistant":
|
| 33 |
+
st.markdown(f"**Bot:** {message['content']}")
|
| 34 |
+
|
| 35 |
+
# User input
|
| 36 |
+
user_input = st.text_input("Type your message:")
|
| 37 |
+
|
| 38 |
+
# Handle user input
|
| 39 |
+
if st.button("Send"):
|
| 40 |
+
if user_input.strip():
|
| 41 |
+
# Add user input to chat history
|
| 42 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
| 43 |
+
|
| 44 |
+
# Get bot response
|
| 45 |
+
bot_response = query_openai(st.session_state.messages)
|
| 46 |
+
|
| 47 |
+
# Add bot response to chat history
|
| 48 |
+
st.session_state.messages.append({"role": "assistant", "content": bot_response})
|
| 49 |
+
|
| 50 |
+
# Display updated chat history
|
| 51 |
+
st.experimental_rerun()
|
| 52 |
+
|
| 53 |
+
# Clear chat
|
| 54 |
+
if st.button("Clear Chat"):
|
| 55 |
+
st.session_state.messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 56 |
+
st.experimental_rerun()
|