Skip to content

About

Full-stack LLM bias auditing platform for multi-model fairness, prompt perturbation, diagnostics, and performance comparison.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

LLM Bias Auditor

LLM Bias Auditor is a full-stack platform for comparing how language models respond to the same task when the prompt is systematically perturbed. It is designed to help developers, researchers, and AI product teams inspect fairness drift, semantic instability, stereotype risk, toxicity changes, and performance trade-offs across multiple LLM providers.

The current version is a production-shaped prototype with a FastAPI backend, Celery worker execution, Redis, Postgres, a React + TypeScript dashboard, custom model endpoint support, Docker Compose orchestration, and an nginx entrypoint.

Overview

Modern LLM applications can behave inconsistently when a prompt includes different demographic framing, role assumptions, tone qualifiers, or wording changes. LLM Bias Auditor turns that problem into a repeatable audit workflow:

  1. Submit a base prompt.
  2. Select one to six model slots.
  3. Choose preset Ollama/OpenAI/mock models or configure custom HTTP model endpoints.
  4. Apply controlled prompt perturbations.
  5. Generate baseline and perturbed responses.
  6. Score response changes with local and judge-backed metrics.
  7. Compare model-level risk, diagnostic flags, and runtime performance in a dashboard.

Key Features

  • Multi-model audits with one to six model comparison slots.
  • Preset provider support for Ollama, OpenAI, and mock execution.
  • Custom HTTP model support with GET and POST transports.
  • Transport templates for OpenAI chat, Ollama generate, and generic prompt APIs.
  • Adjustable generation controls: temperature, top-p, top-k, repetition penalty, presence penalty, frequency penalty, and max tokens.
  • Prompt perturbation engine for lexical substitutions, framing shifts, intensity modulation, counterfactual roles, demographic insertions, and contextual qualifiers.
  • Bias diagnostics for semantic divergence, fairness shift, stereotype risk, harmful assumptions, respectfulness drop, and toxicity shift.
  • Composite bias scoring with configurable metric weights.
  • Performance tracking for total duration, prompt token count, output token count, and tokens per second.
  • Celery-backed asynchronous execution for long-running cloud model audits.
  • Inline execution mode for local development and quick checks.
  • React dashboard with summary cards, radar/bar/line/heatmap visualizations, and perturbation-level inspection.
  • Dockerized backend, worker, frontend, Redis, Postgres, and nginx services.

Architecture

Bias Auditor Prototype/
|-- backend/
|   |-- app/
|   |   |-- api/              # FastAPI routes
|   |   |-- core/             # Settings and logging
|   |   |-- db/               # SQLAlchemy session/database setup
|   |   |-- models/           # Database models
|   |   |-- schemas/          # Pydantic request/response contracts
|   |   |-- services/         # Audit orchestration, LLM, metrics, perturbations
|   |   |-- utils/            # Shared utility code
|   |   `-- workers/          # Celery app and task definitions
|   |-- tests/                # Backend pytest suite
|   |-- Dockerfile
|   |-- main.py
|   `-- requirements.txt
|-- frontend/
|   |-- src/
|   |   |-- charts/           # Recharts visualizations
|   |   |-- components/       # Form, summary, inspector components
|   |   |-- pages/            # Application page shell
|   |   |-- services/         # API client and shared TypeScript types
|   |   `-- styles/           # Tailwind/global styles
|   |-- Dockerfile
|   |-- package.json
|   |-- tsconfig.json
|   `-- vite.config.ts
|-- nginx/
|   `-- default.conf          # Unified reverse proxy config
|-- .env.example              # Environment template
|-- docker-compose.yml        # Full-stack service orchestration
|-- build_v2.md               # Build/design notes
`-- README.md

Technology Stack

Layer Technology
Backend API FastAPI, Uvicorn, Pydantic
Background jobs Celery
Queue/result backend Redis
Database Postgres with SQLAlchemy
Model calls Ollama, OpenAI-compatible APIs, custom HTTP APIs, mock mode
Metrics NumPy, VADER sentiment, custom diagnostics, LLM judge scoring
Frontend React 19, TypeScript, Vite
Charts Recharts
Styling Tailwind CSS
Deployment Docker, Docker Compose, nginx
Tests pytest

How The Audit Pipeline Works

1. Request Intake

The frontend sends an audit request to POST /api/v1/audit. The request contains:

  • A base prompt.
  • A list of model selections.
  • A perturbation limit.
  • Generation parameters.

The backend validates the request with Pydantic schemas and stores an audit record in the database.

2. Execution Mode

The backend supports two execution modes:

  • ASYNC_MODE=celery: stores the job, marks it as running, and dispatches execution to Celery.
  • ASYNC_MODE=inline: executes the audit immediately inside the API process.

Celery mode is recommended for cloud-backed model audits because generation and judge calls can take time.

3. Prompt Perturbation

The perturbation engine generates controlled variants of the input prompt. Current perturbation types include:

  • lexical_substitution
  • framing_shift
  • intensity_modulation
  • counterfactual_role
  • demographic_insertion
  • contextual_qualifier

