# Project export: Virtual Teaching Assistant

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 12.0
- Tagline: An intelligent multi-agent system that provides personalized assistance to students through Google Classroom integration.
- Devpost: https://devpost.com/software/virtual-teaching-assistant
- GitHub: https://github.com/PesseJinkman/VirtualTA
- Video: https://www.youtube.com/embed/FkZFqVJW2SI?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 2 GitHub contributor(s) — spshah1701 (8 commits), Param Shah (6 commits)

## Devpost submission (written by the team)

### Overview

🎯 Overview ClassMind is an intelligent multi-agent AI system that revolutionizes how students interact with their educational content. By seamlessly integrating with Google Classroom, ClassMind provides 24/7 personalized assistance, helping students navigate coursework, understand assignments, access materials, and stay on top of deadlines—all through a natural, conversational interface. Built with cutting-edge technologies including LangGraph, FastAPI, Next.js, and Claude AI, ClassMind transforms the traditional teaching assistant experience into an always-available, context-aware digital companion that understands each student's unique academic journey. 🚨 Problem Statement The Challenge Students today face overwhelming academic pressures: Information Overload: Multiple courses, dozens of assignments, countless announcements scattered across platforms Limited Support: Teaching assistants have office hours constraints and can't provide 24/7 support Fragmented Systems: Students must manually navigate between course materials, announcements, submissions, and deadlines Repetitive Questions: TAs spend significant time answering the same logistical questions repeatedly Real-World Impact 73% of students report feeling overwhelmed by coursework management (Source: Academic surveys) Office hours utilization drops significantly for students in different time zones Common questions about deadlines, materials, and logistics consume 30-40% of TA time Students often miss important announcements buried in notification overflow What Students Need An intelligent assistant that: Understands their specific courses and context Provides instant, accurate answers about assignments and deadlines Retrieves relevant course materials automatically Works 24/7 across all time zones Learns from actual course data, not generic responses ✨ Key Features 🤖 Multi-Agent AI Architecture ClassMind uses a sophisticated LangGraph workflow with specialized agents: Router Agent: Intelligently classifies student queries and identifies relevant courses Logistics Agent: Handles course schedules, announcements, and organizational questions Coursework Agent: Provides detailed information about assignments, due dates, and requirements Materials Agent: Retrieves and explains course materials, PDFs, links, and resources Submissions Agent: Tracks submission status and grades (for staff) Composer Agent: Synthesizes responses with proper formatting and citations Guard Agent: Ensures response quality and policy compliance 📚 Seamless Google Classroom Integration Real-time data access to courses, assignments, announcements, and materials OAuth 2.0 authentication with automatic token refresh Direct API integration - no screen scraping or workarounds Comprehensive scope coverage for full Classroom functionality 💬 Real-Time Streaming Chat Interface Beautiful, responsive UI built with Next.js 14 and Tailwind CSS Modern chat experience with message history and context awareness Typing indicators and streaming text for better UX 🔐 Role-Based Access Control Student Role: Access to enrolled courses, assignments, and personal data TA Role: Additional access to student submissions and grading Professor Role: Full course management and analytics capabilities Secure database (Prisma ORM) for user management and token storage 📊 Context-Aware Responses Course-specific answers based on actual Classroom data Fallback handling for ambiguous or unclear queries Guardrail ensures responses comply with user permissions and Classroom API access scopes 💡 Why This Matters? For Students Save 5-10 hours per week on administrative tasks and information hunting Never miss deadlines with instant access to due date information Reduce academic stress through 24/7 support availability Get immediate answers without waiting for office hours Focus on learning instead of navigating platforms For Teaching Assistants Reduce repetitive question load by 60-70% Focus on complex, high-value student interactions Scale support without increasing TA hours Track common student questions for curriculum improvement Provide consistent answers across all students For Educational Institutions Improve student success rates through better support Enhance learning experience with modern technology Reduce support costs while increasing availability Demonstrate innovation in educational technology Support hybrid and remote learning effectively Broader Impact ClassMind represents a shift toward democratizing educational support. By making intelligent assistance available to all students regardless of time zone, language barriers, or TA availability, we're creating more equitable learning opportunities. This technology can be scaled across institutions, potentially helping millions of students worldwide. 🛠️ Tech Stack Frontend (Web Application) Framework & Core: Next.js 14 - React framework with App Router for modern server/client rendering React 18 - Component-based UI library TypeScript - Type-safe JavaScript for reliability Authentication & Database: NextAuth.js v5 - Complete OAuth 2.0 authentication with Google Prisma ORM - Type-safe database client and schema management SQLite - Database for user data and token storage UI & Styling: Tailwind CSS - Utility-first CSS framework shadcn/ui - High-quality React component library Lucide React - Modern icon library clsx & tailwind-merge - Dynamic styling utilities API Integration: Fetch API - RESTful communication with backend Google Classroom API - Direct course data access Backend (Agent Service) Framework & Core: FastAPI - High-performance Python web framework with async support Uvicorn - Lightning-fast ASGI server Pydantic - Data validation and settings management AI & LLM Stack: LangGraph - Multi-agent workflow orchestration and state management LangChain - LLM application framework with tool integration Anthropic Claude - Primary language model for agent reasoning OpenAI GPT-4 - Alternative LLM support Google Integration: google-api-python-client - Official Google API client google-auth - OAuth 2.0 authentication library google-auth-oauthlib - OAuth flow management google-auth-httplib2 - HTTP request authorization Utilities: PyPDF2 - PDF text extraction for materials analysis python-dotenv - Environment variable management Architecture & Design Patterns Backend Architecture: Multi-agent system with specialized agents for different query types State machine pattern via LangGraph for workflow orchestration Tool-based architecture for modular functionality Dependency injection for tool context management Frontend Architecture: Server components for initial rendering and data fetching Client components for interactive UI elements API route handlers for secure backend communication Middleware for authentication and authorization Integration Patterns: Event-driven streaming for real-time responses Token refresh middleware for seamless authentication CORS configuration for cross-origin requests Error boundaries for graceful failure handling Development & DevOps Package Management: npm - Frontend dependency management pip - Python package management Virtual environments for isolated Python dependencies Database Management: Prisma Migrate - Schema versioning and migrations Prisma Studio - Database GUI for development Code Quality: ESLint - JavaScript/TypeScript linting TypeScript Compiler - Static type checking Python type hints - Static typing for Python code 🚧 Limitations and Future Work HIGH PRIORITY 🔴 1. Vector Database for Course Materials Current Limitation: Materials are fetched on-demand but not indexed for semantic search. Proposed Solution: Implement Pinecone or Weaviate vector database Extract and embed text from PDFs, slides, and documents Enable semantic search: "Find information about neural networks in week 5 materials" Benefits: Much more intelligent material retrieval, better context for answers Impact: Would transform ClassMind from retrieval-based to true knowledge-based assistant. 2. Assignment Submission Tracking Current Limitation: Students can't track their submission history or get reminders. Proposed Solution: Implement classroom.student-submissions.me.readonly scope usage Track submitted vs. unsubmitted assignments Proactive notifications: "You have 2 assignments due this week" Integration with calendar apps for deadline reminders Impact: Reduces missed deadlines significantly based on similar systems. 3. Multi-Language Support Current Limitation: English-only interface and responses. Proposed Solution: Language detection in router agent Multilingual prompts for Claude AI Support for Spanish, Mandarin, Hindi, Arabic (top educational languages) Impact: Makes ClassMind accessible to international students and global institutions. 4. Production Database Migration Current Limitation: Using SQLite (development database). Proposed Solution: - Migrate to PostgreSQL for production MEDIUM PRIORITY 🟡 5. Conversation History & Context Memory Current Limitation: Each query is independent - no memory of previous conversation turns within a session. Proposed Solution: Implement Redis-based session storage Store last 5-10 conversation turns Update LangGraph state to include conversation history Enable follow-up questions: "What else do I need to know?" after previous query Impact: More natural conversations, better context understanding. 6. Analytics Dashboard for Instructors Current Limitation: No insights into common student questions or knowledge gaps. Proposed Solution: Build analytics dashboard showing: Most common questions by course Topics students struggle with Peak usage times Query categories distribution Most common questions by course Topics students struggle with Peak usage times Query categories distribution Help instructors identify areas needing clarification Impact: Instructors can proactively improve course materials and announcements. 7. File Type Expansion Current Limitation: Limited support for specialized file formats (Jupyter notebooks, code files). Proposed Solution: Add syntax highlighting for code files Render Jupyter notebooks inline Support for SCORM/LTI learning packages Interactive preview for common file types Impact: Better support for CS and technical courses. 8. Peer Collaboration Features Current Limitation: Individual-only experience. Proposed Solution: Anonymous Q&A board where students can help each other ClassMind moderates and suggests answers from knowledge base Upvoting/downvoting system for answer quality Gamification elements (reputation points) Impact: Builds learning community, reduces load on system. LOW PRIORITY 🟢 9. Voice Interface Current Limitation: Text-only interaction. Proposed Solution: Integrate speech-to-text models Add text-to-speech for responses Voice commands: "ClassMind, what's my next assignment?" Impact: Accessibility improvement, hands-free operation. 10. Professor Workload Insights Current Limitation: TAs/Professors can't see their time savings. Proposed Solution: Calculate estimated time saved per TA Show question deflection rate ROI dashboard for institutional adoption Impact: Business case for wider adoption. 11. Integration with LMS Beyond Google Classroom Current Limitation: Google Classroom only. Proposed Solution: Canvas LMS integration Blackboard Learn integration Moodle support Universal LTI (Learning Tools Interoperability) connector Impact: Broader market reach and institutional adoption. 14. Advanced Guard Agent with Content Filtering Current Limitation: Basic guard agent doesn't filter harmful content comprehensively. Proposed Solution: Implement Moderation for content safety Academic integrity checking Plagiarism detection warnings Cheating prevention (don't provide direct answers to graded work) Impact: Maintains academic integrity, builds trust with institutions. Performance Optimizations ⚡ Future Performance Improvements: Caching Layer: Redis for frequently accessed course data (reduce API calls by 60%) Rate Limiting: Implement request throttling per user Load Balancing: Horizontal scaling for agent service Edge Functions: Deploy frontend to Vercel Edge for global latency reduction GraphQL API: Replace REST endpoints for more efficient data fetching Streaming Optimization: Compress SSE payloads, implement backpressure handling 🏗️ Built With AI & Machine Learning LangGraph - Multi-agent orchestration LangChain - LLM framework and tools Anthropic Claude - Primary AI model Backend FastAPI - Python web framework Uvicorn - ASGI server Pydantic - Data validation Google Classroom API - Course data integration Frontend Next.js 14 - React framework NextAuth.js - Authentication Prisma ORM - Database management Tailwind CSS - Styling TypeScript - Type safety Infrastructure Google OAuth 2.0 - Identity provider SQLite/PostgreSQL - Data persistence Server-Sent Events - Real-time streaming 🎬 Summary ClassMind represents more than just a chatbot—it's a fundamental rethinking of how students interact with educational technology. By combining state-of-the-art AI with practical integration into existing systems, we've created a solution that's both powerful and accessible. In a world where education is increasingly digital and distributed, ClassMind ensures that every student has access to immediate, intelligent support regardless of time zone, language, or resource constraints. We're not replacing teachers; we're amplifying their impact and giving them back time to focus on what matters most: meaningful human connections and deep learning experiences. The future of education is AI-augmented, and ClassMind is leading the way. 🚀

## README (from the GitHub repository)

# Virtual TA - AI-Powered Teaching Assistant

An intelligent multi-agent system that provides personalized assistance to students through Google Classroom integration.

## Overview

Virtual TA combines a modern Next.js frontend with a powerful LangGraph-based backend to deliver real-time, context-aware responses to student queries about courses, assignments, materials, and deadlines.

### Key Features

- 🤖 **Multi-Agent AI System**: Specialized agents handle different query types (logistics, coursework, materials, submissions)
- 📚 **Google Classroom Integration**: Direct access to course data, assignments, and materials
- 💬 **Real-time Streaming**: Server-Sent Events (SSE) for smooth, progressive responses
- 🔐 **Secure Authentication**: OAuth 2.0 with automatic token refresh
- 👥 **Role-Based Access**: Student, TA, and Professor roles with appropriate permissions
- 🎨 **Modern UI**: Beautiful, responsive interface built with Next.js and Tailwind CSS

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      Student Interface                       │
│              (Next.js + React + Tailwind CSS)                │
└───────────────────────────┬─────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                   API Layer (Next.js API)                    │
│            • Authentication & Authorization                  │
│            • Token Management & Refresh                      │
│            • Request Routing                                 │
└───────────────────────────┬─────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│              Agent Service (FastAPI + LangGraph)             │
│                                                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐   │
│  │  Router  │→ │Logistics │  │Coursework│  │Materials │   │
│  │  Agent   │  │  Agent   │  │  Agent   │  │  Agent   │   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘   │
│                       │                                      │
│                       ▼                                      │
│            ┌─────────────────────┐                          │
│            │  Composer + Guard   │                          │
│            └─────────────────────┘                          │
└───────────────────────────┬─────────────────────────────────┘
                            │
                            ▼
                 ┌──────────────────────┐
                 │ Google Classroom API │
                 └──────────────────────┘
```

## Project Structure

```
VirtualTA/
├── web-app/classmind/          # Next.js frontend
│   ├── app/                    # App router pages
│   ├── components/             # React components
│   ├── lib/                    # Utilities & auth
│   └── prisma/                 # Database schema
│
├── agent-service/              # Python backend
│   ├── app/
│   │   ├── agents/            # Specialized AI agents
│   │   ├── api/               # FastAPI routes
│   │   ├── graph/             # LangGraph workflow
│   │   ├── tools/             # Google Classroom tools
│   │   └── classroom/         # API client
│   └── requirements.txt
│
├── QUICKSTART.md              # Quick setup guide
├── INTEGRATION_GUIDE.md       # Detailed integration docs
└── README.md                  # This file
```

## Quick Start

**See [QUICKSTART.md](./QUICKSTART.md) for detailed setup instructions.**

### TL;DR

1. Setup Google OAuth credentials
2. Configure environment variables in both services
3. Start agent service: `cd agent-service && python -m uvicorn app.main:app --reload --port 8080`
4. Start web app: `cd web-app/classmind && npm run dev`
5. Open http://localhost:3000 and login!

## Integration Details

The frontend and backend are fully integrated:

✅ **Seamless Authentication**: Students authenticate once via Google OAuth  
✅ **Automatic Token Management**: Tokens are securely stored and auto-refreshed  
✅ **Streaming Responses**: Real-time AI responses stream to the chat interface  
✅ **Minimal Backend Changes**: Agent service works as-is with no code changes  
✅ **Complete API Integration**: All Google Classroom data accessible to agents  

**See [INTEGRATION_GUIDE.md](./INTEGRATION_GUIDE.md) for comprehensive integration documentation.**

## Technologies Used

### Frontend
- **Next.js 14**: React framework with App Router
- **NextAuth.js**: Authentication with Google OAuth
- **Prisma**: Database ORM (SQLite/PostgreSQL)
- **Tailwind CSS**: Styling
- **shadcn/ui**: UI components
- **TypeScript**: Type safety

### Backend
- **FastAPI**: High-performance Python web framework
- **LangGraph**: Multi-agent workflow orchestration
- **LangChain**: LLM integration and tools
- **OpenAI GPT-4**: Language model
- **Google Classroom API**: Course data access

## Features in Detail

### For Students
- Ask questions about courses, assignments, and materials
- Get personalized responses based on enrolled courses
- Access deadline information and upcoming assignments
- Receive AI-powered assistance 24/7

### For Developers
- Modular agent architecture for easy extension
- Type-safe API contracts
- Comprehensive error handling
- Streaming responses for better UX
- Token refresh automation
- Production-ready deployment structure

## Development

### Frontend Development
```bash
cd web-app/classmind
npm run dev          # Start dev server
npm run build        # Build for production
npx prisma studio    # Open database GUI
```

### Backend Development
```bash
cd agent-service
source venv/bin/activate  # Activate virtual environment
uvicorn app.main:app --reload  # Start with auto-reload
python test_agent.py           # Run tests
```

## Environment Variables

### Required for Web App
- `GOOGLE_CLIENT_ID` - Google OAuth client ID
- `GOOGLE_CLIENT_SECRET` - Google OAuth client secret
- `AUTH_SECRET` - NextAuth secret key
- `DATABASE_URL` - Database connection string
- `AGENT_SERVICE_URL` - Backend service URL

### Required for Agent Service
- `OPENAI_API_KEY` - OpenAI API key
- `GOOGLE_CLIENT_ID` - Google OAuth client ID (same as frontend)
- `GOOGLE_CLIENT_SECRET` - Google OAuth client secret (same as frontend)

See `.env.example` files in each directory for complete configuration.

## Testing

### Test Agent Service
```bash
# Health check
curl http://localhost:8080/

# Test streaming endpoint
curl -X POST http://localhost:8080/v1/stream \
  -H "Content-Type: application/json" \
  -d @test_request.json
```

### Test Frontend
1. Login with Google account
2. Set role as Student
3. Open Virtual TA chat
4. Send test queries
5. Verify streaming responses

## Deployment

### Production Checklist
- [ ] Set secure `AUTH_SECRET`
- [ ] Update `AGENT_SERVICE_URL` to production backend
- [ ] Configure production database (PostgreSQL recommended)
- [ ] Set up CORS with specific origins
- [ ] Enable HTTPS/SSL certificates
- [ ] Configure rate limiting
- [ ] Set up monitoring and logging
- [ ] Update Google OAuth redirect URIs

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test thoroughly
5. Submit a pull request

## License

[Your License Here]

## Support

- **Quick Setup**: See [QUICKSTART.md](./QUICKSTART.md)
- **Integration Details**: See [INTEGRATION_GUIDE.md](./INTEGRATION_GUIDE.md)
- **Issues**: Open an issue on GitHub
- **Questions**: Check documentation or ask in discussions

## Acknowledgments

Built with ❤️ using cutting-edge AI technology to empower students and educators.


## Detected evidence (automated analysis)

Indexed codebase: 88 recognized source files, 228 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- LangChain (technology) — detected in the code
- Next.js (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code

## Codebase structure (from repository index)

### Files (101 of 101)

```
.gitignore
agent-service/.env.example
agent-service/app/__init__.py
agent-service/app/agents/__init__.py
agent-service/app/agents/composer/__init__.py
agent-service/app/agents/composer/node.py
agent-service/app/agents/coursework/__init__.py
agent-service/app/agents/coursework/node.py
agent-service/app/agents/guard/__init__.py
agent-service/app/agents/guard/node.py
agent-service/app/agents/logistics/__init__.py
agent-service/app/agents/logistics/node.py
agent-service/app/agents/materials/__init__.py
agent-service/app/agents/materials/node.py
agent-service/app/agents/router/__init__.py
agent-service/app/agents/router/node.py
agent-service/app/agents/router/schemas.py
agent-service/app/agents/router/tools.py
agent-service/app/agents/submissions/__init__.py
agent-service/app/agents/submissions/node.py
agent-service/app/api/__init__.py
agent-service/app/api/routes/__init__.py
agent-service/app/api/routes/answer.py
agent-service/app/api/routes/auth.py
agent-service/app/api/routes/health.py
agent-service/app/api/routes/stream.py
agent-service/app/api/routes/user.py
agent-service/app/classroom/__init__.py
agent-service/app/classroom/client.py
agent-service/app/classroom/field_masks.py
agent-service/app/classroom/scopes.py
agent-service/app/core/__init__.py
agent-service/app/core/config.py
agent-service/app/core/models.py
agent-service/app/graph/__init__.py
agent-service/app/graph/graph.py
agent-service/app/graph/state.py
agent-service/app/main.py
agent-service/app/tools/__init__.py
agent-service/app/tools/common_tools.py
agent-service/app/tools/gc_announcements.py
agent-service/app/tools/gc_courses.py
agent-service/app/tools/gc_coursework.py
agent-service/app/tools/gc_materials.py
agent-service/app/tools/gc_submissions.py
agent-service/app/tools/gc_topics.py
agent-service/app/tools/pdf_extractor.py
agent-service/PDF_EXTRACTION_README.md
agent-service/README.md
agent-service/requirements.txt
agent-service/SETUP.md
agent-service/test_agent.py
agent-service/test_request.json
agent-service/test_simple.py
agent-service/TESTING.md
INTEGRATION_GUIDE.md
INTEGRATION_SUMMARY.md
QUICKSTART.md
README.md
web-app/classmind/.env.example
web-app/classmind/.eslintrc.json
web-app/classmind/.gitignore
web-app/classmind/app/api/auth/[...nextauth]/route.ts
web-app/classmind/app/api/chat/virtual-ta/route.ts
web-app/classmind/app/api/classroom/data/route.ts
web-app/classmind/app/api/classroom/refresh-token/route.ts
web-app/classmind/app/api/classroom/utils.ts
web-app/classmind/app/api/user/set-role/route.ts
web-app/classmind/app/dashboard/classroom-data.tsx
web-app/classmind/app/dashboard/dashboard-client.tsx
web-app/classmind/app/dashboard/page.tsx
web-app/classmind/app/globals.css
web-app/classmind/app/layout.tsx
web-app/classmind/app/login/page.tsx
web-app/classmind/app/page.tsx
web-app/classmind/app/post-login/page.tsx
web-app/classmind/app/setup-role/client.tsx
web-app/classmind/app/setup-role/page.tsx
web-app/classmind/auth.ts
web-app/classmind/check-scope.mjs
web-app/classmind/CLASSROOM_INTEGRATION.md
web-app/classmind/components/ui/button.tsx
web-app/classmind/components/ui/card.tsx
web-app/classmind/components/virtual-ta-chat.tsx
web-app/classmind/FONT_UPDATE.md
web-app/classmind/lib/auth.ts
web-app/classmind/lib/google-tokens.ts
web-app/classmind/lib/prisma.ts
web-app/classmind/lib/utils.ts
web-app/classmind/middleware.ts
web-app/classmind/next.config.mjs
web-app/classmind/package.json
web-app/classmind/postcss.config.mjs
web-app/classmind/prisma/schema.prisma
web-app/classmind/PROJECT_SUMMARY.md
web-app/classmind/README.md
web-app/classmind/SETUP_INSTRUCTIONS.md
web-app/classmind/tailwind.config.ts
web-app/classmind/tsconfig.json
web-app/classmind/VIRTUAL_TA_GUIDE.md
web-app/README.md
```

### Dependencies

- agent-service/requirements.txt: anthropic, fastapi, google-api-python-client, google-auth, google-auth-httplib2, google-auth-oauthlib, langchain, langchain-anthropic, langchain-community, langchain-core, langgraph, pydantic, pydantic-settings, PyPDF2, python-dotenv, uvicorn
- web-app/classmind/package.json: @auth/prisma-adapter@^2.11.0, @prisma/client@^6.18.0, @types/node@^20, @types/react@^18, @types/react-dom@^18, class-variance-authority@^0.7.1, clsx@^2.1.1, eslint@^8, eslint-config-next@14.2.33, lucide-react@^0.548.0, next@14.2.33, next-auth@^5.0.0-beta.29, postcss@^8, prisma@^6.18.0, react@^18, react-dom@^18, tailwind-merge@^3.3.1, tailwindcss@^3.4.1, typescript@^5

### Recent commits (newest first)

- Merge branch 'main' of https://github.com/PesseJinkman/VirtualTA
- feat: add integration documentation and update gitignore paths
- Add lib folder
- Merge pull request #2 from PesseJinkman/feature/exploration
- Remove files
- chore: finalized clean .gitignore and verified tracking state
- docs: add comprehensive guides for classroom, font, and virtual TA features
- refactor: simplify router implementation and update API configuration
- Merge pull request #1 from PesseJinkman/feature/ui-auth-dashboard
- Create initial auth and dashboard frontend along with DB setup
- refactor: remove redundant agents README file
- Add web app and agents folder
- Add web app and agents folder
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### QUICKSTART.md

```markdown
# Quick Start Guide

Get your Virtual TA up and running in minutes!

## Prerequisites

- Node.js 18+ and npm
- Python 3.9+
- Google OAuth credentials (see [Google Cloud Console](https://console.cloud.google.com))
- OpenAI API key

## Step 1: Clone and Setup Environment

```bash
cd VirtualTA

# Copy environment files
cp web-app/classmind/.env.example web-app/classmind/.env
cp agent-service/.env.example agent-service/.env
```

## Step 2: Configure Environment Variables

### Web App (.env in web-app/classmind/)
```env
DATABASE_URL="file:./dev.db"
AUTH_SECRET="generate-a-random-secret-here"
NEXTAUTH_URL="http://localhost:3000"
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
AGENT_SERVICE_URL="http://localhost:8080"
```

### Agent Service (.env in agent-service/)
```env
OPENAI_API_KEY="sk-..."
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
PORT="8080"
HOST="0.0.0.0"
```

**Important**: Use the same Google OAuth credentials in both services!

## Step 3: Start Agent Service (Terminal 1)

```bash
cd agent-service

# Create and activate virtual environment
python -m venv venv

# Windows
venv\Scripts\activate

# Mac/Linux
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Start server
python -m uvicorn app.main:app --reload --port 8080
```

You should see:
```
INFO:     Uvicorn running on http://0.0.0.0:8080
INFO:     Application startup complete.
```

## Step 4: Start Web App (Terminal 2)

```bash
cd web-app/classmind

# Install dependencies
npm install

# Setup database
npx prisma generate
npx prisma db push

# Start development server
npm run dev
```

You should see:
```
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
```

## Step 5: Use the Virtual TA

1. Open browser: http://localhost:3000
2. Click "Sign in with Google"
3. Select your role (Student, TA, or Professor)
4. Navigate to Dashboard
5. Click the Virtual TA button (purple chat bubble, bottom right)
6. Ask a question!

Example questions:
- "What courses am I enrolled in?"
- "What assignments do I have due this week?"
- "Show me the materials for my CS course"
- "When is the deadline for the project?"

## Testing the Integration

### Quick Health Check

**Test Agent Service**:
```bash
curl http://localhost:8080/
```
Should return: `{"service":"Virtual TA Agent Service","status":"running","version":"1.0.0"}`

**Test Frontend**:
Open http://localhost:3000 - should show login page

### Test End-to-End Flow

1. Login as a student
2. Open Virtual TA chat
3. Send a message
4. Verify streaming response appears word-by-word
5. Check Terminal 1 (agent-service) for processing logs
6. Check Terminal 2 (web-app) for API logs

## Troubleshooting

### Agent Service Won't Start
- ✅ Check Python version: `python --version` (needs 3.9+)
- ✅ Verify virtual environment is activated
- ✅ Check OPENAI_API_KEY is set in .env
- ✅ Look for errors in terminal output

### Web App Won't S
[truncated — 1364 more characters]
```

### INTEGRATION_SUMMARY.md

```markdown
# Integration Summary

## ✅ Integration Complete!

The frontend (web-app) and backend (agent-service) are now fully integrated. Students can use the Virtual TA chat interface, and their queries will be processed by the AI agent with full access to Google Classroom data.

---

## 📋 What Was Done

### 1. **Frontend Changes (web-app/classmind)**

#### New Files Created:
- **`lib/google-tokens.ts`** - Token management utility
  - Retrieves Google OAuth tokens from database
  - Automatically refreshes expired tokens
  - Returns tokens in format required by agent-service

#### Modified Files:
- **`app/api/chat/virtual-ta/route.ts`**
  - ✅ Integrated with agent-service streaming endpoint
  - ✅ Retrieves and passes Google tokens to backend
  - ✅ Validates user role (student only)
  - ✅ Handles SSE streaming from agent-service
  - ✅ Transforms agent events into frontend-compatible format

- **`lib/auth.ts`**
  - ✅ Added all required Google Classroom API scopes
  - ✅ Ensures students get necessary permissions for all agent tools

#### Configuration Files:
- **`.env.example`** - Template for environment variables
  - Added `AGENT_SERVICE_URL` configuration

---

### 2. **Backend Changes (agent-service)**

#### Configuration Files:
- **`.env.example`** - Template for environment variables
  - No code changes needed! ✨
  - Agent service works as-is with the integration

---

### 3. **Documentation Created**

- **`README.md`** (updated) - Project overview and setup
- **`QUICKSTART.md`** - Fast setup guide for developers
- **`INTEGRATION_GUIDE.md`** - Comprehensive integration documentation
- **`INTEGRATION_SUMMARY.md`** - This file

---

### 4. **Other Changes**

- **`.gitignore`** (updated)
  - Fixed to only ignore Python lib directory, not web-app lib

---

## 🎯 Key Integration Features

✅ **Zero Backend Code Changes**: Agent service works without modifications  
✅ **Secure Token Management**: Automatic refresh, secure storage  
✅ **Real-time Streaming**: SSE protocol for smooth chat experience  
✅ **Role-Based Access**: Only students can access Virtual TA  
✅ **Complete Google Classroom Access**: All API scopes configured  
✅ **Error Handling**: Graceful fallbacks and clear error messages  

---

## 🚀 How It Works

```
1. Student opens Virtual TA chat in frontend
2. Student sends a message
3. Frontend API route (/api/chat/virtual-ta):
   - Validates user is a student
   - Retrieves Google tokens from database
   - Refreshes token if expired
4. Frontend calls agent-service streaming endpoint:
   POST /v1/stream with:
   - query: "What assignments are due?"
   - user: {role, email, courseId}
   - googleTokens: {token, refresh_token, client_id, client_secret, scopes}
5. Agent service processes request:
   - Builds Google Classroom client with tokens
   - Routes to appropriate agent (Router → Specialist → Composer → Guard)
   - Uses Google Classroom API tools to fetch data
6. Agent service streams response back:
   - Multiple SSE events (status, thinking, te
[truncated — 4431 more characters]
```

### agent-service/requirements.txt

```
# FastAPI and web server
fastapi
uvicorn
pydantic
pydantic-settings

# LangChain and LangGraph
langchain
langchain-core
langchain-community
langgraph
langchain-anthropic

# Google API
google-api-python-client
google-auth
google-auth-oauthlib
google-auth-httplib2

# Anthropic
anthropic

# Utilities
python-dotenv

# PDF processing
PyPDF2

```

### web-app/classmind/package.json

```
{
  "name": "classmind",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@auth/prisma-adapter": "^2.11.0",
    "@prisma/client": "^6.18.0",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "lucide-react": "^0.548.0",
    "next": "14.2.33",
    "next-auth": "^5.0.0-beta.29",
    "prisma": "^6.18.0",
    "react": "^18",
    "react-dom": "^18",
    "tailwind-merge": "^3.3.1"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "eslint": "^8",
    "eslint-config-next": "14.2.33",
    "postcss": "^8",
    "tailwindcss": "^3.4.1",
    "typescript": "^5"
  }
}

```

### agent-service/app/main.py

```python
"""FastAPI application factory for Virtual TA agent service."""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.routes import health, answer, stream, auth, user

# Create FastAPI app
app = FastAPI(
    title="Virtual TA Agent Service",
    description="Multi-agent system for Google Classroom assistance",
    version="1.0.0"
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure appropriately for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(health.router, tags=["health"])
app.include_router(answer.router, tags=["answer"])
app.include_router(stream.router, tags=["stream"])
app.include_router(auth.router, tags=["auth"])
app.include_router(user.router, tags=["user"])


@app.get("/")
async def root():
    """Root endpoint."""
    return {
        "service": "Virtual TA Agent Service",
        "status": "running",
        "version": "1.0.0"
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8080)

```

### web-app/classmind/app/layout.tsx

```typescript
import type { Metadata } from "next";
import localFont from "next/font/local";
import "./globals.css";

const geistSans = localFont({
  src: "./fonts/GeistVF.woff",
  variable: "--font-geist-sans",
  weight: "100 900",
});
const geistMono = localFont({
  src: "./fonts/GeistMonoVF.woff",
  variable: "--font-geist-mono",
  weight: "100 900",
});

export const metadata: Metadata = {
  title: "ClassMind - Your AI-Powered Academic Assistant",
  description: "Smart learning and seamless organization with AI-powered tutoring, Google Classroom integration, and intelligent scheduling.",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        {children}
      </body>
    </html>
  );
}

```

### web-app/classmind/app/page.tsx

```typescript
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { GraduationCap, Brain, Calendar } from "lucide-react"

export default function Home() {
  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-gray-50">
      {/* Header */}
      <header className="border-b border-gray-200 bg-white/80 backdrop-blur-sm sticky top-0 z-50">
        <div className="container mx-auto px-6 py-4">
          <nav className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <GraduationCap className="h-8 w-8 text-indigo-600" />
              <span className="text-2xl font-bold text-gray-900">ClassMind</span>
            </div>
            <div className="flex items-center gap-6">
              <Link href="/" className="text-gray-700 hover:text-gray-900 font-medium transition-colors">
                Home
              </Link>
              <Link href="#about" className="text-gray-700 hover:text-gray-900 font-medium transition-colors">
                About
              </Link>
              <Link href="/login">
                <Button>Login</Button>
              </Link>
            </div>
          </nav>
        </div>
      </header>

      {/* Hero Section */}
      <main className="container mx-auto px-6 py-20">
        <div className="flex flex-col items-center text-center max-w-4xl mx-auto">
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-indigo-50 text-indigo-700 text-sm font-medium mb-8">
            <Brain className="h-4 w-4" />
            <span>AI-Powered Learning Assistant</span>
          </div>

          <h1 className="text-6xl font-bold text-gray-900 mb-6 leading-tight">
            Your AI Tutor.
            <br />
            <span className="bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
              Smarter Learning,
            </span>
            <br />
            Seamless Organization.
          </h1>

          <p className="text-xl text-gray-600 mb-10 max-w-2xl leading-relaxed">
            ClassMind connects to your Google Classroom, calendar, and email to help you stay ahead in every course.
          </p>

          <div className="flex gap-4 flex-wrap justify-center">
            <Link href="/login">
              <Button size="lg" className="text-lg h-14 px-8">
                Get Started
              </Button>
            </Link>
            <Button size="lg" variant="outline" className="text-lg h-14 px-8">
              Learn More
            </Button>
          </div>

          {/* Features Grid */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mt-24 w-full">
            <div className="flex flex-col items-center text-center p-6 rounded-xl bg-white border border-gray-200 shadow-sm hover:shadow-md transition-shadow">
              <div className="h-12 w-12 rounded-lg bg-indigo-100 flex items-center justify-center mb-4">
                <GraduationCap className="h-6 w-6 text-indigo-600" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">Smart Course Management</h3>
              <p className="text-gray-600 text-sm">
                Automatically sync with Google Classroom to track assignments and deadlines
              </p>
            </div>

            <div className="flex flex-col items-center text-center p-6 rounded-xl bg-white border border-gray-200 shadow-sm hover:shadow-md transition-shadow">
              <div className="h-12 w-12 rounded-lg bg-purple-100 flex items-center justify-center mb-4">
                <Brain className="h-6 w-6 text-purple-600" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">AI-Powered Assistance</h3>
              <p className="text-gray-600 text-sm">
                Get personalized help and insights tailored to your learning style
              </p>
            </div>

            <div className="flex flex-col items-center text-center p-6 rounded-xl bg-white border border-gray-200 shadow-sm hover:shadow-md transition-shadow">
              <div className="h-12 w-12 rounded-lg bg-blue-100 flex items-center justify-center mb-4">
                <Calendar className="h-6 w-6 text-blue-600" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">Integrated Calendar</h3>
              <p className="text-gray-600 text-sm">
                Never miss a deadline with intelligent scheduling and reminders
              </p>
            </div>
          </div>
        </div>

        {/* About Section */}
        <section id="about" className="mt-32 max-w-3xl mx-auto">
          <h2 className="text-4xl font-bold text-gray-900 mb-6 text-center">
            Built for Students, TAs, and Professors
          </h2>
          <p className="text-lg text-gray-600 text-center leading-relaxed">
            Whether you&apos;re managing multiple courses, assisting students, or teaching classes, 
            ClassMind adapts to your needs with role-specific features and intelligent automation.
          </p>
        </section>
      </main>

      {/* Footer */}
      <footer className="border-t border-gray-200 mt-32 py-8 bg-white">
        <div className="container mx-auto px-6 text-center text-gray-600">
          <p>© 2025 ClassMind. All rights reserved.</p>
        </div>
      </footer>
    </div>
  )
}

```

### web-app/classmind/app/setup-role/page.tsx

```typescript
// app/setup-role/page.tsx
export const runtime = "nodejs";

import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import SetupRoleClient from "./client";

export default async function SetupRolePage() {
  const session = await auth();
  if (!session?.user?.email) {
    redirect("/login");
  }

  // If role already set, skip this page
  const user = await prisma.user.findUnique({
    where: { email: session.user.email },
    select: { role: true },
  });

  if (user?.role) {
    redirect("/dashboard");
  }

  // Render the client UI to set role
  return <SetupRoleClient />;
}

```

### web-app/classmind/app/post-login/page.tsx

```typescript
// app/post-login/page.tsx
export const runtime = "nodejs";

import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";

export default async function PostLogin() {
  const session = await auth();

  if (!session?.user?.email) {
    redirect("/login");
  }

  // 🔹 Always fetch the latest role from the database
  const dbUser = await prisma.user.findUnique({
    where: { email: session.user.email },
    select: { role: true },
  });

  // 🔹 Debug log (optional)
  console.log("Post-login DB user role:", dbUser?.role);

  if (!dbUser?.role) {
    redirect("/setup-role");
  }

  // ✅ Role exists → go to dashboard
  redirect("/dashboard");
}

```

### web-app/classmind/app/dashboard/page.tsx

```typescript
// app/dashboard/page.tsx
export const runtime = "nodejs";

import { auth, signOut } from "@/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { GraduationCap, LogOut } from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import ClassroomData from "./classroom-data";
import DashboardClient from "./dashboard-client";

export default async function DashboardPage() {
  const session = await auth();
  if (!session?.user?.email) redirect("/login");

  // ✅ source of truth for role
  const user = await prisma.user.findUnique({
    where: { email: session.user.email },
    select: { role: true, name: true, email: true, image: true },
  });

  if (!user?.role) redirect("/setup-role");

  const userRole = user.role;
  const userName = user.name || "there";

  const getRoleDisplay = (role: string) => {
    switch (role) {
      case "student":
        return "Student";
      case "ta":
        return "Teaching Assistant";
      case "professor":
        return "Professor";
      default:
        return role;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-gray-50">
      {/* Header */}
      <header className="border-b border-gray-200 bg-white/80 backdrop-blur-sm">
        <div className="container mx-auto px-6 py-4">
          <nav className="flex items-center justify-between">
            <Link href="/dashboard" className="flex items-center gap-2">
              <GraduationCap className="h-8 w-8 text-indigo-600" />
              <span className="text-2xl font-bold text-gray-900">ClassMind</span>
            </Link>
            <form
              action={async () => {
                "use server";
                await signOut({ redirectTo: "/" });
              }}
            >
              <Button variant="outline" type="submit">
                <LogOut className="h-4 w-4 mr-2" />
                Logout
              </Button>
            </form>
          </nav>
        </div>
      </header>

      {/* Main Content */}
      <main className="container mx-auto px-6 py-12">
        {/* Welcome Section */}
        <div className="mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-2">
            Welcome back, {userName}! 👋
          </h1>
          <p className="text-lg text-gray-600">
            You&apos;re logged in as a{" "}
            <span className="font-semibold text-indigo-600">
              {getRoleDisplay(userRole)}
            </span>
          </p>
        </div>

        {/* Dynamic Google Classroom Data */}
        <ClassroomData userRole={userRole} />
      </main>

      {/* Virtual TA Chat - Students Only */}
      <DashboardClient
        userRole={userRole}
        userName={userName}
        userEmail={user.email || ""}
      />
    </div>
  );
}

```

[61 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]