Skip to content
This repository was archived by the owner on Jul 22, 2025. It is now read-only.

🎓 Revolutionary AI-powered educational platform combining Web3 technology, blockchain rewards, and personalized learning through knowledge graphs and LLMs. Transform education with smart contracts and tokenized incentives!

Notifications You must be signed in to change notification settings

NhanPhamThanh-IT/Educhain-AI-Web3-Hackfest

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EduChain AI - Web3 Educational Platform

Code Quality GitHub stars GitHub forks GitHub issues GitHub license

Website Build Status Maintained

PRs Welcome Contributors Documentation

✨ Introduction

EduChain AI is an innovative Web3-based educational platform that integrates artificial intelligence (AI) and blockchain technology to revolutionize online learning. With features like AI-powered personalized learning tools, a tokenized economy for document exchange and rewards systems, and blockchain-secured transactions. Educhain offers a comprehensive ecosystem for both learners and educators. The platform leverages LLMs (e.g., Llama-3,3-chatQA-finetuned, Llama-3.2-Vision, DeepSeek-Coder-V2) and knowledge-augmented generation (combine of knowledge graph and vector retrieval) techniques to create a seamless and engaging experience and allow users to achieve their educational goals, while Web3 technology (e.g., smart contracts, cryptocurrencies) builds a secure and transparent system that includes a rewards mechanism based on users effort.

EduChain's unique features include AI-driven content generation (quiz, exam,...), customizable study guides, and a transparent marketplace for course creation and purchase. Learners can upload their materials, use an interactive agentic chatbot for tailored learning support, and participate in gamified activities to enhance their educational journey.

🎯 Mission

To provide a dynamic and decentralized platform that makes education accessible, engaging, and rewarding through the integration of AI and Web3 technologies:

  • For Learners: The platform personalizes learning experiences by creating quizzes, study guides, and multimedia content from uploaded files. Learners are incentivized with token rewards for their achievements and active participation.

  • For Educators and Creators: Educhain allows educators to design, upload, and monetize their courses while earning tokens based on learner engagement and sales.

  • For All Users: Blockchain ensures secure, transparent transactions, while a token economy promotes motivation, fairness, and inclusivity within the learning ecosystem.

🚀 Why Web3 x AI?

The synergy of Web3 and AI offers opportunities for innovation in education:

  • Personalization at Scale: AI tailors learning paths and content to individual needs, while Web3 ensures transparency and ownership of data.

  • Tokenized Incentives: Blockchain enables a decentralized reward system, motivating learners to stay engaged while providing fair compensation to creators.

  • Secure and Transparent Ecosystem: Web3 guarantees secure transactions and traceable ownership of educational resources, reducing fraud and increasing trust.

  • Empowering Creators and Learners: With AI automating content generation and Web3 ensuring equitable distribution, the platform fosters a collaborative and inclusive learning environment.

EduChain’s unique features include AI-driven content generation (quiz, exam,...), customizable study guides, and a transparent marketplace for course creation and purchase. Learners can upload their materials, use an interactive agentic chatbot for tailored learning support, and participate in gamified activities to enhance their educational journey.

🏗️ Project Architecture

EduChain AI follows a modular, full-stack architecture designed for scalability and maintainability:

EduChain-AI/
├── 📁 backend/              # FastAPI-based Python backend
├── 📁 frontend/             # React.js frontend (v1)
├── 📁 frontend_v2/          # React.js frontend (v2 - Enhanced)
├── 📁 contract/             # Move smart contracts for Sui blockchain
├── 📁 tests/                # Comprehensive testing suite
└── 📁 .git/                 # Git version control

🛠️ Technology Stack

Backend Technologies

