Skip to content
Tinbox

tutorials

Summarize long email threads with an AI sub-call

November 20, 2026

#ai#summarization#inbox#agents#tutorial
Conversation pages fold into a concise briefing card.

A vendor thread has 40 messages, three people, two attachments, and a decision buried somewhere in the middle. You open it, scroll, lose the plot, and close it again. You do not need to read all 40. You need one paragraph.

To summarize a long email thread with AI, fetch the thread's messages in chronological order, render them into a single bounded prompt (sender plus body per message, truncated), and make one LLM sub-call with a system prompt that asks for the participants, the ask, the current state, and what needs a response. A 40-message thread becomes one model call. The interesting engineering is not the call itself, it is bounding the input so you never overrun the context window and never accidentally feed the whole inbox into the prompt.

This walkthrough builds the summarizer by hand: fetching the thread, rendering it safely, making the sub-call, and parsing the result. It is honest about the truncation and prompt-hygiene work that the naive version skips. Then it shows how Tinbox ships the same logic as a summarize_thread tool that your chat agent, MCP clients, and CLI all share.

How do you summarize a long email thread with AI?

You reduce the whole thread to one prompt and make one call. Summarization is a reduction over a fixed, self-contained input, which makes it the simplest shape of LLM work: one request, one response, no agent loop. The steps are:

  1. Load every message in the thread, oldest to newest.
  2. Render them into a single string the model can read.
  3. Send that string with a system prompt that defines what a good summary contains.
  4. Parse the returned text and show it.

Nothing here needs an agent, a tool loop, or retrieval. People reach for retrieval-augmented answers over an email archive when the input will not fit in a prompt, but a single thread almost always fits. Adding retrieval to summarize one conversation buys you latency and new failure modes and nothing else. Keep this path boring.

The part that is easy to get wrong is step 2. A 40-message thread where each message quotes the entire conversation below it is not 40 messages of content, it is the same content pasted 40 times with a growing prefix. Render that raw and you send roughly O(n squared) text to the model: you pay for it, you may overrun the window, and the summary gets worse because the signal is drowned in repetition.

How do I fetch the thread's messages?

Load the thread and its messages from your store, sorted oldest to newest, keeping the sender and a plain-text body for each. Whatever backs your inbox (Postgres, SQLite, D1), the query is the same shape: one thread, its messages in order. On Cloudflare D1 with Drizzle it looks like this.

import { eq, asc } from "drizzle-orm";
import { messages, threads } from "./schema";

export async function loadThread(db: DrizzleD1Database, threadId: string) {
  const [thread] = await db
    .select({ subject: threads.subject })
    .from(threads)
    .where(eq(threads.id, threadId))
    .limit(1);

  if (!thread) return null;

  const rows = await db
    .select({ from: messages.from, bodyText: messages.bodyText })
    .from(messages)
    .where(eq(messages.threadId, threadId))
    .orderBy(asc(messages.date));

  return { subject: thread.subject, messages: rows };
}

The orderBy(asc(messages.date)) matters: a summary of an out-of-order thread reads like a transcript shuffled by a dealer. If your schema stores message bodies in both HTML and plain text, take the plain text. The model does not need your markup, and HTML inflates the token count for no gain. (If you only have HTML, strip tags before you render. A summary prompt full of <div style="..."> is mostly noise.)

How do I render the thread into a prompt without overrunning the context window?

Bound the input on three axes before you build the string: per-message length, total message count, and quoted-reply duplication. Trusting a large context window to absorb anything is the mistake that turns a cheap call into an expensive one. The window is generous, but you pay per token and quality degrades when the prompt is mostly repetition.

Here is a renderer that caps each body, caps the number of messages, and keeps the oldest and newest when a thread is enormous (the middle of a long thread is usually the least load-bearing for a summary).

const MAX_BODY_CHARS = 4000;
const MAX_MESSAGES = 60;

function stripQuotedReply(body: string): string {
  // Drop everything from the first quoted-reply marker onward.
  // Crude but effective: most clients prefix quotes with "> " or
  // an "On <date>, <person> wrote:" line.
  const lines = body.split("\n");
  const out: string[] = [];
  for (const line of lines) {
    if (/^>/.test(line)) break;
    if (/^On .+ wrote:$/.test(line.trim())) break;
    out.push(line);
  }
  return out.join("\n").trim();
}

