Update app.py
Browse files
app.py
CHANGED
|
@@ -11,7 +11,10 @@ EOS_TOKEN = "<|end|>"
|
|
| 11 |
CHAT_HISTORY_DIR = "chat_histories" # Directory to save chat histories
|
| 12 |
|
| 13 |
# Ensure the directory exists
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# Streamlit Configurations (must come first)
|
| 17 |
st.set_page_config(page_title="🐶 DUBSChat", layout="wide")
|
|
@@ -22,16 +25,23 @@ def save_chat_history(session_name, messages):
|
|
| 22 |
Save the chat history to a JSON file.
|
| 23 |
"""
|
| 24 |
file_path = os.path.join(CHAT_HISTORY_DIR, f"{session_name}.json")
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def load_chat_history(file_name):
|
| 29 |
"""
|
| 30 |
Load the chat history from a JSON file.
|
| 31 |
"""
|
| 32 |
file_path = os.path.join(CHAT_HISTORY_DIR, file_name)
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
def get_saved_sessions():
|
| 37 |
"""
|
|
@@ -71,8 +81,8 @@ if "messages" not in st.session_state:
|
|
| 71 |
{"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
|
| 72 |
{"role": "assistant", "content": "Hello! How can I assist you today?"}
|
| 73 |
]
|
|
|
|
| 74 |
st.session_state["session_name"] = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 75 |
-
save_chat_history(st.session_state["session_name"], st.session_state["messages"])
|
| 76 |
|
| 77 |
# Main Chat UI
|
| 78 |
st.title("🐶 DUBSChat")
|
|
@@ -87,36 +97,54 @@ for message in st.session_state["messages"]:
|
|
| 87 |
|
| 88 |
# User Input
|
| 89 |
if prompt := st.chat_input():
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
|
|
|
| 11 |
CHAT_HISTORY_DIR = "chat_histories" # Directory to save chat histories
|
| 12 |
|
| 13 |
# Ensure the directory exists
|
| 14 |
+
try:
|
| 15 |
+
os.makedirs(CHAT_HISTORY_DIR, exist_ok=True)
|
| 16 |
+
except OSError as e:
|
| 17 |
+
st.error(f"Failed to create chat history directory: {e}")
|
| 18 |
|
| 19 |
# Streamlit Configurations (must come first)
|
| 20 |
st.set_page_config(page_title="🐶 DUBSChat", layout="wide")
|
|
|
|
| 25 |
Save the chat history to a JSON file.
|
| 26 |
"""
|
| 27 |
file_path = os.path.join(CHAT_HISTORY_DIR, f"{session_name}.json")
|
| 28 |
+
try:
|
| 29 |
+
with open(file_path, "w") as f:
|
| 30 |
+
json.dump(messages, f)
|
| 31 |
+
except IOError as e:
|
| 32 |
+
st.error(f"Failed to save chat history: {e}")
|
| 33 |
|
| 34 |
def load_chat_history(file_name):
|
| 35 |
"""
|
| 36 |
Load the chat history from a JSON file.
|
| 37 |
"""
|
| 38 |
file_path = os.path.join(CHAT_HISTORY_DIR, file_name)
|
| 39 |
+
try:
|
| 40 |
+
with open(file_path, "r") as f:
|
| 41 |
+
return json.load(f)
|
| 42 |
+
except (FileNotFoundError, json.JSONDecodeError):
|
| 43 |
+
st.error("Failed to load chat history. Starting with a new session.")
|
| 44 |
+
return []
|
| 45 |
|
| 46 |
def get_saved_sessions():
|
| 47 |
"""
|
|
|
|
| 81 |
{"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
|
| 82 |
{"role": "assistant", "content": "Hello! How can I assist you today?"}
|
| 83 |
]
|
| 84 |
+
if "session_name" not in st.session_state:
|
| 85 |
st.session_state["session_name"] = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
|
|
| 86 |
|
| 87 |
# Main Chat UI
|
| 88 |
st.title("🐶 DUBSChat")
|
|
|
|
| 97 |
|
| 98 |
# User Input
|
| 99 |
if prompt := st.chat_input():
|
| 100 |
+
if not dubs_key:
|
| 101 |
+
st.warning("Please provide a valid Dubs Key.")
|
| 102 |
+
else:
|
| 103 |
+
# Append the user's message to the chat history
|
| 104 |
+
st.session_state["messages"].append({"role": "user", "content": prompt})
|
| 105 |
+
st.chat_message("user").write(prompt)
|
| 106 |
+
|
| 107 |
+
# Serialize chat history for API
|
| 108 |
+
chat_history = "".join(
|
| 109 |
+
[f"<|{msg['role']}|>{msg['content']}<|end|>" for msg in st.session_state["messages"]]
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Stream response
|
| 113 |
+
with st.spinner("Translating Dubs language (Woof Woof!)"):
|
| 114 |
+
assistant_message_placeholder = st.chat_message("assistant").empty()
|
| 115 |
+
|
| 116 |
+
# Function to stream the response
|
| 117 |
+
def stream_response():
|
| 118 |
+
try:
|
| 119 |
+
response = requests.post(
|
| 120 |
+
SPACE_URL,
|
| 121 |
+
json={"prompt": chat_history},
|
| 122 |
+
headers={"Authorization": f"Bearer {dubs_key}"},
|
| 123 |
+
stream=True, # Enable streaming
|
| 124 |
+
timeout=120,
|
| 125 |
+
)
|
| 126 |
+
response.raise_for_status()
|
| 127 |
+
|
| 128 |
+
# Read and yield the response incrementally
|
| 129 |
+
for chunk in response.iter_content(chunk_size=256):
|
| 130 |
+
if chunk:
|
| 131 |
+
yield chunk.decode("utf-8")
|
| 132 |
+
except requests.exceptions.Timeout:
|
| 133 |
+
yield "The request timed out. Please try again later."
|
| 134 |
+
except requests.exceptions.RequestException as e:
|
| 135 |
+
yield f"Error: {e}"
|
| 136 |
+
except json.JSONDecodeError:
|
| 137 |
+
yield "Error decoding server response."
|
| 138 |
+
|
| 139 |
+
# Update assistant's message incrementally
|
| 140 |
+
full_response = ""
|
| 141 |
+
for chunk in stream_response():
|
| 142 |
+
full_response += chunk
|
| 143 |
+
assistant_message_placeholder.write(full_response)
|
| 144 |
+
|
| 145 |
+
# Append the assistant's final response to the chat history
|
| 146 |
+
st.session_state["messages"].append({"role": "assistant", "content": full_response})
|
| 147 |
+
|
| 148 |
+
# Auto-save the updated chat history
|
| 149 |
+
save_chat_history(st.session_state["session_name"], st.session_state["messages"])
|
| 150 |
|