Skip to main content
A
Docs

API Reference

Complete endpoint reference for the Anar Guard API.

Base URL

http://localhost:8002/api/v1

All endpoints except /health require JWT authentication via the Authorization: Bearer <token> header. Write operations on policies require the admin role.

Health

GET
/api/v1/health

Health check. No authentication required.

{
  "status": "healthy",
  "service": "anar-guard",
  "uptime_seconds": 3600
}

Governance

Evaluate Content

POST
/api/v1/governance/evaluate

Evaluate content against all active policies, content filters, and PII detection.

Request Body:

FieldTypeRequiredDescription
contentstringYesThe text content to evaluate (max 100,000 chars)
user_idstringNoUser identifier for audit logging
modelstringNoModel identifier for audit logging
contextstringNoContext hint (e.g., "customer_chat")
curl -X POST http://localhost:8002/api/v1/governance/evaluate \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"content": "Please diagnose my symptoms", "context": "chatbot"}'

Response:

FieldTypeDescription
allowedbooleanfalse when action is block, true otherwise
actionstringEscalated action: pass, log, warn, or block
violationsarrayList of policy violations with policy ID, name, action, reason, and matched terms
pii_detectedarrayList of PII entities found with type, value, start, and end offsets
content_scorefloatToxicity/restricted topic score (0.0 to 1.0, flagged at 0.3)
redacted_contentstringContent with PII replaced by [REDACTED_TYPE] markers (null if no PII)

Policies

List Policies

GET
/api/v1/policies

List governance policies with optional filtering.

Query Parameters:

ParameterTypeDefaultDescription
active_onlybooleanfalseOnly return active policies
skipinteger0Pagination offset
limitinteger50Results per page (1-100)

Create Policy

POST
/api/v1/policies

Create a new policy. Requires admin role.

Request Body:

FieldTypeRequiredDescription
namestringYesPolicy name (max 500 chars)
descriptionstringNoPolicy description (max 5,000 chars)
rule_typeenumYeskeyword, regex, or model-based
rule_configstringYesJSON-encoded rule configuration (max 50,000 chars)
actionenumYesblock, warn, or log
is_activebooleanNoWhether the policy is active (default: true)

Keyword rule config:

{"keywords": ["diagnosis", "prescribe", "تشخيص"]}

Regex rule config:

{"patterns": ["(?:\\+|00)(?:971|966)\\d{8,10}"]}

Get Policy

GET
/api/v1/policies/{policy_id}

Get a specific policy by ID.

Update Policy

PUT
/api/v1/policies/{policy_id}

Update a policy. Requires admin role. Only include fields to change.

Delete Policy

DELETE
/api/v1/policies/{policy_id}

Delete a policy. Requires admin role.

Returns {"deleted": true} on success.


PII Detection

Detect PII

POST
/api/v1/pii/detect

Detect personally identifiable information in text.

Request Body:

FieldTypeRequiredDescription
textstringYesText to scan for PII (max 100,000 chars)

Response:

FieldTypeDescription
entitiesarrayPII entities with type, value, start, end
has_piibooleanWhether any PII was detected

Redact PII

POST
/api/v1/pii/redact

Detect and replace PII with typed redaction markers.

Request Body:

FieldTypeRequiredDescription
textstringYesText to redact (max 100,000 chars)

Response:

FieldTypeDescription
originalstringOriginal input text
redactedstringText with PII replaced by [REDACTED_TYPE]
entities_redactedintegerNumber of entities that were redacted

Safety

Check Safety

POST
/api/v1/safety/check

Classify content safety using Llama Guard 4 via Groq.

Request Body:

FieldTypeRequiredDescription
textstringYesText to classify (max 100,000 chars)
scan_typestringNoinput (default) or output

Response:

FieldTypeDescription
safebooleanWhether the content is safe
categoriesstring[]Violated category names (e.g., "Violent Crimes", "Hate")
confidencefloat1.0 for safe, 0.9 for unsafe, 0.0 when checks are skipped
raw_responsestringRaw model output for debugging

Monitoring

Get Metrics

GET
/api/v1/monitoring/metrics

Get aggregated metrics for a time period.

Query Parameters:

ParameterTypeDefaultDescription
daysinteger7Lookback period (1-90 days)

Response:

FieldTypeDescription
total_requestsintegerTotal monitored requests
avg_latency_msfloatAverage response latency
error_ratefloatPercentage of errors
total_cost_usdfloatEstimated total cost
total_tokensintegerTotal tokens consumed
model_breakdownarrayPer-model usage statistics
daily_usagearrayDay-by-day usage data

List Alerts (Legacy)

GET
/api/v1/monitoring/alerts

List alerts from the legacy alert system.

Resolve Alert (Legacy)

PUT
/api/v1/monitoring/alerts/{alert_id}/resolve

Resolve an alert. Requires admin role.


Alert Rules

Create Alert Rule

POST
/api/v1/alerts/rules

Create a new alert rule with metric, threshold, and optional webhook dispatch.

Request Body:

