Module 3 · Long-context ingestion

Ingesting codebases, contracts and financial reports

7 min read

With windows of several hundred thousand tokens, you can give the model an entire code repository, a hundred-page contract or an annual report, rather than a few excerpts chosen by a search engine. You still have to give them well: with their structure, their sources, and without the noise around them. This lesson describes how to prepare three kinds of documents, then how to ask questions to get verifiable answers.

Assembling documents: sources and structure

The principle is the same for every document: each in its own tag, with its source as an attribute. The model can then cite "app/auth.py" or "article 12.3", and you can check.

def pack(docs: list[Doc], with_tree: bool = True) -> str:
    parts = [f"<arborescence>\n{tree(docs)}\n</arborescence>"] if with_tree else []
    parts += [f'<document index="{i}" source="{d.source}">\n{d.content}\n</document>'
              for i, d in enumerate(docs, 1)]
    return "<documents>\n" + "\n".join(parts) + "\n</documents>"

The result looks like this:

<documents>
<arborescence>
examples/01_prompt_anatomy.py
quill/extraction.py
...
</arborescence>
<document index="1" source="examples/01_prompt_anatomy.py">
...
</document>
...
</documents>

The file tree at the top gives the model the map before the territory: it knows which files exist before reading them, like a developer opening a project.

Codebases: removing the noise

A repository contains many things that are not useful code: installed dependencies, generated files, lock files, binaries. Including them costs tokens and dilutes attention.

SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", "dist", "build", "runs", ".cache"}
SKIP_FILES = {"package-lock.json", "poetry.lock", "uv.lock", "yarn.lock", "pnpm-lock.yaml"}


def source_files(root: str | Path, suffixes: tuple[str, ...] = (".py", ".md", ".toml", ".yaml")) -> list[Doc]:
    """Les fichiers utiles d'un dépôt : ni dépendances, ni fichiers générés, ni verrous, ni binaires."""
    root = Path(root)
    docs = []
    for path in sorted(root.rglob("*")):
        rel = path.relative_to(root)
        if any(part in SKIP_DIRS for part in rel.parts) or path.name in SKIP_FILES:
            continue
        if path.is_file() and path.suffix in suffixes:
            try:
                docs.append(Doc(rel.as_posix(), path.read_text(encoding="utf-8")))
            except UnicodeDecodeError:
                continue
    return docs

Measured on the Quill project itself, with the Qwen tokenizer:

MeasureValue
Files kept39
Size110,000 characters
Tokens, full assembly33,333
of which tags and file tree1,055 (3%)
Largest file: promptfoo/tests.yaml5,685 tokens (17%)

Two practical lessons:

  • Even a small project exceeds a small model's window: 33,333 tokens is more than Qwen2.5's 32,768. A model with 200,000 tokens or more swallows it easily, but you must count before sending;
  • The largest file is not code: tests.yaml is a dataset generated by a script. If the question is about architecture, it weighs 17% of the prompt for nothing. Exclude generated files and data, or keep only their first lines.

When the budget is exceeded, choose what goes in, in a deliberate order (files mentioned in the question, then entry points, then the rest):

def fit_budget(docs: list[Doc], budget: int, count) -> tuple[list[Doc], list[Doc]]:
    """Garde les documents dans l'ordre tant que le budget de jetons le permet ; renvoie (gardés, écartés)."""
    kept, dropped, used = [], [], 0
    for d in docs:
        n = count(d.content)
        if used + n <= budget:
            kept.append(d)
            used += n
        else:
            dropped.append(d)
    return kept, dropped

With a 20,000-token budget, 26 files fit and 13 are dropped. Tell the model ("the following files were not provided: …"): it will know it does not see everything, instead of inventing their contents.

Contracts: keeping the numbering