4. Model Generation

For each selected model, the system generates:

  • One baseline response to the original prompt.
  • One response per perturbed prompt.

Supported provider modes:

  • ollama: calls an Ollama-compatible /api/generate endpoint.
  • openai: calls an OpenAI-compatible /chat/completions endpoint.
  • custom_http: calls a user-provided endpoint using selected transport settings.
  • mock: returns deterministic mock responses for development and smoke testing.

5. Scoring And Diagnostics

The metrics engine compares baseline and perturbed responses using:

  • Sentiment shift.
  • Semantic divergence.
  • Emotion distance.
  • Fairness shift.
  • Stereotype risk.
  • Toxicity shift.
  • Harmful assumption score.
  • Respectfulness drop.
  • Composite bias score.

Semantic divergence uses embeddings when available. In Ollama mode, embeddings are requested through OLLAMA_EMBEDDING_BASE_URL; otherwise the system falls back to a deterministic mock embedding.

Judge-backed diagnostics use the configured judge model and request JSON-only scores. If judge parsing fails, the connector attempts a repair pass and then falls back to heuristic scoring.

6. Results And Visualization

The frontend polls GET /api/v1/audit/{audit_id} until the audit reaches completed or failed. Completed audits display:

  • Model-level bias score.
  • Baseline response.
  • Average metrics.
  • Highest-risk perturbation.
  • Perturbation-by-perturbation responses.
  • Diagnostic flags and rationale.
  • Runtime performance metrics.

API Reference

Health Check

GET /api/v1/health

Example response:

{
  "status": "healthy"
}

Submit Audit

POST /api/v1/audit
Content-Type: application/json

Example request:

{
  "prompt": "Evaluate the candidate's suitability for a leadership role and explain the reasoning clearly.",
  "models": [
    {
      "label": "Gemma 4B",
      "provider": "ollama",
      "source_type": "preset",
      "method": "POST",
      "transport": "ollama_generate",
      "model": "gemma3:4b",
      "prompt_param": "prompt",
      "model_param": "model",
      "headers": {}
    },
    {
      "label": "Ministral 3B",
      "provider": "ollama",
      "source_type": "preset",
      "method": "POST",
      "transport": "ollama_generate",
      "model": "ministral-3:3b",
      "prompt_param": "prompt",
      "model_param": "model",
      "headers": {}
    }
  ],
  "perturbation_limit": 6,
  "generation": {
    "temperature": 0.2,
    "top_p": 0.9,
    "top_k": 40,
    "repetition_penalty": 1.0,
    "presence_penalty": 0.0,
    "frequency_penalty": 0.0,
    "max_tokens": 512
  }
}

Example response in Celery mode:

{
  "audit_id": "generated-audit-id",
  "status": "running",
  "mode": "celery",
  "results": null
}

Fetch Audit

GET /api/v1/audit/{audit_id}

The response includes the audit status, prompt, model names, and results when available.

Model Configuration

Preset Ollama Models

The frontend currently exposes these Ollama presets:

  • gemma3:4b
  • ministral-3:3b
  • ministral-3:8b
  • gemma3:12b
  • ministral-3:14b

Recommended routine comparison:

gemma3:4b, ministral-3:3b

Larger models can be used, but they are slower and may cause long audit durations.

Preset OpenAI Models

The frontend exposes these OpenAI-style presets:

  • gpt-4o-mini
  • gpt-4o
  • gpt-4.1-mini
  • gpt-4.1

Set OPENAI_API_KEY and confirm OPENAI_BASE_URL before using OpenAI mode.

Custom HTTP Models

Custom HTTP slots support:

  • GET or POST.
  • API key header customization.
  • Optional bearer-style key prefix.
  • openai_chat, ollama_generate, or generic_prompt payload shapes.
  • Custom prompt and model parameter names.
  • Dot-path response extraction such as choices.0.message.content.

Example custom OpenAI-compatible model:

{
  "label": "Internal model",
  "provider": "custom_http",
  "source_type": "custom_http",
  "method": "POST",
  "transport": "openai_chat",
  "model": "internal-chat-model",
  "endpoint_url": "https://api.example.com/v1/chat/completions",
  "api_key": "your-key",
  "api_key_header": "Authorization",
  "api_key_prefix": "Bearer",
  "response_path": "choices.0.message.content",
  "prompt_param": "prompt",
  "model_param": "model",
  "headers": {}
}

Environment Variables

Create a .env file from the template:

Copy-Item .env.example .env -Force

For macOS/Linux:

cp .env.example .env

Important variables:

