Documentation
Everything you need to integrate PromptUnit into your stack. Two-minute setup, zero code changes beyond a single base URL swap.
Getting Started
Quick Start
Integrate PromptUnit in two steps. No new SDKs, no refactoring. just change your base URL and add two headers.
from openai import OpenAI
client = OpenAI(
api_key="your-openai-key",
base_url="https://www.promptunit.ai/api/proxy/openai",
default_headers={
"x-promptunit-key": "pu_live_xxxxxxxxxxxx",
"x-promptunit-feature": "customer-support",
}
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}],
)import OpenAI from "openai"
const openai = new OpenAI({
apiKey: "your-openai-key",
baseURL: "https://www.promptunit.ai/api/proxy/openai",
defaultHeaders: {
"x-promptunit-key": "pu_live_xxxxxxxxxxxx",
"x-promptunit-feature": "customer-support",
},
})
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello" }],
})What happens after you connect
Your first request, within seconds
Send one request from your app. It shows up live at the end of setup and on your dashboard: the model you asked for, the model that answered, what it cost and what it saved.
Every request after that
Each request is checked. When a cheaper model is just as good for it, PromptUnit uses it. Writing, analysis and specialist questions stay on the model you chose unless a cheaper one is just as good.
Free until we've saved you money
No card needed until your real savings reach $5 (individual accounts) or $100 (business accounts, which need a work email address).
Then 20% of what we save you
Add a card to keep saving. Without one, savings pause and your app keeps working on the models you chose. We email you when half and 80% of the free amount is used, and when savings pause. If we save you nothing, you pay nothing.
You stay in control
Send the header x-promptunit-routing: off to keep one request on its model, or turn routing off for your whole account on your dashboard.
The learning window, the nightly adjustments and the optional side-by-side checks: How your savings grow over time.
Authentication
Two headers authenticate your requests. The PromptUnit key identifies your account; the provider key is forwarded to the upstream model provider.
| Header | Required | Description |
|---|---|---|
| x-promptunit-key | Required | Your PromptUnit API key from the dashboard. Format: pu_live_... |
| x-api-key | Optional* | Your Anthropic API key (sk-ant-...). Omit if stored in the dashboard. |
| Authorization | Optional* | Your OpenAI API key as Bearer sk-.... Omit if stored in the dashboard. |
* Provider keys can be configured once in the PromptUnit dashboard instead of passing them per-request. Per-request keys always take precedence.
Feature Tagging
The x-promptunit-feature header tags each request with the product feature that made the call. This powers per-feature cost breakdowns in your dashboard. the most valuable insight for understanding where your AI spend actually goes.
Pick descriptive, consistent kebab-case names:
You can pass any string up to 64 characters. Tags appear immediately in the dashboard after the first tagged request is received.
Supported Providers
Your app connects through one of six: OpenAI, Anthropic, Google, Groq, DeepSeek or OpenRouter (your own OpenRouter key, which reaches hundreds of models). Mistral, Together AI, Perplexity, xAI and Cohere are extra options: add their keys and PromptUnit can switch a request to one of their models, but your app can't send its requests to them through PromptUnit directly yet. Add provider keys in the dashboard under API Keys.
| Provider | Models | Price range | Key format |
|---|---|---|---|
| OpenAI | GPT-6 (Astra, Sol, Luna), GPT-5.6/5.5/5.4, o3, o4-mini, GPT-4o | $0.05–$180/MTok | sk-proj-... |
| Anthropic | Claude Fable 5.1, Opus 5.5/5, Sonnet 5.5/5, Haiku 4.5 | $1–$50/MTok | sk-ant-... |
| Gemini 3.1 Pro, Gemini 3.8/3.5 Flash, Gemini 2.5 series | $0.10–$12/MTok | AIza... | |
| Groq | llama-3.3-70b, GPT-OSS 120B/20B, qwen3.8-27b | $0.05–$0.79/MTok | gsk_... |
| DeepSeek | deepseek-v4-pro, deepseek-flash | $0.30–$3.96/MTok | sk-... |
| OpenRouter | Hundreds of models from many companies, on your own OpenRouter key | OpenRouter's prices | sk-or-... |
| Mistral (extra option) | mistral-large-latest, mistral-small-latest, codestral | $0.10–$6/MTok | any string |
| Together AI (extra option) | Llama-3.3-70B-Instruct-Turbo, Llama-3.1-8B-Instruct-Turbo | $0.18–$0.88/MTok | any string |
| Perplexity (extra option) | sonar-pro, sonar (web-augmented) | $1–$15/MTok | pplx-... |
| xAI (extra option) | Grok 4.7/4.6/4.5, Grok 4.3 | $1.25–$12/MTok | xai-... |
| Cohere (extra option) | command-r-plus, command-r, command-r7b | $0.15–$10/MTok | any string |
CPR (Cross-Provider Routing) evaluates all connected providers on every call and routes to the globally cheapest model that clears your quality threshold. You get routing across your entire provider stack with zero extra code.
OpenAI Integration
Base URL
Replace the OpenAI base URL with the PromptUnit proxy endpoint. Every other part of your SDK usage stays identical.
| URL | |
|---|---|
| Direct (before) | https://api.openai.com/v1 |
| Via PromptUnit | https://www.promptunit.ai/api/proxy/openai |
Supported endpoints
Anthropic Integration
Base URL
Point your Anthropic SDK at the PromptUnit proxy endpoint to get routing, prompt caching optimization, and cost tracking.
| URL | |
|---|---|
| Direct (before) | https://api.anthropic.com/v1 |
| Via PromptUnit | https://www.promptunit.ai/api/proxy/anthropic |
Supported endpoints
Tools that always append /v1/messages themselves (like Claude Code's ANTHROPIC_BASE_URL, which can't be overridden to skip this) also work, that path is aliased to the same handler.
Response Headers
Every proxied response is augmented with x-promptunit-* headers that expose routing decisions, costs, quality scores, and optimization results. Your application can read these headers directly, or they are automatically ingested into your dashboard.
| Header | Example | Description |
|---|---|---|
| x-promptunit-cost | 0.000420 | Actual cost in USD for this call |
| x-promptunit-latency | 340ms | End-to-end latency |
| x-promptunit-model-used | gpt-4o-mini | Model that actually ran |
| x-promptunit-model-requested | gpt-4o | Model the client asked for |
| x-promptunit-task-type | summarization | Detected task classification |
| x-promptunit-saving | 0.003200 | USD saved vs requested model |
| x-promptunit-routing | routed / passthrough / observation | Routing decision |
| x-promptunit-spam-score | 0 | 0 when the request went through. Only an empty message is rejected (1, with x-promptunit-blocked: empty) |
| x-promptunit-circuit-breaker | ok / anomaly / open | Budget guard status |
| x-promptunit-prompt-cache | marked / none | Whether PromptUnit asked Anthropic to cache your system prompt (it does when the same prompt came within the last 5 minutes) |
| x-promptunit-compression | 0 | Tokens removed from a long conversation before sending. Always 0 for now: conversation trimming is switched off |
| x-promptunit-dialect | none | Prompt-rewriting rules applied when routing switched the model. Always none: the rules are switched off |
| x-promptunit-inflation | clean / base64_blob | Bill-inflation check, for information only: the request is sent as written |
| x-promptunit-output-verified | ok / truncated / refusal | Output quality check |
| x-promptunit-efficiency | 87 | Prompt efficiency score 0–100 |
| x-promptunit-efficiency-issues | verbose_preamble,filler_phrases | Detected prompt issues |
| x-promptunit-context-injected | date,recency | Auto-injected context fields |
| x-promptunit-cache | semantic-hit / miss | Semantic cache result (Layer 24) |
| x-promptunit-complexity | simple / medium / complex / reasoning-heavy | Detected prompt complexity (Layer 23) |
| x-promptunit-complexity-score | 45 | Raw complexity score 0–100 |
| x-promptunit-high-stakes | false / medical / legal / financial | High-stakes detection result (Layer 25) |
Inferio™ Engine
Inferio™ is the inference optimization engine that processes every request before it reaches the upstream model provider. It operates as a transparent pipeline: your request goes in, an optimized request goes out to the best-fit model, and the original response format is returned to your application unchanged.
How Routing Works
For each request, Inferio™ computes a score across 10 dimensions:
The score vector is matched against a continuously-updated capability matrix of available models. The cheapest model whose capability profile meets your configured quality threshold receives the request. If no cheaper model qualifies, the originally requested model is used as a passthrough.
x-promptunit-routing: off with it; to stop switching for your whole account, turn routing off on your dashboard.The 27 Layers
Inferio™ runs each request through up to 27 processing layers. Not all layers fire on every request. The pipeline is conditional based on request characteristics and your configuration. Layers 23-27 are the advanced intelligence algorithms that compound in value as traffic grows.
Multi-dimensional model selection across 10 scoring axes
Rejects an empty message. The other checks (repeats, injection phrases, random-looking text) are switched off: they rejected ordinary requests
Detects identical requests within a rolling window and returns cached responses, preventing duplicate spend on retried or parallel calls.
Anthropic prompt caching. 10x cheaper reads for repeated system prompts
Switched off: conversations go to the model exactly as your app sent them
Detects wasteful prompt patterns, scores prompts 0–100
Checks for refusals, truncation, and format mismatch
Records per-provider, per-model latency on every call. Feeds routing decisions when two models score equally on quality.
Aggregate learnings across anonymized traffic (coming soon)
Reports suspected bill-inflation tricks in a response header; your text is sent as written
Request formats are converted between OpenAI and Anthropic when routing crosses providers; your prompt text is not rewritten
Switched off: no notes are added to your prompts
Rolling spend windows, auto-downgrade, anomaly detection
Scores every prompt across 8 complexity signals (reasoning depth, constraint count, word count, code indicators) and recommends the minimum viable model. Routes simple requests to cheap models without burning tokens on the routing decision itself.
Fingerprints incoming requests using normalized content hashing. Returns a cached response when an equivalent request was seen recently, avoiding redundant API calls entirely. Hit rate grows with traffic volume.
Flags requests about medical, legal, financial, security or irreversible infrastructure topics. With debug logging on, the result comes back in the x-promptunit-high-stakes header, so your app can add its own review step. The flag doesn't change the model by itself: the routing layers keep your model for emergencies and hold medical, legal and financial requests to a stricter quality bar.
Aggregates anonymized quality signals across all traffic to build a per-model, per-task-type performance index. Surfaces real-world quality benchmarks trained on millions of requests. Gets more accurate with every call across the platform.
Every night, adjusts the quality bar for each kind of request from your last 7 days: answers that score well and are rarely repeated lower it a little (more savings), poor scores or many repeats raise it. Each model's scores are also corrected by how it did on your traffic over 30 days. See How your savings grow over time (/docs/savings).
Layer numbers reflect internal pipeline position. Non-sequential numbers indicate reserved slots for layers in private beta or upcoming release.
Logging Modes
PromptUnit stores per-request metadata to power your dashboard analytics. You control how much metadata is retained. Switch modes any time from your dashboard settings. changes take effect on the next request.
Standard (default)
- Token counts (input + output)
- Cost (actual + would-have-been)
- Model used + model requested
- Task type classification
- Feature tag (x-promptunit-feature)
- Step of your app + a 2-3 word step name, written once by AI on your own key
- Efficiency score
- Latency
Privacy
- Token counts (input + output)
- Cost (actual + would-have-been)
- Model used + model requested
- Task type classification, not stored
- Feature tag, not stored
- Step and step name, not stored
- Efficiency score, not stored
Routing is unaffected by logging mode. Classification and model selection happen in memory during the request. Logging mode only controls what gets written to the database after the response is returned.
In Privacy mode, the Spend by Feature breakdown in your dashboard will show Unknown for feature names and the task type column in your logs will be empty. Cost and savings data remain fully accurate.
GitHub Action
The PromptUnit AI Cost Analyzer is a GitHub Action that scans every pull request for expensive AI model usage and posts a comment with routing savings estimates. It runs automatically on PR open and sync with no build step required.
What it does
- Scans added lines in the PR diff for GPT-4o, Claude Opus, Gemini 2.5 Pro and other expensive models
- Skips PRs that already use PromptUnit (no duplicate comments)
- Posts a cost comparison table showing what routing would save
- Updates the existing comment on re-push rather than duplicating it
Add to your repo
Create .github/workflows/ai-cost-analyzer.yml in your repository:
name: AI Cost Analyzer
on:
pull_request:
types: [opened, synchronize]
jobs:
analyze:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: promptunit/sdk@main
with:
github-token: ${{ secrets.GITHUB_TOKEN }}That's the entire setup. The action uses only the standard GITHUB_TOKEN, no extra secrets required.
Setup time
2 minutes
Paste the YAML, done
Dependencies
Zero
No npm install, no build step
Permissions needed
pull-requests: write
Read PR diff, post comment
The action is self-contained and uses only Node.js built-in modules. It detects usage of GPT-4o, GPT-4 Turbo, o1, o3, Claude Opus, and Gemini 2.5 Pro in PR diffs. If any expensive model is found and PromptUnit is not already integrated, it posts a comment showing which calls could cost less and the two settings (base URL and PromptUnit key) that connect PromptUnit.
Source and full documentation are available at github.com/promptunit/sdk.
Limits & Billing
PromptUnit charges only on verified savings: the measurable difference between what you would have paid and what you actually paid through optimized routing.
Billing model
20% of verified savings
Charged once a week, only when you owe $5 or more. No setup fee.
Zero savings
$0 bill
If Inferio™ saves you nothing, you pay nothing
Default spend limit
$100 / hr · $500 / day
You can change them in your dashboard settings
Rate limits
100 requests / min
Per account and per IP address (HTTP 429 above that). Email us if you need more.
Answer length
32,000 tokens
A larger max_tokens is lowered to 32,000 (Claude with extended thinking: the thinking budget plus 32,000), because a request through PromptUnit can run for at most 5 minutes.
Request size
512 KB
Larger requests are refused (HTTP 413). Up to 10 answers per request (n).
How savings are calculated
- 01Each call records the requested model and the model that actually ran, logged in
x-promptunit-model-requestedandx-promptunit-model-used. - 02The cost delta. what you would have paid minus what you paid. is recorded in
x-promptunit-savingper call. - 03Savings are summed and auditable. You can export the full call log at any time from the dashboard.
- 04Once a week, 20% of the savings since the last charge is charged to your card, if that comes to $5 or more. Under $5 it rolls into the next week. If the total is $0, nothing is charged.
Examples and the full explanation: How billing works.
Ready to start?
Your first optimization in 5 minutes
Savings from your first request. If PromptUnit doesn't reduce your AI spend, you pay nothing.