Module 4 · Chapter 20 Output Design and Control › Output Format Prompting

Output Format Prompting

Output format prompting tells a language model exactly how its response should be structured - as a paragraph, list, table, JSON, XML, YAML, or code - turning a correct answer into one your application can actually use.

Quick takeaway: Name the exact format, define every field, data type, and allowed value, state the missing-value rule, and forbid surrounding text like Markdown fences or explanations. Prompt instructions improve compliance but never guarantee it - always validate structured output with a real parser before using it.

Introduction

Output format prompting is the practice of telling a language model exactly how its response should be structured.

A prompt may ask the model to return information as:

  • A paragraph
  • A bullet-point list
  • A numbered list
  • Markdown
  • A table
  • HTML
  • CSV
  • JSON
  • XML
  • YAML
  • Source code
  • A predefined schema

Without clear format instructions, the model decides how to organize the response. The answer may still be correct, but it may not be suitable for the application that needs to process it.

For example, a human may understand a product description written in paragraphs. However, a software application may require the same information as valid JSON.

Output format prompting improves:

  • Response consistency
  • Readability
  • Data extraction
  • Software integration
  • Validation
  • Automation
  • User-interface rendering
  • Database storage
  • API communication

A strong output format prompt acts like an output contract between the user and the model.

Learning Objectives

After studying this chapter, you should be able to:

  • Define the required output structure clearly.
  • Select the correct format for a task.
  • Generate paragraphs, lists, tables, and Markdown.
  • Request structured formats such as JSON, XML, and YAML.
  • Create schema-based prompts.
  • Validate model-generated output.
  • Detect invalid or incomplete responses.
  • Repair incorrectly formatted output.
  • Design prompts that work reliably in automated systems.

Output Format Prompting at a Glance

Output format prompting answers one main question:

How should the model present the result?

Consider the following basic prompt:

Prompt
Explain dependency injection.

This prompt defines the topic but does not define the output format. The model may return several paragraphs, a list, an example, or a combination of formats.

A more controlled prompt is:

Prompt
Explain dependency injection.
Return exactly five bullet points.
Keep each bullet below 25 words.
Include one practical Java example.
Do not include an introduction or conclusion.

The second prompt provides a clear output structure.

A complete format instruction may define:

  • Output type
  • Required fields
  • Field order
  • Number of items
  • Heading structure
  • Data types
  • Allowed values
  • Length limits
  • Missing-value rules
  • Escaping rules
  • Validation requirements
  • Prohibited content

Defining the Output Format

Defining the output format means describing the exact structure in which the model must return its answer.

The format instruction should be specific enough that both a human and a software program can understand the expected result.

Weak instruction:

Prompt
Give me the result in a proper format.

The phrase “proper format” is unclear. The model does not know whether the user expects a paragraph, table, JSON object, or another structure.

Improved instruction:

Prompt
Return the result as a Markdown table.
Use the columns Name, Category, Price, and Availability.
Include exactly five products.
Sort the rows by Price in ascending order.
Do not include text before or after the table.

This prompt defines:

  • The format
  • The column names
  • The number of rows
  • The sorting rule
  • The surrounding-content rule

Main parts of an output format instruction:

  1. Format type: JSON, table, paragraph, HTML, or another format.
  2. Structure: Fields, columns, sections, elements, or headings.
  3. Order: The sequence in which values must appear.
  4. Quantity: Number of paragraphs, rows, items, or records.
  5. Content rules: Required and prohibited information.
  6. Data types: String, number, Boolean, array, or object.
  7. Length rules: Word, character, sentence, or item limits.
  8. Fallback rules: What to return when information is missing.
  9. Validation rules: Conditions that make the response valid.
  10. Surrounding-text rules: Whether explanations may appear outside the requested format.

Detailed example:

Prompt
Analyze the customer review provided below.
Return one JSON object.
Use the fields sentiment, confidence, keyIssues, and requiresFollowUp.
Set sentiment to positive, neutral, or negative.
Set confidence to a number between 0 and 1.
Set keyIssues to an array of short strings.
Set requiresFollowUp to true or false.
Use an empty array when no issue is found.
Do not add Markdown fences.
Do not add explanations before or after the JSON.
Review: The product works well, but delivery was delayed by four days.

Expected structure:

JSON
{
  "sentiment": "neutral",
  "confidence": 0.92,
  "keyIssues": ["Delivery was delayed by four days"],
  "requiresFollowUp": true
}

Best practices:

  • Name the exact format.
  • Define every required field.
  • State whether additional fields are allowed.
  • Define the expected data type of each field.
  • Explain how missing values should be represented.
  • Provide one valid example when the structure is complex.
  • Tell the model whether surrounding explanations are allowed.
  • Separate formatting instructions from input data.

Paragraph Output

Paragraph output is suitable when the response should read like natural written communication.

It is commonly used for:

  • Explanations
  • Articles
  • Product descriptions
  • Summaries
  • Reports
  • Email content
  • Background information
  • Narrative answers
  • Conceptual discussions

A paragraph prompt should define more than simply “write a paragraph.” It may also define:

  • Number of paragraphs
  • Number of sentences
  • Approximate word count
  • Tone
  • Audience
  • Technical depth
  • Opening sentence
  • Closing sentence
  • Whether examples are allowed

Basic paragraph prompt:

Prompt
Explain cloud computing in one paragraph.
Use simple language.
Write between 100 and 130 words.
Target readers who have no technical background.
Include one everyday example.

Multi-paragraph prompt:

Prompt
Explain how a REST API works.
Return exactly four paragraphs.
Use the first paragraph for the definition.
Use the second paragraph for the request-response process.
Use the third paragraph for a practical example.
Use the fourth paragraph for common limitations.
Keep each paragraph below 80 words.

Why paragraph constraints are useful:

  • They prevent excessively long responses.
  • They create predictable content blocks.
  • They improve page layout.
  • They help maintain a consistent writing style.
  • They make content easier to place in reports or web pages.

Common problem:

A model may produce a heading followed by several paragraphs even when only one paragraph was requested.

Stronger instruction:

Prompt
Return one paragraph only.
Do not include a title.
Do not include headings.
Do not include bullet points.
Do not include a conclusion section.

Example with input data:

Prompt
Summarize the following incident report in one paragraph.
Use past tense.
Mention the cause, impact, response, and final status.
Keep the response below 120 words.
Do not invent missing details.
Incident report: The payment service stopped responding at 10:15 AM because the database connection pool was exhausted. Checkout failed for 18 minutes. The engineering team increased the pool size and restarted two service instances. Service returned to normal at 10:33 AM.

Expected output:

The payment service stopped responding at 10:15 AM because its database connection pool was exhausted. As a result, customers were unable to complete checkout for 18 minutes. The engineering team responded by increasing the connection pool size and restarting two service instances. The service returned to normal operation at 10:33 AM, and no additional issue was reported in the provided incident information.

Best practices:

  • State the exact paragraph count.
  • Add word or sentence limits.
  • Define what each paragraph should cover.
  • Prohibit headings or lists when they are not needed.
  • Specify whether the model may infer missing information.
  • Mention the target audience and technical level.

Bullet-Point Output

Bullet-point output presents information as independent, easy-to-scan items.

It is suitable for:

  • Features
  • Benefits
  • Requirements
  • Risks
  • Key findings
  • Recommendations
  • Checklists
  • Summaries
  • Interview answers
  • Troubleshooting steps without a required sequence

Bullet points are useful when the order of items is not the main concern.

Basic bullet-point prompt:

Prompt
List the main advantages of unit testing.
Return exactly six bullet points.
Keep each bullet below 20 words.
Start each bullet with an action verb.
Do not include an introduction.

