ShubhamDahane18/HalluciGuard

Python

0

2 commits

updated Oct 3, 2026

See the code

README

πŸ›‘οΈ HalluciGuard

Claim-Level LLM Hallucination Detection & Evaluation Framework
A research prototype for detecting hallucinations at the individual claim level using adaptive cascading verification.


πŸ“Œ Problem

Whole-answer hallucination detection treats a response as a single unit β€” either hallucinated or not. This is insufficient: an LLM answer may be mostly factual with a single fabricated detail, and binary detection misses this.

HalluciGuard verifies each extracted atomic claim independently against retrieved evidence, providing fine-grained hallucination analysis.

Example:

Question: "Who founded Tesla?"
Answer: "Tesla was founded in 2003 by Elon Musk. Martin Eberhard served as early CEO."

ClaimStatus
Tesla was founded in 2003βœ… Supported
Elon Musk founded Tesla❌ Unsupported
Martin Eberhard served as early CEOβœ… Supported

πŸ—οΈ Architecture

graph TD
    A[Question] --> B[LLM Answer Generation\nOllama]
    B --> C[Claim Extraction\nLLM-based]
    C --> D[Evidence Retrieval\nFAISS + Embeddings]
    D --> E{Adaptive Verification}
    E -->|High embedding sim| F[βœ… Supported]
    E -->|Uncertain| G[NLI Verifier\nDeBERTa]
    G -->|High confidence| H[Final Result]
    G -->|Uncertain| I[LLM Judge\nOllama]
    I --> J[Final Result]
    F --> K[Report + Metrics]
    H --> K
    J --> K
    K --> L[Streamlit Dashboard]
    K --> M[MLflow Tracking]

πŸ”¬ Verification Methods

MethodDescriptionSpeedAccuracy
EmbeddingCosine similarity between claim and evidence⚑ FastBaseline
NLIDeBERTa entailment classificationβœ… MediumBetter
LLM JudgeOllama LLM evaluates claim vs evidence🐒 SlowBest
Adaptive (proposed)Cascades: Embedding β†’ NLI β†’ LLM (only when needed)βœ… EfficientCompetitive

Main Hypothesis

A cascading verification architecture can reduce expensive LLM calls while maintaining competitive claim-level hallucination detection performance.


πŸ“ Project Structure

HalluciGuard/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ main.py                    # FastAPI app
β”‚   β”œβ”€β”€ config.py                  # Centralized config (pydantic-settings)
β”‚   β”œβ”€β”€ api/routes.py              # REST endpoints
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ answer_generator.py    # Ollama LLM
β”‚   β”‚   β”œβ”€β”€ claim_extractor.py     # LLM claim extraction
β”‚   β”‚   β”œβ”€β”€ retriever.py           # FAISS evidence retrieval
β”‚   β”‚   β”œβ”€β”€ similarity_verifier.py # Embedding baseline
β”‚   β”‚   β”œβ”€β”€ nli_verifier.py        # NLI baseline
β”‚   β”‚   β”œβ”€β”€ llm_verifier.py        # LLM judge baseline
β”‚   β”‚   β”œβ”€β”€ adaptive_verifier.py   # Proposed method
β”‚   β”‚   └── report_generator.py    # Metrics & report
β”‚   β”œβ”€β”€ models/schemas.py          # Pydantic schemas
β”‚   └── utils/logging_config.py
β”‚
β”œβ”€β”€ frontend/app.py                # Streamlit dashboard
β”‚
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ documents/                 # Evidence corpus (.txt files)
β”‚   └── evaluation/benchmark.json  # Ground-truth labeled claims
β”‚
β”œβ”€β”€ experiments/
β”‚   β”œβ”€β”€ run_experiment.py          # CLI runner with MLflow
β”‚   β”œβ”€β”€ baseline_embedding.py
β”‚   β”œβ”€β”€ baseline_nli.py
β”‚   β”œβ”€β”€ baseline_llm.py
β”‚   └── adaptive_halluciguard.py
β”‚
β”œβ”€β”€ evaluation/
β”‚   β”œβ”€β”€ metrics.py                 # Accuracy, F1, hallucination rate
β”‚   β”œβ”€β”€ evaluator.py               # Run one method against benchmark
β”‚   └── benchmark.py              # Compare all 4 methods
β”‚
β”œβ”€β”€ tests/                         # pytest unit tests
β”œβ”€β”€ results/                       # Generated experiment CSVs
β”œβ”€β”€ mlruns/                        # MLflow experiment data
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .env.example
└── run.py

πŸš€ Installation

1. Create virtual environment

python -m venv venv

Windows:

venv\Scripts\activate

Linux/Mac:

source venv/bin/activate

2. Install dependencies

pip install -r requirements.txt