Python FastAPI OpenAI Azure LangChain LightRAG

  • Framework: FastAPI (Python) - High-performance web framework
  • AI/ML:
    • LangChain - AI application framework
    • LightRAG - Knowledge-augmented generation
    • OpenAI GPT models
    • Azure Cognitive Services
    • DeepSeek models
  • Database:
    • PostgreSQL - Primary relational database
    • Neo4j - Graph database for knowledge graphs
  • Cloud Services:
    • Azure Blob Storage - File storage
    • Azure Document Intelligence - Document processing
    • Azure Speech Services - Text-to-speech functionality
  • Authentication: JWT tokens, bcrypt for password hashing

Frontend Technologies

React TypeScript MUI Vite SWC ESLint

  • Framework: React.js with Vite
  • UI Libraries:
    • Material-UI (MUI)
    • Framer Motion - Animations
    • React Router - Navigation
  • Web3 Integration:
    • Sui Wallet Kit - Sui blockchain integration
    • RainbowKit - Ethereum wallet connections
    • Wagmi - React hooks for Ethereum
  • Additional: Axios, React Hot Toast, React Markdown

Blockchain Technologies

Sui Move PostgreSQL Neo4j

  • Smart Contracts: Move language on Sui blockchain
  • Token Standard: Custom EduToken implementation
  • Features: Staking, DEX, ICO, Treasury management

📂 Detailed Project Structure

🔧 Backend (/backend)

The backend is built with FastAPI and follows a clean architecture pattern:

Core Application (/backend/app/)

API Layer (/app/api/v1/endpoints/)

  • auth.py - User authentication and authorization
  • chatbot.py - AI chatbot endpoints with streaming support
  • course.py - Course management and CRUD operations
  • document.py - Document upload and processing
  • user.py - User profile management
  • video.py - Video generation and processing
  • speech.py - Text-to-speech conversion
  • storage.py - File storage management
  • graph.py - Knowledge graph operations

Database Layer (/app/database/)

  • connect_db.py - Database connection management
  • course.py - Course-related database operations
  • document.py - Document storage and retrieval
  • user_info.py - User information management
  • chat_history.py - Conversation history tracking
  • exam.py - Exam and quiz management
  • mission.py - Gamification and missions
  • lightrag_usage.py - LightRAG integration
  • neo4j_usage.py - Neo4j graph database operations

Services Layer (/app/services/)

  • chatbot_service.py - AI-powered chatbot logic
  • document_service.py - Document processing and analysis
  • course_services.py - Course creation and management
  • auth.py - Authentication services
  • azure_file_processing.py - Azure AI document processing
  • blob_storage_service.py - Azure Blob Storage integration
  • speech_service.py - Text-to-speech services
  • video_service.py - Video generation (HeyGen integration)
  • retrieval_service.py - Information retrieval services

Models (/app/models/)

  • auth_model.py - Authentication data models
  • postgre_model.py - PostgreSQL data models
  • neo4j_model.py - Neo4j graph models
  • lightrag_model.py - LightRAG integration models

AI Integration (/app/LightRAG/)

  • Advanced RAG (Retrieval-Augmented Generation) implementation
  • Knowledge graph construction and querying
  • Vector embeddings for semantic search

Utilities (/app/utils/ & /app/prompt/)

  • Helper functions and utilities
  • AI prompt templates and engineering

Key Features:

  • FastAPI Framework: High-performance async API
  • CORS Middleware: Cross-origin resource sharing
  • Authentication: JWT-based user authentication
  • File Processing: Azure AI for document analysis
  • Real-time Chat: Streaming responses for chatbot
  • Database Integration: PostgreSQL + Neo4j hybrid approach

🎨 Frontend (/frontend & /frontend_v2)

Two versions of the React frontend with progressive enhancements:

Frontend V1 (/frontend)

Components (/src/components/)

  • Reusable UI components
  • Form components for user input
  • Navigation and layout components

Pages (/src/pages/)

  • Course browsing and details
  • User authentication pages
  • Dashboard and profile management
  • Chat interface

Features:

  • Material-UI design system
  • Ethereum wallet integration (RainbowKit)
  • Sui blockchain support
  • File upload with drag-and-drop
  • Real-time chat interface
  • Responsive design

Frontend V2 (/frontend_v2)

