Two calls from your server: check() before the model runs, record() after.
Any language works: the API is two JSON POST requests, and aiag.js is only a convenience for Node.js and for solving challenges in the browser. Your AI Guard key is a server secret, like your model provider’s key: never send it to a browser. Get a free key if you don’t have one.
Always pass your end user’s address and browser (ip, ua), not your server’s, and use feature to separate sites or products: the dashboard breaks everything down by it.
Node.js
With the SDK: download aiag.js (one file, no dependencies). It fails open after 1.5 seconds.
// npm-free: download aiag.js next to your server code (Node 18+)
const AIAG = require('./aiag.js');
const aiag = AIAG.init({ key: process.env.AIAG_KEY, feature: 'chat' });
app.post('/chat', async (req, res) => {
const d = await aiag.check({
user_id: req.user?.id, // whatever identity you have
ip: req.ip, // your END USER's address and browser,
ua: req.get('user-agent'), // not your server's
model: 'gpt-4.1-mini',
prompt_text: req.body.message,
pow: req.body.pow, // only if challenges are on for your account
});
if (d.action === 'block') return res.status(429).json({ error: 'slow_down' });
if (d.action === 'challenge') return res.json({ challenge: d.challenge });
if (d.action === 'throttle') await new Promise(r => setTimeout(r, d.retry_after_ms));
const r = await openai.chat.completions.create({ model: 'gpt-4.1-mini',
messages: [{ role: 'user', content: req.body.message }] });
await aiag.record(d.check_id, { tokens_in: r.usage.prompt_tokens,
tokens_out: r.usage.completion_tokens, model: 'gpt-4.1-mini' });
res.json({ reply: r.choices[0].message.content });
});
Next.js
A route handler keeps the key on the server. Put aiag.js in lib/; it works with import.
// app/api/chat/route.js (runs on the server: the key never reaches the browser)
import AIAG from '@/lib/aiag.js';
const aiag = AIAG.init({ key: process.env.AIAG_KEY, feature: 'chat' });
export async function POST(req) {
const { message, pow } = await req.json();
const d = await aiag.check({
user_id: req.headers.get('x-user-id') ?? undefined, // your session's user id
ip: (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim(),
ua: req.headers.get('user-agent') ?? '',
model: 'gpt-4.1-mini', prompt_text: message, pow,
});
if (d.action === 'block') return Response.json({ error: 'slow_down' }, { status: 429 });
if (d.action === 'challenge') return Response.json({ challenge: d.challenge });
if (d.action === 'throttle') await new Promise(r => setTimeout(r, d.retry_after_ms));
const r = await openai.chat.completions.create({ model: 'gpt-4.1-mini',
messages: [{ role: 'user', content: message }] });
await aiag.record(d.check_id, { tokens_in: r.usage.prompt_tokens,
tokens_out: r.usage.completion_tokens, model: 'gpt-4.1-mini' });
return Response.json({ reply: r.choices[0].message.content });
}
Python
Standard library only. Works the same in Flask, Django or FastAPI.
import json, os, time, urllib.request
def aiag(path, **body):
"""POST to AI Guard; on any problem answer 'allow' (fail open)."""
req = urllib.request.Request(
f"https://www.omegaconceptsdesign.com/api/{path}",
json.dumps({"key": os.environ["AIAG_KEY"], **body}).encode(),
{"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=1.5) as r:
return json.load(r)
except Exception:
return {"ok": 0, "action": "allow"}
d = aiag("aiag_check", feature="chat", user_id=user_id, ip=client_ip, ua=user_agent,
model="gpt-4.1-mini", prompt_text=message)
if d.get("action") == "block":
return "You're sending messages too fast. Please try again in a few minutes."
if d.get("action") == "throttle":
time.sleep(d.get("retry_after_ms", 1000) / 1000)
r = client.chat.completions.create(model="gpt-4.1-mini",
messages=[{"role": "user", "content": message}])
aiag("aiag_record", check_id=d.get("check_id", ""), tokens_in=r.usage.prompt_tokens,
tokens_out=r.usage.completion_tokens, model="gpt-4.1-mini")
PHP
Uses curl. Behind Cloudflare, pass CF-Connecting-IP; otherwise REMOTE_ADDR.
function aiag(string $path, array $body): array {
$ch = curl_init("https://www.omegaconceptsdesign.com/api/$path");
curl_setopt_array($ch, [
CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT_MS => 1500,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode(['key' => getenv('AIAG_KEY')] + $body),
]);
$res = curl_exec($ch);
curl_close($ch);
$d = $res ? json_decode($res, true) : null;
return is_array($d) ? $d : ['ok' => 0, 'action' => 'allow']; // fail open
}
$d = aiag('aiag_check', [
'feature' => 'chat', 'user_id' => $userId,
'ip' => $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'],
'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
'model' => 'gpt-4.1-mini', 'prompt_text' => $message,
]);
if (($d['action'] ?? 'allow') === 'block') { http_response_code(429); exit('Please slow down.'); }
if (($d['action'] ?? '') === 'throttle') usleep(($d['retry_after_ms'] ?? 1000) * 1000);
// ...call the model, then report what it really cost:
aiag('aiag_record', ['check_id' => $d['check_id'] ?? '', 'model' => 'gpt-4.1-mini',
'tokens_in' => $usage['prompt_tokens'], 'tokens_out' => $usage['completion_tokens']]);
Perl
Core modules only. This is how our own Users.Solutions chat widget is connected.
use HTTP::Tiny; # core; https needs IO::Socket::SSL (usually installed)
use JSON::PP qw(encode_json decode_json);
my $http = HTTP::Tiny->new(timeout => 1.5);
sub aiag {
my ($path, %body) = @_;
my $r = $http->post("https://www.omegaconceptsdesign.com/api/$path", {
headers => { 'Content-Type' => 'application/json' },
content => encode_json({ key => $ENV{AIAG_KEY}, %body }) });
my $d = $r->{success} ? eval { decode_json($r->{content}) } : undef;
return ref $d eq 'HASH' ? $d : { ok => 0, action => 'allow' }; # fail open
}
my $d = aiag('aiag_check', feature => 'chat', user_id => $user_id,
ip => $ENV{HTTP_CF_CONNECTING_IP} || $ENV{REMOTE_ADDR}, ua => $ENV{HTTP_USER_AGENT} // '',
model => 'gpt-4.1-mini', prompt_text => $message);
if ($d->{action} eq 'block') { print "Please slow down and try again later.\n"; exit }
select(undef, undef, undef, ($d->{retry_after_ms} || 0) / 1000) if $d->{action} eq 'throttle';
# ...call the model, then report what it really cost:
aiag('aiag_record', check_id => $d->{check_id}, tokens_in => $usage->{prompt_tokens},
tokens_out => $usage->{completion_tokens}, model => 'gpt-4.1-mini');
React and browser JavaScript
Browser code never calls AI Guard and never sees the key. It calls your backend, and solves a challenge only if your backend relays one.
// The browser talks to YOUR /api/chat, never to AI Guard: the key stays on the server.
import AIAG from './aiag.js'; // only needed if challenges are on for your account
async function send(message) {
const post = body => fetch('/api/chat', { method: 'POST',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(r => r.json());
let reply = await post({ message });
if (reply.challenge) { // solve once, send again
const pow = await AIAG.solvePow(reply.challenge); // well under a second on a laptop
reply = await post({ message, pow });
}
return reply;
}
Decisions
What each answer means
| action | Meaning | Your move |
|---|---|---|
allow | Clean, or AI Guard could not decide | Proceed |
throttle | Going too fast | Wait retry_after_ms, then proceed |
degrade | Suspicious, but plausibly a person | Use degrade_model if your policy sets one; otherwise treat it as throttle |
challenge | Probably automated. Only if challenges are on for your account; they’re off by default, and that band is throttled instead | Relay challenge to the browser, then retry with pow |
block | Abusive, or a spend cap is reached | Refuse |
POST /api/aiag_check
{ "key": "AIAG_KEY", "feature": "chat",
"user_id": "u_123", "fingerprint": "fp_abc", "ip": "203.0.113.7", "ua": "Mozilla/5.0 ...",
"model": "gpt-4.1-mini", "est_tokens_in": 800, "max_tokens": 500, "est_cost_usd": 0.0011,
"prompt_text": "...", "pow": "<solution>" }
Everything except key is optional. The identity is the strongest of user_id, fingerprint and ip, and the address is scored on its own as well. With none of them, only feature and overall caps apply and the reply carries a warn. Cost comes from est_cost_usd if you send it, otherwise from the model and token estimates.
{ "ok": 1, "action": "allow", "score": 10, "reason": "cold_identity (trust 0)",
"check_id": "9f2c41d07ab35e18", "est_cost_usd": 0.0011,
"budget": { "identity_day_left": 1.9989, "feature_day_left": 49.9989 } }
POST /api/aiag_record
{ "key": "AIAG_KEY", "check_id": "9f2c41d07ab35e18",
"tokens_in": 812, "tokens_out": 240, "model": "gpt-4.1-mini", "outcome": "ok" }
Reconciles the estimate to what the call really cost (send cost_usd to skip the price table), once per check_id. outcome is ok, error, reported or abuse; the last two lower that identity’s trust.
POST /api/aiag_pow
{ "key": "AIAG_KEY", "feature": "chat", "ip": "203.0.113.7" }
Issues a challenge up front, for accounts with challenges on whose policy requires proof-of-work on every request. A solution is good for one request, from the address it was issued to, for ten minutes.
Your dashboard
Open https://www.omegaconceptsdesign.com/ai-guard-dashboard?key=aiagv_… with the dashboard key you got next to your API key. It shows every check: decisions, scores and the reasons behind them, spend, tokens, a breakdown per feature, and the identities with the most flags. Spend figures are estimates per checked call, from the model and tokens you report; your AI provider’s bill is the exact number. The dashboard key is view-only and can’t make API calls; the API key never goes in a URL.
Prompts aren’t stored: only a short fingerprint to spot repeats, plus the first 500 characters of flagged ones, kept for 30 days so you can see why they were flagged.
Failure is open
Every example above gives AI Guard 1.5 seconds. On a timeout, an error or an unreadable reply, treat the answer as allow. Our downtime lowers your protection; it never takes your feature down. Default limits per day: $2 per end user and $50 per feature; ask us to change them.