Spaces:
Sleeping
Sleeping
File size: 18,462 Bytes
f2681f2 f3c1a41 f2681f2 f3c1a41 f2681f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | import os
import streamlit as st
import uuid
import time
# from teacher import teacher_agent
from synthesize import workflow
# ================================================================
# PAGE CONFIG
# ================================================================
st.set_page_config(
page_title="Academic AI System",
page_icon="๐",
layout="wide",
initial_sidebar_state="expanded",
)
# ================================================================
# CUSTOM CSS
# ================================================================
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@300;400;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
:root {
--bg: #0d0f14;
--surface: #13161f;
--border: #1e2330;
--accent: #4f8ef7;
--accent2: #a78bfa;
--green: #34d399;
--yellow: #fbbf24;
--red: #f87171;
--text: #e2e8f0;
--muted: #64748b;
}
html, body, [data-testid="stAppViewContainer"] {
background-color: var(--bg) !important;
font-family: 'Sora', sans-serif;
color: var(--text);
}
[data-testid="stSidebar"] {
background-color: var(--surface) !important;
border-right: 1px solid var(--border);
}
[data-testid="stSidebar"] * { color: var(--text) !important; }
/* Header */
.header {
display: flex;
align-items: center;
gap: 14px;
padding: 18px 0 24px 0;
border-bottom: 1px solid var(--border);
margin-bottom: 24px;
}
.header-icon {
font-size: 2.2rem;
background: linear-gradient(135deg, #4f8ef7, #a78bfa);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.header-title {
font-size: 1.5rem;
font-weight: 700;
background: linear-gradient(90deg, #4f8ef7, #a78bfa);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin: 0;
}
.header-sub {
font-size: 0.78rem;
color: var(--muted);
margin: 0;
}
/* Chat messages */
.msg-user {
display: flex;
justify-content: flex-end;
margin: 12px 0;
}
.msg-user .bubble {
background: linear-gradient(135deg, #4f8ef7, #3b6fd4);
color: #fff;
padding: 12px 18px;
border-radius: 18px 18px 4px 18px;
max-width: 70%;
font-size: 0.93rem;
line-height: 1.6;
box-shadow: 0 4px 20px rgba(79,142,247,0.25);
}
.msg-assistant {
display: flex;
justify-content: flex-start;
margin: 12px 0;
gap: 10px;
}
.msg-assistant .avatar {
width: 34px;
height: 34px;
border-radius: 50%;
background: linear-gradient(135deg, #a78bfa, #4f8ef7);
display: flex;
align-items: center;
justify-content: center;
font-size: 1rem;
flex-shrink: 0;
margin-top: 2px;
}
.msg-assistant .bubble {
background: var(--surface);
border: 1px solid var(--border);
color: var(--text);
padding: 14px 18px;
border-radius: 4px 18px 18px 18px;
max-width: 75%;
font-size: 0.93rem;
line-height: 1.7;
}
/* Agent badge */
.agent-badge {
display: inline-block;
font-size: 0.68rem;
font-family: 'JetBrains Mono', monospace;
padding: 2px 8px;
border-radius: 4px;
margin-bottom: 6px;
font-weight: 500;
}
.badge-teacher { background: rgba(79,142,247,0.15); color: #4f8ef7; border: 1px solid rgba(79,142,247,0.3); }
.badge-teacher_assistant { background: rgba(167,139,250,0.15); color: #a78bfa; border: 1px solid rgba(167,139,250,0.3); }
.badge-planner { background: rgba(52,211,153,0.15); color: #34d399; border: 1px solid rgba(52,211,153,0.3); }
.badge-router { background: rgba(251,191,36,0.15); color: #fbbf24; border: 1px solid rgba(251,191,36,0.3); }
/* Status indicators */
.status-bar {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin: 8px 0 16px 0;
}
.status-dot {
display: flex;
align-items: center;
gap: 5px;
font-size: 0.75rem;
color: var(--muted);
font-family: 'JetBrains Mono', monospace;
}
.dot { width: 7px; height: 7px; border-radius: 50%; }
.dot-active { background: var(--green); box-shadow: 0 0 6px var(--green); animation: pulse 1.5s infinite; }
.dot-idle { background: var(--muted); }
.dot-routing { background: var(--yellow); box-shadow: 0 0 6px var(--yellow); animation: pulse 1s infinite; }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
/* Thinking indicator */
.thinking {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 0.82rem;
font-family: 'JetBrains Mono', monospace;
padding: 10px 0;
}
.thinking-dots span {
display: inline-block;
width: 5px; height: 5px;
border-radius: 50%;
background: var(--accent);
animation: bounce 1.2s infinite;
margin: 0 2px;
}
.thinking-dots span:nth-child(2) { animation-delay: 0.2s; }
.thinking-dots span:nth-child(3) { animation-delay: 0.4s; }
@keyframes bounce {
0%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-6px); }
}
/* Sidebar session item */
.session-item {
padding: 10px 12px;
border-radius: 8px;
border: 1px solid var(--border);
margin-bottom: 6px;
cursor: pointer;
transition: all 0.2s;
font-size: 0.82rem;
}
.session-item:hover { border-color: var(--accent); background: rgba(79,142,247,0.07); }
.session-active { border-color: var(--accent) !important; background: rgba(79,142,247,0.12) !important; }
/* Input area */
[data-testid="stChatInput"] textarea {
background: var(--surface) !important;
border: 1px solid var(--border) !important;
color: var(--text) !important;
border-radius: 12px !important;
font-family: 'Sora', sans-serif !important;
}
[data-testid="stChatInput"] textarea:focus {
border-color: var(--accent) !important;
box-shadow: 0 0 0 2px rgba(79,142,247,0.2) !important;
}
/* Metrics */
.metric-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 12px 16px;
text-align: center;
}
.metric-val { font-size: 1.6rem; font-weight: 700; color: var(--accent); }
.metric-label { font-size: 0.72rem; color: var(--muted); margin-top: 2px; }
/* Divider */
hr { border-color: var(--border) !important; margin: 16px 0 !important; }
/* Hide streamlit chrome */
#MainMenu, footer, header { visibility: hidden; }
[data-testid="stToolbar"] { display: none; }
</style>
""", unsafe_allow_html=True)
# ================================================================
# SESSION STATE INIT
# ================================================================
if "sessions" not in st.session_state:
st.session_state.sessions = {} # {session_id: {"name": str, "messages": []}}
if "active_session" not in st.session_state:
# create default session
sid = str(uuid.uuid4())[:8]
st.session_state.sessions[sid] = {"name": "Session 1", "messages": []}
st.session_state.active_session = sid
if "is_thinking" not in st.session_state:
st.session_state.is_thinking = False
if "total_queries" not in st.session_state:
st.session_state.total_queries = 0
# ================================================================
# HELPERS
# ================================================================
def get_active_messages():
return st.session_state.sessions[st.session_state.active_session]["messages"]
def add_message(role: str, content: str, agent: str = None):
get_active_messages().append({
"role": role,
"content": content,
"agent": agent,
"time": time.strftime("%H:%M"),
})
def new_session():
sid = str(uuid.uuid4())[:8]
name = f"Session {len(st.session_state.sessions) + 1}"
st.session_state.sessions[sid] = {"name": name, "messages": []}
st.session_state.active_session = sid
def clear_session():
st.session_state.sessions[st.session_state.active_session]["messages"] = []
def render_message(msg: dict):
if msg["role"] == "user":
st.markdown(f"""
<div class="msg-user">
<div class="bubble">{msg['content']}</div>
</div>""", unsafe_allow_html=True)
else:
agent = msg.get("agent", "system")
badge_class = f"badge-{agent}" if agent in ["teacher","teacher_assistant","planner","router"] else "badge-router"
agent_label = {
"teacher": "๐งโ๐ซ Teacher",
"teacher_assistant": "๐ค Assistant",
"planner": "๐ Planner",
"router": "๐งญ Router",
}.get(agent, "๐ค Agent")
st.markdown(f"""
<div class="msg-assistant">
<div class="avatar">๐</div>
<div>
<span class="agent-badge {badge_class}">{agent_label}</span>
<div class="bubble">{msg['content']}</div>
<div style="font-size:0.68rem;color:var(--muted);margin-top:4px;font-family:'JetBrains Mono',monospace;">{msg.get('time','')}</div>
</div>
</div>""", unsafe_allow_html=True)
def query_workflow(user_input: str) -> str:
# โ
build history from current session messages
history = get_active_messages()
# format history as conversation context
history_text = ""
for msg in history[:-1]: # exclude the last user message (already in query)
role = "User" if msg["role"] == "user" else "Assistant"
history_text += f"{role}: {msg['content']}\n\n"
# โ
inject history into query
full_query = user_input
if history_text:
full_query = f"""Previous conversation:
{history_text}
Current question: {user_input}"""
inputs = {
"query": full_query, # โ
query + history
"classifications": [],
"results": [],
"final_answer": "",
}
thread_id = f"session_{st.session_state.active_session}"
config = {"configurable": {"thread_id": thread_id}}
final_text = ""
try:
for chunk in workflow.stream(inputs, config=config, stream_mode="values"):
if "final_answer" in chunk and chunk["final_answer"]:
final_text = chunk["final_answer"]
except Exception as e:
return f"โ ๏ธ Error: {str(e)}"
return final_text or "I could not generate a response. Please try again."
# def query_workflow(user_input: str) -> str:
# # โ
build history
# history = get_active_messages()
# history_text = ""
# for msg in history[:-1]:
# role = "User" if msg["role"] == "user" else "Assistant"
# history_text += f"{role}: {msg['content']}\n\n"
# full_query = user_input
# if history_text:
# full_query = f"""Previous conversation:
# {history_text}
# Current question: {user_input}"""
# # โ
ุงุณุชุฎุฏู
teacher_agent ู
ุจุงุดุฑุฉ โ ู
ุด workflow
# thread_id = f"session_{st.session_state.active_session}"
# config = {"configurable": {"thread_id": thread_id}}
# final_text = ""
# try:
# result = teacher_agent.invoke(
# {"messages": [("user", full_query)]},
# config=config
# )
# messages = result.get("messages", [])
# for msg in reversed(messages):
# if hasattr(msg, "content") and msg.content:
# if not hasattr(msg, "tool_calls") or not msg.tool_calls:
# final_text = msg.content
# break
# except Exception as e:
# return f"โ ๏ธ Error: {str(e)}"
# return final_text or "I could not generate a response. Please try again."
# ================================================================
# SIDEBAR
# ================================================================
with st.sidebar:
st.markdown("""
<div style="padding:16px 0 8px 0">
<div style="font-size:1.1rem;font-weight:700;background:linear-gradient(90deg,#4f8ef7,#a78bfa);
-webkit-background-clip:text;-webkit-text-fill-color:transparent;">
๐ Academic AI
</div>
<div style="font-size:0.72rem;color:var(--muted);margin-top:2px;">Multi-Agent System</div>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# โโ New session button โโ
if st.button("๏ผ New Session", use_container_width=True, type="primary"):
new_session()
st.rerun()
st.markdown("<div style='font-size:0.72rem;color:var(--muted);margin:12px 0 6px 0;font-family:JetBrains Mono,monospace;'>SESSIONS</div>", unsafe_allow_html=True)
# โโ Session list โโ
for sid, sdata in st.session_state.sessions.items():
is_active = sid == st.session_state.active_session
msg_count = len(sdata["messages"])
label = f"{sdata['name']} ยท {msg_count // 2} msg{'s' if msg_count != 2 else ''}"
cls = "session-item session-active" if is_active else "session-item"
st.markdown(f'<div class="{cls}" id="sess_{sid}">{label}</div>', unsafe_allow_html=True)
if st.button(sdata["name"], key=f"btn_{sid}", use_container_width=True,
help="Switch to this session"):
st.session_state.active_session = sid
st.rerun()
st.markdown("---")
# โโ Agents status โโ
st.markdown("<div style='font-size:0.72rem;color:var(--muted);margin-bottom:8px;font-family:JetBrains Mono,monospace;'>AGENTS</div>", unsafe_allow_html=True)
for agent_name, color, icon in [
("Teacher", "#4f8ef7", "๐งโ๐ซ"),
("Teacher Assistant", "#a78bfa", "๐ค"),
("Planner", "#34d399", "๐"),
("Router", "#fbbf24", "๐งญ"),
]:
st.markdown(f"""
<div style="display:flex;align-items:center;gap:8px;
padding:6px 10px;border-radius:6px;margin-bottom:4px;
background:var(--surface);border:1px solid var(--border);">
<div style="width:7px;height:7px;border-radius:50%;background:{color};"></div>
<span style="font-size:0.78rem;">{icon} {agent_name}</span>
</div>""", unsafe_allow_html=True)
st.markdown("---")
# โโ Stats โโ
msgs = get_active_messages()
user_msgs = [m for m in msgs if m["role"] == "user"]
c1, c2 = st.columns(2)
with c1:
st.markdown(f"""
<div class="metric-card">
<div class="metric-val">{len(user_msgs)}</div>
<div class="metric-label">Queries</div>
</div>""", unsafe_allow_html=True)
with c2:
st.markdown(f"""
<div class="metric-card">
<div class="metric-val">{len(st.session_state.sessions)}</div>
<div class="metric-label">Sessions</div>
</div>""", unsafe_allow_html=True)
st.markdown("---")
if st.button("๐๏ธ Clear Chat", use_container_width=True):
clear_session()
st.rerun()
# ================================================================
# MAIN AREA
# ================================================================
st.markdown("""
<div class="header">
<div class="header-icon">๐</div>
<div>
<p class="header-title">Academic AI System</p>
<p class="header-sub">3 specialized agents ยท Router ยท Synthesizer</p>
</div>
</div>
""", unsafe_allow_html=True)
# โโ Chat history โโ
messages = get_active_messages()
if not messages:
st.markdown("""
<div style="text-align:center;padding:60px 0;color:var(--muted);">
<div style="font-size:3rem;margin-bottom:12px;">๐</div>
<div style="font-size:1rem;font-weight:600;color:var(--text);margin-bottom:6px;">
Ask anything academic
</div>
<div style="font-size:0.82rem;">
Theory ยท Technical ยท Planning โ the right agent will handle it
</div>
<div style="margin-top:24px;display:flex;gap:10px;justify-content:center;flex-wrap:wrap;">
<span style="background:var(--surface);border:1px solid var(--border);
padding:6px 14px;border-radius:20px;font-size:0.78rem;">
๐ก Explain transformers in deep learning
</span>
<span style="background:var(--surface);border:1px solid var(--border);
padding:6px 14px;border-radius:20px;font-size:0.78rem;">
๐ ๏ธ Fix my PyTorch CUDA error
</span>
<span style="background:var(--surface);border:1px solid var(--border);
padding:6px 14px;border-radius:20px;font-size:0.78rem;">
๐ Create a 3-month ML roadmap
</span>
</div>
</div>
""", unsafe_allow_html=True)
else:
for msg in messages:
render_message(msg)
# โโ Thinking indicator โโ
thinking_placeholder = st.empty()
# โโ Chat input โโ
user_input = st.chat_input("Ask your question...")
if user_input:
# Add user message
add_message("user", user_input)
st.session_state.total_queries += 1
# Show thinking
with thinking_placeholder:
st.markdown("""
<div class="thinking">
๐งญ Routing & thinking
<span class="thinking-dots">
<span></span><span></span><span></span>
</span>
</div>""", unsafe_allow_html=True)
# Get full response
response = query_workflow(user_input)
# Clear thinking
thinking_placeholder.empty()
# โ
stream character by character in the UI
stream_placeholder = st.empty()
displayed = ""
for char in response:
displayed += char
stream_placeholder.markdown(f"""
<div class="msg-assistant">
<div class="avatar">๐</div>
<div>
<span class="agent-badge badge-teacher">๐งโ๐ซ Teacher</span>
<div class="bubble">{displayed}โ</div>
</div>
</div>""", unsafe_allow_html=True)
time.sleep(0.008) # โก adjust speed โ lower = faster
# Final render without cursor
stream_placeholder.markdown(f"""
<div class="msg-assistant">
<div class="avatar">๐</div>
<div>
<span class="agent-badge badge-teacher">๐งโ๐ซ Teacher</span>
<div class="bubble">{displayed}</div>
</div>
</div>""", unsafe_allow_html=True)
# Save to history
add_message("assistant", response, agent="teacher")
st.rerun() |