This commit is contained in:
2026-05-28 22:44:18 +01:00
13 changed files with 426 additions and 337 deletions

View File

@@ -1,6 +1,8 @@
# Architecture Overview - AI Study Assistant
## 🏗️ COMPLETE SYSTEM ARCHITECTURE
## 🏗️ ACTUAL SYSTEM ARCHITECTURE
> ⚠️ **Nota importante**: Esta documentação reflete a arquitetura REAL implementada no código. O projeto é uma aplicação Flutter que comunica diretamente com Firebase e Ollama, sem backend Node.js ou Python intermediário.
---
@@ -31,46 +33,45 @@ This document provides a comprehensive overview of the AI Study Assistant system
## 🏛️ HIGH-LEVEL ARCHITECTURE
### System Overview
### System Overview (Real Implementation)
```
┌─────────────────────────────────────────────────────────────────┐
│ PRESENTATION LAYER │
├─────────────────┬─────────────────┬─────────────────────────────┤
│ Flutter App │ Web App │ Admin Dashboard
│ (Mobile/Web) │ (PWA) │ (Management)
│ Flutter App │ Web App │ (Same codebase)
│ (Mobile/Web) │ (Flutter Web) │
└─────────────────┴─────────────────┴─────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
API GATEWAY
│ • Authentication • Rate Limiting • Load Balancing │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ SERVICE LAYER │
FLUTTER SERVICES
├─────────────┬─────────────┬─────────────┬───────────────────────┤
│ Auth │ Tutor │ Quiz │ Analytics
│ Auth │ Tutor │ Quiz │ Gamification
│ Service │ Service │ Service │ Service │
├─────────────┼─────────────┼─────────────┼───────────────────────┤
│ RAG │ Chat │ Content │ Vector │
│ Service │ Memory │ Service │ Service (Mock) │
└─────────────┴─────────────┴─────────────┴───────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
AI/ML LAYER
├─────────────┬─────────────┬────────────────────────────────────┤
RAG Embedding │ LLM Vector Store
Engine Service Service │ (FAISS)
└─────────────┴─────────────┴─────────────┴───────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ DATA LAYER │
├─────────────┬─────────────┬─────────────┬───────────────────────┤
│ Firestore │ Storage │ Cache │ Search │
│ Database │ (Files) │ (Redis) │ (Elasticsearch) │
└─────────────┴─────────────┴─────────────┴───────────────────────┘
EXTERNAL SERVICES
├─────────────────────────┬────────────────────────────────────┤
Firebase Ollama LLM
• Auth │ • Model: qwen3-coder:30b
│ • Firestore │ • Endpoint: /api/chat │
│ • Storage │
• Analytics │
│ • Crashlytics │ │
└─────────────────────────┴─────────────────────────────────────┘
```
### Architecture Notes
- **No Backend Server**: The Flutter app communicates directly with Firebase and Ollama
- **RAG Implementation**: Keyword-based search with windowing, implemented in Dart
- **Embeddings**: Mock/simulated embeddings (384 dimensions) using text hashing
- **Vector Store**: Not FAISS - simple in-memory Firestore storage with cosine similarity
---
## 📱 FRONTEND ARCHITECTURE
@@ -187,7 +188,14 @@ class TutorRepositoryImpl implements TutorRepository {
## ⚡ BACKEND ARCHITECTURE
### Cloud Functions Architecture
> ⚠️ **Nota**: Não existe backend Node.js/Cloud Functions. A arquitetura descrita abaixo é para referência futura apenas.
### Actual Backend
The "backend" consists of:
1. **Firebase Services** (managed by Google)
2. **Ollama Instance** (self-hosted at 89.114.196.110:11434)
### Cloud Functions Architecture (NOT IMPLEMENTED)
```
┌─────────────────────────────────────────────────────────────────┐
│ API GATEWAY LAYER │
@@ -198,6 +206,8 @@ class TutorRepositoryImpl implements TutorRepository {
│ • CORS │ • Schema Valid │ • Per-Endpoint Limits │
│ • Logging │ • Sanitization │ • Global Limits │
│ • Error Handl │ • Type Check │ • Burst Protection │
Note: This layer does not exist in the current implementation.
└─────────────────┴─────────────────┴─────────────────────────────┘
@@ -274,32 +284,32 @@ export class TutorService {
---
## 🤖 AI/ML ARCHITECTURE
## 🤖 AI/ML ARCHITECTURE (DART IMPLEMENTATION)
### RAG Engine Architecture
### RAG Engine Architecture (Real Implementation)
```
┌─────────────────────────────────────────────────────────────────┐
│ INPUT PROCESSING
│ INPUT PROCESSING (Dart)
├─────────────────┬─────────────────┬─────────────────────────────┤
│ Text Input │ Content │ Query Processing │
│ Processing │ Processing │ │
│ │ │ │
│ • Tokenization │ • PDF Parsing │ • Query Embedding
│ • Cleaning │ • Text Extract │ • Vector Search │
│ • Normalization │ • Chunking │ • Similarity Calculation
│ • Validation │ • Metadata │ • Ranking
│ • Text Cleaning │ • PDF Parsing │ • Keyword Extraction
│ • LaTeX Filter │ • Text Extract │ • Window Search │
│ • Normalization │ • Chunking │ • Similarity Matching
│ • Validation │ • Cache (Hive) │ • Content Ranking
└─────────────────┴─────────────────┴─────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ VECTOR STORE
│ VECTOR STORE (Mock/Simple)
├─────────────────┬─────────────────┬─────────────────────────────┤
Indexing │ Storage │ Retrieval │
Embeddings │ Storage │ Retrieval │
│ │ │ │
│ • FAISS Index │ • Vector Data │ • Approximate Search
│ • HNSW Tree │ • Metadata │ • Exact Search
│ • IVF Clusters │ • Chunks │ • Hybrid Search
│ • Optimization │ • Updates │ • Filtering
│ • Hash-based │ • Firestore │ • Cosine Similarity
│ • 384 dims │ • contentChunks │ • Keyword Matching
│ • Deterministic │ • materials │ • Window-based Search │
│ • Fast/Cheap │ • No FAISS │ • No Approximate Search
└─────────────────┴─────────────────┴─────────────────────────────┘
@@ -309,107 +319,124 @@ export class TutorService {
│ Prompt │ Generation │ Post-Processing │
│ Engineering │ │ │
│ │ │ │
│ • Context Build │ • OpenAI API │ • Response Validation
│ • Template │ • Anthropic API│ • Safety Checks
│ • Formatting │ • Model Selection│ • Quality Assessment
│ • Safety │ • Rate Limit │ • Caching
│ • Context Embed │ • Ollama API │ • UTF-8 Encoding
│ • User Persona │ • qwen3-coder │ • Response Formatting
│ • PDF Content │ • 30B model │ • Citation Handling
│ • Constraints │ • Direct HTTP │ • Error Handling
└─────────────────┴─────────────────┴─────────────────────────────┘
```
### RAG Pipeline Implementation
```python
# RAG Engine Pipeline
class RAGPipeline:
def __init__(self):
self.embedding_service = EmbeddingService()
self.vector_store = VectorStore()
self.llm_service = LLMService()
self.prompt_builder = PromptBuilder()
### RAG Pipeline Implementation (Dart)
```dart
// Real implementation in lib/core/services/rag_ai_service.dart
class RAGAIService {
static const String _baseUrl = 'http://89.114.196.110:11434/api/chat';
static const String _model = 'qwen3-coder:30b';
async def process_query(self, query: str, mode: str = "EXPLANATION") -> str:
# Step 1: Process input
processed_query = self.preprocess_query(query)
static Future<String> askTutor({
required String question,
required List<String> materialIds,
required String mode,
}) async {
// Step 1: Retrieve context from materials (keyword-based)
final context = await MaterialsRAGService.getContextForQuestion(
question: question,
materialIds: materialIds,
);
# Step 2: Generate embedding
query_embedding = await self.embedding_service.encode([processed_query])
// Step 2: Build prompt with embedded context
final prompt = _buildPrompt(
question: question,
context: context,
mode: mode,
);
# Step 3: Retrieve relevant context
context_chunks = await self.vector_store.search(
query_embedding[0],
k=10,
filters=self.get_filters(mode)
)
// Step 3: Call Ollama API directly
final response = await http.post(
Uri.parse(_baseUrl),
headers: {'Content-Type': 'application/json; charset=utf-8'},
body: utf8.encode(jsonEncode({
'model': _model,
'messages': [
{'role': 'system', 'content': _systemPrompt},
{'role': 'user', 'content': prompt},
],
})),
);
# Step 4: Build prompt
prompt = self.prompt_builder.build(
query=processed_query,
context=context_chunks,
mode=mode
)
// Step 4: Process response
return _processResponse(response);
}
}
# Step 5: Generate response
response = await self.llm_service.generate(prompt)
# Step 6: Post-process
final_response = self.postprocess_response(response, context_chunks)
return final_response
def preprocess_query(self, query: str) -> str:
# Clean and normalize query
query = query.strip().lower()
# Remove special characters
query = re.sub(r'[^\w\s]', '', query)
# Tokenize and normalize
return query
def get_filters(self, mode: str) -> Dict[str, Any]:
# Mode-specific filtering
filters = {}
if mode == "EXPLANATION":
filters["content_type"] = ["explanation", "definition"]
elif mode == "TUTOR":
filters["difficulty"] = {"$lte": 0.7}
return filters
// MaterialsRAGService - keyword window search
class MaterialsRAGService {
static Future<String> getContextForQuestion({
required String question,
required List<String> materialIds,
}) async {
// PDF extraction with syncfusion_flutter_pdf
// Keyword matching with windowing (1200 chars)
// No FAISS, no embeddings, no vector search
}
}
```
### Key Differences from Original Design
-**No Python RAG Engine**: Implemented entirely in Dart
-**No FAISS**: Uses keyword matching and simple cosine similarity
-**No Sentence Transformers**: Hash-based mock embeddings (384 dims)
-**No OpenAI/Anthropic**: Only Ollama (qwen3-coder:30b)
-**PDF Processing**: syncfusion_flutter_pdf for text extraction
-**Caching**: Hive for PDF content caching
-**Firestore**: Stores contentChunks with simple vector data
---
## 🗄️ DATA ARCHITECTURE
### Database Schema
### Database Schema (Actual Implementation)
```
┌─────────────────────────────────────────────────────────────────┐
│ FIRESTORE DATABASE │
├─────────────────┬─────────────────┬─────────────────────────────┤
│ USERS │ CONTENT │ LEARNING
│ USERS │ MATERIALS │ CONTENTCHUNKS
│ │ │ │
│ • uid │ • id │ • studentId
│ • email │ • title │ • concept
│ • role │ • subject │ • mastery
│ • schoolId │ • concept │ • confidence
│ • profile │ • difficulty │ • lastInteraction
│ • preferences │ • grade │ • interactions
• createdAt │ • uploadedAt │ • recommendations
│ • lastActive │ • uploadedBy │ • spacedRepetition │
│ • uid │ • id │ • id
│ • email │ • teacherId │ • text
│ • role │ • fileName │ • subject
│ • schoolId │ • fileUrl │ • concept
│ • displayName │ • type │ • embedding (List<double>)
│ • createdAt │ • createdAt │ • metadata
│ • createdAt
└─────────────────┴─────────────────┴─────────────────────────────┘
┌─────────────────┬─────────────────┬─────────────────────────────┐
│ QUIZ INTERACTIONS SCHOOLS
│ │ │ │
│ • id │ • id │ • id │
│ • title │ • studentId │ • name
│ • subject │ • query │ • email
│ • concept │ • response │ • settings
│ • questions │ • mode │ • subscription
│ • timeLimit │ • timestamp │ • maxStudents
• passingScore │ • feedback │ • maxTeachers
│ • createdBy │ • metadata │ • isActive │
│ • createdAt │ • sources │ • createdAt │
│ QUIZZESCONVERSATIONS │ CLASSES/ENROLLMENTS
│ │ (userChats/*) │ │
│ • id │ │ • id │
│ • teacherId │ • id │ • teacherId/classId
│ • title │ • title │ • name/code
│ • description │ • selectedMaterials│ • studentId
│ • questions │ • createdAt │ • createdAt/joinedAt
│ • createdAt │ • hasUserMessage│
│ • messages/* │
└─────────────────┴─────────────────┴─────────────────────────────┘
```
### Collections NOT Implemented
-`learningStates` - Not in codebase
-`auditLogs` - Not implemented
-`quizAttempts` - Not implemented
-`interactions` - Replaced by userChats/{uid}/conversations
### Roles (Only 2 implemented)
-`student` - Can view content, take quizzes, ask tutor
-`teacher` - Can upload materials, create quizzes, view analytics
-`admin` - NOT IMPLEMENTED
-`super_admin` - NOT IMPLEMENTED
### Data Flow Architecture
```
┌─────────────────────────────────────────────────────────────────┐
@@ -524,88 +551,84 @@ class RAGPipeline:
---
## 🔧 TECHNOLOGY STACK
## 🔧 TECHNOLOGY STACK (ACTUAL)
### Frontend Technologies
```yaml
Flutter Framework:
- SDK: 3.41.0+
- SDK: ^3.11.5 (Dart 3.0+)
- Language: Dart 3.0+
- State Management: Riverpod 2.4.9
- Navigation: GoRouter 12.1.3
- UI: Material Design 3
- Testing: Flutter Test, Integration Test
- Testing: Flutter Test, Integration Test (not implemented)
Firebase Services:
- Authentication: Firebase Auth
- Database: Cloud Firestore
- Storage: Firebase Storage
- Analytics: Firebase Analytics
- Crashlytics: Firebase Crashlytics
- Performance: Firebase Performance
- Authentication: firebase_auth ^4.17.8
- Database: cloud_firestore ^4.15.8
- Storage: firebase_storage ^11.6.9
- Analytics: firebase_analytics ^10.8.0
- Crashlytics: firebase_crashlytics ^3.5.7
- Messaging: firebase_messaging ^14.9.3
- Performance: NOT IMPLEMENTED
- Remote Config: NOT IMPLEMENTED
Third-Party Libraries:
- HTTP: Dio 5.4.0
- Caching: Cached Network Image 3.3.0
- Fonts: Google Fonts 6.1.0
- Animations: Flutter Animate 4.2.0
- Local Storage: Hive 2.2.3
- HTTP: Dio ^5.4.0, http ^1.1.2
- PDF Processing: syncfusion_flutter_pdf ^33.2.6
- Caching: cached_network_image ^3.3.0, hive ^2.2.3
- Fonts: google_fonts ^6.1.0
- Animations: flutter_animate ^4.2.0, lottie ^2.7.0
- Charts: fl_chart ^0.64.0
- File Handling: file_selector ^1.0.3, image_picker ^1.0.4
- Utilities: intl ^0.20.2, uuid ^4.2.1, equatable ^2.0.5
```
### Backend Technologies
### Backend Technologies (NOT IMPLEMENTED)
```yaml
Runtime Environment:
- Platform: Firebase Cloud Functions
- Runtime: Node.js 18.x LTS
- Language: TypeScript 5.0+
- Package Manager: npm 9.x
Status: NO BACKEND SERVER
Core Services:
- Authentication: Firebase Admin SDK
- Database: Firestore Admin SDK
- Storage: Cloud Storage Admin SDK
- HTTP Framework: Express.js 4.18+
- Validation: Joi 17.9+
- Security: Helmet 7.0+
The following technologies are documented but NOT implemented:
❌ Firebase Cloud Functions - Not used
❌ Node.js / TypeScript - Not used
❌ Python RAG Engine - Not used
❌ FAISS Vector Database - Not used
❌ Sentence Transformers - Not used
❌ OpenAI API - Not used
❌ Anthropic Claude - Not used
AI/ML Services:
- Vector Database: FAISS 1.7.4
- Embeddings: Sentence Transformers 2.2.2
- LLM APIs: OpenAI 4.20.1, Anthropic 0.6.3
- Processing: NumPy 1.21+, PyTorch 1.12+
Monitoring & Logging:
- Logging: Winston 3.8+
- Metrics: Prometheus Client
- Tracing: OpenTelemetry
- Error Tracking: Sentry
Actual Implementation:
✅ Flutter app calls Ollama directly via HTTP
✅ Firebase services handle auth, database, storage
✅ RAG logic implemented in Dart (keyword matching)
✅ Embeddings: Mock/hash-based in Dart
```
### Infrastructure Technologies
```yaml
Cloud Platform:
- Provider: Google Cloud Platform
- Services: Firebase, Cloud Functions, Cloud Storage
- Regions: us-central1, europe-west1
- CDN: Firebase Hosting
- Provider: Google Firebase (BaaS)
- Services: Firebase Auth, Firestore, Storage
- Hosting: Firebase Hosting (for web builds)
- Self-hosted: Ollama LLM server (89.114.196.110:11434)
Database:
- Primary: Cloud Firestore
- Cache: Redis (MemoryStore)
- Search: Elasticsearch (if needed)
- Backup: Automated daily backups
- Primary: Cloud Firestore (NoSQL)
- Cache: Hive (local), Memory cache
- Search: Not implemented (no Elasticsearch)
- Backup: Firebase automated backups
Security:
- TLS: 1.3
- Authentication: Firebase Auth
- Authorization: Custom RBAC
- Monitoring: Security Command Center
- TLS: HTTPS for all communications
- Authentication: Firebase Auth (email/password, Google)
- Authorization: Client-side role checks (student/teacher)
- Note: No admin role implemented
CI/CD:
- Pipeline: GitHub Actions
- Build: Cloud Build
- Deploy: Firebase CLI
- Testing: Automated test suites
- Pipeline: Manual builds
- Build: flutter build web/apk
- Deploy: Firebase CLI (manual)
- Testing: No automated tests implemented
```
---

View File

@@ -1,71 +1,47 @@
# Backend MVP Tasks - AI Study Assistant
## 🔧 MVP BACKEND ROADMAP (8-12 WEEKS)
> ⚠️ **IMPORTANTE**: Este documento foi atualizado para refletir a arquitetura REAL do projeto.
>
> **NÃO EXISTE BACKEND NODE.JS/TYPESCRIPT**. O projeto utiliza apenas:
> - Firebase Services (Auth, Firestore, Storage) - BaaS
> - Ollama LLM auto-hospedado
> - Lógica de negócio implementada em Dart no Flutter
---
## 🏗️ WEEK 1-2: FIREBASE FOUNDATION
### Task 1.1: Firebase Project Setup
**Priority**: Critical
**Estimated Time**: 6 hours
**Dependencies**: None
**Status**: ✅ COMPLETED
#### Subtasks:
- [ ] Create Firebase project in Google Cloud Console
- [ ] Enable required Firebase services:
- [ ] Firebase Authentication
- [ ] Cloud Firestore
- [ ] Cloud Storage
- [ ] Cloud Functions
- [ ] Firebase Analytics
- [ ] Configure project settings
- [ ] Set up billing account (if needed)
- [ ] Enable API access for LLM services
- Create Firebase project in Google Cloud Console
- Enable required Firebase services:
- Firebase Authentication
- Cloud Firestore
- Cloud Storage
- Cloud Functions - NOT IMPLEMENTED (not needed)
- Firebase Analytics
- Configure project settings
- ✅ Enable Ollama API access (self-hosted)
#### Detailed Steps:
#### Actual Configuration:
1. **Create Firebase Project**
```bash
# Using Firebase CLI
firebase projects create teachit-ai-assistant
firebase use teachit-ai-assistant
**pubspec.yaml dependencies:**
```yaml
dependencies:
firebase_core: ^2.25.4
firebase_auth: ^4.17.8
cloud_firestore: ^4.15.8
firebase_storage: ^11.6.9
firebase_analytics: ^10.8.0
firebase_crashlytics: ^3.5.7
```
2. **Enable Services**
```bash
# Enable Authentication
firebase auth --enable
# Enable Firestore
firebase firestore:databases:create
# Enable Storage
firebase storage:buckets:create teachit-content
# Enable Functions
firebase functions:config:set
```
3. **Project Configuration**
```json
// firebase.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"storage": {
"rules": "storage.rules"
},
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
],
"source": "functions"
}
}
**Ollama Configuration (in rag_ai_service.dart):**
```dart
static const String _baseUrl = 'http://89.114.196.110:11434/api/chat';
static const String _model = 'qwen3-coder:30b';
```
---

View File

@@ -1,12 +1,16 @@
# Contributing Guidelines - AI Study Assistant
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a arquitetura REAL (Flutter + Firebase apenas).
>
> **Nota:** Não existe backend Node.js nem Python RAG engine. Toda a lógica está no Flutter.
## 🤝 HOW TO CONTRIBUTE
---
## 📋 OVERVIEW
Thank you for your interest in contributing to the AI Study Assistant! This guide provides comprehensive information on how to contribute to our project, including development workflows, coding standards, and community guidelines.
Thank you for your interest in contributing to the AI Study Assistant! This guide provides information on how to contribute to our Flutter + Firebase project.
---
@@ -14,11 +18,10 @@ Thank you for your interest in contributing to the AI Study Assistant! This guid
### Prerequisites
- **Git**: Version 2.30 or higher
- **Flutter**: Version 3.41.0+
- **Node.js**: Version 18.x LTS
- **Python**: Version 3.9+ (for RAG engine)
- **Flutter**: Version 3.11.5+ (with Dart 3.0+)
- **Firebase CLI**: Latest version
- **Code Editor**: VS Code recommended
- **Note**: No Node.js or Python required (backend is Firebase BaaS)
### Development Environment Setup
1. Fork the repository
@@ -32,19 +35,15 @@ Thank you for your interest in contributing to the AI Study Assistant! This guid
git clone https://github.com/YOUR_USERNAME/teachit.git
cd teachit
# Install Flutter dependencies
# Install Flutter dependencies only
flutter pub get
# Install Node.js dependencies
cd functions && npm install && cd ..
# Install Python dependencies
cd rag_engine && pip install -r requirements.txt && cd ..
# Note: No backend dependencies to install
# No Cloud Functions (Firebase BaaS is used)
# No Python RAG engine (implemented in Dart)
# Run tests
flutter test
npm test
pytest tests/
```
---

View File

@@ -1,12 +1,18 @@
# Deployment Guide - AI Study Assistant
## 🚀 COMPLETE DEPLOYMENT STRATEGY
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a arquitetura REAL do projeto (Flutter + Firebase BaaS, sem backend Node.js).
>
> **O que mudou:**
> - ❌ Removido: Node.js dependencies, Cloud Functions, backend server setup
> - ✅ Atualizado: Flutter SDK ^3.11.5, Firebase BaaS only, Ollama LLM
## 🚀 DEPLOYMENT STRATEGY
---
## 📋 OVERVIEW
This comprehensive guide covers the complete deployment process for the AI Study Assistant project, including development, staging, and production environments, CI/CD pipelines, monitoring, and maintenance procedures.
This guide covers the deployment process for the AI Study Assistant project. **Note:** This is a Flutter + Firebase BaaS (Backend-as-a-Service) architecture. There is no custom backend server - all business logic is in the Flutter app.
---
@@ -54,29 +60,25 @@ cd teachit
# Install Flutter dependencies
flutter pub get
# Install Node.js dependencies (for functions)
cd functions
npm install
# Note: No Node.js backend to install
# No Cloud Functions to set up
# Start Firebase emulators
firebase emulators:start
# Run Flutter app
# Run Flutter app (Firebase services connect directly)
flutter run
```
#### Development Firebase Project:
- **Project ID**: `teachit-dev-12345`
- **Services**: All services enabled in test mode
- **Services**: Auth, Firestore, Storage, Analytics, Crashlytics
- **Security Rules**: Relaxed for development
- **Emulators**: Local Firestore, Auth, Storage, Functions
- **Emulators**: Local Firestore, Auth, Storage (Functions not used)
#### Environment Variables:
```bash
# .env.development
FIREBASE_PROJECT_ID=teachit-dev-12345
FLUTTER_ENV=development
API_BASE_URL=http://localhost:5001
OLLAMA_BASE_URL=http://89.114.196.110:11434/api/chat
ENABLE_LOGGING=true
ENABLE_DEBUG=true
```

View File

@@ -1,12 +1,16 @@
# Development Setup Guide - AI Study Assistant
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a arquitetura REAL.
>
> **Nota:** NÃO é necessário Node.js nem Python. O projeto usa Flutter + Firebase BaaS apenas.
## 🛠️ COMPLETE DEVELOPMENT ENVIRONMENT SETUP
---
## 📋 OVERVIEW
This guide provides step-by-step instructions for setting up a complete development environment for the AI Study Assistant project, including Flutter frontend, Node.js backend, Firebase services, and development tools.
This guide provides step-by-step instructions for setting up the development environment for the AI Study Assistant project. **Note:** This is a Flutter + Firebase BaaS (Backend-as-a-Service) project. There is no custom Node.js backend or Python RAG engine to set up.
---

View File

@@ -1,12 +1,21 @@
# Firebase Configuration - AI Study Assistant
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a configuração REAL do projeto.
>
> **Notas Importantes:**
> - ❌ Cloud Functions: NÃO implementado
> - ❌ Performance Monitoring: NÃO implementado
> - ❌ Remote Config: NÃO implementado
> - ❌ Roles admin/super_admin: NÃO implementados (apenas student/teacher)
> - ✅ Estrutura real: users, materials, contentChunks, quizzes, classes, enrollments, userChats
## 🔥 COMPLETE FIREBASE SETUP GUIDE
---
## 📋 OVERVIEW
This document provides comprehensive instructions for setting up Firebase for the AI Study Assistant project, including authentication, database, storage, cloud functions, and security configurations.
This document provides instructions for setting up Firebase for the AI Study Assistant project. Note: This is a **Flutter + Firebase BaaS** architecture without a custom backend.
---
@@ -32,15 +41,18 @@ This document provides comprehensive instructions for setting up Firebase for th
### 1.2 Enable Required Services
#### Firebase Services to Enable:
#### Firebase Services Actually Used:
- ✅ Firebase Authentication
- ✅ Cloud Firestore
- ✅ Cloud Storage
- ✅ Cloud Functions
- ✅ Firebase Analytics
- ✅ Firebase Crashlytics
- ✅ Firebase Performance Monitoring
- ✅ Firebase Remote Config
- ✅ Firebase Cloud Messaging
#### Firebase Services NOT Used:
- ❌ Cloud Functions (not needed - logic in Flutter)
- ❌ Firebase Performance Monitoring (not implemented)
- ❌ Firebase Remote Config (not implemented)
#### Enable Commands:
```bash
@@ -53,10 +65,9 @@ firebase firestore:databases:create
# Enable Storage
firebase storage:buckets:create teachit-content
# Enable Functions
firebase functions:config:set
# Enable Analytics (automatically enabled)
# Note: Cloud Functions not needed
```
---
@@ -105,17 +116,23 @@ firebase functions:config:set
### 2.2 User Management Configuration
#### Custom Claims Setup:
```javascript
// Cloud Function to set custom claims
exports.setCustomClaims = functions.auth.user().onCreate(async (user) => {
const customClaims = {
role: 'student', // Default role
schoolId: 'default',
permissions: ['basic_access']
};
#### User Roles (Only 2 implemented):
```dart
// lib/core/services/auth_service.dart
class AuthService {
static const String studentRole = 'student';
static const String teacherRole = 'teacher';
// ❌ adminRole - NOT IMPLEMENTED
// ❌ superAdminRole - NOT IMPLEMENTED
}
```
await admin.auth().setCustomUserClaims(user.uid, customClaims);
**Note:** Role assignment is done client-side during signup:
```dart
await FirebaseFirestore.instance.collection('users').doc(user.uid).set({
'role': selectedRole, // 'student' or 'teacher'
'email': user.email,
'createdAt': FieldValue.serverTimestamp(),
});
```
@@ -131,17 +148,25 @@ exports.setCustomClaims = functions.auth.user().onCreate(async (user) => {
3. Choose location (e.g., `europe-west1`)
4. Set up security rules
#### Database Structure:
#### Actual Database Structure:
```javascript
// Collections Structure
schools/{schoolId}
├── users/{userId}
├── learningStates/{studentId}
├── contentChunks/{chunkId}
├── quizzes/{quizId}
├── quizAttempts/{attemptId}
├── interactions/{interactionId}
└── auditLogs/{logId}
// Collections Structure (as implemented in code)
// Top-level collections:
users/{userId} // User profiles with role
schools/{schoolId} // Schools/institutions
materials/{materialId} // Teacher uploaded content
contentChunks/{chunkId} // Text chunks with mock embeddings
quizzes/{quizId} // Quiz definitions
classes/{classId} // Teacher-created classes
enrollments/{enrollmentId} // Student class memberships
userChats/{userId}/conversations/{convId}/messages/{msgId} // Chat history
// Collections NOT implemented:
// ❌ learningStates/{studentId} - Not in codebase
// ❌ quizAttempts/{attemptId} - Not implemented
// ❌ interactions/{interactionId} - Replaced by userChats subcollection
// ❌ auditLogs/{logId} - Not implemented
```
### 3.2 Security Rules

View File

@@ -1,5 +1,10 @@
# Frontend MVP Tasks - AI Study Assistant
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a implementação REAL.
>
> **Versão Flutter:** 3.11.5+ (não 3.41.9 como documentado anteriormente)
> **Nota:** Não existe backend Node.js. Firebase BaaS é usado diretamente.
## 📱 MVP FRONTEND ROADMAP (8-12 WEEKS)
---
@@ -13,50 +18,77 @@
#### Subtasks:
- [ ] Create new Flutter project: `flutter create learn_it`
- [ ] Configure Flutter SDK version (3.41.9 or latest stable)
- [x] Configure Flutter SDK version (^3.11.5 or higher stable)
- [ ] Set up version control (Git repository)
- [ ] Create initial project structure
- [ ] Configure pubspec.yaml with initial dependencies
#### Dependencies to Add:
#### Actual Dependencies (from pubspec.yaml):
```yaml
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
# State Management
flutter_riverpod: ^2.4.9
riverpod_annotation: ^2.3.3
# Navigation
go_router: ^12.1.3
flutter_animate: ^4.2.0+1
# Firebase
firebase_core: ^2.24.2
firebase_auth: ^4.15.3
cloud_firestore: ^4.13.6
firebase_storage: ^11.5.6
firebase_core: ^2.25.4
firebase_auth: ^4.17.8
cloud_firestore: ^4.15.8
firebase_storage: ^11.6.9
firebase_analytics: ^10.8.0
firebase_messaging: ^14.9.3
firebase_crashlytics: ^3.5.7
# UI Components
cupertino_icons: ^1.0.6
google_fonts: ^6.1.0
# Navigation
go_router: ^12.1.3
cached_network_image: ^3.3.0
flutter_svg: ^2.0.9
lottie: ^2.7.0
shimmer: ^3.0.0
# HTTP & Networking
http: ^1.1.2
dio: ^5.4.0
http: ^1.1.2
connectivity_plus: ^5.0.2
# Local Storage
shared_preferences: ^2.2.2
hive: ^2.2.3
hive_flutter: ^1.1.0
flutter_secure_storage: ^9.0.0
# PDF Processing (for RAG)
syncfusion_flutter_pdf: ^33.2.6
file_selector: ^1.0.3
image_picker: ^1.0.4
# Utilities
intl: ^0.19.0
intl: ^0.20.2
uuid: ^4.2.1
equatable: ^2.0.5
# Charts
fl_chart: ^0.64.0
# Biometrics
local_auth: ^2.1.7
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.1
mockito: ^5.4.4
build_runner: ^2.4.7
mockito: ^5.4.4
```
#### Implementation Details:

View File

@@ -1,12 +1,16 @@
# Performance Optimization Guide - AI Study Assistant
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a arquitetura REAL.
>
> **Nota:** O projeto é Flutter + Firebase BaaS + Ollama. Não existe backend Node.js para otimizar.
## ⚡ COMPREHENSIVE PERFORMANCE STRATEGY
---
## 📋 OVERVIEW
This guide provides comprehensive performance optimization strategies for the AI Study Assistant platform, covering frontend performance, backend optimization, database efficiency, AI model performance, and overall system scalability.
This guide provides performance optimization strategies for the AI Study Assistant platform (Flutter + Firebase BaaS + Ollama). Focus areas: Flutter frontend performance, Firestore database efficiency, Ollama API response times, and Firebase service optimization.
---

View File

@@ -6,12 +6,14 @@ Documento Completo de Especificação Técnica e
Pedagógica
<EFBFBD>
<EFBFBD> PARTE 1: VISÃO E ARQUITECTURA GLOBAL
1.1 Definição do Sistema
Este projeto é uma Plataforma de Inteligência Educacional Distribuída baseada em:
• LLMs condicionados por conhecimento institucional (não conhecimento aberto)
• Arquitectura RAG multi-camada (Retrieval-Augmented Generation)
Controlo de acesso baseado em papéis (RBAC)
Geração adaptativa de aprendizagem (pedagogically-constrained output)
> ⚠️ **NOTA IMPORTANTE**: Este documento descreve uma visão aspiracional. A implementação REAL é: Flutter + Firebase + Ollama (sem backend Node.js/Python).
1.1 Definição do Sistema (VERSÃO REAL IMPLEMENTADA)
Este projeto é uma Plataforma de Inteligência Educacional baseada em:
LLM local (Ollama qwen3-coder:30b) com materiais PDF de professores
RAG simplificado com keyword search em Dart (não FAISS/BM25)
• RBAC apenas com roles student/teacher (sem admin)
• Flutter 3.11.5+ com Firebase BaaS (Backend-as-a-Service)
Core Identity:
Institutional AI Learning Operating System
with controlled knowledge injection,

View File

@@ -1,16 +1,14 @@
# 📊 Project Progress - AI Study Assistant
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a arquitetura REAL.
>
> **Nota:** "Backend Integration" refere-se a Firebase BaaS (Backend-as-a-Service), não a um backend Node.js/Python customizado.
---
## 🎯 OVERVIEW
This document tracks the overall progress of the AI Study Assistant project development. Updated in real-time as features are implemented.
This document tracks the overall progress of the AI Study Assistant project development (Flutter + Firebase BaaS + Ollama).

View File

@@ -1,43 +1,59 @@
# RAG Engine MVP Tasks - AI Study Assistant
## 🧠 MVP RAG ENGINE ROADMAP (8-12 WEEKS)
> ⚠️ **IMPORTANTE - DOCUMENTO DESATUALIZADO**: Este documento descreve uma arquitetura Python/FAISS que **NÃO FOI IMPLEMENTADA**.
>
> **Implementação Real:**
> - **Linguagem**: Dart (Flutter)
> - **Localização**: `lib/core/services/materials_rag_service.dart`, `lib/core/services/rag_ai_service.dart`
> - **Vector Store**: Firestore com embeddings mock (hash-based)
> - **PDF Processing**: `syncfusion_flutter_pdf` (não Python)
> - **Busca**: Keyword window search (não FAISS)
>
> **NÃO EXISTE:** Python, FAISS, Sentence Transformers, OpenAI, Anthropic
---
## 📚 WEEK 1-2: FOUNDATION & SETUP
## 🧠 MVP RAG ENGINE ROADMAP (DOCUMENTAÇÃO ORIGINAL - NÃO IMPLEMENTADA)
---
## 📚 WEEK 1-2: FOUNDATION & SETUP (NOT IMPLEMENTED)
### Task 1.1: Vector Database Setup
**Priority**: Critical
**Estimated Time**: 8 hours
**Dependencies**: None
**Status**: ❌ NOT IMPLEMENTED - FAISS não é utilizado
#### Subtasks:
- [ ] Choose vector database technology (FAISS for MVP)
- [ ] Set up development environment
- [ ] Install required dependencies
- [ ] Configure storage for vector indices
- [ ] Create basic vector operations
- [ ] Set up backup and recovery
#### What Actually Exists:
```dart
// lib/core/services/vector_service.dart
class VectorService {
// Mock embedding generation using text hashing
static List<double> generateEmbedding(String text) {
final embedding = List<double>.filled(384, 0.0);
// Hash-based deterministic embeddings (not ML)
return embedding;
}
}
#### Technology Stack:
// lib/core/services/materials_rag_service.dart
class MaterialsRAGService {
// Keyword-based window search for PDFs
static Future<String> getContextForQuestion(...) async {
// 1. Extract PDF text with syncfusion_flutter_pdf
// 2. Find keyword matches
// 3. Return window of 1200 chars around match
// NO FAISS, NO VECTOR SEARCH, NO PYTHON
}
}
```
#### Technology Stack (Original - NOT USED):
```bash
# Core dependencies
pip install faiss-cpu # or faiss-gpu for GPU acceleration
pip install sentence-transformers
pip install numpy
pip install pandas
pip install scikit-learn
# Text processing
pip install nltk
pip install spacy
python -m spacy download en_core_web_sm
# Storage and utilities
pip install firebase-admin
pip install google-cloud-storage
pip install pickle
pip install h5py
# These dependencies DO NOT EXIST in the project:
# ❌ pip install faiss-cpu
# ❌ pip install sentence-transformers
# ❌ pip install numpy
# ❌ pip install nltk
# ❌ pip install spacy
```
#### Project Structure:

View File

@@ -1,12 +1,16 @@
# Security Documentation - AI Study Assistant
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a implementação REAL.
>
> **Nota Importante sobre Roles:** Apenas `student` e `teacher` estão implementados. Roles `admin` e `super_admin` NÃO existem no código.
## 🔒 COMPREHENSIVE SECURITY FRAMEWORK
---
## 📋 OVERVIEW
This document outlines the complete security architecture, policies, and procedures for the AI Study Assistant platform, ensuring data protection, privacy compliance, and secure operations across all components.
This document outlines the security architecture for the AI Study Assistant platform. Note: This is a Flutter + Firebase BaaS application without a custom backend server.
---

View File

@@ -1,12 +1,16 @@
# Testing Strategy - AI Study Assistant
## 🧪 COMPREHENSIVE TESTING APPROACH
> ⚠️ **ATUALIZADO**: Este documento foi corrigido para refletir a arquitetura REAL.
>
> **Nota:** O projeto é Flutter + Firebase BaaS. Não existe backend Node.js/Python para testar.
## 🧪 TESTING APPROACH
---
## 📋 OVERVIEW
This document outlines the complete testing strategy for the AI Study Assistant project, covering unit tests, integration tests, widget tests, end-to-end tests, performance testing, and quality assurance processes.
This document outlines the testing strategy for the AI Study Assistant project (Flutter + Firebase BaaS). Testing focuses on Flutter unit/widget tests and Firebase security rules. There is no custom backend to test.
---