export function renderThread(thread: {
  subject?: string;
  messages: { from: string; bodyText: string }[];
}): string {
  let msgs = thread.messages;

  // If the thread is huge, keep the oldest 20 and newest 40.
  if (msgs.length > MAX_MESSAGES) {
    msgs = [...msgs.slice(0, 20), ...msgs.slice(-40)];
  }

  const head = `Subject: ${thread.subject ?? "(no subject)"}\n\n`;
  const body = msgs
    .map((m) => {
      const text = stripQuotedReply(m.bodyText).slice(0, MAX_BODY_CHARS);
      return `From: ${m.from}\n${text}`;
    })
    .join("\n\n---\n\n");

  return head + body;
}

stripQuotedReply is the line that pays for itself. Without it, message 40 contains messages 1 through 39 quoted underneath it, and you send the early conversation dozens of times. With it, each message contributes only its new content, which is what a summary should be built from. The regex is deliberately crude; email quoting has no standard, so you handle the two common cases (> prefixes and the On ... wrote: header) and accept that an exotic client will occasionally leak a quote. That is fine. The goal is bounding, not perfection.

The truncation is lossy on purpose. A single message longer than 4000 characters is rare in practice and usually a pasted log or a forwarded newsletter, neither of which improves a summary. If you have a domain where long bodies carry signal, raise the cap, but raise it knowingly.

How do I make the AI sub-call?

Send the rendered thread as the user prompt with a system prompt that defines what a good summary is, and make one call. This is the whole "AI" part, and it is a single request. Using the Anthropic SDK:

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const SUMMARY_SYSTEM =
  "You are an email summarizer. Given a thread, produce a concise summary: " +
  "who is involved, what they want, the current state, and what (if anything) " +
  "needs a response. 3-5 sentences. No preamble.";

export async function summarizeThread(rendered: string): Promise<string> {
  const response = await client.messages.create({
    model: "claude-opus-4-8",
    max_tokens: 1024,
    thinking: { type: "adaptive" },
    output_config: { effort: "low" },
    system: SUMMARY_SYSTEM,
    messages: [{ role: "user", content: rendered }],
  });

  const text = response.content
    .filter((b) => b.type === "text")
    .map((b) => (b as { text: string }).text)
    .join("")
    .trim();

  return text;
}

A few choices worth naming. effort: "low" keeps this fast and cheap; summarization is a bounded reduction, not a reasoning marathon, so you do not need to spend much. max_tokens: 1024 is plenty for a 3-5 sentence summary and caps your downside if the model gets chatty. The system prompt does the real work: it tells the model the four things a useful thread summary answers, so you get a consistent shape instead of a different essay each time. "No preamble" suppresses the "Here is a summary of the thread:" throat-clearing that you would otherwise strip in post.

Note the content extraction. The response content is an array of blocks, so you filter for text blocks and join them rather than reading content[0].text blindly. With adaptive thinking on, the array can also carry thinking blocks; the filter skips them.

The failure mode you will hit first

The naive version of this call sends the raw thread with no truncation and no max_tokens ceiling, and the first genuinely long thread either errors or costs more than the feature is worth. The error looks like this:

RequestTooLargeError: 413 {"type":"error","error":{
  "type":"request_too_large",
  "message":"input length exceeds the maximum allowed"}}

The fix is not a bigger model or a bigger window. It is the renderer from the previous section. Bound the input, then the call is cheap and predictable no matter how long the thread runs. If you only take one thing from this walkthrough, take that: the model call is trivial, the input discipline is the engineering.

How do I put it together?

Wire the three pieces into one function: fetch, render, call. The orchestration is small because each piece does one thing.

export async function summarize(db: DrizzleD1Database, threadId: string) {
  const thread = await loadThread(db, threadId);
  if (!thread) return { error: "Thread not found." };

  const rendered = renderThread(thread);
  const summary = await summarizeThread(rendered);

  return {
    threadId,
    summary,
    messageCount: thread.messages.length,
  };
}

Return the messageCount alongside the summary. When your UI shows "Summary of 41 messages" above the paragraph, the reader can calibrate trust: a one-line summary of 41 messages is doing a lot of compression, and saying so is more honest than presenting the paragraph as if it captured everything. It also makes the truncation visible, since a thread of 200 messages summarized from 60 is a fact the reader deserves.