Expected output:

  • Detect defects before deployment.
  • Improve confidence during code changes.
  • Document expected application behaviour.
  • Reduce manual testing effort.
  • Support safer refactoring.
  • Isolate failures more quickly.

Detailed bullet format:

Prompt
Review the following project plan.
Return five bullet points.
Use the format "- Risk: Explanation".
Include only high-priority risks.
Keep each explanation below 30 words.
Do not include solutions.
Project plan: The project has one backend developer, an eight-week deadline, an unknown third-party API, and no automated testing environment.

Expected output:

  • Risk: The project depends heavily on one backend developer, creating a major resource and continuity risk.
  • Risk: The eight-week deadline may not allow enough time for development, integration, testing, and defect correction.
  • Risk: The third-party API has unknown behaviour, documentation quality, availability, and integration complexity.
  • Risk: The lack of automated testing may increase regression defects and slow down release validation.
  • Risk: Integration problems may be discovered late because the external dependency has not been tested.

Useful bullet-point controls:

  • Exact number of bullets
  • Maximum words per bullet
  • Required prefix
  • Required label
  • Sentence or phrase format
  • Sorting order
  • Priority level
  • Whether sub-bullets are allowed

Prompt with labels:

Prompt
Summarize the security review.
Return exactly four bullet points.
Begin each bullet with one label from Finding, Impact, Recommendation, or Priority.
Use one label per bullet.
Do not create sub-bullets.

Common mistakes:

  • Asking for bullet points but receiving paragraphs under each bullet
  • Receiving more items than requested
  • Receiving nested bullets when flat bullets are required
  • Receiving repeated information
  • Receiving an introductory sentence before the list

Stronger instruction:

Prompt
Return only a flat bullet list.
Use exactly seven bullets.
Do not use numbered items.
Do not use sub-bullets.
Do not write text before or after the list.
Keep every bullet self-contained.

Numbered List Output

A numbered list is appropriate when sequence, order, priority, or reference number matters.

It is commonly used for:

  • Procedures
  • Setup instructions
  • Workflows
  • Ranked recommendations
  • Troubleshooting processes
  • Learning paths
  • Migration steps
  • Decision-making stages
  • Ordered interview answers

Basic numbered-list prompt:

Prompt
Explain how to create a Git branch.
Return exactly five numbered steps.
Begin each step with an action verb.
Include one command in each step.
Keep the steps in execution order.

Expected output:

  1. Open the repository by running cd project-directory.
  2. Update the main branch by running git pull origin main.
  3. Create a new branch by running git branch feature-name.
  4. Switch to the branch by running git checkout feature-name.
  5. Verify the active branch by running git branch.

When code fences are not desired, commands can be placed as plain inline text or indented lines.

Priority-based numbered list:

Prompt
Review the following application risks.
Return a numbered list ordered from highest to lowest risk.
Include exactly five items.
Use the format "1. Risk name — Reason".
Do not provide solutions.

Numbered list with nested details:

Prompt
Create a three-step deployment process.
Under each numbered step, include two bullet points.
Use the bullet points for validation checks.
Do not use more than one level of nesting.

When to choose numbered lists instead of bullets:

Use numbered lists when:

  • Steps must be followed in order.
  • Items are ranked.
  • Individual items will be referenced later.
  • The output represents stages.
  • The reader must track completion.

Use bullet points when:

  • Items are independent.
  • Order is not important.
  • The list is mainly for scanning.
  • There is no ranking or sequence.

Common mistake:

The model may reorder instructions based on its own judgment.

Stronger instruction:

Prompt
Preserve the process order exactly as provided.
Do not combine steps.
Do not add optional steps.
Number the steps from 1 to 6.
Return only the numbered list.

Markdown Output

Markdown is a lightweight formatting language commonly used in documentation, knowledge bases, Git repositories, technical articles, and chat interfaces.

Markdown output can contain:

  • Headings
  • Paragraphs
  • Bullet points
  • Numbered lists
  • Tables
  • Links
  • Images
  • Bold text
  • Italic text
  • Quotes
  • Horizontal separators
  • Code blocks

Markdown is suitable when the response must be both readable and structurally organized.

Basic Markdown prompt:

Prompt
Explain database indexing.
Return the response in Markdown.
Use one main heading.
Use four section headings.
Include one bullet list.
Include one comparison table.
End with a short conclusion.
Do not use HTML.

Specific Markdown structure:

Prompt
Create a Markdown guide about Java exception handling.
Use "# Java Exception Handling" as the main heading.
Use "##" for all section headings.
Include the sections Definition, Checked Exceptions, Unchecked Exceptions, Best Practices, and Example.
Use bullet points under Best Practices.
Use an indented Java code example under Example.
Do not use headings below level two.

Expected structure:

Prompt
# Java Exception Handling
## Definition
Java exception handling is a mechanism for detecting and managing runtime problems.
## Checked Exceptions
Checked exceptions are verified by the compiler.
## Unchecked Exceptions
Unchecked exceptions usually represent programming errors.
## Best Practices
- Catch specific exceptions.
- Avoid empty catch blocks.
- Preserve the original cause.
## Example
    try {
        processFile();
    } catch (IOException exception) {
        System.out.println(exception.getMessage());
    }

Important Markdown controls:

  • Allowed heading levels
  • Whether code fences are allowed
  • Table structure
  • Link format
  • List style
  • Use of bold and italics
  • Maximum section depth
  • Whether HTML is prohibited
  • Whether a table of contents is required

Markdown formatting problems:

  • Incorrect heading hierarchy
  • Unclosed code fences
  • Mixed HTML and Markdown
  • Broken tables
  • Inconsistent list indentation
  • Extra headings not requested
  • Excessive bold text
  • Escaped characters appearing incorrectly

Stronger instruction:

Prompt
Return valid Markdown only.
Use one level-one heading.
Use level-two headings for all sections.
Do not use level-three headings.
Do not use HTML tags.
Do not use code fences.
Use four-space indentation for code.
Do not include explanatory text outside the document.

Table Output

Table output organizes related information into rows and columns.

Tables are useful for:

  • Comparisons
  • Feature matrices
  • Product data
  • Test results
  • Schedules
  • Reports
  • Pricing plans
  • Requirements
  • Status summaries
  • Structured records

A table prompt should define:

  • Table type
  • Column names
  • Column order
  • Number of rows
  • Sorting rules
  • Value formats
  • Missing-value rules
  • Whether text outside the table is allowed

Markdown table prompt:

Prompt
Compare Java, Python, and JavaScript.
Return one Markdown table.
Use the columns Language, Main Use, Typing, Learning Difficulty, and Common Framework.
Include exactly three rows.
Do not include text before or after the table.

Expected output:

LanguageMain UseTypingLearning DifficultyCommon Framework
JavaEnterprise applicationsStaticMediumSpring Boot
PythonAutomation and data scienceDynamicEasyDjango
JavaScriptWeb developmentDynamicEasyReact

HTML table prompt:

Prompt
Return an HTML table.
Use the columns ID, Name, Department, and Status.
Include a header row and five data rows.
Add thead and tbody elements.
Do not add CSS.
Do not add surrounding HTML document tags.

Table with controlled values:

Prompt
Analyze the project tasks.
Return a Markdown table.
Use the columns Task, Priority, Owner, Status, and Due Date.
Set Priority to High, Medium, or Low.
Set Status to Not Started, In Progress, Blocked, or Completed.
Use YYYY-MM-DD for Due Date.
Use "Unassigned" when the owner is missing.
Sort High-priority tasks first.

Problems with table output:

  • Long content may make tables difficult to read.
  • Line breaks inside cells may break parsers.
  • The pipe character may need escaping in Markdown.
  • Missing values may shift columns.
  • The model may add a summary outside the table.
  • Complex nested data does not fit well in a flat table.