A contract is a web of cross-references: "subject to article 9.2", "as defined in appendix B". Correct answers depend on these references. To preserve them:

  • keep the numbering and headings as they are when converting the PDF to text: a conversion that loses them makes cross-references meaningless;
  • include appendices and amendments, each in its own document: an amendment often modifies a clause of the main contract, and the model must see both;
  • state the order of precedence ("in case of conflict, the amendment prevails over the contract, which prevails over the general terms");
  • ask for references: every statement must point to an article.

Financial reports: tables, units and calculations

Financial reports set three traps:

TrapRemedy
Tables badly extracted from the PDF (shifted columns)Convert tables to Markdown or CSV, and check a sample by hand
Units and scopes ("in thousands of euros", "excluding discontinued operations")Keep headers and table footnotes with the table
Calculations (changes, ratios, totals)Have the model extract the figures, have code compute (lesson 2.3)

The third point is the most important: a model that reads a 300-page report very well can still get a subtraction wrong. Ask it for the source figures with their page, then compute.

Quote first, answer next

On a long document, the most effective technique for verifiable answers is to ask first for exact quotes, then for the answer based on them:

QUOTE_THEN_ANSWER = """{documents}

Question : {question}

Procède en deux temps :
1. Dans <citations>, recopie mot pour mot les passages qui répondent à la question, chacun précédé de sa
   source (fichier, article ou page). S'il n'y en a aucun, écris « aucun passage ».
2. Dans <reponse>, réponds en t'appuyant uniquement sur ces citations."""

This template combines several good practices:

  • documents first, question last (lesson 3.2);
  • an explicit search step, which forces the model to find the passages before reasoning;
  • an automatically verifiable output: each quote must appear verbatim in the document, which a simple in in Python checks;
  • a planned way out ("aucun passage") when the answer is not in the document, which reduces fabrication.

With the Claude API, the long document is cached, and the question comes after the cache point (lesson 3.4):

def ask_long_document(document: str, title: str, question: str, effort: str = "medium") -> tuple[str, dict]:
    """Document long EN TÊTE, mis en cache ; question À LA FIN. Renvoie la réponse et l'usage (jetons, cache)."""
    response = client().messages.create(
        model=config.CLAUDE_MODEL,
        max_tokens=4000,
        system="Tu réponds aux questions sur les documents fournis. Cite le passage qui justifie ta réponse.",
        messages=[{"role": "user", "content": [
            {"type": "text", "text": f"<document titre=\"{title}\">\n{document}\n</document>",
             "cache_control": {"type": "ephemeral"}},  # le préfixe stable est relu depuis le cache
            {"type": "text", "text": question},          # la partie variable, après le point de cache
        ]}],
        output_config={"effort": effort},  # low | medium | high | xhigh | max
    )
    u = response.usage
    usage = {"input": u.input_tokens, "cache_write": u.cache_creation_input_tokens or 0,
             "cache_read": u.cache_read_input_tokens or 0, "output": u.output_tokens}
    return text_of(response), usage

Long context or RAG?

SituationApproach
A corpus that fits in the window, queried many timesLong context + prompt caching
Questions spanning the whole document (consistency, contradictions, synthesis)Long context: excerpt-based search does not see the whole
A corpus much larger than the window, or constantly changingRAG (Advanced RAG course)
A one-off question about a precise fact in a large baseRAG: cheaper and faster

The two combine: RAG selects the relevant documents whole (not fragments), then the long context reads them in full.

Key takeaways

  • Each document in its own tag, with its source: the model can cite, you can check.
  • Remove the noise (dependencies, lock files, generated files) and count tokens before sending: the Quill project alone is 33,333 tokens.
  • Contracts: keep the numbering, include amendments, state the order of precedence.
  • Financial reports: clean tables, units with the figures, calculations by code.
  • Quote first, answer next: grounded answers that can be checked automatically.

Practice

  1. Assemble one of your repositories with packing.source_files and packing.pack, then count the tokens: which files weigh the most?
  2. Write the automatic check of the quotes from the QUOTE_THEN_ANSWER template (each quote present verbatim in the documents).
  3. Ask the same architecture question with and without the file tree at the top: does the answer change?

Resources