Summarization & Transformation Prompts
Prompt Patterns for Summarization and Transformation
Summarization (condensing content while preserving its important meaning) and transformation (rewriting content into a different form, tone, structure, or language) differ from extraction and classification in a fundamental way: there is no single correct output to check against. Two different summaries of the same article can both be accurate and useful while reading nothing alike. This changes what a well-engineered prompt needs to control — instead of constraining the output to one of a small set of exact values, it needs to constrain length, focus, and fidelity to the source, while leaving wording genuinely open. This lesson covers the patterns that make summarization and transformation prompts reliable in application code.
Why Summarization and Transformation Need Different Controls Than Classification
A classification prompt fails clearly: the output is either a valid category or it isn't. A summarization prompt can fail in much subtler ways that a naive check will not catch — a summary that is well-written but omits the single most important fact, or one that "summarizes" by inventing plausible-sounding details not present in the source (a specific and consequential failure mode usually called hallucination in this context). Because there is no exact string to compare against, the prompt itself has to do more of the work of preventing these failures, since post-hoc validation is harder than it is for extraction's null checks or classification's category matching.
Pattern: Length- and Focus-Constrained Summarization
The baseline summarization pattern controls two things explicitly: how long the output should be, and what it should prioritize. Leaving either open produces summaries of unpredictable length or summaries that focus on whatever the model finds most salient, which may not match what the application actually needs:
from openai import OpenAI
client = OpenAI()
SUMMARY_INSTRUCTIONS = """Summarize the following article in 3-4 sentences.
Focus on the main conclusion and any specific numbers or dates mentioned.
Do not include background information that is not essential to the conclusion.
Do not add any information that is not present in the article."""
def summarize_article(article_text: str) -> str:
response = client.responses.create(
model="gpt-5.6-terra",
instructions=SUMMARY_INSTRUCTIONS,
input=article_text,
)
return response.output_text
The sentence count (3-4 sentences) gives the model a concrete, checkable target instead of a vague instruction like "briefly summarize," which different runs will interpret with different lengths. The focus instruction (main conclusion and any specific numbers or dates) tells the model what to prioritize when it must choose what to cut — every summary is a lossy compression, and without explicit priorities, the model makes that choice implicitly and inconsistently across similar inputs. The final line ("do not add any information not present") is a direct instruction against hallucination; it does not guarantee the model will comply, but omitting it entirely removes even the instruction-level defense against invented content.
Pattern: Extractive vs. Abstractive Summarization
A distinction worth making explicit in the prompt, because it changes what failure looks like and how much you can verify: extractive summarization selects and lightly reassembles sentences taken directly from the source, while abstractive summarization generates new sentences that paraphrase the source's meaning.
EXTRACTIVE_INSTRUCTIONS = """Summarize the article by selecting the 3 most
important sentences verbatim from the text. Do not paraphrase or combine
sentences. Output each selected sentence on its own line, in the order
they appeared in the original text."""
ABSTRACTIVE_INSTRUCTIONS = """Summarize the article in your own words in
2-3 sentences, capturing the main point. You may combine information
from multiple parts of the article into a single sentence."""
Extractive summaries are directly verifiable — application code can check that every output line is an exact substring of the input, the same grounding technique from Lesson 5 — which makes them a strong choice whenever a summary's factual accuracy matters more than its readability, such as a legal or compliance context. Abstractive summaries read better and can synthesize information spread across a document, but they cannot be verified by simple substring matching, and they are the mode more prone to introducing details that were not in the source. Choose extractive when auditability matters most; choose abstractive when readability and synthesis matter most and some review process (human or automated, per Lesson 9) can catch factual drift.
def verify_extractive_summary(summary: str, original_text: str) -> bool:
lines = [line.strip() for line in summary.strip().split("\n") if line.strip()]
return all(line in original_text for line in lines)
Pattern: Structural Transformation
Transformation tasks — converting a bulleted list into prose, rewriting a formal document into plain language, translating between formats such as Markdown and HTML — need the target structure spelled out explicitly, because "rewrite this" alone underspecifies what should and should not change:
TRANSFORM_INSTRUCTIONS = """Rewrite the following technical changelog entry
into a single plain-language sentence suitable for a non-technical user.
Rules:
- Preserve the specific feature name and version number exactly as given.
- Do not use technical jargon (e.g., "API", "endpoint", "schema").
- Do not add marketing language or exclamation points."""
def transform_changelog_entry(entry: str) -> str:
response = client.responses.create(
model="gpt-5.6-terra",
instructions=TRANSFORM_INSTRUCTIONS,
input=entry,
)
return response.output_text
entry = "v2.4.1: Fixed a race condition in the /users endpoint schema validation."
result = transform_changelog_entry(entry)
print(result)
# "Version 2.4.1 fixes a bug that could occasionally cause errors when updating user information."
The rule about preserving the version number exactly is important for a practical reason distinct from readability: version numbers and feature names are exactly the kind of specific, checkable detail that a rewriting task can accidentally drop or alter while otherwise producing fluent, plausible-sounding prose. Naming this constraint explicitly, and ideally verifying it in code ("2.4.1" in result), catches a real failure mode that a purely qualitative read of the output would likely miss.
Pattern: Multi-Step Transformation Pipelines
Some transformations are more reliable when split into a short pipeline of focused prompts rather than one prompt trying to do everything at once — for example, summarizing a long document and then translating the summary, rather than asking for a translated summary directly:
def summarize_then_translate(document: str, target_language: str) -> str:
summary_response = client.responses.create(
model="gpt-5.6-terra",
instructions="Summarize the following document in 2-3 sentences.",
input=document,
)
summary = summary_response.output_text
translate_response = client.responses.create(
model="gpt-5.6-terra",
instructions=f"Translate the following text into {target_language}. "
f"Preserve the meaning exactly; do not add or remove information.",
input=summary,
)
return translate_response.output_text
Splitting into two calls costs additional latency and API usage compared to a single combined prompt, so it is not free — the reason to do it anyway is that each step becomes independently simpler, easier to verify, and easier to reuse. The summarization step can be tested and improved on its own (does it capture the right content), and the translation step can be tested and improved on its own (is it accurate translation), rather than debugging one prompt that is implicitly doing both jobs and where a bad output gives no signal about which half went wrong.
Comparing Summarization and Transformation Approaches
| Aspect | Extractive summarization | Abstractive summarization | Structural transformation |
|---|---|---|---|
| Verifiability | High — substring check against source | Low — requires semantic review | Medium — specific facts checkable, phrasing is not |
| Readability | Lower, can feel disjointed | Higher, natural prose | Depends on target format |
| Hallucination risk | Very low | Higher | Moderate, depends on preserved facts |
| Best for | Compliance, audit trails, legal review | User-facing summaries, digests | Format conversion, tone/audience adaptation |
Handling Length Precisely
Instructions like "3-4 sentences" are usually followed reasonably well but not with hard guarantees — the model may occasionally produce five sentences or a very long single sentence that reads like more content than intended. For applications with a hard length requirement (a UI component with fixed space, an SMS character limit), enforce it in code rather than relying on the instruction alone:
def summarize_with_max_length(article_text: str, max_chars: int = 280) -> str:
response = client.responses.create(
model="gpt-5.6-terra",
instructions=(
f"Summarize the following article in one sentence, "
f"under {max_chars} characters."
),
input=article_text,
)
summary = response.output_text.strip()
if len(summary) > max_chars:
summary = summary[: max_chars - 1].rsplit(" ", 1)[0] + "…"
return summary
The instruction states the target so the model produces a reasonably close result most of the time, and the code afterward enforces the hard limit as a guaranteed fallback rather than a hope. This combination — a clear instruction plus a deterministic code-level backstop — is the general pattern for any requirement where "usually correct" is not good enough, and it applies just as well to the length, format, and field-presence requirements covered in Lesson 7.
Testing Summarization and Transformation Logic
The verifiable parts — length enforcement, extractive grounding, fact preservation — can be tested with fake model output, exactly as in earlier lessons:
def test_max_length_truncation_respects_limit():
long_summary = "word " * 100
result = long_summary.strip()
if len(result) > 20:
result = result[:19].rsplit(" ", 1)[0] + "…"
assert len(result) <= 20
print("PASS: truncated summary respects character limit")
def test_extractive_summary_verifies_against_source():
original = "The system failed at noon. Engineers restored service by 1pm. No data was lost."
good_summary = "The system failed at noon.\nEngineers restored service by 1pm."
bad_summary = "The system failed at noon.\nThe outage lasted three hours."
assert verify_extractive_summary(good_summary, original) is True
assert verify_extractive_summary(bad_summary, original) is False
print("PASS: extractive verification distinguishes grounded from fabricated summaries")
test_max_length_truncation_respects_limit()
test_extractive_summary_verifies_against_source()
Common Mistakes
Leaving summary length unconstrained. An instruction to "summarize" without a target length or sentence count produces inconsistent output length across similar inputs, which is disruptive for any UI or downstream process expecting roughly uniform output size.
Not distinguishing extractive from abstractive needs before writing the prompt. Asking for an abstractive-style summary ("in your own words") for a use case that actually needs auditability produces output that cannot be verified against the source, discovered only after it's already in production.
Combining too many transformation steps into a single prompt. A prompt asked to summarize, translate, and reformat all at once is harder to debug when the output is wrong, because there is no way to tell which of the three steps introduced the problem without decomposing it into separate calls.
Best Practices
State an explicit length or size target, and enforce a hard limit in code when one is required. Treat the prompt instruction as a strong hint and the code-level check as the guarantee for any hard constraint.
Choose extractive summarization when factual auditability matters more than fluency. Extractive output can be mechanically verified against the source; abstractive output requires a review process to catch drift.
Decompose multi-step transformations into separate, independently testable prompts. Each step becomes easier to verify, debug, and improve on its own, at the cost of additional latency and API calls that should be weighed against the reliability gain.