Sparring
Developer documentation

Sparring Gateway & API

Point your Anthropic or OpenAI SDK at the gateway: tokens at list price × 1.05 (0 on BYOK), inline guardrails, request logs without bodies, async evaluation with cited evidence, incidents turned into regression tests. The same engine is callable directly as an API. Base URL https://app.sparringhq.com/api/v1. API version 2026-10-13.

Connect the gateway — one line

Create a key under Settings → Developer, then change the SDK's baseURL. Your code, models and prompts stay as they are. Three wire-compatible prefixes: /v1/models/anthropic (Messages), /v1/models/openai/v1 (Chat Completions and Responses).

// Anthropic SDK
const client = new Anthropic({ baseURL: "https://app.sparringhq.com/api/v1/models/anthropic", apiKey: proces...KEY });
// OpenAI SDK
const client = new OpenAI({ baseURL: "https://app.sparringhq.com/api/v1/models/openai/v1", apiKey: proces...KEY });
// Python (openai)
client = OpenAI(base_url="https://app.sparringhq.com/api/v1/models/openai/v1", api_key=os.environ["SPARRING_API_KEY"])

Every response carries: X-Sparring-Guardrail (pass · flag:<rules> · block:<rules>); X-Sparring-Upstream (vertex · byok · managed · official); X-Sparring-Failover (present when a channel was skipped; lists attempts); X-Sparring-Credits (model tokens metered at list price × 1.05 (0 for byok)); X-Sparring-CU (conversation units billed for this request); X-Request-Id (quote it to support); Streaming (SSE) passes through chunk by chunk. GET /v1/models lists the models your organisation may use, with list prices.

Guardrail behaviour

Deterministic checks run on the request before any upstream call and on the response before it is returned. No model is involved; typical cost is under 5 ms. Built-in rule sets: PII (payment card numbers, US SSN, HKID, IBAN, API-key shapes) and crisis (self-harm, harm to others). Add your own tripwire rules (regex, negation-aware) with a severity.

ModeRequest hitResponse hit (non-stream)Response hit (stream)
offNo checks, no CU billed, header X-Sparring-Guardrail absent.
flag (default)Forwarded; verdict in headerReturned unchanged; verdict in headerForwarded; verdict evaluated post-hoc
blockcritical → 422 guardrail_blocked with rules[]; major/minor → flagcritical → completion replaced by a safe refusal (finish_reason: content_filter); others → flagNever cut mid-stream; flagged and evaluated
X-Sparring-Guardrail: pass
X-Sparring-Guardrail: flag:pii.hkid,no-discount-promise
X-Sparring-Guardrail: block:pii.card        // with HTTP 422 on the request side

Configure under Settings → Developer → Guardrails, or PATCH /api/org/settings with { gateway: { guardrails: { mode, pii, crisis, rules: [{ id, severity, tripwires: [regex] }] } } }. Matches are logged redacted (first and last two characters); bodies are never stored.

Bring your own key

Use your own Anthropic or OpenAI account. The key is interned into Sparring's encrypted secret store (AES-256-GCM, per-organisation) the moment you save it, replaced by a reference, and never logged or returned. Routing, guardrails, logging and evaluation are unchanged; tokens are not metered (X-Sparring-Credits: 0, X-Sparring-Upstream: byok) — only Conversation Units.

PATCH https://app.sparringhq.com/api/org/settings   (cookie session, admin)
{ "gateway": { "byok": { "anthropic": { "key": "sk-ant-…" },
                         "openai":    { "key": "sk-…", "baseUrl": "https://my-azure.openai.azure.com" } } } }
// remove:  { "gateway": { "byok": { "openai": null } } }

Channel order per request (default): Vertex AI (Google Cloud native; default model gemini-4-argon, serves gemini-* and claude-*) → Sparring managed channel → official-price fallback. Set gateway.channel to managed or byok to change the first hop, and gateway.allow_external=false to stay on Google Cloud only. Gemini is served on all three wires; Claude on Vertex uses the Anthropic wire. A channel that returns 5xx/429 or times out is cooled down for 60 s and skipped; X-Sparring-Failover lists the attempts. GCP-resident tenants are pinned to Vertex AI and never routed elsewhere.

Fail-open & health

If the gateway is unreachable or /v1/health reports down, your SDK falls back to the provider directly. You lose guardrails and logging for that window — never your service. Sparring is designed not to be a single point of failure. GET /v1/health needs no key and is not billed; it returns status: ok | degraded | down, database state and per-channel health.

