Sub topic 5
Summarizing, rewriting, translating, and drafting
This chapter covers the four text-to-text tasks that most LLM products start with. It assumes you can call a model through a complete(prompt) function, as in the earlier chapters on prompting. It also assumes you know that a model has a limited context window and can produce wrong statements with confidence.
What these tasks have in common
In summarizing, rewriting, translating, and drafting, the model transforms or produces text. Summarizing, rewriting, and translating are grounded in a source text you supply. Drafting often starts from a short brief and has little grounding.
That difference decides where the risk sits:
| Task | Input | Main risk | Typical check |
|---|---|---|---|
| Summarizing | Long source text | Dropped key points, invented details | Compare against the source |
| Rewriting | Text plus a style goal | Meaning drift, lost facts | Compare facts before and after |
| Translating | Text plus target language | Mistranslated terms, tone shifts | Glossary check, bilingual review |
| Drafting | Brief or notes | Unsupported claims, generic tone | Human review before sending |
The more the output must stay faithful to a source, the more you should constrain the prompt and verify the result.
Summarizing
A summary is only useful relative to a purpose. "Summarize this" gives you a generic result. Name the reader, the length, and what matters.
def summarize(text: str, complete, audience: str = "an engineering manager",
max_sentences: int = 3) -> str:
prompt = (
f"Summarize the text below for {audience}.\n"
f"Use at most {max_sentences} sentences.\n"
"Include decisions and deadlines. Use only facts stated in the text.\n"
"If the text does not contain enough information, say so.\n\n"
"Text:\n" + text
)
return complete(prompt).strip()The line "use only facts stated in the text" reduces invented detail. It does not eliminate it, so you still need checks.
Extractive and abstractive summaries
An extractive summary selects sentences from the source. An abstractive summary writes new sentences. Models produce abstractive summaries by default. If you need exact quotes, such as in legal or compliance settings, ask for quoted sentences and then verify that each quote appears in the source.
def quotes_are_verbatim(quotes: list[str], source: str) -> bool:
return all(q in source for q in quotes)
source = "The audit finished on 3 May. Two findings remain open."
print(quotes_are_verbatim(["Two findings remain open."], source))
print(quotes_are_verbatim(["Three findings remain open."], source))Long documents
A document longer than the context window cannot be summarized in one call. Even when it fits, quality often drops for details buried in the middle. The common fix is map-reduce summarization:
- Split the document into chunks, ideally at section or paragraph boundaries.
- Summarize each chunk separately (the map step).
- Summarize the combined chunk summaries (the reduce step).
def chunk(text: str, max_chars: int = 4000) -> list[str]:
parts, current = [], ""
for para in text.split("\n\n"):
if current and len(current) + len(para) > max_chars:
parts.append(current)
current = ""
current += para + "\n\n"
if current.strip():
parts.append(current)
return parts
def summarize_long(text: str, complete) -> str:
partials = [summarize(c, complete, max_sentences=4) for c in chunk(text)]
return summarize("\n".join(partials), complete, max_sentences=5)The chunk function counts characters because it is simple. Production code should count tokens with the tokenizer of your model. A single paragraph longer than max_chars becomes its own oversized chunk, which is an edge case to handle if your documents contain long unbroken text.
Each reduce step compounds errors. A fact dropped in the map step cannot return in the reduce step.
Rewriting
Rewriting changes form while keeping meaning: tone, reading level, length, or format. The key instruction is what must not change.
def rewrite(text: str, complete, style: str) -> str:
prompt = (
f"Rewrite the text below in this style: {style}.\n"
"Keep every number, name, date, and commitment unchanged.\n"
"Do not add new information. Return only the rewritten text.\n\n"
"Text:\n" + text
)
return complete(prompt).strip()Common failures:
- Meaning drift. "We may refund you" becomes "We will refund you" when the model polishes the tone.
- Changed numbers. Rounding or reformatting alters a value.
- Extra framing. The reply begins with "Sure, here is the rewrite:". The line "Return only the rewritten text" reduces this, but strip such prefixes if you cannot tolerate them.
A cheap automated check extracts numbers from both versions and compares them:
import re
def numbers(text: str) -> list[str]:
return sorted(re.findall(r"\d+(?:[.,]\d+)?", text))
def numbers_preserved(before: str, after: str) -> bool:
return numbers(before) == numbers(after)
print(numbers_preserved("Pay 40 EUR by 12 June.", "Please pay 40 EUR by 12 June."))
print(numbers_preserved("Pay 40 EUR by 12 June.", "Please pay 45 EUR by 12 June."))This check fails for spelled-out numbers and for translations that change digit formats, so use it on same-language rewrites.
Translating
Models translate well between widely used languages and less reliably for rare ones. Quality depends on the language pair, the domain, and the amount of context you give.
Specify the following in the prompt:
- The source and target language, and the regional variant if it matters (for example Brazilian or European Portuguese).
- The register, such as formal or informal address.
- Terms that must not be translated, such as product names.
- A glossary of required translations.
def translate(text: str, complete, target: str, glossary: dict[str, str]) -> str:
terms = "\n".join(f"- {src} -> {dst}" for src, dst in glossary.items())
prompt = (
f"Translate the text into {target}.\n"
"Use these fixed translations for these terms:\n" + terms + "\n"
"Keep placeholders such as {name} unchanged. Return only the translation.\n\n"
"Text:\n" + text
)
return complete(prompt).strip()Placeholders and markup are a frequent source of bugs. A model may translate {name}, drop a tag, or reorder variables. Verify that every placeholder in the source appears exactly once in the output:
import re
def placeholders_ok(source: str, translated: str) -> bool:
pattern = r"\{[a-z_]+\}"
return sorted(re.findall(pattern, source)) == sorted(re.findall(pattern, translated))A useful test is back-translation: translate the result back to the original language and compare. It catches gross errors but can hide subtle ones, because both directions may share the same mistake. For text with legal, medical, or safety consequences, have a qualified human review it.
Drafting
Drafting produces new text from a brief: an email reply, a product description, a status report. Because there is less source material, the model fills gaps with plausible content. Give it facts, and tell it what to do when facts are missing.
def draft_reply(ticket: str, facts: list[str], complete) -> str:
fact_lines = "\n".join(f"- {f}" for f in facts)
prompt = (
"Draft a polite, concise reply to the customer message below.\n"
"Use only these facts:\n" + fact_lines + "\n"
"Do not promise refunds, dates, or actions not listed above.\n"
"If the message asks for something the facts do not cover, "
"say that you will check and follow up.\n\n"
"Customer message:\n" + ticket
)
return complete(prompt).strip()Treat the output as a draft. For customer-facing text, the safest design keeps a person between the model and the send button until you have measured how often drafts are acceptable.
Choosing settings and style controls
- Temperature. Use a low value for summarizing, rewriting, and translating, where fidelity matters. A moderate value suits drafting where variety helps. Even low settings do not guarantee identical output across calls.
- Examples. One or two sample outputs in the prompt fix tone and format better than adjectives do.
- Length. Models follow word counts only approximately. Ask for a sentence or bullet count, and truncate or retry if you need a hard limit.
- Format. State the output format, such as "three bullet points", and parse it if code depends on it.
Evaluating text tasks
There is rarely one correct answer, so build a small set of representative inputs and check properties:
- Faithfulness: every claim appears in the source.
- Coverage: required points are present.
- Constraints: length, format, language, placeholders.
- Tone: judged by a reviewer against a short rubric.
Automate the mechanical checks, as shown above, and sample the rest for human review. When you change the prompt or model, rerun the same set and compare.
Common errors summary
- Asking for a summary with no audience or length.
- Sending text longer than the context window and letting it be cut off silently.
- Trusting a rewrite to keep numbers and hedges intact.
- Skipping glossaries and placeholder checks in translation.
- Sending drafts to customers without review.
Exercise
You summarize a 60-page report with map-reduce. The final summary omits a deadline that appears once on page 41. Name two places where the deadline could have been lost and one change that reduces the risk.
Show answer
The deadline could have been lost in the map step, when the chunk summary for page 41 judged it unimportant, or in the reduce step, when the combined summaries were compressed further. Reduce the risk by telling the prompt to always keep dates, deadlines, and decisions in both steps, and by running a check that searches the source for dates and confirms each appears in the final summary.
Exercise
A translation prompt returns "Bonjour {nom}" for the source "Hello {name}". Which function from this chapter catches the problem, and what does it return?
Show answer
placeholders_ok catches it. The source contains {name} and the translation contains {nom}, so the sorted lists differ and the function returns False.