Apply to my task
arXiv:2606.12897 ★ 85 Jun 11, 2026

SafeLLM (Extraction over Rewriting): Line Numbering as a Shield Against Hallucinations When Working with Documents

Key result

Ask an LLM "tell me what's in the contract" and it won't quote. It composes a plausible retelling, quietly blending the document with what it knows from training. In legal and medical texts, that's a silent disaster. The SafeLLM method lets you get answers strictly from the document — without a single word added by the model. The trick: number the lines — ask for numbers only. You assemble the text from the original yourself; the LLM physically can't add anything. The result — 95% accuracy on medical documents instead of a hallucinating retelling.

01

TL;DR

Extraction over Rewriting is a principle where, instead of asking an LLM to retell a document, you ask it to pick lines from it. The concrete technique: number the document's lines, paste them into the chat, ask your question — and the model returns only line numbers. You assemble the answer from the original yourself. No generation — just selection.

The main pain point: when you paste in a contract or a manual and ask "what does it say about returns?", the model doesn't copy — it paraphrases. In the process it blends the document's text with knowledge from its training. The result: an answer that looks plausible but may contain details that aren't in the document. For everyday questions — no big deal. For legal, medical or financial ones — a real risk.

The researchers proposed four strategies that tackle this step by step: from "copy verbatim" to "give me only the line numbers, I'll assemble it myself." The LINES strategy delivered the best results — it physically rules out generation: the model doesn't write the answer text, it outputs numbers.

Want this for your own case? Apply this study to your task: AI adapts its method to what you are working on and writes the prompt.

02

Method Blueprint

All four strategies — from simple to complex:

STRATEGY 1 — COPY (Verbatim copying)
  Prompt: Copy verbatim the sentences that answer the question.
  Ban: don't paraphrase, don't add anything of your own.
  → Output: a set of sentences from the document

STRATEGY 2 — LINES (Line selection) ← BEST RESULT
  STEP 1: Number every line of the document (1, 2, 3...)
  STEP 2: The LLM picks the minimal set of line numbers
  STEP 3: You pull those lines from the original by hand
  → Output: a list of numbers (e.g., 4, 17, 23, 31)
  → Guarantee: the answer contains only original text, not a word from the model

STRATEGY 3 — SAFETY (Extraction with role labels)
  The LLM copies sentences + tags each one with a label:
    - answers_question (answers directly)
    - adds_required_detail (clarifies)
    - safety_critical (critical, must not be skipped)
  → Output: a labeled list of sentences from the document

STRATEGY 4 — JUNIOR (Two-agent workflow)
  AGENT 1: answers the question from memory, without the document
           → a draft answer with specifics (thresholds, numbers, steps)
  AGENT 2: compares the draft against the document
           → copies sentences that support, refine
           or correct the draft
  → Output: verified lines from the source

All four strategies work in a single chat — no code, just prompt structure.

03

Example in Action

The task: You sell products on Amazon. You want to know what happens if your product is damaged in shipping — who's liable and what the deadline is for filing a claim. The seller agreement runs 47 pages and you don't have time to read it.

Prompt (LINES strategy — two steps):

STEP 1 — send this message:

Number every line of the following text.  
Format: [number] line text  
Each line gets its own number, even if it's a single word.

[paste the section of the agreement about liability and shipping]

---

STEP 2 — once you have the numbered text, send:

Here is the numbered text of the agreement. 
Question: who is liable for damage to goods during shipping, 
and what is the deadline for filing a claim?

Rules:
- Return ONLY the numbers of the lines that answer the question
- The minimum necessary set — no more
- No explanations, no text of your own
- Format: a comma-separated list of numbers

[paste the numbered text from step 1]

Result:

The model will return something like: 12, 13, 34, 35, 36, 51. You open the numbered text from step one, copy out those lines — and get the exact answer from the agreement. Word for word. No one else's words.

If you use the SAFETY strategy, you'll also see labels: which lines answer directly, which add detail, and which are flagged as "must not skip." Handy for checking important terms.

04

Why It Works

An LLM is a next-word predictor, not a photocopier. When you ask "tell me what it says," the model generates text that is probably right. It doesn't quote — it composes a plausible continuation. Even with the document right in front of it, the model "blends" it with what it knows from training. That's the hallucination: not an invention from scratch, but an invisible blend.