Enhanced version with improved performance and features:

  • Optimized bundle size with Terser
  • Better ESLint configuration
  • Updated React 19 support
  • Enhanced Sui wallet integration
  • Improved animations with Framer Motion

Key Frontend Features:

  • Web3 Integration: Multi-wallet support (Sui, Ethereum)
  • Real-time Communication: WebSocket support for chat
  • File Management: Document upload and processing
  • Interactive UI: Animations and responsive design
  • Accessibility: ARIA compliance and keyboard navigation

⛓️ Smart Contracts (/contract)

Built on Sui blockchain using Move language:

Core Contract (/contract/core/sources/)

  • admin.move - Administrative functions and access control
  • dex.move - Decentralized exchange functionality
  • events.move - Event emission and tracking
  • ICO.move - Initial Coin Offering implementation
  • missions.move - Gamification and reward system
  • protocol_fee.move - Fee collection and distribution
  • staking.move - Token staking mechanisms
  • treasury.move - Treasury management and governance
  • version.move - Contract versioning

EduToken (/contract/edutoken/sources/)

  • edutoken.move - Main token contract implementation

Features:

  • Custom Token: EduToken for platform economy
  • Staking System: Incentivize long-term participation
  • DEX Integration: Token trading capabilities
  • Mission System: Gamified rewards
  • Treasury Management: Decentralized fund management
  • ICO Functionality: Token distribution mechanisms

🧪 Testing Suite (/tests)

Comprehensive testing across all components:

Backend Tests (/tests/backend/)

  • API endpoint testing
  • Database operation validation
  • Authentication flow testing
  • AI service integration tests

Frontend Tests (/tests/frontend/)

  • Component unit tests
  • Integration testing
  • E2E testing scenarios

AI/ML Tests (/tests/ai/)

  • test_azure_ai.py - Azure AI services testing
  • test_openrouter.py - OpenRouter API testing
  • lightrag_test.py - LightRAG functionality testing

Blockchain Tests (/tests/blockchain/)

  • Smart contract testing
  • Token functionality validation
  • Integration testing with frontend

Specialized Tests

  • crawl4AI.py - Web crawling and data extraction
  • graph_visualize.py - Knowledge graph visualization
  • selenium_ktu.py - Browser automation testing

🔄 Data Flow Architecture

1. User Authentication Flow

Frontend → FastAPI Auth Endpoint → JWT Generation → Database Storage

2. Document Processing Flow

File Upload → Azure Blob Storage → Azure AI Processing →
LightRAG Indexing → Knowledge Graph Creation → Vector Embeddings

3. AI Chat Flow

User Query → FastAPI Chatbot Endpoint → LightRAG Retrieval →
LLM Processing → Streaming Response → Frontend Display

4. Blockchain Integration Flow

User Action → Sui Wallet → Smart Contract Execution →
Event Emission → Backend Notification → Database Update

🤖 AI Integration Details

LightRAG Implementation

  • Knowledge Graphs: Automatic extraction from documents
  • Vector Embeddings: Semantic search capabilities
  • Hybrid Retrieval: Combines graph and vector search
  • Multi-Modal: Text, image, and document processing

Large Language Models

  • Primary: GPT-4 via OpenAI API
  • Alternative: DeepSeek models for coding tasks
  • Vision: GPT-4 Vision for image analysis
  • Embedding: OpenAI text-embedding-ada-002

Azure AI Services

  • Document Intelligence: Extract text from PDFs and images
  • Cognitive Services: Advanced document analysis
  • Speech Services: Text-to-speech conversion
  • Blob Storage: Secure file storage and retrieval

🔐 Security Features

Authentication & Authorization

  • JWT-based stateless authentication
  • bcrypt password hashing
  • Role-based access control
  • Session management

Data Protection

  • Azure Blob Storage encryption
  • HTTPS/TLS encryption in transit
  • Environment variable protection
  • SQL injection prevention

Blockchain Security

  • Move language safety features
  • Multi-signature support
  • Access control mechanisms
  • Audit trail on blockchain

