API Reference

This is the canonical public contract for ValGuard. Fetch the live OpenAPI document at https://api.valguard.ai/openapi.json. Integration steps live in the quickstart. Contract changes are listed in the API changelog.

Client contract

  • Every /v1 response includes X-VG-Request-Id and JSON errors use Content-Type: application/json.
  • stream: true with a block, reask, or response-repair rule is buffered. ValGuard validates the full assistant text, then emits OpenAI chunks (role on the first delta, finish_reason and usage on the last) and [DONE]. That response sets X-VG-Stream-Buffered: true. Warn-only agents can use live passthrough (X-VG-Validation-Status: stream_passthrough). Stream usage comes from the provider stream_options.include_usage chunk, or a server-side estimate when the provider omits it.
  • Provider reasoning fields are forwarded on the completion and are not validated or stripped. Validators see choices[0].message.content only.
  • A request with no model and no agent default returns 400 missing_model. A BYOK key whose prefix belongs to another provider (for example a Groq gsk_ key with a Gemini model) returns 400 provider_key_mismatch and is not forwarded. Upstream error text is redacted so key material, including masked fragments, is not returned.
  • GET /v1/models returns a curated catalog. Browser CORS is not supported; OPTIONS explains that and does not send Access-Control-* headers.
  • Warn results set X-VG-Warnings. Estimated spend, when a price exists, is X-VG-Estimated-Cost-Microusd. A null provider usage_breakdown is omitted.

Find endpoints fast

Use the endpoint index for a complete route map, then jump to payload examples for request and response shapes.

Authentication

API keys, bearer auth, scopes, and dashboard key lifecycle.

Errors

Unified error envelopes and the status codes clients must handle.

Completions

OpenAI-compatible request and response contract for /v1/chat/completions.

Operations

Health checks and the public OpenAPI discovery endpoint.

On this page

Jump straight to the exact part of the contract you need.

Integration patterns

Choose the integration style that matches your stack. All paths use the same response envelope and validation headers.

Direct API call

Best for server apps, workers, and low-level control.

POST /v1/chat/completions
Authorization: Bearer ...
X-VG-Agent: default

Flow routing

Use playbook orchestration with deterministic branch logic.

POST /v1/chat/completions
Authorization: Bearer ...
X-VG-Flow: invoice-triage

Dashboard management API

Session-auth routes for workspace configuration and defaults.

GET/PATCH /api/org/features
Cookie: session=...

Common integration scenarios

Copy-paste flows for the most common production paths. Sample bodies use groq/openai/gpt-oss-20b; any provider/model works, for example groq/llama-3.3-70b-versatile.

Backend request handler

Synchronous server call with full validation headers.

POST https://api.valguard.ai/v1/chat/completions
Headers:
  Authorization: Bearer vg_live_...
  X-VG-Agent: support-default
Body:
  {
    "model": "groq/openai/gpt-oss-20b",
    "messages": [{"role":"user","content":"Summarize order"}],
    "temperature": 0.2
  }

Read headers:
  X-VG-Request-Id
  X-VG-Validation-Status

Cron / batch job

Nightly processing with deterministic flow routing.

for each record in batch:
  POST https://api.valguard.ai/v1/chat/completions
  Headers:
    X-VG-Api-Key: vg_live_...
    X-VG-Flow: invoice-triage
  Body:
    {
      "model": "groq/openai/gpt-oss-20b",
      "messages": [{"role":"user","content":"...record payload..."}]
    }

on 429/503:
  exponential backoff + retry

Workspace defaults workflow

Configure org-level self-heal defaults used by inherited agents.

GET /api/org/features

PATCH /api/org/features
{
  "self_heal_preset_default": "custom",
  "self_heal_rules_default": {
    "tier1:fix_trailing_comma": true,
    "tier2:cast_numeric": true
  }
}

Result:
  agents with preset=inherit use these defaults

SDK guides

Complete quick links for Python, Node.js, Go, and C#. Each SDK covers API auth headers, agent or flow routing, and validation metadata parsing.

SDKInstallQuick docsPackage source
Pythonpip install valguard-sdk (import valguard). PyPI valguard is an unrelated project (jhmanton/valguard); this client cannot use that name.Python quickstartpackages/sdk-python
Node.jsnpm install @valguard/sdk-node. Unscoped npm valguard is a placeholder, not this client.Node quickstartpackages/sdk-node
Gogo get github.com/valguard-ai/sdk-goGo quickstartpackages/sdk-go
C#dotnet add package ValGuard.SdkC# quickstartpackages/sdk-csharp

SDK capabilities checklist

  • Injects ValGuard auth headers and default routing metadata.
  • Supports OpenAI-compatible request payloads for chat completions.
  • Parses validation metadata from response headers and error envelopes.
  • Can be used with official OpenAI SDK flow (Python/Node) or standalone helper calls.

Recommended SDK path

  1. Start in SDK packages to install your language client.
  2. Copy the language snippet from Python, Node, Go, or C#.
  3. Return to this page for endpoint and response shape details.

Retry pseudocode by SDK language

