Summarise email threads and meeting notes in English and French.
A background job reads each long thread or transcript, and a model turns it into a few bullets, the decisions, the proposals nobody agreed to yet, the warnings, and the action items with an owner and a due date, as JSON that always matches your schema. Results go into Postgres and out in a daily digest, in the thread’s language or translated. We tested it on a thread with a trap and kept the model that didn’t fall in.
Facts checked
What the job produces
A summary people can act on needs more than prose. The schema below asks for five things: up to six summary bullets; decisions, with who made them; proposals, the ideas that were raised but not agreed; cautions, anything the thread says must not be done; and action items with an owner, a due date in YYYY-MM-DD and a status.
Proposals and cautions are there because of how summaries go wrong. A model asked only for “decisions” tends to promote a suggestion into one, and a warning such as “don’t re-run that import” is easy to lose in a bullet. Giving each its own field is what made the difference in our tests.
With response_format and a JSON schema, the output from Canner’s AI endpoints always parses and always has those fields, including the date pattern. It can still be wrong: the schema guarantees shape, not truth.
Three tables: threads, jobs, summaries
Store the thread as plain text, a job row next to it, and the result as jsonb. Inserting the thread and its job in one transaction means nothing is ever left unsummarised. output_lang is empty to keep the thread’s language, or en / fr to translate.
CREATE TABLE threads (
id bigserial PRIMARY KEY,
subject text NOT NULL,
body text NOT NULL, -- the thread or transcript as plain text
output_lang text CHECK (output_lang IN ('en', 'fr')), -- NULL: keep the thread's language
received_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE summary_jobs (
thread_id bigint PRIMARY KEY REFERENCES threads(id) ON DELETE CASCADE,
state text NOT NULL DEFAULT 'queued'
CHECK (state IN ('queued', 'running', 'done', 'failed')),
attempts int NOT NULL DEFAULT 0,
last_error text,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE summaries (
thread_id bigint PRIMARY KEY REFERENCES threads(id) ON DELETE CASCADE,
model text NOT NULL,
result jsonb NOT NULL, -- matches SUMMARY_SCHEMA
created_at timestamptz NOT NULL DEFAULT now()
);
-- Enqueue in the same transaction as the thread:
-- INSERT INTO threads (subject, body) VALUES ($1, $2) RETURNING id;
-- INSERT INTO summary_jobs (thread_id) VALUES ($1);The summariser: one call, or map-reduce for long threads
The instructions carry the rules that matter: a suggestion is not a decision, a later message overrides an earlier one, relative dates are resolved against the date of the message that contains them, and an item is done only when a later message says so. temperature: 0 keeps reruns stable.
The chat endpoint takes up to 16,384 tokens of context and writes up to 2,048. Most threads and one-hour meeting notes fit in one call. Above the threshold, the code splits the text on message or paragraph boundaries, summarises each part in order, then merges the partial summaries with the rule that later parts win. The token estimate is deliberately rough (about three characters per token); it only has to keep you under the limit.
Choose the output language once, before splitting. In our first map-reduce run the parts were summarised separately, the part holding the English messages came back in English, and the merged result mixed both languages. guessLanguage fixes that for bilingual threads; pass outputLang when you know what the reader wants.
// summarize.js
import OpenAI from "openai";
const ai = new OpenAI({ maxRetries: 4 }); // retries 429 server_busy after Retry-After
const SUMMARY_SCHEMA = {
type: "object",
additionalProperties: false,
required: ["summary", "decisions", "proposals", "cautions", "action_items"],
properties: {
summary: { type: "array", maxItems: 6, items: { type: "string" } },
decisions: {
type: "array",
items: {
type: "object", additionalProperties: false,
required: ["decision", "decided_by"],
properties: { decision: { type: "string" }, decided_by: { type: ["string", "null"] } },
},
},
proposals: { type: "array", items: { type: "string" } }, // ideas nobody agreed to yet
cautions: { type: "array", items: { type: "string" } }, // "do NOT do X", stated in the thread
action_items: {
type: "array",
items: {
type: "object", additionalProperties: false,
required: ["task", "owner", "due", "status"],
properties: {
task: { type: "string" },
owner: { type: ["string", "null"] },
due: { type: ["string", "null"], pattern: "^\\d{4}-\\d{2}-\\d{2}$" },
status: { type: "string", enum: ["open", "done"] },
},
},
},
},
};
const LANGS = { en: "English", fr: "French (Québec)" };
function instructions(outputLang, referenceDate) {
const lang = outputLang ? `Write everything in ${LANGS[outputLang]}.`
: "Write in the language most of the thread is written in.";
return `You summarise email threads and meeting notes for busy colleagues.
${lang}
- summary: at most 6 short bullets, the facts someone needs if they read nothing else.
- decisions: only what the participants explicitly agreed or decided. A suggestion, an idea, or "we could..." is NOT a decision: put it in proposals.
- When a later message corrects an earlier one, the later message wins. Never repeat a corrected claim as fact.
- cautions: anything the thread says must NOT be done, with its meaning kept exactly.
- action_items: who does what, by when. due is YYYY-MM-DD: resolve "Friday" or "tomorrow" against the date of the message that says it; null when no date was given. status is "done" only when a later message reports the task finished; a promise to do it is "open".
- Use names as written. Don't invent anything.
The thread starts on or after ${referenceDate}.`;
}
// Rough token estimate: about 3 characters per token for English and French text.
const estimateTokens = (s) => Math.ceil(s.length / 3);
const SINGLE_PASS_TOKENS = 11_000; // 16,384 context minus the instructions and up to 2,048 tokens of output
async function summariseOnce(text, { model, outputLang, referenceDate }) {
const r = await ai.chat.completions.create({
model,
temperature: 0,
max_tokens: 1500,
response_format: { type: "json_schema", json_schema: { name: "summary", strict: true, schema: SUMMARY_SCHEMA } },
messages: [
{ role: "system", content: instructions(outputLang, referenceDate) },
{ role: "user", content: text },
],
});
const choice = r.choices[0];
if (choice.finish_reason === "content_filter") throw new Error("blocked by the content policy");
if (choice.finish_reason === "length") throw new Error("answer cut off: shorten the input or the schema");
return JSON.parse(choice.message.content);
}
// Count common short words of each language; good enough to pick en or fr.
function guessLanguage(text) {
const words = text.toLowerCase().match(/\p{L}+/gu) ?? [];
const fr = new Set(["le", "la", "les", "des", "est", "et", "pour", "une", "pas", "que", "on", "du"]);
const en = new Set(["the", "is", "and", "for", "a", "not", "that", "we", "to", "of", "it"]);
let score = 0;
for (const w of words) score += fr.has(w) ? 1 : en.has(w) ? -1 : 0;
return score > 0 ? "fr" : "en";
}
// Split on message or paragraph boundaries, never mid-sentence.
function splitIntoChunks(text, maxTokens) {
const parts = text.split(/\n(?=---\n|From: )|\n{2,}/);
const chunks = [];
let current = "";
for (const p of parts) {
if (current && estimateTokens(current + "\n\n" + p) > maxTokens) {
chunks.push(current);
current = p;
} else {
current = current ? current + "\n\n" + p : p;
}
}
if (current) chunks.push(current);
return chunks;
}
export async function summarise(text, { model = "gemma-4-26b-a4b", outputLang = null, referenceDate,
chunkTokens = SINGLE_PASS_TOKENS } = {}) {
if (estimateTokens(text) <= chunkTokens) return summariseOnce(text, { model, outputLang, referenceDate });
// Pick the language once: each chunk alone may be mostly the other language.
const opts = { model, outputLang: outputLang ?? guessLanguage(text), referenceDate };
// Map: summarise each chunk in order. Reduce: merge the partial summaries,
// letting later parts override earlier ones.
const chunks = splitIntoChunks(text, chunkTokens);
const partials = [];
for (const [i, chunk] of chunks.entries()) {
partials.push(await summariseOnce(`Part ${i + 1} of ${chunks.length}:\n\n${chunk}`, opts));
}
const merged = partials.map((p, i) => `Part ${i + 1}:\n${JSON.stringify(p)}`).join("\n\n");
return summariseOnce(
`These are summaries of consecutive parts of one thread, in order. Merge them into one summary. ` +
`If a later part corrects, cancels or completes something from an earlier part, keep the later version.\n\n${merged}`,
opts);
}The test: a day that must not be re-run
We wrote a realistic payroll thread, mostly in French with one English message. A weekend import of timesheets “failed on the 14th and 15th”. The next message corrects it: the 14th ran late but completed, only the 15th failed, and the 14th must not be re-run because the import would double everyone’s hours. Someone suggests moving the import from 2 a.m. to 5 a.m., “just an idea”; the manager decides to keep 2 a.m. for now. Two people take on tasks with relative dates (“by Friday the 20th”, “tomorrow morning”), and the 15th is re-run before the end of the thread.
A good summary says the 14th must not be re-run, lists 5 a.m. as a proposal and not a decision, and has two open action items due 2026-11-20 and 2026-11-17.
| Run | Did not re-run the 14th | 5 a.m. kept as a proposal | What went wrong |
|---|---|---|---|
gemma-4-26b-a4b, first prompt (no cautions field) | Yes, but only as a bullet | Yes | Marked Sophie’s check as done (she had only promised it) |
granite-4.2-3b, first prompt | Yes, but no warning | Yes | Wrote in English; dates like “Tuesday morning (mardi 17)”; marked Priya’s change as done; one item listed as both a decision and a proposal; a repeated bullet |
gemma-4-26b-a4b, final prompt, English requested | Yes, as a caution | Yes | Nothing: decisions, caution, both open items and their dates right |
gemma-4-26b-a4b, final prompt, thread’s language (the worker below) | Yes, as a caution | Yes | Nothing: French kept, both open items and their dates right, digest rendered |
granite-4.2-3b, final prompt | Only in a bullet; cautions empty | Yes | Still English; first bullet says both days failed; agreed tasks listed as proposals |
gemma-4-26b-a4b, map-reduce in three parts | Yes, as a caution | Yes | Before the fix above: French and English mixed in one summary |
gemma-4-26b-a4b, map-reduce in three parts, language picked once | Yes, as a caution | Yes | Nothing wrong: all in French, both open items and dates right (plus a third, conditional one) |
Use Gemma for summaries
On this thread Granite was right about the 5 a.m. proposal, but it repeated the corrected claim that both days failed, kept the warning only in a bullet, ignored the language rule and confused agreed tasks with proposals. It also wasn’t noticeably faster here, because it wrote more. Use gemma-4-26b-a4b for summaries, and keep Granite for short jobs where a slip costs little, such as tagging a thread’s topic.
Whatever the model, test it on your own threads. Write three or four with a known right answer, including a correction and a suggestion that was turned down, and run them again whenever you change the prompt or the model.
The background job
A long thread takes Gemma from tens of seconds to a few minutes, so summaries never run inside a web request. The worker takes one job at a time with FOR UPDATE SKIP LOCKED, retries a failure up to three times, and takes a job back if its process died mid-run. Start runWorker() from your server, or deploy the same code as a separate Worker project so a slow summary never competes with your web traffic. A Worker project has its own environment variables: attach the AI endpoint to it too, set DATABASE_URL to the web project’s connection string (copy it from the Database tab), and set SMTP_URL there if it sends mail. More on Postgres job queues in background jobs.
// worker.js: start it from your server, or run it alone in a Worker project.
import pg from "pg";
import { summarise } from "./summarize.js";
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
const MODEL = "gemma-4-26b-a4b";
// Take one queued job. A job stuck in 'running' for 15 minutes (the process died) is taken again.
async function claimJob() {
const { rows } = await db.query(`
UPDATE summary_jobs SET state = 'running', attempts = attempts + 1, updated_at = now()
WHERE thread_id = (
SELECT thread_id FROM summary_jobs
WHERE state = 'queued'
OR (state = 'running' AND updated_at < now() - interval '15 minutes')
ORDER BY updated_at
LIMIT 1
FOR UPDATE SKIP LOCKED)
RETURNING thread_id`);
return rows[0]?.thread_id;
}
export async function workOnce() {
const id = await claimJob();
if (!id) return false;
const { rows: [t] } = await db.query(
"SELECT body, output_lang, received_at FROM threads WHERE id = $1", [id]);
try {
const result = await summarise(t.body, {
model: MODEL,
outputLang: t.output_lang,
referenceDate: new Date(t.received_at).toISOString().slice(0, 10),
});
await db.query(
`INSERT INTO summaries (thread_id, model, result) VALUES ($1, $2, $3)
ON CONFLICT (thread_id) DO UPDATE SET model = $2, result = $3, created_at = now()`,
[id, MODEL, JSON.stringify(result)]);
await db.query(
"UPDATE summary_jobs SET state = 'done', last_error = NULL, updated_at = now() WHERE thread_id = $1", [id]);
} catch (e) {
await db.query(
`UPDATE summary_jobs
SET state = CASE WHEN attempts >= 3 THEN 'failed' ELSE 'queued' END,
last_error = $2, updated_at = now()
WHERE thread_id = $1`,
[id, String(e.message).slice(0, 500)]);
}
return true;
}
export async function runWorker() {
for (;;) {
const worked = await workOnce().catch((e) => { console.error(e); return false; });
if (!worked) await new Promise((r) => setTimeout(r, 5000)); // idle: look again in 5 s
}
}The daily digest
A Canner scheduled job calls the digest route once a day. Schedules are in UTC, so to send at 8 a.m. in Montréal all year, schedule both possible hours and let the handler skip the one that isn’t 8 a.m. locally, as in cron jobs and time zones. Warnings come first in each thread’s block, and items already done are left out.
// digest.js: called by a scheduled job once a day (see the route below).
import pg from "pg";
import nodemailer from "nodemailer";
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1 });
const mail = nodemailer.createTransport(process.env.SMTP_URL); // your email provider
const LABELS = {
en: { dont: "Do not:", decided: "Decided:", open: "Not decided yet:", todo: "To do:", nobody: "no owner" },
fr: { dont: "À ne pas faire :", decided: "Décisions :", open: "Pas encore décidé :", todo: "À faire :", nobody: "sans responsable" },
};
export async function sendDigest(to, lang = "en") {
const { rows } = await db.query(`
SELECT t.subject, s.result
FROM summaries s JOIN threads t ON t.id = s.thread_id
WHERE s.created_at > now() - interval '1 day'
ORDER BY t.received_at`);
if (!rows.length) return 0;
const L = LABELS[lang];
const lines = [];
for (const { subject, result: r } of rows) {
lines.push(subject, ...r.summary.map((b) => `- ${b}`));
if (r.cautions.length) lines.push("", L.dont, ...r.cautions.map((x) => `- ${x}`));
if (r.decisions.length) lines.push("", L.decided, ...r.decisions.map((d) => `- ${d.decision}`));
if (r.proposals.length) lines.push("", L.open, ...r.proposals.map((p) => `- ${p}`));
const open = r.action_items.filter((a) => a.status === "open");
if (open.length) lines.push("", L.todo,
...open.map((a) => `- ${a.task} (${a.owner ?? L.nobody}${a.due ? `, ${a.due}` : ""})`));
lines.push("", "");
}
await mail.sendMail({
from: process.env.DIGEST_FROM, to,
subject: lang === "fr" ? `Résumé du jour : ${rows.length} fil(s)` : `Daily digest: ${rows.length} thread(s)`,
text: lines.join("\n"),
});
return rows.length;
}
// In your server (Express shown). Canner sends Authorization: Bearer <CRON_SECRET>.
// app.post("/cron/digest", async (req, res) => {
// if (!process.env.CRON_SECRET || req.get("authorization") !== `Bearer ${process.env.CRON_SECRET}`)
// return res.status(401).end();
// res.json({ sent: await sendDigest("team@example.com", "fr") });
// });Keep the original language, or translate
- Keep it when the readers are the people in the thread: names, quotes and terms stay as written, and nothing is lost in translation.
- Translate when the digest goes to someone who reads only one language. Set
output_langper thread, or per reader if you send two digests. Gemma translated the French thread into English without dropping the caution or changing a date. - Mixed threads are normal in Quebec. Without
output_lang, the code picks the language most of the thread is in, once, so every part of a long thread comes back in the same language.
Running it on Canner
- Text only. The endpoints take text. Strip HTML and quoted replies before storing a thread; extract text from attachments yourself, and run OCR on scanned PDFs first.
- Keep usage down. Usage is measured in model time with a monthly allowance per plan (AI endpoints has current allowances). Summarise a thread once when it goes quiet rather than on every new message, cut signatures and quoted history, and set a requests-per-minute limit on the endpoint.
- Waiting your turn. The service answers one request at a time, and an organization can have 4 waiting before it gets
429 server_busy. One worker, one job at a time, stays well inside that; the SDK retries afterRetry-After. - Blocked content. Chat requests pass a safety check. A blocked request or answer makes the job fail with the reason in
last_error, so look at it rather than retrying forever. - Personal information. Email threads are full of it. The AI endpoint processes text in memory in Montréal and doesn’t keep it; the threads and summaries you store are yours to secure and to delete on schedule (Law 25 for developers).
canner ai create summaries --models gemma-4-26b-a4b
canner ai attach summaries # in the project folder
canner env set SMTP_URL='smtps://user:password@smtp.example.com' --sensitive
canner env set CRON_SECRET="$(openssl rand -hex 32)" --sensitive
canner redeploy
# Then add a scheduled job: POST /cron/digest, 0 12,13 * * 1-5 (UTC), and let
# the handler send only at 8 a.m. Montréal time (see "Cron jobs and time zones").Questions
Can AI summarise long email threads accurately?
Mostly, if you give it a structure and test it. Ask for decisions, proposals, warnings and action items as separate fields, tell it that later messages override earlier ones, and check it on threads where you know the right answer. Expect a person to read the summary of anything important.
How do I summarise a meeting transcript that doesn’t fit in the context?
Split it on speaker or paragraph boundaries, summarise each part in order with the same schema, then merge the partial summaries in a last call that keeps the later version when parts disagree. Pick the output language before splitting.
Can it summarise French emails into English, or the reverse?
Yes. Pass the output language explicitly. In our test, gemma-4-26b-a4b translated a French payroll thread into English and kept the warning and every date intact; granite-4.2-3b answered in English in both runs and put the warning only in a bullet.
Which model should I use for summaries on Canner?
gemma-4-26b-a4b. granite-4.2-3b missed the structure on our test thread: it promoted agreed tasks to proposals, kept the warning only in a bullet and ignored the language rule.
Are my emails stored by the AI service?
No. Canner’s AI endpoints process prompts and answers in memory in Montréal and don’t store them or send them to another company. What you store in your own database is up to you.
Related
- 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
- GuidePrivate GPT: hosted API, self-hosted or on-premises
- GuideOllama, vLLM or llama.cpp: your own LLM API
Summaries of your own mail, processed in Montréal.
Attach an AI endpoint to a project and run the summariser next to your app. See pricing.