CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 3 · Lesson 19/56

    Adjusting an LLM response from baseline to desired output

    Create a prompt that adjusts an LLM's response from a baseline to a desired output

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

    What you will be able to do

    • Describe how a baseline response falls short in tone, length, scope or structure before changing the prompt
    • Rewrite a baseline prompt with a role, a precise instruction, delimited context and explicit constraints
    • Choose between few-shot examples, chain-of-thought and generation parameters for a given gap
    • Register baseline and adjusted prompts as versions, compare them with mlflow.genai.evaluate, and let mlflow.genai.optimize_prompts propose a better version

    Key concept

    Baseline-to-target prompt iteration — Start from a minimal baseline prompt, name exactly how its output misses the target, change the prompt to close that specific gap, and confirm the change with an evaluation instead of judging it by eye.

    1.Diagnosing how the baseline misses the target

    Before you change a prompt, write down exactly how the current output differs from the one you want. A baseline is the response a minimal prompt produces, for example classify this: {{query}} or Answer this question: {{question}}. Its failures are rarely about being plain wrong. Usually the response is too long, in the wrong tone, covers too much or too little, or comes back in a shape the next step cannot use. Each of those gaps needs a different fix, so a vague verdict like "the answer is bad" gives you nothing to edit.

    That classifier is a gap in structure and scope. The target is one word from a fixed set of five, with no explanation. Writing it that precisely already tells you what the new prompt needs: the allowed labels and a ban on extra text. A Q&A prompt can fail on a different axis. The answer is correct, but the downstream page renders Markdown and the model returns plain prose, so the gap there is formatting alone.

    Find gaps by looking at the inputs your application handles worst, not at average cases. For each of those inputs, write the gold-standard response you wanted next to the one you got. The difference between the two is your diagnosis, and those gold responses become reusable material for examples and evaluation later on.

    Common baseline gaps and the constraint line that closes each one (lines from a revised summarization prompt)
    Gap in the baselineWhat to write downConstraint added to the prompt
    LengthSummary runs to a paragraph; target is a fixed sentence countContain exactly {{num_sentences}} sentences
    ScopeSummary repeats minor detailsInclude only the most important information
    ToneSummary editorializesBe written in a neutral, objective tone
    RegisterCasual output for a formal sourceMaintain the same level of formality as the original text

    Checkpoint 1 of 8· Match them up

    Each of these summaries misses its target in a different way. Match each diagnosed gap to the constraint line that fixes it.

    Tap a term, then the definition that fits it.

    Sources123

    2.Anatomy of an adjusted prompt

    An adjusted prompt has four parts, and each one fixes a different kind of gap. The role ("You are an expert summarizer.") sets voice and expertise. The instruction states the task in measurable terms. The context is the input the model works on, kept in its own labelled slot. The constraints are the rules your diagnosis produced. Template variables in {{double braces}} fill the context at inference time. They can also carry extra values such as the current date or user context, which is the subject of augmenting a prompt from user input.

    Version 2 of a summarization prompt: role, emphasized instruction, guideline constraints, then a labelled content slotpython
    prompt_v2 = mlflow.genai.register_prompt(
        name=PROMPT_NAME,
        template="""You are an expert summarizer. Create a summary of the following content in *exactly* 2 sentences (no more, no less - be very careful about the number of sentences).
    
    Guidelines:
    - Include ALL core facts and key findings
    - Use clear, concise language
    - Maintain factual accuracy
    - Cover all main points mentioned
    - Write for a general audience
    - Use exactly 2 sentences
    
    Content: {{content}}
    
    Summary:""",
        commit_message="v2: Added comprehensive fact coverage with 2-sentence requirement"
    )

    Compare it with the version 1 baseline, Summarize this text: {{content}}. The rewrite uses three techniques to make sure the most important rule is followed. Emphasis: the sentence count is in italics, explained ("no more, no less") and repeated as the final guideline. Delimiting: a Guidelines: header sets the rules apart, and Content: and Summary: labels separate the input from the place where the answer starts. Specificity: "exactly 2 sentences" can be checked, while "be brief" cannot.

    Placement also matters. Genie Agents give a concrete rule: put clarification instructions at the end of the general instructions so Genie gives that behavior priority. Summary rules go in a dedicated section at the end, under its own heading. The general lesson is to give the instruction that matters most its own labelled block in a deliberate position, rather than burying it in the middle of a paragraph.

    Delimiters also keep input data separate from instructions. When a pipeline needs machine-readable output, ask for the exact format and wrap the source text in tags. A plain request such as "extract the product name and price" invites a prose sentence back. Instructions like "format it nicely", "one field per line" or "answer in few words" still produce free text that a parser can break on. Stating a JSON object with named fields and showing one correctly formatted example closes the gap. On Foundation Model APIs, response_format can also enforce JSON. Format design in depth belongs to designing a prompt for a formatted response.

    Asking for a JSON object, with the input fenced in description tags and JSON enforced by response_formatpython
    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>"
          }]

    Checkpoint 2 of 8· Check yourself

    A pipeline sends product descriptions to a Foundation Model API with the prompt "extract the product name and price", and the downstream parser keeps failing on the prose it gets back. Which revision closes the gap?

    Checkpoint 3 of 8· Exam question

    A developer needs an LLM step in a pipeline to return machine-readable output so a downstream Python function can parse it without errors. With a plain instruction such as Extract the product name and price from this review, the model sometimes returns a sentence like 'The product is a blender priced at $39.99' instead of structured data. Which prompt design change best guarantees the desired structured output?

    Sources453

    3.Few-shot examples, chain-of-thought and generation parameters

    Some gaps survive even a well-written instruction. Each of the next three tools fits a particular kind of gap.

    Few-shot examples show the model what you want instead of only describing it. Put a few example inputs, each paired with its ideal response, inside the template. The model picks up format, style and content from them. This is the fix when a zero-shot classifier makes up labels outside the allowed set. Give a handful of labelled examples that cover every category, and state plainly that the output must be exactly one of the allowed labels. The training data for an abstract classifier does this by attaching the same rule to every record: "Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'". Choose examples from the query types your chain struggles with, and make them varied enough to represent real traffic. A larger context window or a confidence score attached to the output does not stop the model from inventing a new label.

    Chain-of-thought (CoT) is for gaps in reasoning, not formatting. If a tutoring prompt asks only for the final number, the model has to do several dependent calculations at once and often gets them wrong. Asking it to work through the problem step by step and explain its reasoning before giving the answer splits the question into sequential steps. That tends to produce more detailed and better-reasoned answers on multi-step or open-ended questions. Restating the problem word for word, translating it, or demanding a single-number reply does not add reasoning steps. The last one actually removes the room the model needs to reason.

    Generation parameters control how the model samples, not what it is asked. temperature sets how random the output is, and max_tokens caps how long a response can be. The evaluation harness for the summarization prompts calls the model with temperature=0.1, which keeps outputs stable when comparing prompt versions. The best settings depend on the task, the prompt and the style you want, so tune them through evaluation. Note that max_tokens cuts a response off at the limit. It does not make the model write a complete two-sentence summary, so set length targets in the instruction.

    Which adjustment closes which kind of gap
    TechniqueCloses this gapTypical case
    Few-shot examplesFormat, style or content the model can't infer from an instructionClassifier invents labels outside the allowed set
    Chain-of-thoughtWrong answers on complicated, multi-step questionsWord problems with dependent calculations
    temperatureToo much randomness in the generated textUnstable output across repeated runs
    max_tokensResponses that run past a hard length limitCapping cost or response size

    Checkpoint 4 of 8· Check yourself

    Your zero-shot classifier for abstract sentences keeps returning labels such as "FINDINGS" and "INTRODUCTION", which are not among the five labels your pipeline allows. Which change to the prompt fixes this?

    Checkpoint 5 of 8· Exam question

    A team is prompting an LLM to solve multi-step word problems for a tutoring app. The baseline prompt just asks for the final numeric answer, and the model frequently arrives at incorrect results on problems involving several dependent calculations. The team wants the model to reliably show its reasoning steps before giving the final answer, since this has been shown to improve accuracy on multi-step problems. Which prompting technique directly targets this goal?

    Checkpoint 6 of 8· Exam question

    A prompt engineer is building a classifier prompt that asks an LLM to label incoming emails as billing, technical, or other. With a zero-shot instruction alone, the model occasionally invents new labels like account or feedback that break the downstream routing logic, which only recognizes the three defined categories. Which change to the prompt is most effective at keeping the model's output within the desired fixed label set?

    Sources31

    4.Measuring and auto-optimizing prompt versions with MLflow

    A rewrite that looks better on a few samples might not help across real inputs, so measure it. Start by registering the baseline and the adjusted template as two versions of the same prompt. The mechanics of the registry are covered in MLflow Prompt Registry versioning. Here, versions give you two fixed URIs, prompts:/<name>/1 and prompts:/<name>/2, that a prediction function can load. Write commit messages that record what each change was for, such as "v2: Added comprehensive fact coverage with 2-sentence requirement".

    Next, turn the diagnosis into scorers. Build an evaluation dataset of inputs, each with the expected facts a good summary should include. Then run mlflow.genai.evaluate once per version, using the same data and the same scorers. Correctness() checks whether the expected facts are present. A custom judge built with make_judge checks the specific gap you targeted. With feedback_value_type=bool, MLflow averages the pass/fail results into a pass rate, reported as a metric like sentence_count_compliance/mean, so the two versions can be compared directly. If you change the dataset between runs, the comparison no longer tells you which prompt is better.

    A pass/fail judge that scores exactly the gap version 2 was written to closepython
    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,
    )

    After you can measure, MLflow can propose new versions for you. mlflow.genai.optimize_prompts(), in Beta and requiring MLflow 3.5.0 or later, takes a prediction function, training data with expected outputs, the prompt URIs and scorers. Its GepaPromptOptimizer improves the prompt over several rounds. A reflection model reviews the scored results and rewrites the prompt. The optimized prompt is automatically registered as a new version in the Prompt Registry, so you can evaluate it the same way as a hand-written version. If the scorer is categorical (for example, a Markdown-quality judge returning high, medium or low), pass an aggregation function that converts the feedback into a numeric score.

    Optimizing the bare classification prompt against labelled training data with GEPApython
    # Optimize the prompt
    result = mlflow.genai.optimize_prompts(
        predict_fn=predict_fn,
        train_data=dataset,
        prompt_uris=[prompt.uri],
        optimizer=GepaPromptOptimizer(reflection_model="databricks:/databricks-claude-sonnet-4-5"),
        scorers=[Correctness(model="databricks:/databricks-gpt-5")],
    )
    
    # Use the optimized prompt
    optimized_prompt = result.optimized_prompts[0]
    print(f"Optimized template: {optimized_prompt.template}")

    Checkpoint 7 of 8· Fill the gap

    This judge scores only the gap that version 2 was written to close. You want MLflow to average its verdicts into a pass rate, such as sentence_count_compliance/mean, so you can compare versions 1 and 2 directly. Which value completes the judge?

    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= ? ,
    )

    Checkpoint 8 of 8· Check yourself

    You have registered a bare summarization prompt as version 1 and a rewritten one as version 2. What makes the measured difference between them trustworthy?

    Sources46

    Sources

    (8)

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

    1. 1.
      “you want the model to output one word from a choice of five words. It should only output that word without any further explanation.”
      ↩︎ Diagnosing how the baseline misses the target
      “Classification label must be 'CONCLUSIONS', 'RESULTS', 'METHODS', 'OBJECTIVE', 'BACKGROUND'”
      ↩︎ Few-shot examples, chain-of-thought and generation parameters
      “While accurate, it's not aligned to any task or use case you're looking for.”
      ↩︎ Prediction
    2. 2.
      “In the following example, the model doesn't output in a Markdown format.”
      ↩︎ Diagnosing how the baseline misses the target
    3. 3.
      “One useful way to come up with good examples is to identify types of queries your chain struggles with.”
      ↩︎ Diagnosing how the baseline misses the target
      “This could be variables such as current date, user context, or other relevant metadata.”
      ↩︎ Anatomy of an adjusted prompt
      “This helps the model understand the desired format, style, and content of the responses.”
      ↩︎ Few-shot examples, chain-of-thought and generation parameters
      “This prompt engineering strategy breaks down complicated questions into simpler, sequential steps, guiding the LLM through a logical reasoning process.”
      ↩︎ Few-shot examples, chain-of-thought and generation parameters
      “adjusting the temperature can control the randomness of the generated text, while max_tokens can limit the response length.”
      ↩︎ Few-shot examples, chain-of-thought and generation parameters
      “Include examples of well-formed queries and their corresponding ideal responses within the prompt template itself (few-shot learning).”
      ↩︎ Exam trap 2
      “prompts often do not transfer seamlessly across different language models.”
      ↩︎ Exam trap 3
      “Include examples of well-formed queries and their corresponding ideal responses within the prompt template itself (few-shot learning).”
      ↩︎ Checkpoint
    4. 4.
      “in *exactly* 2 sentences (no more, no less - be very careful about the number of sentences)”
      ↩︎ Anatomy of an adjusted prompt
      “MLflow aggregates boolean feedback into an average, so you get a pass rate to compare versions on”
      ↩︎ Measuring and auto-optimizing prompt versions with MLflow
      “Build a dataset with expected facts that should appear in good summaries:”
      ↩︎ Measuring and auto-optimizing prompt versions with MLflow
      “Start simple: Begin with basic prompts and iteratively improve based on evaluation results.”
      ↩︎ Key concept
      “Use consistent datasets: Evaluate all versions against the same data for fair comparison.”
      ↩︎ Exam trap 4
      “Use consistent datasets: Evaluate all versions against the same data for fair comparison.”
      ↩︎ Checkpoint
    5. 5.
      “Add clarification question instructions at the end of your general instructions to help Genie prioritize this behavior when responding to ambiguous questions.”
      ↩︎ Anatomy of an adjusted prompt
      “add a dedicated section at the end of your text instructions with the heading”
      ↩︎ Anatomy of an adjusted prompt
    6. 6.
      “GEPA iteratively refines prompts using LLM-driven reflection and automated feedback, leading to systematic and data-driven improvements.”
      ↩︎ Measuring and auto-optimizing prompt versions with MLflow
      “Version Control: Automatically registers optimized prompts in MLflow Prompt Registry.”
      ↩︎ Measuring and auto-optimizing prompt versions with MLflow
      “The optimize_prompts API requires MLflow >= 3.5.0.”
      ↩︎ Measuring and auto-optimizing prompt versions with MLflow

    Also cited

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