3. Configure environment

cp .env.example .env

Edit .env as needed. Key settings:

OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=qwen2.5:7b
EMBEDDING_MODEL=BAAI/bge-small-en-v1.5
TOP_K=5

πŸ¦™ Ollama Setup

  1. Install Ollama: https://ollama.com/download

  2. Start Ollama:

    ollama serve
    
  3. Pull the model:

    ollama pull qwen2.5:7b
    
  4. Verify:

    ollama list
    

Any Ollama-compatible model works. Change OLLAMA_MODEL in .env.


▢️ Running the Application

Backend (FastAPI)

uvicorn backend.main:app --reload --port 8000

Test health:

curl http://localhost:8000/health

Frontend (Streamlit)

In a separate terminal:

streamlit run frontend/app.py

Open: http://localhost:8501


πŸ§ͺ Running Experiments

# Single method
python experiments/run_experiment.py --method adaptive
python experiments/run_experiment.py --method embedding
python experiments/run_experiment.py --method nli
python experiments/run_experiment.py --method llm

# All methods (full comparison)
python experiments/run_experiment.py --method all

Results are saved to results/ as CSV files.


πŸ“ˆ MLflow Tracking

Launch MLflow UI

mlflow ui --port 5000

Open: http://localhost:5000

Each experiment run logs:

  • Parameters: model, thresholds, method
  • Metrics: accuracy, precision, recall, F1, faithfulness, hallucination rate, LLM avoidance rate
  • Artifacts: result CSVs, confusion matrix JSON

πŸ”Œ API Endpoints

EndpointMethodDescription
/healthGETBackend status check
/analyzePOSTFull pipeline analysis
/retrievePOSTEvidence retrieval for a query
/verify-claimPOSTVerify a single claim against evidence

Example /analyze request:

curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d '{"question": "Who founded Tesla?", "verification_method": "adaptive"}'

πŸ§ͺ Tests

pytest tests/ -v

Tests cover:

  • Claim extraction (valid JSON, malformed, fallback)
  • FAISS retrieval (indexing, relevance, structure)
  • Similarity verifier (thresholds, empty evidence)
  • API endpoints (/health, /retrieve, /verify-claim, /analyze validation)

πŸ“Š Evaluation Metrics

Classification

  • Accuracy, Precision, Recall, F1 (weighted)
  • Per-class metrics (supported / uncertain / unsupported)
  • Confusion matrix

Hallucination (Project-specific)

  • Faithfulness Score = Supported Claims / Total Claims
  • Hallucination Rate = Unsupported Claims / Total Claims

Efficiency (Adaptive method)

  • LLM calls, NLI calls, Embedding calls
  • LLM Avoidance Rate = 1 βˆ’ (LLM calls / Total claims)
  • Average latency per claim

πŸ”¬ Research Questions

  1. Does claim-level verification improve hallucination detection over whole-answer approaches?
  2. How do embedding, NLI, and LLM-based verification compare in accuracy?
  3. Can adaptive verification reduce LLM calls while maintaining competitive accuracy?
  4. What is the trade-off between verification accuracy and computational cost?

βš™οΈ Configuration Reference

VariableDefaultDescription
OLLAMA_MODELqwen2.5:7bOllama model name
OLLAMA_BASE_URLhttp://localhost:11434Ollama API URL
EMBEDDING_MODELBAAI/bge-small-en-v1.5Sentence transformer model
TOP_K5Evidence chunks to retrieve
SIMILARITY_THRESHOLD0.70Embedding verification threshold
HIGH_SIMILARITY_THRESHOLD0.85Adaptive: skip NLI if above this
LOW_SIMILARITY_THRESHOLD0.40Adaptive: force NLI if below this
NLI_CONFIDENCE_THRESHOLD0.80Adaptive: call LLM if NLI below this
NLI_MODELcross-encoder/nli-deberta-v3-smallHuggingFace NLI model
BACKEND_URLhttp://localhost:8000Streamlit β†’ Backend URL
MLFLOW_TRACKING_URI./mlrunsMLflow tracking location

πŸ“ Adding Documents

Place .txt files in data/documents/. The system will:

  1. Split into paragraphs (~chunks)
  2. Embed with the configured sentence transformer
  3. Index into FAISS

Delete data/faiss_index/ to force a rebuild.


⚠️ Limitations

  • Requires Ollama running locally for LLM-dependent features
  • NLI and embedding models are downloaded on first run (~500MB)
  • Small benchmark dataset (7 questions, ~33 claims) β€” extend data/evaluation/benchmark.json for robust research
  • Adaptive thresholds are manually configured β€” future work could learn them

πŸ† Acknowledgements

Built as a research internship project exploring claim-level hallucination detection using adaptive verification strategies.