Best practices:

  • Keep column names short and clear.
  • Limit the number of columns.
  • Define how empty cells should be represented.
  • Ask the model to avoid line breaks inside cells.
  • Define date and number formats.
  • Specify the sorting order.
  • Use JSON instead when records contain nested data.

HTML Output

HTML output is useful when model-generated content will be displayed on a web page.

It may include:

  • Headings
  • Paragraphs
  • Lists
  • Tables
  • Forms
  • Cards
  • Navigation elements
  • Semantic page sections

Before requesting HTML, decide whether you need:

  • A complete HTML document
  • A reusable HTML fragment
  • A single component
  • Only semantic markup
  • Inline styling
  • External class names
  • JavaScript behaviour

HTML fragment prompt:

Prompt
Create an HTML product card.
Return an HTML fragment only.
Use article as the root element.
Include a product name, description, price, and Buy Now button.
Use semantic HTML elements.
Add class names using kebab-case.
Do not include CSS.
Do not include JavaScript.
Do not include html, head, or body tags.

Expected output:

Prompt
<article class="product-card">
  <h2 class="product-card-title">Wireless Keyboard</h2>
  <p class="product-card-description">A compact wireless keyboard designed for everyday work.</p>
  <p class="product-card-price">₹1,499</p>
  <button class="product-card-button" type="button">Buy Now</button>
</article>

Complete-document prompt:

Prompt
Create a complete HTML5 document.
Include the doctype, html, head, and body elements.
Set the page title to "Java Learning Roadmap".
Include a main heading and five ordered learning steps.
Use UTF-8 encoding.
Do not include CSS or JavaScript.

HTML with accessibility rules:

Prompt
Create an accessible contact form as an HTML fragment.
Add a visible label for every input.
Use correct input types.
Add required attributes where necessary.
Include an accessible error-message container.
Do not use placeholder text as a replacement for labels.
Do not add inline event handlers.

Security considerations:

Model-generated HTML must not automatically be trusted.

Applications should sanitize generated HTML before displaying it because it may contain:

  • Script elements
  • Inline event handlers
  • Unsafe URLs
  • Embedded objects
  • Untrusted iframe elements
  • Malicious attributes
  • Unexpected form actions

Safer HTML prompt:

Prompt
Return a safe HTML fragment.
Use only p, strong, em, ul, ol, li, h2, h3, and a elements.
Do not use script, style, iframe, object, embed, form, input, or button elements.
Do not use inline event attributes.
Use HTTPS links only.
Do not add target="_blank".

Prompt rules improve the output, but application-level sanitization is still required.

Common HTML mistakes:

  • Missing closing tags
  • Invalid nesting
  • Duplicate IDs
  • Incorrect form labels
  • Inline JavaScript
  • Unrequested CSS
  • Complete documents returned instead of fragments
  • Markdown fences surrounding the HTML

CSV Output

CSV stands for Comma-Separated Values. It represents tabular data as plain text.

CSV is commonly used for:

  • Spreadsheet imports
  • Data exports
  • Reporting
  • Database transfers
  • Batch processing
  • Simple application integration

Each line usually represents one record, and commas separate the fields.

Basic CSV prompt:

Prompt
Return the employee data as CSV.
Use the columns employee_id, name, department, and status.
Include one header row and five data rows.
Use commas as separators.
Quote fields that contain commas.
Use UTF-8 text.
Do not include Markdown fences.
Do not include explanations.

Expected output:

Prompt
employee_id,name,department,status
101,Amit Patil,Engineering,Active
102,Neha Sharma,Human Resources,Active
103,Rahul Verma,Finance,Inactive
104,Priya Shah,Marketing,Active
105,Arjun Rao,Engineering,Active

CSV containing commas:

Prompt
product_id,product_name,description,price
1,Keyboard,"Compact, wireless keyboard",1499
2,Mouse,"Ergonomic mouse, black",799

Fields containing commas must be quoted. Quotes inside values must normally be escaped by doubling them.

Example:

Prompt
id,comment
1,"The customer said, ""Delivery was fast."""

Important CSV instructions:

  • Define the delimiter.
  • Define the header names.
  • Define the column order.
  • State whether a header row is required.
  • Define line-ending requirements when necessary.
  • Explain how commas, quotes, and line breaks should be escaped.
  • Define the text encoding.
  • Prohibit surrounding explanations.
  • Define how missing values should appear.

Prompt with missing-value rules:

Prompt
Return the records as CSV.
Use an empty field for missing text values.
Use 0 for missing numeric values.
Use YYYY-MM-DD for dates.
Do not use "N/A", "null", or "undefined".
Do not add commas after the final column.

Possible CSV problems:

  • Additional commas create extra columns.
  • Unescaped quotes make the file invalid.
  • Multiline values break row processing.
  • Header names do not match application fields.
  • Numbers may lose leading zeros.
  • Dates may be interpreted differently by spreadsheet software.
  • Formula-like values may be executed by spreadsheet applications.

Security consideration:

When CSV output will be opened in spreadsheet software, values beginning with characters such as =, +, -, or @ may be treated as formulas.

The application should escape or neutralize untrusted values before creating downloadable CSV files.

Safer prompt rule:

Prompt
Prefix text values beginning with =, +, -, or @ with a single quote.
Preserve leading zeros in identifier fields.
Quote every text field.
Return CSV only.

JSON Output

JSON stands for JavaScript Object Notation. It is one of the most widely used formats for software integration.

JSON supports:

  • Objects
  • Arrays
  • Strings
  • Numbers
  • Booleans
  • Null values

JSON is suitable for:

  • API responses
  • Data extraction
  • Configuration
  • Application state
  • Database records
  • Automation workflows
  • Structured classification
  • Tool communication

Basic JSON prompt:

Prompt
Analyze the following support request.
Return one valid JSON object.
Use the fields category, priority, summary, and requiresHumanReview.
Set category to billing, technical, account, or other.
Set priority to low, medium, or high.
Set summary to a string below 25 words.
Set requiresHumanReview to true or false.
Do not include Markdown fences.
Do not include comments.
Do not include text outside the JSON.
Support request: I was charged twice for the same subscription.

Expected output:

JSON
{
  "category": "billing",
  "priority": "high",
  "summary": "The customer reports being charged twice for one subscription.",
  "requiresHumanReview": true
}

Strict JSON rules:

  • Property names must use double quotes.
  • String values must use double quotes.
  • Comments are not allowed.
  • Trailing commas are not allowed.
  • Boolean values must be lowercase true or false.
  • Null must be written as null.
  • Undefined values are not supported.
  • Every opening bracket or brace must be closed.
  • Special characters inside strings must be escaped.

JSON array prompt:

Prompt
Extract all products from the input.
Return one valid JSON array.
Return one object per product.
Use the fields name, quantity, and unitPrice.
Set quantity to an integer.
Set unitPrice to a number.
Use an empty array when no product is found.
Do not return null.
Do not add explanations.

Expected output:

Prompt
[
  {
    "name": "Wireless Mouse",
    "quantity": 2,
    "unitPrice": 799
  },
  {
    "name": "Keyboard",
    "quantity": 1,
    "unitPrice": 1499
  }
]

Nested JSON prompt:

Prompt
Return a JSON object describing the project.
Use the fields projectName, manager, technologies, milestones, and active.
Set technologies to an array of strings.
Set milestones to an array of objects.
Each milestone object must contain name, dueDate, and completed.
Use YYYY-MM-DD for dueDate.
Set completed and active to Boolean values.

Missing-value strategy:

Choose one consistent method:

  • Use null.
  • Use an empty string.
  • Use an empty array.
  • Use an empty object.
  • Omit the field.

Do not mix methods without a clear reason.

Example instruction:

Prompt
Include every required field.
Use null when a scalar value is unknown.
Use an empty array when a list has no values.
Do not use empty strings for missing data.

