FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

How a 12-email thread becomes 78 copies in your RAG index

Every reply drags the quoted history along with it, so old decisions drown out new ones unless you strip them at ingest.

ShareLinkedInFacebookX

In brief

  • When you pull a thread through an API, every reply carries the full chain of quotes, so old emails are repeated and crowd out new ones in the embeddings.
  • Remove quoted text and signatures at ingest, and keep sender, date, message_id and in_reply_to as metadata.
  • Make each email one chunk, check the chunk count against the email count the API reports, and filter on metadata before semantic search.
A long horizontal bar split into two parts, drawn to scale: 12 new copies in teal and 66 repeated copies in orange, making 78 copies of content in a 12-email thread. Stripping quoted text at ingest leaves exactly 12 copies.
When a 12-email thread is pulled through the Gmail API, each reply comes back with its entire quoted chain, so 12 real emails become 78 copies of content. Only 12 of them are new. Source: analysis on DEV Community (the sum 1 + 2 + … + 12).

Pull a 12-email client thread through the Gmail API and you can end up with 78 copies of its content. An analysis on DEV Community points out that every reply comes back with the full chain of quotes beneath it. The first email therefore appears 12 times, the second 11 times, and so on: 1 + 2 + … + 12 = 78.

Only 12 of those 78 copies are new; the rest are repeats. A user on the LangChain forum reports that when whole emails are chunked, 60-80% of the content is quoted history. That is a practitioner’s observation rather than a systematic measurement, but it is consistent with the arithmetic above.

So when the client asks “when did we last agree the deadline?”, the retriever tends to pull back the old agreement, because that sentence is repeated most often. This guide builds a small pipeline that deals with the problem at ingest. If a client wants question answering over their mailbox, build this stage first.

What will you build, and what do you need?

The input is the raw emails of one thread. The output is a list of records, one per email: the text the sender just wrote, with no quotes and no signature, plus metadata. The field list follows a suggestion on the LangChain forum: sender, recipients, date, thread_id, message_id, in_reply_to, has_attachments.

You need Python and two open-source libraries. Zapier’s Email Reply Parser is a Python port of GitHub’s parser, built to extract the last reply in a thread. Mailgun’s Talon was written specifically to separate quoted text and signatures from emails.

pip install email_reply_parser
pip install talon
# Talon's machine learning mode needs a separate extra
pip install "talon[ml]"

Check: both libraries import in a REPL. If you don’t need ML mode yet, skip the third install.

Step 1: capture sender and date before touching the content

Headers must be read first. Once you cut the quoted text, you lose lines such as “On Monday, A wrote:”, which are the only place in the body that says who said what. The headers stay intact. The code below is a simplified sketch: it uses Python’s built-in email module and assumes each email has a single plain-text part.

One detail is easy to miss: the Date header is a string such as “Mon, 3 Feb 2025 09:15:00 +0700”. Sorting it alphabetically does not give chronological order, so convert it to datetime as you read it.

import email
from email.utils import parsedate_to_datetime

def read_headers(raw: str, thread_id: str) -> dict:
    msg = email.message_from_string(raw)
    raw_date = msg["Date"]
    return {
        "sender": msg["From"],
        "recipients": msg["To"],
        # raw Date strings do not sort chronologically, so parse them
        "date": parsedate_to_datetime(raw_date) if raw_date else None,
        "thread_id": thread_id,
        "message_id": msg["Message-ID"],
        "in_reply_to": msg["In-Reply-To"],
        # rough approximation: multipart does not always mean an attachment
        "has_attachments": msg.is_multipart(),
        "body": msg.get_payload(),
    }

Check: print the records for the second and third emails. date must be a datetime object, and the third email’s in_reply_to must match the message_id of the email it answers. Take this field seriously.

The DEV Community article stresses that an email thread is a conversation tree, so flattening it into a straight line loses the record of who replied to whom. Keep in_reply_to and you can rebuild the tree when you need it.

Step 2: keep only what the sender just wrote

This step removes the 66 repeated copies in the opening example. EmailReplyParser.parse_reply returns just the newest reply in an email.

from email_reply_parser import EmailReplyParser

def newest_text(body: str) -> str:
    return EmailReplyParser.parse_reply(body)

Check: compare the length of body with the result. For the last email in a 12-email thread, the result should be far shorter and contain no sentence from earlier emails. The library leans toward plain text, so if the client sends a lot of HTML email, don’t assume it will still work well: collect a set of their real HTML samples and read the results yourself before trusting them.