ShubhamDahane18/HalluciGuard

Python

0

2 commits

updated Oct 3, 2026

See the code

README

πŸ›‘οΈ HalluciGuard

Claim-Level LLM Hallucination Detection & Evaluation Framework
A research prototype for detecting hallucinations at the individual claim level using adaptive cascading verification.


πŸ“Œ Problem

Whole-answer hallucination detection treats a response as a single unit β€” either hallucinated or not. This is insufficient: an LLM answer may be mostly factual with a single fabricated detail, and binary detection misses this.

HalluciGuard verifies each extracted atomic claim independently against retrieved evidence, providing fine-grained hallucination analysis.

Example:

Question: "Who founded Tesla?"
Answer: "Tesla was founded in 2003 by Elon Musk. Martin Eberhard served as early CEO."

ClaimStatus
Tesla was founded in 2003βœ… Supported
Elon Musk founded Tesla❌ Unsupported
Martin Eberhard served as early CEOβœ… Supported

πŸ—οΈ Architecture

graph TD
    A[Question] --> B[LLM Answer Generation\nOllama]
    B --> C[Claim Extraction\nLLM-based]
    C --> D[Evidence Retrieval\nFAISS + Embeddings]
    D --> E{Adaptive Verification}
    E -->|High embedding sim| F[βœ… Supported]
    E -->|Uncertain| G[NLI Verifier\nDeBERTa]
    G -->|High confidence| H[Final Result]
    G -->|Uncertain| I[LLM Judge\nOllama]
    I --> J[Final Result]
    F --> K[Report + Metrics]
    H --> K
    J --> K
    K --> L[Streamlit Dashboard]
    K --> M[MLflow Tracking]

πŸ”¬ Verification Methods

MethodDescriptionSpeedAccuracy
EmbeddingCosine similarity between claim and evidence⚑ FastBaseline
NLIDeBERTa entailment classificationβœ… MediumBetter
LLM JudgeOllama LLM evaluates claim vs evidence🐒 SlowBest
Adaptive (proposed)Cascades: Embedding β†’ NLI β†’ LLM (only when needed)βœ… EfficientCompetitive

Main Hypothesis

A cascading verification architecture can reduce expensive LLM calls while maintaining competitive claim-level hallucination detection performance.


πŸ“ Project Structure

HalluciGuard/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ main.py                    # FastAPI app
β”‚   β”œβ”€β”€ config.py                  # Centralized config (pydantic-settings)
β”‚   β”œβ”€β”€ api/routes.py              # REST endpoints
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ answer_generator.py    # Ollama LLM
β”‚   β”‚   β”œβ”€β”€ claim_extractor.py     # LLM claim extraction
β”‚   β”‚   β”œβ”€β”€ retriever.py           # FAISS evidence retrieval
β”‚   β”‚   β”œβ”€β”€ similarity_verifier.py # Embedding baseline
β”‚   β”‚   β”œβ”€β”€ nli_verifier.py        # NLI baseline
β”‚   β”‚   β”œβ”€β”€ llm_verifier.py        # LLM judge baseline
β”‚   β”‚   β”œβ”€β”€ adaptive_verifier.py   # Proposed method
β”‚   β”‚   └── report_generator.py    # Metrics & report
β”‚   β”œβ”€β”€ models/schemas.py          # Pydantic schemas
β”‚   └── utils/logging_config.py
β”‚
β”œβ”€β”€ frontend/app.py                # Streamlit dashboard
β”‚
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ documents/                 # Evidence corpus (.txt files)
β”‚   └── evaluation/benchmark.json  # Ground-truth labeled claims
β”‚
β”œβ”€β”€ experiments/
β”‚   β”œβ”€β”€ run_experiment.py          # CLI runner with MLflow
β”‚   β”œβ”€β”€ baseline_embedding.py
β”‚   β”œβ”€β”€ baseline_nli.py
β”‚   β”œβ”€β”€ baseline_llm.py
β”‚   └── adaptive_halluciguard.py
β”‚
β”œβ”€β”€ evaluation/
β”‚   β”œβ”€β”€ metrics.py                 # Accuracy, F1, hallucination rate
β”‚   β”œβ”€β”€ evaluator.py               # Run one method against benchmark
β”‚   └── benchmark.py              # Compare all 4 methods
β”‚
β”œβ”€β”€ tests/                         # pytest unit tests
β”œβ”€β”€ results/                       # Generated experiment CSVs
β”œβ”€β”€ mlruns/                        # MLflow experiment data
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .env.example
└── run.py

πŸš€ Installation

1. Create virtual environment

python -m venv venv

Windows:

venv\Scripts\activate

Linux/Mac:

source venv/bin/activate

2. Install dependencies

pip install -r requirements.txt

