CoolFace
Apppublic

raorich/RAG-Based-Assistant-for-Academic-Final-Project-Information

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
App README

EPS Thesis Assistant (UdL)

Unofficial student project — A multilingual RAG chatbot that helps EPS (Escola Politècnica Superior) students navigate bachelor's and master's thesis (TFG/TFM) procedures at the Universitat de Lleida.

![Python](https://www.python.org/) ![FastAPI](https://fastapi.tiangolo.com/) ![ChromaDB](https://www.trychroma.com/) ![MongoDB](https://www.mongodb.com/atlas) License


⚠️ Important disclaimer

This tool is not affiliated with, endorsed by, or maintained by the EPS or the University of Lleida (UdL). It was built independently by an EPS student using publicly available information for educational purposes.

  • —Answers are guidance only — always confirm deadlines and requirements with the Academic Office (Secretaria) or your thesis supervisor.
  • —The knowledge base may be incomplete or outdated.
  • —Do not treat this as an official university service.

Table of contents


Overview

EPS Thesis Assistant is a retrieval-augmented generation (RAG) application that lets registered users ask natural-language questions about TFG/TFM topics: enrollment windows, submission deadlines, evaluation criteria, required documents, and more.

The system combines:

  1. 1.Semantic search over curated Markdown knowledge files (ChromaDB + multilingual embeddings).
  2. 2.Grounded answers from an LLM (Groq or Ollama) constrained to retrieved context.
  3. 3.JWT authentication with sessions stored in MongoDB Atlas.
  4. 4.A modern web UI with Catalan, Spanish, and English support.

Features

FeatureDescription
RAG Q&AAnswers grounded in local knowledge files, not open-ended hallucination
Section-aware chunkingMarkdown split by ## / ### headers for precise retrieval
Topic re-rankingKeyword boosts (e.g. evaluation → tfg_evaluacion_portafolio.md)
Multilingual UICA / ES / EN switcher with localized welcome message
LLM language controlResponses in the user's selected language even when sources are in Spanish
Auth gateBrowse freely; login/register modal when sending a message
Session managementJWT + server-side sessions in MongoDB
Question analyticsUser questions logged to MongoDB (questions collection)
Deploy-readyrender.yaml included for one-click cloud deployment

Architecture

mermaid
flowchart TB
    subgraph Client["Browser"]
        UI["static/ — Chat UI + i18n"]
    end

    subgraph API["FastAPI (app.py)"]
        AUTH["auth.py — JWT"]
        RAG["rag.py — Retrieve + rank"]
        LLM["llm.py — Groq / Ollama"]
        LOG["question_logger.py"]
    end

    subgraph Storage["Data stores"]
        CHROMA[("ChromaDB — db/<br/>vector embeddings")]
        MONGO[("MongoDB Atlas<br/>users · sessions · questions")]
        MD["data/*.md<br/>knowledge base"]
    end

    UI -->|HTTPS / REST| API
    AUTH --> MONGO
    LOG --> MONGO
    RAG --> CHROMA
    RAG --> LLM
    MD -.->|ingest_data.py| CHROMA

How it works (RAG pipeline)

mermaid
sequenceDiagram
    participant U as User
    participant API as FastAPI
    participant R as rag.py
    participant C as ChromaDB
    participant L as LLM (Groq)

    U->>API: POST /api/chat { message, language }
    API->>API: Validate JWT session (MongoDB)
    API->>R: chat(question, language)
    R->>C: Semantic search (top-k chunks)
    R->>R: Re-rank (topic boosts + dedupe)
    R->>L: Context + question + language rule
    L-->>R: Grounded answer
    R-->>API: { answer, found }
    API->>API: Log question → MongoDB
    API-->>U: JSON response

Ingestion (run once after cloning or updating data/):

bash
python ingest_data.py

This rebuilds the Chroma collection from all .md files under data/, using section-based chunking (~37 chunks for the default corpus).


Tech stack

LayerTechnology
APIFastAPI + Uvicorn
FrontendVanilla HTML / CSS / JavaScript
Embeddingssentence-transformers — paraphrase-multilingual-MiniLM-L12-v2
Vector DBChromaDB (persistent, local db/)
LLMGroq API (default) or Ollama (local)
AuthJWT (python-jose) + bcrypt
DatabaseMongoDB Atlas (PyMongo)
DeployRender (render.yaml)

Project structure

putoagent/
├── app.py                 # FastAPI entry point + routes
├── auth.py                # Registration, login, JWT validation
├── config.py              # Central paths (data/, db/, static/)
├── rag.py                 # Retrieval, re-ranking, chat orchestration
├── llm.py                 # LLM prompts per language (ca / es / en)
├── mongodb.py             # Users, sessions, DB indexes
├── question_logger.py     # Persist questions to MongoDB
├── ingest_data.py         # Build Chroma index from data/
├── query.py               # Optional CLI for local testing
├── requirements.txt
├── render.yaml            # Render Blueprint
├── .env.example
│
├── data/                  # Knowledge base (Markdown)
│   ├── tfg_faq.md
│   ├── tfg_fechas_y_plazos.md
│   ├── tfg_evaluacion_portafolio.md
│   └── ...
│
├── static/                # Web UI
│   ├── index.html
│   ├── app.js
│   ├── i18n.js            # CA / ES / EN translations
│   ├── style.css
│   └── auth.css
│
└── db/                    # Chroma persistence (gitignored, generated)

Getting started

Prerequisites

  • —Python 3.11+
  • —[Groq API key](https://console.groq.com) (free tier) or local Ollama
  • —[MongoDB Atlas](https://www.mongodb.com/atlas) cluster (free tier)

1. Clone and install

bash
git clone https://github.com/YOUR_USERNAME/YOUR_REPO.git
cd YOUR_REPO

python -m venv venv

# Windows
venv\Scripts\activate

# macOS / Linux
source venv/bin/activate

pip install -r requirements.txt

2. Configure environment

bash
cp .env.example .env

Edit .env with your credentials (see Environment variables).

3. Index the knowledge base

bash
python ingest_data.py

Expected output: ~37 chunks indexed into collection tfg_udl.

4. Run the server

bash
uvicorn app:app --reload

Open http://127.0.0.1:8000 in your browser.

5. (Optional) CLI testing without the web UI

bash
python query.py

Environment variables

VariableRequiredDescriptionExample
GROQ_API_KEYYes*Groq API keygsk_...
LLM_PROVIDERNogroq or ollamagroq
LLM_MODELNoModel identifierllama-3.1-8b-instant
OLLAMA_BASE_URLNoOllama OpenAI-compatible URLhttp://localhost:11434/v1
MONGODB_URIYesMongoDB Atlas connection stringmongodb+srv://...
MONGODB_DB_NAMENoDatabase nametfg_assistant
JWT_SECRET_KEYYesSecret for signing JWTslong random string
JWT_EXPIRE_MINUTESNoSession lifetime10080 (7 days)
MAX_DISTANCENoRetrieval distance threshold26
SHOW_CONTEXTNoPrint retrieved chunks in CLItrue

\* Not required if using Ollama only (LLM_PROVIDER=ollama).


API reference

MethodEndpointAuthDescription
GET/NoChat UI
GET/api/healthNoHealth check
POST/api/auth/registerNoCreate account + JWT
POST/api/auth/login/jsonNoLogin → JWT
POST/api/auth/logoutBearerRevoke session
GET/api/auth/meBearerCurrent user
POST/api/chatBearerAsk a question

Chat request example:

json
{
  "message": "When is the thesis enrollment period in February 2026?",
  "language": "en"
}

language must be one of: ca, es, en.


MongoDB collections

CollectionPurpose
usersEmail + bcrypt password hash
sessionsActive JWT sessions (jti, expiry, TTL index)
questionsLogged user questions for analytics

Deployment (Render)

  1. 1.Push this repository to GitHub (never commit `.env`).
  2. 2.Create a new Blueprint on Render from render.yaml.
  3. 3.Set secret environment variables in the Render dashboard:
  4. 4.GROQ_API_KEY
  5. 5.MONGODB_URI
  6. 6.The build step runs pip install + python ingest_data.py automatically.
Note: The db/ folder is gitignored. Chroma is rebuilt on each deploy via ingest_data.py.

Development

TaskCommand
Re-index after editing data/*.mdpython ingest_data.py
Run API with hot reloaduvicorn app:app --reload
Kill process on port 8000 (Windows)See below
powershell
# Find and kill process on port 8000 (Windows PowerShell)
Get-NetTCPConnection -LocalPort 8000 -ErrorAction SilentlyContinue |
  ForEach-Object { Stop-Process -Id $_.OwningProcess -Force }

Security notes

  • —Passwords are hashed with bcrypt; never stored in plain text.
  • —JWTs are validated against server-side sessions in MongoDB (revocable on logout).
  • —.env is gitignored — use .env.example as a template only.
  • —Rotate JWT_SECRET_KEY and API keys if they were ever exposed.

Roadmap

  • —[ ] Admin dashboard for question analytics
  • —[ ] PDF ingestion from official EPS documents
  • —[ ] Rate limiting per user
  • —[ ] Docker Compose setup
  • —[ ] Automated tests for retrieval quality

License

This project is intended for educational and non-commercial use as a student initiative. The University of Lleida and EPS names are used descriptively only; no endorsement is implied.

For official thesis regulations, always consult:


<p align="center"> Built with care for fellow EPS students · Not an official UdL product </p>