Lesson 3 of 4 Prompt Engineering for FMs

Producing Reliable Structured Output

This lesson covers techniques that make FM output machine-readable and valid every time it feeds other software, since asking politely for JSON is not enough at production scale.

Learning outcomes

After completing this lesson, you will be able to:

  • Specify output formats precisely.
  • Enforce a JSON Schema with forced tool use.
  • Use response templates for human-readable output.

Output format specifications

When another program will read a model's output, the format must be exact: a missing field or an extra sentence before the JSON breaks the parser. The simplest technique is to state the required format precisely, for example a JSON object with named fields, their types and allowed values, or a fixed set of headed sections, ideally with an example of a correct response.

Several settings improve consistency further. A low temperature reduces variation, and a stop sequence after the closing tag prevents the model from adding commentary. Some models accept a prefilled assistant turn, in which the application writes the first characters of the response, such as {, so the model continues directly in the required format. These techniques work well but still produce occasional invalid output, so the application must validate every response and retry or repair it when validation fails; native structured output and tool use with a schema, described next, reduce this risk.

Fix the problem

Output that breaks the parser

Exam skills 1.6.5 · 5.2.3

Choose the fix for each structured output problem.

Log in to try this activity Interactive activities are free with an account.

Enforcing a JSON Schema with tool use

A more reliable approach defines a tool whose inputSchema is the desired JSON Schema and forces the model to call it with toolChoice. The model's response is then a toolUse block with arguments that follow the schema, which the application reads instead of parsing free text. Some models also offer native structured output modes that constrain generation to a schema. Even then, the application validates the result with a JSON Schema validator, because constraints and business rules (such as a total equal to the sum of line items) can still be violated.

tool = {"toolSpec": {"name": "record_invoice", "description": "Record extracted invoice fields.",
  "inputSchema": {"json": {"type": "object", "additionalProperties": False,
    "properties": {"invoice_number": {"type": "string"}, "currency": {"type": "string", "enum": ["EUR", "USD", "GBP"]},
                   "total": {"type": "number"}, "due_date": {"type": "string", "format": "date"}},
    "required": ["invoice_number", "currency", "total"]}}}}
r = brt.converse(modelId=model_id, messages=messages,
                 toolConfig={"tools": [tool], "toolChoice": {"tool": {"name": "record_invoice"}}})
fields = next(b["toolUse"]["input"] for b in r["output"]["message"]["content"] if "toolUse" in b)
jsonschema.validate(fields, tool["toolSpec"]["inputSchema"]["json"])

The following diagram shows the structured output path.

Enforcing a JSON Schema with tool use. The request defines a tool whose input schema is the required JSON Schema and forces it with toolChoice, so the model returns a toolUse block with structured arguments. A JSON Schema validator rejects remaining violations, which are retried once and otherwise routed for review.
Validation still runs because a schema cannot express every business rule.
Put in order

Schema-enforced output

Exam skills 1.6.5 · 3.1.3

Put the steps of getting schema-conforming JSON from the Converse API in order.

Log in to try this activity Interactive activities are free with an account.

Templates for human-readable responses

Responses read by people also benefit from a defined structure. Response templates specify sections, such as a summary, details, next steps and sources; a maximum length; and formatting rules suited to the channel, such as Markdown for a web chat, plain text for SMS and no tables or lists for a voice assistant, where they would be read aloud awkwardly.

Consistent templates make responses easier for users to scan, because important information is always in the same place, and easier for teams to test, because automated checks can confirm that each section is present and within its length limit. They also make different prompt or model versions easier to compare. The following table compares the approaches for structuring output.

ApproachReliabilityUse for
Format instructions and examplesGoodHuman-readable templates; simple JSON
Prefilled response startBetterModels that support prefill
Forced tool use with JSON SchemaHighMachine-readable extraction and classification
Schema validation in codeDetects all violationsAlways, as a final check
Worked example

Parser failures

An extraction pipeline asks a model to "return JSON". About 2% of responses include extra text or missing fields, breaking downstream processing.

Defining a tool with the required JSON Schema and forcing it with toolChoice makes the model return structured arguments; a JSON Schema validator then rejects any remaining violations, which are retried once and otherwise routed for review. Parser failures fall to near zero.

Check yourself

Output is produced through forced tool use with a JSON Schema. Is validation in code still needed?

Show answer

Yes. Always validate the output against the schema, because the model can still produce invalid values.

Exam Tips

Remember for the exam

  • Reliable machine-readable output: forced tool use with a JSON Schema.
  • Always validate output against the schema in code.
  • Low temperature and examples improve format consistency.
  • Use response templates for consistent human-readable answers.