Triage support tickets and email automatically.
Incoming email and form submissions land in Postgres. A background job asks Canner’s classify endpoint which queue each ticket belongs to and gets a probability for every queue, then routes it by rules you can read. Tickets the model isn’t sure about go to a person, and every probability is stored so you can tune the threshold later. The code below ran end to end against the real endpoint.
Facts checked
What you’ll build
- An inbound webhook,
POST /inbound, that stores each email or form submission as a row and answers202at once. - A worker that takes one ticket at a time and calls
/v1/classifywithgranite-4.2-3bthree times: which category (with priors), whether it needs action today, and whether the writer is upset. - Routing rules in plain code: a queue per category; a probability under 0.7 sends the ticket to a person; cancellation words send it to escalations; urgent tickets get high priority.
- An optional one-line summary from
gemma-4-26b-a4bfor the agent view, written after the ticket is already routed. - Every probability in a `jsonb` column, next to what the person finally decided, so you can measure and tune.
Endpoint, database and project
Create an AI endpoint with the two models and attach it to your project: the project gets OPENAI_BASE_URL and OPENAI_API_KEY on its next deploy, and the openai SDK reads both. The project also needs a Postgres database (it arrives as DATABASE_URL); run schema.sql below once, with psql or your migration tool.
Run the worker inside the web server (the default here) or as a separate Worker project: set RUN_WORKER=off on the web project, start the Worker with node worker.js, attach the same AI endpoint to it, and set DATABASE_URL on the Worker to the web project’s connection string (copy it from the Database tab). A separate Worker keeps slow model calls away from web requests; for a small inbox the single process is fine. More in background jobs.
On Starter, a project with no visitors for 3 hours sleeps. An incoming webhook is a request, so it wakes the app, and the worker picks up where it stopped.
canner ai create triage --models granite-4.2-3b,gemma-4-26b-a4b
canner ai attach triage # in the project folder
canner env set INBOUND_TOKEN=<a long random string> --sensitive
canner redeployThe table
One table holds the ticket, its state in the queue, what the model said and what a person decided. probs keeps every label’s probability for every question, not just the winner: when you change the threshold or the labels later, you can replay the decision on old tickets without calling the model again.
CREATE TABLE tickets (
id bigserial PRIMARY KEY,
source text NOT NULL, -- 'email', 'form', ...
from_addr text,
subject text,
body text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
status text NOT NULL DEFAULT 'new', -- new, working, routed, needs_person, failed
attempts int NOT NULL DEFAULT 0,
claimed_at timestamptz,
last_error text,
-- what the model said, kept for tuning
category text,
category_p real,
urgent_p real,
upset_p real,
probs jsonb, -- every label's probability, per question
model text,
classified_at timestamptz,
-- what we did with it
queue text,
priority text,
summary text,
-- what a person decided, when they re-route or confirm
final_category text
);
CREATE INDEX tickets_todo ON tickets (id) WHERE status IN ('new', 'working');The inbound webhook
Most inbound-email services can turn each message into an HTTP POST to a URL you give them, as JSON or as a form; check your provider’s field names and map them in the handler. An HTML contact form can post to the same route. Most providers only let you configure a URL, so the shared secret travels in the query string, compared in constant time. The token is part of the URL, so it can appear in request logs; rotate it with canner env set if the URL leaks.
The handler only inserts a row and returns 202. The GET /queues/:queue route is a minimal agent view: urgent tickets first, then oldest first.
// db.js
import pg from "pg";
export const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 4 });
// server.js: the inbound webhook, a list for agents, and (optionally) the worker.
import express from "express";
import { timingSafeEqual } from "node:crypto";
import { db } from "./db.js";
import { loop } from "./worker.js";
const app = express();
app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ extended: false, limit: "1mb" })); // HTML forms
// Most inbound-email services can POST each message to a URL. Put a long random
// INBOUND_TOKEN in that URL: https://your-app.example/inbound?token=...
function tokenOk(t = "") {
const a = Buffer.from(String(t)), b = Buffer.from(process.env.INBOUND_TOKEN ?? "");
return b.length > 0 && a.length === b.length && timingSafeEqual(a, b);
}
app.post("/inbound", async (req, res) => {
if (!tokenOk(req.query.token)) return res.sendStatus(401);
// Map your provider's field names here.
const from = req.body.from ?? req.body.email;
const subject = req.body.subject ?? null;
const body = req.body.text ?? req.body.message ?? "";
if (!body.trim()) return res.status(400).json({ error: "empty message" });
const { rows } = await db.query(
"INSERT INTO tickets (source, from_addr, subject, body) VALUES ($1, $2, $3, $4) RETURNING id",
[req.body.source ?? "email", from, subject, body]);
res.status(202).json({ id: rows[0].id }); // the worker classifies it shortly
});
// The agent view: routed tickets by queue, the people's queue first.
app.get("/queues/:queue", async (req, res) => {
const { rows } = await db.query(
`SELECT id, from_addr, subject, summary, category, category_p, priority, received_at
FROM tickets WHERE queue = $1 AND status IN ('routed', 'needs_person')
ORDER BY priority = 'high' DESC, received_at`, [req.params.queue]);
res.json(rows);
});
app.listen(process.env.PORT || 3000);
if (process.env.RUN_WORKER !== "off") loop(); // in-process; set RUN_WORKER=off with a Worker projectClassify, then route
/v1/classify isn’t part of the OpenAI API, so the code calls it through the SDK’s generic ai.post(): same base URL, same key, and the SDK’s retries apply. The answer has a probability for every label; the probabilities are calibrated, so a 0.9 should be right about 9 times in 10 (how).
Write labels the way customers write. “cannot log in, password or account access” works better than “auth”. Labels in English work on French tickets: our French login ticket went to the accounts queue at 0.88.
No catch-all “other”. Calibration removes the model’s standing preference for each label, measured on an empty input, and a vague label is exactly what the model leans to when there’s nothing to read. A ticket that fits no category simply scores low everywhere and goes to a person: our “please send a copy of the contract” ticket topped out at 0.60 (billing) and landed in the people’s queue.
Priors say how common each category is in your inbox. Start with a guess, then use the measured shares (see tuning).
The threshold (0.7 here) is the trade-off between work for people and misrouted tickets. Start cautious and lower it once you’ve measured.
// triage.js: classify one ticket, apply the routing rules, store everything.
import OpenAI from "openai";
import { db } from "./db.js";
// OPENAI_BASE_URL and OPENAI_API_KEY come from the attached endpoint.
// The SDK retries 429 server_busy after the Retry-After the server sends.
const ai = new OpenAI({ maxRetries: 3 });
// Describe each category the way a customer would write it.
// No catch-all "other": anything that fits nothing scores low and goes to a person.
const CATEGORIES = [
{ label: "billing, payment, invoice or refund", queue: "billing", prior: 0.3 },
{ label: "cannot log in, password or account access", queue: "accounts", prior: 0.25 },
{ label: "something is broken or shows an error", queue: "support", prior: 0.25 },
{ label: "asks for a new feature or a change", queue: "product", prior: 0.1 },
{ label: "thanks or compliments, nothing to do", queue: "feedback", prior: 0.1 },
];
// Two-sided questions, not "urgent / normal / low": see "Urgency and sentiment".
const URGENT = ["needs action today: money, access or data at risk", "can wait a few days"];
const UPSET = ["the writer is angry or upset", "the writer is calm or happy"];
// Threats to leave: a word list, not the model (it read polite complaints as threats).
const CANCEL = /\b(cancel\w*|unsubscribe|lawyer|chargeback|annul\w*|résili\w*|avocat)\b/i;
const CONFIDENT = 0.7; // below this, a person routes the ticket (tune it later)
async function classify(input, labels, priors) {
return ai.post("/classify", { body: { model: "granite-4.2-3b", input, labels, priors } });
}
const p = (r, label) => r.labels.find((l) => l.label === label).probability;
const asMap = (r) => Object.fromEntries(r.labels.map((l) => [l.label, l.probability]));
export async function triage(ticket) {
const text = `Subject: ${ticket.subject ?? ""}\n\n${ticket.body}`.slice(0, 4000);
// One request at a time on the server side, so sequential is as fast as parallel.
const cat = await classify(text, CATEGORIES.map((c) => c.label), CATEGORIES.map((c) => c.prior));
const urg = await classify(text, URGENT);
const mood = await classify(text, UPSET);
const best = CATEGORIES.find((c) => c.label === cat.prediction);
const category_p = p(cat, cat.prediction);
const urgent_p = p(urg, URGENT[0]);
const upset_p = p(mood, UPSET[0]); // for sorting the agent view, not for routing
// Routing rules: plain code, easy to read and to change.
let queue = best.queue;
let status = "routed";
if (category_p < CONFIDENT) { queue = "triage"; status = "needs_person"; }
if (CANCEL.test(text)) queue = "escalations";
const priority = urgent_p >= 0.8 ? "high" : "normal";
await db.query(
`UPDATE tickets SET status = $2, category = $3, category_p = $4, urgent_p = $5, upset_p = $6,
probs = $7, model = 'granite-4.2-3b', classified_at = now(), queue = $8, priority = $9
WHERE id = $1`,
[ticket.id, status, best.queue, category_p, urgent_p, upset_p,
JSON.stringify({ category: asMap(cat), urgent: asMap(urg), upset: asMap(mood) }), queue, priority]);
return { status, queue, priority, category: best.queue, category_p, urgent_p, upset_p };
}
// Optional: a one-line summary for the agent view. Slower than classifying,
// so it runs after the ticket is already routed.
export async function summarise(ticket) {
const r = await ai.chat.completions.create({
model: "gemma-4-26b-a4b",
max_tokens: 60,
messages: [
{ role: "system", content: "Summarise the support ticket in one line of at most 20 words, in the ticket's language. No preamble." },
{ role: "user", content: `${ticket.subject ?? ""}\n\n${ticket.body}`.slice(0, 4000) },
],
});
const choice = r.choices[0];
if (choice.finish_reason === "content_filter") return null; // blocked: leave it empty
const summary = choice.message.content.trim();
await db.query("UPDATE tickets SET summary = $2 WHERE id = $1", [ticket.id, summary]);
return summary;
}Urgency and sentiment: what worked and what didn’t
We tested several ways to ask for urgency and mood on the same tickets. The pattern: a middle label (“normal”, “neutral”, “calm”) is close to what the model says about an empty text, so calibration pushes it down, and the extremes win instead. Two-sided questions behave much better.
| Question and labels | What happened | Verdict |
|---|---|---|
| Urgency: “urgent / normal / low” | “Charged twice, please refund” came out low (0.73); a thank-you note came out normal (0.78) | Don’t use a three-level scale |
| Urgency: “needs action today: money, access or data at risk” / “can wait a few days” | Login lockout and lost data: 0.86 to 0.98 urgent. Thank-you note: 0.09. Double charge: 0.799, just under our 0.8 cut-off | Use this |
| Mood: “angry or frustrated / neutral / happy” | The polite refund request came out angry (0.97); “neutral” never won | Middle label crushed |
| Mood: “angry or upset” / “calm or happy” | Praise is clearly calm; every complaint, polite or not, reads as upset | Fine for sorting, not for measuring anger |
| Churn: “threatens to cancel, leave or complain publicly” / “no threat to cancel or leave” | The polite double-charge ticket scored 0.95 as a threat; so did the French login ticket | Replaced with a word list |
The worker
The worker claims one ticket with FOR UPDATE SKIP LOCKED, so two workers never take the same row, and handles it outside any transaction: a model call can wait in the queue, and you don’t want a transaction open meanwhile.
One at a time is the right speed: the service answers one request at a time across all customers, and an organization can have 4 requests waiting; beyond that the API answers 429 server_busy with a Retry-After header. The openai SDK retries 429s after the time the server asks for, so the worker just waits. A ticket that fails three times goes to a person with the error stored; one left in working by a crash or a deploy is taken again after 10 minutes.
// worker.js: take new tickets one at a time. Run it inside the web server
// (import "./worker.js") or as its own Worker project (node worker.js).
import { pathToFileURL } from "node:url";
import { db } from "./db.js";
import { triage, summarise } from "./triage.js";
async function claim() {
// SKIP LOCKED: two workers never take the same ticket. A ticket left in
// 'working' for 10 minutes (crash, deploy) is taken again.
const { rows } = await db.query(
`UPDATE tickets SET status = 'working', attempts = attempts + 1, claimed_at = now()
WHERE id = (SELECT id FROM tickets
WHERE status = 'new'
OR (status = 'working' AND claimed_at < now() - interval '10 minutes')
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING *`);
return rows[0];
}
export async function runOnce() {
const t = await claim();
if (!t) return false;
try {
await triage(t);
if (process.env.TRIAGE_SUMMARY !== "off") await summarise(t);
} catch (err) {
// Back to 'new' for another try, or to a person after 3.
await db.query(
`UPDATE tickets SET last_error = $2,
status = CASE WHEN attempts >= 3 THEN 'needs_person' ELSE 'new' END,
queue = CASE WHEN attempts >= 3 THEN 'triage' ELSE queue END
WHERE id = $1`, [t.id, String(err.message ?? err)]);
}
return true;
}
export async function loop() {
for (;;) {
const didWork = await runOnce().catch((e) => { console.error(e); return false; });
if (!didWork) await new Promise((r) => setTimeout(r, 5000)); // idle: look again in 5 s
}
}
// `node worker.js` (a Worker project) starts the loop; importing it doesn't.
if (import.meta.url === pathToFileURL(process.argv[1]).href) loop();A one-line summary for the agent view
summarise() in triage.js asks gemma-4-26b-a4b for one line in the ticket’s language, capped at 60 tokens. It runs after the ticket is routed, so a slow summary never delays routing. Our French ticket came back in French: “Impossible de se connecter car le mot de passe est reconnu comme invalide, malgré l’urgence de la paie.”
Chat requests go through Canner’s safety check; an answer it blocks comes back empty with finish_reason: "content_filter", and the code leaves the summary empty. Classify requests aren’t checked. Summaries are the costly part of this workflow: set TRIAGE_SUMMARY=off on the project that runs the worker (the web project, or the Worker project if you split them) if your agents read the ticket anyway.
Tune the threshold and the priors
When an agent confirms or re-routes a ticket, store their answer in final_category. After a few hundred tickets, the first query shows how often the model was right in each confidence band: raise CONFIDENT until the band just above it is right as often as you need, or lower it if people are confirming nearly everything they get. The second gives the real share of each category, to use as the new priors.
Because probs keeps every label’s probability, you can test a new threshold on last month’s tickets in SQL before changing the code.
-- When a person confirms or re-routes a ticket, store their answer:
-- UPDATE tickets SET final_category = 'accounts' WHERE id = $1;
-- 1. How often the model was right, by confidence band. Raise CONFIDENT
-- until the band just above it is right as often as you need.
SELECT width_bucket(category_p::numeric, 0.5, 1.0, 5) AS band,
round(min(category_p)::numeric, 2) AS from_p,
count(*) AS tickets,
round(avg((category = final_category)::int), 2) AS right_share
FROM tickets
WHERE final_category IS NOT NULL
GROUP BY band ORDER BY band;
-- 2. How common each category really is: use these shares as the new priors.
SELECT final_category,
round(count(*)::numeric / sum(count(*)) OVER (), 2) AS share
FROM tickets
WHERE final_category IS NOT NULL
AND received_at > now() - interval '90 days'
GROUP BY final_category ORDER BY share DESC;The same call from Python
The Python SDK has the same escape hatch: client.post() with cast_to=object returns the JSON as a dict. The rest of the workflow (table, rules, worker) carries over as is; with Django or Flask, run the worker as a management command or a Worker project.
# classify.py: the same call from Python (Django, Flask, a Celery-free worker...)
from openai import OpenAI
client = OpenAI(max_retries=3) # OPENAI_BASE_URL + OPENAI_API_KEY
LABELS = ["billing, payment, invoice or refund", "cannot log in, password or account access",
"something is broken or shows an error", "asks for a new feature or a change",
"thanks or compliments, nothing to do"]
PRIORS = [0.3, 0.25, 0.25, 0.1, 0.1]
def classify(text: str) -> dict:
# /v1/classify isn't part of the OpenAI API, so call it through the client's post().
r = client.post("/classify", cast_to=object, body={
"model": "granite-4.2-3b", "input": text[:4000], "labels": LABELS, "priors": PRIORS})
return {l["label"]: l["probability"] for l in r["labels"]}
if __name__ == "__main__":
probs = classify("Bonjour, ma carte a été débitée deux fois pour la facture de novembre.")
best = max(probs, key=probs.get)
print(best, round(probs[best], 3), "-> a person" if probs[best] < 0.7 else "-> routed")What our test run did
Five tickets through the webhook, into Postgres, through the worker and the real endpoint, with the code above:
| Ticket | Category (probability) | Needs action today | Where it went |
|---|---|---|---|
| “I was charged twice for my November invoice. Please refund the extra charge.” | billing (1.00) | 0.799 | billing, normal priority (just under 0.8) |
| « Je n’arrive plus à me connecter… C’est urgent, ma paie est due aujourd’hui! » | accounts (0.88) | 0.86 | accounts, high priority |
| “Thanks so much, the new export feature is great” | feedback (0.77) | 0.09 | feedback |
| “Third time I’m writing… deleted half my customer list… fix it today or I’m cancelling” | support (0.91) | 0.98 | escalations, high priority |
| “Could you send me a copy of the service agreement we signed in March?” | billing (0.60) | 0.24 | a person (below 0.7) |
When this isn’t the right tool
Ticket text is processed in memory on Canner’s server in Montréal and never stored there; nothing is sent to another company or used for training. The tickets themselves live in your own Postgres database.
- High volume. The service answers one request at a time, and each ticket here takes three classify calls. That suits a support inbox, not a stream of thousands of messages an hour.
- Attachments. The endpoints read text only. Screenshots and PDFs attached to an email aren’t seen; for PDFs with a text layer, see document extraction.
- Instant answers to the customer. This sorts tickets for people. Writing replies is a different job, with a person checking them.
- Usage. Classify calls are the cheap part; summaries cost the most model time. Usage is measured in model time with a monthly allowance per plan: see AI endpoints for current allowances, and set a requests-per-minute limit on the endpoint to protect it from a runaway loop.
Questions
Can I use AI to classify support tickets in French and English?
Yes. The labels can stay in English: both French tickets in our tests went to the right category with English labels. Probabilities come back for every label, so a ticket the model isn’t sure about can go to a person.
Is /v1/classify better than asking a chat model for a category?
For routing, yes: you get a calibrated probability for every label in one short request, instead of a word you have to parse and no confidence. Classify requests also aren’t subject to the content filter that checks chat.
Does sentiment analysis through classify work?
For clear cases. Praise versus complaint is reliable; telling a polite complaint from an angry one is not, with a 3-billion-parameter model. Avoid a middle label like “neutral”, which calibration pushes down.
What happens if the AI service is busy?
The request waits its turn, up to 2 minutes. Past 4 waiting requests per organization, the API answers 429 server_busy with Retry-After; the openai SDK waits and retries. Tickets stay in Postgres meanwhile, so nothing is lost.
Where is ticket text processed?
On Canner’s server in Montréal, in memory. Prompts and answers aren’t stored, sent to another company or used for training.
Related
- GuideAn assistant that answers questions from your database
- GuideSummarise email threads and meeting notes
- GuideDraft French versions of your app and emails
- GuideChatGPT, Copilot and GitHub Copilot: what they keep
- GuideGenerative AI in Quebec and Law 25
- GuideCanadian AI companies: who builds, who hosts, where prompts go
Sort the inbox in Montréal, in your own database.
Attach an AI endpoint to a project, add a database, and the triage worker runs next to your app.