Step 3: strip signatures, because no two look alike

With the quotes gone, each passage still ends in a signature. The DEV Community article describes a real organization with more than 30 signature styles, on top of compliance disclaimers in several languages. Left in place, all of that gets embedded as content.

Talon separates signatures in two modes. The rule-based mode needs nothing extra installed, and Talon’s own README says it is fast and works very well 90% of the time. The remaining cases use the ML mode, which is built on scikit-learn SVM classifiers and needs the talon[ml] extra.

The function returns a pair: the body and the signature it extracted. Only the body is kept.

from talon.signature.bruteforce import extract_signature

def strip_signature(text: str, sender: str) -> str:
    # rule-based mode: returns (body, signature or None)
    body, _signature = extract_signature(text)
    # ML mode (needs talon[ml]) also takes the sender's address;
    # switch only when tests show the rule-based mode misses cases
    return body

Check: take 20 emails from 20 different senders and read the end of each result yourself. Long disclaimers often look nothing like signatures, so keep a separate list of patterns for this client’s own disclaimers.

Step 4: one chunk per email, counted against an independent number

A chunking guide on theneuralbase recommends treating each email as a natural boundary and attaching the thread’s metadata to it. Chunking by a fixed token count cuts through emails and mixes two senders in one passage.

The check that source proposes is that the number of chunks must equal the number of emails. But if you count the list you just built, the check can never fail. Compare it with a number from somewhere else, such as the email count the API reports for the thread, and confirm that no message_id is duplicated.

def build_chunks(raws: list[str], thread_id: str,
                 expected_count: int) -> list[dict]:
    # expected_count: the API's email count for the thread, not len(raws)
    chunks = []
    for raw in raws:
        rec = read_headers(raw, thread_id)
        text = newest_text(rec.pop("body"))
        rec["text"] = strip_signature(text, rec["sender"])
        chunks.append(rec)
    ids = {c["message_id"] for c in chunks}
    assert len(ids) == len(chunks), "duplicate message_id found"
    assert len(chunks) == expected_count, "chunk count differs from API email count"
    return chunks

Check: on the sample thread, chunking whole emails also yields 12 chunks, so the number 12 proves nothing by itself. What you need to see is that each chunk now holds only one email’s own text, meaning the 66 repeated copies are gone. Search every chunk for a distinctive sentence from the first email: it should appear exactly once.

The open-source project mailrag also lists removing reply chains among its core preprocessing steps, alongside removing chunks with identical text and filtering out newsletters. Run those two steps right after this chunking stage.

Step 5: filter on metadata first, search semantically second

With clean metadata in hand, don’t make the embedding guess dates. The LangChain forum states the principle concisely: filter by metadata first, retrieve semantically second. The question “when did we last agree the deadline?” should run in this order: filter by thread_id, sort by date (a datetime since step 1) in descending order, then rank semantically within the filtered set.

Check: ask the same question twice, once with the date filter and once without. If the unfiltered run returns an older email, you have a before-and-after example to show the client.

What are the most common mistakes?

The first is testing only on your own email. The Email Reply Parser README acknowledges that every email client formats replies differently, which makes parsing very hard. Ask which clients your customer uses, then gather real samples of each for the test set.

The second is removing quotes before reading the headers, which leaves clean text with no known author. The third is treating a thread as a straight line. When two people answer the same email, only in_reply_to shows where the two branches split.

What will clients complain about on a real project?

Clients rarely ask for “email cleaning”. They are more likely to complain that the bot answers from outdated information, which is the symptom the arithmetic at the start explains.

Open with that count: take one of their real threads, count the repeated copies and show them the result before proposing time for the ingest stage.

When you put this on your CV, write a measurable outcome instead of a list of tools. For example: “removed 66 of 78 copies of repeated content in a 12-email thread by stripping quotes at ingest, and added date filtering before retrieval”. That line shows an FDE interviewer that you understand the client’s data.

If the job description mentions RAG over enterprise data, this is an example to take into the interview.

However good the model, it cannot rescue a mailbox in which old emails are repeated a dozen times. Correct answers start with clean data.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
6 sources
Read next on the roadmap · Stage 3: Applied AIWhy RAG chatbots fail at question three, and how to prove the fixThe usual culprit is a pronoun the retriever cannot resolve; rewriting the question helps, but only a test set split by turn will convince a client.