By **Aman Kumar (@aman179102)* — aman179102.netlify.app · GitHub*
When teams move an LLM feature from a weekend prototype to production, three operational problems show up almost immediately:
- Data leakage in prompts. Support agents, internal tools, and end users paste API keys, JWTs, customer emails, credit card numbers, and national IDs straight into chat inputs — and your backend forwards them verbatim to an external inference provider.
- Prompt injection & jailbreaks. User-controlled text (or retrieved tool/RAG content) overrides system instructions, smuggles role delimiters (
<|im_start|>,[INST]), or tries to exfiltrate system prompts and environment variables. - Unbounded, unattributed token spend. A single tenant or runaway retry loop can burn through your monthly OpenAI/Gemini budget before anyone notices.
You can bolt on a closed-source SaaS AI gateway, but routing unredacted sensitive prompts through yet another third-party cloud defeats the purpose for many security-conscious teams.
That's why I built AegisLLM — an MIT-licensed, self-hosted OpenAI-compatible reverse proxy, CLI scanner, and live observability dashboard written in Python.
Drop-In Integration: One base_url Change
AegisLLM implements POST /v1/chat/completions and GET /v1/models, so any codebase using the official OpenAI Python/JS SDK can adopt it by changing a single base_url and passing an optional X-Aegis-Tenant header:
from openai import OpenAI client = OpenAI( base_url="http://127.0.0.1:8080/v1", api_key="any-placeholder-if-server-holds-key", default_headers={"X-Aegis-Tenant": "payments-team"}, ) resp = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Summarize ticket for user@company.com"}], ) print(resp.choices[0].message.content) Because it speaks the OpenAI Chat Completions wire format, it sits cleanly in front of OpenAI, Gemini (OpenAI-compatible endpoint), Groq, Together, Ollama, or vLLM.
Inside the 4-Stage Request Pipeline
Every POST /v1/chat/completions request in aegis_llm/app.py passes through four deterministic stages before returning a response:
Client Request (X-Aegis-Tenant) │ ▼ [1. Per-Tenant Budget Gate] ──(spent >= budget)──▶ 429 aegis_budget_exceeded │ ▼ [2. Prompt-Injection Firewall] ──(flagged & mode=block)──▶ 403 aegis_prompt_injection │ ▼ [3. PII & Secret Redactor] ──(replaces with <REDACTED_*_N>) │ ▼ [4. Upstream Dispatch + SQLite Audit & Cost Ledger] ──▶ 200 + X-Aegis-* headers 1. Per-Tenant Token & USD Budget Caps (aegis_llm/ledger.py)
AegisLLM tracks cumulative USD spend per X-Aegis-Tenant header (defaulting to "default" and $25.00 via AEGIS_DEFAULT_BUDGET_USD) in a thread-safe SQLite database (aegis_ledger.db, guarded by threading.Lock()).
Before a request ever touches the firewall or upstream LLM, db.get_budget_status(tenant) checks spent_usd >= budget_usd. If exceeded, AegisLLM logs a blocked_budget event and immediately returns HTTP 429 with code: "aegis_budget_exceeded".
Budgets can be updated dynamically at runtime via the REST API:
curl -X POST http://127.0.0.1:8080/api/tenants/payments-team/budget \ -H "Content-Type: application/json" \ -d '{"budget_usd": 50.0}' 2. Prompt-Injection & Jailbreak Firewall (aegis_llm/firewall.py)
inspect_messages() scans user and tool messages (explicitly skipping trusted role == "system" messages) against five deterministic rules:
| Rule ID | Severity | What It Catches |
|---|---|---|
INJ-001 | 90 | Instruction override attempts (ignore previous instructions, override system policies) |
INJ-002 | 95 | System prompt exfiltration (reveal system prompt, dump developer message) |
INJ-003 | 85 | Jailbreak / unrestricted persona framing (you are now DAN, developer mode enabled) |
INJ-004 | 80 | Role / delimiter smuggling (`<\ |
{% raw %}INJ-005 | 85 | Credential or environment exfiltration (dump /etc/passwd, process.env, os.environ, .env) |
Controlled via AEGIS_INJECTION_MODE:
-
block(default): returns HTTP403(aegis_prompt_injection) withX-Aegis-Risk-Scoreandmatched_rules. -
flag: logs the risk score and matched rules to the audit trail while allowing the request through. -
off: bypasses firewall enforcement.
3. Deterministic PII & Secret Redaction (aegis_llm/redactor.py)
If AEGIS_REDACT_PII=1 (default), redact_messages() sanitizes both plain-string content and multimodal list-of-parts {"type": "text", "text": ...} blocks before the payload leaves your network.
It covers 13 high-signal categories:
- Secrets & Keys: PEM
PRIVATE_KEYblocks,OPENAI_KEY(sk-/sk-proj-/sk-svcacct-/sk-admin-),GITHUB_TOKEN(ghp_,gho_,ghu_,ghs_,ghr_,github_pat_),AWS_ACCESS_KEY(AKIA/ASIA),GOOGLE_API_KEY(AIza...),SLACK_TOKEN(xox[baprs]-...), andJWTtokens. - PII & Financial / National IDs:
EMAIL,PHONE(Indian+91and international formats),SSN_US,PAN_IN(Indian PAN),AADHAAR_IN(Indian Aadhaar), andCREDIT_CARD.
To avoid corrupting legitimate 13–19 digit order or tracking IDs, credit card candidates are validated with a Luhn checksum (_luhn_valid) before redaction. Matched values are replaced with indexed, deduplicated placeholders like <REDACTED_EMAIL_1> or <REDACTED_OPENAI_KEY_1>.
4. Upstream Dispatch, Cost Estimation & Live Dashboard
After sanitization, AegisLLM forwards the payload via httpx.AsyncClient to AEGIS_UPSTREAM_URL (or generates a deterministic local response in --mock mode).
Token usage from the upstream response (with a character-length fallback estimator if usage is omitted) is priced against DEFAULT_MODEL_PRICING in aegis_llm/config.py (supporting gpt-4o, gpt-4o-mini, gpt-4.1, gpt-4.1-mini, gemini-2.5-flash, gemini-2.5-pro, claude-3-7-sonnet, llama-3.3-70b, and aegis-mock, with a fallback rate).
Every response includes observability headers:
X-Aegis-Tenant-
X-Aegis-Action(allowed,redacted_allowed,flagged_allowed,blocked_injection,blocked_budget) X-Aegis-RedactionsX-Aegis-Cost-USDX-Aegis-Latency-Ms
And at GET /, AegisLLM serves a self-contained dark-mode dashboard polling /api/stats, /api/tenants, and /api/logs every 4 seconds.
CLI Scanner & Local Mock Mode
You can test AegisLLM locally with zero API keys:
pip install -e . aegis-llm serve --mock --port 8080 Or run the built-in CLI scanner directly against any string (exits with status code 2 if an injection is flagged, making it easy to wire into CI/CD or pre-commit checks):
aegis-llm scan "Email aman@example.com with key sk-proj-abc12345678901234567890" Docker Compose is also included (docker compose up --build).
Why Deterministic Rules + SQLite Instead of Heavy ML?
A deliberate architectural choice in AegisLLM v0.1.0 is keeping the dependency footprint minimal: FastAPI, Uvicorn, httpx, Pydantic, and Python's standard library.
- Zero GPU / model-weight overhead: No downloading 500MB NER models or running a sidecar classifier just to redact an AWS key or email address.
- Zero external infra required: SQLite gives you persistent budgets and audit trails out of the box in a single container.
- Honest trade-off: Deterministic regex + Luhn validation catches structured secrets, PII, and known injection patterns reliably, but it won't catch subtle semantic jailbreaks or unstructured PII. For many teams, having a fast, zero-dependency first line of defense in front of every LLM call is the 80/20 win they were missing.
Check out the code on GitHub: github.com/aman179102/aegis-llm, or learn more about my work at aman179102.netlify.app.