LLMs are good at classifying and matching. Saying "here are 100 lines, which ones answer the question?" is a fundamentally different task from "write an answer." In the first case the model chooses from what's already there. In the second, it generates. Choosing is more accurate.

LINES closes the gap completely: the model returns only numbers. The text is assembled from the original mechanically — the LLM physically can't add a single word of its own. That's not a quality limitation — it's a guarantee of accuracy. The study showed up to 95% agreement with correct answers on medical terms.

Control levers: - COPY strictness → add "if unsure, leave it out" to raise precision, at the cost of some misses - Chunk size in LINES → if the document is long, first ask it to pick a section, then the lines within it - Roles in SAFETY → add your own label, e.g. must_read_before_signing for legal terms - Agents in JUNIOR → give Agent 1 a specific role (lawyer, accountant) for a sharper draft

05

Prompt Template

COPY strategy — quick start:

Below is a document. Answer the question using ONLY verbatim 
sentences from the document.

Rules:
- Copy whole sentences without changes
- Don't paraphrase, don't summarize, don't add context of your own
- If a needed sentence is long, copy it in full
- If the answer isn't in the text, write "not found in the document"

Question: {your question}

Document:
{paste the document text}

LINES strategy — maximum accuracy:

TEMPLATE (two requests):

── REQUEST 1 ──
Number every line of the text below.
Numbering format: [N] line text
Number every line, including short ones.

{paste the document or section text}

── REQUEST 2 (after you get the numbered text) ──
Here is the numbered text.
Question: {your question}

Instructions:
- Return only the numbers of the lines needed to answer
- Pick the minimal sufficient set
- No text of your own — numbers only
- Format: comma-separated numbers

{paste the numbered text from request 1}

SAFETY strategy — with importance labels:

Below are a document and a question. Pick the minimal set of sentences 
that answer the question and contain important conditions.

For each sentence, state its role:
- answers_question — directly answers the question
- adds_required_detail — a necessary clarification
- critical — must not be skipped; an important condition or restriction

Rules:
- Copy sentences verbatim, without changes
- Keep the original order
- Don't add words of your own — only labeled quotes

Output format:
[role] "sentence from the document"

Question: {your question}

Document:
{paste the text}

Placeholders: - {your question} — a specific question about the document - {paste the document text} — the copied text (contract, policy, manual)


🚀 Quick start — paste into the chat:

I have a document and I want an exact answer without the model 
rewording anything. Help me adapt one of the SafeLLM templates 
to my task: {describe the task}.

Ask me clarifying questions.

[paste the template above]

The LLM will ask what document and what question — because the strategy depends on the task type: LINES is best for legal precision, SAFETY for understanding structure, COPY for quick lookups.

06

Limitations

⚠️ Document length: LINES works worse on very long, structurally uneven documents (narrative text rather than protocols). The more "free-form" the document's language, the lower the accuracy of line selection.

⚠️ Context window: A numbered document takes up more tokens than the original. For very long documents (10,000+ words), split them into parts first and query section by section.

⚠️ Synthesis questions: If a question requires combining information from different parts of the document ("compare conditions X and Y"), LINES gives an incomplete result. It selects lines; it doesn't build connections between them.

⚠️ The SAFETY strategy cuts completeness: The "minimal set" requirement makes the model skip important details. In almost all models, Safety gives higher precision but more misses than LINES.

⚠️ The numbering step is manual: If you have a PDF or a scan, you need to copy the text first. Tables and visual elements don't carry over — text only.

07

How They Studied It

A team from UCL and the NHS took three types of clinical documents: short acute-care protocols (UCLH, ~750 words), mid-length oncology guidelines (Somerset, ~3,150 words) and national NICE guidelines (~5,200 words). A 7x spread in length — which matters a lot, because different strategies behave differently depending on the structure of the text.

Each document was tested with 50–500 questions. The four strategies (COPY, LINES, SAFETY, JUNIOR) were compared against baseline RAG (semantic search over chunks). They measured not only word-level accuracy but also accuracy on medical terms — because errors in terms are what's dangerous (dose, contraindication, escalation threshold). In parallel, three clinical experts rated the answers manually on "relevant" and "complete."