Common JSON mistakes:

  • Markdown fences around the object
  • Single quotes instead of double quotes
  • Comments inside the JSON
  • Trailing commas
  • Text before or after the object
  • Numbers returned as strings
  • Missing required properties
  • Unexpected extra properties
  • Invalid enumeration values
  • Incorrect nesting

Strong JSON prompt pattern:

Prompt
Return valid JSON only.
Follow the exact property names and property order shown below.
Do not add additional properties.
Do not include Markdown fences.
Do not include comments.
Do not include explanations.
Use null only where the schema allows it.
Ensure the final output can be parsed by a standard JSON parser.

XML Output

XML stands for Extensible Markup Language. It stores structured information using elements and attributes.

XML is still used in:

  • Enterprise systems
  • SOAP services
  • Configuration files
  • Document formats
  • Data exchange
  • Legacy integrations
  • Publishing systems
  • Java-based systems

Basic XML prompt:

Prompt
Convert the employee data into valid XML.
Use employees as the single root element.
Use one employee element per record.
Include id, name, department, and active as child elements.
Use true or false for active.
Escape XML special characters.
Do not include Markdown fences.
Do not include explanations.

Expected output:

Prompt
<employees>
  <employee>
    <id>101</id>
    <name>Amit Patil</name>
    <department>Engineering</department>
    <active>true</active>
  </employee>
  <employee>
    <id>102</id>
    <name>Neha Sharma</name>
    <department>Human Resources</department>
    <active>true</active>
  </employee>
</employees>

Important XML rules:

  • XML must have one root element.
  • Every opening element must have a closing element.
  • Elements must be correctly nested.
  • Attribute values must be quoted.
  • Special characters must be escaped.
  • Element names must follow valid naming rules.
  • The document must distinguish uppercase and lowercase names.
  • An XML declaration may be included when required.

Special character escaping:

  • & becomes &amp;
  • < becomes &lt;
  • > may become &gt;
  • " becomes &quot; inside attributes
  • ' becomes &apos; inside attributes when needed

Attribute-based XML prompt:

Prompt
Return valid XML.
Use products as the root element.
Use one product element per item.
Store id and active as attributes.
Store name and price as child elements.
Use INR as the currency attribute on price.
Do not add an XML declaration.

Expected output:

Prompt
<products>
  <product id="P101" active="true">
    <name>Wireless Keyboard</name>
    <price currency="INR">1499</price>
  </product>
</products>

Elements versus attributes:

Use elements when:

  • The value may contain longer content.
  • The value may have nested structure.
  • The value is part of the main data.

Use attributes when:

  • The value is short metadata.
  • The value identifies or classifies the element.
  • The value does not need nested content.

Common XML mistakes:

  • Multiple root elements
  • Missing closing elements
  • Incorrect nesting
  • Unescaped ampersands
  • Inconsistent element names
  • Missing namespace declarations
  • Invalid attribute quoting
  • Text outside the root element

Security consideration:

Applications should use secure XML parsers. External entity processing should normally be disabled when handling untrusted XML to reduce XML external entity risks.

YAML Output

YAML is a human-readable data serialization format commonly used for configuration files.

YAML is often used in:

  • Docker Compose
  • Kubernetes
  • CI/CD pipelines
  • Application configuration
  • Infrastructure as code
  • Workflow definitions
  • Static-site configuration
  • API specifications

YAML uses indentation to represent structure.

Basic YAML prompt:

Prompt
Return the application configuration as valid YAML.
Use two spaces for indentation.
Include the fields application, server, database, and logging.
Store database settings as a nested object.
Store allowedOrigins as a list.
Quote all date-like and version-like values.
Do not include Markdown fences.
Do not include explanations.

Expected output:

Prompt
application:
  name: CodeLangs API
  version: "1.0"
server:
  port: 8080
  environment: production
database:
  host: localhost
  port: 3306
  name: codelangs
logging:
  level: info
  allowedOrigins:
    - "https://example.com"
    - "https://admin.example.com"

Important YAML rules:

  • Indentation must be consistent.
  • Tabs should not be used for indentation.
  • A colon separates a key from its value.
  • List items usually begin with a hyphen.
  • Strings containing special characters may need quotes.
  • Values such as dates, yes, no, on, off, or version numbers may be interpreted unexpectedly.
  • Duplicate keys should be avoided.
  • Deeply nested structures should remain readable.

YAML list prompt:

Prompt
Return valid YAML only.
Use tasks as the root key.
Store each task as a list item.
Include id, title, priority, completed, and tags.
Set priority to high, medium, or low.
Set completed to true or false.
Set tags to a list of strings.
Use two spaces for each indentation level.

Expected output:

Prompt
tasks:
  - id: 1
    title: Create database schema
    priority: high
    completed: false
    tags:
      - database
      - backend
  - id: 2
    title: Build login page
    priority: medium
    completed: true
    tags:
      - frontend
      - authentication

Common YAML mistakes:

  • Incorrect indentation
  • Tab characters
  • Duplicate keys
  • Missing spaces after colons
  • Incorrect list indentation
  • Unquoted ambiguous values
  • Multiple documents returned unexpectedly
  • Markdown fences surrounding the YAML

Safer YAML instructions:

Prompt
Return one YAML document only.
Use two spaces for indentation.
Do not use tabs.
Do not use anchors or aliases.
Do not use custom YAML tags.
Do not include duplicate keys.
Quote date, time, and version strings.
Do not add comments.

YAML is easy for humans to read but more sensitive to spacing than JSON.

Code-Only Output

Code-only output means the model must return source code without explanation, headings, Markdown fences, or surrounding text.

It is useful when:

  • Code will be copied directly into a file.
  • An automated system will process the response.
  • A developer needs a focused implementation.
  • Explanations are not required.
  • The output will be inserted into an existing codebase.

Basic code-only prompt:

Prompt
Write a Java method that returns the largest number in an integer array.
Return Java code only.
Use a static method named findMaximum.
Throw IllegalArgumentException when the array is null or empty.
Do not include a class declaration.
Do not include Markdown fences.
Do not include explanations.
Use one single-line comment above the method.

Expected output:

Prompt
// Returns the largest value in a non-empty array
public static int findMaximum(int[] numbers) {
    if (numbers == null || numbers.length == 0) {
        throw new IllegalArgumentException("Array must not be null or empty");
    }
    int maximum = numbers[0];
    for (int number : numbers) {
        if (number > maximum) {
            maximum = number;
        }
    }
    return maximum;
}

Complete-file prompt:

Prompt
Create a complete Java class named EmailValidator.
Return code only.
Include the package declaration com.codelangs.validation.
Include all required imports.
Add one public static method named isValid.
Use Pattern and Matcher.
Return false for null or blank input.
Do not include Markdown fences.
Do not include usage examples.
Do not include explanations.

Code modification prompt:

Prompt
Fix the null pointer problem in the Java code below.
Return the complete corrected code only.
Preserve the existing public method names.
Do not change business logic unless required for the fix.
Add single-line comments only where the fix is not obvious.
Do not include a change summary.
Code:
[Insert code here]

Important code-only controls:

  • Programming language
  • Language version
  • Framework version
  • Complete file or partial snippet
  • Class and method names
  • Required imports
  • Error handling
  • Comment style
  • Indentation
  • Dependencies
  • Input and output types
  • Testing requirements
  • Prohibited libraries
  • Surrounding-text restrictions

Weak instruction:

Prompt
Write code for user login.

This does not define:

  • Programming language
  • Framework
  • Authentication method
  • Database
  • Error handling
  • Input type
  • Output type
  • Security requirements
  • Expected file structure

Improved instruction:

Prompt
Create a Spring Boot service method for authenticating a user.
Use Java 21 and Spring Boot 3.
Accept email and password as method parameters.
Load the user through UserRepository.
Verify the password through PasswordEncoder.
Throw BadCredentialsException when authentication fails.
Return an AuthenticationResponse object.
Do not generate controller or repository code.
Return Java code only.
Do not include Markdown fences.

Common code-only failures:

  • Markdown fences are included.
  • Explanations appear before the code.
  • Placeholder methods are returned.
  • Required imports are missing.
  • The model changes method names.
  • Unsupported libraries are added.
  • The output contains multiple alternative solutions.
  • The code does not compile.

Reliability improvement:

Prompt
Return one implementation only.
Return complete compilable code.
Include all required imports.
Do not use placeholder comments.
Do not omit method bodies.
Do not use external libraries.
Verify that all referenced variables and methods are declared.

Schema-Based Output

Schema-based prompting defines the exact structure, field names, data types, allowed values, and validation rules for the model’s response.

A schema is more precise than simply asking for JSON or XML.

For example, requesting “JSON output” defines the syntax. A schema defines what the JSON must contain.

Simple schema prompt:

Prompt
Analyze the job candidate profile.
Return valid JSON matching the schema below.
name: string
experienceYears: integer greater than or equal to 0
primarySkill: string
skillLevel: beginner, intermediate, or advanced
available: Boolean
missingInformation: array of strings
Include every field.
Do not add additional fields.
Use an empty array when no information is missing.
Do not include Markdown fences.
Do not include explanations.

Expected output:

JSON
{
  "name": "Rahul Patil",
  "experienceYears": 5,
  "primarySkill": "Java",
  "skillLevel": "advanced",
  "available": true,
  "missingInformation": []
}

Nested schema example:

Prompt
Return valid JSON matching the following schema.
orderId: string
customer: object
customer.name: string
customer.email: string or null
items: array of objects
items[].productId: string
items[].productName: string
items[].quantity: integer greater than 0
items[].unitPrice: number greater than or equal to 0
totalAmount: number greater than or equal to 0
currency: INR, USD, or EUR
status: pending, paid, shipped, delivered, or cancelled
Do not add additional fields.
Include every required field.
Use null only for customer.email.

JSON Schema-style definition:

Prompt
Return valid JSON matching this structure.
{
  "type": "object",
  "required": ["title", "priority", "completed"],
  "additionalProperties": false,
  "properties": {
    "title": {
      "type": "string",
      "minLength": 1
    },
    "priority": {
      "type": "string",
      "enum": ["low", "medium", "high"]
    },
    "completed": {
      "type": "boolean"
    }
  }
}
Return the generated object only.
Do not return the schema.
Do not include Markdown fences.

Schema components:

  • Property name: Exact key or field name.
  • Data type: String, number, integer, Boolean, array, object, or null.
  • Required status: Whether the field must exist.
  • Allowed values: A fixed enumeration.
  • Minimum and maximum: Numeric limits.
  • Length limits: Minimum and maximum string length.
  • Pattern: Required string pattern.
  • Array rules: Minimum items, maximum items, and item schema.
  • Nested object rules: Fields inside another object.
  • Additional-property rule: Whether unknown fields are allowed.
  • Nullability: Whether null is accepted.
  • Conditional rules: Requirements based on another field.

Conditional schema example:

Prompt
Return valid JSON.
Use the fields paymentStatus, transactionId, and failureReason.
Set paymentStatus to successful or failed.
When paymentStatus is successful, transactionId must be a non-empty string and failureReason must be null.
When paymentStatus is failed, transactionId must be null and failureReason must be a non-empty string.
Do not add other fields.

Why schema-based prompting is useful:

  • It creates predictable output.
  • It reduces field-name variations.
  • It supports automatic validation.
  • It improves API integration.
  • It reduces manual data cleaning.
  • It makes error handling easier.
  • It supports database mapping.
  • It allows strict business rules.

Prompt schema versus application schema:

A prompt schema tells the model what to produce.

An application schema checks whether the produced output is valid.

Both should be used together. Prompt instructions alone cannot guarantee perfect compliance.

Output Format Validation

Output format validation checks whether the model’s response follows the required structure and rules.

Validation should not be limited to checking whether the output “looks correct.”

A reliable system validates several levels.

1. Syntax validation

Syntax validation checks whether the format itself is valid.

Examples:

  • Can the JSON be parsed?
  • Is the XML well formed?
  • Is the YAML indentation valid?
  • Does every CSV row contain the expected number of columns?
  • Are HTML elements properly structured?

2. Structural validation

Structural validation checks whether required fields and sections exist.

Examples:

  • Does the JSON contain name, email, and status?
  • Does the table contain the required columns?
  • Does the XML contain one root element?
  • Does the Markdown document contain the required headings?

3. Data-type validation

Data-type validation checks whether each value has the correct type.

Examples:

  • Age must be an integer.
  • Price must be a number.
  • Active must be a Boolean.
  • Tags must be an array.
  • Due date must be a string in the required format.

4. Value validation

Value validation checks allowed values and limits.

Examples:

  • Priority must be low, medium, or high.
  • Confidence must be between 0 and 1.
  • Quantity must be greater than zero.
  • Description must be below 200 characters.

5. Semantic validation

Semantic validation checks whether the information makes logical sense.

Examples:

  • The end date should not be before the start date.
  • A completed task should not have a future completion date.
  • A failed payment should not have a successful status message.
  • A child category should belong to the selected parent category.

6. Business-rule validation

Business-rule validation checks application-specific conditions.

Examples:

  • A refund above ₹10,000 requires manager review.
  • A high-priority incident must have an assigned owner.
  • An inactive account cannot have an active subscription.
  • A shipped order must contain a tracking number.

7. Security validation

Security validation checks for dangerous or prohibited content.

Examples:

  • Unsafe HTML elements
  • Script injection
  • Formula injection in CSV
  • Unexpected file paths
  • SQL fragments
  • Malicious links
  • Sensitive data leakage

JSON Validation Example

The following Python code parses JSON and checks required fields:

Python
import json
def validate_response(response_text):
    try:
        data = json.loads(response_text)
    except json.JSONDecodeError as error:
        return False, f"Invalid JSON: {error}"
    required_fields = {"category", "priority", "summary", "requiresHumanReview"}
    if set(data.keys()) != required_fields:
        return False, "JSON fields do not match the required schema"
    if data["category"] not in {"billing", "technical", "account", "other"}:
        return False, "Invalid category"
    if data["priority"] not in {"low", "medium", "high"}:
        return False, "Invalid priority"
    if not isinstance(data["summary"], str):
        return False, "Summary must be a string"
    if not isinstance(data["requiresHumanReview"], bool):
        return False, "requiresHumanReview must be Boolean"
    return True, data

This validation checks:

  • JSON syntax
  • Exact field names
  • Allowed category values
  • Allowed priority values
  • String data type
  • Boolean data type

Java JSON Validation Example

The following Java example uses Jackson to parse and validate a response:

Java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Set;
public class ResponseValidator {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static final Set<String> ALLOWED_PRIORITIES = Set.of("low", "medium", "high");
    // Validates the basic response structure
    public static boolean isValid(String response) {
        try {
            JsonNode root = OBJECT_MAPPER.readTree(response);
            if (!root.isObject()) {
                return false;
            }
            if (!root.hasNonNull("title") || !root.get("title").isTextual()) {
                return false;
            }
            if (!root.hasNonNull("priority") || !root.get("priority").isTextual()) {
                return false;
            }
            if (!ALLOWED_PRIORITIES.contains(root.get("priority").asText())) {
                return false;
            }
            if (!root.has("completed") || !root.get("completed").isBoolean()) {
                return false;
            }
            return root.size() == 3;
        } catch (Exception exception) {
            return false;
        }
    }
}