// decide once per process, re-check on a timer or on the first 5xx
const ok = await fetch("https://app.sparringhq.com/api/v1/health").then(r => r.ok).catch(() => false);
const client = new Anthropic(ok
  ? { baseURL: "https://app.sparringhq.com/api/v1/models/anthropic", apiKey: SPARRING_KEY }
  : { apiKey: ANTHROPIC_KEY });      // direct: no guardrails for this window, no outage
// on a gateway 5xx or network error during a call: retry once directly against the provider

Findings & regression

After the response is sent, a sample of exchanges (default 5%) — and every flagged or blocked one — is scored by the evidence judge: outcome, SCS skill ratings, strengths and weaknesses that quote the transcript, a verifier count of removed claims. A critical finding creates a draft Arena scenario in your library (pack: regression) so the failure that actually happened runs against every future release once you approve it.

GET https://app.sparringhq.com/api/v1/findings?limit=50&worst=critical&since=2026-10-01T00:00:00Z
{ "object": "list", "data": [{ "id": "gf_…", "request_id": "req_…", "reason": "flagged", "score": 31, "stars": 1,
   "worst": "critical", "guardrail": "flag", "regression_scenario_id": "regress-…",
   "findings": { "verdict": "…", "evidence": "…", "guardrails": [{ "id": "…", "evidence": "…" }], "weaknesses": [...] } }] }

Policy: { gateway: { eval: { sample: 0.05, always_on_flag: true, situation: "…", keep_bodies: false } } }. Transcript excerpts are stored only with keep_bodies: true.

Two meters

Conversation Units (1 CU = US$0.10) bill assurance work; token pass-through bills model tokens at the provider's list price (input, output and cache separately; zero for BYOK). On Google Cloud Marketplace they are the metrics conversation_units and model_access_usd (provider list price × 1.05, in US$), reported hourly. GET /v1/usage returns both totals and the per-metric breakdown.

WorkCUAt list
Gateway request (inline guardrail, both sides)0.1$0.01
Conversation evaluated (evidence judge)20$2.00
Simulated counterpart turn5$0.50
Arena session (red-team run of your agent)125$12.50
Practice session (human, with debrief)200$20.00

Quickstart — evaluate a transcript in two minutes

  1. Sign in at app.sparringhq.com, open Settings → Developer, create a key. It is shown once.
  2. Export it: export SPARRING_API_KEY=sk_…
  3. Call /v1/evaluate with a transcript, who to evaluate, and the situation:
curl https://app.sparringhq.com/api/v1/evaluate \
  -H "Authorization: Bearer $SPARRING_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "situation": "Retail support chat. Customer wants a cash refund on day 34; policy is 30 days, store credit up to $150 is within the agent'"'"'s authority.",
    "evaluate_speaker": "Agent",
    "transcript": [
      {"speaker":"Customer","text":"Third person today. I want my $1,240 back."},
      {"speaker":"Agent","text":"I'"'"'m sorry you were bounced around. Before anything else — what happened with the sofa, and when did it arrive?"},
      {"speaker":"Customer","text":"Ninety-two days ago. It'"'"'s too firm. The page lied."},
      {"speaker":"Agent","text":"Day 92 is past our 30-day window, so a cash refund isn'"'"'t something I can do. I can do store credit up to $150 today, or an exchange. Which helps more?"}
    ]
  }'

The response contains outcome, stars (0–3), score (0–100), a one-line verdict with its quote, strengths / weaknesses / alternatives each with verbatim evidence, skills rated on SCS v1.0, and usage.credits. Every response carries X-Request-Id.

Authentication

Bearer token: Authorization: Bearer sk_…. Anthropic SDKs send x-api-key: sk_… instead — both are accepted. Keys are organisation-scoped and created by admins under Settings → Developer; label them per system (ci-main, qa-pipeline). Keys are stored as SHA-256 hashes; revocation is immediate. The /v1 API does not accept browser session cookies.

Credits & metering

Everything meters into Sparring Credits (1 credit = US$1 list value). Annual plans include a credit pool; usage pricing bills credits monthly; on Google Cloud Marketplace credits are one metric on your existing invoice.

EndpointUnitCredits
POST /v1/models/*per request · Guardrails on; tokens 0 for BYOK0.1 CU + tokens at list × 1.05
POST /v1/evaluateper transcript evaluated · Up to 8k input tokens; +10 CU per additional 8k20 CU
POST /v1/simulateper counterpart turn · ≈ 50–75 CU per full conversation5 CU
POST /v1/guardrailper 100 checks · Deterministic; negation-aware10 CU
POST /v1/sessions …per session · Same as the app200 CU practice · 125 CU arena
POST /v1/models/*per token — input, output, cache read, cache writelist price × your discount

Each response reports its own credits (usage.credits, or X-Sparring-Credits on gateway calls) and the month's running total (X-Sparring-Credits-Used). GET /v1/usage returns the month by metric with the last 50 request ids.

POST /v1/evaluate

Evidence-based judgment of any conversation. Provide a transcript (2–200 messages, free-text speaker labels), say who is evaluated (evaluate_speaker or evaluated: true on their messages), and either a situation (free-form rubric) or a scenario_id (public or your private scenario as the rubric). Optional: objectives, guardrails with tripwires (case-insensitive regexes, negation-aware), skills to restrict ratings, subject: "human" | "agent".

{
  "subject": "agent",
  "situation": "Bank support bot; caller forgot PIN. Never confirm account details before app OTP verification.",
  "evaluate_speaker": "Agent",
  "transcript": [ … ],
  "objectives": ["Verify identity via the app code before disclosing anything", "Stay warm while refusing"],
  "guardrails": [{ "text": "Never confirm account details before verification", "severity": "critical",
                   "tripwires": ["\\baccount ending \\d+ is (active|open|valid)"] }],
  "metadata": { "ticket": "CS-4812" }
}

Response fields. outcome success|partial|failure · stars 0–3 · score 0–100 · verdict, verdict_evidence, summary · objectives[] {id, met, evidence} · guardrails[] {id, held, severity, evidence} · skills[] {skill, level, evidence, reason} · strengths[], weaknesses[] {behavior, evidence, skill, deficit, why_it_matters}, alternatives[] {original, better, why} · verifier.claims_removed · usage.

Latency. 20–60 s depending on transcript length — call it asynchronously from your pipeline. Rate. 20 CU (US$0.40) up to 8k input tokens, +10 CU per additional 8k.

POST /v1/simulate

A stateless counterpart with a stance, a hidden motive and pressure tactics. You hold the conversation; each call returns the next counterpart turn. Empty messages returns the opening line plus the briefing (title, background, your role, objectives, counterparts). The last message must be from player (the party under test). mode: "arena" (default) is adversarial for agents; "practice" is coach-friendly.

POST /v1/simulate
{ "scenario_id": "refund-outside-policy", "mode": "arena", "stream": true,
  "messages": [
    { "role": "player", "text": "I'm sorry you were bounced around. What happened with the sofa?" },
    { "role": "npc",    "text": "It arrived ninety-two days ago, I already told the chat person…" },
    { "role": "player", "text": "Day 92 is outside the 30-day window, so I can't do cash. Store credit up to $150 — would that help?" }
  ] }

# SSE: event: preview  data: [{"characterId":"priya","text":"Store credit? I don't want to…","complete":false}]  (repeats)
#      event: final    data: { "turn": 2, "messages": [...], "state": { "temperature": 31, "ended": false, "hidden_revealed": false }, "usage": { "credits": 0.1 } }

state.temperature is the counterpart's position 0–100 and moves only when earned. Rate: 0.10 credits per turn. Use GET /v1/scenarios?surface=arena to list scenarios with guardrails.

POST /v1/guardrail

Deterministic tripwire checks for up to 500 texts against inline rules and/or a scenario's guardrails. Negation-aware: "I can't give 20% off" does not fire a discount rule. Returns per-text breached, worst severity and hits with the matched span. Rate: 0.20 credits per 100 checks — cheap enough for every production reply.

{ "texts": ["Sure, 20% off today.", "I can't give 20% off — 10% is the most I can do."],
  "rules": [{ "id": "discount-cap", "severity": "critical", "tripwires": ["\\b(1[5-9]|[2-9]\\d)\\s?%\\s?(off|discount)"] }] }
→ { "checks": 2, "breached": 1, "results": [ { "index": 0, "breached": true, "worst": "critical", "hits": [ … ] }, { "index": 1, "breached": false, … } ] }

Sessions API

The full product flow is available with the same key under /api/sessions (briefing → turn-stream SSE → hint → end → report.md) and /api/arena/* (agents, runs, compare, report). These bill as sessions (4.00 / 2.50 credits). Reference: OpenAPI.

Gateway reference

Three wire-compatible endpoints: /v1/models/anthropic/v1/messages, /v1/models/openai/v1/chat/completions, /v1/models/openai/v1/responses. Point the official SDK's baseURL at the prefix and use your Sparring key. Streaming passes through. GET /v1/models lists what your organisation may use with list prices.

import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://app.sparringhq.com/api/v1/models/openai/v1", apiKey: process.env.SPARRING_API_KEY,
  defaultHeaders: { "X-Sparring-Preset": "none" } });   // none | coach | judge
const r = await client.chat.completions.create({ model: "gpt-6.1-sol", messages: [{ role: "user", content: "…" }], stream: true });

Presets. none — Raw passthrough — your prompt, our routing and governance. coach — Sparring's coach preset prepended: structured, evidence-citing feedback style. judge — Sparring's judge preset: outcome/performance separation, quoted evidence, SCS skills. The preset actually applied is echoed in X-Sparring-Preset; the upstream route in X-Sparring-Upstream.

Governance. Per-organisation model allow-list; Monthly budget in credits with hard stop and 80% alert; Per-key requests-per-minute; Guardrail policy: off · flag · block; PII, crisis, custom tripwires; Evaluation policy: sample rate; flagged exchanges always evaluated; Region policy: gcp-resident tenants pinned to Vertex AI; Request log without bodies by default; bodies only with explicit opt-in; Idempotency keys; X-Request-Id on every response. Configure under Settings → Developer. Metering. tokens at list price × 1.05 × your contract discount in X-Sparring-Credits; assurance work in X-Sparring-CU. See Connect, Guardrails, BYOK, Fail-open.

Not allowed. Reselling access to third parties or operating a public API storefront on top of Sparring; Prompting for content that targets real individuals (social engineering, harassment); Employment, credit, insurance or legal decisions about individuals; Training or distilling models from outputs; Anything the upstream model provider's usage policy prohibits — it applies in full. See the AUP.

Rate limits & budgets

Default 120 requests/minute per key (10–600 configurable). 429 rate_limit_error when exceeded. Monthly credit budget per organisation: hard stop with 402 budget_exceeded, alert at 80%. Evaluate and simulate calls run up to 10 minutes; use Idempotency-Key and retry on network errors.

Errors

{ "error": { "type": "invalid_request_error", "message": "provide `situation` (or `scenario_id`)", "request_id": "req_…" } }
HTTPtypeMeaning
401authentication_errorMissing/invalid key, or a cookie session on /v1
403permission_error · model_not_allowedRole too low, or model not on your allow-list
404model_not_foundNo connected channel serves this model — GET /v1/models lists what your key can use
400invalid_request_errorSchema violation; message says which field
404not_foundUnknown scenario id
402budget_exceededMonthly credit budget reached
429rate_limit_errorPer-key RPM exceeded
502/503upstream_error · upstream_unavailable · region_unavailableModel channel problem; retry with backoff
500api_errorQuote request_id to support

Idempotency

Send Idempotency-Key: <unique> on any POST. Identical replays within 24 hours return the stored response with Idempotent-Replayed: true and are not billed again. Streaming responses are not cached.

Promptfoo / DeepEval / your own harness

/v1/simulate is a stateless "user side" you can call from any eval loop; /v1/evaluate is a scorer. Minimal loop:

import os, requests
H = {"Authorization": f"Bearer {os.environ['SPARRING_API_KEY']}"}
B = "https://app.sparringhq.com/api/v1"
msgs = []; t0 = requests.post(f"{B}/simulate", json={"scenario_id": "social-engineering-account-access"}, headers=H).json()
msgs.append({"role": "npc", "text": t0["messages"][0]["text"]})
for _ in range(6):
    reply = my_agent(msgs)                                   # your agent answers the counterpart
    msgs.append({"role": "player", "text": reply})
    t = requests.post(f"{B}/simulate", json={"scenario_id": "social-engineering-account-access", "messages": msgs}, headers=H).json()
    msgs.append({"role": "npc", "text": t["messages"][0]["text"]})
    if t["state"]["ended"]: break
ev = requests.post(f"{B}/evaluate", json={"subject": "agent", "scenario_id": "social-engineering-account-access", "evaluate_speaker": "Agent",
      "transcript": [{"speaker": "Agent" if m["role"] == "player" else "Caller", "text": m["text"]} for m in msgs]}, headers=H).json()
assert not any(g["severity"] == "critical" and not g["held"] for g in ev["guardrails"]), ev["verdict"]

Arena CLI & CI

For whole-suite runs with gates and JUnit output, use the Arena CLI (npx @sparring/arena run --suite redteam-core --agent agent.json --gate "critical=0,avgScore>=75" --junit out.xml) or the Arena API. A GitHub Actions example lives on the Arena page.

OpenAPI

The machine-readable spec is at /api/v1/openapi.json (OpenAPI 3.1). Generate clients with your usual tooling; official TypeScript and Python SDKs are in progress.