Stop AI Token Waste Before, During, and After Every LLM Call
aurex-sdk is an open-source, in-process Python and Node.js SDK that shields prompt caches, circuit-breaks runaway agent spend in real time, and gates Pull Requests on verified cost per completed task—with 0 ms proxy latency and zero raw prompts leaving your servers.
Why Aurex Exists: 23 Real-World GitHub Issues & Reddit Reports
Passive observability dashboards show yesterday's token bill after the money is gone, while proxy gateways add network hops and require routing sensitive prompts outside your VPC. Across frontier-lab SDK trackers and engineering forums, production teams hit six recurring cost traps:
- Silent cache invalidation & TTL rewrites: Changing a timestamp at character 20 or shuffling JSON tool keys wipes out 50%–90% prefix-cache discounts, while resuming an Anthropic session past 5 minutes triggers a
1.25xcache-write surcharge. - The 200k 2x pricing cliff & missing cloud spend caps: Sending
200,001input tokens to Claude or Gemini doubles the price of the entire request, and cloud budget alerts arrive hours after runaway spend. - Hidden reasoning tokens, agent loops & HTTP-200 soft failures: Reasoning models burn thousands of internal thinking tokens billed at output rates, nested retries multiply
429storms6x, and empty or whitespace-looped HTTP200 OKresponses still bill full price.
Number of Tracked Issues per Issue Label
Click any bar to filter the 23 linked GitHub issues and Reddit engineering threads below.
| Source & Link | Reported Problem | Labels | Aurex Fix |
|---|
What Aurex Does: One 3-Stage Pipeline Around Every Call
Instead of acting as a remote proxy, Aurex patches your installed provider SDKs directly in memory (<0.1 ms overhead) and connects three stages around every request:
Before the Call (Stage 1)
Deterministically sorts JSON keys in tools and schemas, hashes prompt layers to pinpoint the exact character index breaking your prefix cache, flags >5m Anthropic TTL gaps, and warns before crossing the 200,000-token 2x cliff. Any runtime hint appends at the tail so index 0 caches stay warm.
During the Call (Stage 2)
Isolates sessions via workflow_id, async context, or active OpenTelemetry trace_id; shares live session/minute dollar caps across workers via optional Redis; clamps hidden thinking budgets; injects stream_options.include_usage; logs aborted streams in try...finally; and raises AurexBlocked on loops.
After the Call + CI (Stage 3)
Classifies empty thinking-exhausted outputs and \n\n\n JSON grammar loops as unfulfilled_spend, joins spend with mark_success() to compute true cost per completed task, enforces per-tenant margin downgrades, and posts cost regression diffs on Pull Requests.
How to Use It (Step-by-Step)
Step 1: Install the SDK
pip install aurex-sdk
# Optional multi-worker Redis & OpenTelemetry extras:
pip install "aurex-sdk[redis,otel]"
npm install aurex-sdk
# Optional multi-worker Redis & OpenTelemetry peers:
npm install ioredis @opentelemetry/api
Step 2: Initialize Once at Startup & Mark Task Outcomes
Keep your existing provider client calls unchanged. Aurex automatically strips workflow_id / workflowId and tags before requests hit the network wire so upstream APIs never return HTTP 400 validation errors.
from aurex_sdk import AurexAuditor, AurexBlocked, AurexConfig, patch_all
import openai
auditor = AurexAuditor(
AurexConfig(
redis_url=None, # Or "redis://localhost:6379/0" (also reads AUREX_REDIS_URL)
enable_loop_guard=True,
budget_guard={
"max_cost_per_session": 1.50,
"max_cost_per_minute": 15.00,
"max_context_tokens": 195000,
"max_thinking_tokens": 4096,
"on_budget_exceeded": "throw",
},
resilience={"enabled": True, "mode": "enforce", "max_attempts": 2},
)
)
patch_all(auditor)
client = openai.OpenAI()
try:
resp = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize support ticket #42."}],
workflow_id="ticket-42",
tags={"tenant_id": "acme-corp"},
)
auditor.mark_success("ticket-42")
except AurexBlocked as err:
print("Circuit breaker tripped:", err.reason)
finally:
auditor.flush()
import { AurexAuditor, AurexBlocked } from "aurex-sdk";
import OpenAI from "openai";
const auditor = AurexAuditor.getInstance({
redisUrl: process.env.AUREX_REDIS_URL,
enableLoopGuard: true,
budgetGuard: {
maxCostPerSession: 1.5,
maxCostPerMinute: 15.0,
maxContextTokens: 195000,
maxThinkingTokens: 4096,
onBudgetExceeded: "throw",
},
resilience: { enabled: true, mode: "enforce", maxAttempts: 2 },
});
await auditor.patchAll();
auditor.instrument(OpenAI); // Bundler-safe hook for Next.js / Vite / Vitest
const client = new OpenAI();
try {
const resp = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Summarize support ticket #42." }],
workflowId: "ticket-42",
tags: { tenant_id: "acme-corp" },
} as any);
auditor.markSuccess("ticket-42");
} catch (err) {
if (err instanceof AurexBlocked) console.error("Circuit breaker tripped:", err.reason);
} finally {
await auditor.flushAndWait();
}
Step 3: Audit Locally, Gate Pull Requests in CI, or Use Zero-Code Hook
# Inspect local ledger waste, cache breaks & cost_per_success
aurex audit
# Diff PR branch ledger against main baseline in GitHub Actions
aurex ci --ledger .aurex/ledger.jsonl --baseline main_ledger.jsonl --github-comment --fail-on-regression
# Optional zero-code startup hook (no application imports required)
aurex install-hook && AUREX_ENABLED=1 python app.py
# Inspect local ledger waste, cache breaks & costPerSuccess
npx aurex audit
# Diff PR branch ledger against main baseline in GitHub Actions
npx aurex ci --ledger=.aurex/ledger.jsonl --baseline=main_ledger.jsonl --github-comment --fail-on-regression
# Optional zero-code startup hook
npx aurex install-hook && source .env.aurex && AUREX_ENABLED=1 node server.js
Multi-Provider Integration: One Shared Budget Across Every Model
A single patch_all(auditor) / await auditor.patchAll() call intercepts native SDKs and OpenAI-compatible gateways side by side—sharing one unified workflow_id session cap across OpenAI, Anthropic Claude, Google Gemini, LiteLLM, OpenRouter, IBM watsonx, NVIDIA NIM, Groq, Together AI, Fireworks AI, Hugging Face, and local Ollama ($0.00):
import os
from aurex_sdk import AurexAuditor, AurexConfig, patch_all
import openai
import anthropic
from google import genai
import litellm
import ollama
from huggingface_hub import InferenceClient
# 1. Initialize once — enforces one shared $2.50 session cap across EVERY provider below
auditor = AurexAuditor(
AurexConfig(
enable_loop_guard=True,
budget_guard={"max_cost_per_session": 2.50, "max_thinking_tokens": 4096, "on_budget_exceeded": "throw"},
)
)
patch_all(auditor)
wf = "pipeline-order-108"
# 2. Anthropic Claude (5m/1h prompt caching, ThinkingBlock & >200k cliff guard)
claude = anthropic.Anthropic()
claude.messages.create(
model="claude-sonnet-4",
max_tokens=512,
messages=[{"role": "user", "content": "Plan the order validation steps."}],
workflow_id=wf,
)
# 3. Google Gemini (thoughts_token_count & >200k cliff guard)
gemini = genai.Client()
gemini.models.generate_content(
model="gemini-2.5-flash",
contents="Extract structured shipping metadata.",
workflow_id=wf,
)
# 4. OpenAI + OpenAI-Compatible Gateways (Groq, OpenRouter, NVIDIA NIM, IBM watsonx, Together, Fireworks)
openai_client = openai.OpenAI()
groq_client = openai.OpenAI(base_url="https://api.groq.com/openai/v1", api_key=os.getenv("GROQ_API_KEY"))
openrouter_client = openai.OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.getenv("OPENROUTER_API_KEY"))
nvidia_nim_client = openai.OpenAI(base_url="https://integrate.api.nvidia.com/v1", api_key=os.getenv("NVIDIA_API_KEY"))
watsonx_client = openai.OpenAI(
base_url=f"https://us-south.ml.cloud.ibm.com/ml/v1",
api_key=os.getenv("WATSONX_API_KEY"),
)
together_client = openai.OpenAI(base_url="https://api.together.xyz/v1", api_key=os.getenv("TOGETHER_API_KEY"))
fireworks_client = openai.OpenAI(base_url="https://api.fireworks.ai/inference/v1", api_key=os.getenv("FIREWORKS_API_KEY"))
for client, model_id in [
(openai_client, "gpt-4o-mini"),
(groq_client, "llama-3.3-70b-versatile"),
(openrouter_client, "anthropic/claude-3-5-haiku"),
(nvidia_nim_client, "meta/llama-3.3-70b-instruct"),
(watsonx_client, "meta-llama/llama-3-3-70b-instruct"),
(together_client, "meta-llama/Llama-3.3-70B-Instruct-Turbo"),
(fireworks_client, "accounts/fireworks/models/llama-v3p3-70b-instruct"),
]:
client.chat.completions.create(
model=model_id,
messages=[{"role": "user", "content": "Verify line-item tax rules."}],
workflow_id=wf,
)
# 5. LiteLLM Unified Router (watsonx, NVIDIA NIM, AWS Bedrock, Vertex AI, Azure)
litellm.completion(
model="watsonx/meta-llama/llama-3-3-70b-instruct",
messages=[{"role": "user", "content": "Cross-check regional compliance."}],
workflow_id=wf,
)
# 6. Local Ollama ($0.00 local billing) & Hugging Face InferenceClient
ollama.Client().chat(model="llama3.3", messages=[{"role": "user", "content": "Draft local summary."}], workflow_id=wf)
InferenceClient().chat_completion(model="Qwen/Qwen2.5-72B-Instruct", messages=[{"role": "user", "content": "Tag intent."}], workflow_id=wf)
auditor.mark_success(wf)
auditor.flush()
import { AurexAuditor } from "aurex-sdk";
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";
import { GoogleGenAI } from "@google/genai";
import { Ollama } from "ollama";
import { HfInference } from "@huggingface/inference";
// 1. Initialize once — enforces one shared $2.50 session cap across EVERY provider below
const auditor = AurexAuditor.getInstance({
enableLoopGuard: true,
budgetGuard: { maxCostPerSession: 2.5, maxThinkingTokens: 4096, onBudgetExceeded: "throw" },
});
await auditor.patchAll();
auditor.instrument(OpenAI, Anthropic, GoogleGenAI, Ollama, HfInference);
const wf = "pipeline-order-108";
// 2. Anthropic Claude & Google Gemini
const claude = new Anthropic();
await claude.messages.create({
model: "claude-sonnet-4",
max_tokens: 512,
messages: [{ role: "user", content: "Plan the order validation steps." }],
workflowId: wf,
} as any);
const gemini = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
await gemini.models.generateContent({
model: "gemini-2.5-flash",
contents: "Extract structured shipping metadata.",
workflowId: wf,
} as any);
// 3. OpenAI, Groq, OpenRouter, NVIDIA NIM, IBM watsonx, Together AI, Fireworks AI & LiteLLM Proxy
const providers: Array<[OpenAI, string]> = [
[new OpenAI(), "gpt-4o-mini"],
[new OpenAI({ baseURL: "https://api.groq.com/openai/v1", apiKey: process.env.GROQ_API_KEY }), "llama-3.3-70b-versatile"],
[new OpenAI({ baseURL: "https://openrouter.ai/api/v1", apiKey: process.env.OPENROUTER_API_KEY }), "anthropic/claude-3-5-haiku"],
[new OpenAI({ baseURL: "https://integrate.api.nvidia.com/v1", apiKey: process.env.NVIDIA_API_KEY }), "meta/llama-3.3-70b-instruct"],
[new OpenAI({ baseURL: "https://us-south.ml.cloud.ibm.com/ml/v1", apiKey: process.env.WATSONX_API_KEY }), "meta-llama/llama-3-3-70b-instruct"],
[new OpenAI({ baseURL: "https://api.together.xyz/v1", apiKey: process.env.TOGETHER_API_KEY }), "meta-llama/Llama-3.3-70B-Instruct-Turbo"],
[new OpenAI({ baseURL: "https://api.fireworks.ai/inference/v1", apiKey: process.env.FIREWORKS_API_KEY }), "accounts/fireworks/models/llama-v3p3-70b-instruct"],
];
for (const [client, model] of providers) {
await client.chat.completions.create({
model,
messages: [{ role: "user", content: "Verify line-item tax rules." }],
workflowId: wf,
} as any);
}
// 4. Local Ollama ($0.00 local billing) & Hugging Face
const localOllama = new Ollama({ host: "http://127.0.0.1:11434" });
await localOllama.chat({ model: "llama3.3", messages: [{ role: "user", content: "Draft local summary." }], workflowId: wf } as any);
const hf = new HfInference(process.env.HF_TOKEN);
await hf.chatCompletion({ model: "Qwen/Qwen2.5-72B-Instruct", messages: [{ role: "user", content: "Tag intent." }], workflowId: wf } as any);
auditor.markSuccess(wf);
await auditor.flushAndWait();
Integrate in 30 Seconds Using llms.txt with AI Coding Assistants
Aurex ships a compact, machine-readable llms.txt and AGENTS.md specification so coding assistants (Claude Code, Cursor, Antigravity, GitHub Copilot, Windsurf, and Codex) wire Aurex into your existing codebase without hallucinating config keys or rewriting your LLM calls:
- One-Prompt Drop-In (Claude Code, Antigravity, Copilot, Codex, Cursor Chat): Paste the prompt below—your coding agent fetches
llms.txt, finds your entrypoint (FastAPIlifespan, Express/Next.jsinstrumentation.ts, Celery, or LangGraph), and wires Aurex cleanly in one pass. - Cursor / Windsurf
@DocsIndexing: Addhttps://raw.githubusercontent.com/bhav09/aurex-sdk/main/llms.txtunder Settings → Features → Docs as@Aurex, then ask@Aurex protect our LLM routes and background workers. - Repo-Local Rule File (Offline / CI Agents): Save a local copy in your repo root so every developer's coding agent inherits the exact rules automatically.
Read https://raw.githubusercontent.com/bhav09/aurex-sdk/main/llms.txt and integrate aurex-sdk into our existing codebase:
1. Initialize AurexAuditor once at application startup and call patch_all (plus auditor.instrument(...) if bundled TypeScript). Do NOT rewrite our existing LLM client calls.
2. Enable enable_loop_guard and set budget_guard caps (max_cost_per_session, max_context_tokens=195000, max_thinking_tokens=4096).
3. Propagate workflow_id per request/job (via call kwargs or aurex_context / aurexContext), call mark_success on completion, exclude AurexBlocked from retry decorators, and flush on shutdown.
# Download llms.txt into your repo for Claude Code, Cursor, Antigravity & Codex
curl -sL https://raw.githubusercontent.com/bhav09/aurex-sdk/main/llms.txt -o .aurex-llms.txt
# Or run with Claude Code directly from your terminal:
claude "Read .aurex-llms.txt and integrate aurex-sdk into this repository without rewriting existing LLM calls."
Open-Source Agent Benchmarks: OpenHands, BrowserGym, tau-bench, terminal-bench & SWE-agent
Aurex has been benchmarked end-to-end across six open-source agent ecosystems (terminal-bench 8.9/10, tau-bench 8.8/10, OpenHands 8.7/10, SWE-agent 8.6/10, BrowserGym 8.4/10, and LangGraph) across Claude, GPT, Gemini, NVIDIA NIM (Nemotron), LiteLLM, and local Ollama (Llama)—with healthy status and 0 SDK drift under AUREX_STRICT_DRIFT=1.
| Benchmark | Agent Archetype | Score | Hot-Path p50 | Verified Waste Caught & Prevented |
|---|---|---|---|---|
| terminal-bench | Linux Bash (LiteLLM + Terminus2 / MCPTerminus) |
8.9 / 10 | 0.080 ms | Blocked 336k-token dump pre-call (+$1.01 saved), clamped 16k → 1k thinking budget (including extra_body.reasoning_budget), bypassed 3x3 tenacity sleep, caught 64/64 reasoning-starvation HTTP 200 soft failures, and gated PR in aurex ci (+9,280%). |
| tau-bench | Multi-Actor Retail (LiteLLM + 15 tools + User Sim) |
8.8 / 10 | < 0.50 ms | Isolated -agent vs -user workflow_id dual system caches, clamped 8k → 1k thinking budget, thread-isolated concurrent session caps, and caught 48/48 empty reasoning-starvation calls (aurex ci +3,516%). |
| OpenHands | Coding Agent (OpenAI + file_editor) |
8.7 / 10 | 0.268 ms | Kept reordered tool schemas cache-warm, pinpointed system timestamp break at char 590, blocked 360k-token cliff pre-call (+$1.08 saved), and caught mid-stream aborts + JSON grammar loops (aurex ci +861%). |
| SWE-agent | Autonomous Repo Solver (str_replace_editor) |
8.6 / 10 | < 0.30 ms | Granted multi-file discovery headroom while halting stuck non-progressive tool loops—preventing 1.5M–5M+ wasted tokens across 40k–120k-context repo trajectories. |
| BrowserGym | Multimodal Web (OpenAI + Vision PNG / DOM) |
8.4 / 10 | 0.558 ms | Blocked 480k-token unpruned DOM pre-call (+$1.44 saved where native callback only checked post-call), boosted cacheable prefix 64.9x, and blocked stuck disabled-button clicks in 0.109 ms. |
Live End-to-End NVIDIA NIM (Nemotron) Runs — 4/4 Solved for < $0.01 Combined ($0.00 Wasted)
| Benchmark | Live Task Executed | Result | Wall Time | Input / Reasoning Tokens | Live Cost |
|---|---|---|---|---|---|
| OpenHands | Inspect @openhands/agent-canvas via file_editor |
Solved | 1.43 s | 1,077 / 99 | $0.000186 |
| BrowserGym | 3-step ExpArgs.run() web checkout episode |
Solved (reward=1.0) | 10.01 s | 3,843 / 1,533 | $0.001206 |
| tau-bench | Retail Task 0 (16 multi-actor messages) | Solved (Pass^1=1.0) | 17.08 s | 41,088 / 1,332 | $0.003053 |
| terminal-bench | analyze-access-logs (2,000 log lines, 7 bash cmds) |
Solved (is_resolved=True) | 15.41 s | 25,488 / 874 | $0.002989 |
Configuration, Providers & Typed Exceptions
Python uses snake_case keys while Node.js uses camelCase keys with identical behavior across both runtimes.
| Python / Node.js Key | Default | What It Controls |
|---|---|---|
max_cost_per_session / maxCostPerSession |
None |
Hard USD cap per workflow_id (downgrades at 80%, blocks with AurexBlocked at 100%). |
max_cost_per_minute / maxCostPerMinute |
None |
Sliding 60-second USD cap across calls (shared across pods when Redis is configured). |
max_context_tokens / maxContextTokens |
None |
Pre-call input cap; set to 195000 to stop requests before 200k 2x pricing cliffs. |
max_thinking_tokens / maxThinkingTokens |
None |
Clamps thinking.budget_tokens / Gemini thinking budgets and lowers reasoning_effort. |
on_budget_exceeded / onBudgetExceeded |
"warn" |
"warn" logs only; "throw" raises AurexBlocked; "webhook" posts an alert. |
enable_loop_guard / enableLoopGuard |
False |
Stops argument-aware structural, multimodal, and semantic agent retry loops with AurexBlocked. |
max_consecutive_same_tool / maxConsecutiveSameTool |
8 |
Exploration headroom when an agent calls the same tool name consecutively with different arguments (identical name + args still blocks on Turn 2). |
cache_ttl / cacheTtl |
"5m" |
Anthropic cache-creation billing multiplier ("5m" = 1.25x, "1h" = 2.0x). |
redis_url / redisUrl |
env AUREX_REDIS_URL |
Enables RedisStateStore for multi-worker Gunicorn, Uvicorn, Celery, or Kubernetes pods. |
storage_mode / storageMode |
"file" |
"file" writes .aurex/ledger.jsonl; "memory" supports read-only containers. |
strict_provider_drift / strictProviderDrift |
env AUREX_STRICT_DRIFT=1 |
Raises AurexProviderDriftError in CI if an upstream SDK breaks internal layouts; production fails open. |
- Supported Providers: OpenAI (Chat, Structured
.parse(),.stream(), andresponsesAPI, plus automaticbase_urlpricing for Groq, OpenRouter, NVIDIA NIM, IBM watsonx, Together AI, Fireworks, and$0.00local Ollama), Anthropic Claude (5m/1hprompt caching,ThinkingBlock,>200k2x tiers), Google Gemini (sync &.aioasync,thoughts_token_count,>200k2x tiers), LiteLLM, Ollama, and Hugging Face. - Typed Exceptions & Health: Catch
AurexBlocked,AurexBudgetExceeded,AurexResilienceExhausted, andAurexProviderDriftError. Inspect live patch state anytime withauditor.get_health()/auditor.getHealth().
Data Storage & Zero-PII Architecture
Raw prompts and model responses are never transmitted to Aurex servers. By default, Aurex runs in 100% local mode with no API key required:
- Local-Only Mode (Default): Writes numeric token breakdowns, USD cost,
workflow_id,tenant_id, latency,outcome, and local one-way SHA-256 hashes (prompt_hash,system_prompt_hash,response_hash) to.aurex/ledger.jsonlon your own disk. - User-Owned Redis (Optional): When
AUREX_REDIS_URLis set, temporary sliding-window counters (aurex:session_cost:*,aurex:min_cost:*,aurex:prefix:*) stay inside your own Redis instance and auto-expire in120s–2h. - Opt-In Cloud Sync (When
AUREX_API_KEYis set): Transmits only operational cost metadata; SHA-256 prompt hashes are stripped before leaving the SDK unless explicitly enabled, and backend ingestion enforcesprompt=Noneandresponse=None.
Production Playbook & Contributing
- Move changing dates and IDs to the tail of prompts: Keep
messages[0]/systemstatic and setmax_context_tokens: 195000on Claude and Gemini pipelines so 50%–90% cache discounts stay warm and requests stop before the 2x cliff. - Scope LangGraph & multi-agent workflows: Wrap agent runs with
aurex_context.set({"workflow_id": run_id})(Python) oraurexContext.run({ workflowId }, ...)(Node.js) so sub-agents share one isolated session budget instead of falling back todefault_workflow. - Exclude
AurexBlockedfrom retry decorators: Passretry=retry_if_not_exception_type(AurexBlocked)intenacityso intentional blocks are never re-fired, and raiseloop_similarity_threshold(e.g.0.90–0.95) when coding agents need wider file-reading headroom on large repos. - Share state with Redis & gate PRs: Set
AUREX_REDIS_URL=redis://...in multi-worker Kubernetes or Gunicorn deployments and runaurex ci --fail-on-regressionin GitHub Actions.
Contributing
Contributions and provider adapter PRs are welcome! Fork bhav09/aurex-sdk, keep Python (sdk/python) and Node.js (sdk/node) changes in lockstep, verify with AUREX_STRICT_DRIFT=1 bash .agent/skills/aurex-smoke-test/scripts/run_smoke.sh, and open a Pull Request.