The application should validate model output before using it in:

  • Database operations
  • API requests
  • Financial calculations
  • User-interface rendering
  • File generation
  • Automated decisions
  • Security-sensitive workflows

Format-Specific Validation

FormatMain Validation Checks
ParagraphParagraph count, word count, sentence count, prohibited headings
Bullet listBullet count, bullet marker, nesting level, item length
Numbered listStep count, numbering sequence, item order
MarkdownHeading hierarchy, table structure, link format, code-block closure
TableColumn count, column names, row count, missing values
HTMLValid nesting, allowed tags, safe attributes, sanitization
CSVHeader names, field count, quoting, delimiter consistency
JSONParsing, required properties, types, enumerations, extra fields
XMLOne root element, valid nesting, schema compliance, safe parser settings
YAMLParsing, indentation, duplicate keys, allowed tags
CodeCompilation, linting, tests, security checks, dependency checks
Schema-based outputSyntax, structure, types, constraints, business rules

Prompt-Based Validation

The model can also be asked to verify its own output before returning it.

Example:

Prompt
Generate a JSON object using the required schema.
Before returning the response, verify that the JSON is syntactically valid.
Verify that every required field is present.
Verify that no additional field is included.
Verify that all values use the required data types.
Return only the final validated JSON.

This instruction may improve compliance, but it is not a replacement for application-level validation.

A model may incorrectly believe that its output is valid. Therefore, software should still use a real parser and schema validator.

Handling Invalid Output

Invalid output occurs when the model fails to follow the requested format.

Examples include:

  • Invalid JSON
  • Broken XML
  • Incorrect YAML indentation
  • Missing table columns
  • Extra explanation around code
  • Incorrect field names
  • Missing required values
  • Unexpected data types
  • Additional properties
  • Prohibited content
  • Incomplete code
  • Wrong number of list items

A production system should expect occasional format failures and include a recovery process.

Step 1: Detect the Failure

The application should first identify why the output is invalid.

Possible validation errors include:

  • Parsing error
  • Missing field
  • Invalid field type
  • Invalid allowed value
  • Extra field
  • Length violation
  • Incorrect item count
  • Broken nesting
  • Business-rule failure

Example validation result:

JSON
{
  "valid": false,
  "errors": [
    "Field priority must be low, medium, or high",
    "Field completed must be Boolean",
    "Unexpected field explanation"
  ]
}

Specific validation errors make repair prompts more effective.

Step 2: Request a Format Repair

A repair prompt should include:

  • The invalid output
  • The validation errors
  • The required schema
  • A rule to preserve valid information
  • A rule to return only the corrected format

Repair prompt:

Prompt
The previous response does not match the required JSON schema.
Correct the formatting and schema errors only.
Preserve all valid information from the previous response.
Remove properties that are not defined in the schema.
Add any missing required properties.
Correct invalid data types.
Return valid JSON only.
Do not include Markdown fences.
Do not include explanations.
Required schema:
title: non-empty string
priority: low, medium, or high
completed: Boolean
Validation errors:
priority contains an unsupported value
completed is a string instead of a Boolean
explanation is an unexpected property
Invalid response:
[Insert invalid response here]

Step 3: Retry the Original Task

When the original answer is too damaged to repair, run the task again with stronger format instructions.

Retry prompt:

Prompt
Perform the original classification again.
Ignore the previous response.
Return one valid JSON object.
Include exactly four properties.
Use the properties category, confidence, summary, and requiresReview.
Do not add additional properties.
Set confidence to a number between 0 and 1.
Set requiresReview to a Boolean.
Return JSON only.
Do not use Markdown.
Do not include explanations.

Step 4: Use a Fallback Result

A system should define what happens when repeated repair attempts fail.

Possible fallback actions include:

  • Return a safe default object.
  • Send the response for human review.
  • Store the raw response for investigation.
  • Mark the processing status as failed.
  • Ask the user for clarification.
  • Use a simpler format.
  • Skip the affected record.
  • Disable the automated action.

Example fallback JSON:

JSON
{
  "status": "processing_failed",
  "data": null,
  "requiresHumanReview": true,
  "errorCode": "INVALID_MODEL_OUTPUT"
}

Fallback output should itself follow a valid and predictable schema.

Step 5: Limit Retry Attempts

Applications should not retry forever.

A practical strategy may be:

  1. Generate the initial response.
  2. Validate the response.
  3. Run one format-repair attempt.
  4. Validate the repaired response.
  5. Run one full-regeneration attempt.
  6. Use a fallback result or human review.

The number of attempts should depend on:

  • Cost
  • Response time
  • Business importance
  • Failure risk
  • Model reliability
  • User experience

Invalid JSON Example

Invalid response:

JSON
{
  'category': 'billing',
  'priority': urgent,
  'requiresReview': True,
}

Problems:

  • Property names use single quotes.
  • String values use single quotes.
  • urgent is not quoted.
  • True uses invalid capitalization.
  • A trailing comma appears after the last property.
  • The required summary field is missing.

Corrected response:

JSON
{
  "category": "billing",
  "priority": "high",
  "summary": "The customer reported a billing problem.",
  "requiresReview": true
}

Invalid XML Example

Invalid response:

Prompt
<employees>
  <employee>
    <name>Amit & Sons</name>
    <department>Sales</employee>
  </department>
</employees>

Problems:

  • The ampersand is not escaped.
  • The elements are incorrectly nested.
  • The closing tags are in the wrong order.

Corrected response:

Prompt
<employees>
  <employee>
    <name>Amit &amp; Sons</name>
    <department>Sales</department>
  </employee>
</employees>

Invalid YAML Example

Invalid response:

Prompt
application:
   name: CodeLangs
  version: 1.0
server:
 port: 8080

Problems:

  • Indentation is inconsistent.
  • Related fields do not use the same indentation level.
  • The version may be better preserved as a quoted string.

Corrected response:

Prompt
application:
  name: CodeLangs
  version: "1.0"
server:
  port: 8080

Invalid CSV Example

Invalid response:

Prompt
id,name,description,price
1,Keyboard,Compact, wireless keyboard,1499
2,Mouse,Ergonomic mouse,799

The first data row contains five comma-separated values even though the header contains four columns.

Corrected response:

Prompt
id,name,description,price
1,Keyboard,"Compact, wireless keyboard",1499
2,Mouse,Ergonomic mouse,799

Invalid Code-Only Output Example

Requested output:

Prompt
Return Java code only.

Invalid response:

Prompt
Here is the Java code you requested:
public static int add(int first, int second) {
    return first + second;
}
This method returns the sum of two integers.

The source code is surrounded by explanatory text.

Corrected output:

Prompt
public static int add(int first, int second) {
    return first + second;
}

Improving Output Format Reliability

A model is more likely to follow a format when the prompt is explicit and internally consistent.

Use these techniques:

1. Put the output format near the end

The final part of the prompt can restate the output requirements.

Prompt
Task: Analyze the customer feedback.
Input: The application is useful, but it crashes during checkout.
Output requirements:
Return valid JSON only.
Use the fields sentiment, issues, and requiresReview.
Do not add explanations.

2. Provide a valid example

Examples show the exact expected pattern.

Prompt
Follow this output pattern:
{
  "sentiment": "negative",
  "issues": ["Checkout failure"],
  "requiresReview": true
}

The example should match the real schema. A contradictory example can reduce accuracy.

3. Use exact field names

Avoid vague instructions such as:

Prompt
Include customer details.

Use:

Prompt
Include the fields customerId, customerName, customerEmail, and accountStatus.

4. Define data types

Do not assume the model will select the correct type.

Prompt
Set age to an integer.
Set active to a Boolean.
Set tags to an array of strings.
Set score to a number between 0 and 100.

5. Define allowed values

