Content moderation and spam filtering with calibrated labels.
When a comment or listing arrives, send it to the classify endpoint with your labels (ok, spam, harassment, off-topic) and how common each one is on your site. You get a calibrated probability for every label: publish what is clearly fine, reject what is clearly spam, and put everything else in front of a person. Store the probabilities, and let the reviews tell you where to set the thresholds.
Facts checked
What you’re building
A comment endpoint that accepts the comment at once and shows it as “awaiting moderation”, a background worker that classifies each new comment with granite-4.2-3b and decides, a review queue for the comments it isn’t sure about, and a query that turns your reviewers’ decisions into better thresholds. The same design works for marketplace listings, reviews, profile bios or contact-form messages: change the labels and the instruction.
It is one Node app (Express, the openai SDK and pg) on any Postgres database; no extension is needed. Classifying a short comment takes a few seconds at most, but the service answers one request at a time, so a comment can wait in the queue. That is why classification runs in the background and never holds up the person posting.
What “calibrated” means
The classify endpoint asks the model which of your labels fits the text and scores every label, not just the winner. Two corrections make those scores usable as probabilities. First, the model’s standing preference for some labels is measured against an empty input and removed. Second, the scores are softened so that “90%” means right about 9 times in 10. On public test sets, Canner measured a gap between stated confidence and actual accuracy of 0.07 (English news topics) and 0.03 (French film reviews); see AI endpoints.
Priors say how common each label is in your data before the model reads anything. They enter the calculation the way a base rate does: on a blog where 85% of comments are fine, a short, ambiguous comment should lean towards ok. In our test, “Can I freeze the leftovers?” came out at 0.99 ok with the priors in the code and 0.77 without priors. Without them, every short question would land in the review queue.
Calibrated doesn’t mean right. It means the confidence is honest on average, which is what lets you pick a threshold and predict how many mistakes it lets through. Canner measured that on two public test sets; with your own labels, instruction and priors, check it on reviewed comments with the tuning query below.
POST https://ai.canner.ca/v1/classify
{ "model": "granite-4.2-3b",
"instruction": "These are reader comments on a recipe blog. Classify the comment.",
"input": "Great recipe! Check out my site for cheap Ray-Ban sunglasses www.cheap-shades.biz",
"labels": ["ok", "spam", "harassment", "off-topic"],
"priors": [0.85, 0.08, 0.03, 0.04] }
→ { "prediction": "spam",
"labels": [ { "label": "spam", "probability": 0.72, ... },
{ "label": "ok", "probability": 0.15, ... }, ... ] }Labels, instruction and priors
- Labels are short phrases the model reads, up to 20. Plain words work best:
ok,spam,harassment,off-topic. Keep them distinct; two labels that overlap split the probability between them. - The instruction tells the model what it is looking at. “These are reader comments on a recipe blog” is what makes “Anyone know a good mechanic in Laval?” off-topic rather than ok.
- Priors should come from your own data. Start with a guess, then replace it with the shares the second query in “Tune the thresholds” gives you once people have reviewed a few hundred comments.
What it did on our test comments
Twelve of the fourteen comments we sent, with the thresholds in the code (publish at p(ok) ≥ 0.9, reject at p(spam) ≥ 0.9, otherwise hold). The two not shown: another ordinary comment, published at 0.99, and a second insult, labelled harassment at 0.94 and held.
- Nothing wrong was published, nothing fine was rejected. The clear cases went through automatically; the rest waited for a person.
- Harsh but legitimate criticism was held, not rejected. “This recipe is terrible…” got 0.58 ok. “Are you even a cook?” was labelled harassment at 0.91: whether a dig at the author crosses your line is a policy decision, and the review queue is where you make it.
- Soft spam is uncertain. A link-drop that opens with a compliment scored 0.72 and 0.55 spam. Holding those costs a reviewer a click; auto-rejecting at 0.5 would also start rejecting real comments that mention a link.
- French works the same way. The French spam and the French recipe comment were classified as confidently as the English ones.
| Comment (excerpt) | Expected | Top label | p(ok) | p(spam) | Decision |
|---|---|---|---|---|---|
| “Made this last night with chicken thighs… a bit more garlic next time.” | ok | ok | 1.00 | 0.00 | published |
| “Can I freeze the leftovers?” | ok | ok | 0.99 | 0.00 | published |
| “J’ai essayé avec du sirop d’érable au lieu du miel, c’était délicieux!” | ok | ok | 0.99 | 0.00 | published |
| “This recipe is terrible, the timings are all wrong and my cake burned.” | ok | ok | 0.58 | 0.11 | held |
| “This is the worst recipe I’ve ever seen, are you even a cook?” | ok (rude) | harassment (0.91) | 0.01 | 0.05 | held |
| “Earn $5000 a week working from home, message me on WhatsApp…” | spam | spam | 0.01 | 0.98 | rejected |
| “Gagnez de l’argent rapidement! Cliquez ici : bit.ly/…” | spam | spam | 0.01 | 0.99 | rejected |
| “Great recipe! Check out my site for cheap Ray-Ban sunglasses…” | spam | spam | 0.15 | 0.72 | held |
| “Nice post. Visit my blog too :) myfoodblog.example” | spam | spam | 0.21 | 0.55 | held |
| “You’re a moron and your kids must be embarrassed by you.” | harassment | harassment (0.97) | 0.00 | 0.03 | held |
| “Who do you think will win the election next month?” | off-topic | off-topic (0.85) | 0.01 | 0.10 | held |
| “Anyone know a good mechanic in Laval?” | off-topic | off-topic (0.86) | 0.07 | 0.06 | held |
Schema
Every comment keeps the model’s top label and the probability of every label, so you can re-decide old comments with new thresholds without calling the model again. audit marks a random share of all classified comments, whatever the decision, which also go to review; without it, you would only ever see the cases the model was unsure about and never learn how often its confident decisions are wrong.
CREATE TABLE comments (
id bigserial PRIMARY KEY,
post_id bigint NOT NULL,
author text NOT NULL,
body text NOT NULL,
status text NOT NULL DEFAULT 'pending', -- pending, published, held, rejected
label text, -- the model's top label
probabilities jsonb, -- every label's calibrated probability
audit boolean NOT NULL DEFAULT false, -- a random sample sent to review too
reviewed text, -- the label a person gave it
reviewed_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON comments (status, created_at);
CREATE INDEX ON comments (post_id, created_at) WHERE status = 'published';The app: accept, classify in the background, review
POST /api/posts/:post/comments stores the comment as pending, answers 202 right away and wakes the worker. The worker takes pending comments one at a time, calls classify, and sets the status. If the call fails (the service is busy past the SDK’s retries, or restarting), the comment is held for a person rather than published unchecked. A timer runs the worker every 30 seconds too, so comments left pending by a restart are picked up.
The review queue lists held comments and the audit sample; a reviewer posts the right label, which publishes or rejects the comment and records the label for tuning. Put the /admin routes behind your admin login.
import express from "express";
import OpenAI from "openai";
import pg from "pg";
const ai = new OpenAI({ maxRetries: 3 }); // retries 429 server_busy after Retry-After
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
const LABELS = ["ok", "spam", "harassment", "off-topic"];
const PRIORS = [0.85, 0.08, 0.03, 0.04]; // how common each label is on YOUR site (from the review data)
const PUBLISH = 0.9; // p(ok) at or above: publish
const REJECT = 0.9; // p(spam) at or above: reject
const AUDIT = 0.05; // share of automatic decisions also sent to review
async function classify(text) {
const r = await ai.post("/classify", {
body: {
model: "granite-4.2-3b",
instruction: "These are reader comments on a recipe blog. Classify the comment.",
input: text.slice(0, 4000),
labels: LABELS,
priors: PRIORS,
},
});
return Object.fromEntries(r.labels.map((l) => [l.label, l.probability]));
}
function decide(p) {
if (p.ok >= PUBLISH) return "published";
if (p.spam >= REJECT) return "rejected";
return "held"; // everything unsure, and every harassment, goes to a person
}
// Worker: one comment at a time, in the background, in this one process. Pending rows wait in the
// table, so a restart loses nothing. Several instances? Use a job queue (pg-boss) instead.
async function work() {
for (;;) {
const { rows: [c] } = await db.query(
"SELECT id, body FROM comments WHERE status = 'pending' ORDER BY id LIMIT 1");
if (!c) return;
let p;
try {
p = await classify(c.body);
} catch (err) {
console.error(`comment ${c.id}:`, err.status ?? err.message);
await db.query("UPDATE comments SET status = 'held' WHERE id = $1", [c.id]); // a person decides
continue;
}
const label = Object.entries(p).sort((a, b) => b[1] - a[1])[0][0];
await db.query(
"UPDATE comments SET status = $2, label = $3, probabilities = $4, audit = $5 WHERE id = $1",
[c.id, decide(p), label, JSON.stringify(p), Math.random() < AUDIT]);
}
}
let running = false;
async function kick() {
if (running) return;
running = true;
try { await work(); } catch (err) { console.error(err); } finally { running = false; }
}
setInterval(kick, 30_000); // also picks up anything left after a restart
const app = express();
app.use(express.json());
app.post("/api/posts/:post/comments", async (req, res) => {
const body = String(req.body.body ?? "").trim();
if (!body) return res.status(400).json({ error: "body is required" });
const { rows: [c] } = await db.query(
"INSERT INTO comments (post_id, author, body) VALUES ($1, $2, $3) RETURNING id",
[req.params.post, String(req.body.author ?? "anonymous").slice(0, 80), body.slice(0, 10_000)]);
res.status(202).json({ id: c.id, status: "pending" }); // shown as "awaiting moderation"
kick();
});
app.get("/api/posts/:post/comments", async (req, res) => {
const { rows } = await db.query(
"SELECT id, author, body, created_at FROM comments WHERE post_id = $1 AND status = 'published' ORDER BY created_at",
[req.params.post]);
res.json(rows);
});
// Review queue (put it behind your admin login).
app.get("/admin/review", async (req, res) => {
const { rows } = await db.query(
`SELECT id, post_id, author, body, status, label, probabilities FROM comments
WHERE reviewed IS NULL AND (status = 'held' OR audit)
ORDER BY created_at LIMIT 50`);
res.json(rows);
});
app.post("/admin/review/:id", async (req, res) => {
const label = req.body.label;
if (!LABELS.includes(label)) return res.status(400).json({ error: `label must be one of ${LABELS}` });
const { rowCount } = await db.query(
"UPDATE comments SET reviewed = $2, reviewed_at = now(), status = $3 WHERE id = $1",
[req.params.id, label, label === "ok" ? "published" : "rejected"]);
res.status(rowCount ? 204 : 404).end();
});
app.listen(process.env.PORT || 3000);Tune the thresholds from your own data
After a few hundred reviews, run this. For each candidate publish threshold it counts how many reviewed comments would have been published automatically, how many of those a person did not call ok, and how many ok comments would still wait for review. Pick the lowest threshold whose wrongly-published count you can live with. The same query with spam and reviewed = 'spam' sets the reject threshold. The second query gives the label shares to use as priors.
Reviewed comments are skewed towards the hard cases, because most of them were held. The audit sample is what keeps the counts honest; if you change thresholds based on held comments alone, you will overestimate the mistakes. For counts that hold for all comments, add AND audit to the first query too, once the audit sample is large enough.
-- For each threshold: of the comments a person reviewed, how many would have been
-- published automatically, and how many of those a person did NOT call ok.
SELECT t AS publish_at,
count(*) FILTER (WHERE (probabilities->>'ok')::float >= t) AS auto_published,
count(*) FILTER (WHERE (probabilities->>'ok')::float >= t AND reviewed <> 'ok') AS wrongly_published,
count(*) FILTER (WHERE (probabilities->>'ok')::float < t AND reviewed = 'ok') AS ok_but_held
FROM comments, unnest(ARRAY[0.5, 0.7, 0.8, 0.9, 0.95, 0.99]) AS t
WHERE reviewed IS NOT NULL AND probabilities IS NOT NULL
GROUP BY t ORDER BY t;
-- Priors: how common each label really is, from the random audit sample (held comments overstate the bad ones).
-- Give a label the sample never shows a small share such as 0.01: every prior must be above zero.
SELECT reviewed AS label, round(count(*)::numeric / sum(count(*)) OVER (), 3) AS share
FROM comments WHERE reviewed IS NOT NULL AND audit GROUP BY reviewed ORDER BY share DESC;The same decision in Python
The OpenAI Python SDK has no classify method, but client.post sends any request to the endpoint with the same key and retries. In our test this printed ('rejected', {'spam': 0.99…}) for the French spam comment.
from openai import OpenAI
client = OpenAI() # OPENAI_BASE_URL + OPENAI_API_KEY from the attached endpoint
LABELS = ["ok", "spam", "harassment", "off-topic"]
PRIORS = [0.85, 0.08, 0.03, 0.04]
def moderate(text: str) -> tuple[str, dict[str, float]]:
r = client.post("/classify", cast_to=object, body={
"model": "granite-4.2-3b",
"instruction": "These are reader comments on a recipe blog. Classify the comment.",
"input": text[:4000],
"labels": LABELS,
"priors": PRIORS,
})
p = {l["label"]: l["probability"] for l in r["labels"]}
if p["ok"] >= 0.9:
return "published", p
if p["spam"] >= 0.9:
return "rejected", p
return "held", p
if __name__ == "__main__":
print(moderate("Gagnez de l'argent rapidement! Cliquez ici : bit.ly/xyz-promo"))Deploy it on Canner
Create an AI endpoint with Granite, attach it to the project and redeploy: the project gets OPENAI_BASE_URL and OPENAI_API_KEY, which the SDK reads on its own. Create the table from schema.sql in your release command or migration tool. The shared Postgres tier is enough; no extension is used.
canner ai create moderation --models granite-4.2-3b
canner ai attach moderation # in the project folder
canner redeploy # the project now has OPENAI_BASE_URL and OPENAI_API_KEYKeep usage down
Usage is measured in model time, with a monthly allowance per plan; see AI endpoints for current allowances. A classify call on a short comment is one of the cheapest requests the service handles, and every label costs a little more, so:
- Filter before the model. Rate-limit posting, drop exact duplicates, and skip comments from users you already trust.
- Keep the label list short. Four labels cost less than twelve and are easier to calibrate.
- Truncate. The code sends the first 4,000 characters; spam declares itself early.
- Classify once. The stored probabilities let you re-run the decision on new thresholds with SQL, not with the model.
- Set a requests-per-minute limit on the endpoint, so a spam wave can’t use up the month’s allowance. The SDK waits and retries; a comment still over the limit after that is held for a person.
Limits, and when another tool fits better
- The content policy doesn’t apply to classify. Chat and uncertainty requests are checked by a safety model; classify is not, so it can label abusive or offensive text without the request being blocked. That is what makes it usable for moderation.
- It supports your policy; it isn’t a legal judgment. A probability of harassment is a model’s reading of a text, not a finding about the person who wrote it or about what the law allows. Keep people in the loop for anything you remove that isn’t obvious spam, and give users a way to appeal.
- Text only. Images, video and audio need another service. A comment that is just a link is judged on the link text, not on what the page contains.
- Volume. One request at a time across the service, paid plans first. A request waits up to 2 minutes and an organization can have 4 waiting before
429 server_busy. A site receiving many comments a second needs a GPU-hosted classifier or a dedicated spam service. - Your data. Comments are processed in memory in Montréal and not stored by the endpoint; nothing goes to another company or into training. The comments and probabilities stay in your database.
Questions
What is a content moderation API?
An API that reads user-generated text and tells you whether it breaks your rules: spam, harassment, off-topic and so on. The classify endpoint returns a calibrated probability for each label you define, so your app can publish, hold or reject automatically and send the uncertain cases to a person.
How accurate is the spam detection?
On our test comments, every clear spam was rejected and no legitimate comment was rejected or wrongly published; soft spam (a link after a compliment) was held for review. Accuracy depends on your labels, instruction and priors, so measure it on your own reviewed comments with the tuning query.
Can the model label offensive or abusive comments?
Yes. The content policy that checks chat requests doesn’t apply to classify, so harassment and slurs can be sent and labelled. The label is an input to your moderation decision, not a legal judgment.
Does it work for French comments?
Yes. French spam and French comments were classified as confidently as English ones in our test, with the same English labels and instruction.
What threshold should I use?
Start by publishing at p(ok) ≥ 0.9, rejecting at p(spam) ≥ 0.9 and holding the rest. After a few hundred reviews, use the tuning query to see how many mistakes each threshold would have let through, and adjust.
Related
- GuideSemantic and hybrid search in Postgres
- GuideRelated articles, recommendations and reranking
- GuideTriage support tickets and email automatically
- GuideExtract invoice and form data into Postgres
- GuideAn assistant that answers questions from your database
- GuideSummarise email threads and meeting notes
Comment moderation on models hosted in Montréal.
Create an AI endpoint with Granite and attach it to your project. See AI endpoints for models and allowances.