Spaces:
Runtime error
Runtime error
File size: 21,998 Bytes
ed13191 | 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 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 | """
QuantProdigy AI Agents - Free Version for Hugging Face Spaces
Multi-agent learning platform for CFA preparation using only free resources
"""
import streamlit as st
import json
import plotly.graph_objects as go
from typing import Dict, List, Optional
from datetime import datetime
import sys
import os
# Debug: Print current directory and files
print("Current directory:", os.getcwd())
print("Files in directory:", os.listdir('.'))
# Add current directory to path for Hugging Face Spaces
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
# Import agent system with error handling
try:
# Check if agent files exist
if os.path.exists('agent_orchestrator.py'):
from agent_orchestrator import AgentOrchestrator
else:
print("agent_orchestrator.py not found")
AgentOrchestrator = None
if os.path.exists('knowledge_engine.py'):
from knowledge_engine import KnowledgeEngine
else:
print("knowledge_engine.py not found")
KnowledgeEngine = None
if os.path.exists('monitoring_system.py'):
from monitoring_system import MonitoringSystem
else:
print("monitoring_system.py not found")
MonitoringSystem = None
if os.path.exists('runtime_environment.py'):
from runtime_environment import RuntimeEnvironment
else:
print("runtime_environment.py not found")
RuntimeEnvironment = None
except ImportError as e:
print(f"Import error details: {e}")
# Create dummy classes for demo mode
class DummyOrchestrator:
def __init__(self):
pass
def initialize_agents(self):
return True
def process_query(self, query, user_profile, selected_agents):
return {
'response': f"This is a demo response to: {query}\n\nIn a full deployment, multiple AI agents would analyze this question and provide comprehensive answers.",
'primary_agent': 'Demo Agent'
}
class DummyKnowledgeEngine:
def __init__(self):
pass
def retrieve_knowledge(self, query):
return {
'results': [
{
'type': 'concept',
'content': {
'name': 'Time Value of Money',
'definition': 'The concept that money available now is worth more than the same amount in the future due to its potential earning capacity.',
'formula': 'FV = PV ร (1 + r)โฟ'
},
'topics': ['Quantitative Methods']
}
]
}
class DummyMonitoring:
def __init__(self):
pass
def get_system_metrics(self):
return {
'active_agents': 6,
'avg_response_time': 1.2,
'success_rate': 0.95,
'total_queries': 0
}
def update_metrics(self):
pass
class DummyRuntime:
def __init__(self):
pass
AgentOrchestrator = DummyOrchestrator
KnowledgeEngine = DummyKnowledgeEngine
MonitoringSystem = DummyMonitoring
RuntimeEnvironment = DummyRuntime
# Page configuration for Hugging Face Spaces
st.set_page_config(
page_title="QuantProdigy AI Agents",
page_icon="๐",
layout="wide",
initial_sidebar_state="expanded"
)
# Initialize session state
def init_session_state():
"""Initialize session state with safe defaults"""
defaults = {
'orchestrator': None,
'knowledge_engine': None,
'monitoring': None,
'runtime': None,
'chat_history': [],
'user_profile': {
'cfa_level': 'I',
'study_focus': ['Quantitative Methods', 'Economics'],
'weak_areas': [],
'learning_style': 'visual',
'experience_level': 'beginner',
'user_id': 'user_' + datetime.now().strftime('%Y%m%d_%H%M%S')
},
'active_agents': {},
'system_ready': False,
'demo_mode': True # Added for Hugging Face Spaces
}
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
# Initialize components safely
if st.session_state.orchestrator is None:
try:
st.session_state.orchestrator = AgentOrchestrator()
except:
st.session_state.orchestrator = AgentOrchestrator() if callable(AgentOrchestrator) else None
if st.session_state.knowledge_engine is None:
try:
st.session_state.knowledge_engine = KnowledgeEngine()
except:
st.session_state.knowledge_engine = KnowledgeEngine() if callable(KnowledgeEngine) else None
if st.session_state.monitoring is None:
try:
st.session_state.monitoring = MonitoringSystem()
except:
st.session_state.monitoring = MonitoringSystem() if callable(MonitoringSystem) else None
if st.session_state.runtime is None:
try:
st.session_state.runtime = RuntimeEnvironment()
except:
st.session_state.runtime = RuntimeEnvironment() if callable(RuntimeEnvironment) else None
# Initialize session state
init_session_state()
# Custom CSS for Hugging Face Spaces
st.markdown("""
<style>
/* Main styling */
.main-header {
font-size: 2.5rem;
color: #1E3A8A;
text-align: center;
margin-bottom: 1rem;
padding: 1rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Card styling */
.agent-card {
background: white;
padding: 1.5rem;
border-radius: 15px;
margin: 10px 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
border-left: 5px solid #667eea;
transition: transform 0.3s ease;
}
/* Message styling */
.message-user {
background-color: #E3F2FD;
padding: 15px;
border-radius: 15px 15px 15px 5px;
margin: 10px 0;
text-align: right;
max-width: 80%;
margin-left: auto;
border: 1px solid #BBDEFB;
}
.message-agent {
background-color: #F3E5F5;
padding: 15px;
border-radius: 15px 15px 5px 15px;
margin: 10px 0;
max-width: 80%;
border: 1px solid #E1BEE7;
}
/* Button styling */
.stButton button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 0.5rem 2rem;
border-radius: 25px;
font-weight: bold;
transition: all 0.3s ease;
}
.stButton button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
/* Demo banner */
.demo-banner {
background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
color: white;
padding: 10px;
border-radius: 10px;
text-align: center;
margin-bottom: 20px;
}
</style>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.title("๐ QuantProdigy")
# Demo mode indicator
if st.session_state.demo_mode:
st.markdown('<div class="demo-banner">DEMO MODE</div>', unsafe_allow_html=True)
st.markdown("### Free CFA Learning Platform")
st.markdown("---")
# System Status
st.subheader("๐ฅ๏ธ System Status")
if st.session_state.system_ready:
st.success("โ
System Ready")
else:
if st.button("Initialize System", type="primary", use_container_width=True):
try:
with st.spinner("Initializing AI Agents..."):
if st.session_state.orchestrator:
st.session_state.orchestrator.initialize_agents()
st.session_state.system_ready = True
st.success("System initialized successfully!")
st.rerun()
except Exception as e:
st.error(f"Initialization failed: {e}")
# User profile
st.subheader("๐ค Your Profile")
with st.expander("Edit Profile", expanded=True):
cfa_level = st.selectbox(
"CFA Level",
["I", "II", "III"],
index=0
)
learning_focus = st.multiselect(
"Learning Focus",
["Quantitative Methods", "Economics", "Financial Reporting",
"Corporate Finance", "Equity", "Fixed Income", "Derivatives",
"Alternative Investments", "Portfolio Management", "Ethics"],
default=["Quantitative Methods", "Economics"]
)
learning_style = st.selectbox(
"Learning Style",
["Visual", "Auditory", "Reading/Writing", "Kinesthetic"],
index=0
)
experience_level = st.selectbox(
"Experience Level",
["Beginner", "Intermediate", "Advanced"],
index=0
)
# Update user profile
st.session_state.user_profile.update({
'cfa_level': cfa_level,
'study_focus': learning_focus,
'learning_style': learning_style.lower(),
'experience_level': experience_level.lower()
})
# Quick actions
st.subheader("โก Quick Actions")
quick_topics = ["Time Value of Money", "Statistics", "Portfolio Theory", "Ethics"]
for topic in quick_topics:
if st.button(f"Learn: {topic}", use_container_width=True):
st.session_state.chat_history.append({
'role': 'user',
'content': f"Teach me about {topic}",
'timestamp': datetime.now().isoformat()
})
st.rerun()
# Main content
if not st.session_state.system_ready:
# Welcome screen
st.markdown('<h1 class="main-header">Welcome to QuantProdigy AI Agents</h1>', unsafe_allow_html=True)
col1, col2 = st.columns([2, 1])
with col1:
st.markdown("""
## ๐ Free CFA Learning Platform
**QuantProdigy** is an intelligent multi-agent system designed to help you master
CFA concepts using AI-powered assistance - completely free!
### โจ Features:
- **๐ค 6 Specialized AI Agents** working together
- **๐ Comprehensive CFA Knowledge Base**
- **๐งฎ Built-in Financial Calculators**
- **๐ Progress Tracking & Analytics**
- **๐ฌ Interactive Learning Sessions**
""")
if st.session_state.demo_mode:
st.info("""
โ ๏ธ **Demo Mode Active**
This is a lightweight demo version for Hugging Face Spaces.
Full features require local deployment with additional AI models.
""")
with col2:
st.markdown("""
### ๐ Get Started
Click the button below to initialize the AI agents and start learning:
""")
if st.button("๐ Initialize & Start Learning", type="primary", use_container_width=True):
try:
with st.spinner("๐ค Loading AI Agents..."):
# Initialize all components
if st.session_state.orchestrator:
st.session_state.orchestrator.initialize_agents()
st.session_state.system_ready = True
st.success("โ
System Ready!")
st.rerun()
except Exception as e:
st.error(f"Initialization failed: {e}")
# Feature showcase
st.markdown("---")
st.subheader("๐ฏ Featured Learning Agents")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="agent-card">
<h4>๐ง Diagnostician</h4>
<p>Analyzes your learning gaps and identifies weak areas</p>
<small>Ready to use</small>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="agent-card">
<h4>๐จโ๐ซ Socratic Tutor</h4>
<p>Guides you through questions to build understanding</p>
<small>Ready to use</small>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="agent-card">
<h4>๐งฎ Calculator</h4>
<p>Performs complex financial calculations instantly</p>
<small>Ready to use</small>
</div>
""", unsafe_allow_html=True)
st.stop()
# Main application (system is ready)
st.markdown('<h1 class="main-header">QuantProdigy AI Learning Agents</h1>', unsafe_allow_html=True)
if st.session_state.demo_mode:
st.info("""
๐ก **Demo Mode**: This version runs with simplified AI agents.
For full functionality with local LLMs, download and run locally.
""")
# Tab layout
tab1, tab2, tab3, tab4, tab5 = st.tabs([
"๐ Learning Session",
"๐ค Agent Dashboard",
"๐ Knowledge Base",
"๐ Progress Analytics",
"๐ ๏ธ Tools & Calculators"
])
# Tab 1: Learning Session
with tab1:
st.header("Interactive Learning Session")
# Chat interface
col1, col2 = st.columns([3, 1])
with col1:
user_input = st.text_area(
"Type your question here:",
height=100,
placeholder="E.g., 'Explain the concept of beta in finance' or 'Help me calculate portfolio variance...'"
)
with col2:
if st.button("Ask AI Agents", type="primary", use_container_width=True):
if user_input.strip():
# Add user message to history
st.session_state.chat_history.append({
'role': 'user',
'content': user_input,
'timestamp': datetime.now().isoformat()
})
# Process with orchestrator
if st.session_state.orchestrator:
with st.spinner("๐ค AI agents are analyzing your question..."):
try:
response = st.session_state.orchestrator.process_query(
query=user_input,
user_profile=st.session_state.user_profile,
selected_agents=["Diagnostician", "Knowledge Expert"]
)
# Add agent response to history
st.session_state.chat_history.append({
'role': 'agent',
'content': response['response'],
'agent': response.get('primary_agent', 'Orchestrator'),
'timestamp': datetime.now().isoformat()
})
st.rerun()
except Exception as e:
st.error(f"Error processing query: {e}")
# Add fallback response
st.session_state.chat_history.append({
'role': 'agent',
'content': f"""I'll help you with: "{user_input}"
**Time Value of Money Example:**
If you invest $1,000 at 5% annual interest for 5 years:
- Future Value = $1,000 ร (1 + 0.05)โต = $1,276.28
**Key Concept:** Money today is worth more than the same amount in the future due to earning potential.""",
'agent': 'Demo Agent',
'timestamp': datetime.now().isoformat()
})
st.rerun()
else:
# Demo response
st.session_state.chat_history.append({
'role': 'agent',
'content': f"""Thanks for your question about "{user_input}"!
**In a full deployment**, multiple AI agents would:
1. Analyze your learning level and style
2. Retrieve relevant CFA knowledge
3. Provide step-by-step explanations
4. Generate practice problems
5. Track your progress
**For now, here's a helpful insight:**
In finance, understanding core concepts like risk-return tradeoff, time value of money, and diversification is fundamental to mastering CFA material.""",
'agent': 'Demo Agent',
'timestamp': datetime.now().isoformat()
})
st.rerun()
# Display chat history
st.subheader("๐ Conversation History")
if not st.session_state.chat_history:
st.info("๐ Start by asking a question above!")
else:
for message in st.session_state.chat_history[-10:]:
if message['role'] == 'user':
st.markdown(f"""
<div class="message-user">
<strong>You:</strong> {message['content']}
<br><small>{message.get('timestamp', '')[:16]}</small>
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div class="message-agent">
<strong>{message.get('agent', 'AI Agent')}:</strong><br>
{message['content']}
<br><small>{message.get('timestamp', '')[:16]}</small>
</div>
""", unsafe_allow_html=True)
# Tab 2: Agent Dashboard
with tab2:
st.header("Agent Dashboard")
# Agent status grid
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="agent-card">
<h4>๐ง Diagnostician</h4>
<p>Analyzes learning gaps and problems</p>
<small>Active in Demo</small>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="agent-card">
<h4>๐จโ๐ซ Socratic Tutor</h4>
<p>Guides through questions and reasoning</p>
<small>Active in Demo</small>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="agent-card">
<h4>๐งฎ Calculator</h4>
<p>Performs complex calculations</p>
<small>Active in Demo</small>
</div>
""", unsafe_allow_html=True)
# Tab 3: Knowledge Base
with tab3:
st.header("CFA Knowledge Base")
# Sample knowledge
st.subheader("๐ Sample CFA Concepts")
concepts = [
{
"name": "Time Value of Money",
"definition": "Money available now is worth more than the same amount in the future due to its potential earning capacity.",
"formula": "FV = PV ร (1 + r)โฟ"
},
{
"name": "Sharpe Ratio",
"definition": "Measures risk-adjusted return of an investment portfolio.",
"formula": "Sharpe Ratio = (Rp - Rf) / ฯp"
},
{
"name": "Beta Coefficient",
"definition": "Measures the volatility of an investment relative to the market.",
"formula": "ฮฒ = Cov(Ri, Rm) / Var(Rm)"
}
]
for concept in concepts:
with st.expander(f"๐ {concept['name']}"):
st.markdown(f"**Definition:** {concept['definition']}")
st.markdown(f"**Formula:** `{concept['formula']}`")
if st.button(f"Learn more about {concept['name']}", key=f"learn_{concept['name']}"):
st.session_state.chat_history.append({
'role': 'user',
'content': f"Explain {concept['name']} in detail",
'timestamp': datetime.now().isoformat()
})
st.rerun()
# Tab 4: Progress Analytics
with tab4:
st.header("Learning Progress Analytics")
# Sample progress chart
st.subheader("๐ Sample Progress Data")
fig = go.Figure(data=[
go.Bar(name='Topics Studied', x=['Week 1', 'Week 2', 'Week 3'], y=[3, 5, 8]),
go.Bar(name='Practice Problems', x=['Week 1', 'Week 2', 'Week 3'], y=[5, 12, 20])
])
fig.update_layout(barmode='group', title='Learning Progress Over Time')
st.plotly_chart(fig, use_container_width=True)
# Tab 5: Tools & Calculators
with tab5:
st.header("๐ ๏ธ Financial Calculators")
# Simple TVM Calculator
st.subheader("๐ฐ Time Value of Money Calculator")
col1, col2 = st.columns(2)
with col1:
pv = st.number_input("Present Value ($)", value=1000.0, min_value=0.0, step=100.0)
rate = st.number_input("Annual Rate (%)", value=5.0, min_value=0.0, max_value=100.0, step=0.5)
periods = st.number_input("Periods (years)", value=5, min_value=1, max_value=100, step=1)
with col2:
if st.button("Calculate Future Value", type="primary", use_container_width=True):
fv = pv * (1 + rate/100) ** periods
st.success(f"**Future Value:** ${fv:,.2f}")
st.info(f"${pv:,.2f} at {rate}% for {periods} years grows to ${fv:,.2f}")
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; padding: 20px;">
<p><strong>QuantProdigy AI Agents</strong> โข Free CFA Learning Platform</p>
<small>Demo Version for Hugging Face Spaces โข For full features, run locally</small>
</div>
""", unsafe_allow_html=True)
|