Using Output Indicators and Response Formats
What Is an Output Indicator? An output indicator is the part of a prompt that tells the model what the response should look like, or marks exactly where the response should begin.
In simple terms, the instruction tells the model what to do; the output indicator tells it what the finished result should look like.
The term covers two related techniques:
Technique What It Does Example Format specification Describes the shape of the response Respond as a numbered list of 5 items. Output cue (prefix) Ends the prompt with the start of the expected answer Answer: or Category: Both work for the same reason explained in Lesson 2: the model predicts what comes next. A clear description of the expected shape, or the first part of that shape, makes responses with that shape far more likely.
Example Without an output indicator:
What are the benefits of using a virtual environment in Python? The model may answer in paragraphs, bullet points, or a mix, at any length.
With an output indicator:
What are the benefits of using a virtual environment in Python? List exactly 3 benefits. Write each as one line in the format: : Possible output:
Dependency isolation: Each project keeps its own package versions without affecting other projects. Reproducibility: The exact dependencies can be recorded and recreated on another machine. Clean system Python: Packages are installed inside the environment instead of the global Python installation. Example Explanation exactly 3 controls the count. one line controls the length of each item. : is a pattern the model can copy precisely. The content is the same kind of information either way. The output indicator controls only its shape, and that shape decides whether the response is easy to use.
Why Response Format Matters For Human Readers The right format makes information faster to understand:
Steps belong in a numbered list, because order matters. Comparisons belong in a table, because readers scan across columns. Explanations belong in paragraphs, because ideas connect to each other. Short answers belong on one line, because anything more wastes the reader's time. For Programs When code processes the response, format is not a preference; it is a requirement. A program that expects one word cannot handle a paragraph. A program that expects JSON fails when the response begins with "Sure! Here is the JSON you asked for:".
Response Consumer Typical Format Needed A person reading a chat Readable prose or Markdown A web page that renders Markdown Markdown with headings and lists An SMS or plain-text email Plain text without Markdown symbols Code that branches on the result One exact label from a fixed set Code that stores fields in a database JSON with defined keys and types A spreadsheet import CSV with fixed columns What Happens Without Format Control Inconsistent length: the same prompt produces 2 sentences one time and 6 paragraphs the next. Unwanted extras: introductions ("Great question!"), closing offers ("Let me know if you need more help"), and disclaimers. Wrong rendering: Markdown symbols such as ** and # appear as raw characters in plain-text channels. Broken automation: parsing code fails on unexpected text. Technique 1: Output Cues (Prefixes) An output cue is a label placed at the very end of the prompt, which the model continues from.
Extract the city from the address.
Address: 14, Gandhi Street, T. Nagar, Chennai 600017
City: Expected output:
Chennai Why It Works Ending with City: makes the city name the most natural next text. It also discourages extra sentences, because the label signals that a short value fills this slot.
Multiple Cues as a Template Read the job posting and fill in the fields.
Posting: "We are hiring a Junior Django Developer in Bengaluru. Hybrid work. 0-2 years of experience. Apply by 15 November."
Job title: Location: Work mode: Experience required: Application deadline: Expected output:
Job title: Junior Django Developer Location: Bengaluru Work mode: Hybrid Experience required: 0-2 years Application deadline: 15 November The model fills each label in order. Templates like this are among the simplest and most reliable ways to obtain structured output.
Technique 2: Describing the Format For more complex structures, describe the format explicitly.
Lists List the steps to create a Django project. Use a numbered list. Start each step with a verb. Put any command in a code block. Tables Compare SQLite, MySQL, and PostgreSQL for a small Django project. Respond with a Markdown table with these columns: Database | Setup Effort | Best For | Main Limitation Keep each cell under 10 words. Paragraphs Explain what caching is in exactly two paragraphs: the first explains the concept with an everyday analogy, the second explains how websites use it. Plain Text Write the reply as plain text for an SMS. Do not use Markdown, bullet symbols, or emojis. Maximum 300 characters. Why Specific Descriptions Work Better "Make it a table" leaves the columns undefined. "A Markdown table with columns Database | Setup Effort | Best For | Main Limitation" defines the exact structure, so every row contains comparable information.
Technique 3: Restricting the Allowed Values When code branches on the response, restrict the answer to a fixed set of values.
Classify the urgency of the support ticket. Reply with exactly one of these words and nothing else: LOW, MEDIUM, HIGH
Ticket: "Our online store checkout has been down for an hour." Expected output:
HIGH Explanation exactly one of these words defines the set. and nothing else prevents explanations around the label. Uppercase labels are easy to distinguish from normal words in a sentence, which reduces accidental partial matches in code. Always Validate in Code Even with clear instructions, a model can occasionally return something outside the set, such as High. with a period. Normalize and check the response:
ALLOWED = {"LOW", "MEDIUM", "HIGH"}
def parse_urgency(raw: str) -> str: value = raw.strip().strip(".").upper() if value not in ALLOWED: raise ValueError(f"Unexpected urgency value: {raw!r}") return value Explanation: strip() removes whitespace and newlines, strip(".") removes a trailing period, and upper() normalizes case. Anything still outside ALLOWED raises an error instead of silently entering your system with a wrong value.
Technique 4: Controlling Length Length controls are output indicators too.
Control Example Precision Item count List 5 tips. High Sentence count Answer in 2 sentences. High Paragraph count Write 3 short paragraphs. High Word count Under 100 words. Approximate Character count Under 160 characters. Approximate Models process tokens, not words or characters (Lesson 2), so word and character limits are followed approximately. Counts of items, sentences, and paragraphs are easier for the model to respect exactly. When a strict character limit matters, such as for an SEO meta description or an SMS, check the length in code:
def fits_limit(text: str, max_chars: int = 160) -> bool: return len(text) <= max_chars If the check fails, you can send a follow-up request asking the model to shorten the text, or reject the result.
Technique 5: JSON Output JSON is the most common format when a program needs several fields from one response.
Basic JSON Prompt Extract information from the course description below.
Return only a JSON object with these keys:
- "title": string
- "difficulty": one of "Beginner", "Intermediate", "Advanced"
- "topics": array of strings
- "duration_weeks": integer, or null if not stated
Learn React from scratch in this beginner-friendly course. You will cover components, props, state, and hooks while building three small projects. Possible output:
{ "title": "React from Scratch", "difficulty": "Beginner", "topics": ["components", "props", "state", "hooks"], "duration_weeks": null } Example Explanation Each key is listed with its type, so the model knows topics is an array and duration_weeks is a number. difficulty has an allowed set of values, the same technique as for labels. or null if not stated defines behavior for missing information. The description does not state a duration, so the model returns null instead of inventing a number. title was not stated explicitly either. The model created a reasonable title from the text. If you need only titles that are written in the input, say so, for example: "Use null if no title is stated." Parsing and Validating JSON in Python Models sometimes wrap JSON in a Markdown code fence or add a sentence before it. Robust code handles this and validates the result.
import json import re
ALLOWED_DIFFICULTY = {"Beginner", "Intermediate", "Advanced"}
def extract_json(text: str) -> dict: """Parse a JSON object from model output, removing a code fence if present.""" cleaned = text.strip() fence = re.match(r"^(?:json)?\s*(.*?)\s*$", cleaned, re.DOTALL) if fence: cleaned = fence.group(1) return json.loads(cleaned)
def validate_course(data: dict) -> list[str]: """Return a list of validation errors; an empty list means the data is valid.""" errors = [] if not isinstance(data.get("title"), str): errors.append("title must be a string") if data.get("difficulty") not in ALLOWED_DIFFICULTY: errors.append(f"difficulty must be one of {sorted(ALLOWED_DIFFICULTY)}") topics = data.get("topics") if not isinstance(topics, list) or not all(isinstance(t, str) for t in topics): errors.append("topics must be a list of strings") duration = data.get("duration_weeks") if duration is not None and not isinstance(duration, int): errors.append("duration_weeks must be an integer or null") return errors
raw_output = """`json {"title": "React from Scratch", "difficulty": "Beginner", "topics": ["components", "props", "state", "hooks"], "duration_weeks": null}
course = extract_json(raw_output)
problems = validate_course(course)
if problems:
print("Invalid:", problems)
else:
print("Valid:", course)
Output:
Valid: {'title': 'React from Scratch', 'difficulty': 'Beginner', 'topics': ['components', 'props', 'state', 'hooks'], 'duration_weeks': None}
Code Explanation
extract_json
text.strip() removes surrounding whitespace.
The regular expression checks whether the whole response is wrapped in a code fence, with an optional json language tag. re.DOTALL lets . match newlines so multi-line JSON is captured.
If a fence is found, only the content inside it is kept.
json.loads converts the JSON text into a Python dictionary and raises json.JSONDecodeError if the text is not valid JSON. JSON null becomes Python None.
validate_course
Checks every field's type and allowed values and collects all errors instead of stopping at the first one, which makes debugging prompts easier.
Uses data.get(...) so a missing key is reported as an error rather than raising a KeyError.
Why validation is necessary: Valid JSON is not necessarily correct JSON. The response might parse successfully but contain "difficulty": "Easy", a value your application does not support.
Note: Prompt instructions make JSON likely, not guaranteed. Many APIs, including OpenAI's, provide structured output features that constrain the model to a JSON schema. These are covered in Lesson 99. Use them for production systems, and keep validation in place anyway.
Technique 6: Removing Unwanted Extras
Chat models often add text around the answer, such as introductions, summaries, and offers of further help. Remove these explicitly when they are not wanted.
Write a product title for the item below.
Return only the title. Do not include quotation marks, explanations,
or any text before or after it.
Why This Is Needed
Instruction-tuned models have learned conversational habits from their training (Lesson 2). These habits are helpful in chat but harmful in automation. Stating "return only..." together with the specific extras to omit is more reliable than "be concise".
Technique 7: Showing an Example of the Output
When a format is complex or unusual, an example is clearer than a description.
Convert each course into a single-line catalog entry.
Example:
Input: Python Basics, 4 weeks, Beginner, ₹1,999
Output: [BEGINNER] Python Basics — 4 weeks — ₹1,999
Now convert:
Input: Advanced Django, 6 weeks, Advanced, ₹4,999
Output:
Expected output:
[ADVANCED] Advanced Django — 6 weeks — ₹4,999
Example Explanation
Describing this format in words requires several rules: uppercase level in square brackets, em dashes as separators, a specific field order. The single example communicates all of them at once. The final Output: cue tells the model exactly where to write. This combination of examples and cues is the basis of few-shot prompting, covered in Lesson 26.
Choosing the Right Format
Content Recommended Format Why
A single fact or decision One line or one word Anything longer hides the answer
Sequential steps Numbered list Order matters
Independent points Bullet list Easy to scan
Comparison across attributes Table Readers compare columns
Explanation of a concept Short paragraphs Ideas connect to each other
Code Code block with language tag Preserves whitespace and enables highlighting
Data for a program JSON (or CSV for flat rows) Machine-readable and validatable
Consider Where the Output Will Be Displayed
The same Markdown table that looks clean in a chat interface appears as a mess of | and - characters in a plain-text email. Always specify the format according to the destination of the output, not only its content.
Common Mistakes
Mistake 1: Asking for a Format Without Defining It
What it is: "Return JSON" or "Make a table" without keys, types, or columns.
Why it happens: The format feels self-explanatory.
What it causes: Different key names and structures on different runs, which breaks parsing.
How to fix it: Define every key or column, its type, and its allowed values, or show an example.
Mistake 2: Trusting the Format Without Validation
What it is: Passing model output directly into a database, API, or user interface.
Why it happens: The format looks correct during testing.
What it causes: Occasional invalid values or malformed JSON cause errors or corrupt data in production.
How to fix it: Parse, validate, and handle errors for every structured response.
Mistake 3: Forgetting Missing-Value Rules
What it is: Requiring a field without saying what to do when the input does not contain it.
Why it happens: Test inputs usually contain all the information.
What it causes: The model invents plausible values to fill required fields.
How to fix it: Specify null, "Not stated", or another explicit value for missing information.
Mistake 4: Conflicting Format Instructions
What it is: Asking for "a detailed explanation" and "one line", or "JSON only" and "explain your reasoning".
Why it happens: Requirements are added at different times.
What it causes: The model satisfies one instruction and breaks the other, inconsistently.
How to fix it: Decide on one format. If you need both reasoning and structured data, include the reasoning as a JSON field, such as "reason".
Mistake 5: Using Markdown for Non-Markdown Destinations
What it is: Leaving the format unspecified for output shown in SMS, plain email, or plain-text fields.
Why it happens: Chat models commonly use Markdown by default.
What it causes: Raw asterisks, hash symbols, and table pipes appear to end users.
How to fix it: State the destination and request plain text explicitly.
Best Practices
Specify the format for every reusable prompt. One-off chats can be flexible; prompts in applications should never leave format to chance.
Use output cues for short, single-value answers. A final label such as Answer: or Category: is simple and effective.
Define structure completely. List every field, column, or section, with types and allowed values.
Define missing-value behavior. Tell the model exactly what to write when information is absent.
Show an example for unusual formats. One example often replaces many rules.
Request "only" the output when code consumes it. Explicitly exclude introductions, explanations, and code fences when needed.
Choose the format by destination. Markdown for rendered pages, plain text for SMS, JSON for programs.
Validate in code and enforce hard limits there. Instructions guide the model; code guarantees correctness.
Try It Yourself
Exercise 1: Add an Output Cue
Turn this prompt into one that returns only the language name:
What programming language is this code written in?
console.log("Hello");
Add a label and delimiter for the code, an allowed-answer rule, and a final cue such as Language:.
Exercise 2: Design a JSON Format
Write a prompt that extracts information from a resume summary into JSON with these fields: name, years_of_experience (integer or null), skills (array of strings), and current_role (string or null). Test it with a summary that does not mention years of experience and confirm that null is returned.
Exercise 3: Format for Different Destinations
Ask a model to explain "how to reset a forgotten password on our platform" three times, each with a different output format:
A Markdown help-center article with headings and numbered steps
A plain-text SMS under 300 characters
A JSON object with title and steps (an array of strings) for a mobile app
Compare how the same content is shaped for each destination.