CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 1 · Lesson 1/56

    Prompting for formatted LLM output and structured outputs on Databricks

    Design a prompt that elicits a specifically formatted response

    20 min read
    2.33% of exam
    8 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Write a prompt that puts the exact output format in its instruction and constraints, with delimiters and a worked example
    • Choose between response_format types (text, json_object, json_schema) and function calling for a given format requirement
    • Design a JSON schema that stays inside what Foundation Model APIs support and that the model follows reliably
    • Parse and validate model output before downstream use, including checking finish_reason
    • Apply responseFormat in batch SQL with ai_query
    • Compare prompt versions on format compliance using a pass/fail scorer and its mean

    Key concept

    Structured outputs — Asking for a format in the prompt makes that format likely. Setting response_format on a Databricks-served chat model makes the model generate JSON that follows a schema you define. Use prompt wording on its own only when no schema can describe the output.

    1.State the exact format in the instruction and constraints

    An instruction like "Extract the customer name, issue category, and urgency as JSON" leaves the model to decide how much of its reply is JSON. On some tickets it returns a bare object. On others it writes a sentence of explanation with a JSON snippet inside, and the downstream json.loads call fails. A format the prompt never spells out is one the model is free to vary, so the first fix is to spell it out: name the structure you want, in words the parser would accept.

    A prompt has four parts: role, instruction, context and constraints (see Anatomy of an adjusted prompt (role, instruction, context, constraints)). The format specification goes in the instruction and the constraints. The instruction says what artifact to produce. The constraints list the rules that artifact must meet. A complete specification contains:

    • The exact keys or section labels, spelled the way the consumer expects them (customer_name, issue_category, urgency, or Diagnosis:, Root Cause:, Next Steps:), and the order they come in.
    • Delimiters around the input data, so the model can tell material to process from instructions to follow. The Databricks product-extraction example wraps the text in <description> tags.
    • Hard rules as a bulleted constraint list. The MLflow summarizer template ends with "Your summary should:" followed by bullets such as "Contain exactly {{num_sentences}} sentences".
    • One or two worked examples, each an input paired with output in exactly the target format.

    Put the specification in the system message, not the user turn. A system (or developer) message stays fixed however the user words the question, so a support agent that must always answer with Diagnosis, Root Cause and Next Steps in that order keeps the template even when a user writes three rambling paragraphs. Relying on the user's phrasing to suggest a structure produces as many structures as there are phrasings.

    Several plausible-sounding fixes leave the format unchanged. Raising temperature adds randomness, which is the opposite of what a parser needs. max_output_tokens is an upper bound on how many tokens the reply may use, so it decides how long the reply can get, not how it is laid out. A closing reminder to "be thorough and organized" names no labels and no order. Asking the model to reason step by step improves the reasoning, but any reasoning it writes out is extra text around the JSON. Sending the input twice adds context without adding a single word about format.

    Few-shot examples are the strongest lever when schema enforcement isn't available (the general technique is covered in Few-shot examples, chain-of-thought and generation parameters). Examples matter most for text templates no JSON schema can describe, such as a labeled Diagnosis / Root Cause / Next Steps answer, and for models that don't accept response_format. One filled-in example shows the labels, their order, their punctuation and how long each part runs, which a description alone rarely pins down.

    Formatting that comes only from the prompt still drifts. The same prompt can come back with a different structure on another run, and a prompt tuned for one model may not hold on the next. Databricks' own guidance on Genie Code says so plainly: "The structure and detail that Genie Code provides varies from time to time, even for the same prompt." When a program consumes the output, treat the prompt specification as the first layer and enforce the format at the API as well.

    Checkpoint 1 of 9· Check yourself

    A ticket-extraction prompt puts the exact keys, their order and two ticket-to-JSON examples in the system message. It parses cleanly in testing, and a program will consume its output in production. What should the team expect and do next?

    Checkpoint 2 of 9· Exam question

    A team is building a pipeline that sends customer support tickets to an LLM and expects a JSON object with the keys customer_name, issue_category, and urgency so a downstream Python script can parse the result reliably. The zero-shot instruction "Extract the customer name, issue category, and urgency as JSON" sometimes produces valid JSON and sometimes produces prose with an embedded JSON snippet. Which change to the prompt design would most reliably fix the downstream parsing failures?

    Checkpoint 3 of 9· Exam question

    A support-agent application must always answer using the same template, with the labeled sections "Diagnosis:", "Root Cause:", and "Next Steps:" in that order, regardless of how the user phrases their question. Which prompt design approach best guarantees this consistent section structure across varied user inputs?

    Sources12345

    2.Enforce JSON with response_format

    response_format moves the format from a request in the prompt to a parameter of the API call. You set it on any supported chat model served through Foundation Model APIs, on both pay-per-token and provisioned throughput endpoints. The request looks the same whatever the provider, because Databricks translates it into each provider's native mechanism. The same field accepts three output types.

    The three response_format types and when each fits
    typeWhat comes backUse when
    textOrdinary text, the same as omitting the fieldFree-form answers or labeled text templates, where few-shot examples carry the format
    json_objectA JSON object whose keys the model choosesYou need valid JSON but the schema is not known beforehand
    json_schemaJSON that follows the schema you supply, with strict set to TrueA downstream program expects specific keys and types: document extraction, batch inference, turning unstructured data into structured data
    json_object: the keys are named only in the prompt, and the input sits inside description tags as delimiterspython
    response_format = {
          "type": "json_object",
        }
    
    messages = [
          {
            "role": "user",
            "content": "Extract the name, size, price, and color from this product description as a JSON object:\n<description>\nThe SmartHome Mini is a compact smart home assistant available in black or white for only $49.99. It's 5 inches wide.\n</description>"
          }]
    json_schema: the schema itself names every key and typepython
          "type": "json_schema",
          "json_schema": {
            "name": "research_paper_extraction",
            "schema": {
              "type": "object",
              "properties": {
                "title": { "type": "string" },
                "authors": {
                  "type": "array",
                  "items": { "type": "string" }
                },
                "abstract": { "type": "string" },
                "keywords": {
                  "type": "array",
                  "items": { "type": "string" }
                }
              },
            },
            "strict": True
          }

    In the json_object call, only the prompt tells the model which keys to produce: name, size, price and color. You are guaranteed JSON but not those keys. With json_schema, the keys and their types come from the schema. The research-paper example still keeps a short system message describing the task, so the prompt and the schema reinforce each other. Enforcement also costs tokens: Databricks adds its own instructions behind the scenes to improve structured-output quality, and the extra input and output tokens are billed. (The documentation calls this "prompt injection", meaning the platform's own additions, not an attack.)

    Function calling also constrains output with a JSON schema, but it does a different job. You describe functions in the tools parameter. The model decides whether to call one, and if it does, it returns a JSON object of arguments for your code to run. You then send the result back to the model so it can summarize the answer for the user. Use it for assistants that take actions or call APIs, such as send_email or get_customers. For batch inference or for turning unstructured text into structured records, Databricks recommends structured outputs, which always produce JSON in your schema instead of a call the model may or may not make.

    Extra structured-output constraints for Claude models on Databricks
    ConstraintConsequence
    Only json_schema is supportedA json_object request is not supported. For unconstrained output, omit response_format
    No streaming with structured outputsSet stream to false whenever response_format is set
    No tools alongside response_formatresponse_format cannot be combined with tools or tool_choice
    databricks-claude-opus-5-5, databricks-claude-sonnet-5-5, databricks-claude-haiku-5-5, databricks-claude-fable-5-1response_format on the Chat Completions API returns HTTP 400. For Opus 5.5, Sonnet 5.5 and Haiku 5.5, use the format field of output_config on the Anthropic Messages API
    databricks-claude-opus-5May return finish_reason content_filter when it declines, and the output then might not match the schema

    Checkpoint 4 of 9· Fill the gap

    This product-extraction request should come back as valid JSON. No schema is defined beforehand, and only the prompt names the keys. Which type value completes the request?

    response_format = {
          "type": " ? ",
        }
    
    messages = [
          {
            "role": "user",
            "content": "Extract the name, size, price, and color from this product description as a JSON object:\n<description>\nThe SmartHome Mini is a compact smart home assistant available in black or white for only $49.99. It's 5 inches wide.\n</description>"
          }]

    Sources56

    3.Design a JSON schema the model can follow

    Foundation Model APIs accept most of the structured outputs OpenAI accepts, but only a subset of JSON Schema, and they reject the rest on purpose. Simpler schemas produce higher-quality JSON, so the supported subset leaves out the constructs that make generation worse. A schema that follows these rules is one the model can actually fill in.

    Neither keyword does what you wanted. pattern (regular expressions) is not supported. Length and size keywords such as maxLength, maxProperties and minProperties are not enforced for objects and arrays. To limit an abstract to a few sentences, put the rule in the prompt's constraints and check it in post-processing. The full set of design rules:

    • Flatten. Heavily nested schemas lower generation quality. Promote fields to the top level instead of nesting them inside objects within objects.
    • Stay under 64 keys. That is the maximum number of keys a schema may specify.
    • Skip composition. anyOf, oneOf, allOf, prefixItems and $ref are not supported. Write one concrete object instead of a union of alternatives.
    • One type per field. A list of types is allowed only in one case: a single valid JSON type paired with "null", for a field that may be absent.
    • Give fixed-value fields their allowed values in the prompt. A field like sentiment (negative, positive or neutral) or urgency is easiest for the model when the instruction lists the permitted values. That keeps the field a plain string, which the schema subset supports.

    In practice, write a flat object of strings, numbers and simple string arrays, like the research-paper schema with its title, authors, abstract and keywords. Then let the prompt carry the rules the schema can't express.

    Checkpoint 5 of 9· Check yourself

    You are reviewing a draft json_schema for a support-ticket extraction job on Foundation Model APIs. Which proposed schema element will the API accept?

    Sources5

    4.Parse and validate the response before using it

    Whatever the model returns arrives as text, so the step right after the LLM call must turn that text into a structured object and confirm it is valid. In a LangChain-style chain that component is the output parser (see chain components). It is set up with the target schema and turns the raw response into a validated object with fields such as title, author and year, ready to write to a table. The components it is easily confused with do other jobs. A retriever adds context to the LLM's input. A memory component stores conversation turns. A second prompt template rewords the question. None of them looks at the response.

    Databricks' RAG guidance frames this as post-processing: after generation, "it is often necessary to apply post-processing techniques or guardrails to ensure that the output meets the desired format, style, and content requirements." For structured output it names libraries such as Instructor or Outlines as starting points for this validation step. It also warns that the step should tolerate small variations in the response while still enforcing the required format.

    response_format doesn't remove the need to parse. In ai_query, a json_schema response comes back as a JSON string. The databricks-gpt-oss-20b model returns content as a list of blocks, so you take the block whose type is "text" and parse that. Some models add a further check. databricks-claude-opus-5 can set finish_reason to content_filter when it declines a structured-output request, and the output then might not match the schema. Check finish_reason before parsing, and decide in advance what happens to a reply that fails validation: return a default response or send it to a person for review.

    Checkpoint 6 of 9· Check yourself

    A nightly batch job sends documents to databricks-claude-opus-5 with a strict json_schema response_format, and a few rows fail when they are loaded into the table. What should the code right after the LLM call do?

    Checkpoint 7 of 9· Exam question

    An engineer is assembling a LangChain-style chain: a prompt template feeds an LLM, and the raw text response must become a validated Python object with fields title, author, and year before being written to a table. Which chain component should the engineer add immediately after the LLM call to reliably convert the model's text response into that structured object?

    Sources475

    5.Apply the same format in batch with ai_query

    Batch extraction across a table is where a strict format pays off most, because one malformed row can break every downstream join. ai_query takes a responseFormat argument for chat foundation models. It requires Databricks Runtime 15.4 LTS or above, and the general batch pattern is covered in batch inference with ai_query(). You can give the format either as a DDL-style string, as below, or as a JSON string with the type text, json_object or json_schema.

    DDL-style responseFormat: the STRUCT describes the same research-paper fields as the JSON schemasql
    SELECT ai_query(
        "system.ai.gpt-oss-20b",
        "Extract research paper details from the following abstract: " || abstract,
        responseFormat => 'STRUCT<research_paper_extraction:STRUCT<title:STRING, authors:ARRAY<STRING>, abstract:STRING, keywords:ARRAY<STRING>>>'
    )
    FROM research_papers;

    The DDL form suits SQL authors, since STRUCT and ARRAY<STRING> match the column types the result will land in. The JSON-schema form lets you reuse the same schema object from a Python serving call. Either way, the schema rules from the previous section still apply.

    Checkpoint 8 of 9· Fill the gap

    This SQL query should load every row of research_papers as a record with the same title, authors, abstract and keywords fields used by the Python serving call. Which ai_query argument name goes in the blank?

    SELECT ai_query(
        "system.ai.gpt-oss-20b",
        "Extract research paper details from the following abstract: " || abstract,
         ?  => 'STRUCT<research_paper_extraction:STRUCT<title:STRING, authors:ARRAY<STRING>, abstract:STRING, keywords:ARRAY<STRING>>>'
    )
    FROM research_papers;

    Sources7

    6.Measure format compliance across prompt versions

    A prompt change that seems to fix formatting is only a hypothesis until you score it across a dataset. Compliance is a pass/fail property of each output: it parses and validates against the schema, or it has exactly the required sentences or sections, or it doesn't. The proportion of outputs that pass is the number to compare. With prompts kept as numbered versions in the registry (prompt version control), you can run each version over the same dataset and compare that proportion.

    A boolean pass/fail judge for one format rule: exactly two sentencespython
    sentence_count_judge = make_judge(
        name="sentence_count_compliance",
        instructions="""Evaluate if this summary follows the 2-sentence requirement.
    
    Summary: {{ outputs }}
    
    Count the sentences carefully. Return true if the summary has exactly 2 sentences, and false otherwise.""",
        feedback_value_type=bool,
    )

    Make the scorer boolean, as Databricks recommends for pass/fail judges. MLflow averages boolean feedback, so sentence_count_compliance/mean is the pass rate. In the Databricks example, version 1 is just "Summarize this text: {{content}}". Version 2 adds an expert role, a guideline list and a stated two-sentence requirement. Each version runs through mlflow.genai.evaluate in its own MLflow run, with Correctness scored next to the compliance judge, so a version that wins on format can't hide a loss on content. The prediction function calls the model at temperature=0.1, which keeps sampling noise from muddying the comparison. For JSON output, the pass/fail question is whether the output parses and validates against your schema. That check is a good candidate for a custom scorer.

    Checkpoint 9 of 9· Fill the gap

    You want sentence_count_compliance/mean to read as a pass rate that you can compare across prompt version 1 and version 2. Which value completes the judge definition?

    sentence_count_judge = make_judge(
        name="sentence_count_compliance",
        instructions="""Evaluate if this summary follows the 2-sentence requirement.
    
    Summary: {{ outputs }}
    
    Count the sentences carefully. Return true if the summary has exactly 2 sentences, and false otherwise.""",
        feedback_value_type= ? ,
    )

    Sources8

    Sources

    (8)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Specify the structure of the response you want.”
      ↩︎ State the exact format in the instruction and constraints
      “The structure and detail that Genie Code provides varies from time to time, even for the same prompt.”
      ↩︎ State the exact format in the instruction and constraints
    2. 2.
      “An upper bound for the number of tokens that can be generated for a response”
      ↩︎ State the exact format in the instruction and constraints
      “A system (or developer) message inserted into the model's context.”
      ↩︎ State the exact format in the instruction and constraints
      “0 is deterministic and higher values introduce more randomness.”
      ↩︎ Exam trap 1
      “0 is deterministic and higher values introduce more randomness.”
      ↩︎ Prediction
    3. 4.
      “Recognize that prompts often do not transfer seamlessly across different language models.”
      ↩︎ State the exact format in the instruction and constraints
      “it is often necessary to apply post-processing techniques or guardrails to ensure that the output meets the desired format, style, and content requirements.”
      ↩︎ Parse and validate the response before using it
      “libraries such as Instructor or Outlines provide good starting points to implement this kind of validation step”
      ↩︎ Parse and validate the response before using it
      “implement mechanisms to gracefully deal with cases where the step encounters an issue or fails to generate a satisfactory response”
      ↩︎ Parse and validate the response before using it
    4. 5.
      “Extract the name, size, price, and color from this product description as a JSON object:”
      ↩︎ State the exact format in the instruction and constraints
      “They work with any supported chat model through a response_format field.”
      ↩︎ Enforce JSON with response_format
      “You can choose to generate text, unstructured JSON objects, and JSON objects that adhere to a specific JSON schema.”
      ↩︎ Enforce JSON with response_format
      “Prompt injection and other techniques are used to enhance the quality of structured outputs.”
      ↩︎ Enforce JSON with response_format
      “A request that specifies a response_format for these models returns an HTTP 400 error.”
      ↩︎ Enforce JSON with response_format
      “Structured outputs are not supported with streaming. Set stream to false when you specify a response_format.”
      ↩︎ Enforce JSON with response_format
      “using a simpler JSON schema for JSON schema definitions results in higher quality JSON generation”
      ↩︎ Design a JSON schema the model can follow
      “Heavily nested JSON schemas result in lower quality generation. If possible, try flattening the JSON schema for better results.”
      ↩︎ Design a JSON schema the model can follow
      “The maximum number of keys specified in the JSON schema is 64.”
      ↩︎ Design a JSON schema the model can follow
      “Regular expressions using pattern.”
      ↩︎ Design a JSON schema the model can follow
      “identifying and classifying product review feedback as negative, positive or neutral”
      ↩︎ Design a JSON schema the model can follow
      “this model returns content as a list of blocks”
      ↩︎ Parse and validate the response before using it
      “Structured outputs on Databricks let you generate responses in a defined JSON format as part of your AI application workflows.”
      ↩︎ Key concept
      “Only the json_schema structured output type is supported. json_object is not supported.”
      ↩︎ Exam trap 2
      “Foundation Model APIs does not enforce length or size constraints for objects and arrays.”
      ↩︎ Exam trap 4
      “In that case, the output might not conform to the schema. Check finish_reason before you parse the output.”
      ↩︎ Exam trap 5
      “Lists of types except for the special case of [type, “null”] where one type in the list is a valid JSON type”
      ↩︎ Checkpoint
      “In that case, the output might not conform to the schema. Check finish_reason before you parse the output.”
      ↩︎ Checkpoint
    5. 6.
      “The model decides whether or not to call the defined functions.”
      ↩︎ Enforce JSON with response_format
      “it creates a JSON object that users can use to call the functions in their code”
      ↩︎ Enforce JSON with response_format
      “For batch inference or data processing tasks, like converting unstructured data into structured data. Databricks recommends using structured outputs.”
      ↩︎ Exam trap 3
    6. 7.
      “Requires Databricks Runtime 15.4 LTS or above. Only available for querying chat foundation models.”
      ↩︎ Apply the same format in batch with ai_query
      “Ensure that the output conforms to a specific schema for easier downstream processing using responseFormat.”
      ↩︎ Apply the same format in batch with ai_query
      “Three JSON string types of response format are supported:text, json_object, json_schema”
      ↩︎ Apply the same format in batch with ai_query
    7. 8.
      “Databricks recommends feedback_value_type=bool for pass/fail judges.”
      ↩︎ Measure format compliance across prompt versions
      “MLflow aggregates boolean feedback into an average, so you get a pass rate to compare versions on”
      ↩︎ Measure format compliance across prompt versions
      “v2: Added comprehensive fact coverage with 2-sentence requirement”
      ↩︎ Measure format compliance across prompt versions

    Spotted a mistake, or was something unclear? Tell us.