Use this skeleton in your app-level wrapper around SDK calls.

Python

attempt = 0
while attempt < 5:
    try:
        return sdk.chat_completions(payload)
    except ApiError as err:
        if err.status not in (429, 503):
            raise
        sleep(min(10, 0.5 * (2 ** attempt)) + jitter_ms(0, 250) / 1000)
        attempt += 1
raise RetryExhausted()

Node.js

for (let attempt = 0; attempt < 5; attempt++) {
  try {
    return await sdk.chatCompletions(payload);
  } catch (err) {
    if (![429, 503].includes(err.status)) throw err;
    const delayMs = Math.min(10_000, 500 * 2 ** attempt) + jitter(0, 250);
    await wait(delayMs);
  }
}
throw new Error("retry_exhausted");

Go

for attempt := 0; attempt < 5; attempt++ {
    out, err := client.ChatCompletions(ctx, payload)
    if err == nil {
        return out, nil
    }
    if !isRetryable(err, 429, 503) {
        return nil, err
    }
    sleep(backoff(attempt, 500*time.Millisecond, 10*time.Second) + jitter(250*time.Millisecond))
}
return nil, errors.New("retry_exhausted")

C#

for (var attempt = 0; attempt < 5; attempt++)
{
    try { return await sdk.ChatCompletionsAsync(payload); }
    catch (ApiException ex) when (ex.StatusCode is 429 or 503)
    {
        var delay = Math.Min(10000, 500 * (int)Math.Pow(2, attempt)) + Jitter(0, 250);
        await Task.Delay(delay, cancellationToken);
    }
}
throw new Exception("retry_exhausted");

SDK troubleshooting

Fast runbook for the most common production integration failures.

401 Unauthorized

API key missing, invalid, or sent in the wrong header.

  • Primary: Authorization: Bearer VG_API_KEY. Alternative: X-VG-Api-Key. Use exactly one.
  • Confirm key belongs to the expected workspace.
  • Check key is active and not revoked in dashboard.

429 Too Many Requests

Rate or quota limit reached.

  • Read Retry-After when present.
  • Use exponential backoff with jitter.
  • Reduce burst concurrency in workers/cron jobs.

503 Service Unavailable

Temporary upstream or platform unavailability.

  • Retry with bounded exponential backoff.
  • Log X-VG-Request-Id for support and incident traces.
  • Fallback to queued processing when possible.

Recommended retry policy

Retry on: 429, 503
Max attempts: 5
Backoff: min(10s, base * 2^attempt) + jitter(0-250ms)
Non-retryable: 400, 401, 403, 404, 422

Structured error logging fields

{
  "status": 429,
  "code": "rate_limited",
  "request_id": "from X-VG-Request-Id",
  "agent_or_flow": "support-default",
  "attempt": 2,
  "retry_after": "2"
}

Data load and returned data

What each endpoint expects on input and what it returns on success.

EndpointData load (request)Data returned (response)Common statuses
/v1/chat/completionsHeaders: X-VG-Api-Key, X-VG-Agent or X-VG-Flow.
Body: model, messages[], optional stream, temperature, max_tokens.
OpenAI-style completion: id, choices[], usage.
Response headers include X-VG-Request-Id, X-VG-Validation-Status, and X-Vg-Upstream-Retries on agent and playbook completions.
200, 400, 401, 403, 404, 413, 429, 503
/api/org/features (GET)Session-auth cookie, admin role.quarantine_payloads_enabled, self_heal_preset_default, self_heal_rules_default.200, 401, 403
/api/org/features (PATCH)JSON patch for: quarantine_payloads_enabled, self_heal_preset_default, self_heal_rules_default.Same shape as GET with normalized defaults.200, 400, 401, 403
/healthzNo body.Plain text liveness response.200
/readyzNo body.Plain text readiness response.200, 503
/openapi.jsonNo body.OpenAPI 3.2 JSON document.200

Org features PATCH payload (new defaults)

{
  "quarantine_payloads_enabled": true,
  "self_heal_preset_default": "custom",
  "self_heal_rules_default": {
    "tier1:fix_trailing_comma": true,
    "tier1:fix_missing_comma": true,
    "tier2:cast_numeric": true
  }
}

Org features response shape

{
  "quarantine_payloads_enabled": true,
  "self_heal_preset_default": "custom",
  "self_heal_rules_default": {
    "tier1:fix_trailing_comma": true,
    "tier1:fix_missing_comma": true,
    "tier2:cast_numeric": true
  }
}

Endpoint index

Complete endpoint map for production use and dashboard management surfaces.

Public runtime API (API key auth)

These endpoints are part of the public contract and represented in OpenAPI.

MethodPathPurposeBody
POST/v1/chat/completionsValidated chat completionsJSON request payload
GET/healthzLiveness probeNone
GET/readyzReadiness probeNone
GET/openapi.jsonCanonical API contract documentNone

Workspace management API (dashboard session auth)

Used by the dashboard for CRUD and orchestration management. Requires active session cookies, not API key headers.

