Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
import shelve
|
4 |
+
from g4f.client import Client
|
5 |
+
|
6 |
+
|
7 |
+
st.title("Streamlit Chatbot Interface")
|
8 |
+
|
9 |
+
USER_AVATAR = "👤"
|
10 |
+
BOT_AVATAR = "🤖"
|
11 |
+
client = Client()
|
12 |
+
|
13 |
+
# Ensure openai_model is initialized in session state
|
14 |
+
if "openai_model" not in st.session_state:
|
15 |
+
st.session_state["openai_model"] = "gpt-3.5-turbo"
|
16 |
+
|
17 |
+
|
18 |
+
# Load chat history from shelve file
|
19 |
+
def load_chat_history():
|
20 |
+
with shelve.open("chat_history") as db:
|
21 |
+
return db.get("messages", [])
|
22 |
+
|
23 |
+
|
24 |
+
# Save chat history to shelve file
|
25 |
+
def save_chat_history(messages):
|
26 |
+
with shelve.open("chat_history") as db:
|
27 |
+
db["messages"] = messages
|
28 |
+
|
29 |
+
|
30 |
+
# Initialize or load chat history
|
31 |
+
if "messages" not in st.session_state:
|
32 |
+
st.session_state.messages = load_chat_history()
|
33 |
+
|
34 |
+
# Sidebar with a button to delete chat history
|
35 |
+
with st.sidebar:
|
36 |
+
if st.button("Delete Chat History"):
|
37 |
+
st.session_state.messages = []
|
38 |
+
save_chat_history([])
|
39 |
+
|
40 |
+
# Display chat messages
|
41 |
+
for message in st.session_state.messages:
|
42 |
+
avatar = USER_AVATAR if message["role"] == "user" else BOT_AVATAR
|
43 |
+
with st.chat_message(message["role"], avatar=avatar):
|
44 |
+
st.markdown(message["content"])
|
45 |
+
|
46 |
+
# Main chat interface
|
47 |
+
if prompt := st.chat_input("How can I help?"):
|
48 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
49 |
+
with st.chat_message("user", avatar=USER_AVATAR):
|
50 |
+
st.markdown(prompt)
|
51 |
+
|
52 |
+
with st.chat_message("assistant", avatar=BOT_AVATAR):
|
53 |
+
message_placeholder = st.empty()
|
54 |
+
full_response = ""
|
55 |
+
response = client.chat.completions.create(
|
56 |
+
model="gpt-3.5-turbo",
|
57 |
+
messages=st.session_state["messages"],
|
58 |
+
)
|
59 |
+
full_response = response.choices[0].message.content
|
60 |
+
message_placeholder.markdown(full_response)
|
61 |
+
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
62 |
+
|
63 |
+
# Save chat history after each interaction
|
64 |
+
save_chat_history(st.session_state.messages)
|