Reins Developer Docs
Everything you need to integrate AI governance into your application. Track transactions, enforce spend policies, and audit every agent call — all through a clean REST API and zero-dependency SDK.
Quickstart #
From zero to first tracked transaction in under 5 minutes. Three steps.
Get an API Key
Log into your Reins dashboard and navigate to Admin → API Keys. Create a new key — give it a name like production. Copy the key, keep it secret.
Install the SDK
Node.js: npm install reins-sdk — or copy sdk/reins.js directly into your project. Python SDK also available.
Track Your First Transaction
Initialize the client and submit a transaction. Every AI API call gets recorded with vendor, model, cost, and user context.
Authentication
All requests require a Bearer token in the Authorization header:
Authorization: Bearer rk_your_api_key_here
process.env.REINS_API_KEY in Node.js.
Installation
npm install reins-sdk
const { reins } = require('reins-sdk');
const client = reins({
apiKey: process.env.REINS_API_KEY,
baseUrl: 'https://reins-rh6x.polsia.app'
});
// Submit a transaction
const result = await client.submitTransaction({
amount: 150, // cents — $1.50
vendor: 'openai',
model: 'gpt-4',
userId: 'user-123'
});
console.log('Transaction recorded:', result.id);
Core Concepts #
Five building blocks. Understand these and the entire API makes sense.
Agent Registry #
Agents are the AI systems making requests — your Slack bot, your customer support agent, your data enrichment pipeline. Register them with a unique agentId and attach per-agent budgets and policies.
POST /api/agents
Authorization: Bearer rk_your_api_key
{
"agentId": "support-bot-v2",
"name": "Customer Support Bot v2",
"description": "Handles Tier 1 customer support across email and chat",
"vendor": "openai",
"monthlyBudgetCents": 50000,
"metadata": {
"team": "support",
"tier": "tier1",
"region": "us-east"
}
}
// Response
{
"success": true,
"agentId": "support-bot-v2",
"createdAt": "2026-03-15T10:30:00Z"
}
agentId to get agent-level analytics, per-agent policy enforcement, and budget tracking. If omitted, the transaction is tracked under a default agent.
Vendor Registry #
Vendors are the AI providers your agents call — OpenAI, Anthropic, Google, Cohere, Mistral, Perplexity. Each vendor has configurable rate limits, default cost estimation, and policy scoping.
// Vendor cost estimation is automatic when using ReinsSDK.wrap()
const { ReinsSDK } = require('reins-sdk');
const reins = new ReinsSDK({
apiKey: process.env.REINS_API_KEY
});
// Wrapped clients automatically detect vendor and estimate cost
const protectedOpenAI = reins.wrap(openAIClient);
const protectedAnthropic = reins.wrap(anthropicClient);
// Manual vendor detection
const vendors = ['openai', 'anthropic', 'cohere', 'mistral', 'google', 'perplexity'];
Policy Rules #
Policy rules define conditions and the action to take when those conditions are met. They're evaluated in priority order — the first matching rule wins. Rules can scope to specific agents, vendors, models, and time windows.
POST /api/policy-rules
Authorization: Bearer rk_your_api_key
{
"name": "Block expensive models for trial users",
"description": "Prevent trial users from using gpt-4 or claude-3-opus",
"enabled": true,
"priority": 10,
"conditions": {
"vendors": ["openai", "anthropic"],
"models": ["gpt-4", "gpt-4o", "claude-3-opus"],
"agentIds": [],
"amountCents": { "min": 0 },
"userRoles": ["trial"]
},
"action": "block",
"actionConfig": {
"message": "Upgrade to Pro to use advanced models",
"redirectUrl": "/upgrade"
}
}
Enforcement Actions #
When a rule matches, Reins takes one of three actions. Actions are fail-safe: network errors default to pass — your agents never freeze because a policy check fails.
block
halt immediately
Stops the request before it reaches the AI provider. The ReinsSDK throws a REINS_BLOCKED error with the rule's message. Use for hard budget limits and compliance requirements.
try {
await protectedGPT.chat.completions.create({
model: 'gpt-4',
messages: [...]
});
} catch (e) {
if (e.code === 'REINS_BLOCKED') {
console.log('Policy blocked:', e.message);
}
}
warn
alert and continue
Allows the request through but fires a notification. Ideal for soft budget warnings — you stay informed without blocking users. Triggers onWarn callback.
flag
log for review
Records the transaction normally but marks it for manual review. Triggers onFlag callback. Use for anomaly detection and compliance auditing.
Audit Events #
Every state change in Reins is recorded as an immutable audit event. Transactions, policy changes, alerts, API key operations — all immutable. Download as CSV for compliance, or query the API for real-time dashboards.
GET /api/v1/audit-log?limit=50&action=policy_rule.block
Authorization: Bearer rk_your_api_key
// Response
{
"success": true,
"events": [
{
"id": "evt_8x2k9p",
"eventType": "transaction.blocked",
"occurredAt": "2026-05-05T08:14:22Z",
"actor": "agent:support-bot",
"entityType": "transaction",
"entityId": "txn_abc123",
"metadata": {
"vendor": "openai",
"model": "gpt-4",
"amountCents": 400,
"ruleId": "rule_block_trial_gpt4",
"ruleName": "Block gpt-4 for trial users",
"action": "block"
}
}
],
"count": 1,
"total": 1
}
API Reference #
Complete endpoint documentation. All endpoints return JSON and require Authorization: Bearer {key}.
Transactions
| Param | Type | Description |
|---|---|---|
| amountreq | integer | Transaction amount in cents (1 = $0.01) |
| vendorreq | string | AI provider name: openai, anthropic, cohere, mistral, google, perplexity |
| model | string | Model identifier (e.g. gpt-4, claude-3-opus) |
| agentId | string | ID of the agent making the request |
| userId | string | End user who initiated the request |
| prompt | string | Original prompt text, truncated to 1,000 chars |
| response | string | Response snippet, truncated to 1,000 chars |
| metadata | object | Arbitrary key-value metadata |
| timestamp | string | ISO 8601 timestamp (defaults to server time) |
POST /api/v1/transactions
Authorization: Bearer rk_abc123
Content-Type: application/json
{
"amount": 320,
"vendor": "openai",
"model": "gpt-4",
"agentId": "support-bot-v2",
"userId": "user-789",
"prompt": "Summarize the Q4 earnings report...",
"metadata": {
"requestId": "req_xyz",
"channel": "slack"
}
}
| Param | Type | Description |
|---|---|---|
| limit | integer | Max results, 1–500 (default: 50) |
| offset | integer | Pagination offset (default: 0) |
| vendor | string | Filter by vendor name |
| agentId | string | Filter by agent ID |
| userId | string | Filter by user ID |
| startDate | string | ISO 8601 start date filter |
| endDate | string | ISO 8601 end date filter |
| action | string | Filter by action: pass, warn, flag, block |
GET /api/v1/transactions?limit=10&vendor=openai&startDate=2026-05-01
Authorization: Bearer rk_abc123
{
"success": true,
"transactions": [...],
"count": 10,
"total": 2847,
"limit": 10,
"offset": 0
}
GET /api/v1/transactions/txn_m9k2p7q/trace
Authorization: Bearer rk_abc123
{
"success": true,
"traceId": "trc_8x2k9p",
"transactionId": "txn_m9k2p7q",
"evaluatedRules": [
{
"ruleId": "rule_block_trial_gpt4",
"ruleName": "Block gpt-4 for trial users",
"matched": false,
"reason": "User has Pro role"
},
{
"ruleId": "rule_daily_cap",
"ruleName": "Daily $50 cap per agent",
"matched": false,
"reason": "Daily spend $23.40 below $50 limit"
}
],
"finalAction": "pass",
"evaluatedAt": "2026-05-05T08:14:22Z"
}
Policy Rules
| Param | Type | Description |
|---|---|---|
| enabled | boolean | Filter by enabled status (default: all) |
| action | string | Filter by action type |
| vendor | string | Filter by vendor scope |
priority carefully.POST /api/policy-rules
Authorization: Bearer rk_abc123
Content-Type: application/json
{
"name": "Daily $20 cap for free-tier agents",
"priority": 5,
"enabled": true,
"conditions": {
"agentIds": ["free-tier-*"],
"vendors": ["openai", "anthropic"],
"amountCents": { "min": 1 },
"timeWindow": "daily"
},
"action": "block",
"actionConfig": {
"message": "Daily spend limit reached. Upgrade to Pro.",
"thresholdPct": 100
}
}
// Response
{
"success": true,
"id": "rule_cap_free_daily",
"name": "Daily $20 cap for free-tier agents",
"priority": 5,
"createdAt": "2026-05-05T08:30:00Z"
}
PUT /api/policy-rules/rule_cap_free_daily
Authorization: Bearer rk_abc123
Content-Type: application/json
{
"enabled": false,
"priority": 10
}
// Response
{ "success": true, "id": "rule_cap_free_daily", "updatedAt": "2026-05-05T09:00:00Z" }
POST /api/policy-rules/evaluate
Authorization: Bearer rk_abc123
{
"agentId": "support-bot-v2",
"vendor": "openai",
"amount": 320
}
// Response — no transaction is recorded
{
"success": true,
"result": {
"action": "pass",
"ruleId": null,
"message": "No rules matched"
}
}
| Param | Type | Description |
|---|---|---|
| limit | integer | Max results (default: 50, max: 500) |
| action | string | Filter by action type (e.g. policy_rule.block) |
| entityType | string | transaction, policy_rule, api_key |
| startDate | string | ISO date filter |
| endDate | string | ISO date filter |
GET /api/v1/audit-log?limit=50&action=policy_rule.block
Authorization: Bearer rk_abc123
{
"success": true,
"events": [...],
"count": 50,
"total": 187
}
GET /api/v1/audit-log/csv?action=policy_rule.block
Authorization: Bearer rk_abc123
# Content-Type: text/csv
# id,eventType,occurredAt,actor,entityType,entityId,vendor,action
API Keys
GET /api/keys
Authorization: Bearer rk_abc123
{
"success": true,
"keys": [
{
"id": "key_8x2k9p",
"name": "production",
"keyMasked": "rk_prod_****f8e2",
"createdAt": "2026-03-15T10:30:00Z",
"lastUsedAt": "2026-05-05T08:00:00Z",
"isActive": true,
"permissions": ["transactions:write", "policies:read", "audit:read"]
}
]
}
POST /api/keys
Authorization: Bearer rk_abc123
Content-Type: application/json
{ "name": "production", "permissions": ["transactions:write", "policies:read"] }
// Response — key shown ONCE only
{
"success": true,
"id": "key_8x2k9p",
"name": "production",
"key": "rk_prod_a8b2c9d4e5f6g7h8i9j0",
"keyMasked": "rk_prod_****f8e2",
"createdAt": "2026-05-05T08:30:00Z"
}
Alerts
| Param | Type | Description |
|---|---|---|
| read | boolean | Filter by read/unread status |
| ruleId | string | Filter by specific policy rule |
| limit | integer | Max results (default: 50) |
PUT /api/policy-alerts/alert_8x2k9p/read
Authorization: Bearer rk_abc123
{ "success": true, "id": "alert_8x2k9p", "read": true }
Analytics
GET /api/analytics/summary?period=monthly
Authorization: Bearer rk_abc123
{
"success": true,
"period": "monthly",
"totalSpendCents": 48230,
"byVendor": { "openai": 35000, "anthropic": 13230 },
"byAgent": { "support-bot": 41000, "data-enrichment": 7230 },
"transactionCount": 2847,
"blockedCount": 12,
"flaggedCount": 34
}
GET /api/analytics/forecast
Authorization: Bearer rk_abc123
{
"success": true,
"totalSpendCents": 7800,
"projectedSpendCents": 48360,
"budgetCents": 50000,
"budgetUtilizationPct": 96.7,
"burnRateCentsPerDay": 1560
}
End-to-End Examples #
Six complete patterns from basic throttling to multi-policy cascades. Each ships to production.
Basic Throttling
Block any single transaction over $5.00. The simplest policy — catches expensive requests before they reach the AI provider.
POST /api/policy-rules
Authorization: Bearer rk_abc123
{
"name": "Block transactions over $5",
"priority": 1,
"enabled": true,
"conditions": {
"amountCents": { "min": 501 },
"vendors": ["openai","anthropic","cohere","mistral","google","perplexity"]
},
"action": "block",
"actionConfig": { "message": "Individual transactions over $5 are not permitted." }
}const { reins } = require('reins-sdk');
const client = reins({ apiKey: process.env.REINS_API_KEY });
const result = await client.submitTransaction({
amount: 600, // $6.00 — over the $5 limit
vendor: 'openai',
model: 'gpt-4'
});
if (result.action === 'block') {
console.error('Blocked:', result.policyResult.message);
}Per-Agent Budgets
Each agent gets its own monthly budget. Support bot: $500/mo hard cap. Data enrichment: $100/mo warn at 80%. Finance: $50/mo no overages.
// Support bot: $500/mo hard cap
POST /api/policy-rules
{
"name": "Support bot monthly cap",
"priority": 20,
"conditions": {
"agentIds": ["support-bot"],
"vendors": ["openai","anthropic"],
"timeWindow": "monthly"
},
"action": "block",
"actionConfig": { "message": "Support bot monthly budget exhausted ($500/mo)" }
}
// Data enrichment: warn at 80%
{
"name": "Data enrichment 80% warning",
"priority": 20,
"conditions": { "agentIds": ["data-enrichment"], "timeWindow": "monthly" },
"action": "warn",
"actionConfig": { "message": "80% of monthly budget used", "thresholdPct": 80 }
}await client.submitTransaction({
amount: 200,
vendor: 'openai',
model: 'gpt-4',
agentId: 'support-bot', // Required for per-agent policies
userId: 'user-123'
});Time-Window Policies
Limit by time window: hourly, daily, weekly, monthly. Useful for rate limiting, burst protection, and budget pacing.
// Block more than 50 requests per hour
{
"name": "Hourly burst protection",
"priority": 30,
"conditions": {
"vendors": ["openai","anthropic","cohere","mistral","google","perplexity"],
"timeWindow": "hourly"
},
"action": "block",
"actionConfig": { "message": "Hourly request limit (50/hour) exceeded", "maxTransactions": 50 }
}
// Warn at 80% of daily $100 budget
{
"name": "Daily budget warning at 80%",
"priority": 10,
"conditions": { "vendors": ["openai","anthropic"], "timeWindow": "daily" },
"action": "warn",
"actionConfig": { "message": "Daily budget 80% exhausted", "thresholdPct": 80 }
}Vendor Allowlisting
Default-deny vendor list. Compliance requirement: only OpenAI and Anthropic allowed. All others blocked.
// Block non-approved vendors (priority 100)
{
"name": "Vendor allowlist",
"priority": 100,
"conditions": {
"vendors": ["google","perplexity","cohere","mistral"],
"amountCents": { "min": 1 }
},
"action": "block",
"actionConfig": { "message": "Vendor not on approved list. Contact your admin." }
}
// Allow OpenAI and Anthropic (priority 1)
{
"name": "Allow approved vendors",
"priority": 1,
"conditions": { "vendors": ["openai","anthropic"] },
"action": "pass"
}Cost Caps
Organization-wide monthly ceiling. When total spend hits the cap, everything stops. Progressive thresholds: warn at 70%, 90%, block at 100%.
{
"name": "Organization monthly cost cap",
"priority": 200,
"conditions": {
"vendors": ["openai","anthropic","cohere","mistral","google","perplexity"],
"amountCents": { "min": 1 },
"timeWindow": "monthly"
},
"action": "block",
"actionConfig": {
"message": "Monthly AI spend cap reached ($2,000). Resets 1st of next month.",
"thresholdPct": 100
}
}
// Tiered: warn at 70% ($1,400) — warn at 90% ($1,800) — block at 100% ($2,000)Multi-Policy Cascade
Layered defense using priority ordering. Rules are evaluated highest-first — first match wins. Free users, trial users, paid users each get different limits.
// Priority 100: Free users — no gpt-4
{ "name": "Free: no gpt-4", "priority": 100,
"conditions": { "userRoles": ["free"], "models": ["gpt-4","gpt-4o"] },
"action": "block", "actionConfig": { "message": "Upgrade to Pro to use gpt-4" } }
// Priority 90: Free users — $5/day hard cap
{ "name": "Free: $5/day", "priority": 90,
"conditions": { "userRoles": ["free"], "timeWindow": "daily", "amountCents": { "min": 501 } },
"action": "block", "actionConfig": { "message": "Daily limit reached. Upgrade for more." } }
// Priority 80: Trial users — warn at 80% monthly
{ "name": "Trial: 80% warning", "priority": 80,
"conditions": { "userRoles": ["trial"], "timeWindow": "monthly" },
"action": "warn", "actionConfig": { "message": "Trial budget 80% used", "thresholdPct": 80 } }
// Priority 10: Hard cap — no single transaction over $50
{ "name": "Hard cap: $50 max", "priority": 10,
"conditions": { "amountCents": { "min": 5001 } },
"action": "block", "actionConfig": { "message": "Exceeds $50 limit" } }
// Priority 1: Pass everything else
{ "name": "Default: pass", "priority": 1,
"conditions": { "amountCents": { "min": 1 } },
"action": "pass" }Request Lifecycle #
A complete trace of a single AI request through Reins — from your app to the provider and back.
5 flow stages
Request received
POST /api/v1/transactions
Your app calls the Reins API with amount, vendor, agent, and context. Authenticated via Bearer token.
Policy evaluation
Rule engine checks conditions
Reins loads enabled rules, sorts by priority, and evaluates each against vendor, agent, model, amount, user role, and time window.
Action execution
block | warn | flag | pass
Matched rule determines outcome. Block throws immediately. Warn fires notifications. Flag marks for review. Pass allows through.
Transaction recorded
PostgreSQL INSERT
Transaction and policy result written to database. If blocked, API returns error immediately. Otherwise returns 202 Accepted.
Audit event emitted
Immutable event log
Every transaction emits an audit event. Events are append-only and can be exported as CSV or queried via the API.
Error Codes #
What to do when something goes wrong. Start here.
| Status | Code | Meaning | Fix |
|---|---|---|---|
| 401 | UNAUTHORIZED | Invalid or missing API key | Check Authorization header — must be Bearer rk_... |
| 403 | POLICY_VIOLATION | Request blocked by a policy rule | Inspect error.policyResult for the rule that fired |
| 403 | FORBIDDEN | API key lacks required permission | Create a new key with the needed permissions |
| 422 | VALIDATION_ERROR | Missing or invalid parameters | amount and vendor are mandatory |
| 429 | RATE_LIMITED | Too many requests per second | Add delay between requests |
| 500 | INTERNAL_ERROR | Reins server error | Check health status and report if persistent |
| 503 | SERVICE_UNAVAILABLE | Reins is unreachable | Fail-open: requests pass through without tracking |
{
"success": false,
"message": "Policy violation: Monthly budget exceeded",
"code": "POLICY_VIOLATION",
"policyResult": {
"action": "block",
"ruleId": "rule_cap_free_daily",
"ruleName": "Daily $20 cap for free-tier agents",
"message": "Daily spend limit reached. Upgrade to Pro."
},
"details": { "limit": 2000, "current": 2050, "timeWindow": "daily" }
}
FAQ #
Policy rules are evaluated in priority order — highest priority first. A lower-priority rule with action: pass matching first will prevent higher-priority block rules from firing. Check your rule priority ordering and ensure the rule's conditions actually match the transaction (vendor, agent, amount, user role).
Reins policy evaluation adds ~5-15ms per request. This is typically imperceptible. If seeing significant slowdown: (1) is your Reins instance in the same region? (2) are you using strictMode: false for non-critical paths? (3) are you calling evaluatePolicy synchronously before every request?
Use POST /api/policy-rules/evaluate for preview-mode testing — it evaluates rules without recording or blocking. Or create rules with action: flag first to see what would match before switching to block.
Yes. Set all rules to action: flag or action: warn — transactions are recorded but never blocked. Use this for the first week to understand spend patterns before enabling hard limits.
Reins SDK is fail-open by design. If the policy evaluation API errors or times out, the request is allowed through with a warning logged. Your agents never freeze because of a Reins outage. Transactions are not recorded during outages.
Use the userRoles condition. Tag transactions with the user's role in metadata, then create separate rules scoped to each role. For example: conditions.userRoles: ["trial"] for trial users, conditions.userRoles: ["pro"] for Pro users.
Version History #
All notable changes to the Reins SDK and API. Breaking changes are marked.
v2.0.0 — SDK Reference Launch
newComplete SDK documentation hub. Full API reference, 6 worked examples, animated sequence diagram, dark mode, search, and copy buttons. All new design with sidebar navigation.
v1.9.0 — Policy Priority Override
newAdded priority field to policy rules. Rules are evaluated in descending priority order (highest first). Backwards compatible.
v1.8.0 — Enforcement Actions
newThree enforcement actions: block, warn, flag. Callback hooks onWarn and onFlag added to ReinsSDK. Upgrade from v1.7 required.
v1.7.0 — Agent Registry
newAgent registry API. Per-agent budgets and analytics. Transactions can now be tagged with agentId.
v1.6.0 — Time-Window Policies
improveAdded timeWindow condition: hourly, daily, weekly, monthly. Policy rules track cumulative spend over a window.
v1.5.0 — Audit Log CSV Export
newGET /api/v1/audit-log/csv for compliance exports. Added userRoles to conditions. Bulk transaction insert.
v1.4.0 — Analytics and Forecasting
improveGET /api/analytics/forecast predicts end-of-period spend. GET /api/analytics/anomalies flags unusual patterns.
v1.3.0 — Vendor Registry
newAutomatic cost estimation for Google Gemini and Perplexity. trace endpoint for transaction debugging.
v1.2.0 — Policy Rules API
newCRUD operations for policy rules. Conditions support vendors, models, and amountCents ranges.
v1.1.0 — ReinsSDK.wrap()
newReinsSDK.wrap() wraps OpenAI and Anthropic clients for automatic policy enforcement. Automatic vendor detection.
v1.0.0 — Initial Release
newTransaction tracking, audit log, dashboard. Multi-vendor support: OpenAI, Anthropic, Cohere, Mistral.