OpenAI shipped Health alerts on 3 December 2026, so OpenAI API monitoring now covers your error rate, cache hit rate, rate-limit use and Fast-tier spillover. You'll end with a rules file synced through the Admin API and a verified webhook receiver. We'd start with email rules on 5xx errors, TPM pressure and cache hit rate. Webhooks need $500 of qualifying prepaid purchases, so below that, skip the webhook steps.
What you'll build
A project that keeps your alert rules in a versioned JSON file and syncs them to OpenAI with a script, plus a webhook receiver that verifies the signature, drops duplicates and fetches the alert behind each event. Plan on 25-35 minutes. Steps use Python only, and everything runs against a local stand-in for the Admin API with a fake key, so no real call is made until you choose to.
The layout you'll have at the end:
openai-health-alerts/
├── .env.example
├── .gitignore
├── requirements.txt
├── alert_rules.json # the rules, in version control
├── common.py # client and database helpers
├── sync_rules.py # create or update rules from the file
├── cleanup.py # delete the rules in the file
├── fake_openai.py # local stand-in for the Admin API (tutorial code)
├── receiver.py # Flask: verify, store, dedupe (tutorial code)
├── send_test_event.py # signs and posts a test event (tutorial code)
├── worker.py # fetches the alert by data.id
└── events.db # created at runtimeExample output of the two scripts that matter (the values are illustrative):
$ python sync_rules.py
created ops-error-rate-5xx alertrule_<32 hex> v1
created ops-tpm-pressure alertrule_<32 hex> v1
created ops-cache-hit-rate alertrule_<32 hex> v1
$ python worker.py
triggered ops-error-rate-5xx: error_rate 0.06 vs threshold 0.05 (60 of 1000 requests)What you need before you start
- Python 3.11 or later.
- A macOS or Linux shell. On Windows, use WSL.
- For a real account, an Admin API key from your organization settings. OpenAI's Health alerts guide says rule management needs an organization Admin key. The tutorial itself runs on the fake key
sk-admin-fake. - A workload worth watching. If you don't have one yet, build it first with the OpenAI Responses API tutorial, whose error-handling step tells you to alert a human on spend and credit 429s. This tutorial builds that alert for aggregates.
What you can create depends on your cumulative qualifying prepaid credit purchases:
| Your prepaid purchases | Custom rules | Webhooks |
|---|---|---|
| Default | 3 | No |
| $100 or more | 10 | No |
| $500 or more | 100 | Yes |
The guide lists no per-alert charge, and email works at every level. Below $500, do steps 1-5 and 9 and skip steps 6-8, which build the webhook path. Rules you disable still count toward the limit, and deleting a rule frees its slot. Production webhooks also need a public URL; use a tunnel for real tests.
Why email first: a 5xx rule on a low-traffic project can't fire below 100 matching requests in its 300-second window, while a TPM rule has no volume floor. So on a quiet project, email on a TPM rule covers more than a webhook on the 5xx rule.
Quickstart
One rule in about ten lines. Save it as quickstart.py and swap in your own project ID for proj_your_project_id. It isn't part of the project, and against a real account it uses one of your slots:
pip install "openai>=3.62,<4"
OPENAI_ADMIN_KEY=your-admin-key python quickstart.pyimport os
from openai import OpenAI
client = OpenAI(
admin_api_key=os.environ["OPENAI_ADMIN_KEY"],
base_url=os.environ.get("OPENAI_ADMIN_BASE_URL", "https://api.openai.com/v1"),
)
rule = client.admin.organization.health.alert_rules.create(
name="quickstart-error-rate",
condition={"type": "error_rate", "threshold": 0.05, "window_seconds": 300, "status_class": "5xx"},
filters={"project_ids": ["proj_your_project_id"]},
)
print(rule.id, rule.version)Three things to get right before you build on it:
- Thresholds are fractions. 0.05 means 5%, and writing 5 is the classic mistake.
- The Admin key and the webhook signing secret are different secrets. Keep them in separate variables.
- Verify the signature against the raw request body, before you parse any JSON.
How the pieces fit
Your rules go to OpenAI through your sync script. When a rule fires, OpenAI sends an email, or a webhook carrying only an alert ID. The receiver verifies and stores that event, and the worker turns the ID into a measurement.
sync_rules.py ---- Admin key ----> Admin API /v1/organization/health/alert_rules
|
| rule breaches (two evaluations, or its configured minutes)
v
OpenAI --- POST health.alert.triggered, data.id ---> receiver.py
verify (webhook secret), store by webhook-id
|
v
worker.py --- Admin key ---> Admin API /v1/organization/health/alerts/{id}Locally, fake_openai.py stands in for both the Admin API and OpenAI's sender:
sync_rules.py, worker.py ---> fake_openai.py on 127.0.0.1:8099
send_test_event.py ---------> receiver.py on 127.0.0.1:5001How to set up OpenAI health alerts as code
1. Create the project and install the packages
Make a folder, a virtual environment and the files every later step relies on. Nothing else gets installed after this.
In a terminal, from wherever you keep projects:
mkdir openai-health-alerts && cd openai-health-alerts
python3 -m venv .venv && source .venv/bin/activateCreate requirements.txt:
openai>=3.62,<4
flask>=3,<4
python-dotenv>=1,<2The openai package gained the health resources in 3.62.0, so the pin matters. Flask is glue for the receiver, and python-dotenv loads .env, because the SDK doesn't. Create .env.example, which is safe to commit:
OPENAI_ADMIN_KEY=
OPENAI_WEBHOOK_SECRET=
OPENAI_ADMIN_BASE_URL=Create .gitignore:
.env
.venv/
__pycache__/
events.dbInstall, copy the template and generate a signing secret for the local tests:
pip install -r requirements.txt
cp .env.example .env
python -c "import base64,os;print('whsec_'+base64.b64encode(os.urandom(32)).decode())"Edit .env, pasting the printed secret after OPENAI_WEBHOOK_SECRET=:
OPENAI_ADMIN_KEY=sk-admin-fake
OPENAI_WEBHOOK_SECRET=whsec_<the value you generated>
OPENAI_ADMIN_BASE_URL=http://127.0.0.1:8099/v1For a real account, you'll later put real values in and delete the base URL line, which makes the scripts default to https://api.openai.com/v1.
Checkpoint:
python -c "import openai; c = openai.OpenAI(admin_api_key='sk-admin-fake'); c.admin.organization.health.alert_rules; print(openai.__version__, 'ok')"You should see something like (the version will differ):
3.63.0 okIf you see AttributeError, the installed openai is older than 3.62: re-run pip install -r requirements.txt.
2. Start the local fake Admin API
Create fake_openai.py. It's tutorial code, not OpenAI's: a stdlib server on port 8099 that implements only the routes the scripts call, keeps rules in memory and rejects any key but sk-admin-fake with a 401. Two choices in it are ours, not OpenAI's: it answers a stale expected_version with a 409, and it returns an empty first page that still carries next, so a sloppy pagination loop fails here the way it would in production.
import json
import re
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
KEY = "sk-admin-fake"
BASE = "/v1/organization/health"
PAGE_SIZE = 2
RULES = {}
RULE_PATH = re.compile(rf"{BASE}/alert_rules/(alertrule_[0-9a-f]{{32}})")
ALERT_PATH = re.compile(rf"{BASE}/alerts/(alertnotif_[0-9a-f]{{32}})")
def expected_version(body, query):
value = body.get("expected_version", query.get("expected_version", [None])[0])
return int(value) if value is not None else None
def canned_alert(alert_id):
rule = next((r for r in RULES.values() if r["condition"].get("type") == "error_rate"), None)
if rule is None:
return None
now = int(time.time())
return {
"id": alert_id,
"alert_rule_id": rule["id"],
"created_at": now,
"occurred_at": now,
"type": "triggered",
"object": "health.alert",
"dimensions": {"model": "example-model", "project_id": "proj_example", "service_tier": "default"},
"window": {"started_at": now - 300, "ended_at": now},
"measurement": {
"type": "error_rate",
"error_count": 60,
"request_count": 1000,
"threshold": rule["condition"]["threshold"],
"value": 0.06,
},
}
class Handler(BaseHTTPRequestHandler):
def send_json(self, status, payload):
data = json.dumps(payload).encode()
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def read_body(self):
length = int(self.headers.get("content-length", 0))
return json.loads(self.rfile.read(length)) if length else {}
def route(self, method):
if self.headers.get("authorization") != f"Bearer {KEY}":
return self.send_json(401, {"error": {"message": "Invalid Admin API key"}})
url = urlparse(self.path)
query = parse_qs(url.query)
try:
body = self.read_body()
except ValueError:
return self.send_json(400, {"error": {"message": "Body is not JSON"}})
if url.path == f"{BASE}/alert_rules":
if method == "GET":
return self.list_rules(query)
if method == "POST":
return self.create_rule(body)
match = RULE_PATH.fullmatch(url.path)
if match:
rule = RULES.get(match.group(1))
if rule is None:
return self.send_json(404, {"error": {"message": "No such rule"}})
if method == "GET":
return self.send_json(200, rule)
if method == "POST":
return self.update_rule(rule, body, query)
if method == "DELETE":
return self.delete_rule(rule, body, query)
match = ALERT_PATH.fullmatch(url.path)
if match and method == "GET":
alert = canned_alert(match.group(1))
if alert is None:
return self.send_json(404, {"error": {"message": "Create an error_rate rule first"}})
return self.send_json(200, alert)
return self.send_json(404, {"error": {"message": "No such route"}})
def list_rules(self, query):
rules = list(RULES.values())
token = query.get("page", [None])[0]
if token is None:
data, following = [], ("p1" if rules else None)
else:
k = int(token[1:])
data = rules[(k - 1) * PAGE_SIZE : k * PAGE_SIZE]
following = f"p{k + 1}" if len(rules) > k * PAGE_SIZE else None
self.send_json(200, {"object": "page", "data": data, "has_more": following is not None, "next": following})
def create_rule(self, body):
now = int(time.time())
rule = {
"id": "alertrule_" + uuid.uuid4().hex,
"object": "health.alert_rule",
"organization_id": "org_fake",
"created_at": now,
"updated_at": now,
"version": 1,
"enabled": body.get("enabled", True),
"name": body["name"],
"condition": body["condition"],
"filters": body.get("filters", {}),
"notifications": body.get("notifications", {}),
}
RULES[rule["id"]] = rule
self.send_json(200, rule)
def update_rule(self, rule, body, query):
if expected_version(body, query) != rule["version"]:
return self.send_json(409, {"error": {"message": "Rule changed, retrieve the latest version and retry"}})
for key in ("condition", "enabled", "filters", "name", "notifications"):
if key in body:
rule[key] = body[key]
rule["version"] += 1
rule["updated_at"] = int(time.time())
self.send_json(200, rule)
def delete_rule(self, rule, body, query):
if expected_version(body, query) != rule["version"]:
return self.send_json(409, {"error": {"message": "Rule changed, retrieve the latest version and retry"}})
del RULES[rule["id"]]
self.send_json(200, {"id": rule["id"], "object": "health.alert_rule.deleted", "deleted": True})
def do_GET(self):
self.route("GET")
def do_POST(self):
self.route("POST")
def do_DELETE(self):
self.route("DELETE")
if __name__ == "__main__":
print("fake Admin API on http://127.0.0.1:8099")
ThreadingHTTPServer(("127.0.0.1", 8099), Handler).serve_forever()In a terminal you'll leave running (terminal 1), from openai-health-alerts/ with the virtual environment active:
python fake_openai.pyIn a second terminal (terminal 2), also with the virtual environment active:
curl -s -H "Authorization: Bearer sk-admin-fake" http://127.0.0.1:8099/v1/organization/health/alert_rulesYou should see:
{"object": "page", "data": [], "has_more": false, "next": null}If you see Address already in use, something else holds port 8099: stop it or change the port in both fake_openai.py and .env.
The stub keeps rules in memory, so restarting it empties the account.
3. Define your alert rules in a file
Create alert_rules.json with three rules, one per metric we'd watch first. The file is the source of truth: you review changes to it in pull requests, and the sync script makes OpenAI match it. Thresholds and the model name are examples, so replace them with numbers from your own traffic.
[
{
"name": "ops-error-rate-5xx",
"enabled": true,
"condition": {"type": "error_rate", "threshold": 0.05, "window_seconds": 300, "status_class": "5xx"},
"filters": {"project_ids": ["proj_example"]},
"notifications": {
"email": {"addresses": ["oncall@example.com"], "enabled": true},
"webhook": {"enabled": false}
}
},
{
"name": "ops-tpm-pressure",
"enabled": true,
"condition": {"type": "rate_limit_utilization", "metric": "tpm", "consecutive_minutes": 5, "threshold": 0.8},
"filters": {"models": ["gpt-6.1-sol"]},
"notifications": {
"email": {"addresses": ["oncall@example.com"], "enabled": true},
"webhook": {"enabled": false}
}
},
{
"name": "ops-cache-hit-rate",
"enabled": true,
"condition": {"type": "prompt_cache_hit_rate", "threshold": 0.3},
"filters": {"project_ids": ["proj_example"]},
"notifications": {
"email": {"addresses": ["oncall@example.com"], "enabled": true},
"webhook": {"enabled": false}
}
}
]The ops- prefix is how you'll spot your rules in a shared organization, and the script matches on name, since a rule has no external key of ours. Per the guide, project filters suit the error, cache and spillover rules, and model filters suit rate-limit rules. The cache rule alerts when the hit rate falls below its threshold, while the other two alert on rising values. Three rules is the default allowance exactly, so a fourth needs $100 of prepaid purchases. In a real account, swap proj_example for your project ID and webhook.enabled to true once you're eligible.
Checkpoint:
python -c "import json;print(len(json.load(open('alert_rules.json'))))"You should see:
34. Create the missing rules
Create common.py for the client, then sync_rules.py, which lists every rule in the account and creates the ones whose name isn't there yet. This version is for a fresh account. Run it twice and the second run would only report exists, but it can't change anything, which step 5 fixes.
common.py:
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
def make_client():
return OpenAI(
admin_api_key=os.environ["OPENAI_ADMIN_KEY"],
webhook_secret=os.environ.get("OPENAI_WEBHOOK_SECRET"),
base_url=os.environ.get("OPENAI_ADMIN_BASE_URL") or "https://api.openai.com/v1",
max_retries=0,
)max_retries=0 turns the SDK's automatic retries off, so a failing call fails once and clearly. sync_rules.py:
import json
from common import make_client
RULES_FILE = "alert_rules.json"
def load_desired():
with open(RULES_FILE) as f:
return json.load(f)
def list_all_rules(client):
rules_api = client.admin.organization.health.alert_rules
rules = []
page = rules_api.list(limit=100)
while True:
rules.extend(page.data)
if not page.next:
return rules
page = rules_api.list(limit=100, page=page.next)
def main():
client = make_client()
existing = {rule.name: rule for rule in list_all_rules(client)}
for desired in load_desired():
rule = existing.get(desired["name"])
if rule is None:
created = client.admin.organization.health.alert_rules.create(**desired)
print(f"created {created.name} {created.id} v{created.version}")
else:
print(f"exists {rule.name} v{rule.version}")
if __name__ == "__main__":
main()The loop follows next until it's gone, and it doesn't stop at an empty page. OpenAI's guide notes an empty page can still carry next, and the stub does exactly that, so a loop that stops on empty data would see no rules and create duplicates on every run.
In terminal 2:
python sync_rules.pyYou should see something like (the IDs will differ):
created ops-error-rate-5xx alertrule_<32 hex> v1
created ops-tpm-pressure alertrule_<32 hex> v1
created ops-cache-hit-rate alertrule_<32 hex> v1If you see KeyError: 'OPENAI_ADMIN_KEY', .env isn't in this folder or the line is empty.
5. Update changed rules with expected_version
Replace sync_rules.py so it compares each desired rule with the live one and updates only on a difference. An update must carry the expected_version you read, and that's what makes two people editing the same rule safe: the second write is refused. The script treats a refusal as "re-read and retry once". It catches the SDK's generic APIStatusError. It never inspects a status code, because re-reading the rule is the recovery that matters.
Replace the whole file:
import json
import openai
from common import make_client
RULES_FILE = "alert_rules.json"
def load_desired():
with open(RULES_FILE) as f:
return json.load(f)
def list_all_rules(client):
rules_api = client.admin.organization.health.alert_rules
rules = []
page = rules_api.list(limit=100)
while True:
rules.extend(page.data)
if not page.next:
return rules
page = rules_api.list(limit=100, page=page.next)
def contains(actual, wanted):
if isinstance(wanted, dict):
return isinstance(actual, dict) and all(k in actual and contains(actual[k], v) for k, v in wanted.items())
return actual == wanted
def matches(rule, desired):
current = rule.model_dump(exclude_none=True)
return all(contains(current.get(key), value) for key, value in desired.items())
def update_rule(client, rule, desired):
rules_api = client.admin.organization.health.alert_rules
try:
return rules_api.update(rule.id, expected_version=rule.version, **desired)
except openai.APIStatusError:
latest = rules_api.retrieve(rule.id)
if matches(latest, desired):
return latest
return rules_api.update(latest.id, expected_version=latest.version, **desired)
def main():
client = make_client()
existing = {rule.name: rule for rule in list_all_rules(client)}
for desired in load_desired():
rule = existing.get(desired["name"])
if rule is None:
created = client.admin.organization.health.alert_rules.create(**desired)
print(f"created {created.name} {created.id} v{created.version}")
elif matches(rule, desired):
print(f"unchanged {rule.name} v{rule.version}")
else:
updated = update_rule(client, rule, desired)
print(f"updated {updated.name} v{rule.version} -> v{updated.version}")
if __name__ == "__main__":
main()matches only checks the fields you wrote in the file, so defaults OpenAI fills in don't cause endless updates. Omitted fields keep their value on the server, which is why an update can send the full desired rule safely.
Create cleanup.py as well. Don't run it until Clean up, because it deletes your rules:
from common import make_client
from sync_rules import list_all_rules, load_desired
def main():
client = make_client()
names = {rule["name"] for rule in load_desired()}
for rule in list_all_rules(client):
if rule.name in names:
client.admin.organization.health.alert_rules.delete(rule.id, expected_version=rule.version)
print(f"deleted {rule.name}")
if __name__ == "__main__":
main()Checkpoint, in terminal 2. The rules from step 4 still exist, so the first run changes nothing:
python sync_rules.pyYou should see something like:
unchanged ops-error-rate-5xx v1
unchanged ops-tpm-pressure v1
unchanged ops-cache-hit-rate v1Now change "threshold": 0.05 in the first rule to 0.08 and run it again. You should see updated ops-error-rate-5xx v1 -> v2 followed by two unchanged lines. Set the threshold back to 0.05 and run once more (v2 -> v3) so your file matches the rest of the tutorial.
6. Optional: receive the webhook and verify the signature
Create receiver.py, a Flask route that reads the raw request body and verifies it with the SDK's webhooks.unwrap before anything else. Flask is glue for this tutorial, not part of OpenAI's SDK. The signature is the route's only authentication, so a body that fails it gets a 400 and nothing more.
from flask import Flask, request
from openai import InvalidWebhookSignatureError
from common import make_client
app = Flask(__name__)
client = make_client()
@app.post("/webhook")
def webhook():
raw = request.get_data()
try:
event = client.webhooks.unwrap(raw, request.headers)
except InvalidWebhookSignatureError:
return "invalid signature", 400
print(f"verified {event.type} {event.data.id}", flush=True)
return "", 200
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5001)OpenAI can't reach localhost, so you also need a sender. Create send_test_event.py. It builds an event shaped like a health.alert.triggered webhook and signs it the way the Standard Webhooks specification describes: HMAC-SHA256 over webhook-id, webhook-timestamp and the raw body, keyed with the base64-decoded secret. --id sets the webhook-id so you can resend it, and --tamper changes the body after signing.
import argparse
import base64
import hashlib
import hmac
import json
import os
import secrets
import time
import urllib.error
import urllib.request
from dotenv import load_dotenv
load_dotenv()
URL = "http://127.0.0.1:5001/webhook"
NOTIFICATION_ID = "alertnotif_" + "a" * 32
def sign(secret, webhook_id, timestamp, body):
key = base64.b64decode(secret[len("whsec_"):])
message = f"{webhook_id}.{timestamp}.".encode() + body
digest = hmac.new(key, message, hashlib.sha256).digest()
return "v1," + base64.b64encode(digest).decode()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--id", default=f"msg_{secrets.token_hex(8)}")
parser.add_argument("--tamper", action="store_true")
args = parser.parse_args()
now = int(time.time())
body = json.dumps(
{
"id": f"evt_{secrets.token_hex(16)}",
"object": "event",
"created_at": now,
"type": "health.alert.triggered",
"data": {"id": NOTIFICATION_ID},
}
).encode()
timestamp = str(now)
signature = sign(os.environ["OPENAI_WEBHOOK_SECRET"], args.id, timestamp, body)
if args.tamper:
body += b" "
request = urllib.request.Request(
URL,
data=body,
method="POST",
headers={
"content-type": "application/json",
"webhook-id": args.id,
"webhook-timestamp": timestamp,
"webhook-signature": signature,
},
)
try:
with urllib.request.urlopen(request) as response:
print(response.status)
except urllib.error.HTTPError as err:
print(err.code)
if __name__ == "__main__":
main()Start the receiver in a third terminal (terminal 3), from openai-health-alerts/ with the virtual environment active:
python receiver.pyIn terminal 2, send a valid event, then a tampered one:
python send_test_event.py
python send_test_event.py --tamperYou should see:
200
400For the first request only, terminal 3 prints one line in the form verified <event type> <notification ID>, here verified health.alert.triggered followed by the ID. If the sender fails with a connection error, check that the receiver is running and nothing else holds port 5001.
Verifying the raw bytes matters: a framework that parses JSON first and re-serializes it changes the bytes, and the signature check fails on good events.
7. Optional: store events and ignore duplicates
Replace common.py and receiver.py so each verified event is saved before you answer. OpenAI's webhooks guide says delivery can repeat, with retries on exponential backoff for up to 72 hours, and tells you to dedupe on webhook-id. A 3xx counts as a failure, so return 200 for duplicates too. Persist first, then return 200, and leave the slow work to the worker in step 8.
Replace the whole of common.py:
import os
import sqlite3
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
def make_client():
return OpenAI(
admin_api_key=os.environ["OPENAI_ADMIN_KEY"],
webhook_secret=os.environ.get("OPENAI_WEBHOOK_SECRET"),
base_url=os.environ.get("OPENAI_ADMIN_BASE_URL") or "https://api.openai.com/v1",
max_retries=0,
)
def open_db():
db = sqlite3.connect("events.db")
db.execute(
"""CREATE TABLE IF NOT EXISTS events (
webhook_id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
notification_id TEXT NOT NULL,
received_at INTEGER NOT NULL,
processed INTEGER NOT NULL DEFAULT 0
)"""
)
return dbReplace the whole of receiver.py:
from flask import Flask, request
from openai import InvalidWebhookSignatureError
from common import make_client, open_db
HEALTH_EVENTS = {"health.alert.triggered", "health.alert.resolved"}
app = Flask(__name__)
client = make_client()
open_db().close()
@app.post("/webhook")
def webhook():
raw = request.get_data()
try:
event = client.webhooks.unwrap(raw, request.headers)
except InvalidWebhookSignatureError:
return "invalid signature", 400
if event.type in HEALTH_EVENTS:
db = open_db()
with db:
db.execute(
"INSERT INTO events (webhook_id, event_type, notification_id, received_at) "
"VALUES (?, ?, ?, strftime('%s', 'now')) ON CONFLICT(webhook_id) DO NOTHING",
(request.headers["webhook-id"], event.type, event.data.id),
)
db.close()
return "", 200
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5001)Stop the receiver in terminal 3 with Ctrl+C and start it again with python receiver.py. Then, in terminal 2, send the same webhook-id twice and count the rows:
python send_test_event.py --id msg_1
python send_test_event.py --id msg_1
python -c "import sqlite3; print(sqlite3.connect('events.db').execute('select count(*) from events').fetchone()[0])"You should see:
200
200
18. Optional: fetch the notification in a worker
Create worker.py. The webhook payload holds only data.id, so the measurement behind the alert comes from the Admin API: the worker reads unprocessed rows, fetches each alert, looks up its rule for a name and marks the row done. data.id is the notification ID, not the rule ID and not the top-level event ID. Fetching needs the Admin key; the signing secret and a project key both fail. OpenAI keeps notifications retrievable for 30 days, so a worker that was down can catch up.
The four measurement types each have their own fields, so a small dispatch table prints each one:
import openai
from common import make_client, open_db
MEASUREMENTS = {
"error_rate": lambda m: f"error_rate {m.value} vs threshold {m.threshold} ({m.error_count} of {m.request_count} requests)",
"prompt_cache_hit_rate": lambda m: f"cache hit rate {m.value} vs threshold {m.threshold} ({m.cached_input_token_count} of {m.input_token_count} input tokens)",
"rate_limit_utilization": lambda m: f"{m.metric} utilization {m.value} vs threshold {m.threshold} for {m.consecutive_minutes} minutes ({m.rate_limit_scope})",
"service_tier_fallback_rate": lambda m: f"fallback rate {m.value} vs threshold {m.threshold} ({m.fallback_count} of {m.eligible_attempt_count} {m.source_tier} attempts)",
}
def main():
client = make_client()
db = open_db()
rows = db.execute("SELECT webhook_id, notification_id FROM events WHERE processed = 0").fetchall()
for webhook_id, notification_id in rows:
try:
alert = client.admin.organization.health.alerts.retrieve(notification_id)
rule = client.admin.organization.health.alert_rules.retrieve(alert.alert_rule_id)
except openai.APIStatusError as err:
print(f"skipped {webhook_id}: {type(err).__name__}")
continue
describe = MEASUREMENTS.get(alert.measurement.type, lambda m: m.type)
print(f"{alert.type} {rule.name}: {describe(alert.measurement)}")
with db:
db.execute("UPDATE events SET processed = 1 WHERE webhook_id = ?", (webhook_id,))
if __name__ == "__main__":
main()In terminal 2:
python worker.pyYou should see something like (the stub's numbers are canned):
triggered ops-error-rate-5xx: error_rate 0.06 vs threshold 0.05 (60 of 1000 requests)If you see skipped msg_1: NotFoundError, the stub has no error_rate rule: restart it and run python sync_rules.py again.
9. Run and verify the whole project
Run everything from a clean state and check the negative cases. Your files now match Full code.
Reset first: stop the stub (terminal 1) and the receiver (terminal 3) with Ctrl+C, then in terminal 2 run rm -f events.db. Start the stub again in terminal 1 with python fake_openai.py, and the receiver in terminal 3 with python receiver.py. Then, in terminal 2:
python sync_rules.py
python send_test_event.py --id msg_1
python send_test_event.py --id msg_1
python send_test_event.py --id msg_2 --tamper
python worker.py
python sync_rules.pyYou should see something like:
created ops-error-rate-5xx alertrule_<32 hex> v1
created ops-tpm-pressure alertrule_<32 hex> v1
created ops-cache-hit-rate alertrule_<32 hex> v1
200
200
400
triggered ops-error-rate-5xx: error_rate 0.06 vs threshold 0.05 (60 of 1000 requests)
unchanged ops-error-rate-5xx v1
unchanged ops-tpm-pressure v1
unchanged ops-cache-hit-rate v1The duplicate got a 200 and left one row, the tampered body got a 400 and left none, and the second sync changed nothing. If you skipped steps 6-8, only the three sync_rules.py outputs apply.
One more negative check, for the version guard. This sends an update with a wrong expected_version:
python - <<'EOF'
import openai
from common import make_client
from sync_rules import list_all_rules
client = make_client()
rule = list_all_rules(client)[0]
try:
client.admin.organization.health.alert_rules.update(rule.id, expected_version=rule.version + 1, enabled=False)
except openai.APIStatusError:
print("rejected: stale expected_version")
EOFYou should see:
rejected: stale expected_versionOn a real account, dashboard test webhooks verify receipt and signatures, but their sample IDs can't be retrieved, so the worker has nothing to fetch. For an end-to-end run, point a low-threshold rule at a test project, trigger it, and read the real notification with the worker. Then delete the rule in Clean up. OpenAI says notifications typically arrive a few minutes after an alert changes state and doesn't guarantee delivery times, so time the email on your test rule.
To receive real webhooks, register your public URL for health.alert.triggered and health.alert.resolved and save the signing secret, which is shown once, into OPENAI_WEBHOOK_SECRET. Our rules belong to the organization, so they use the organization webhook settings. Then flip webhook.enabled to true in alert_rules.json and run python sync_rules.py. Put the receiver behind HTTPS, keep the signing secret out of logs, and leave the SDK's timestamp check on.
Clean up
Stop the stub and the receiver with Ctrl+C, then:
rm -f events.db
deactivateAgainst a real account, run python cleanup.py first, with your real values in .env, so the rules stop using slots. Revoke any Admin key you made for this tutorial, and rotate the webhook signing secret on the page where you created it if it ever appeared in a log or chat.
Full code
The project layout:
openai-health-alerts/
├── .env.example
├── .gitignore
├── requirements.txt
├── alert_rules.json
├── common.py
├── sync_rules.py
├── cleanup.py
├── fake_openai.py
├── receiver.py
├── send_test_event.py
├── worker.py
└── events.db # created at runtimeInstall and run, from openai-health-alerts/ (macOS or Linux, Python 3.11+):
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
python -c "import base64,os;print('whsec_'+base64.b64encode(os.urandom(32)).decode())"Fill .env as in step 1 (OPENAI_ADMIN_KEY=sk-admin-fake, the generated OPENAI_WEBHOOK_SECRET, OPENAI_ADMIN_BASE_URL=http://127.0.0.1:8099/v1), then use three terminals with the environment active:
# terminal 1
python fake_openai.py
# terminal 3
python receiver.py
# terminal 2
python sync_rules.py
python send_test_event.py --id msg_1
python send_test_event.py --id msg_1
python send_test_event.py --id msg_2 --tamper
python worker.py
python sync_rules.py.env.example:
OPENAI_ADMIN_KEY=
OPENAI_WEBHOOK_SECRET=
OPENAI_ADMIN_BASE_URL=.gitignore:
.env
.venv/
__pycache__/
events.dbrequirements.txt:
openai>=3.62,<4
flask>=3,<4
python-dotenv>=1,<2alert_rules.json:
[
{
"name": "ops-error-rate-5xx",
"enabled": true,
"condition": {"type": "error_rate", "threshold": 0.05, "window_seconds": 300, "status_class": "5xx"},
"filters": {"project_ids": ["proj_example"]},
"notifications": {
"email": {"addresses": ["oncall@example.com"], "enabled": true},
"webhook": {"enabled": false}
}
},
{
"name": "ops-tpm-pressure",
"enabled": true,
"condition": {"type": "rate_limit_utilization", "metric": "tpm", "consecutive_minutes": 5, "threshold": 0.8},
"filters": {"models": ["gpt-6.1-sol"]},
"notifications": {
"email": {"addresses": ["oncall@example.com"], "enabled": true},
"webhook": {"enabled": false}
}
},
{
"name": "ops-cache-hit-rate",
"enabled": true,
"condition": {"type": "prompt_cache_hit_rate", "threshold": 0.3},
"filters": {"project_ids": ["proj_example"]},
"notifications": {
"email": {"addresses": ["oncall@example.com"], "enabled": true},
"webhook": {"enabled": false}
}
}
]common.py:
import os
import sqlite3
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
def make_client():
return OpenAI(
admin_api_key=os.environ["OPENAI_ADMIN_KEY"],
webhook_secret=os.environ.get("OPENAI_WEBHOOK_SECRET"),
base_url=os.environ.get("OPENAI_ADMIN_BASE_URL") or "https://api.openai.com/v1",
max_retries=0,
)
def open_db():
db = sqlite3.connect("events.db")
db.execute(
"""CREATE TABLE IF NOT EXISTS events (
webhook_id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
notification_id TEXT NOT NULL,
received_at INTEGER NOT NULL,
processed INTEGER NOT NULL DEFAULT 0
)"""
)
return dbsync_rules.py:
import json
import openai
from common import make_client
RULES_FILE = "alert_rules.json"
def load_desired():
with open(RULES_FILE) as f:
return json.load(f)
def list_all_rules(client):
rules_api = client.admin.organization.health.alert_rules
rules = []
page = rules_api.list(limit=100)
while True:
rules.extend(page.data)
if not page.next:
return rules
page = rules_api.list(limit=100, page=page.next)
def contains(actual, wanted):
if isinstance(wanted, dict):
return isinstance(actual, dict) and all(k in actual and contains(actual[k], v) for k, v in wanted.items())
return actual == wanted
def matches(rule, desired):
current = rule.model_dump(exclude_none=True)
return all(contains(current.get(key), value) for key, value in desired.items())
def update_rule(client, rule, desired):
rules_api = client.admin.organization.health.alert_rules
try:
return rules_api.update(rule.id, expected_version=rule.version, **desired)
except openai.APIStatusError:
latest = rules_api.retrieve(rule.id)
if matches(latest, desired):
return latest
return rules_api.update(latest.id, expected_version=latest.version, **desired)
def main():
client = make_client()
existing = {rule.name: rule for rule in list_all_rules(client)}
for desired in load_desired():
rule = existing.get(desired["name"])
if rule is None:
created = client.admin.organization.health.alert_rules.create(**desired)
print(f"created {created.name} {created.id} v{created.version}")
elif matches(rule, desired):
print(f"unchanged {rule.name} v{rule.version}")
else:
updated = update_rule(client, rule, desired)
print(f"updated {updated.name} v{rule.version} -> v{updated.version}")
if __name__ == "__main__":
main()cleanup.py:
from common import make_client
from sync_rules import list_all_rules, load_desired
def main():
client = make_client()
names = {rule["name"] for rule in load_desired()}
for rule in list_all_rules(client):
if rule.name in names:
client.admin.organization.health.alert_rules.delete(rule.id, expected_version=rule.version)
print(f"deleted {rule.name}")
if __name__ == "__main__":
main()fake_openai.py:
import json
import re
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
KEY = "sk-admin-fake"
BASE = "/v1/organization/health"
PAGE_SIZE = 2
RULES = {}
RULE_PATH = re.compile(rf"{BASE}/alert_rules/(alertrule_[0-9a-f]{{32}})")
ALERT_PATH = re.compile(rf"{BASE}/alerts/(alertnotif_[0-9a-f]{{32}})")
def expected_version(body, query):
value = body.get("expected_version", query.get("expected_version", [None])[0])
return int(value) if value is not None else None
def canned_alert(alert_id):
rule = next((r for r in RULES.values() if r["condition"].get("type") == "error_rate"), None)
if rule is None:
return None
now = int(time.time())
return {
"id": alert_id,
"alert_rule_id": rule["id"],
"created_at": now,
"occurred_at": now,
"type": "triggered",
"object": "health.alert",
"dimensions": {"model": "example-model", "project_id": "proj_example", "service_tier": "default"},
"window": {"started_at": now - 300, "ended_at": now},
"measurement": {
"type": "error_rate",
"error_count": 60,
"request_count": 1000,
"threshold": rule["condition"]["threshold"],
"value": 0.06,
},
}
class Handler(BaseHTTPRequestHandler):
def send_json(self, status, payload):
data = json.dumps(payload).encode()
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def read_body(self):
length = int(self.headers.get("content-length", 0))
return json.loads(self.rfile.read(length)) if length else {}
def route(self, method):
if self.headers.get("authorization") != f"Bearer {KEY}":
return self.send_json(401, {"error": {"message": "Invalid Admin API key"}})
url = urlparse(self.path)
query = parse_qs(url.query)
try:
body = self.read_body()
except ValueError:
return self.send_json(400, {"error": {"message": "Body is not JSON"}})
if url.path == f"{BASE}/alert_rules":
if method == "GET":
return self.list_rules(query)
if method == "POST":
return self.create_rule(body)
match = RULE_PATH.fullmatch(url.path)
if match:
rule = RULES.get(match.group(1))
if rule is None:
return self.send_json(404, {"error": {"message": "No such rule"}})
if method == "GET":
return self.send_json(200, rule)
if method == "POST":
return self.update_rule(rule, body, query)
if method == "DELETE":
return self.delete_rule(rule, body, query)
match = ALERT_PATH.fullmatch(url.path)
if match and method == "GET":
alert = canned_alert(match.group(1))
if alert is None:
return self.send_json(404, {"error": {"message": "Create an error_rate rule first"}})
return self.send_json(200, alert)
return self.send_json(404, {"error": {"message": "No such route"}})
def list_rules(self, query):
rules = list(RULES.values())
token = query.get("page", [None])[0]
if token is None:
data, following = [], ("p1" if rules else None)
else:
k = int(token[1:])
data = rules[(k - 1) * PAGE_SIZE : k * PAGE_SIZE]
following = f"p{k + 1}" if len(rules) > k * PAGE_SIZE else None
self.send_json(200, {"object": "page", "data": data, "has_more": following is not None, "next": following})
def create_rule(self, body):
now = int(time.time())
rule = {
"id": "alertrule_" + uuid.uuid4().hex,
"object": "health.alert_rule",
"organization_id": "org_fake",
"created_at": now,
"updated_at": now,
"version": 1,
"enabled": body.get("enabled", True),
"name": body["name"],
"condition": body["condition"],
"filters": body.get("filters", {}),
"notifications": body.get("notifications", {}),
}
RULES[rule["id"]] = rule
self.send_json(200, rule)
def update_rule(self, rule, body, query):
if expected_version(body, query) != rule["version"]:
return self.send_json(409, {"error": {"message": "Rule changed, retrieve the latest version and retry"}})
for key in ("condition", "enabled", "filters", "name", "notifications"):
if key in body:
rule[key] = body[key]
rule["version"] += 1
rule["updated_at"] = int(time.time())
self.send_json(200, rule)
def delete_rule(self, rule, body, query):
if expected_version(body, query) != rule["version"]:
return self.send_json(409, {"error": {"message": "Rule changed, retrieve the latest version and retry"}})
del RULES[rule["id"]]
self.send_json(200, {"id": rule["id"], "object": "health.alert_rule.deleted", "deleted": True})
def do_GET(self):
self.route("GET")
def do_POST(self):
self.route("POST")
def do_DELETE(self):
self.route("DELETE")
if __name__ == "__main__":
print("fake Admin API on http://127.0.0.1:8099")
ThreadingHTTPServer(("127.0.0.1", 8099), Handler).serve_forever()receiver.py:
from flask import Flask, request
from openai import InvalidWebhookSignatureError
from common import make_client, open_db
HEALTH_EVENTS = {"health.alert.triggered", "health.alert.resolved"}
app = Flask(__name__)
client = make_client()
open_db().close()
@app.post("/webhook")
def webhook():
raw = request.get_data()
try:
event = client.webhooks.unwrap(raw, request.headers)
except InvalidWebhookSignatureError:
return "invalid signature", 400
if event.type in HEALTH_EVENTS:
db = open_db()
with db:
db.execute(
"INSERT INTO events (webhook_id, event_type, notification_id, received_at) "
"VALUES (?, ?, ?, strftime('%s', 'now')) ON CONFLICT(webhook_id) DO NOTHING",
(request.headers["webhook-id"], event.type, event.data.id),
)
db.close()
return "", 200
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5001)send_test_event.py:
import argparse
import base64
import hashlib
import hmac
import json
import os
import secrets
import time
import urllib.error
import urllib.request
from dotenv import load_dotenv
load_dotenv()
URL = "http://127.0.0.1:5001/webhook"
NOTIFICATION_ID = "alertnotif_" + "a" * 32
def sign(secret, webhook_id, timestamp, body):
key = base64.b64decode(secret[len("whsec_"):])
message = f"{webhook_id}.{timestamp}.".encode() + body
digest = hmac.new(key, message, hashlib.sha256).digest()
return "v1," + base64.b64encode(digest).decode()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--id", default=f"msg_{secrets.token_hex(8)}")
parser.add_argument("--tamper", action="store_true")
args = parser.parse_args()
now = int(time.time())
body = json.dumps(
{
"id": f"evt_{secrets.token_hex(16)}",
"object": "event",
"created_at": now,
"type": "health.alert.triggered",
"data": {"id": NOTIFICATION_ID},
}
).encode()
timestamp = str(now)
signature = sign(os.environ["OPENAI_WEBHOOK_SECRET"], args.id, timestamp, body)
if args.tamper:
body += b" "
request = urllib.request.Request(
URL,
data=body,
method="POST",
headers={
"content-type": "application/json",
"webhook-id": args.id,
"webhook-timestamp": timestamp,
"webhook-signature": signature,
},
)
try:
with urllib.request.urlopen(request) as response:
print(response.status)
except urllib.error.HTTPError as err:
print(err.code)
if __name__ == "__main__":
main()worker.py:
import openai
from common import make_client, open_db
MEASUREMENTS = {
"error_rate": lambda m: f"error_rate {m.value} vs threshold {m.threshold} ({m.error_count} of {m.request_count} requests)",
"prompt_cache_hit_rate": lambda m: f"cache hit rate {m.value} vs threshold {m.threshold} ({m.cached_input_token_count} of {m.input_token_count} input tokens)",
"rate_limit_utilization": lambda m: f"{m.metric} utilization {m.value} vs threshold {m.threshold} for {m.consecutive_minutes} minutes ({m.rate_limit_scope})",
"service_tier_fallback_rate": lambda m: f"fallback rate {m.value} vs threshold {m.threshold} ({m.fallback_count} of {m.eligible_attempt_count} {m.source_tier} attempts)",
}
def main():
client = make_client()
db = open_db()
rows = db.execute("SELECT webhook_id, notification_id FROM events WHERE processed = 0").fetchall()
for webhook_id, notification_id in rows:
try:
alert = client.admin.organization.health.alerts.retrieve(notification_id)
rule = client.admin.organization.health.alert_rules.retrieve(alert.alert_rule_id)
except openai.APIStatusError as err:
print(f"skipped {webhook_id}: {type(err).__name__}")
continue
describe = MEASUREMENTS.get(alert.measurement.type, lambda m: m.type)
print(f"{alert.type} {rule.name}: {describe(alert.measurement)}")
with db:
db.execute("UPDATE events SET processed = 1 WHERE webhook_id = ?", (webhook_id,))
if __name__ == "__main__":
main()Reference
The four rule types
| Metric | API type | Window | Minimum volume |
|---|---|---|---|
| Error rate | error_rate | 300, 900 or 1800 s | 100 matching requests |
| Prompt cache hit rate | prompt_cache_hit_rate | 15 min | 100 requests, 1,000 input tokens with cache data |
| Approaching rate limit | rate_limit_utilization | 1-60 consecutive minutes | Dedicated models unsupported |
| Fast-tier spillover | service_tier_fallback_rate | 5 min | 100 eligible Fast-tier attempts |
Error rate, cache hit rate and spillover rules evaluate once a minute and trigger after two consecutive breaching evaluations. A rate-limit rule triggers after its configured consecutive minutes. Every type resolves after two healthy evaluations. Missing or stale data doesn't count as recovery. Error rate takes status_class of all, 4xx or 5xx, and metric for rate limits is rpm or tpm. A rule's condition type can't change after creation, and enabled=false pauses it.
Notification fields
Every alert carries id, alert_rule_id, created_at, occurred_at, type (triggered or resolved), dimensions and window. The measurement differs by rule type:
Measurement type | Fields besides threshold and value |
|---|---|
error_rate | error_count, request_count |
prompt_cache_hit_rate | cached_input_token_count, input_token_count |
rate_limit_utilization | metric, consecutive_minutes, rate_limit_scope |
service_tier_fallback_rate | source_tier, eligible_attempt_count, fallback_count |
Webhook headers
| Header | Use |
|---|---|
webhook-id | Idempotency key: dedupe on it |
webhook-timestamp | Unix seconds, part of the signed message |
webhook-signature | v1, followed by the base64 HMAC-SHA256 |
The event envelope has the event's own id at the top level and the alert notification's ID in data.id.
Common mistakes
- Writing a threshold as 5 instead of 0.05. Thresholds are fractions (step 3).
- Creating every rule on every run. Match on
nameand update withexpected_version, or you burn slots and duplicate alerts (steps 4 and 5). - Forgetting that disabled rules count toward the 3, 10 or 100 allowance (step 3).
- Parsing the JSON before verifying. The signature covers the raw bytes (step 6).
- Treating
data.idas a rule ID or the top-level event ID. It's the notification ID (step 8). - Fetching the notification with the webhook secret or a project key. It takes the organization Admin key (step 8).
Next steps
- Decide which three rules you keep and whether $500 of qualifying prepaid purchases is worth it for webhooks, using the email-versus-webhook call from the prerequisites. Who should hold an Admin key at all is covered in AI in the engineering workflow: tools, permissions and policy.
- Add project-owned rules under
/v1/organization/projects/{project_id}/health/alert_rules, which use that project's webhook settings. If you use the Fast tier, add aservice_tier_fallback_raterule, and route notifications into Slack or a pager from the worker. - If you call a model on OpenAI's removal list, whose dates run from 11 December 2026 to 1 April 2027, add a rule whose
filtersname that model so its errors alert you on their own. - If you also call Claude, the Claude API tutorial covers errors and limits on that side.
FAQ
Do OpenAI health alerts need webhooks?
No. Email works at every allowance level, from the default 3 rules up. Webhooks need at least $500 in cumulative qualifying prepaid credit purchases, which is also the tier that raises the limit to 100 rules.
What is the difference between Health alerts and the OpenAI status page?
The status page covers OpenAI-wide outages. Health alerts watch your own traffic: your error rate, your cache hit rate, your rate-limit use. That makes them the answer to "how do I check my API health" when the status page is green and your requests still fail.
Why does my error-rate alert not fire?
The rule needs at least 100 matching requests in its window, and it evaluates once a minute, triggering only after two breaching evaluations in a row. A quiet project never reaches the volume floor, so check your request count first.
Can I create health alert rules with the Python SDK?
Yes, from openai 3.62.0. The Admin key goes in OpenAI(admin_api_key=...), and client.admin.organization.health.alert_rules has create, retrieve, update, list and delete, with client.admin.organization.health.alerts.retrieve for notifications. Pin openai>=3.62,<4.