Installation

Prerequisites

Before installing EduChain AI, ensure you have the following installed:

  • Python 3.8+ - For backend development
  • Node.js 16+ - For frontend development
  • PostgreSQL 12+ - Primary database
  • Neo4j 4.0+ - Graph database
  • Git - Version control

Backend Setup

1. Clone the Repository

git clone https://github.com/NhanPhamThanh-IT/Educhain-AI.git
cd Educhain-AI

2. Create Virtual Environment

cd backend
python -m venv venv
.\venv\Scripts\Activate.ps1  # PowerShell
# or
venv\Scripts\activate        # Command Prompt

3. Install Dependencies

pip install -r requirements.txt

4. Environment Configuration

Create a .env file in the backend directory:

# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key

# PostgreSQL Database
DB_NAME=educhain_db
DB_USER=your_username
DB_PASSWORD=your_password
DB_HOST=localhost
DB_PORT=5432

# Neo4j Graph Database
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASS=your_neo4j_password

# Azure Services
AZURE_STORAGE_CONNECTION_STRING=your_azure_connection_string
AZURE_STORAGE_CONTAINER_NAME=educhain-storage
AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT=your_azure_endpoint
AZURE_DOCUMENT_INTELLIGENCE_KEY=your_azure_key
AZURE_SPEECH_KEY=your_speech_key
AZURE_SPEECH_REGION=your_region

# JWT Configuration
SECRET_KEY=your_secret_key
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# LightRAG Configuration
LIGHTRAG_WORKING_DIR=./lightrag_storage

5. Database Setup

PostgreSQL Setup:

# Install PostgreSQL and create database
createdb educhain_db

# Run database initialization
python -c "from app.database.init_db import init_all_tables; init_all_tables()"

Neo4j Setup:

  1. Install Neo4j Desktop or Neo4j Community Server
  2. Create a new database named educhain
  3. Start the database service
  4. Update .env with connection details

6. Start Backend Server

python main.py
# or
uvicorn main:app --reload --host 127.0.0.1 --port 8000

The backend will be available at http://localhost:8000

Frontend Setup

Frontend V1 Setup

cd frontend
npm install
npm run dev

Frontend V2 Setup (Recommended)

cd frontend_v2
npm install
npm run dev

The frontend will be available at http://localhost:5173

Smart Contract Setup

Prerequisites for Sui Development

  1. Install Sui CLI:
# Install Sui CLI (Windows)
# Download from: https://github.com/MystenLabs/sui/releases
  1. Install Move Analyzer (Optional):
# For VS Code development
# Install "Move Analyzer" extension from VS Code marketplace

Deploy Contracts

cd contract/core
sui move build

cd ../edutoken
sui move build

# Deploy to devnet (example)
sui client publish --gas-budget 20000000

Development Workflow

Running the Full Stack

  1. Start Backend:
cd backend
.\venv\Scripts\Activate.ps1
python main.py
  1. Start Frontend:
cd frontend_v2
npm run dev
  1. Start Databases:
  • Ensure PostgreSQL is running
  • Ensure Neo4j is running

Running Tests

Backend Tests:

cd backend
python -m pytest tests/

Frontend Tests:

cd frontend_v2
npm test

Integration Tests:

cd tests
python test_azure_ai.py
python lightrag_test.py

Configuration Guide

Azure Services Setup

  1. Create Azure Storage Account:

    • Create a storage account in Azure Portal
    • Create a container named educhain-storage
    • Copy connection string to .env
  2. Setup Document Intelligence:

    • Create Azure Document Intelligence resource
    • Copy endpoint and key to .env
  3. Setup Speech Services:

    • Create Azure Speech Services resource
    • Copy key and region to .env

Database Configuration

PostgreSQL Extensions:

-- Enable UUID extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Enable vector extension (if using pgvector)
CREATE EXTENSION IF NOT EXISTS vector;

Neo4j Configuration:

