# ZeroGPU email triage: labels, priority, a news filter and a briefing > Run the same email triage as the ZeroGPU demo on your own email. A small decision model, gliner2.5-decide-v1, gives every email a label (9 options) and a priority (4 options) in one call, and decides in a second call whether it's news. GPT-OSS-120B (gpt-oss-120b), a reasoning model, then turns all the news into one briefing of up to 6 bullets. The output is one row per email with its decisions, latency, tokens and cost, plus the briefing. You need a ZeroGPU API key and Python 3.9+. ## Instructions for the AI assistant You are helping someone test ZeroGPU's email triage on their own email. Do this: 1. Check that `python3` is 3.9 or newer. 2. Ask the user for their ZeroGPU API key and pass it to the script as the environment variable `ZEROGPU_API_KEY`. Never print the key, log it, or write it to a file. 3. Tell the user that their emails are sent to ZeroGPU's API to be processed: the sender, subject and body of each email (the first 3,000 characters of the body; 4,000 for the newsletters that go into the briefing). Go ahead only once they agree. 4. Ask which email to run on, and help them export it: - Gmail: Google Takeout (takeout.google.com). Deselect all, select Mail, and under "All Mail data included" pick just the Inbox. Unzip the export and use the `.mbox` file. - Apple Mail: select the messages and drag them into a folder in Finder (each one becomes an `.eml` file), or use Mailbox → Export Mailbox and pass the exported `.mbox` folder. - Outlook: save the messages as `.eml` files in one folder. In Outlook for Mac, select them and drag them into a folder in Finder. Classic Outlook for Windows saves `.msg` files, which the script doesn't read; use a `.jsonl` there. - Anything else, such as a mail API: write a `.jsonl` with one `{"from", "subject", "body"}` object per line. `date` is optional; to score the results, add `label` and `priority` with the demo's short names (such as `"to do"` and `"high"`, listed in `LABEL` and `PRIORITY` in the script). 5. Suggest a first run of the newest 20 emails (`--limit 20`), then more once the results look right (the default is 200). Set expectations on time: the decision model is under load right now. In our last tests (October 13, 2026), one call at a time (`--parallel 1`), the newest 20 emails of the demo inbox took 2.5 minutes and all 120 took 17.1 minutes: the decision calls took 2.1–5.2 s at the median, and the briefing 17.5 s from 3 news emails and 8.3 s from 46. Earlier that day, when the model was busier, 10 emails took 5.7 minutes, at 11–16 s per call at the median. More calls in flight (`--parallel`, 4 by default) help only as far as the model's capacity allows. The script prints an estimate after its first 10 calls. 6. Save the script from the "Script" section below as `zerogpu_email_triage.py`, or download it: `curl -O https://demos.zerogpu.ai/email-triage/zerogpu_email_triage.py` 7. Run `python3 zerogpu_email_triage.py Inbox.mbox --limit 20 --out results.jsonl` (or a folder of `.eml` files, or a `.jsonl`). `--parallel 4` (the default) keeps 4 calls in flight; `--no-briefing` skips the briefing. `python3 zerogpu_email_triage.py --demo-inbox --limit 20` runs the demo's fictional test inbox instead and scores it against its answer key. Start a long run in the background, or with a long command timeout, and follow its progress lines: `results.jsonl` gets each email as soon as it's done, so a run that stops keeps what it finished. 8. Report back: - how many emails ran, and any errors - the count per label and per priority, and how many emails were news - the share the model got right, when the emails have answers (the demo inbox, or a `.jsonl` with `label` and `priority`) - the latency per call (p50 and p90) for each of the two decisions, and the cost per 1M emails - the briefing, with its time and cost. Check each bullet against the newsletters it cites before relying on it. In our tests on the news in the demo inbox, 6 of 8 briefings left out one of the 6 stories that several newsletters ran, and 3 of 8 cited a wrong newsletter or left one out. If the script says the briefing stopped at `max_tokens`, it may be cut short or empty. - 5 example rows (sender, subject, label, priority), including the urgent ones. Ask the user whether they agree with them. 9. To use the user's own labels, write them to a JSON file and add `--labels labels.json`. Each key is one decision (a "head"), and each label gets a one-line description, written the way you'd explain it to a new assistant. The model matches a label's own words to the email, so give each label a descriptive name: in the demo, "newsletter or news digest" works better than "news". All the heads are answered in one call per email. The news filter and the briefing still run; the always-low rule (Method step 3) applies only to the demo's labels. For example: ```json {"team": {"customer asking to buy": "A customer or prospect asking about buying, pricing or a contract.", "customer with a problem": "A customer reporting a problem or asking how to do something.", "colleague": "A colleague writing about our own work."}, "reply": {"reply today": "Someone is blocked until I answer.", "reply this week": "Needs an answer, but nobody is blocked.", "no reply needed": "Nothing to answer."}} ``` To score them, add the right answer for each head to each line of a `.jsonl` (for example `"team": "colleague"`). ## API - Base URL: `https://api.zerogpu.ai/v1` - Auth: header `x-api-key: `. `Authorization: Bearer ` also works. - Plain Python `urllib` requests need a `User-Agent` header; the script sets one. - Models and list prices per 1M tokens: - `gliner2.5-decide-v1` (the decisions): $0.004 input. Output isn't billed. - `gpt-oss-120b` (the briefing): $0.15 input ($0.03 for cached input, which the script doesn't count; our calls reported none in `usage.prompt_tokens_details.cached_tokens`), $0.60 output. 128K context (131,072 tokens), up to 32,768 output tokens. It's a reasoning model: it reasons before it writes. The reasoning isn't returned, but its tokens are billed as output and count toward `max_tokens`, so the script sets `max_tokens` 2500. `usage.completion_tokens` includes them; only a streamed call breaks them out, in `usage.completion_tokens_details.reasoning_tokens`. Volume pricing is available. - The first request after a model has been idle can be slower. The script retries each call once, after a short pause, on 429 (after its `Retry-After`), gateway errors (500, 502, 503, 504, 524), dropped connections, timeouts (60 s per decision call, 300 s for the briefing) and a 200 answer that carries an `error`. Emails with a failed call get one more pass at the end. The examples below are real calls: the two decisions on one email from the demo's test inbox, and the briefing on its newsletters. ### 1. Label and priority: `POST /v1/responses` ```json { "model": "gliner2.5-decide-v1", "input": "From: Tom Becker \nSubject: Approval needed: Q4 on-call budget\n\nMorning Jordan,\n\nCould you approve the Q4 on-call budget when you get a sec?\n\n- Weekly stipends for the 6 engineers on rotation: $3,900\n- Incident overtime buffer: $900\n- Total: $4,800 (same as Q3)\n\nRaj needs it approved by Wednesday to get the stipends into the October payroll run.\n\nApprove here: https://finance.kilnfern.example/requests/OC-2026-Q4\n\nThanks,\nTom", "metadata": { "usecase": "decide", "threshold": 0.01, "labels": { "label": { "labels": { "question waiting for my reply": "A person wrote to me and is waiting for my answer to a question.", "task for me to do": "Asks me to do a task, such as sign, approve, pay, review or submit something, with no question to answer.", "meeting or calendar invite": "Schedules, moves or cancels a meeting (including asking me to pick a time), or sends an invite or agenda.", "invoice, receipt or payment": "An invoice, receipt, renewal, refund or failed payment.", "security alert about my account": "A real account alert: a new sign-in, a password or two-factor change, or suspicious activity.", "spam, scam or phishing": "Unwanted or fraudulent mail: phishing, scams, fake alerts or junk.", "newsletter or news digest": "A newsletter or news digest sent to many readers.", "marketing or sales promotion": "Marketing from a company: sales, discounts, offers, product launches or event promotions.", "automated app notification": "An automated update from an app or service: shipping, builds, reports, comments and activity." } }, "priority": { "labels": { "needs me today": "Needs me today: a hard deadline within 24 hours, something broken, or a security risk.", "needs me this week": "Needs me this week.", "worth handling, no deadline": "Worth handling, but no deadline.", "nothing to do": "Nothing to do: read later or ignore." } } } } } ``` - `labels` holds one entry per decision ("head"): its labels by descriptive name, each with a one-line description. One call answers every head. - `threshold: 0.01` makes the model always return its best label, never "none of these". 0 isn't allowed. Response (shortened): ```json { "id": "ef405aed-4686-4c0d-99a0-67403f668386", "object": "response", "status": "completed", "model": "gliner2.5-decide-v1", "output": [ { "type": "message", "role": "assistant", "content": [ {"type": "output_text", "text": "{\"decisions\":{\"label\":\"task for me to do\",\"priority\":\"needs me this week\"}}", "annotations": []} ], … } ], "usage": {"input_tokens": 113, "output_tokens": 19, "total_tokens": 132, …}, "metadata": {"usecase": "decide"}, … } ``` `output[0].content[0].text` is JSON: `{"decisions": {"": "", …}}`. The script maps each answer back to its short name (`"task for me to do"` → `to do`, `"needs me this week"` → `high`): it matches the descriptive or the short name, ignoring case, spacing and a trailing period, and anything else counts as no answer. ### 2. News or not news: `POST /v1/responses` The same call with one head: ```json { "model": "gliner2.5-decide-v1", "input": "From: Tom Becker \nSubject: Approval needed: Q4 on-call budget\n\nMorning Jordan,\n\nCould you approve the Q4 on-call budget when you get a sec?\n\n- Weekly stipends for the 6 engineers on rotation: $3,900\n- Incident overtime buffer: $900\n- Total: $4,800 (same as Q3)\n\nRaj needs it approved by Wednesday to get the stipends into the October payroll run.\n\nApprove here: https://finance.kilnfern.example/requests/OC-2026-Q4\n\nThanks,\nTom", "metadata": { "usecase": "decide", "threshold": 0.01, "labels": { "news": { "labels": { "news": "A newsletter or news digest sent to many readers.", "not news": "Anything else: mail from people, promotions, receipts, alerts and app notifications." } } } } } ``` Response (shortened): ```json { "id": "cf3caf65-f71c-4379-8b8c-9aafc319ffd5", "object": "response", "status": "completed", "model": "gliner2.5-decide-v1", "output": [ { "type": "message", "role": "assistant", "content": [ {"type": "output_text", "text": "{\"decisions\":{\"news\":\"not news\"}}", "annotations": []} ], … } ], "usage": {"input_tokens": 113, "output_tokens": 9, "total_tokens": 122, …}, … } ``` `usage.input_tokens` counts the email only, not the labels: 113 tokens for this email in both calls, with 13 labels and with 2. ### 3. The briefing: `POST /v1/chat/completions` One call with all the news (here, the 46 newsletter emails from 14 newsletters in the test inbox): ```json { "model": "gpt-oss-120b", "max_tokens": 2500, "temperature": 0, "messages": [ {"role": "system", "content": ""}, {"role": "user", "content": "=== The Morning Byteloom · Polestead goes open with Quorlen-3 · 2026-10-12\n\n\n=== Seedrift Digest · Seedrift Digest: Quorlen-3 and your AI bill · 2026-10-12\n\n\n…\n\n---\nNow write the briefing, following these instructions exactly:\n"} ] } ``` Response (this call took 14.8 s): ```json { "id": "id-1791909802317", "object": "chat.completion", "created": 1791909802, "model": "gpt-oss-120b", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "role": "assistant", "content": "- Polestead released Quorlen-3, an open‑weight AI model in 8B and 70B sizes under a permissive commercial license. [The Morning Byteloom, Seedrift Digest, Hushwire Weekly] \n- The central bank kept its benchmark rate at 4.25% for a third straight meeting, signaling a possible cut early next year. [Seedrift Digest, Pylon & Prairie, Marketvane Brief] \n- Arcwell unveiled the Tolvex‑9 AI accelerator, claiming 2.4× faster inference per watt and slated to ship to cloud providers in Q1 2027. [The Morning Byteloom, Pylon & Prairie, Marketvane Brief] \n- Ploverfield Grid warned of rolling outages on Tuesday and Wednesday evening as a late heat wave pushed record demand, urging customers to shift laundry, dishwashing and thermostat settings. [Pylon & Prairie, Harbor Point Daily] \n- Harbor Point city council approved a $340 million transit plan adding three new bus‑rapid lines, passing 7‑2. [The Weekend Compass, Harbor Point Daily] \n- Orchardline Foods is in advanced talks to buy snack brand Pell & Rowe for roughly $1.1 billion. [Marketvane Brief]" } } ], "usage": {"completion_tokens": 1560, "prompt_tokens": 13981, "total_tokens": 15541, "prompt_tokens_details": {"cached_tokens": 0}} } ``` This call cost $0.0030 at list price. `completion_tokens` includes the hidden reasoning: a streamed call on the same emails reported 680 of its 976 completion tokens as reasoning. Six stories in the test inbox ran in several newsletters. This answer covers 5 of them, each citing the newsletters that ran it (as "Marketvane Brief" for The Marketvane Brief). It leaves out the Penderpay breach, which three newsletters ran, and adds a story from one newsletter instead. Six more calls on the same emails the same day, five like this one and one streamed, were each worded differently, even at `temperature` 0. Five of them also left out the Penderpay breach; one covered all 6. Three cited a wrong newsletter or left one out: two cited Marketvane Brief for the transit plan instead of The Weekend Compass, and two left Seedrift Digest off the rate story. The seven calls took 10.5–29.3 s and 976–1,560 completion tokens, $0.0027–0.0030 each, all with the settings above; none stopped at `max_tokens`. GPT-OSS writes some hyphens and spaces as Unicode: non-breaking hyphens (U+2011) as in "open‑weight", and narrow no-break spaces (U+202F) between a number and its unit, as in "$340 million". Normalize them before matching text. Check a briefing's stories and sources against the emails before relying on it. ## Method (identical to the demo) 1. The email text every model reads, built from the sender, the subject and the body. A body longer than 3,000 characters is cut there and ends with "…": ``` From: <
> Subject: ``` For your own email, the script reads the plain-text part, or the HTML part with its tags and entities stripped when there's no plain text. It decodes the headers and skips attachments. 2. Label and priority: one call per email to `gliner2.5-decide-v1` with both heads (request 1 above), `threshold` 0.01. Each label has a short name, which the script reports, and what the model reads: a descriptive name and a one-line description (`LABEL` and `PRIORITY` in the script). The answers are mapped back to the short names. 3. The always-low rule, after the model: if the label is `news`, `promotion` or `spam` (`ALWAYS_LOW`), the priority is set to `low`. It's part of the pipeline, not the model, and the demo applies it to every model's answers. 4. News or not news: one call per email with the `news` head (request 2 above). 5. The briefing: one call to `gpt-oss-120b` with every email the filter called news, newest first, `max_tokens` 2500 and `temperature` 0 (`BRIEFING` in the script). No setting shortens the reasoning (ZeroGPU accepts `reasoning_effort`, but it made no measurable difference), so `max_tokens` is the only bound. The reasoning and the briefing share it: on the 46 newsletters of the demo inbox, our seven calls used 976–1,560 completion tokens, reasoning included. - System message: the briefing instructions (below). - User message: each news email as `=== · · `, a new line and the first 4,000 characters of its body, with a blank line between emails. Then `\n\n---\nNow write the briefing, following these instructions exactly:\n` and the same instructions again. The repeat dates from the demo's earlier briefing model, Llama 3.1 8B, which followed the instructions it read last and wrote one bullet per newsletter without it; every model still gets it. - If the news runs past 360,000 characters (about 88K tokens at the 4.1 characters per token of the demo's newsletters), the script keeps the newest that fits. GPT-OSS-120B's context is 131,072 tokens (128K). 6. Metrics: the time of each call, its tokens from `usage`, and its cost (tokens × list price). Cost per 1M emails is the mean cost per email × 1,000,000. The demo labels the newest 20 emails of its test inbox and filters all 120. The script does both for every email. The briefing instructions (`BRIEFING_PROMPT` in the script): ``` You write a short morning briefing from the newsletters in someone's inbox. - 6 bullets: the 6 most important stories of the week, not one per newsletter. With fewer than 6 stories, write one bullet per story and stop; never make one up. - A story covered by several newsletters is more important: put those first and write each once, naming every newsletter that covered it. - Each bullet is one or two sentences with the key names and figures, ending with its sources in square brackets, e.g. [The Morning Byteloom, Hushwire Weekly]. - Only facts from the newsletters. Plain text: a "- " before each bullet, no title, no intro, no closing line. ``` ## Comparing with your current model Run the same tasks on the model you use today, with: - the same email text (Method step 1), one call per email - the same labels and descriptions, in this prompt as the system message, with the email text as the user message - the first JSON object in the reply as the answer, mapped back to the short names the same way (anything that isn't one of the listed labels counts as no answer) - the same always-low rule after the model (Method step 3) Label and priority: ``` You triage a work inbox. Read the email and return only compact JSON, no prose: {"label":"...","priority":"..."} label: exactly one of - question waiting for my reply: A person wrote to me and is waiting for my answer to a question. - task for me to do: Asks me to do a task, such as sign, approve, pay, review or submit something, with no question to answer. - meeting or calendar invite: Schedules, moves or cancels a meeting (including asking me to pick a time), or sends an invite or agenda. - invoice, receipt or payment: An invoice, receipt, renewal, refund or failed payment. - security alert about my account: A real account alert: a new sign-in, a password or two-factor change, or suspicious activity. - spam, scam or phishing: Unwanted or fraudulent mail: phishing, scams, fake alerts or junk. - newsletter or news digest: A newsletter or news digest sent to many readers. - marketing or sales promotion: Marketing from a company: sales, discounts, offers, product launches or event promotions. - automated app notification: An automated update from an app or service: shipping, builds, reports, comments and activity. priority: exactly one of - needs me today: Needs me today: a hard deadline within 24 hours, something broken, or a security risk. - needs me this week: Needs me this week. - worth handling, no deadline: Worth handling, but no deadline. - nothing to do: Nothing to do: read later or ignore. ``` News or not news: ``` You triage a work inbox. Read the email and return only compact JSON, no prose: {"news":"..."} news: exactly one of - news: A newsletter or news digest sent to many readers. - not news: Anything else: mail from people, promotions, receipts, alerts and app notifications. ``` The briefing gets the same two messages as Method step 5, built from the news that model's own filter found. The demo compares GPT-6 luna and Gemini 3.8 Flash with reasoning effort minimal, and Claude Haiku 5.5 with reasoning off, this way, and scores every model against the same answer key. ## Output (`results.jsonl`) One line per email, in the order they finish, then one line with the briefing. Two emails and the briefing from a test run on 10 emails of the demo inbox (a `.jsonl` with their answers, `--parallel 1`, one call at a time); the briefing is shortened to its first bullet. The decision model was under load, so its calls took 1.8–52 s each; `ms` is the whole call, a retry included. The briefing's `tokens.out` includes its reasoning, and its `finish_reason` is `length` if it hit `max_tokens` (in a test with `max_tokens` lowered to 150 on the same 6 newsletters, the reasoning used them all and the briefing came back empty): ```json {"id": "m012", "date": "2026-10-12T07:05:00-07:00", "from": "Tom Becker ", "subject": "Approval needed: Q4 on-call budget", "decisions": {"label": "to do", "priority": "high", "news": "not news"}, "answer_key": {"label": "to do", "priority": "high", "news": "not news"}, "ms": {"label + priority": 26860, "news filter": 1846}, "tokens": {"label + priority": {"in": 113, "out": 19}, "news filter": {"in": 113, "out": 9}}, "cost_usd": 9.04e-07} {"id": "m020", "date": "2026-10-12T06:04:00-07:00", "from": "The Marketvane Brief ", "subject": "Marketvane Brief: the week ahead, plus a $1.1B snack deal", "decisions": {"label": "news", "priority": "low", "news": "news"}, "answer_key": {"label": "news", "priority": "low", "news": "news"}, "ms": {"label + priority": 9283, "news filter": 9946}, "tokens": {"label + priority": {"in": 308, "out": 21}, "news filter": {"in": 308, "out": 8}}, "cost_usd": 2.464e-06} {"briefing": "- Polestead released Quorlen-3, an open‑weight AI model in 8B and 70B sizes under a permissive commercial license, allowing companies to run and fine‑tune it on their own servers. [The Morning Byteloom, Seedrift Digest, Hushwire Weekly] \n- …", "model": "gpt-oss-120b", "news_ids": ["m015", "m016", "m020", "m025", "m026", "m027"], "finish_reason": "stop", "ms": 5761, "tokens": {"in": 2196, "out": 811}, "cost_usd": 0.000816} ``` ## Script ```python #!/usr/bin/env python3 """Triage your own email with ZeroGPU: a label and a priority for every email, the news filtered out, and one short briefing from that news. Same models, labels, descriptions and prompts as the ZeroGPU email triage demo: label + priority gliner2.5-decide-v1 POST /v1/responses one call per email answers both news or not news gliner2.5-decide-v1 POST /v1/responses one call per email the briefing gpt-oss-120b POST /v1/chat/completions one call for all the news Needs Python 3.9+ and ZEROGPU_API_KEY in the environment. No other packages. The emails are sent to ZeroGPU's API. python3 zerogpu_email_triage.py INBOX [--limit 200] [--parallel 4] [--out results.jsonl] [--labels labels.json] [--no-briefing] python3 zerogpu_email_triage.py --demo-inbox # the demo's fictional 120-email inbox, scored against its answer key INBOX: an .mbox file (Gmail via Google Takeout), a folder of .eml files (searched recursively), or a .jsonl with one {"from", "subject", "body"} per line ("date" is optional, and so are "label" and "priority" to score against). """ import argparse, collections, email, email.policy, email.utils, html, http.client, json, mailbox, os, random, re, sys import threading, time, urllib.error, urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone API = "https://api.zerogpu.ai/v1" DEMO_INBOX = "https://demos.zerogpu.ai/email-triage/inbox.json" DECIDE, SUMMARY = "gliner2.5-decide-v1", "gpt-oss-120b" PRICES = {DECIDE: (0.004, 0.0), SUMMARY: (0.15, 0.60)} # USD per 1M tokens (input, output); decide doesn't bill output UA = "zerogpu-email-triage/1.0" THRESHOLD = 0.01 # the best label always comes back, never "none of these" (0 isn't allowed) # The briefing call's settings, as in the demo. GPT-OSS-120B reasons before it writes: the reasoning isn't returned, # but its tokens are billed as output and count toward max_tokens, so the limit leaves room for both (the demo's # briefings used about 800 to 1,600 tokens in all). BRIEFING = {"max_tokens": 2500, "temperature": 0} TIMEOUT = 60 # seconds per attempt, as in the demo RETRY = (429, 500, 502, 503, 504, 524) EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) # The briefing keeps the newest news that fits in 360,000 characters: about 88K tokens at the 4.1 characters per token # measured on the demo's newsletters, well inside GPT-OSS-120B's 131,072-token (128K) context with max_tokens on top. MAX_NEWS_CHARS = 360_000 # The demo's decisions. Each head is one decision. Each label has a short name (what the script reports) and what the # model reads: [a descriptive name, a one-line description]. The decision model matches the label's own words to the # email, so "newsletter or news digest" works better than "news". Answers are mapped back to the short name. LABEL = { "needs reply": ["question waiting for my reply", "A person wrote to me and is waiting for my answer to a question."], "to do": ["task for me to do", "Asks me to do a task, such as sign, approve, pay, review or submit something, with no question to answer."], "meeting": ["meeting or calendar invite", "Schedules, moves or cancels a meeting (including asking me to pick a time), or sends an invite or agenda."], "billing": ["invoice, receipt or payment", "An invoice, receipt, renewal, refund or failed payment."], "security": ["security alert about my account", "A real account alert: a new sign-in, a password or two-factor change, or suspicious activity."], "spam": ["spam, scam or phishing", "Unwanted or fraudulent mail: phishing, scams, fake alerts or junk."], "news": ["newsletter or news digest", "A newsletter or news digest sent to many readers."], "promotion": ["marketing or sales promotion", "Marketing from a company: sales, discounts, offers, product launches or event promotions."], "notification": ["automated app notification", "An automated update from an app or service: shipping, builds, reports, comments and activity."], } PRIORITY = { "urgent": ["needs me today", "Needs me today: a hard deadline within 24 hours, something broken, or a security risk."], "high": ["needs me this week", "Needs me this week."], "normal": ["worth handling, no deadline", "Worth handling, but no deadline."], "low": ["nothing to do", "Nothing to do: read later or ignore."], } NEWS = { "news": ["news", "A newsletter or news digest sent to many readers."], "not news": ["not news", "Anything else: mail from people, promotions, receipts, alerts and app notifications."], } # A rule after the model, as in the demo: news, promotions and spam never need anything from me. ALWAYS_LOW = ["news", "promotion", "spam"] BRIEFING_PROMPT = """You write a short morning briefing from the newsletters in someone's inbox. - 6 bullets: the 6 most important stories of the week, not one per newsletter. With fewer than 6 stories, write one bullet per story and stop; never make one up. - A story covered by several newsletters is more important: put those first and write each once, naming every newsletter that covered it. - Each bullet is one or two sentences with the key names and figures, ending with its sources in square brackets, e.g. [The Morning Byteloom, Hushwire Weekly]. - Only facts from the newsletters. Plain text: a "- " before each bullet, no title, no intro, no closing line.""" # ---------- calls ---------- def post(api_key, path, body, timeout=TIMEOUT): """One call, retried once after a short pause on 429 (after its Retry-After), gateway errors, dropped connections and an error inside a 200 answer. The time covers the whole call, the retry included, as in the demo.""" data = json.dumps(body).encode() t0 = time.time() for attempt in (1, 2): req = urllib.request.Request(API + path, data=data, headers={ "content-type": "application/json", "x-api-key": api_key, "user-agent": UA}) wait, retry = random.uniform(0.3, 0.8), True try: with urllib.request.urlopen(req, timeout=timeout) as r: resp = json.load(r) if isinstance(resp, dict) and not resp.get("error"): return resp, (time.time() - t0) * 1000 problem = f"error in the answer: {json.dumps(resp.get('error') if isinstance(resp, dict) else resp)[:200]}" except urllib.error.HTTPError as e: problem, retry = f"HTTP {e.code}: {e.read()[:200].decode(errors='replace')}", e.code in RETRY if e.code == 429 and (e.headers.get("retry-after") or "").isdigit(): wait = min(int(e.headers["retry-after"]), 30) except (OSError, http.client.HTTPException, ValueError) as e: problem = str(e) or type(e).__name__ if attempt == 2 or not retry: raise RuntimeError(f"{body['model']}: {problem}") time.sleep(wait) def usage(u): """Input and output tokens, or None when the answer didn't report them: unknown, not zero.""" if not u: return None return {"in": u.get("input_tokens", u.get("prompt_tokens", 0)), "out": u.get("output_tokens", u.get("completion_tokens", 0))} def cost(model, tokens): return None if tokens is None else (tokens["in"] * PRICES[model][0] + tokens["out"] * PRICES[model][1]) / 1e6 def sender(e): return f"{e['name']} <{e['addr']}>" if e["name"] and e["addr"] else e["name"] or e["addr"] def email_text(e, max_body=3000): """What every model reads for one email, as in the demo: the sender, the subject and the body.""" body = e["body"].strip() return f"From: {sender(e)}\nSubject: {e['subject']}\n\n" + (body[:max_body] + "…" if len(body) > max_body else body) def model_labels(heads): """What the model reads: {head: {descriptive name: description}}.""" return {h: dict(labels.values()) for h, labels in heads.items()} def pick(labels, value): """An answer counts only if it is one of the head's labels, by its descriptive or short name (any case or spacing, a trailing period ignored), and comes back as the short name. Anything else is None.""" norm = lambda s: re.sub(r"[.。]$", "", re.sub(r"[\s_-]+", " ", str(s if s is not None else "").strip().lower())) return next((short for short, (name, _) in labels.items() if norm(value) in (norm(name), norm(short))), None) def decide(api_key, heads, e, always_low=False): """One email through the decision model: every head in one call.""" resp, ms = post(api_key, "/responses", { "model": DECIDE, "input": email_text(e), "metadata": {"usecase": "decide", "threshold": THRESHOLD, "labels": {h: {"labels": ls} for h, ls in model_labels(heads).items()}}}) try: out = json.loads(resp["output"][0]["content"][0]["text"]).get("decisions") or {} except (KeyError, IndexError, TypeError, ValueError, AttributeError): out = {} decisions = {h: pick(labels, out.get(h)) for h, labels in heads.items()} if always_low and decisions.get("label") in ALWAYS_LOW: # the rule, after the model decisions["priority"] = "low" tokens = usage(resp.get("usage")) return {"decisions": decisions, "ms": round(ms), "tokens": tokens, "cost_usd": cost(DECIDE, tokens)} def briefing_messages(news): """The demo's briefing messages: the instructions, the news (newest first, the order the emails are in), then the instructions again. The repeat dates from the demo's earlier briefing model, Llama 3.1 8B, which followed the instructions it read last and wrote one bullet per newsletter without it; every model still gets it.""" parts, size = [], 0 for e in news: date = f" · {e['date'][:10]}" if e["date"] else "" part = f"=== {e['name'] or e['addr']} · {e['subject']}{date}\n{e['body'].strip()[:4000]}" if parts and size + len(part) > MAX_NEWS_CHARS: break parts.append(part) size += len(part) + 2 messages = [{"role": "system", "content": BRIEFING_PROMPT}, {"role": "user", "content": "\n\n".join(parts) + "\n\n---\nNow write the briefing, following these " "instructions exactly:\n" + BRIEFING_PROMPT}] return messages, news[:len(parts)] def briefing(api_key, news): messages, used = briefing_messages(news) resp, ms = post(api_key, "/chat/completions", {"model": SUMMARY, "messages": messages, **BRIEFING}, timeout=300) tokens = usage(resp.get("usage")) # "out" includes the reasoning tokens choice = resp["choices"][0] return {"briefing": (choice["message"].get("content") or "").strip(), "model": SUMMARY, "news_ids": [e["id"] for e in used], "finish_reason": choice.get("finish_reason"), "ms": round(ms), "tokens": tokens, "cost_usd": cost(SUMMARY, tokens)} # ---------- reading email ---------- def parse_date(s): if not s: return None try: d = datetime.fromisoformat(str(s).replace("Z", "+00:00")) except ValueError: try: d = email.utils.parsedate_to_datetime(str(s)) except (TypeError, ValueError): return None return d.replace(tzinfo=timezone.utc) if d.tzinfo is None else d def strip_html(s): s = re.sub(r"(?is)<(script|style|head|title)\b.*?|", " ", s) s = re.sub(r"(?i)|", "\n", s) return html.unescape(re.sub(r"<[^>]*>", " ", s)) def clean(s): """Collapse the spacing and invisible padding mail templates leave in, so the tokens go to the words.""" s = re.sub(r"[\u200b-\u200d\u034f\u00ad\ufeff]", "", s) lines = [re.sub(r"[ \t\xa0]+", " ", line).strip() for line in s.splitlines()] return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() def body_of(msg): """The text/plain part, or the HTML part with its tags and entities stripped. Attachments are skipped.""" for kind in ("plain", "html"): part = msg.get_body(preferencelist=(kind,)) if part is None: continue try: text = part.get_content() except Exception: # an unknown charset: decode as UTF-8 and move on text = (part.get_payload(decode=True) or b"").decode("utf-8", "replace") text = clean(strip_html(text) if kind == "html" else text) if text: return text return "" def headers_only(f): """Just the headers of one message, for its date: big mailboxes are parsed in full only for the emails kept.""" lines = [] for line in f: if not line.strip(): break lines.append(line) return email.message_from_bytes(b"".join(lines), policy=email.policy.default) def read_mail(path, limit): """.mbox or a folder of .eml: the newest `limit` messages, parsed.""" if os.path.isfile(os.path.join(path, "mbox")): # Apple Mail's Export Mailbox makes a folder with an mbox inside path = os.path.join(path, "mbox") if os.path.isdir(path): files = sorted(os.path.join(d, n) for d, _, names in os.walk(path) for n in names if n.lower().endswith(".eml")) items = [(os.path.relpath(p, path), lambda p=p: open(p, "rb")) for p in files] else: box = mailbox.mbox(path, create=False) items = [(k, lambda k=k: box.get_file(k)) for k in box.keys()] dated = [] for mid, opener in items: try: with opener() as f: date = parse_date(headers_only(f).get("date")) except Exception: date = None dated.append((date, mid, opener)) dated.sort(key=lambda x: (x[0] is not None, x[0] or EPOCH), reverse=True) emails = [] for date, mid, opener in dated[:limit]: try: with opener() as f: msg = email.message_from_binary_file(f, policy=email.policy.default) try: a = msg["from"].addresses[0] name, addr = a.display_name, a.addr_spec except Exception: name, addr = email.utils.parseaddr(str(msg.get("from", ""))) emails.append({"id": mid, "date": date.isoformat() if date else None, "name": name, "addr": addr, "subject": str(msg.get("subject", "") or ""), "body": body_of(msg), "key": {}}) except Exception as e: # one unreadable message shouldn't stop the run print(f"skipped message {mid}: {e}") return emails def read_records(records, limit, heads): """.jsonl rows or the demo inbox: {"from", "subject", "body"}, an optional date, and optional answers (the demo inbox keeps them in "key"). An email's news answer is "news" when its label is news. Answers that aren't one of their head's labels are set aside in "unmapped" and left out of the score.""" dated = [] for i, d in enumerate(records, 1): frm = d.get("from") or "" name, addr = (frm.get("name", ""), frm.get("email", "")) if isinstance(frm, dict) else email.utils.parseaddr(str(frm)) key, unmapped = {}, [] for h, v in (d.get("key") or d).items(): if h in heads and v not in (None, ""): short = pick(heads[h], v) key.update({h: short}) if short else unmapped.append((h, str(v))) elif h == "news" and v: key["news"] = v if "label" in key and "news" not in key: key["news"] = "news" if key["label"] == "news" else "not news" date = parse_date(d.get("date")) dated.append((date, {"id": d.get("id", i), "date": date.isoformat() if date else None, "name": name, "addr": addr, "subject": str(d.get("subject") or ""), "body": str(d.get("body") or ""), "key": key, "unmapped": unmapped})) dated.sort(key=lambda x: (x[0] is not None, x[0] or EPOCH), reverse=True) return [e for _, e in dated[:limit]] def read_jsonl(f): rows = [] for n, line in enumerate(f, 1): if line.strip(): try: d = json.loads(line) except ValueError: d = None if not isinstance(d, dict): raise ValueError(f"line {n} isn't a JSON object") rows.append(d) return rows def load(args, heads): """The emails to triage, newest first. A problem with the input ends the run with a one-line error.""" src = args.demo_inbox or args.inbox try: if args.demo_inbox: if src.startswith("http"): with urllib.request.urlopen(urllib.request.Request(src, headers={"user-agent": UA}), timeout=60) as r: inbox = json.load(r) else: with open(src, encoding="utf-8") as f: inbox = json.load(f) if not isinstance(inbox, dict) or not isinstance(inbox.get("emails"), list): raise ValueError("not the demo inbox (no list of emails)") return read_records(inbox["emails"], args.limit, heads) if src.lower().endswith(".jsonl"): with open(src, encoding="utf-8") as f: return read_records(read_jsonl(f), args.limit, heads) if not os.path.exists(src): raise FileNotFoundError("no such file or folder") return read_mail(src, args.limit) except (OSError, ValueError, mailbox.Error) as e: sys.exit(f"Can't read {src}: {e}") # ---------- run and report ---------- def pct(xs, q): s = sorted(xs) return s[min(len(s) - 1, int(q * len(s)))] if s else 0 def minutes(seconds): return f"{seconds / 60:.0f} min" if seconds >= 90 else f"{seconds:.0f} s" def main(): ap = argparse.ArgumentParser(description="Triage your own email with ZeroGPU, the same way as the demo.") ap.add_argument("inbox", nargs="?", help=".mbox file, folder of .eml files, or .jsonl") ap.add_argument("--demo-inbox", nargs="?", const=DEMO_INBOX, metavar="URL_OR_FILE", help="run the demo's test inbox and score it against its answer key") ap.add_argument("--limit", type=int, default=200, help="the newest N emails (default 200)") ap.add_argument("--parallel", type=int, default=4, help="calls in flight at once (default 4)") ap.add_argument("--out", default="results.jsonl", help="one JSON line per email as it's done, then the briefing") ap.add_argument("--labels", help='your own decisions: a JSON file of {"head": {"label": "description", ...}}') ap.add_argument("--no-briefing", action="store_true", help="label and filter only") args = ap.parse_args() sys.stdout.reconfigure(line_buffering=True) # progress shows up even when the output is piped if not args.inbox and not args.demo_inbox: ap.error("give an .mbox file, a folder of .eml files or a .jsonl, or --demo-inbox") api_key = os.environ.get("ZEROGPU_API_KEY", "").strip() if not api_key: sys.exit("Set ZEROGPU_API_KEY first.") heads = {"label": LABEL, "priority": PRIORITY} if args.labels: # {head: {name: description}}: each name is both what the model reads and what the script reports try: with open(args.labels, encoding="utf-8") as f: own = {h: v.get("labels", v) if isinstance(v, dict) else v for h, v in json.load(f).items()} except (OSError, ValueError, AttributeError) as e: sys.exit(f"Can't read {args.labels}: {e}") if not own or not all(isinstance(v, dict) and v for v in own.values()): sys.exit(f"Can't use {args.labels}: expected " '{"head": {"label": "one-line description", ...}, ...}') heads = {h: {name: d if isinstance(d, list) else [name, d] for name, d in v.items()} for h, v in own.items()} emails = load(args, heads) if not emails: sys.exit("No emails found.") first = " + ".join(heads) # the first call's name: "label + priority", or your own heads steps = [(first, heads, not args.labels), ("news filter", {"news": NEWS}, False)] unmapped = collections.Counter(f'{h} "{v}"' for e in emails for h, v in e.get("unmapped", [])) if unmapped: print(f"Left out of the score, not one of the labels: {', '.join(f'{k} ×{n}' for k, n in unmapped.most_common(8))}") print(f"{len(emails)} emails, newest first. {args.parallel} calls at a time. Results go to {args.out} as they're done.") rows = [{"id": e["id"], "date": e["date"], "from": sender(e), "subject": e["subject"], "decisions": {}, "answer_key": e["key"] or None, "ms": {}, "tokens": {}, "cost_usd": None} for e in emails] total, done, t0, lock = 2 * len(emails), [0], time.time(), threading.Lock() def run(i, names): """The given steps for one email, one call after the other.""" out = {} for name, step_heads, always_low in steps: if name in names: try: out[name] = decide(api_key, step_heads, emails[i], always_low) except Exception as x: # keep going; record the failure out[name] = {"error": str(x)} with lock: done[0] += 1 if done[0] == 10 and total > 10: per = (time.time() - t0) / 10 print(f" 10 calls in {minutes(per * 10)}: about {minutes(per * (total - 10))} to go at this speed") return i, out def merge(i, out): row = rows[i] for name, r in out.items(): if "error" in r: row.setdefault("errors", {})[name] = r["error"] continue row.get("errors", {}).pop(name, None) row["decisions"].update(r["decisions"]) row["ms"][name], row["tokens"][name] = r["ms"], r["tokens"] if r["cost_usd"] is not None: row["cost_usd"] = round((row["cost_usd"] or 0) + r["cost_usd"], 10) if not row.get("errors"): row.pop("errors", None) names = [name for name, _, _ in steps] with ThreadPoolExecutor(max(1, args.parallel)) as pool, open(args.out, "w", encoding="utf-8") as out: write = lambda row: (out.write(json.dumps(row, ensure_ascii=False) + "\n"), out.flush()) failed = [] for n, job in enumerate(as_completed([pool.submit(run, i, names) for i in range(len(emails))]), 1): i, result = job.result() merge(i, result) write(rows[i]) if "errors" not in rows[i] else failed.append(i) if n % 10 == 0 or n == len(emails): print(f" {n}/{len(emails)} emails") if failed: # one more pass for the emails with a failed call, as the page does print(f" one more try for {len(failed)} emails with a failed call") for job in as_completed([pool.submit(run, i, list(rows[i]["errors"])) for i in failed]): i, result = job.result() merge(i, result) write(rows[i]) news = [e for e, row in zip(emails, rows) if row["decisions"].get("news") == "news"] brief = None if news and not args.no_briefing: print(f" briefing from {len(news)} news emails") try: brief = briefing(api_key, news) except Exception as x: brief = {"briefing": None, "error": str(x)} write(brief) # The report print(f"\nResults: {args.out}") errors = [(row["id"], name, err) for row in rows for name, err in row.get("errors", {}).items()] print(f"{'emails:':<24} {len(rows)} · {len(errors)} failed calls") for mid, name, err in errors: print(f" error on {mid} ({name}): {err}") count = lambda h: " · ".join(f"{k} {n}" for k, n in collections.Counter( r["decisions"].get(h) for r in rows if h in r["decisions"]).most_common()) for h in heads: print(f"{h + ':':<24} {count(h)}") print(f"{'news:':<24} {len(news)} of {sum('news' in r['decisions'] for r in rows)}") for h in [*heads, "news"]: # against the answers, when the inbox has them scored = [(r["answer_key"][h], r["decisions"][h]) for r in rows if (r["answer_key"] or {}).get(h) and h in r["decisions"]] if scored: misses = collections.Counter(f"{t} → {g}" for t, g in scored if t != g) print(f"{'right (' + h + '):':<24} {sum(t == g for t, g in scored)}/{len(scored)}" + (f" misses: {', '.join(f'{k} ×{n}' for k, n in misses.most_common(5))}" if misses else "")) per_email = 0.0 for name in names: ok = [r for r in rows if name in r["ms"]] known = [r["tokens"][name] for r in ok if r["tokens"][name] is not None] if ok: tin = sum(t["in"] for t in known) c = cost(DECIDE, {"in": tin, "out": 0}) per_email += c / len(known) if known else 0 ms = [r["ms"][name] for r in ok] print(f"{name + ':':<24} {len(ok)} calls · p50 {pct(ms, 0.5)} ms · p90 {pct(ms, 0.9)} ms · {tin:,} tokens in" + (f" · ${c:.6f} · ${c / len(known) * 1e6:.2f} per 1M emails" if known else " · usage not reported")) print(f"{'both decisions:':<24} ${per_email * 1e6:.2f} per 1M emails") if brief and brief.get("error"): print(f"briefing failed: {brief['error']}") elif brief: t = brief["tokens"] print(f"{'briefing:':<24} {len(brief['news_ids'])} news emails · {brief['ms'] / 1000:.1f} s · " + (f"{t['in']:,} in / {t['out']:,} out, reasoning included · ${brief['cost_usd']:.6f}" if t else "usage not reported")) if brief.get("finish_reason") == "length": # the reasoning and the briefing share max_tokens print(f"The briefing stopped at max_tokens ({BRIEFING['max_tokens']:,}), which the reasoning shares: " "it may be cut short or empty.") if len(brief["news_ids"]) < 3: # with little news, a model can pad the briefing print("With this little news, the model can add stories that aren't in the emails. " "Check each bullet against its sources.") print(f"\n{brief['briefing']}") if __name__ == "__main__": main() ``` ## Contact For questions, or a dedicated key for a larger test: maddy@zerogpu.ai · https://zerogpu.ai