That is the entire feature. Fetch in order, render with bounds, call once, return the text and the count. No agent loop, no retrieval, no vector store. The hard-way version and the shortcut version do exactly the same four things; the only question is how much of the plumbing you want to own.

Should the summarizer be a tool or an endpoint?

Make it a tool that takes a thread id, so every surface that talks to your inbox can call the same code. An endpoint is fine for a "Summarize" button, but a tool is what lets your chat agent decide when a summary is useful mid-conversation, lets an MCP client request one, and lets your CLI run it from a script. Same logic, one definition, many callers. This is the nested-LLM pattern: a tool the outer agent can call, whose implementation itself makes an LLM call.

The tool's input schema is one field, the thread id, and its execute function is the summarize orchestration above. Because the implementation reads the thread through your normal authorized data path and only ever calls the model with a bounded prompt, it inherits your access control for free: a caller can only summarize threads they can already read.

Or skip all of this: the Tinbox summarize tool

Tinbox ships this as a summarize_thread tool so you do not build the renderer, the truncation, and the sub-call yourself. It is one of the inbox tools the chat agent, the MCP server, and the CLI all share from a single Zod manifest, so the same summarizer answers a question in the webmail chat, a request from Claude over MCP, and a tinbox summarize-thread <id> command in your terminal.

The tool reads the thread through the same authorized query path the rest of the inbox uses (so summarizing respects who can see what), renders the messages with the bounding described above, and makes the model sub-call with the inbox's configured provider key. When no model is wired up (in tests, or a deploy with no key), it returns a graceful "summarization is not available" result instead of throwing, so the agent degrades cleanly rather than crashing a conversation. Because the whole stack runs on your own Cloudflare account (D1 for the messages, your key for the model), the thread text never passes through a third-party summarization SaaS, and there is no per-thread or per-token markup on top of what you already pay the model provider.

If you want the AI inbox layer above this, the same tool surface powers automatic inbox triage and a chat agent you can connect Claude to over MCP, all reading the same D1 you own. For the wider menu of what this layer can do, the AI inbox features every developer should know about and the email tasks worth automating with an AI agent are good maps, and the things RAG over your email unlocks picks up where the retrieval aside above leaves off.

Deploy this yourself: npx tinbox init <your-domain>. The summarize tool, the shared tool manifest, and the streaming chat agent are in the box; see the docs for the agent tool reference and how to wire your own provider key.

Frequently asked questions

How do I get an AI to summarize a long email thread?

Fetch every message in the thread in chronological order, concatenate them into one prompt as sender plus body (truncating each body so the total stays inside the model's context window), and make a single LLM call with a system prompt that asks for a concise summary: participants, the ask, the current state, and what needs a response. One thread maps to one model call. You parse the model's text back out and show it above the thread.

Do I need embeddings or a vector database to summarize one thread?

No. A single thread is small and self-contained, so you pass the whole thing to the model in one call. Embeddings and retrieval are for querying across an entire archive you cannot fit in a prompt. For one conversation, retrieval adds latency and failure modes for no benefit. Reach for retrieval only when the input genuinely will not fit, which a 40-message thread almost never does.

How do I keep a thread summary from blowing the context window?

Bound the input before you send it. Cap each message body to a few thousand characters, cap the number of messages you include (oldest plus newest if the thread is huge), and strip quoted reply chains so you are not re-summarizing the same text 40 times. A 1M-token context window is generous, but you still pay for every token, so truncate deliberately rather than trusting the window to absorb anything.

Which model should I use to summarize email threads?

Summarization is a single-call task, so any capable model works. The example uses claude-opus-4-8 with adaptive thinking and low effort, which is fast and cheap for this kind of bounded reduction. You can drop to a smaller model if cost matters more than nuance; the prompt and parsing stay identical because the request shape does not change.

Should an AI thread summary be a tool the agent calls, or a separate endpoint?

Make it a tool. If you expose summarize_thread as a tool with a thread id input, your chat agent, an MCP client, and your CLI can all invoke the same code path, and the model decides when a summary is useful rather than you hardcoding it. A standalone endpoint works for a button in the UI, but a tool is reusable across every surface that talks to the inbox.