Guardrails API
Scan AI agent inputs and outputs in real time to detect PII, secrets, prohibited content, and policy violations before they reach production.
Beta: The Guardrails API is in beta. Endpoints and response schemas may change. We recommend pinning your SDK version.
Quick Start
import { init, guardrails } from '@thinkhive/sdk';
init({ apiKey: 'th_your_api_key' });
const result = await guardrails.scan({
input: 'My email is john@example.com and SSN is 123-45-6789',
scanners: ['pii'],
config: {
pii: { action: 'redact' }
}
});
console.log(result.action); // 'redact'
console.log(result.redactedInput); // 'My email is [EMAIL] and SSN is [SSN]'Authentication
All guardrails endpoints require an API key via the Authorization: Bearer header or X-API-Key header.
Authorization: Bearer th_your_api_keySee Authentication for details on obtaining and managing API keys.
Scan Content
POST /v1/guardrails/scanScan input, output, or tool calls against one or more scanners. Returns an action (pass, flag, redact, or block) and detailed findings.
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
input | string | One of input/output/toolCall | User input to scan |
output | string | One of input/output/toolCall | Agent output to scan |
toolCall | object | One of input/output/toolCall | Tool call to validate ({ name, arguments }) |
scanners | string[] | No | Scanner names to run. Falls back to default policy if omitted. |
policyId | string | No | Named policy to apply. Overrides scanners if both provided. |
config | object | No | Per-scanner configuration overrides |
options | object | No | Execution options (see below) |
At least one of input, output, or toolCall must be provided. You can scan multiple content types in a single request.
If neither scanners nor policyId is provided, the scan will use the company’s default active policy. If no default policy exists, a 400 error is returned.
Options
| Field | Type | Default | Description |
|---|---|---|---|
options.timeout | number | 5000 | Per-scanner timeout in milliseconds (100-30000) |
options.failOpen | boolean | false | On scanner timeout: true = pass, false = block |
options.shortCircuit | boolean | false | Stop scanning on first block result |
options.returnRedacted | boolean | true | Include redacted content in response |
Response
{
"success": true,
"data": {
"action": "redact",
"actionReason": "pii: email, ssn",
"redactedInput": "My email is [EMAIL] and SSN is [SSN]",
"results": {
"pii": {
"scanner": "pii",
"status": "completed",
"action": "redact",
"findings": [
{
"type": "email",
"value": "[EMAIL]",
"start": 12,
"end": 28,
"confidence": 0.95
},
{
"type": "ssn",
"value": "[SSN]",
"start": 37,
"end": 48,
"confidence": 0.95
}
],
"latencyMs": 2
}
},
"metadata": {
"scanId": "a1b2c3d4-...",
"totalLatencyMs": 3,
"scannersExecuted": 1,
"scannersBlocked": 0,
"scannersFlagged": 0,
"scannersTimedOut": 0,
"cached": false
}
}
}Action Priority
When multiple scanners run, the highest-priority action wins:
| Priority | Action | Meaning |
|---|---|---|
| 4 (highest) | block | Content rejected — do not send |
| 3 | redact | Content modified — sensitive data replaced |
| 2 | flag | Content allowed but flagged for review |
| 1 (lowest) | pass | Content is clean |
List Scanners
GET /v1/guardrails/scannersReturns all available scanners with their descriptions.
{
"success": true,
"data": {
"scanners": [
{ "name": "pii", "description": "Detects personally identifiable information" },
{ "name": "secrets", "description": "Detects API keys, tokens, and credentials" },
{ "name": "keywords", "description": "Matches against keyword blocklists" },
{ "name": "regex", "description": "Matches user-defined regex patterns" },
{ "name": "topic", "description": "Detects prohibited topics" },
{ "name": "tool_call", "description": "Validates tool calls against allow-lists" }
]
}
}Scanner Reference
PII Scanner
Detects personally identifiable information using pattern matching and entity recognition.
| Config | Type | Default | Description |
|---|---|---|---|
entities | string[] | all | Entity types to detect: email, phone, ssn, credit_card, ip_address, date_of_birth, jwt, aws_key, private_key, password, bearer_token, basic_auth, connection_string, medical_record_number, health_plan_id, npi |
action | string | "redact" | Action on detection: redact, mask, block |
{
"scanners": ["pii"],
"config": {
"pii": {
"entities": ["email", "ssn", "credit_card"],
"action": "redact"
}
}
}Secrets Scanner
Detects API keys, tokens, passwords, and other credentials using prefix matching and entropy analysis.
| Config | Type | Default | Description |
|---|---|---|---|
action | string | "block" | Action on detection: block, redact, flag |
{
"scanners": ["secrets"],
"config": {
"secrets": { "action": "block" }
}
}Detected patterns: AWS keys (AKIA...), GitHub tokens (ghp_, gho_, ghs_), Stripe keys (sk_live_, sk_test_), generic API keys, Bearer tokens, private keys, and high-entropy strings.
Keywords Scanner
Matches content against keyword blocklists using the Aho-Corasick algorithm for efficient multi-pattern matching.
| Config | Type | Default | Description |
|---|---|---|---|
keywords | string[] | required | Keywords to match |
caseSensitive | boolean | false | Case-sensitive matching |
{
"scanners": ["keywords"],
"config": {
"keywords": {
"keywords": ["competitor_name", "confidential", "internal only"],
"caseSensitive": false
}
}
}Regex Scanner
Matches user-defined regular expression patterns against content.
| Config | Type | Default | Description |
|---|---|---|---|
patterns | object[] | required | Array of { pattern, name, action } |
{
"scanners": ["regex"],
"config": {
"regex": {
"patterns": [
{
"pattern": "\\b[A-Z]{2}\\d{6}\\b",
"name": "internal_id",
"action": "flag"
}
]
}
}
}Topic Scanner
Detects prohibited or sensitive topics using built-in and custom topic definitions.
| Config | Type | Default | Description |
|---|---|---|---|
topics | string[] | required | Built-in topics to detect: medical_advice, legal_advice, financial_advice. Custom topics can be added via customTopics. |
customTopics | object[] | [] | Custom topic definitions: { name, keywords[] } |
threshold | number | 2 | Minimum unique keyword matches to trigger detection |
{
"scanners": ["topic"],
"config": {
"topic": {
"topics": ["medical_advice", "legal_advice"],
"customTopics": [
{
"name": "pricing_discussion",
"keywords": ["discount", "pricing", "negotiate", "deal"]
}
],
"action": "block"
}
}
}Tool Call Scanner
Validates tool calls against an allow-list with optional argument constraints.
| Config | Type | Default | Description |
|---|---|---|---|
allowedTools | object[] | required | Allowed tools with constraints |
{
"scanners": ["tool_call"],
"toolCall": {
"name": "delete_user",
"arguments": { "userId": "123", "permanent": true }
},
"config": {
"tool_call": {
"allowedTools": [
{
"name": "delete_user",
"requiredArgs": ["userId"],
"blockedArgs": ["permanent"]
}
]
}
}
}Policies
Policies are named scan configurations that can be reused across requests. Create policies via the dashboard or API, then reference them by ID.
Create Policy
POST /api/guardrail-policies{
"name": "Production Input Filter",
"description": "Standard input scanning for production agents",
"scanners": [
{ "scanner": "pii", "config": { "action": "redact" } },
{ "scanner": "secrets", "config": { "action": "block" } },
{ "scanner": "keywords", "config": { "keywords": ["confidential"] } }
],
"options": {
"timeout": 3000,
"failOpen": false,
"shortCircuit": true
},
"isDefault": true
}Use Policy in Scan
{
"input": "Check order for john@example.com",
"policyId": "policy_abc123"
}When using a policyId, the scanners field is optional. Per-scanner config overrides in the request are merged with the policy’s configuration.
Policy Endpoints
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/guardrail-policies | Create a new policy |
| GET | /api/guardrail-policies | List all active policies |
| GET | /api/guardrail-policies/:id | Get a specific policy |
| PUT | /api/guardrail-policies/:id | Update a policy |
| DELETE | /api/guardrail-policies/:id | Deactivate a policy (soft delete) |
SDK Examples
import { init, guardrails } from '@thinkhive/sdk';
init({ apiKey: process.env.THINKHIVE_API_KEY });
// Scan with multiple scanners
const result = await guardrails.scan({
input: userMessage,
output: agentResponse,
scanners: ['pii', 'secrets', 'keywords'],
config: {
pii: { action: 'redact', entities: ['email', 'phone'] },
secrets: { action: 'block' },
keywords: { keywords: ['confidential', 'internal'] }
},
options: { timeout: 3000, shortCircuit: true }
});
if (result.action === 'block') {
throw new Error(`Content blocked: ${result.actionReason}`);
}
if (result.action === 'redact') {
// Use redacted content instead
const safeInput = result.redactedInput ?? userMessage;
const safeOutput = result.redactedOutput ?? agentResponse;
}
// Scan with a policy
const policyResult = await guardrails.scan({
input: userMessage,
policyId: 'policy_abc123'
});
// List available scanners
const scanners = await guardrails.listScanners();Error Codes
| Status | Code | Description |
|---|---|---|
| 400 | BAD_REQUEST | Missing required fields or invalid scanner name |
| 401 | UNAUTHORIZED | Missing or invalid API key |
| 404 | NOT_FOUND | Policy not found or inactive |
| 409 | CONFLICT | Duplicate policy name |
| 413 | PAYLOAD_TOO_LARGE | Input exceeds 100KB limit |
| 429 | RATE_LIMIT_EXCEEDED | Too many requests |
| 500 | INTERNAL_ERROR | Server error |
Rate Limits
| Plan | Requests/min | Max scanners/request |
|---|---|---|
| Beta | 60 | 6 |
| Pro | 300 | 6 |
| Enterprise | Custom | Custom |
Rate limits are applied per API key. Contact sales for enterprise rate limits.
Guardrail Analytics
GET /api/guardrail-analyticsGet aggregate analytics about guardrail scan activity across your organization.
Query Parameters:
| Parameter | Type | Description |
|---|---|---|
period | string | Time period: 24h, 7d, 30d (default: 7d) |
agentId | string | Filter by agent |
Response:
{
"success": true,
"data": {
"totalScans": 15420,
"byAction": {
"pass": 12800,
"redact": 1900,
"flag": 520,
"block": 200
},
"byScanner": {
"pii": { "scans": 10200, "findings": 1800 },
"secrets": { "scans": 8500, "findings": 150 },
"keywords": { "scans": 6300, "findings": 420 },
"topic": { "scans": 3100, "findings": 80 }
},
"avgLatencyMs": 4.2,
"topFindings": [
{ "type": "email", "count": 950 },
{ "type": "phone", "count": 420 },
{ "type": "ssn", "count": 230 }
]
}
}Next Steps
- Authentication — API key management
- Guardrail Policies Guide — Setting up policies
- Traces — Connect guardrail results to trace data
- Compliance & Scanning — Compliance features