AreaRoutesData operations
Agents/api/agents, /api/agents/{slug}, /api/agents/bulk-deleteList, create, update, delete agents
Validators/api/agents/{slug}/validators, /history, /validation-summaryRead and replace validator sets
Playbooks/api/orchestration/flows, /publish, /test, /importCRUD, publish, run tests, import/export
Templates/api/templates, /api/org/templates, /api/org/playbook-templatesList, create, fork, submit, apply templates
Keys and org/api/keys, /api/org/*, /api/dashboard/*API keys, members, providers, usage and analytics

Data payload cheat-sheet

Copy-ready request shapes for common API operations.

Chat completion request

{
  "model": "groq/openai/gpt-oss-20b",
  "messages": [
    {"role": "system", "content": "You are a safe assistant."},
    {"role": "user", "content": "Summarize this payload"}
  ],
  "stream": false,
  "temperature": 0.2,
  "max_tokens": 512
}

Agent create request (dashboard API)

{
  "slug": "invoice-agent",
  "name": "Invoice extraction",
  "preset": "standard",
  "settings": {
    "default_provider": "openai",
    "default_model": "groq/openai/gpt-oss-20b",
    "max_reasks": 1,
    "shadow_mode": true,
    "self_heal_preset": "safe"
  }
}

Validators replace request

{
  "validators": [
    {
      "name": "required_fields",
      "enabled": true,
      "priority": 10,
      "severity": "error",
      "on_fail": "block",
      "params": {"fields": ["invoice_id", "total"]}
    }
  ]
}

Playbook create request

{
  "name": "Invoice triage flow",
  "slug": "invoice-triage",
  "description": "Parse invoice and route for approval",
  "graph": {
    "nodes": [],
    "edges": []
  }
}

Authentication

Use a production API key from the dashboard or the X-VG-Api-Key header. Keys are masked in the UI, auditable, and revocable.

Errors

Every non-2xx response follows a structured JSON error envelope with a machine-readable code and a stable message.

Unsupported routes

The layer is chat-first. Legacy OpenAI endpoints that are not wired on the proxy return 404 with a JSON error body.

  • POST /v1/completions — use POST /v1/chat/completions instead.
  • POST /v1/embeddings — not exposed on the public API.
  • Playbooks (X-VG-Flow) do not support stream: true; the API returns HTTP 400 orchestration_stream_unsupported.

Completions

The public completion endpoint is POST /v1/chat/completions and accepts OpenAI-style messages, with ValGuard validation and observability headers.

Request body parameters

Common fields include model, messages, stream, temperature, and max_tokens.

FieldTypeRequiredNotes
modelstringYesProvider-qualified slug such as groq/openai/gpt-oss-20b.
messagesarrayYesOpenAI-style chat turns with role and content.
streambooleanNoSet to true for streaming responses.
temperaturenumberNoControls randomness for the generation step.
max_tokensintegerNoMaximum output length for the completion.
{
  "model": "groq/openai/gpt-oss-20b",
  "messages": [{"role": "user", "content": "Summarize this payload"}],
  "stream": false,
  "temperature": 0.2,
  "max_tokens": 512
}

Authentication headers

Send the API key as Authorization: Bearer. X-VG-Api-Key is an accepted alternative. Use one header, not both. Chat completions do not honor Idempotency-Key (the response sets X-VG-Idempotency: unsupported). Playbooks dedupe X-VG-Idempotency-Key for 24 hours.

curl -X POST https://api.valguard.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "X-VG-Agent: default" \
  -d '{"model":"groq/openai/gpt-oss-20b","messages":[{"role":"user","content":"Hello"}]}'

# Alternative: -H "X-VG-Api-Key: YOUR_API_KEY"

Example request

curl -X POST https://api.valguard.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "X-VG-Agent: default" \
  -d '{
    "model": "groq/openai/gpt-oss-20b",
    "messages": [{"role": "user", "content": "Hello"}]
  }'

Example response

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help?"
    },
    "finish_reason": "stop"
  }]
}

Operations

The API exposes GET /healthz, GET /readyz, and GET /openapi.json for health and discovery.

Response status codes

Successful requests return 200 or 202 for streamed or accepted work. A blocking validator returns 403 by default. Auth failures use 401. 422 is used only when an agent sets that validation status.

200 OK

Completed successfully.

202 Accepted

Accepted for asynchronous or streaming work.

400 Bad Request

Malformed payload or invalid structure.

401 Unauthorized

Missing or invalid API key.

403 Forbidden

Default validation block (`validation_block`). 422 is only used when the agent sets that status.

Public endpoints

The canonical contract lives in the live OpenAPI document at https://api.valguard.ai/openapi.json.

Download OpenAPI 3.2 JSON
POST/v1/chat/completions

OpenAI-compatible chat completion endpoint. Accepts a JSON body with model, messages, and optional stream, temperature, and max_tokens.

GET/healthz

Returns the service health status for probes and uptime checks.

GET/readyz

Returns readiness for load balancer and deployment health checks.

GET/openapi.json

Returns the canonical public OpenAPI 3.2 document for clients and SDK generators.