Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -6,101 +6,117 @@ from datetime import datetime, timedelta
|
|
6 |
import time
|
7 |
import uuid
|
8 |
|
9 |
-
# Page configuration
|
10 |
st.set_page_config(
|
11 |
page_title="Chat Flow π·",
|
12 |
page_icon="π¬",
|
13 |
-
initial_sidebar_state="
|
14 |
-
layout="wide" # Better for mobile
|
15 |
)
|
16 |
|
17 |
-
#
|
18 |
st.markdown("""
|
19 |
<style>
|
20 |
-
/* Main app styling */
|
21 |
.stApp {
|
22 |
-
background:
|
23 |
-
min-height: 100vh;
|
24 |
}
|
25 |
|
26 |
-
/* Container responsive sizing */
|
27 |
.main .block-container {
|
28 |
-
max-width:
|
29 |
-
padding-left: 1rem;
|
30 |
-
padding-right: 1rem;
|
31 |
-
padding-top: 1rem;
|
32 |
}
|
33 |
|
34 |
-
/* Hide Streamlit branding */
|
35 |
#MainMenu {visibility: hidden;}
|
36 |
footer {visibility: hidden;}
|
37 |
header {visibility: hidden;}
|
38 |
.stDeployButton {display: none;}
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
border-radius: 15px;
|
44 |
-
margin: 0.5rem 0;
|
45 |
-
padding: 1rem;
|
46 |
-
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
47 |
-
backdrop-filter: blur(10px);
|
48 |
-
}
|
49 |
-
|
50 |
-
/* User messages - right aligned with blue background */
|
51 |
-
.stChatMessage[data-testid="user-message"] {
|
52 |
-
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
|
53 |
-
color: white;
|
54 |
-
margin-left: 20%;
|
55 |
}
|
56 |
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
margin-right: 20%;
|
62 |
}
|
63 |
|
64 |
-
/*
|
65 |
@media (max-width: 768px) {
|
|
|
|
|
|
|
|
|
66 |
.main .block-container {
|
67 |
-
padding: 0.5rem;
|
68 |
max-width: 100%;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
}
|
70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
.stChatMessage[data-testid="user-message"] {
|
72 |
-
|
73 |
-
|
|
|
74 |
}
|
75 |
|
|
|
76 |
.stChatMessage[data-testid="assistant-message"] {
|
77 |
-
|
78 |
-
|
|
|
79 |
}
|
80 |
|
81 |
-
/*
|
82 |
-
.
|
83 |
-
|
84 |
-
min-width: 100% !important;
|
85 |
}
|
86 |
|
87 |
-
/* Header adjustments for mobile */
|
88 |
h1 {
|
89 |
font-size: 1.5rem !important;
|
|
|
|
|
90 |
text-align: center;
|
91 |
}
|
92 |
|
93 |
-
.
|
94 |
-
|
|
|
95 |
}
|
96 |
|
|
|
97 |
.stButton button {
|
|
|
98 |
font-size: 14px;
|
99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
}
|
101 |
}
|
102 |
|
103 |
-
/* Extra small screens (iPhone 5,
|
104 |
@media (max-width: 480px) {
|
105 |
.main .block-container {
|
106 |
padding: 0.25rem;
|
@@ -112,107 +128,24 @@ st.markdown("""
|
|
112 |
}
|
113 |
|
114 |
.stChatMessage[data-testid="user-message"] {
|
115 |
-
margin-left:
|
116 |
}
|
117 |
|
118 |
.stChatMessage[data-testid="assistant-message"] {
|
119 |
-
margin-right:
|
120 |
}
|
121 |
|
122 |
h1 {
|
123 |
-
font-size: 1.
|
124 |
}
|
125 |
|
126 |
-
.
|
127 |
-
font-size:
|
128 |
-
|
129 |
-
}
|
130 |
-
|
131 |
-
/* Chat input styling */
|
132 |
-
.stChatInput {
|
133 |
-
background: rgba(255, 255, 255, 0.9);
|
134 |
-
border-radius: 25px;
|
135 |
-
border: 2px solid rgba(255, 255, 255, 0.3);
|
136 |
-
backdrop-filter: blur(10px);
|
137 |
-
}
|
138 |
-
|
139 |
-
.stChatInput input {
|
140 |
-
background: transparent;
|
141 |
-
border: none;
|
142 |
-
color: #333;
|
143 |
-
}
|
144 |
-
|
145 |
-
.stChatInput input::placeholder {
|
146 |
-
color: #666;
|
147 |
-
}
|
148 |
-
|
149 |
-
/* Sidebar improvements */
|
150 |
-
.css-1d391kg {
|
151 |
-
background: rgba(255, 255, 255, 0.95);
|
152 |
-
backdrop-filter: blur(15px);
|
153 |
-
}
|
154 |
-
|
155 |
-
/* Model info styling */
|
156 |
-
.model-id {
|
157 |
-
color: #28a745;
|
158 |
-
font-family: monospace;
|
159 |
-
font-weight: bold;
|
160 |
-
}
|
161 |
-
|
162 |
-
.model-attribution {
|
163 |
-
color: #28a745;
|
164 |
-
font-size: 0.8em;
|
165 |
-
font-style: italic;
|
166 |
-
text-align: right;
|
167 |
-
margin-top: 0.5rem;
|
168 |
-
padding-top: 0.5rem;
|
169 |
-
border-top: 1px solid #eee;
|
170 |
-
}
|
171 |
-
|
172 |
-
/* Status indicators */
|
173 |
-
.online-indicator {
|
174 |
-
display: inline-block;
|
175 |
-
width: 10px;
|
176 |
-
height: 10px;
|
177 |
-
background: #28a745;
|
178 |
-
border-radius: 50%;
|
179 |
-
margin-right: 5px;
|
180 |
-
}
|
181 |
-
|
182 |
-
/* Button improvements */
|
183 |
-
.stButton button {
|
184 |
-
border-radius: 10px;
|
185 |
-
border: none;
|
186 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
187 |
-
color: white;
|
188 |
-
transition: all 0.3s;
|
189 |
-
}
|
190 |
-
|
191 |
-
.stButton button:hover {
|
192 |
-
transform: translateY(-2px);
|
193 |
-
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
|
194 |
-
}
|
195 |
-
|
196 |
-
/* Title styling */
|
197 |
-
h1 {
|
198 |
-
color: white;
|
199 |
-
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
|
200 |
-
margin-bottom: 0;
|
201 |
-
}
|
202 |
-
|
203 |
-
.stCaption {
|
204 |
-
color: rgba(255, 255, 255, 0.8);
|
205 |
-
text-align: center;
|
206 |
-
}
|
207 |
-
|
208 |
-
/* Responsive text sizing */
|
209 |
-
@media (max-width: 600px) {
|
210 |
-
.stMarkdown {
|
211 |
-
font-size: 14px;
|
212 |
}
|
213 |
|
214 |
-
.
|
215 |
-
font-size:
|
216 |
}
|
217 |
}
|
218 |
</style>
|
@@ -254,21 +187,23 @@ def clear_chat_history():
|
|
254 |
def get_user_id():
|
255 |
"""Get unique ID for this user session"""
|
256 |
if 'user_id' not in st.session_state:
|
257 |
-
st.session_state.user_id = str(uuid.uuid4())[:8]
|
258 |
return st.session_state.user_id
|
259 |
|
260 |
def update_online_users():
|
261 |
"""Update that this user is online right now"""
|
262 |
try:
|
|
|
263 |
users = {}
|
264 |
if os.path.exists(USERS_FILE):
|
265 |
with open(USERS_FILE, 'r') as f:
|
266 |
users = json.load(f)
|
267 |
|
|
|
268 |
user_id = get_user_id()
|
269 |
users[user_id] = {
|
270 |
'last_seen': datetime.now().isoformat(),
|
271 |
-
'name': f'User-{user_id}'
|
272 |
}
|
273 |
|
274 |
# Remove users not seen in last 5 minutes
|
@@ -279,12 +214,13 @@ def update_online_users():
|
|
279 |
if current_time - last_seen < timedelta(minutes=5):
|
280 |
active_users[uid] = data
|
281 |
|
|
|
282 |
with open(USERS_FILE, 'w') as f:
|
283 |
json.dump(active_users, f, indent=2)
|
284 |
|
285 |
return len(active_users)
|
286 |
except Exception:
|
287 |
-
return 1
|
288 |
|
289 |
def get_online_count():
|
290 |
"""Get number of people currently online"""
|
@@ -295,6 +231,7 @@ def get_online_count():
|
|
295 |
with open(USERS_FILE, 'r') as f:
|
296 |
users = json.load(f)
|
297 |
|
|
|
298 |
current_time = datetime.now()
|
299 |
active_count = 0
|
300 |
for data in users.values():
|
@@ -333,10 +270,11 @@ def get_ai_response(messages, model="openai/gpt-3.5-turbo"):
|
|
333 |
headers = {
|
334 |
"Content-Type": "application/json",
|
335 |
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
336 |
-
"HTTP-Referer": "http://localhost:8501",
|
337 |
-
"X-Title": "Streamlit AI Assistant"
|
338 |
}
|
339 |
|
|
|
340 |
api_messages = [{"role": "system", "content": "You are a helpful AI assistant. Provide clear and helpful responses."}]
|
341 |
api_messages.extend(messages)
|
342 |
|
@@ -354,6 +292,7 @@ def get_ai_response(messages, model="openai/gpt-3.5-turbo"):
|
|
354 |
try:
|
355 |
response = requests.post(url, headers=headers, json=data, stream=True, timeout=60)
|
356 |
|
|
|
357 |
if response.status_code != 200:
|
358 |
error_detail = ""
|
359 |
try:
|
@@ -366,9 +305,12 @@ def get_ai_response(messages, model="openai/gpt-3.5-turbo"):
|
|
366 |
return
|
367 |
|
368 |
full_response = ""
|
|
|
369 |
|
|
|
370 |
for line in response.iter_lines():
|
371 |
if line:
|
|
|
372 |
if line.startswith(b"data: "):
|
373 |
data_str = line[len(b"data: "):].decode("utf-8")
|
374 |
if data_str.strip() == "[DONE]":
|
@@ -393,43 +335,46 @@ def get_ai_response(messages, model="openai/gpt-3.5-turbo"):
|
|
393 |
except Exception as e:
|
394 |
yield f"Unexpected error: {str(e)}. Please try again or contact support."
|
395 |
|
396 |
-
#
|
397 |
-
|
398 |
-
|
399 |
-
st.title("Chat Flow π·")
|
400 |
-
st.caption("10 powerful Models, one simple chat.")
|
401 |
|
402 |
-
#
|
403 |
with st.sidebar:
|
404 |
-
st.header("
|
405 |
|
406 |
-
# API Status
|
407 |
status = check_api_status()
|
408 |
if status == "Connected":
|
409 |
st.success("π’ API Connected")
|
410 |
elif status == "No API Key":
|
411 |
-
st.error("
|
412 |
else:
|
413 |
-
st.warning("
|
414 |
|
415 |
st.divider()
|
416 |
|
417 |
-
#
|
418 |
-
st.header("π₯
|
|
|
|
|
419 |
online_count = update_online_users()
|
420 |
|
|
|
421 |
if online_count == 1:
|
422 |
st.info("π’ Just you online")
|
423 |
else:
|
424 |
st.success(f"π’ {online_count} people online")
|
425 |
|
|
|
426 |
your_id = get_user_id()
|
427 |
st.caption(f"You: User-{your_id}")
|
428 |
|
429 |
-
|
|
|
430 |
st.rerun()
|
431 |
|
432 |
-
# Debug
|
433 |
with st.expander("π Debug Info"):
|
434 |
if os.path.exists(USERS_FILE):
|
435 |
with open(USERS_FILE, 'r') as f:
|
@@ -445,8 +390,7 @@ with st.sidebar:
|
|
445 |
|
446 |
st.divider()
|
447 |
|
448 |
-
#
|
449 |
-
st.header("π€ AI Models")
|
450 |
models = [
|
451 |
("GPT-3.5 Turbo", "openai/gpt-3.5-turbo"),
|
452 |
("LLaMA 3.1 8B", "meta-llama/llama-3.1-8b-instruct"),
|
@@ -463,66 +407,75 @@ with st.sidebar:
|
|
463 |
model_names = [name for name, _ in models]
|
464 |
model_ids = [model_id for _, model_id in models]
|
465 |
|
466 |
-
selected_index = st.selectbox("
|
467 |
format_func=lambda x: model_names[x],
|
468 |
index=0)
|
469 |
selected_model = model_ids[selected_index]
|
470 |
|
|
|
471 |
st.markdown(f"**Model ID:** <span class='model-id'>{selected_model}</span>", unsafe_allow_html=True)
|
472 |
|
473 |
st.divider()
|
474 |
|
475 |
-
# Chat History Controls
|
476 |
-
st.header("
|
477 |
|
|
|
478 |
if st.session_state.messages:
|
479 |
-
st.info(f"
|
480 |
|
|
|
481 |
auto_save = st.checkbox("Auto-save messages", value=True)
|
482 |
|
483 |
-
#
|
484 |
col1, col2 = st.columns(2)
|
485 |
with col1:
|
486 |
-
if st.button("
|
487 |
save_chat_history(st.session_state.messages)
|
488 |
-
st.success("
|
489 |
|
490 |
with col2:
|
491 |
-
if st.button("
|
492 |
st.session_state.messages = load_chat_history()
|
493 |
-
st.success("
|
494 |
st.rerun()
|
495 |
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
|
501 |
-
history_content = f.read()
|
502 |
-
st.text_area("Chat History (JSON)", history_content, height=150)
|
503 |
-
else:
|
504 |
-
st.warning("No history file found")
|
505 |
-
|
506 |
-
# Download History
|
507 |
if os.path.exists(HISTORY_FILE):
|
508 |
-
with open(HISTORY_FILE, '
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
521 |
|
522 |
-
# Display chat messages
|
523 |
for message in st.session_state.messages:
|
524 |
with st.chat_message(message["role"]):
|
|
|
525 |
if message["role"] == "assistant" and "Response created by:" in message["content"]:
|
|
|
526 |
parts = message["content"].split("\n\n---\n*Response created by:")
|
527 |
main_content = parts[0]
|
528 |
if len(parts) > 1:
|
@@ -534,19 +487,24 @@ for message in st.session_state.messages:
|
|
534 |
else:
|
535 |
st.markdown(message["content"])
|
536 |
|
537 |
-
# Chat input
|
538 |
-
if prompt := st.chat_input("
|
|
|
539 |
update_online_users()
|
540 |
|
|
|
541 |
user_message = {"role": "user", "content": prompt}
|
542 |
st.session_state.messages.append(user_message)
|
543 |
|
|
|
544 |
if auto_save:
|
545 |
save_chat_history(st.session_state.messages)
|
546 |
|
|
|
547 |
with st.chat_message("user"):
|
548 |
st.markdown(prompt)
|
549 |
|
|
|
550 |
with st.chat_message("assistant"):
|
551 |
placeholder = st.empty()
|
552 |
|
@@ -556,6 +514,7 @@ if prompt := st.chat_input("π¬ Chat with AI... (works on all devices!)"):
|
|
556 |
full_response = response
|
557 |
placeholder.markdown(full_response + "β")
|
558 |
|
|
|
559 |
placeholder.markdown(full_response)
|
560 |
|
561 |
except Exception as e:
|
@@ -563,15 +522,14 @@ if prompt := st.chat_input("π¬ Chat with AI... (works on all devices!)"):
|
|
563 |
placeholder.markdown(error_msg)
|
564 |
full_response = error_msg
|
565 |
|
|
|
566 |
full_response_with_attribution = full_response + f"\n\n---\n*Response created by: **{model_names[selected_index]}***"
|
567 |
assistant_message = {"role": "assistant", "content": full_response_with_attribution}
|
568 |
st.session_state.messages.append(assistant_message)
|
569 |
|
|
|
570 |
if auto_save:
|
571 |
save_chat_history(st.session_state.messages)
|
572 |
|
573 |
-
#
|
574 |
-
|
575 |
-
with col2:
|
576 |
-
st.caption(f"Currently using: **{model_names[selected_index]}**")
|
577 |
-
st.caption("π± Optimized for all mobile devices")
|
|
|
6 |
import time
|
7 |
import uuid
|
8 |
|
9 |
+
# Page configuration
|
10 |
st.set_page_config(
|
11 |
page_title="Chat Flow π·",
|
12 |
page_icon="π¬",
|
13 |
+
initial_sidebar_state="collapsed"
|
|
|
14 |
)
|
15 |
|
16 |
+
# CSS - Keep original web design, add mobile responsiveness only
|
17 |
st.markdown("""
|
18 |
<style>
|
|
|
19 |
.stApp {
|
20 |
+
background: white;
|
|
|
21 |
}
|
22 |
|
|
|
23 |
.main .block-container {
|
24 |
+
max-width: 800px;
|
|
|
|
|
|
|
25 |
}
|
26 |
|
|
|
27 |
#MainMenu {visibility: hidden;}
|
28 |
footer {visibility: hidden;}
|
29 |
header {visibility: hidden;}
|
30 |
.stDeployButton {display: none;}
|
31 |
|
32 |
+
.model-id {
|
33 |
+
color: #28a745;
|
34 |
+
font-family: monospace;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
}
|
36 |
|
37 |
+
.model-attribution {
|
38 |
+
color: #28a745;
|
39 |
+
font-size: 0.8em;
|
40 |
+
font-style: italic;
|
|
|
41 |
}
|
42 |
|
43 |
+
/* MOBILE ONLY - doesn't affect web */
|
44 |
@media (max-width: 768px) {
|
45 |
+
.stApp {
|
46 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
47 |
+
}
|
48 |
+
|
49 |
.main .block-container {
|
|
|
50 |
max-width: 100%;
|
51 |
+
padding: 0.5rem;
|
52 |
+
}
|
53 |
+
|
54 |
+
/* Make sidebar work better on mobile */
|
55 |
+
.css-1d391kg {
|
56 |
+
width: 100% !important;
|
57 |
+
background: rgba(255, 255, 255, 0.95);
|
58 |
+
backdrop-filter: blur(10px);
|
59 |
}
|
60 |
|
61 |
+
/* Chat messages styling for mobile */
|
62 |
+
.stChatMessage {
|
63 |
+
background: rgba(255, 255, 255, 0.95);
|
64 |
+
border-radius: 15px;
|
65 |
+
margin: 0.5rem 0;
|
66 |
+
padding: 1rem;
|
67 |
+
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
68 |
+
}
|
69 |
+
|
70 |
+
/* User messages - right aligned */
|
71 |
.stChatMessage[data-testid="user-message"] {
|
72 |
+
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
|
73 |
+
color: white;
|
74 |
+
margin-left: 15%;
|
75 |
}
|
76 |
|
77 |
+
/* Assistant messages - left aligned */
|
78 |
.stChatMessage[data-testid="assistant-message"] {
|
79 |
+
background: rgba(255, 255, 255, 0.98);
|
80 |
+
color: #333;
|
81 |
+
margin-right: 15%;
|
82 |
}
|
83 |
|
84 |
+
/* Mobile text sizing */
|
85 |
+
.stMarkdown {
|
86 |
+
font-size: 14px;
|
|
|
87 |
}
|
88 |
|
|
|
89 |
h1 {
|
90 |
font-size: 1.5rem !important;
|
91 |
+
color: white;
|
92 |
+
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
|
93 |
text-align: center;
|
94 |
}
|
95 |
|
96 |
+
.stCaption {
|
97 |
+
color: rgba(255, 255, 255, 0.8);
|
98 |
+
text-align: center;
|
99 |
}
|
100 |
|
101 |
+
/* Mobile buttons */
|
102 |
.stButton button {
|
103 |
+
border-radius: 8px;
|
104 |
font-size: 14px;
|
105 |
+
}
|
106 |
+
|
107 |
+
/* Chat input for mobile */
|
108 |
+
.stChatInput {
|
109 |
+
background: rgba(255, 255, 255, 0.9);
|
110 |
+
border-radius: 20px;
|
111 |
+
backdrop-filter: blur(10px);
|
112 |
+
}
|
113 |
+
|
114 |
+
.stChatInput input {
|
115 |
+
font-size: 16px; /* Prevents zoom on iOS */
|
116 |
}
|
117 |
}
|
118 |
|
119 |
+
/* Extra small screens (iPhone 5, old phones) */
|
120 |
@media (max-width: 480px) {
|
121 |
.main .block-container {
|
122 |
padding: 0.25rem;
|
|
|
128 |
}
|
129 |
|
130 |
.stChatMessage[data-testid="user-message"] {
|
131 |
+
margin-left: 8%;
|
132 |
}
|
133 |
|
134 |
.stChatMessage[data-testid="assistant-message"] {
|
135 |
+
margin-right: 8%;
|
136 |
}
|
137 |
|
138 |
h1 {
|
139 |
+
font-size: 1.3rem !important;
|
140 |
}
|
141 |
|
142 |
+
.stButton button {
|
143 |
+
font-size: 12px;
|
144 |
+
padding: 0.4rem;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
}
|
146 |
|
147 |
+
.stMarkdown {
|
148 |
+
font-size: 13px;
|
149 |
}
|
150 |
}
|
151 |
</style>
|
|
|
187 |
def get_user_id():
|
188 |
"""Get unique ID for this user session"""
|
189 |
if 'user_id' not in st.session_state:
|
190 |
+
st.session_state.user_id = str(uuid.uuid4())[:8] # Short ID for family use
|
191 |
return st.session_state.user_id
|
192 |
|
193 |
def update_online_users():
|
194 |
"""Update that this user is online right now"""
|
195 |
try:
|
196 |
+
# Load current online users
|
197 |
users = {}
|
198 |
if os.path.exists(USERS_FILE):
|
199 |
with open(USERS_FILE, 'r') as f:
|
200 |
users = json.load(f)
|
201 |
|
202 |
+
# Add/update this user
|
203 |
user_id = get_user_id()
|
204 |
users[user_id] = {
|
205 |
'last_seen': datetime.now().isoformat(),
|
206 |
+
'name': f'User-{user_id}' # You can customize this
|
207 |
}
|
208 |
|
209 |
# Remove users not seen in last 5 minutes
|
|
|
214 |
if current_time - last_seen < timedelta(minutes=5):
|
215 |
active_users[uid] = data
|
216 |
|
217 |
+
# Save updated list
|
218 |
with open(USERS_FILE, 'w') as f:
|
219 |
json.dump(active_users, f, indent=2)
|
220 |
|
221 |
return len(active_users)
|
222 |
except Exception:
|
223 |
+
return 1 # If error, assume at least you're online
|
224 |
|
225 |
def get_online_count():
|
226 |
"""Get number of people currently online"""
|
|
|
231 |
with open(USERS_FILE, 'r') as f:
|
232 |
users = json.load(f)
|
233 |
|
234 |
+
# Check who's still active (last 5 minutes)
|
235 |
current_time = datetime.now()
|
236 |
active_count = 0
|
237 |
for data in users.values():
|
|
|
270 |
headers = {
|
271 |
"Content-Type": "application/json",
|
272 |
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
273 |
+
"HTTP-Referer": "http://localhost:8501", # Optional: Your site URL
|
274 |
+
"X-Title": "Streamlit AI Assistant" # Optional: Your app name
|
275 |
}
|
276 |
|
277 |
+
# Create system message and user messages
|
278 |
api_messages = [{"role": "system", "content": "You are a helpful AI assistant. Provide clear and helpful responses."}]
|
279 |
api_messages.extend(messages)
|
280 |
|
|
|
292 |
try:
|
293 |
response = requests.post(url, headers=headers, json=data, stream=True, timeout=60)
|
294 |
|
295 |
+
# Better error handling
|
296 |
if response.status_code != 200:
|
297 |
error_detail = ""
|
298 |
try:
|
|
|
305 |
return
|
306 |
|
307 |
full_response = ""
|
308 |
+
buffer = ""
|
309 |
|
310 |
+
# Using your working streaming logic
|
311 |
for line in response.iter_lines():
|
312 |
if line:
|
313 |
+
# The server sends lines starting with "data: ..."
|
314 |
if line.startswith(b"data: "):
|
315 |
data_str = line[len(b"data: "):].decode("utf-8")
|
316 |
if data_str.strip() == "[DONE]":
|
|
|
335 |
except Exception as e:
|
336 |
yield f"Unexpected error: {str(e)}. Please try again or contact support."
|
337 |
|
338 |
+
# Header
|
339 |
+
st.title("Chat Flow π·")
|
340 |
+
st.caption("10 powerful Models, one simple chat.")
|
|
|
|
|
341 |
|
342 |
+
# Sidebar
|
343 |
with st.sidebar:
|
344 |
+
st.header("Settings")
|
345 |
|
346 |
+
# API Status
|
347 |
status = check_api_status()
|
348 |
if status == "Connected":
|
349 |
st.success("π’ API Connected")
|
350 |
elif status == "No API Key":
|
351 |
+
st.error("No API Key")
|
352 |
else:
|
353 |
+
st.warning("Connection Issue")
|
354 |
|
355 |
st.divider()
|
356 |
|
357 |
+
# Live Users Section
|
358 |
+
st.header("π₯ Who's Online")
|
359 |
+
|
360 |
+
# Update that you're online
|
361 |
online_count = update_online_users()
|
362 |
|
363 |
+
# Show live count
|
364 |
if online_count == 1:
|
365 |
st.info("π’ Just you online")
|
366 |
else:
|
367 |
st.success(f"π’ {online_count} people online")
|
368 |
|
369 |
+
# Show your session
|
370 |
your_id = get_user_id()
|
371 |
st.caption(f"You: User-{your_id}")
|
372 |
|
373 |
+
# Quick refresh button
|
374 |
+
if st.button("Refresh", use_container_width=True):
|
375 |
st.rerun()
|
376 |
|
377 |
+
# Debug Section
|
378 |
with st.expander("π Debug Info"):
|
379 |
if os.path.exists(USERS_FILE):
|
380 |
with open(USERS_FILE, 'r') as f:
|
|
|
390 |
|
391 |
st.divider()
|
392 |
|
393 |
+
# All models including new ones
|
|
|
394 |
models = [
|
395 |
("GPT-3.5 Turbo", "openai/gpt-3.5-turbo"),
|
396 |
("LLaMA 3.1 8B", "meta-llama/llama-3.1-8b-instruct"),
|
|
|
407 |
model_names = [name for name, _ in models]
|
408 |
model_ids = [model_id for _, model_id in models]
|
409 |
|
410 |
+
selected_index = st.selectbox("Model", range(len(model_names)),
|
411 |
format_func=lambda x: model_names[x],
|
412 |
index=0)
|
413 |
selected_model = model_ids[selected_index]
|
414 |
|
415 |
+
# Show selected model ID in green
|
416 |
st.markdown(f"**Model ID:** <span class='model-id'>{selected_model}</span>", unsafe_allow_html=True)
|
417 |
|
418 |
st.divider()
|
419 |
|
420 |
+
# Chat History Controls
|
421 |
+
st.header("Chat History")
|
422 |
|
423 |
+
# Show number of messages
|
424 |
if st.session_state.messages:
|
425 |
+
st.info(f"Messages stored: {len(st.session_state.messages)}")
|
426 |
|
427 |
+
# Auto-save toggle
|
428 |
auto_save = st.checkbox("Auto-save messages", value=True)
|
429 |
|
430 |
+
# Manual save/load buttons
|
431 |
col1, col2 = st.columns(2)
|
432 |
with col1:
|
433 |
+
if st.button("Save History", use_container_width=True):
|
434 |
save_chat_history(st.session_state.messages)
|
435 |
+
st.success("History saved!")
|
436 |
|
437 |
with col2:
|
438 |
+
if st.button("Load History", use_container_width=True):
|
439 |
st.session_state.messages = load_chat_history()
|
440 |
+
st.success("History loaded!")
|
441 |
st.rerun()
|
442 |
|
443 |
+
st.divider()
|
444 |
+
|
445 |
+
# View History
|
446 |
+
if st.button("View History File", use_container_width=True):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
447 |
if os.path.exists(HISTORY_FILE):
|
448 |
+
with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
|
449 |
+
history_content = f.read()
|
450 |
+
st.text_area("Chat History (JSON)", history_content, height=200)
|
451 |
+
else:
|
452 |
+
st.warning("No history file found")
|
453 |
+
|
454 |
+
# Download History
|
455 |
+
if os.path.exists(HISTORY_FILE):
|
456 |
+
with open(HISTORY_FILE, 'rb') as f:
|
457 |
+
st.download_button(
|
458 |
+
label="Download History",
|
459 |
+
data=f.read(),
|
460 |
+
file_name=f"chat_history_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
461 |
+
mime="application/json",
|
462 |
+
use_container_width=True
|
463 |
+
)
|
464 |
+
|
465 |
+
st.divider()
|
466 |
+
|
467 |
+
# Clear controls
|
468 |
+
if st.button("Clear Chat", use_container_width=True, type="secondary"):
|
469 |
+
clear_chat_history()
|
470 |
+
st.success("Chat cleared!")
|
471 |
+
st.rerun()
|
472 |
|
473 |
+
# Display chat messages
|
474 |
for message in st.session_state.messages:
|
475 |
with st.chat_message(message["role"]):
|
476 |
+
# Check if this is an assistant message with attribution
|
477 |
if message["role"] == "assistant" and "Response created by:" in message["content"]:
|
478 |
+
# Split content and attribution
|
479 |
parts = message["content"].split("\n\n---\n*Response created by:")
|
480 |
main_content = parts[0]
|
481 |
if len(parts) > 1:
|
|
|
487 |
else:
|
488 |
st.markdown(message["content"])
|
489 |
|
490 |
+
# Chat input
|
491 |
+
if prompt := st.chat_input("Chat Smarter. Chat many Brains"):
|
492 |
+
# Update online status when user sends message
|
493 |
update_online_users()
|
494 |
|
495 |
+
# Add user message
|
496 |
user_message = {"role": "user", "content": prompt}
|
497 |
st.session_state.messages.append(user_message)
|
498 |
|
499 |
+
# Auto-save if enabled
|
500 |
if auto_save:
|
501 |
save_chat_history(st.session_state.messages)
|
502 |
|
503 |
+
# Display user message
|
504 |
with st.chat_message("user"):
|
505 |
st.markdown(prompt)
|
506 |
|
507 |
+
# Get AI response
|
508 |
with st.chat_message("assistant"):
|
509 |
placeholder = st.empty()
|
510 |
|
|
|
514 |
full_response = response
|
515 |
placeholder.markdown(full_response + "β")
|
516 |
|
517 |
+
# Remove cursor and show final response
|
518 |
placeholder.markdown(full_response)
|
519 |
|
520 |
except Exception as e:
|
|
|
522 |
placeholder.markdown(error_msg)
|
523 |
full_response = error_msg
|
524 |
|
525 |
+
# Add AI response to messages with attribution
|
526 |
full_response_with_attribution = full_response + f"\n\n---\n*Response created by: **{model_names[selected_index]}***"
|
527 |
assistant_message = {"role": "assistant", "content": full_response_with_attribution}
|
528 |
st.session_state.messages.append(assistant_message)
|
529 |
|
530 |
+
# Auto-save if enabled
|
531 |
if auto_save:
|
532 |
save_chat_history(st.session_state.messages)
|
533 |
|
534 |
+
# Show currently using model
|
535 |
+
st.caption(f"Currently using: **{model_names[selected_index]}**")
|
|
|
|
|
|