// Create indexes for better performance
CREATE INDEX ON :User(wallet_address);
CREATE INDEX ON :Course(id);
CREATE INDEX ON :Document(id);

Environment Variables Reference

Variable Description Required
OPENAI_API_KEY OpenAI API key for LLM operations Yes
DB_NAME PostgreSQL database name Yes
DB_USER PostgreSQL username Yes
DB_PASSWORD PostgreSQL password Yes
DB_HOST PostgreSQL host Yes
DB_PORT PostgreSQL port Yes
NEO4J_URI Neo4j connection URI Yes
NEO4J_USER Neo4j username Yes
NEO4J_PASS Neo4j password Yes
AZURE_STORAGE_CONNECTION_STRING Azure Blob Storage connection No
SECRET_KEY JWT secret key Yes

Deployment

Production Deployment Guide

Backend Deployment

Option 1: Docker Deployment

Create Dockerfile:

FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Build and Run:

docker build -t educhain-backend .
docker run -p 8000:8000 --env-file .env educhain-backend

Option 2: Cloud Deployment (Azure/AWS)

Azure App Service:

# Install Azure CLI
az webapp up --name educhain-backend --location eastus --sku B1

AWS EC2:

# Use AWS CLI or console to deploy
# Install dependencies and configure nginx

Frontend Deployment

Build for Production

Frontend V2:

cd frontend_v2
npm run build

Deploy to Vercel

npm install -g vercel
vercel --prod

Deploy to Netlify

npm install -g netlify-cli
netlify deploy --prod --dir=dist

Database Deployment

PostgreSQL Production Setup

-- Create production database
CREATE DATABASE educhain_prod;

-- Create user with limited privileges
CREATE USER educhain_user WITH PASSWORD 'secure_password';
GRANT ALL PRIVILEGES ON DATABASE educhain_prod TO educhain_user;

Neo4j Production Setup

  • Use Neo4j Aura (cloud) or self-hosted instance
  • Configure clustering for high availability
  • Set up monitoring and backups

Smart Contract Deployment

Sui Mainnet Deployment

# Switch to mainnet
sui client switch --env mainnet

# Deploy core contract
cd contract/core
sui client publish --gas-budget 100000000

# Deploy edutoken
cd ../edutoken
sui client publish --gas-budget 50000000

Environment Configuration

Production Environment Variables:

# Use production database credentials
DB_HOST=production-db-host
DB_NAME=educhain_prod

# Use production API keys
OPENAI_API_KEY=prod_openai_key

# Enable production optimizations
ENVIRONMENT=production
DEBUG=false

# Use secure secret keys
SECRET_KEY=very_secure_production_key

Monitoring and Logging

Backend Monitoring

# Add to main.py
import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('app.log'),
        logging.StreamHandler()
    ]
)

Health Check Endpoint

@app.get("/health")
async def health_check():
    return {"status": "healthy", "timestamp": datetime.now()}

Security Hardening

Backend Security

  • Use HTTPS only
  • Implement rate limiting
  • Add security headers
  • Regular dependency updates

Database Security

  • Use connection pooling
  • Enable SSL connections
  • Regular backups
  • Monitor for suspicious activity

Frontend Security

  • Content Security Policy (CSP)
  • Secure headers
  • XSS protection
  • CSRF protection

Performance Optimization

Backend Optimization

# Add caching
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend

# Configure Redis caching
FastAPICache.init(RedisBackend(host="localhost", port=6379), prefix="educhain-cache")

Frontend Optimization

  • Code splitting
  • Lazy loading
  • Image optimization
  • CDN usage

Backup Strategy

Database Backups

# PostgreSQL backup
pg_dump -h hostname -U username -d database_name > backup.sql

# Neo4j backup
neo4j-admin backup --backup-dir=/path/to/backup --name=graph.db-backup

File Storage Backups

  • Configure Azure Blob Storage redundancy
  • Regular backup verification
  • Cross-region replication

Scaling Considerations

Horizontal Scaling

  • Load balancer configuration
  • Multiple backend instances
  • Database read replicas
  • CDN for static assets

