Summarizing a contract with a model: the risk is not style, it is the wrong number
A summary that reads smoothly and says "penalty of 10% per day" when the contract says 1% is worse than no summary at all, because the person reading it trusts it. That is why summarizing legal documents with a language model is designed starting from control, not from the prompt. A preregistered study of commercial AI legal research systems (Magesh et al.) found that the Lexis+ AI and Thomson Reuters tools it evaluated produce false information between 17% and 33% of the time. The figure concerns legal research tools and not the summarization of a single document, but it gives the order of magnitude of the problem: a system designed not to hallucinate still produces hallucinations.
This article builds the three pieces you can run without a model: a chunker that respects the structure of the articles, the map-reduce orchestration with a parallelism limit, and a validator that compares the facts in the summary with those in the original. The model is an insertion point (a function you pass in). I include no training code because I could not run it, and further down I say when training is worth considering.
Why a long document is not given whole to the model
Models have a limited context window, and the limit changes from model to model and over time: read it from your provider's documentation instead of trusting a number in an article. Even within the limit, the research paper "Lost in the Middle" observed that model performance can degrade significantly when the relevant information sits in the middle of a long context, even for models built for long contexts. Putting three hundred pages into a single prompt is therefore not just expensive: it can make you lose precisely the clause hidden on page 150.
Contracts have an extra problem: clauses depend on definitions scattered across the text. A "Serious Default" defined in article 1 has consequences in article 12; a chunk containing only article 12 does not know what the term means. Three strategies recur in practice, and each one pays a price:
- Map-reduce: each part is summarized in parallel and then the summaries are summarized; fast, but each part ignores the others.
- Hierarchical: the parts are grouped by topic and summarized in levels; it preserves the structure better, but it is more complex to build.
- Refinement: you start from one summary and update it with each following part; it keeps the context, but it is sequential and slow.
The order does not say which is better: it depends on what matters. For a high volume of standard contracts, map-reduce is enough, as long as every call also receives the definitions; for a long, unique contract in which the cross-dependencies are the point, refinement or the hierarchical structure cost more and lose less. The listing that follows implements the first, and shows how to pass the definitions.
The chunker: cut on articles, not on a number of characters
Cutting every N characters splits articles in half. The chunker instead uses the article heading
(Art. N, with re.M so that ^ matches at every line) as the boundary, and
falls back to overlapping word windows only if an article exceeds the maximum size. The token estimate is about
four characters per token: it is an approximation, and for a real limit you use the tokenizer of the model you
chose.
import re
from dataclasses import dataclass
INTESTAZIONE = re.compile(r"^(?:Art(?:icle|\.)\s*(\d+))\b", re.M | re.I)
@dataclass(frozen=True)
class Chunk:
id: str
articolo: str | None
testo: str
def stima_token(testo: str) -> int:
"""Rough estimate (about 4 characters per token). For real limits use your model's tokenizer."""
return len(testo) // 4
def spezza(testo: str, max_token: int, sovrapposizione: int) -> list[str]:
parole = testo.split()
passo = max(1, max_token - sovrapposizione) # words per window: estimate 1 word ~ 1 token
return [" ".join(parole[i:i + max_token]) for i in range(0, len(parole), passo)
if parole[i:i + max_token]]
def chunk(testo: str, max_token: int = 4000, sovrapposizione: int = 200) -> list[Chunk]:
inizi = list(INTESTAZIONE.finditer(testo))
if not inizi:
sezioni = [(None, testo.strip())]
else:
fini = [m.start() for m in inizi[1:]] + [len(testo)]
sezioni = [(m.group(1), testo[m.start():f].strip()) for m, f in zip(inizi, fini)]
premessa = testo[:inizi[0].start()].strip()
if premessa:
sezioni.insert(0, ("preamble", premessa))
risultato = []
for numero, corpo in sezioni:
parti = [corpo] if stima_token(corpo) <= max_token else spezza(corpo, max_token, sovrapposizione)
for k, parte in enumerate(parti):
risultato.append(Chunk(f"{numero or 'x'}-{k}", numero, parte))
return risultato
if __name__ == "__main__":
contratto = (
"Between Acme S.p.A. (Supplier) and Beta S.r.l. (Customer) the following is agreed.\n"
"Art. 1 Definitions. \"Serious Default\" means a delivery delay of more than 15 days.\n"
"Art. 2 Delivery. The Supplier delivers by 15 March 2026. " + "Operational detail. " * 60 + "\n"
"Art. 12 Consequences. In case of Serious Default the Customer applies a penalty of 1% per day.\n")
for c in chunk(contratto, max_token=120, sovrapposizione=20):
print(f"{c.id:<10} article={c.articolo!s:<9} ~{stima_token(c.testo):>3} tokens {c.testo[:42]!r}")
# Output (executed):
# preamble-0 article=preamble ~ 20 tokens 'Between Acme S.p.A. (Supplier) and Beta S.'
# 1-0 article=1 ~ 20 tokens 'Art. 1 Definitions. "Serious Default" mean'
# 2-0 article=2 ~289 tokens 'Art. 2 Delivery. The Supplier delivers by '
# 2-1 article=2 ~ 74 tokens 'Operational detail. Operational detail. Op'
# 12-0 article=12 ~ 23 tokens 'Art. 12 Consequences. In case of Serious D'
In the output, article 2 is long (about 289 estimated tokens) and is split into two parts, while the others stay whole. The preamble has a chunk of its own. Two things to notice: the word-window split cuts a sentence in half, because it does not know about punctuation (a better chunker would split on paragraphs), and the definitions of article 1 end up in a different chunk from article 12. The second problem is solved at request time, not at cutting time, as the next step does.
Map-reduce with definitions and a parallelism limit
The code orchestrates the calls: asyncio.Semaphore limits how many requests reach the service at the
same time, to respect its limits; asyncio.gather keeps the order of the results the same as that of
the chunks; and the definitions are added to every call. The function that talks to the model is a parameter
(riassumi): to test the orchestration I used a deterministic stand-in, which is not a model and
does not produce real summaries. No model was called.
import asyncio
from typing import Awaitable, Callable
from chunker import chunk
Riassumi = Callable[[str], Awaitable[str]] # the model call goes here: it is the only point that changes
async def map_reduce(testo_chunks, definizioni: str, riassumi: Riassumi, max_paralleli: int = 3) -> str:
semaforo = asyncio.Semaphore(max_paralleli) # respects the service's request limits
async def mappa(c):
async with semaforo:
# every call also receives the definitions: an isolated chunk does not contain them
return f"[Art. {c.articolo}] " + await riassumi(f"DEFINITIONS:\n{definizioni}\n\nTEXT:\n{c.testo}")
parziali = await asyncio.gather(*(mappa(c) for c in testo_chunks)) # results keep the order of the chunks
return await riassumi("PARTIAL SUMMARIES:\n" + "\n".join(parziali))
async def main():
attive = massimo = chiamate = 0
async def modello_finto(prompt: str) -> str: # deterministic stand-in for a model, to test the orchestration
nonlocal attive, massimo, chiamate
attive += 1; chiamate += 1; massimo = max(massimo, attive)
await asyncio.sleep(0.01)
attive -= 1
return prompt.split("TEXT:\n")[-1][:30].replace("\n", " ") + "..."
contratto = "\n".join(f"Art. {n} Clause number {n}. " + "Sample text. " * 20 for n in range(1, 9))
chunks = chunk(contratto, max_token=200)
finale = await map_reduce(chunks, "Serious Default = delay of more than 15 days", modello_finto)
print(f"chunks: {len(chunks)}, model calls: {chiamate}, max in parallel: {massimo}")
print("final summary:", finale[:60])
if __name__ == "__main__":
asyncio.run(main())
# Output (executed):
# chunks: 8, model calls: 9, max in parallel: 3
# final summary: PARTIAL SUMMARIES: [Art. 1] Ar...
The output shows 8 chunks, 9 calls (8 from the map phase and 1 from the reduce phase) and at most 3 simultaneous calls, which is the limit that was set: the semaphore works. The listing does not handle the failure of a single call: in a real system a request that times out or is refused because of a rate limit must be retried with increasing delays, and if a part cannot be summarized the final summary must say so, not stay silent. With many chunks the result of the map phase can exceed the model's window, and then a second level of reduction is applied instead of a single synthesis.
Validating: why ROUGE-L alone does not see the omitted penalty
Overlap metrics such as ROUGE (ROUGE-L is based on the longest common subsequence of words) measure how much a summary resembles a reference: they are useful for comparing systems on a benchmark with reference summaries written by people. They do not measure whether a fact is true. The listing demonstrates this with three summaries of the same text, computing ROUGE-L and, separately, the facts (percentages, dates, days, references to articles) that are in the summary and not in the original (invented) or the other way round (omitted).
import re
NUMERO = re.compile(r"\d+(?:[.,]\d+)?\s*%|\d{1,2}\s+(?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}|\d+\s+days|\bart\.\s*\d+",
re.I)
def parole(t: str) -> list[str]:
return re.findall(r"\w+", t.lower())
def rouge_l(riferimento: str, candidato: str) -> float:
"""F1 on the longest common subsequence (LCS) of words."""
a, b = parole(riferimento), parole(candidato)
prec = [0] * (len(b) + 1)
for x in a:
corr = [0]
for j, y in enumerate(b, 1):
corr.append(prec[j - 1] + 1 if x == y else max(prec[j], corr[j - 1]))
prec = corr
lcs = prec[-1]
if lcs == 0:
return 0.0
p, r = lcs / len(b), lcs / len(a)
return 2 * p * r / (p + r)
def fatti(testo: str) -> set[str]:
return {re.sub(r"\s+", " ", m.group().lower()) for m in NUMERO.finditer(testo)}
def controlla(originale: str, riassunto: str) -> dict:
o, r = fatti(originale), fatti(riassunto)
return {"rouge_l": round(rouge_l(originale, riassunto), 2),
"invented": sorted(r - o), # in the summary but NOT in the original
"omitted": sorted(o - r)} # in the original but not in the summary
def instrada(esito: dict, valore_eur: float, soglia_valore: float = 1_000_000) -> str:
if esito["invented"]:
return "REJECTED: contains facts absent from the original"
critici = [f for f in esito["omitted"] if not f.startswith("art.")] # design choice: omitted articles do not block
if critici or valore_eur >= soglia_valore:
return "HUMAN REVIEW"
return "PASSES TO SAMPLE CHECK"
if __name__ == "__main__":
originale = ("Art. 2 The Supplier delivers by 15 March 2026. Art. 12 In case of a delay of more than "
"15 days the Customer applies a penalty of 1% per day on the order amount.")
riassunti = {
"faithful": "Delivery by 15 March 2026; with a delay of more than 15 days a penalty of 1% per day (art. 12).",
"wrong number": "Delivery by 15 March 2026; with a delay of more than 15 days a penalty of 10% per day (art. 12).",
"penalty omitted": "The Supplier delivers by 15 March 2026. In case of a delay of more than the agreed time the Customer may act on the order amount.",
}
for nome, testo in riassunti.items():
esito = controlla(originale, testo)
print(f"{nome:<17} {esito}\n{'':<17} -> {instrada(esito, valore_eur=200_000)}")
# Output (executed):
# faithful {'rouge_l': 0.62, 'invented': [], 'omitted': ['art. 2']}
# -> PASSES TO SAMPLE CHECK
# wrong number {'rouge_l': 0.58, 'invented': ['10%'], 'omitted': ['1%', 'art. 2']}
# -> REJECTED: contains facts absent from the original
# penalty omitted {'rouge_l': 0.7, 'invented': [], 'omitted': ['1%', '15 days', 'art. 12', 'art. 2']}
# -> HUMAN REVIEW
The result is the thesis of the article. The summary with the omitted penalty has ROUGE-L 0.70, higher than the faithful one (0.62) and than the one with the wrong number (0.58). The fact check, instead, catches the invented 10% (routed to rejection) and the omissions of the percentage and of the days (routed to human review). The limit is clear: a check based on regular expressions sees only the types of fact you taught it, and does not see meaning (a penalty attributed to the wrong party passes). The check does not replace reading: it reduces the reviewer's work and makes the first filter systematic. The routing thresholds, such as the value above which review is mandatory, are a choice of your firm and not a rule of law.
When training a model is worth it, and when it is not
Adapting an open-source model with LoRA is possible: the technique, described in the original paper, freezes the model's weights and trains small additional matrices, reducing the trainable parameters and the memory required compared with full fine-tuning. I give no code and no memory or time figures because I could not run a training, and they depend on model and hardware. The selection criterion is a different one: training is worthwhile when you have hundreds of document-summary pairs written by lawyers in your domain and a measured terminology problem that a well-made prompt does not solve. Without that data, training means teaching the model the style of summaries that nobody has verified.
Before getting there, three prompt measures cost little: ask to keep legal terms without paraphrasing them, ask for the article each statement comes from (which you can then verify automatically, like the check on references in the listing), and ask for a structured format with fixed sections (parties, subject matter, obligations, deadlines, penalties). Also store the source text with its SHA-256 fingerprint and the version of the prompt used: without them, a summary is neither reproducible nor defensible. On the complementary problem of searching the corpus of documents, see the search engine with embeddings; for the initial reading of a scanned file, from OCR to understanding.
What you can do now
You can split a contract on its articles, orchestrate the calls to a model with a parallelism limit while passing the definitions to every part, and validate summaries on facts rather than on similarity, routing the doubtful ones to a person. You also know why a metric such as ROUGE-L can reward a summary that omits the penalty. What is missing is what I did not run here: the call to a real model and the evaluation on a sample of your own contracts, which is the only way to know how often the system is wrong on your documents. The next step of the series is about data protection, which weighs on every document sent to an external service.
Frequently asked questions
Can a model summarize a contract without errors?
No, and the possibility of error cannot be ruled out in advance. That is why the summary must be checked on facts (amounts, dates, days, references) and doubtful or high-value cases go to a person. A preregistered study found hallucinations between 17% and 33% in commercial legal research tools.
Why is ROUGE not enough to evaluate a legal summary?
Because it measures the similarity of words to a reference, not the truth of the facts. In the article's example, a summary that omits the penalty scores higher than the faithful one. You need a fact check, in addition to a reviewer's reading.
How do you handle a contract longer than the model's window?
You split on the structure (articles and clauses), summarize each part while also passing the definitions, and reduce with a second pass. The context limit must be read from the documentation of the chosen model, because it changes over time.
Before this article in the series: Smart Contracts for Legal Agreements: Solidity and Vyper.
Sources
- Hallucination-Free? Assessing the Reliability of Leading AI Legal Research Tools - the preregistered study and the 17%-33% hallucination range for the tools evaluated, abstract read on 2026-11-12
- Lost in the Middle: How Language Models Use Long Contexts - the performance degradation when the relevant information is in the middle of the context, abstract read on 2026-11-12
- LoRA: Low-Rank Adaptation of Large Language Models - frozen weights and trainable low-rank matrices, abstract read on 2026-11-12
- ROUGE: A Package for Automatic Evaluation of Summaries - the definition of ROUGE-L on the longest common subsequence, text read on 2026-11-12
- Python: asyncio, synchronization primitives -
asyncio.Semaphore, consulted on 2026-11-12
The three listings marked "Output (executed)" were run with Python 3 and the standard library only; the language model in the map-reduce is a deterministic stand-in and no call to a real model was made. The summaries in the validation example are written by hand. No training was run. An automatic summary of a legal document is not legal advice.
Commenti
Caricamento commenti...
Sign in to comment