Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,45 @@
|
|
| 1 |
# app.py
|
| 2 |
import os
|
| 3 |
import openai
|
| 4 |
-
import
|
| 5 |
|
| 6 |
-
# Load API key from
|
| 7 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
for user, bot in history:
|
| 12 |
-
messages.append({"role": "user", "content": user})
|
| 13 |
-
messages.append({"role": "assistant", "content": bot})
|
| 14 |
-
messages.append({"role": "user", "content": message})
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
messages=messages,
|
| 19 |
-
temperature=0.7,
|
| 20 |
-
)
|
| 21 |
-
return response.choices[0].message["content"]
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
)
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# app.py
|
| 2 |
import os
|
| 3 |
import openai
|
| 4 |
+
import streamlit as st
|
| 5 |
|
| 6 |
+
# Load OpenAI API key from Hugging Face Secrets
|
| 7 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 8 |
|
| 9 |
+
# Set Streamlit page config
|
| 10 |
+
st.set_page_config(page_title="OpenAI Chatbot", layout="centered")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
st.title("💬 OpenAI Chatbot")
|
| 13 |
+
st.markdown("Talk with GPT-4 using OpenAI API.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Initialize chat history
|
| 16 |
+
if "messages" not in st.session_state:
|
| 17 |
+
st.session_state.messages = [
|
| 18 |
+
{"role": "system", "content": "You are a helpful assistant."}
|
| 19 |
+
]
|
|
|
|
| 20 |
|
| 21 |
+
# Display previous messages
|
| 22 |
+
for msg in st.session_state.messages[1:]:
|
| 23 |
+
if msg["role"] == "user":
|
| 24 |
+
st.chat_message("user").markdown(msg["content"])
|
| 25 |
+
elif msg["role"] == "assistant":
|
| 26 |
+
st.chat_message("assistant").markdown(msg["content"])
|
| 27 |
+
|
| 28 |
+
# Chat input
|
| 29 |
+
if prompt := st.chat_input("Say something..."):
|
| 30 |
+
st.chat_message("user").markdown(prompt)
|
| 31 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
# Get response from OpenAI
|
| 35 |
+
response = openai.ChatCompletion.create(
|
| 36 |
+
model="gpt-4", # or "gpt-3.5-turbo"
|
| 37 |
+
messages=st.session_state.messages,
|
| 38 |
+
temperature=0.7,
|
| 39 |
+
)
|
| 40 |
+
reply = response.choices[0].message["content"]
|
| 41 |
+
st.chat_message("assistant").markdown(reply)
|
| 42 |
+
st.session_state.messages.append({"role": "assistant", "content": reply})
|
| 43 |
+
except Exception as e:
|
| 44 |
+
error_msg = f"❌ Error: {str(e)}"
|
| 45 |
+
st.chat_message("assistant").markdown(error_msg)
|