Vertical Scaling

  • Resource monitoring
  • Performance profiling
  • Database optimization
  • Caching strategies

For detailed deployment instructions specific to your hosting provider, refer to their documentation and our deployment guides in the /docs folder.

🔌 API Documentation

Authentication Endpoints

POST /api/v1/auth/register

Register a new user account.

Request Body:

{
  "username": "string",
  "email": "string",
  "password": "string",
  "wallet_address": "string (optional)"
}

Response:

{
  "access_token": "string",
  "token_type": "bearer",
  "user_id": "integer"
}

POST /api/v1/auth/login

Authenticate user and return access token.

Request Body:

{
  "email": "string",
  "password": "string"
}

Course Management Endpoints

GET /api/v1/courses

Retrieve all available courses.

Query Parameters:

  • category (optional): Filter by course category
  • limit (optional): Number of courses to return
  • offset (optional): Pagination offset

POST /api/v1/courses

Create a new course.

Request Body:

{
  "name": "string",
  "category": "string",
  "introduction": "string",
  "description": "string",
  "wallet_address": "string"
}

GET /api/v1/courses/{course_id}

Retrieve specific course details.

Document Management Endpoints

POST /api/v1/documents/upload

Upload and process educational documents.

Request: Multipart form data with file

Response:

{
  "document_id": "integer",
  "filename": "string",
  "status": "processing|completed|failed",
  "extracted_text": "string"
}

GET /api/v1/documents/{document_id}

Retrieve document information and content.

AI Chatbot Endpoints

POST /api/v1/chatbot/chat

Send message to AI chatbot.

Request Body:

{
  "docs_id": ["string"],
  "question": "string",
  "thread_id": "string",
  "course_id": "string"
}

GET /api/v1/chatbot/stream

Stream chatbot responses in real-time.

Knowledge Graph Endpoints

POST /api/v1/graph/build

Build knowledge graph from documents.

GET /api/v1/graph/query

Query the knowledge graph.

Query Parameters:

  • query: Natural language query
  • mode: "naive|local|global|hybrid"

🎮 Smart Contract Interface

EduToken Contract

Functions

mint(recipient: address, amount: u64)

  • Mint new EduTokens to specified address
  • Requires admin privileges

transfer(to: address, amount: u64)

  • Transfer tokens between addresses
  • Standard token transfer function

stake(amount: u64, duration: u64)

  • Stake tokens for rewards
  • Returns staking receipt

unstake(stake_id: ID)

  • Unstake tokens after duration
  • Claims accumulated rewards

Core Protocol Contract

Mission System

create_mission(reward: u64, requirements: vector<u8>)

  • Create new learning mission
  • Define completion requirements

complete_mission(mission_id: ID, proof: vector<u8>)

  • Submit mission completion proof
  • Claim token rewards

DEX Functions

create_liquidity_pool(token_a: ID, token_b: ID)

  • Create trading pair
  • Initialize liquidity pool

swap(pool_id: ID, input_amount: u64, min_output: u64)

  • Execute token swap
  • Includes slippage protection

📊 Database Schema

PostgreSQL Tables

Users Table

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(255) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    wallet_address TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Courses Table