Variable Purpose
APP_NAME Application name used by backend settings.
ENVIRONMENT development, staging, or production.
API_PREFIX API route prefix, default /api/v1.
DATABASE_URL SQLAlchemy database URL.
REDIS_URL Celery broker URL.
RESULT_BACKEND Celery result backend URL.
ASYNC_MODE celery for background jobs or inline for direct execution.
LLM_MODE Default provider mode: ollama, openai, or mock.
OPENAI_API_KEY API key for OpenAI-compatible providers.
OPENAI_BASE_URL Base URL for OpenAI-compatible chat completions.
OLLAMA_BASE_URL Base URL for Ollama generation and judge calls.
OLLAMA_API_KEY Optional hosted Ollama API key.
OLLAMA_EMBEDDING_BASE_URL Base URL for embedding calls, usually local Ollama.
EMBEDDING_MODEL_NAME Embedding model name, default nomic-embed-text:latest.
JUDGE_MODEL_NAME Judge model used for structured bias diagnostics.
OLLAMA_TIMEOUT_SECONDS Timeout for generation and embeddings.
OLLAMA_JUDGE_TIMEOUT_SECONDS Timeout for judge model calls.
JWT_SECRET Security secret; replace before deployment.
RATE_LIMIT_PER_MINUTE Planned request limit setting.
COMPOSITE_ALPHA/BETA/GAMMA Composite score weights for local metrics.
JUDGE_DELTA_WEIGHT Composite score weight for fairness shift.
STEREOTYPE_WEIGHT Composite score weight for stereotype risk.
TOXICITY_WEIGHT Composite score weight for toxicity shift.
VITE_API_BASE_URL Frontend API base URL.

Quick Start With Docker

Prerequisites:

  • Docker Desktop or Docker Engine.
  • Docker Compose.
  • Optional Ollama/OpenAI credentials depending on provider mode.

Start the full stack:

Copy-Item .env.example .env -Force
docker compose up --build

Open:

  • Frontend dashboard: http://localhost:5173
  • Backend API docs: http://localhost:8000/docs
  • Unified nginx entrypoint: http://localhost

Stop the stack:

docker compose down

Rebuild changed services:

docker compose up -d --build --force-recreate backend worker frontend

Reset the Postgres volume only when you intentionally want to delete local audit data:

docker compose down -v

Local Development

Backend

From the repository root:

cd backend
python -m venv .venv
.venv\Scripts\activate
pip install -r requirements.txt
uvicorn main:app --reload --host 0.0.0.0 --port 8000

For macOS/Linux activation:

source .venv/bin/activate

If you run the backend outside Docker, update .env so DATABASE_URL and REDIS_URL point to reachable services.

Worker

Run the Celery worker from backend/:

celery -A app.workers.celery_app.celery_app worker --loglevel=info

The worker must use the same .env configuration as the backend.

Frontend

cd frontend
npm install
npm run dev

Production build:

npm run build

Preview production build:

npm run preview

Verification

Run backend tests:

cd backend
pytest

Run frontend build verification:

cd frontend
npm run build

Run a lightweight smoke test without external providers:

  1. Set LLM_MODE=mock.
  2. Set ASYNC_MODE=inline or keep Celery running.
  3. Start the backend/frontend.
  4. Submit an audit with the mock provider.
  5. Confirm that GET /api/v1/audit/{audit_id} returns completed.

Troubleshooting

Problem Likely Cause Fix
UI stays on running Long cloud model execution or worker issue Check worker logs and model endpoint latency.
Audit fails with provider error Invalid API key, URL, model name, or response path Verify .env, model slot settings, and target API response shape.
Semantic scores look weak Embedding endpoint unavailable Start local Ollama and pull nomic-embed-text:latest, or accept mock embedding fallback.
Docker compose fails immediately Docker engine is not running Start Docker Desktop and rerun Compose.
Frontend cannot reach API Wrong VITE_API_BASE_URL Set it to http://localhost:8000/api/v1 for local Compose usage.
Large models take too long Hosted/local model size is high Use gemma3:4b and ministral-3:3b for faster routine audits.

Security And Deployment Notes

This project is not ready for unrestricted public exposure without additional hardening.

Before production deployment:

  • Replace JWT_SECRET with a strong secret stored outside source control.
  • Move provider API keys to a secret manager.
  • Add authentication and authorization around audit endpoints.
  • Enforce rate limiting at the API gateway or reverse proxy.
  • Use managed Postgres/Redis or hardened infrastructure.
  • Configure HTTPS at the edge.
  • Add CI checks for backend tests and frontend builds.
  • Review stored prompts and responses for privacy requirements.

Current Limitations

  • API routes are currently open and should be protected before internet-facing use.
  • Test coverage is focused primarily on metrics and should be expanded.
  • Hosted model latency can make large audits slow.
  • Custom HTTP integrations depend on the target API returning JSON and a predictable response field.
  • Judge-backed scoring quality depends on the selected judge model and its ability to return valid structured JSON.

Recommended Next Improvements

  • Add GitHub Actions for backend tests and frontend build.
  • Add authentication for audit creation and retrieval.
  • Add pagination/search for historical audits.
  • Add export support for JSON/CSV audit reports.
  • Expand tests for API routes, worker tasks, custom connectors, and frontend behavior.
  • Add deployment-specific Compose files for staging and production.

License

No license file is currently included in this local project snapshot. Add a license before publishing or accepting external contributions.

About

Full-stack LLM bias auditing platform for multi-model fairness, prompt perturbation, diagnostics, and performance comparison.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages