Aurex SDK v0.5.5 · MIT

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.

pip install aurex-sdk
npm install aurex-sdk

Using an AI coding agent (Claude Code, Cursor, Antigravity, Codex, Copilot)? Point it directly at llms.txt or AGENTS.md for drop-in setup without rewriting existing OpenAI, Anthropic, Gemini, LiteLLM, or Ollama calls.

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.25x cache-write surcharge.
  • The 200k 2x pricing cliff & missing cloud spend caps: Sending 200,001 input 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 429 storms 6x, and empty or whitespace-looped HTTP 200 OK responses 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.

Showing all 23 verified problem reports (13 GitHub issues + 10 Reddit threads).
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:

Aurex SDK in-process architecture diagram

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]"

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()

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

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()

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:

  1. One-Prompt Drop-In (Claude Code, Antigravity, Copilot, Codex, Cursor Chat): Paste the prompt below—your coding agent fetches llms.txt, finds your entrypoint (FastAPI lifespan, Express/Next.js instrumentation.ts, Celery, or LangGraph), and wires Aurex cleanly in one pass.
  2. Cursor / Windsurf @Docs Indexing: Add https://raw.githubusercontent.com/bhav09/aurex-sdk/main/llms.txt under Settings → Features → Docs as @Aurex, then ask @Aurex protect our LLM routes and background workers.
  3. 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.

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(), and responses API, plus automatic base_url pricing for Groq, OpenRouter, NVIDIA NIM, IBM watsonx, Together AI, Fireworks, and $0.00 local Ollama), Anthropic Claude (5m/1h prompt caching, ThinkingBlock, >200k 2x tiers), Google Gemini (sync & .aio async, thoughts_token_count, >200k 2x tiers), LiteLLM, Ollama, and Hugging Face.
  • Typed Exceptions & Health: Catch AurexBlocked, AurexBudgetExceeded, AurexResilienceExhausted, and AurexProviderDriftError. Inspect live patch state anytime with auditor.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.jsonl on your own disk.
  • User-Owned Redis (Optional): When AUREX_REDIS_URL is set, temporary sliding-window counters (aurex:session_cost:*, aurex:min_cost:*, aurex:prefix:*) stay inside your own Redis instance and auto-expire in 120s–2h.
  • Opt-In Cloud Sync (When AUREX_API_KEY is set): Transmits only operational cost metadata; SHA-256 prompt hashes are stripped before leaving the SDK unless explicitly enabled, and backend ingestion enforces prompt=None and response=None.

Production Playbook & Contributing

  1. Move changing dates and IDs to the tail of prompts: Keep messages[0] / system static and set max_context_tokens: 195000 on Claude and Gemini pipelines so 50%–90% cache discounts stay warm and requests stop before the 2x cliff.
  2. Scope LangGraph & multi-agent workflows: Wrap agent runs with aurex_context.set({"workflow_id": run_id}) (Python) or aurexContext.run({ workflowId }, ...) (Node.js) so sub-agents share one isolated session budget instead of falling back to default_workflow.
  3. Exclude AurexBlocked from retry decorators: Pass retry=retry_if_not_exception_type(AurexBlocked) in tenacity so intentional blocks are never re-fired, and raise loop_similarity_threshold (e.g. 0.90–0.95) when coding agents need wider file-reading headroom on large repos.
  4. Share state with Redis & gate PRs: Set AUREX_REDIS_URL=redis://... in multi-worker Kubernetes or Gunicorn deployments and run aurex ci --fail-on-regression in 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.