Skip to content
Home/Documentation

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.

1Change your base URL and add your PromptUnit headers
python
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"}],
)
javascript / node.js
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" }],
})
2Every call now flows through Inferio™. no other changes needed
Savings start with your first request. Every request is checked: when a cheaper model is just as good for it, Inferio™ uses it, and when it isn't, the request goes to the model you asked for. Your dashboard shows each request and what it saved.

What happens after you connect

1

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.

2

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.

3

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

4

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.

5

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.

HeaderRequiredDescription
x-promptunit-keyRequiredYour PromptUnit API key from the dashboard. Format: pu_live_...
x-api-keyOptional*Your Anthropic API key (sk-ant-...). Omit if stored in the dashboard.
AuthorizationOptional*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.

Feature tagging is optional but strongly recommended. Without it, all your traffic appears as a single unlabeled bucket in analytics.

Pick descriptive, consistent kebab-case names:

customer-support
summarization
code-review
onboarding
search
content-gen

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.

ProviderModelsPrice rangeKey format
OpenAIGPT-6 (Astra, Sol, Luna), GPT-5.6/5.5/5.4, o3, o4-mini, GPT-4o$0.05–$180/MToksk-proj-...
AnthropicClaude Fable 5.1, Opus 5.5/5, Sonnet 5.5/5, Haiku 4.5$1–$50/MToksk-ant-...
GoogleGemini 3.1 Pro, Gemini 3.8/3.5 Flash, Gemini 2.5 series$0.10–$12/MTokAIza...
Groqllama-3.3-70b, GPT-OSS 120B/20B, qwen3.8-27b$0.05–$0.79/MTokgsk_...
DeepSeekdeepseek-v4-pro, deepseek-flash$0.30–$3.96/MToksk-...
OpenRouterHundreds of models from many companies, on your own OpenRouter keyOpenRouter's pricessk-or-...
Mistral (extra option)mistral-large-latest, mistral-small-latest, codestral$0.10–$6/MTokany string
Together AI (extra option)Llama-3.3-70B-Instruct-Turbo, Llama-3.1-8B-Instruct-Turbo$0.18–$0.88/MTokany string
Perplexity (extra option)sonar-pro, sonar (web-augmented)$1–$15/MTokpplx-...
xAI (extra option)Grok 4.7/4.6/4.5, Grok 4.3$1.25–$12/MTokxai-...
Cohere (extra option)command-r-plus, command-r, command-r7b$0.15–$10/MTokany 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 PromptUnithttps://www.promptunit.ai/api/proxy/openai

Supported endpoints

POST/chat/completionsfully compatible, streaming supported

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 PromptUnithttps://www.promptunit.ai/api/proxy/anthropic

Supported endpoints

POST/messagesfully compatible, streaming supported

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.

HeaderExampleDescription
x-promptunit-cost0.000420Actual cost in USD for this call
x-promptunit-latency340msEnd-to-end latency
x-promptunit-model-usedgpt-4o-miniModel that actually ran
x-promptunit-model-requestedgpt-4oModel the client asked for
x-promptunit-task-typesummarizationDetected task classification
x-promptunit-saving0.003200USD saved vs requested model
x-promptunit-routingrouted / passthrough / observationRouting decision
x-promptunit-spam-score00 when the request went through. Only an empty message is rejected (1, with x-promptunit-blocked: empty)
x-promptunit-circuit-breakerok / anomaly / openBudget guard status
x-promptunit-prompt-cachemarked / noneWhether PromptUnit asked Anthropic to cache your system prompt (it does when the same prompt came within the last 5 minutes)
x-promptunit-compression0Tokens removed from a long conversation before sending. Always 0 for now: conversation trimming is switched off
x-promptunit-dialectnonePrompt-rewriting rules applied when routing switched the model. Always none: the rules are switched off
x-promptunit-inflationclean / base64_blobBill-inflation check, for information only: the request is sent as written
x-promptunit-output-verifiedok / truncated / refusalOutput quality check
x-promptunit-efficiency87Prompt efficiency score 0–100
x-promptunit-efficiency-issuesverbose_preamble,filler_phrasesDetected prompt issues
x-promptunit-context-injecteddate,recencyAuto-injected context fields
x-promptunit-cachesemantic-hit / missSemantic cache result (Layer 24)
x-promptunit-complexitysimple / medium / complex / reasoning-heavyDetected prompt complexity (Layer 23)
x-promptunit-complexity-score45Raw complexity score 0–100
x-promptunit-high-stakesfalse / medical / legal / financialHigh-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:

01Task type
02Complexity
03Token count
04Conversation depth
05Domain
06Output format
07Stakes level
08Language
09Context length
10Prior performance

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.

Routing is live from your first request. To keep one request on the model you asked for, send the header 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.

1–10
Smart RoutingRouting

Multi-dimensional model selection across 10 scoring axes

11
Spam FilterSecurity

Rejects an empty message. The other checks (repeats, injection phrases, random-looking text) are switched off: they rejected ordinary requests

12
Request DeduplicationCost

Detects identical requests within a rolling window and returns cached responses, preventing duplicate spend on retried or parallel calls.

13
System Prompt CacheCost

Anthropic prompt caching. 10x cheaper reads for repeated system prompts

14
Conversation CompressionCost

Switched off: conversations go to the model exactly as your app sent them

15
Prompt Efficiency AdvisorQuality

Detects wasteful prompt patterns, scores prompts 0–100

16
Output VerificationQuality

Checks for refusals, truncation, and format mismatch

17
Latency ProfilerIntelligence

Records per-provider, per-model latency on every call. Feeds routing decisions when two models score equally on quality.

18
Cross-Customer Pattern MiningIntelligence

Aggregate learnings across anonymized traffic (coming soon)

19
Token Inflation DefenseSecurity

Reports suspected bill-inflation tricks in a response header; your text is sent as written

20
Dialect TranslationCompatibility

Request formats are converted between OpenAI and Anthropic when routing crosses providers; your prompt text is not rewritten

21
Context GroundingQuality

Switched off: no notes are added to your prompts

22
Circuit BreakerSafety

Rolling spend windows, auto-downgrade, anomaly detection

23
Prompt Complexity ClassifierIntelligence

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.

24
Semantic Request CacheCost

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.

25
High-Stakes FlagQuality

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.

26
Cross-Customer Quality OracleIntelligence

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.

27
Adaptive Threshold LearningIntelligence

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:

yaml
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

  1. 01Each call records the requested model and the model that actually ran, logged inx-promptunit-model-requested and x-promptunit-model-used.
  2. 02The cost delta. what you would have paid minus what you paid. is recorded inx-promptunit-saving per call.
  3. 03Savings are summed and auditable. You can export the full call log at any time from the dashboard.
  4. 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.

Spend limits are enforced at the proxy layer. When a rolling window limit is breached, the circuit breaker (Layer 22) activates and may auto-downgrade requests to a cheaper model rather than rejecting them, depending on your configuration.

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.