Secure Chatbot Documentation
Project Documentation: Chatbot with FastAPI, React, and Keycloak
# Overview
This project is a secure chatbot application using:
- FastAPI as the backend
- React (Vite) for the frontend
- Keycloak for authentication
- Ollama LLM (Deepseek model) for chatbot responses
- MySQL for database storage
## Architecture
+------------+ +--------------------+ +------------------+
| React UI |<------>| FastAPI Backend |<----->| MySQL Database |
| (Vite) | | (Chat + Auth logic) | +------------------+
+------------+ | Auth via Keycloak |
| +--------------------+
+------------------------+
| Keycloak Auth Server |
+------------------------+
# Keycloak Authentication Flow
1. User clicks Login/Signup
2. Redirects to Keycloak login URL
3. On success, returns to frontend with access token
4. Token is used in all API calls with Authorization: Bearer <token>
# FastAPI Backend
# Key Files
- keycloak_setup.py - Configures KeycloakOpenID client
- dependencies.py - Extracts user info from token
- main.py - API routes for chat and history
- crud/chat.py - Functions to save and fetch chat
- models/chat.py - SQLAlchemy model for chat
- services/database.py - MySQL DB engine and session
### API Endpoints
- POST /chat - Sends message to bot, stores user and bot message
- GET /chat-history - Returns all messages for logged-in user
# Database Table: chat_messages
| Column | Type |
|----------|--------------|
| id | INT (PK) |
| username | VARCHAR(100) |
| sender | VARCHAR(10) |
| message | TEXT |
| timestamp| DATETIME |
# React Frontend
- AuthPage.jsx - Sign in / Sign up / Forgot buttons
- App.jsx - Chat UI with auto-scroll, stream updates
- keycloak.js - Keycloak config using keycloak-js
# Features
- Message streaming from /chat
- Past chat history from /chat-history
- Auto scroll and message typing animation
- Logout and new chat support
# Styling
- Dark theme using custom CSS in App.css
- Responsive layout for small screens
# Setup Instructions
# Backend
cd llama-fastapi
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --reload
# Frontend
cd llama-ui
npm install
npm run dev
# Keycloak (Docker)
docker run -p 8080:8080 \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:24.0.1 start-dev
1. Create realm: lama-realm
2. Create client: lama-client (public)
3. Set valid redirect URI: http://localhost:5173/*