The surprise: LINES beat SAFETY even in scenarios Safety was specifically designed for. The reason is simple: the requirement "pick only the critical sentences" forces the model to make judgment calls about what matters — and it gets them wrong. LINES makes no such calls at all: pick the lines, reproduce them verbatim, done. Fewer model decisions = fewer model mistakes.

08

Original from the Paper

From the strategy descriptions (the original has the verbatim prompts in Listings 3-6):

LINES strategy (description):

The guideline text is augmented with line numbers and provided to 
the model together with the user question. The model is then tasked 
with identifying the minimal set of line numbers required to answer 
the question. The final answer is reconstructed deterministically 
by retrieving the corresponding guideline lines in post-processing. 
This approach enforces tighter control over the extracted content 
and guarantees the absence of hallucinated text, as the output 
consists exclusively of selected guideline line numbers.

SAFETY strategy (description):

The model is prompted to select the smallest subset of full sentences 
that (i) directly answer the question and (ii) include any 
safety-critical information. Each selected sentence is annotated with 
a single reason label indicating its role in the response: 
answers_question, adds_required_detail, or safety_critical. 
Sentences must be copied verbatim from the guideline, paraphrasing 
is not allowed, and the original order must be preserved.

Context: Strategy descriptions from the Methods section. The listings with the exact prompts (Listings 3–6) are in the original but weren't included in the excerpt of the paper we had.

09

Adaptations and Extrapolations

💡 Adaptation: LINES for legal documents

Same mechanics, different context — reviewing a contract before signing:

REQUEST 1:
Number every line of this contract. Format: [N] line text.

[contract text]

REQUEST 2:
Here is the numbered contract.
Questions:
1. What conditions allow either party to terminate the contract unilaterally?
2. What is the penalty for late payment?
3. Is there an automatic renewal?

Return only the line numbers for each question.
Format:
Question 1: [numbers]
Question 2: [numbers]  
Question 3: [numbers]

[numbered text]

🔧 Technique: SAFETY with custom labels → prioritizing terms

What changes: standard roles (answers_question / safety_critical) → labels tailored to your task.

Effect: the model categorizes by your logic, not a generic one.

Annotation rules for a lease agreement:
- deal_breaker — a term that means the lease must not be signed
- negotiate — can be discussed with the landlord  
- ok — a standard term, accept as is
- unclear — needs a lawyer's advice

🔧 Technique: JUNIOR for analyzing complex regulations

What changes: Agent 1 answers "off the top of its head" → surfaces discrepancies with the document.

Useful when you need to understand what changed in a new version of the rules:

AGENT 1: In your view, how do product returns on online 
marketplaces work under the general rules? Be specific: deadlines, who 
pays the costs, valid grounds.

AGENT 2: Here is the official document. Find the sentences that 
confirm, refine or CONTRADICT Agent 1's answer. 
Copy them verbatim. Mark contradictions: [DISCREPANCY].

[paste the document]

This works especially well for uncovering "non-obvious" terms — the ones people usually miss.

10

Resources

Paper title: SafeLLM: Extraction as a Hallucination-Resistant Alternative to Rewriting in Safety-Critical Settings

Authors: Julia Ive, Felix Jozsa, Evridiki Georgaki, Nabeel Sheikh, Emma Cattell, Nick Jackson, Paulina Bondaronek, Ciaran Scott Hill, Richard Dobson

Institutions: Institute of Health Informatics, University College London; National Hospital for Neurology and Neurosurgery (Queen Square); Somerset NHS Foundation Trust; King's College Hospital; King's College London

Research digest

Key result

Ask an LLM "tell me what's in the contract" and it won't quote. It composes a plausible retelling, quietly blending the document with what it knows from training. In legal and medical texts, that's a silent disaster. The SafeLLM method lets you get answers strictly from the document — without a single word added by the model. The trick: number the lines — ask for numbers only. You assemble the text from the original yourself; the LLM physically can't add anything. The result — 95% accuracy on medical documents instead of a hallucinating retelling.

Principle

Two tasks look similar but work differently under the hood. "Write an answer based on the document" is generation: the model predicts tokens, mixing the source with memory from training. "Pick the lines that answer" is classification: the model sorts what's already there into "fits / doesn't fit." Classification is more accurate than generation — that's not an opinion, it's the difference in the underlying task. The LINES strategy takes the principle to its limit: the model returns only numbers, and the text is assembled mechanically. Not a single word from the model ends up in the final answer.

Why it works

An LLM is a next-word predictor, not a photocopier. When generating, it follows probability — if something similar showed up in training, it'll leak into the answer. This isn't invention from scratch but an invisible blending of two sources. That's why the answer looks convincing but isn't identical to the document. With line selection the task is different: there's a list, there's a criterion, you match them. The model isn't composing — it's looking for a match. Much harder to get wrong.

When to apply

Legal and financial documents — contracts, return policies, terms of service, where one extra word distorts the meaning. Medical instructions and protocols — especially when dosages, contraindications and timelines matter. Internal company policies — when you need exactly what's written, not an interpretation. NOT suitable for synthesis questions — "compare condition X and Y from different parts of the document": the method selects lines but doesn't build connections between them. Works poorly on very long narrative texts — split them into sections and query piece by piece.

Mini recipe

1. Quick start with copying (COPY): Add to the start of the prompt: "Copy sentences verbatim without changes. Don't paraphrase. If there's no answer, write not found in the document." Paste the document, ask your question. 2. Maximum accuracy (LINES) — two requests: In the first request, number every line of the document — format: [N] line text. In the second, ask the question and request only comma-separated numbers, with no explanations or text of its own. 3. With importance labels (SAFETY): Ask it to copy sentences and tag each with a role: answers_question / adds_required_detail / critical. Handy for contract reviews — you instantly see what can't be skipped. 4. Assemble the answer by hand: For LINES — take the numbered text from the first request and copy out the lines by the numbers you got. That's not an inconvenience — it's the whole point. You control the final text; the model didn't add a word.

Examples

[BAD]: `What does the contract say about product returns?` [GOOD]: Step 1: `Number every line of the text. Format: [N] line text. Each line gets its own number. [paste the contract section]` → Step 2: `Question: what are the deadline and conditions for returns? Return only the line numbers. No text of your own — just comma-separated numbers. [paste the numbered text from step 1]`

In plain words

The core problem is that any LLM, by its very nature, isn't a scanner — it's a professional storyteller. When you ask a model to retell a document, it doesn't copy the facts; it generates the most probable sequence of words. That's when blending hallucination kicks in: the model takes a piece of your text and quietly mixes in knowledge from the internet it was trained on. You end up with an answer that looks logical but contains a critical screwup, because the model decided to "fill in" details on the author's behalf.

It's like asking your gossipy neighbor to summarize the terms of your mortgage. He sort of read the paperwork, but while telling you about it he'll inevitably add something of his own, mix up the interest rates or invent some penalties, simply because "that's what they all say." In legal or medical matters, that kind of "creative interpretation" is a total fail that can cost you money or your health.

To avoid playing a game of telephone, the researchers propose the SafeLLM method, where retelling is replaced with pure extraction. You number every line in the document and ask the model not to write a single word of its own, just to output the numbers of the lines that contain the answer. The model works like a librarian's pointer: it simply taps the right spots in the original, and you assemble the answer from those pieces yourself. No generation — just selection from the primary source.

The method was put through four strategies: from simple line picking to a more elaborate check where the model first explains its choice and then outputs the numbers. But the principle is the same everywhere — no free-form writing allowed. It works anywhere the cost of a mistake is too high: reviewing 50-page contracts, analyzing medical protocols, or digging up the return terms on an online marketplace. You take away the model's ability to lie, turning it from a chatty advisor into a high-precision search filter.

Bottom line: forget prompts like "give me a quick summary" when real obligations are on the line. If you want the truth, make the model work in Extraction over Rewriting mode. It's the only way to guarantee you're reading the terms of your contract and not the model's fantasy about what that contract might look like. Hallucinations are cured only by tightly restricting the freedom to choose words.

AI lab assistant

Apply this study to your task

Describe what you're working on. AI takes the method and the measured results from this paper and adapts them to your case, or writes a ready prompt built on them.

Based on SafeLLM (Extraction over Rewriting): Line Numbering as a Shield Against Hallucinations When Working with Documents arXiv:2606.12897

Sign in to apply this study New accounts get 50 free credits.