FieldTypeRequiredDescription
namestringYesRule name
metricstringYesMetric to monitor: policy_violations, pii_detections, safety_blocks, critical_events
operatorstringYesComparison: gt, gte, lt, lte, eq
thresholdfloatYesThreshold value
window_minutesintegerYesLookback window (1-10080 minutes)
cooldown_minutesintegerNoCooldown between firings (default: 60, range 1-10080)
enabledbooleanNoWhether the rule is active (default: true)
webhook_idsstring[]NoWebhook IDs to notify when triggered
curl -X POST http://localhost:8002/api/v1/alerts/rules \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "High PII Detection Rate",
    "metric": "pii_detections",
    "operator": "gt",
    "threshold": 10,
    "window_minutes": 60,
    "cooldown_minutes": 120,
    "webhook_ids": ["wh-abc123"]
  }'

List Alert Rules

GET
/api/v1/alerts/rules

List configured alert rules.

Query Parameters: enabled_only, skip, limit

Update Alert Rule

PUT
/api/v1/alerts/rules/{rule_id}

Update an alert rule.

Delete Alert Rule

DELETE
/api/v1/alerts/rules/{rule_id}

Delete an alert rule.

List Triggered Alerts

GET
/api/v1/alerts

List triggered alerts with optional status filter.

Query Parameters:

ParameterTypeDescription
statusstringFilter by status: triggered, acknowledged, resolved
limitintegerResults per page (1-500, default 50)

Acknowledge Alert

POST
/api/v1/alerts/{alert_id}/acknowledge

Acknowledge a triggered alert.


Webhooks

Create Webhook

POST
/api/v1/webhooks

Register a webhook endpoint for alert notifications.

Request Body:

FieldTypeRequiredDescription
urlstringYesWebhook endpoint URL
eventsstring[]YesEvent types to subscribe to (e.g., ["alert_triggered"])
secretstringNoHMAC-SHA256 signing secret (auto-generated if omitted)

List Webhooks

GET
/api/v1/webhooks

List registered webhooks.

Delete Webhook

DELETE
/api/v1/webhooks/{webhook_id}

Delete a webhook registration.

Test Webhook

POST
/api/v1/webhooks/{webhook_id}/test

Send a test payload to verify webhook connectivity.

{
  "success": true,
  "status_code": 200,
  "error": null
}

Compliance Reports

List Frameworks

GET
/api/v1/compliance/reports/frameworks

List available compliance frameworks.

Generate Report

POST
/api/v1/compliance/reports/generate

Generate a new compliance report.

Request Body:

FieldTypeRequiredDescription
framework_idstringYesFramework identifier (e.g., uae_ai_ethics)
daysintegerNoAssessment period in days (default: 30, range 1-365)

List Reports

GET
/api/v1/compliance/reports

List previously generated reports.

Query Parameters: framework_id, limit

Get Report

GET
/api/v1/compliance/reports/{report_id}

Get full report details including all sections.

Export Report

GET
/api/v1/compliance/reports/{report_id}/export

Export report in structured JSON format.

Diff Reports

GET
/api/v1/compliance/reports/{report_a_id}/diff/{report_b_id}

Compare two reports from the same framework.


Audit Trail

GET
/api/v1/audit/trail

Query the audit trail with filtering.

Query Parameters:

ParameterTypeDefaultDescription
limitinteger50Results per page (1-500)
event_typestringNoneFilter: evaluation, safety_check, proxy_request, proxy_input_blocked, pii_detection
severitystringNoneFilter: info, warning, critical
user_idstringNoneFilter by user identifier
curl "http://localhost:8002/api/v1/audit/trail?severity=critical&limit=10" \
  -H "Authorization: Bearer $TOKEN"

Telemetry Ingestion

POST
/api/v1/telemetry/ingest

Ingest telemetry events from other Anar products. No JWT required.

Request Body:

FieldTypeRequiredDescription
eventsarrayYesArray of telemetry events (max 1000)
events[].event_typestringNoEvent type (default: llm_call)
events[].productstringYesSource product name
events[].modelstringNoModel used
events[].user_idstringNoUser identifier
events[].latency_msfloatNoResponse latency
events[].prompt_tokensintegerNoPrompt token count
events[].completion_tokensintegerNoCompletion token count
events[].total_tokensintegerNoTotal token count
events[].content_snippetstringNoContent preview (max 1000 chars)
events[].severitystringNoEvent severity (default: info)
events[].metadataobjectNoArbitrary metadata
curl -X POST http://localhost:8002/api/v1/telemetry/ingest \
  -H "Content-Type: application/json" \
  -d '{
    "events": [{
      "event_type": "llm_call",
      "product": "anar-chat",
      "model": "llama-3.3-70b-versatile",
      "latency_ms": 245.3,
      "total_tokens": 512,
      "severity": "info"
    }]
  }'
{"ingested": 1}

Guarded Proxy

POST
/api/v1/proxy/chat/completions

OpenAI-compatible chat completions with full input/output safety scanning.

Request Body: Standard OpenAI chat completion format with model, messages, temperature, max_tokens, and stream fields.

Response: Standard chat completion response with an additional safety object:

FieldTypeDescription
safety.input_safebooleanWhether the input passed safety checks
safety.input_categoriesstring[]Safety categories violated by input
safety.output_safebooleanWhether the output passed safety checks
safety.output_categoriesstring[]Safety categories violated by output
safety.pii_detectedintegerNumber of PII entities found in input
safety.blockedbooleanWhether the request or response was blocked

Gateway Required

The proxy endpoint requires a running Gateway instance at the URL specified by GATEWAY_BASE_URL. If Gateway is unreachable, the proxy returns a 502 error.