Prompt
Set status to pending, approved, or rejected.

This is more reliable than:

Prompt
Add an appropriate status.

6. Prohibit additional content

Prompt
Do not include Markdown fences.
Do not include comments.
Do not include explanations.
Do not add properties that are not in the schema.

7. Define missing-value behaviour

Prompt
Use null when the email is unknown.
Use an empty array when no skills are found.
Do not use "N/A", "unknown", or an empty string.

8. Keep the schema manageable

Deeply nested schemas are more difficult to generate correctly.

When possible:

  • Reduce nesting.
  • Remove unnecessary fields.
  • Split large tasks into stages.
  • Validate each stage separately.
  • Use shorter property names without making them unclear.

9. Separate data from instructions

Use clear labels or delimiters.

Prompt
Instructions:
Extract the customer information.
Return valid JSON only.
Input:
<customer_text>
Customer name is Amit Patil and the account is active.
</customer_text>

10. Validate outside the model

Always use:

  • JSON parsers
  • XML parsers
  • YAML parsers
  • CSV libraries
  • HTML sanitizers
  • Schema validators
  • Compilers
  • Linters
  • Automated tests

Choosing the Correct Output Format

RequirementRecommended Format
Natural explanationParagraph
Quick summaryBullet points
Ordered processNumbered list
DocumentationMarkdown
Human-readable comparisonTable
Web-page renderingHTML
Spreadsheet importCSV
API or application integrationJSON
Enterprise or legacy integrationXML
Human-readable configurationYAML
Direct source-file generationCode-only
Strict automated processingSchema-based JSON or XML

Paragraph Versus List

Use paragraph output when:

  • Ideas must flow naturally.
  • Context and explanation are important.
  • The answer should read like an article.
  • Relationships between ideas need discussion.

Use list output when:

  • Information should be scanned quickly.
  • Items are independent.
  • The user needs a checklist.
  • The answer contains features, risks, or recommendations.

Table Versus JSON

Use a table when:

  • Humans are the main readers.
  • Records are flat.
  • Comparison is important.
  • The number of fields is limited.

Use JSON when:

  • Software is the main consumer.
  • Data contains arrays or nested objects.
  • Data types must be preserved.
  • Validation and API integration are required.

JSON Versus YAML

Use JSON when:

  • Strict machine parsing is important.
  • The format will be used in an API.
  • Predictable syntax is required.
  • Tool support is a priority.

Use YAML when:

  • Humans will edit the configuration.
  • Readability is important.
  • The file represents deployment or infrastructure settings.
  • Comments may be needed in a manually maintained file.

JSON is generally easier to validate strictly. YAML is often easier to read but more sensitive to indentation and implicit value interpretation.

JSON Versus XML

Use JSON when:

  • The application is modern and web-based.
  • Smaller payloads are preferred.
  • Objects and arrays are sufficient.
  • JavaScript compatibility is useful.

Use XML when:

  • The target system requires XML.
  • Namespaces are important.
  • Document-oriented data is involved.
  • An existing enterprise or SOAP integration uses XML.

Common Output Format Mistakes

Vague format instructions

Weak:

Prompt
Format the answer properly.

Better:

Prompt
Return a Markdown table with the columns Feature, Benefit, and Limitation.

Conflicting format instructions

Conflicting prompt:

Prompt
Return JSON only.
Explain every field after the JSON.

The first instruction prohibits surrounding text, while the second requires it.

Resolved prompt:

Prompt
Return one JSON object.
Include an explanation property inside the JSON.
Do not include text outside the JSON.

Undefined missing-value behaviour

Without a rule, the model may use:

  • Null
  • Empty string
  • Unknown
  • N/A
  • Omitted fields

Define one consistent strategy.

Overly complicated schema

A large schema with many nested levels increases the risk of:

  • Missing properties
  • Incorrect nesting
  • Type errors
  • Truncated output
  • Inconsistent objects

Mixing format and content rules

The prompt should clearly separate:

  • What information to produce
  • How to format it
  • What restrictions to follow

Relying only on an example

An example helps, but explicit rules are still required. The model may copy example values or infer incorrect constraints.

Accepting output without validation

A response that looks correct may still contain:

  • Invalid syntax
  • Hidden extra fields
  • Incorrect types
  • Unsupported values
  • Unsafe content
  • Business-rule violations

Practical Example: Product Data Extraction

Task:

Extract product information from a sentence.

Input:

The Wireless Pro Keyboard costs ₹2,499, is currently available, and belongs to the Computer Accessories category.

Prompt:

Prompt
Extract product information from the input.
Return valid JSON only.
Use the fields name, price, currency, category, and available.
Set price to a number.
Set currency to a three-letter currency code.
Set available to a Boolean.
Include every field.
Do not add additional fields.
Input:
The Wireless Pro Keyboard costs ₹2,499, is currently available, and belongs to the Computer Accessories category.

Expected output:

JSON
{
  "name": "Wireless Pro Keyboard",
  "price": 2499,
  "currency": "INR",
  "category": "Computer Accessories",
  "available": true
}

Practical Example: Support Ticket Classification

Prompt:

Prompt
Classify the support ticket.
Return valid JSON only.
Use the fields category, priority, summary, and assignedTeam.
Set category to billing, technical, account, delivery, or other.
Set priority to low, medium, high, or critical.
Set assignedTeam to Finance, Engineering, Customer Support, Logistics, or General Support.
Keep summary below 30 words.
Do not add additional fields.
Ticket:
Customers cannot complete payments because the checkout API is returning HTTP 500 errors.

Expected output:

JSON
{
  "category": "technical",
  "priority": "critical",
  "summary": "Checkout payments are failing because the API is returning HTTP 500 errors.",
  "assignedTeam": "Engineering"
}

Practical Example: Interview Question Generation

Prompt:

Prompt
Generate five Java interview questions about exception handling.
Return a Markdown table.
Use the columns ID, Question, Difficulty, and Skill Tested.
Set Difficulty to Easy, Medium, or Hard.
Keep each question below 25 words.
Do not include answers.
Do not include text outside the table.

Expected output:

IDQuestionDifficultySkill Tested
1What is an exception in Java?EasyBasic understanding
2What is the difference between checked and unchecked exceptions?MediumException classification
3How does the finally block behave when an exception occurs?MediumControl flow
4When should a custom exception be created?MediumException design
5How can exception handling cause resource leaks?HardResource management

Practical Example: HTML FAQ Generation

Prompt:

Prompt
Create an HTML FAQ section.
Return an HTML fragment only.
Use section as the root element.
Include one h2 heading.
Include exactly four details elements.
Add one summary and one paragraph inside each details element.
Use class names beginning with faq-.
Do not include CSS.
Do not include JavaScript.
Do not include Markdown fences.

Expected structure:

Prompt
<section class="faq-section">
  <h2 class="faq-title">Frequently Asked Questions</h2>
  <details class="faq-item">
    <summary class="faq-question">What is output format prompting?</summary>
    <p class="faq-answer">Output format prompting defines how a language model should structure its response.</p>
  </details>
  <details class="faq-item">
    <summary class="faq-question">Why is JSON commonly used?</summary>
    <p class="faq-answer">JSON is easy for applications to parse, validate, store, and transfer.</p>
  </details>
  <details class="faq-item">
    <summary class="faq-question">Should model output be validated?</summary>
    <p class="faq-answer">Yes. Prompt instructions improve consistency but do not guarantee valid output.</p>
  </details>
  <details class="faq-item">
    <summary class="faq-question">What happens when output is invalid?</summary>
    <p class="faq-answer">The application can repair, regenerate, reject, or send the output for human review.</p>
  </details>
</section>

Practical Example: Code Generation

Prompt:

Prompt
Write a Java record named Product.
Return Java code only.
Use the fields id, name, price, and available.
Use String for id and name.
Use BigDecimal for price.
Use boolean for available.
Validate that id and name are not null or blank.
Validate that price is not null or negative.
Use a compact constructor.
Include all required imports.
Add single-line comments only.
Do not include Markdown fences.
Do not include explanations.

Expected output:

Java
import java.math.BigDecimal;
public record Product(String id, String name, BigDecimal price, boolean available) {
    // Validates product data during object creation
    public Product {
        if (id == null || id.isBlank()) {
            throw new IllegalArgumentException("ID must not be null or blank");
        }
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("Name must not be null or blank");
        }
        if (price == null || price.signum() < 0) {
            throw new IllegalArgumentException("Price must not be null or negative");
        }
    }
}

Complete Output Format Prompt Template

Prompt
Role:
Act as a [role or domain expert].
Task:
[Clearly describe what the model must do.]
Input:
[Provide the source information, question, or data.]
Output format:
Return the response as [paragraph, bullet list, Markdown, table, HTML, CSV, JSON, XML, YAML, or code].
Structure:
[Define headings, fields, columns, elements, sections, or methods.]
Field rules:
[Define the data type and allowed values for every field.]
Quantity:
[Define the number of paragraphs, items, rows, records, or sections.]
Order:
[Define the required field, section, row, or step order.]
Length:
[Define word, character, sentence, or item limits.]
Missing values:
[Define whether to use null, an empty string, an empty array, an empty object, or another fallback.]
Validation:
[Define syntax, schema, value, and business-rule requirements.]
Restrictions:
[Define prohibited fields, formats, explanations, comments, or surrounding text.]
Final rule:
Return only the requested output and verify that it follows every format requirement.

JSON Output Template

Prompt
Complete the requested task.
Return one valid JSON object.
Use exactly the fields defined below.
[fieldName]: [data type and rule]
[fieldName]: [data type and rule]
[fieldName]: [data type and rule]
Include every required field.
Do not add additional fields.
Use null for unknown scalar values.
Use an empty array for lists with no values.
Use double quotes for all property names and string values.
Do not use comments.
Do not use trailing commas.
Do not include Markdown fences.
Do not include text before or after the JSON.
Verify that the final output can be parsed by a standard JSON parser.

Table Output Template

Prompt
Complete the requested analysis.
Return one Markdown table.
Use the columns [Column 1], [Column 2], [Column 3], and [Column 4].
Preserve the exact column order.
Include exactly [number] data rows.
Use [value] for missing information.
Keep every cell on one line.
Sort the rows by [column and direction].
Do not add or remove columns.
Do not include text before or after the table.

Code-Only Output Template

Prompt
Write the required [programming language] code.
Use [language or framework version].
Create [class, method, component, or file name].
Implement [required behaviour].
Handle [errors and edge cases].
Use [allowed libraries or dependencies].
Do not use [prohibited libraries or techniques].
Include all required imports.
Return complete compilable code.
Use single-line comments only where necessary.
Do not include placeholder code.
Do not include Markdown fences.
Do not include explanations.
Return code only.

Output Format Validation Checklist

Before accepting a model response, verify the following points:

  • The requested format is used.
  • The response contains no prohibited surrounding text.
  • Every required section or field is present.
  • No unexpected field or section has been added.
  • Field names use the exact required spelling.
  • Values use the correct data types.
  • Values follow allowed-value rules.
  • Numbers follow minimum and maximum limits.
  • Dates use the required format.
  • Lists contain the required number of items.
  • Tables contain the required columns.
  • JSON can be parsed successfully.
  • XML contains one valid root element.
  • YAML uses consistent indentation.
  • CSV rows contain the correct number of fields.
  • HTML has been sanitized before display.
  • Code compiles or passes syntax checking.
  • Business rules are satisfied.
  • Unsafe or sensitive content is rejected.
  • A fallback process exists for invalid output.

Key Takeaways

  • Output format prompting controls how a model presents information.
  • The required format should be stated clearly and directly.
  • Paragraphs are suitable for connected explanations.
  • Bullet points are suitable for independent items.
  • Numbered lists are suitable for sequences and rankings.
  • Markdown is useful for structured documentation.
  • Tables are useful for human-readable comparison.
  • HTML is useful for web rendering but must be sanitized.
  • CSV is useful for flat spreadsheet-style data.
  • JSON is suitable for APIs and automated processing.
  • XML is useful for enterprise and document-based integrations.
  • YAML is useful for human-readable configuration.
  • Code-only prompting removes unwanted explanations around source code.
  • Schema-based prompting defines exact fields, types, and constraints.
  • Prompt instructions improve format reliability but cannot guarantee correctness.
  • Every structured output should be validated with application-level tools.
  • Invalid output should be repaired, regenerated, or replaced with a safe fallback.
  • The strongest output prompts define structure, data types, allowed values, missing-value rules, validation rules, and prohibited content.

Conclusion

Output format prompting is a core technique for producing responses that are clear, consistent, and usable.

For a simple human-readable answer, defining paragraphs, lists, headings, or tables may be enough. For automated systems, the prompt should define a strict structure such as JSON, XML, YAML, CSV, or a schema-based object.

The most reliable workflow contains three parts:

  1. Define the required output structure in the prompt.
  2. Validate the response with a real parser or schema validator.
  3. Repair, regenerate, or safely reject invalid output.

A language model should never be treated as a guaranteed format generator. Clear prompts reduce errors, while validation and fallback handling make the overall system dependable.

Frequently Asked Questions

What is output format prompting?

Output format prompting is the practice of telling a language model exactly how its response should be structured - as a paragraph, list, table, Markdown, HTML, CSV, JSON, XML, YAML, or code - instead of letting the model choose its own structure.

Why doesn't the model return the format I need just from a topic?

Without a format instruction, the model decides how to organize the answer, which may be correct but unsuitable for an application that needs to parse it. Naming the exact format, fields, order, and quantity turns a vague request into a reliable output contract.

When should I use JSON instead of a table?

Use a table when humans are the main readers, records are flat, and comparison matters. Use JSON when software is the main consumer, data contains arrays or nested objects, and data types and validation need to be preserved for an API or automated process.

What is schema-based output and how is it different from just asking for JSON?

Asking for "JSON" only defines the syntax. Schema-based prompting also defines the exact field names, data types, required/optional status, allowed values, and nesting rules, which produces more predictable output and supports automatic validation.

What is the difference between JSON and YAML for output?

JSON is easier to validate strictly and is the standard for APIs, with predictable syntax and strong tool support. YAML is more human-readable and common for configuration files, but it is more sensitive to indentation and can misinterpret values like dates or version numbers.

How should missing values be represented in structured output?

Pick one consistent strategy - null, an empty string, an empty array, an empty object, or omitting the field - and state it explicitly in the prompt. Mixing different missing-value conventions without a stated reason makes the output unpredictable to parse.

Why is code-only output useful and how do I request it?

Code-only output removes explanations, headings, and Markdown fences so the response can be copied straight into a file or processed automatically. Ask for the language, exact class/method names, required imports, error handling, and explicitly forbid Markdown fences and explanatory text.

What levels should output validation check?

A reliable system checks syntax (is it parseable?), structure (are required fields present?), data types, allowed values, semantic correctness (does it make logical sense?), business rules, and security (no unsafe or injected content) - not just whether the output "looks right."

What should happen when a model returns invalid output?

A production workflow detects the specific failure, sends a repair prompt with the validation errors and required schema, retries the original task with stronger instructions if repair fails, and falls back to a safe default or human review after a limited number of attempts.

Can prompt instructions alone guarantee valid structured output?

No. Clear format instructions greatly improve reliability, but a language model is not a guaranteed format generator. Every structured response should still be checked with a real parser, schema validator, or compiler before being used in an application.