Master's Degree thesis work about testing LLMs to solve EU Laws compliances
Jupyter Notebook
0
5 commits
updated Jan 7, 2026
This repository contains a production-ready, modular Python package for LLM-based compliance analysis on legal regulations (GDPR, AI Act).
This work addresses the compliance challenges faced by SMEs under GDPR and the AI Act. Building on prior research on AI Act compliance, we expand to GDPR by constructing a deterministic Knowledge Graph of 99 Articles and 173 Recitals, generating over 5,000 synthetic question-answer pairs. We developed a domain-agnostic retrieval system and evaluated Agentic AI architectures (Routing, Collaborative Debate, Self-Refinement) for legal reasoning using lightweight LLMs on consumer hardware.
π₯ Download thesis: here
# View all setup options
python quick_reference.py
# Quick setup (CPU)
make install-cpu # or: python setup.py install-cpu
# Quick setup (GPU)
make install-gpu # or: python setup.py install-gpu
# Check system
make check-gpu # or: python setup.py check
# Run modules
python -m retrieval_augmented_generation.rag_and_qa
python -m finetuning.finetuning_with_unsloth
python -m synthetic_dataset_creation.synthetic_data_generation
LLMs-for-compliance/
βββ finetuning/ # LLM fine-tuning with Unsloth
β βββ config/ # Configuration settings
β βββ models/ # Model loading and LoRA setup
β βββ datasets/ # Dataset loading and preparation
β βββ training/ # Training utilities
β βββ evaluation/ # Evaluation metrics
β βββ utils/ # Utility functions
β
βββ synthetic_dataset_creation/ # Synthetic Q&A dataset generation
β βββ prompts/ # Prompt templates
β βββ schemas/ # Pydantic validation schemas
β βββ config/ # Configuration dataclasses
β βββ pipeline/ # Async generation pipeline
β βββ utils/ # Utility functions
β βββ gdpr_to_markdown/ # GDPR markdown parsing
β
βββ retrieval_augmented_generation/ # RAG system for Q&A
β βββ config/ # Configuration settings
β βββ prompts/ # RAG prompt templates
β βββ schemas/ # Pydantic schemas
β βββ rag/ # RAG implementations
β βββ patterns/ # Agentic RAG patterns
β βββ evaluation/ # Evaluation metrics
β βββ utils/ # Utility functions
β
βββ data/ # Data directory
β βββ GDPR/
β βββ AI ACT/
β
βββ requirements.txt # Package dependencies
# Auto-detect and install (recommended)
make install
# CPU-only installation
make install-cpu
# GPU installation (requires CUDA)
make install-gpu
# Install optional packages (Datapizza, Unsloth)
make install-optional
# Check system and GPU
make check-gpu
# Run tests
make test
# Auto-detect and install
python setup.py install
# CPU-only installation
python setup.py install-cpu
# GPU installation
python setup.py install-gpu
# Check system
python setup.py check
# Test installation
python setup.py test
# Windows batch script
setup.bat
# Or Linux/Mac shell script
./setup.sh
pip install -r requirements.txt
# For GPU support (CUDA 12.x)
pip install faiss-gpu-cu12
CMAKE_ARGS="-DGGML_CUDA=on -DCMAKE_CUDA_ARCHITECTURES=native" \
FORCE_CMAKE=1 pip install llama-cpp-python --force-reinstall --no-cache-dir
# For CPU only
pip install faiss-cpu llama-cpp-python
For GPU-accelerated inference and training:
Prerequisites:
Check your system:
# Using Makefile
make check-cuda
make check-gpu
# Using Python script
python setup.py check
Install CUDA:
sudo apt install nvidia-cuda-toolkitVerify CUDA installation:
nvcc --version
nvidia-smi
Fine-tune LLMs on legal Q&A datasets using Unsloth with LoRA adapters.
Key Components:
config: Dataset paths, model constants, LoRA target modulesmodels: Model loading, LoRA setup, inference loadingdatasets: Q&A dataset loading, ChatML formattingtraining: SFTTrainer creation, model savingevaluation: Prediction extraction, BLEU/ROUGE/METEOR/BERTScore metricsRunning the Pipeline:
The complete fine-tuning pipeline (finetuning_with_unsloth.py) performs:
# Run complete fine-tuning pipeline
python -m finetuning.finetuning_with_unsloth
# The script will:
# - Load model: unsloth/Llama-3.2-3B-Instruct-bnb-4bit
# - Setup LoRA with r=16, alpha=16
# - Train on GDPR Q&A dataset
# - Save to: ./models/finetuned_model/
# - Output: BLEU, ROUGE, METEOR, BERTScore metrics
Configuration (edit in finetuning/config/settings.py):
SELECTED_MODEL: Choose base modelGDPR_QA_DATASET / AI_ACT_QA_DATASET: Dataset pathsLORA_R, LORA_ALPHA: LoRA hyperparametersMAX_SEQ_LENGTH: Sequence length (default: 2048)Generate synthetic Q&A datasets for GDPR and AI Act using LLMs.
Key Components:
prompts: Question and answer generation templates (unity and binding types)schemas: Pydantic validation schemas for structured outputspipeline: AsyncQAGDPRPipeline for concurrent generation with resume capabilityutils: Data loading, LLM wrapper creation, dataset truncationgdpr_to_markdown: GDPR markdown file parsing utilitiesRunning the Pipeline:
The complete generation pipeline (synthetic_data_generation.py) performs:
# Run complete synthetic data generation pipeline
python -m synthetic_dataset_creation.synthetic_data_generation
# The script will:
# - Initialize llama.cpp LLM (e.g., Llama-3.2-3B-Instruct)
# - Load GDPR graph from: data/GDPR/datasets/gdpr_w_annexes.json
# - Generate 5000+ Q&A pairs asynchronously
# - Save to: data/GDPR/datasets/synthetic_qa_dataset.jsonl
# - Support resume: Ctrl+C safe, auto-checkpoint
Configuration (edit in synthetic_dataset_creation/config/settings.py):
MODEL_NAME: LLM to use for generationINPUT_JSON: GDPR/AI Act source fileOUTPUT_PATH: Where to save generated datasetLIMIT_PER_TYPE: Max questions per categoryTEMPERATURE: LLM generation temperatureComplete RAG system with graph enhancement and agentic patterns.
Key Components:
rag: AbstractRAG base class, BasicRAG (FAISS), DatapizzaRAG (Qdrant)patterns: 6 agentic patterns for legal reasoningevaluation: Comprehensive metrics (EM, F1, BLEU, ROUGE, METEOR, BERTScore)utils: Caching, JSON parsing, LLM calls, document loadingRunning the Pipeline:
The complete RAG evaluation pipeline (rag_and_qa.py) performs:
# Run complete RAG pipeline
python -m retrieval_augmented_generation.rag_and_qa
# The script will:
# Step 1: Initialize BasicRAG for GDPR and AI Act
# Step 2: Load Q&A evaluation datasets
# Step 3: Run retrieval evaluation (topk=20)
# - Basic RAG retrieval
# - RAG with graph enhancement
# - Cache results to: data/*/retrieval_results/*.jsonl
# Step 4: Initialize LLM (e.g., Llama-3.2-3B-Instruct)
# Step 5: Evaluate all 6 agentic patterns
# - Test each pattern with different topk values (1, 5, 10)
# - Cache generation results for each configuration
# Step 6: Compute and display metrics
# - Retrieval: P@K, R@K, F1@K
# - Generation: BLEU, ROUGE-L, METEOR, BERTScore
Configuration (edit in retrieval_augmented_generation/rag_and_qa.py or config/settings.py):
USE_CACHE: Load existing shuffled datasetsTOPK: Number of documents to retrieve (default: 20)selected_emb: Embedding model ("bge", "bge-large", etc.)TOPK_GEN: Top-k for generation evaluationLIMIT_GEN: Limit samples for quick testingThe framework provides multiple RAG implementations optimized for legal documents:
Both implementations support:
Example:
from retrieval_augmented_generation import RAGFactory
# FAISS-based RAG
basic_rag = RAGFactory.create(rag_type="basic", embedding_model="BAAI/bge-base-en-v1.5")
# Qdrant-based RAG
datapizza_rag = RAGFactory.create(
rag_type="datapizza",
embedding_model="BAAI/bge-base-en-v1.5",
vectorstore_path="./qdrant_storage"
)
Six agentic AI patterns for enhanced legal reasoning:
Simple LLM inference without retrieval. Useful for comparison and zero-shot evaluation.
LLM + Vector Retrieval: Retrieves relevant legal documents and generates answers based on context.
LLM + Vector + Knowledge Graph: Expands retrieval using document relationships (Articles cite Recitals, Annexes reference Articles).
Domain Classification β Specialized RAG: Routes queries to domain-specific RAGs (GDPR vs AI Act) based on content.
# Automatically routes to GDPR or AI Act RAG
answer = await routing_rag_pattern(
query="What is personal data processing?",
rags_dict={"GDPR": gdpr_rag, "AIACT": aiact_rag},
llm_func=your_llm
)
Generator β Critic Loop: A generator produces an answer, a critic identifies issues, and the process iterates until consensus or max rounds.
# Multi-round refinement
answer = await collaboration_rag_pattern(
query="Who is the data controller?",
rag=rag,
llm_func=your_llm,
max_rounds=3
)
Iterative Self-Improvement: The LLM critiques its own answers and refines them over multiple iterations.
# Self-critique and improvement
answer = await self_refinement_rag_pattern(
query="What are the data subject rights?",
rag=rag,
llm_func=your_llm,
max_iterations=2
)
Pattern Comparison:
| Pattern | Retrieval | Graph | Multi-Agent | Iterations | Use Case |
|---|---|---|---|---|---|
| Baseline | β | β | β | 1 | Zero-shot baseline |
| RAG | β | β | β | 1 | Standard retrieval |
| RAG+Graph | β | β | β | 1 | Connected legal concepts |
| Routing | β | β | β | 1 | Multi-domain queries |
| Collaboration | β | β | β | N | Complex reasoning |
| Self-Refinement | β | β | β | N | Answer quality improvement |
Python: 3.8+
Core Dependencies:
torch >= 2.0.0 - Deep learning frameworktransformers >= 4.36.0 - Hugging Face modelssentence-transformers >= 2.2.0 - Embeddingspydantic >= 2.0.0 - Data validationFine-tuning:
unsloth - Efficient LoRA trainingpeft >= 0.7.0 - Parameter-efficient fine-tuningtrl >= 0.7.0 - Transformer Reinforcement LearningRAG:
faiss-cpu or faiss-gpu-cu12 >= 1.7.4 - Vector searchllama-cpp-python >= 0.2.0 - Local LLM inferencenetworkx >= 3.0 - Knowledge graphEvaluation:
evaluate >= 0.4.0 - Hugging Face metricsbert-score >= 0.3.13 - Semantic similarityrouge-score >= 0.1.2 - Summarization metricsOptional:
datapizza-ai - Qdrant-based RAG (production)qdrant-client - Vector database clientSee requirements.txt for complete list.
Installation:
# Quick setup
make install # Auto-detect GPU/CPU
python setup.py install # Cross-platform
# See "Quick Start" section for detailed instructions
This project is licensed under the MIT License. See the LICENSE file for details.
If you use this framework in your research, please cite:
@mastersthesis{llms_compliance_2026,
title={Agentic AI for AI Act and GDPR compliance},
author={Manuel Di Lullo},
year={2025},
school={Sapienza University of Rome},
type={Master's Thesis}
}
Note: This research builds upon Tommaso Sgroi's thesis on AI Act compliance using graph-based RAG.
Master's Degree thesis work about testing LLMs to solve EU Laws compliances
Jupyter Notebook
0
5 commits
updated Jan 7, 2026
This repository contains a production-ready, modular Python package for LLM-based compliance analysis on legal regulations (GDPR, AI Act).
This work addresses the compliance challenges faced by SMEs under GDPR and the AI Act. Building on prior research on AI Act compliance, we expand to GDPR by constructing a deterministic Knowledge Graph of 99 Articles and 173 Recitals, generating over 5,000 synthetic question-answer pairs. We developed a domain-agnostic retrieval system and evaluated Agentic AI architectures (Routing, Collaborative Debate, Self-Refinement) for legal reasoning using lightweight LLMs on consumer hardware.
π₯ Download thesis: here
# View all setup options
python quick_reference.py
# Quick setup (CPU)
make install-cpu # or: python setup.py install-cpu
# Quick setup (GPU)
make install-gpu # or: python setup.py install-gpu
# Check system
make check-gpu # or: python setup.py check
# Run modules
python -m retrieval_augmented_generation.rag_and_qa
python -m finetuning.finetuning_with_unsloth
python -m synthetic_dataset_creation.synthetic_data_generation
LLMs-for-compliance/
βββ finetuning/ # LLM fine-tuning with Unsloth
β βββ config/ # Configuration settings
β βββ models/ # Model loading and LoRA setup
β βββ datasets/ # Dataset loading and preparation
β βββ training/ # Training utilities
β βββ evaluation/ # Evaluation metrics
β βββ utils/ # Utility functions
β
βββ synthetic_dataset_creation/ # Synthetic Q&A dataset generation
β βββ prompts/ # Prompt templates
β βββ schemas/ # Pydantic validation schemas
β βββ config/ # Configuration dataclasses
β βββ pipeline/ # Async generation pipeline
β βββ utils/ # Utility functions
β βββ gdpr_to_markdown/ # GDPR markdown parsing
β
βββ retrieval_augmented_generation/ # RAG system for Q&A
β βββ config/ # Configuration settings
β βββ prompts/ # RAG prompt templates
β βββ schemas/ # Pydantic schemas
β βββ rag/ # RAG implementations
β βββ patterns/ # Agentic RAG patterns
β βββ evaluation/ # Evaluation metrics
β βββ utils/ # Utility functions
β
βββ data/ # Data directory
β βββ GDPR/
β βββ AI ACT/
β
βββ requirements.txt # Package dependencies
# Auto-detect and install (recommended)
make install
# CPU-only installation
make install-cpu
# GPU installation (requires CUDA)
make install-gpu
# Install optional packages (Datapizza, Unsloth)
make install-optional
# Check system and GPU
make check-gpu
# Run tests
make test
# Auto-detect and install
python setup.py install
# CPU-only installation
python setup.py install-cpu
# GPU installation
python setup.py install-gpu
# Check system
python setup.py check
# Test installation
python setup.py test
# Windows batch script
setup.bat
# Or Linux/Mac shell script
./setup.sh
pip install -r requirements.txt
# For GPU support (CUDA 12.x)
pip install faiss-gpu-cu12
CMAKE_ARGS="-DGGML_CUDA=on -DCMAKE_CUDA_ARCHITECTURES=native" \
FORCE_CMAKE=1 pip install llama-cpp-python --force-reinstall --no-cache-dir
# For CPU only
pip install faiss-cpu llama-cpp-python
For GPU-accelerated inference and training:
Prerequisites:
Check your system:
# Using Makefile
make check-cuda
make check-gpu
# Using Python script
python setup.py check
Install CUDA:
sudo apt install nvidia-cuda-toolkitVerify CUDA installation:
nvcc --version
nvidia-smi
Fine-tune LLMs on legal Q&A datasets using Unsloth with LoRA adapters.
Key Components:
config: Dataset paths, model constants, LoRA target modulesmodels: Model loading, LoRA setup, inference loadingdatasets: Q&A dataset loading, ChatML formattingtraining: SFTTrainer creation, model savingevaluation: Prediction extraction, BLEU/ROUGE/METEOR/BERTScore metricsRunning the Pipeline:
The complete fine-tuning pipeline (finetuning_with_unsloth.py) performs:
# Run complete fine-tuning pipeline
python -m finetuning.finetuning_with_unsloth
# The script will:
# - Load model: unsloth/Llama-3.2-3B-Instruct-bnb-4bit
# - Setup LoRA with r=16, alpha=16
# - Train on GDPR Q&A dataset
# - Save to: ./models/finetuned_model/
# - Output: BLEU, ROUGE, METEOR, BERTScore metrics
Configuration (edit in finetuning/config/settings.py):
SELECTED_MODEL: Choose base modelGDPR_QA_DATASET / AI_ACT_QA_DATASET: Dataset pathsLORA_R, LORA_ALPHA: LoRA hyperparametersMAX_SEQ_LENGTH: Sequence length (default: 2048)Generate synthetic Q&A datasets for GDPR and AI Act using LLMs.
Key Components:
prompts: Question and answer generation templates (unity and binding types)schemas: Pydantic validation schemas for structured outputspipeline: AsyncQAGDPRPipeline for concurrent generation with resume capabilityutils: Data loading, LLM wrapper creation, dataset truncationgdpr_to_markdown: GDPR markdown file parsing utilitiesRunning the Pipeline:
The complete generation pipeline (synthetic_data_generation.py) performs:
# Run complete synthetic data generation pipeline
python -m synthetic_dataset_creation.synthetic_data_generation
# The script will:
# - Initialize llama.cpp LLM (e.g., Llama-3.2-3B-Instruct)
# - Load GDPR graph from: data/GDPR/datasets/gdpr_w_annexes.json
# - Generate 5000+ Q&A pairs asynchronously
# - Save to: data/GDPR/datasets/synthetic_qa_dataset.jsonl
# - Support resume: Ctrl+C safe, auto-checkpoint
Configuration (edit in synthetic_dataset_creation/config/settings.py):
MODEL_NAME: LLM to use for generationINPUT_JSON: GDPR/AI Act source fileOUTPUT_PATH: Where to save generated datasetLIMIT_PER_TYPE: Max questions per categoryTEMPERATURE: LLM generation temperatureComplete RAG system with graph enhancement and agentic patterns.
Key Components:
rag: AbstractRAG base class, BasicRAG (FAISS), DatapizzaRAG (Qdrant)patterns: 6 agentic patterns for legal reasoningevaluation: Comprehensive metrics (EM, F1, BLEU, ROUGE, METEOR, BERTScore)utils: Caching, JSON parsing, LLM calls, document loadingRunning the Pipeline:
The complete RAG evaluation pipeline (rag_and_qa.py) performs:
# Run complete RAG pipeline
python -m retrieval_augmented_generation.rag_and_qa
# The script will:
# Step 1: Initialize BasicRAG for GDPR and AI Act
# Step 2: Load Q&A evaluation datasets
# Step 3: Run retrieval evaluation (topk=20)
# - Basic RAG retrieval
# - RAG with graph enhancement
# - Cache results to: data/*/retrieval_results/*.jsonl
# Step 4: Initialize LLM (e.g., Llama-3.2-3B-Instruct)
# Step 5: Evaluate all 6 agentic patterns
# - Test each pattern with different topk values (1, 5, 10)
# - Cache generation results for each configuration
# Step 6: Compute and display metrics
# - Retrieval: P@K, R@K, F1@K
# - Generation: BLEU, ROUGE-L, METEOR, BERTScore
Configuration (edit in retrieval_augmented_generation/rag_and_qa.py or config/settings.py):
USE_CACHE: Load existing shuffled datasetsTOPK: Number of documents to retrieve (default: 20)selected_emb: Embedding model ("bge", "bge-large", etc.)TOPK_GEN: Top-k for generation evaluationLIMIT_GEN: Limit samples for quick testingThe framework provides multiple RAG implementations optimized for legal documents:
Both implementations support:
Example:
from retrieval_augmented_generation import RAGFactory
# FAISS-based RAG
basic_rag = RAGFactory.create(rag_type="basic", embedding_model="BAAI/bge-base-en-v1.5")
# Qdrant-based RAG
datapizza_rag = RAGFactory.create(
rag_type="datapizza",
embedding_model="BAAI/bge-base-en-v1.5",
vectorstore_path="./qdrant_storage"
)
Six agentic AI patterns for enhanced legal reasoning:
Simple LLM inference without retrieval. Useful for comparison and zero-shot evaluation.
LLM + Vector Retrieval: Retrieves relevant legal documents and generates answers based on context.
LLM + Vector + Knowledge Graph: Expands retrieval using document relationships (Articles cite Recitals, Annexes reference Articles).
Domain Classification β Specialized RAG: Routes queries to domain-specific RAGs (GDPR vs AI Act) based on content.
# Automatically routes to GDPR or AI Act RAG
answer = await routing_rag_pattern(
query="What is personal data processing?",
rags_dict={"GDPR": gdpr_rag, "AIACT": aiact_rag},
llm_func=your_llm
)
Generator β Critic Loop: A generator produces an answer, a critic identifies issues, and the process iterates until consensus or max rounds.
# Multi-round refinement
answer = await collaboration_rag_pattern(
query="Who is the data controller?",
rag=rag,
llm_func=your_llm,
max_rounds=3
)
Iterative Self-Improvement: The LLM critiques its own answers and refines them over multiple iterations.
# Self-critique and improvement
answer = await self_refinement_rag_pattern(
query="What are the data subject rights?",
rag=rag,
llm_func=your_llm,
max_iterations=2
)
Pattern Comparison:
| Pattern | Retrieval | Graph | Multi-Agent | Iterations | Use Case |
|---|---|---|---|---|---|
| Baseline | β | β | β | 1 | Zero-shot baseline |
| RAG | β | β | β | 1 | Standard retrieval |
| RAG+Graph | β | β | β | 1 | Connected legal concepts |
| Routing | β | β | β | 1 | Multi-domain queries |
| Collaboration | β | β | β | N | Complex reasoning |
| Self-Refinement | β | β | β | N | Answer quality improvement |
Python: 3.8+
Core Dependencies:
torch >= 2.0.0 - Deep learning frameworktransformers >= 4.36.0 - Hugging Face modelssentence-transformers >= 2.2.0 - Embeddingspydantic >= 2.0.0 - Data validationFine-tuning:
unsloth - Efficient LoRA trainingpeft >= 0.7.0 - Parameter-efficient fine-tuningtrl >= 0.7.0 - Transformer Reinforcement LearningRAG:
faiss-cpu or faiss-gpu-cu12 >= 1.7.4 - Vector searchllama-cpp-python >= 0.2.0 - Local LLM inferencenetworkx >= 3.0 - Knowledge graphEvaluation:
evaluate >= 0.4.0 - Hugging Face metricsbert-score >= 0.3.13 - Semantic similarityrouge-score >= 0.1.2 - Summarization metricsOptional:
datapizza-ai - Qdrant-based RAG (production)qdrant-client - Vector database clientSee requirements.txt for complete list.
Installation:
# Quick setup
make install # Auto-detect GPU/CPU
python setup.py install # Cross-platform
# See "Quick Start" section for detailed instructions
This project is licensed under the MIT License. See the LICENSE file for details.
If you use this framework in your research, please cite:
@mastersthesis{llms_compliance_2026,
title={Agentic AI for AI Act and GDPR compliance},
author={Manuel Di Lullo},
year={2025},
school={Sapienza University of Rome},
type={Master's Thesis}
}
Note: This research builds upon Tommaso Sgroi's thesis on AI Act compliance using graph-based RAG.