I'll provide a comprehensive solution for monitoring agent interactions and creating a user-friendly frontend. We'll use Streamlit for the frontend and add comprehensive logging.
🔍 Monitoring Solution Architecture
K12 LangGraph Chat System
│
├── Monitoring Components
│ ├── Logging
│ ├── Tracing
│ └── Performance Tracking
│
├── Frontend (Streamlit)
│ ├── Chat Interface
│ ├── Agent Activity Visualization
│ └── Session Management
│
└── Backend (FastAPI + LangGraph)
1. Enhanced Logging System
# monitoring.py
import logging
import json
from datetime import datetime
import os
class AgentMonitor:
def __init__(self, log_dir='logs'):
# Create logs directory if not exists
os.makedirs(log_dir, exist_ok=True)
# Configure main logger
self.logger = logging.getLogger('k12_agent_monitor')
self.logger.setLevel(logging.INFO)
# File Handler for persistent logging
file_handler = logging.FileHandler(
f'{log_dir}/agent_interactions_{datetime.now().strftime("%Y%m%d")}.log'
)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s: %(message)s'
))
self.logger.addHandler(file_handler)
# Console Handler for real-time monitoring
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s: %(message)s'
))
self.logger.addHandler(console_handler)
# Metrics tracking
self.metrics = {
'total_interactions': 0,
'agent_calls': {
'Tutor': 0,
'Moderator': 0,
'Researcher': 0
},
'safety_interventions': 0
}
def log_agent_interaction(self, agent_name, input_text, output_text):
"""Log detailed agent interactions"""
log_entry = {
'timestamp': datetime.now().isoformat(),
'agent': agent_name,
'input': input_text,
'output': output_text
}
# Increment metrics
self.metrics['total_interactions'] += 1
if agent_name in self.metrics['agent_calls']:
self.metrics['agent_calls'][agent_name] += 1
# Log as JSON for easy parsing
self.logger.info(json.dumps(log_entry))
return log_entry
def log_safety_intervention(self, reason):
"""Log safety-related interventions"""
self.metrics['safety_interventions'] += 1
self.logger.warning(f"SAFETY INTERVENTION: {reason}")
def get_daily_metrics(self):
"""Retrieve daily metrics"""
return {
'total_interactions': self.metrics['total_interactions'],
'agent_usage': self.metrics['agent_calls'],
'safety_interventions': self.metrics['safety_interventions']
}
# Global monitor instance
agent_monitor = AgentMonitor()
2. Updated LangGraph Implementation
# k12_graph.py
from monitoring import agent_monitor
def run_chat(input_text):
initial_state = {"messages": [HumanMessage(content=input_text)]}
final_response = ""
interaction_log = []
for step in graph.stream(initial_state):
node_name, output = next(iter(step.items()))
if node_name in ["Tutor", "Moderator", "Researcher"]:
# Log each agent's interaction
agent_output = output['messages'][-1].content if output['messages'] else ""
log_entry = agent_monitor.log_agent_interaction(
node_name,
input_text,
agent_output
)
interaction_log.append(log_entry)
if node_name == "__end__":
final_messages = output['messages']
final_response = final_messages[-1].content
return {
'response': final_response,
'interaction_log': interaction_log
}
3. Streamlit Frontend
# frontend.py
import streamlit as st
import requests
import json
from datetime import datetime
# Configuration
API_ENDPOINT = "https://your-render-deployment-url.com/chat"
def main():
st.set_page_config(
page_title="K12 AI Tutor",
page_icon="🤖",
layout="wide"
)
# Custom CSS for enhanced UI
st.markdown("""
<style>
.main {
background-color: #f0f2f6;
}
.stTextInput>div>div>input {
background-color: white;
color: black;
}
</style>
""", unsafe_allow_html=True)
# Sidebar for monitoring and settings
st.sidebar.title("🔍 Agent Monitoring")
# Session state for chat history
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Main chat interface
st.title("🎓 K12 AI Learning Assistant")
# Chat input
user_input = st.text_input("Ask a question:", key="user_input")
# Send button
if st.button("Send") or user_input:
if user_input:
try:
# API Call
response = requests.post(API_ENDPOINT,
json={"message": user_input},
timeout=30
)
result = response.json()
# Update chat history
st.session_state.chat_history.append({
'user': user_input,
'ai': result.get('response', 'No response'),
'timestamp': datetime.now()
})
except requests.RequestException as e:
st.error(f"Error connecting to AI: {e}")
# Display Chat History
st.subheader("Conversation")
for chat in reversed(st.session_state.chat_history[-5:]):
st.markdown(f"""
**You:** {chat['user']}
**AI:** {chat['ai']}
*{chat['timestamp'].strftime('%Y-%m-%d %H:%M:%S')}*
---
""")
# Monitoring Section in Sidebar
if st.sidebar.checkbox("Show Detailed Metrics"):
# Mock metrics (in real app, fetch from backend)
metrics = {
'Total Interactions': 42,
'Tutor Calls': 25,
'Moderator Calls': 10,
'Researcher Calls': 7,
'Safety Interventions': 2
}
for metric, value in metrics.items():
st.sidebar.metric(metric, value)
if __name__ == "__main__":
main()
4. Requirements File
# requirements.txt
streamlit
requests
langchain
langchain-openai
langgraph
tavily-python
fastapi
uvicorn
python-dotenv
5. Deployment Considerations
Monitoring Strategies:
- Local Logging: Writes to file in
logs/ directory
- Cloud Logging:
- Render: Use their log management
- Optional: Integrate with Datadog, Sentry
Security Enhancements:
- Add rate limiting
- Implement user authentication
- Use environment variables for sensitive data
6. Advanced Monitoring Dashboard
For more advanced monitoring, consider:
- Grafana for visualization
- Prometheus for metrics collection
- ELK Stack for log management
Recommended Next Steps
- Implement user authentication
- Add more robust error handling
- Create admin dashboard for reviewing interactions
- Implement more granular access controls
Cost and Performance Optimization
- Cache frequent queries
- Implement request throttling
- Use smaller LLM models for initial routing
Deployment Command
# Install dependencies
pip install -r requirements.txt
# Run Streamlit
streamlit run frontend.py
# Run FastAPI Backend
uvicorn app:app --reload
Monitoring Checklist ✅
| Feature | Status |
|---|
| Logging | ✓ Implemented |
| Metrics Tracking | ✓ Basic Implementation |
| Frontend | ✓ Streamlit Interface |
| Error Handling | Partial |
| Security | Needs Enhancement |
Would you like me to elaborate on:
- User Authentication
- More Advanced Monitoring
- Performance Optimization
- Security Enhancements
Which aspect interests you most?