Summarization & Transformation Prompts

Ma Mahalakshmi V Updated 19 Sep 2026
9 min read ·Lesson 149 of 224

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

AspectExtractive summarizationAbstractive summarizationStructural transformation
VerifiabilityHigh — substring check against sourceLow — requires semantic reviewMedium — specific facts checkable, phrasing is not
ReadabilityLower, can feel disjointedHigher, natural proseDepends on target format
Hallucination riskVery lowHigherModerate, depends on preserved facts
Best forCompliance, audit trails, legal reviewUser-facing summaries, digestsFormat 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.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Summarization & Transformation Prompts and get answers drawn from it.

Signed-in readers only.