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.
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:
- Submit a base prompt.
- Select one to six model slots.
- Choose preset Ollama/OpenAI/mock models or configure custom HTTP model endpoints.
- Apply controlled prompt perturbations.
- Generate baseline and perturbed responses.
- Score response changes with local and judge-backed metrics.
- Compare model-level risk, diagnostic flags, and runtime performance in a dashboard.
- Multi-model audits with one to six model comparison slots.
- Preset provider support for Ollama, OpenAI, and mock execution.
- Custom HTTP model support with
GETandPOSTtransports. - 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.
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
| 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 |
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.
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.
The perturbation engine generates controlled variants of the input prompt. Current perturbation types include:
lexical_substitutionframing_shiftintensity_modulationcounterfactual_roledemographic_insertioncontextual_qualifier
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/generateendpoint.openai: calls an OpenAI-compatible/chat/completionsendpoint.custom_http: calls a user-provided endpoint using selected transport settings.mock: returns deterministic mock responses for development and smoke testing.
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.
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.
GET /api/v1/healthExample response:
{
"status": "healthy"
}POST /api/v1/audit
Content-Type: application/jsonExample 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
}GET /api/v1/audit/{audit_id}The response includes the audit status, prompt, model names, and results when available.
The frontend currently exposes these Ollama presets:
gemma3:4bministral-3:3bministral-3:8bgemma3:12bministral-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.
The frontend exposes these OpenAI-style presets:
gpt-4o-minigpt-4ogpt-4.1-minigpt-4.1
Set OPENAI_API_KEY and confirm OPENAI_BASE_URL before using OpenAI mode.
Custom HTTP slots support:
GETorPOST.- API key header customization.
- Optional bearer-style key prefix.
openai_chat,ollama_generate, orgeneric_promptpayload 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": {}
}Create a .env file from the template:
Copy-Item .env.example .env -ForceFor macOS/Linux:
cp .env.example .envImportant 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. |
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 --buildOpen:
- Frontend dashboard:
http://localhost:5173 - Backend API docs:
http://localhost:8000/docs - Unified nginx entrypoint:
http://localhost
Stop the stack:
docker compose downRebuild changed services:
docker compose up -d --build --force-recreate backend worker frontendReset the Postgres volume only when you intentionally want to delete local audit data:
docker compose down -vFrom 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 8000For macOS/Linux activation:
source .venv/bin/activateIf you run the backend outside Docker, update .env so DATABASE_URL and REDIS_URL point to reachable services.
Run the Celery worker from backend/:
celery -A app.workers.celery_app.celery_app worker --loglevel=infoThe worker must use the same .env configuration as the backend.
cd frontend
npm install
npm run devProduction build:
npm run buildPreview production build:
npm run previewRun backend tests:
cd backend
pytestRun frontend build verification:
cd frontend
npm run buildRun a lightweight smoke test without external providers:
- Set
LLM_MODE=mock. - Set
ASYNC_MODE=inlineor keep Celery running. - Start the backend/frontend.
- Submit an audit with the
mockprovider. - Confirm that
GET /api/v1/audit/{audit_id}returnscompleted.
| 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. |
This project is not ready for unrestricted public exposure without additional hardening.
Before production deployment:
- Replace
JWT_SECRETwith 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.
- 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.
- 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.
No license file is currently included in this local project snapshot. Add a license before publishing or accepting external contributions.