CREATE TABLE courses (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    user_id INTEGER REFERENCES users(id),
    name VARCHAR(255) NOT NULL,
    category VARCHAR(255) NOT NULL,
    introduction TEXT,
    description TEXT,
    threads TEXT[],
    lesson UUID[],
    quiz_question TEXT[],
    exam_question TEXT[],
    study_guide INTEGER[],
    document INTEGER[],
    wallet_address TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Documents Table

CREATE TABLE documents (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id),
    filename VARCHAR(255) NOT NULL,
    file_path TEXT NOT NULL,
    file_size BIGINT,
    mime_type VARCHAR(100),
    extracted_text TEXT,
    processing_status VARCHAR(50) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Chat History Table

CREATE TABLE chat_history (
    id SERIAL PRIMARY KEY,
    thread_id VARCHAR(255) NOT NULL,
    user_id INTEGER REFERENCES users(id),
    course_id UUID REFERENCES courses(id),
    message TEXT NOT NULL,
    response TEXT NOT NULL,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Neo4j Graph Schema

Node Types

  • User: User profiles and relationships
  • Course: Course information and connections
  • Document: Document nodes with content
  • Concept: Extracted concepts from documents
  • Topic: Learning topics and subjects

Relationship Types

  • ENROLLED_IN: User enrollment in courses
  • CREATED_BY: Course/document creation relationships
  • CONTAINS: Document-concept relationships
  • RELATED_TO: Concept interconnections
  • PREREQUISITE: Course prerequisite relationships

🧪 Testing Framework

Backend Testing

Unit Tests

# Example test structure
import pytest
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_create_course():
    response = client.post(
        "/api/v1/courses",
        json={
            "name": "Test Course",
            "category": "Technology",
            "introduction": "Test introduction"
        }
    )
    assert response.status_code == 200
    assert "id" in response.json()

Integration Tests

  • Database connectivity tests
  • Azure services integration tests
  • Authentication flow tests
  • File upload and processing tests

Frontend Testing

Component Tests

// Example Jest test
import { render, screen } from "@testing-library/react";
import CourseCard from "../components/CourseCard";

test("renders course information", () => {
  const course = {
    name: "Test Course",
    category: "Technology",
    description: "Test description",
  };

  render(<CourseCard course={course} />);
  expect(screen.getByText("Test Course")).toBeInTheDocument();
});

E2E Tests

  • User registration and login flows
  • Course creation and enrollment
  • Document upload and processing
  • Chatbot interaction tests

Smart Contract Testing

Move Unit Tests

#[test]
fun test_token_transfer() {
    let admin = @0x123;
    let user = @0x456;

    // Test token minting and transfer
    let ctx = test_utils::create_test_context(admin);
    let token = edutoken::mint(&mut ctx, user, 100);

    assert!(coin::value(&token) == 100, 0);
}

🚀 Performance Optimization

Backend Optimization

Database Optimization

  • Connection pooling with psycopg
  • Query optimization and indexing
  • Prepared statements for frequent queries
  • Database partitioning for large tables

Caching Strategy

from functools import lru_cache
import redis

# Redis caching for expensive operations
redis_client = redis.Redis(host='localhost', port=6379, db=0)

@lru_cache(maxsize=128)
def get_course_content(course_id: str):
    # Cache course content retrieval
    cached = redis_client.get(f"course:{course_id}")
    if cached:
        return json.loads(cached)

    # Fetch from database
    content = database.get_course(course_id)
    redis_client.setex(f"course:{course_id}", 3600, json.dumps(content))
    return content

Async Operations

  • Async file processing with Azure services
  • Background task processing with Celery
  • Async database operations with asyncpg

Frontend Optimization

Code Splitting

// Lazy loading for route components
const CourseDetails = lazy(() => import("./pages/CourseDetails"));
const Dashboard = lazy(() => import("./pages/Dashboard"));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <Routes>
        <Route path="/course/:id" element={<CourseDetails />} />
        <Route path="/dashboard" element={<Dashboard />} />
      </Routes>
    </Suspense>
  );
}

Bundle Optimization

  • Tree shaking for unused code elimination
  • Webpack bundle analyzer for size optimization
  • CDN for static assets
  • Image optimization and lazy loading

🔐 Security Best Practices

Authentication Security

  • Password hashing with bcrypt (cost factor 12)
  • JWT token expiration and refresh mechanisms
  • Rate limiting for authentication endpoints
  • Account lockout after failed attempts

Data Protection

  • Input validation and sanitization
  • SQL injection prevention with parameterized queries
  • XSS protection with content security policy
  • CSRF protection with tokens

Smart Contract Security

  • Access control with Move capabilities
  • Overflow protection in arithmetic operations
  • Reentrancy protection
  • Emergency pause mechanisms

Infrastructure Security

  • HTTPS/TLS for all communications
  • Environment variable protection
  • Regular security updates
  • Network firewalls and VPN access

🛠️ Development Tools

Backend Development

  • FastAPI: Modern Python web framework
  • SQLAlchemy: ORM for database operations
  • Alembic: Database migration tool
  • pytest: Testing framework
  • Black: Code formatting
  • Flake8: Code linting

Frontend Development

  • Vite: Fast build tool and dev server
  • ESLint: JavaScript linting
  • Prettier: Code formatting
  • Jest: Testing framework
  • React Testing Library: Component testing

Blockchain Development

  • Sui CLI: Move contract development
  • Move Analyzer: VS Code extension
  • Sui Explorer: Transaction monitoring
  • Sui Wallet: Testing wallet integration

📈 Monitoring and Analytics

Application Monitoring

# Health check endpoint
@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "timestamp": datetime.now(),
        "database": check_database_health(),
        "external_services": check_external_services()
    }

Performance Metrics

  • Response time monitoring
  • Database query performance
  • Memory and CPU usage
  • Error rate tracking

User Analytics

  • Course completion rates
  • User engagement metrics
  • Learning path optimization
  • Token economy analytics

🤝 Contributing

Development Workflow

  1. Fork the Repository
git clone https://github.com/NhanPhamThanh-IT/Educhain-AI.git
cd Educhain-AI
git checkout -b feature/your-feature-name
  1. Set Up Development Environment
  • Follow installation instructions
  • Configure pre-commit hooks
  • Run test suite
  1. Development Guidelines
  • Follow PEP 8 for Python code
  • Use ESLint configuration for JavaScript
  • Write comprehensive tests
  • Update documentation
  1. Submit Pull Request
  • Create descriptive commit messages
  • Include tests for new features
  • Update README if needed
  • Request code review

Code Style Guidelines

Python (Backend)

# Use type hints
def create_course(name: str, category: str) -> Dict[str, Any]:
    """Create a new course with validation."""
    pass

# Use docstrings
def process_document(file_path: str) -> DocumentResult:
    """
    Process uploaded document with Azure AI.

    Args:
        file_path: Path to uploaded file

    Returns:
        DocumentResult with extracted text and metadata

    Raises:
        ProcessingError: If document processing fails
    """
    pass

JavaScript (Frontend)

// Use ES6+ features
const CourseCard = ({ course, onEnroll }) => {
  const handleEnrollment = useCallback(() => {
    onEnroll(course.id);
  }, [course.id, onEnroll]);

  return (
    <Card>
      <CardContent>
        <Typography variant="h6">{course.name}</Typography>
        <Button onClick={handleEnrollment}>Enroll</Button>
      </CardContent>
    </Card>
  );
};

Move (Smart Contracts)

/// Create new mission with reward allocation
public entry fun create_mission(
    admin: &AdminCap,
    ctx: &mut TxContext,
    reward_amount: u64,
    requirements: vector<u8>
) {
    let mission = Mission {
        id: object::new(ctx),
        reward_amount,
        requirements,
        completed_by: vector::empty(),
        created_at: tx_context::epoch(ctx)
    };

    transfer::share_object(mission);
}

📚 Additional Resources

Documentation

Learning Resources

Community

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • OpenAI for providing powerful language models
  • Microsoft Azure for cloud services
  • Sui Foundation for blockchain infrastructure
  • The open-source community for invaluable tools and libraries

📞 Contact

For questions, support, or collaboration opportunities:


🚀 EduChain AI - Transforming Education Through AI and Web3 Technology 🚀

About

🎓 Revolutionary AI-powered educational platform combining Web3 technology, blockchain rewards, and personalized learning through knowledge graphs and LLMs. Transform education with smart contracts and tokenized incentives!

Topics

Resources

Stars

Watchers

Forks

Languages

  • Python 59.5%
  • JavaScript 37.6%
  • Move 1.6%
  • TypeScript 1.0%
  • HTML 0.2%
  • Dockerfile 0.1%