3. Configure environment

cp .env.example .env

Edit .env as needed. Key settings:

OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=qwen2.5:7b
EMBEDDING_MODEL=BAAI/bge-small-en-v1.5
TOP_K=5

πŸ¦™ Ollama Setup

  1. Install Ollama: https://ollama.com/download

  2. Start Ollama:

    ollama serve
    
  3. Pull the model:

    ollama pull qwen2.5:7b
    
  4. Verify:

    ollama list
    

Any Ollama-compatible model works. Change OLLAMA_MODEL in .env.


▢️ Running the Application

Backend (FastAPI)

uvicorn backend.main:app --reload --port 8000

Test health:

curl http://localhost:8000/health

Frontend (Streamlit)

In a separate terminal:

streamlit run frontend/app.py

Open: http://localhost:8501


πŸ§ͺ Running Experiments

# Single method
python experiments/run_experiment.py --method adaptive
python experiments/run_experiment.py --method embedding
python experiments/run_experiment.py --method nli
python experiments/run_experiment.py --method llm

# All methods (full comparison)
python experiments/run_experiment.py --method all

Results are saved to results/ as CSV files.


πŸ“ˆ MLflow Tracking

Launch MLflow UI

mlflow ui --port 5000

Open: http://localhost:5000

Each experiment run logs:

  • Parameters: model, thresholds, method
  • Metrics: accuracy, precision, recall, F1, faithfulness, hallucination rate, LLM avoidance rate
  • Artifacts: result CSVs, confusion matrix JSON

πŸ”Œ API Endpoints

EndpointMethodDescription
/healthGETBackend status check
/analyzePOSTFull pipeline analysis
/retrievePOSTEvidence retrieval for a query
/verify-claimPOSTVerify a single claim against evidence

Example /analyze request:

curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d '{"question": "Who founded Tesla?", "verification_method": "adaptive"}'

πŸ§ͺ Tests

pytest tests/ -v

Tests cover:

  • Claim extraction (valid JSON, malformed, fallback)
  • FAISS retrieval (indexing, relevance, structure)
  • Similarity verifier (thresholds, empty evidence)
  • API endpoints (/health, /retrieve, /verify-claim, /analyze validation)

πŸ“Š Evaluation Metrics

Classification

  • Accuracy, Precision, Recall, F1 (weighted)
  • Per-class metrics (supported / uncertain / unsupported)
  • Confusion matrix

Hallucination (Project-specific)

  • Faithfulness Score = Supported Claims / Total Claims
  • Hallucination Rate = Unsupported Claims / Total Claims

Efficiency (Adaptive method)

  • LLM calls, NLI calls, Embedding calls
  • LLM Avoidance Rate = 1 βˆ’ (LLM calls / Total claims)
  • Average latency per claim

πŸ”¬ Research Questions

  1. Does claim-level verification improve hallucination detection over whole-answer approaches?
  2. How do embedding, NLI, and LLM-based verification compare in accuracy?
  3. Can adaptive verification reduce LLM calls while maintaining competitive accuracy?
  4. What is the trade-off between verification accuracy and computational cost?

βš™οΈ Configuration Reference

VariableDefaultDescription
OLLAMA_MODELqwen2.5:7bOllama model name
OLLAMA_BASE_URLhttp://localhost:11434Ollama API URL
EMBEDDING_MODELBAAI/bge-small-en-v1.5Sentence transformer model
TOP_K5Evidence chunks to retrieve
SIMILARITY_THRESHOLD0.70Embedding verification threshold
HIGH_SIMILARITY_THRESHOLD0.85Adaptive: skip NLI if above this
LOW_SIMILARITY_THRESHOLD0.40Adaptive: force NLI if below this
NLI_CONFIDENCE_THRESHOLD0.80Adaptive: call LLM if NLI below this
NLI_MODELcross-encoder/nli-deberta-v3-smallHuggingFace NLI model
BACKEND_URLhttp://localhost:8000Streamlit β†’ Backend URL
MLFLOW_TRACKING_URI./mlrunsMLflow tracking location

πŸ“ Adding Documents

Place .txt files in data/documents/. The system will:

  1. Split into paragraphs (~chunks)
  2. Embed with the configured sentence transformer
  3. Index into FAISS

Delete data/faiss_index/ to force a rebuild.


⚠️ Limitations

  • Requires Ollama running locally for LLM-dependent features
  • NLI and embedding models are downloaded on first run (~500MB)
  • Small benchmark dataset (7 questions, ~33 claims) β€” extend data/evaluation/benchmark.json for robust research
  • Adaptive thresholds are manually configured β€” future work could learn them

πŸ† Acknowledgements

Built as a research internship project exploring claim-level hallucination detection using adaptive verification strategies.