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.
| Gap in the baseline | What to write down | Constraint added to the prompt |
|---|---|---|
| Length | Summary runs to a paragraph; target is a fixed sentence count | Contain exactly {{num_sentences}} sentences |
| Scope | Summary repeats minor details | Include only the most important information |
| Tone | Summary editorializes | Be written in a neutral, objective tone |
| Register | Casual output for a formal source | Maintain 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.
Each gap (length, scope, tone or register) needs its own fix. Once you have named the gap precisely, you know which line to add. Editorializing is a tone problem. Casual output for a formal source is a register problem, even though both concern how the summary sounds.
“Include only the most important information - Be written in a neutral, objective tone - Maintain the same level of formality as the original text”Source: docs.databricks.com
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.
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.
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?
This is a format gap. Asking for nice formatting or terse answers still gets you free text that a parser can break on. Naming a JSON object with fields, keeping the input inside delimiter tags and enforcing JSON with response_format gives the parser output it can read.
“Extract the name, size, price, and color from this product description as a JSON object:”Source: docs.databricks.com
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?
Correct answer: A — Tell the model to return only a JSON object with the keys product_name (string) and price (number), such as {"product_name": "blender", "price": 39.99}, and add one sample review paired with its expected output in that same format.
- A. Correct. Requiring a JSON object with named, typed keys gives the model a precise target and gives the Python function a format that a standard JSON parser reads directly. The sample review with its expected output shows the exact shape, which discourages replies like 'The product is a blender priced at $39.99'.
- B. Incorrect. A Markdown table row is a presentation format, not a defined data-exchange format. The model may add a header row, a separator line such as
|---|---|, or a lead-in sentence. A product name containing a pipe character would also shift the columns. Any of these breaks a parser that must work without errors. - C. Incorrect. A bare comma-separated line has no field names and no escaping. A product name that contains a comma, such as 'Blender, 600W', splits into extra fields and gives the parser the wrong price. The format has no schema to check the output against, so malformed replies go unnoticed until parsing fails.
- D. Incorrect. Underscore markers only label where a value starts and ends. They do not define a structure, and the model can still wrap the markers in extra prose or reorder them. The parser has to guess which marked value is the name and which is the price. A product name that itself contains underscores would also confuse the scan.
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.
| Technique | Closes this gap | Typical case |
|---|---|---|
| Few-shot examples | Format, style or content the model can't infer from an instruction | Classifier invents labels outside the allowed set |
| Chain-of-thought | Wrong answers on complicated, multi-step questions | Word problems with dependent calculations |
| temperature | Too much randomness in the generated text | Unstable output across repeated runs |
| max_tokens | Responses that run past a hard length limit | Capping 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?
Inventing labels is a format gap. Few-shot examples that cover every category show the model the output you want, and an explicit allowed-label rule closes the set. Chain-of-thought addresses reasoning, sampling parameters only change randomness and length, and extra context or a confidence score does not stop the model from inventing labels.
“Include examples of well-formed queries and their corresponding ideal responses within the prompt template itself (few-shot learning).”Source: docs.databricks.com
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?
Correct answer: A — Instruct the model to write out each intermediate calculation in order, then give the numeric result.
- A. Having the model write out each intermediate calculation before the result is chain-of-thought prompting. The model produces and builds on the dependent steps instead of jumping to a conclusion, which is what the team wants for multi-step problems.
- B. This is few-shot prompting, but the examples go straight from question to numeric result. The model learns to imitate that format and still answers without working, so no reasoning steps appear before the result.
- C. Taking the most frequent of several sampled results is a voting technique. Here it only collects bare results, so the model still shows no reasoning before its answer. The team needs visible intermediate steps, and sampling more results does not supply them.
- D. Rephrasing the problem only changes how the input is worded. The model still has to do all the dependent calculations in one jump, and nothing in the output shows the intermediate steps the team wants.
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?
Correct answer: A — Add a few labeled example emails for each category to the prompt, and tell the model to return exactly one of billing, technical or other as its answer for the email.
- A. Correct. Examples for each category show the model what an acceptable answer looks like. The instruction to return exactly one of
billing,technicalorothernames the only permitted outputs. Together they limit the output to the three routing labels, which prevents invented labels such asaccountorfeedback. - B. Incorrect. Asking for the best-fitting category word and nothing else controls the format of the reply but does not name the allowed values.
accountandfeedbackremain valid single-word answers, and nothing ties the reply tobilling,technicalorother. - C. Incorrect. Temperature controls how random the word choice is, not which labels are permitted. The most probable word for an email can still be
accountorfeedback, so the routing logic still receives labels it does not recognize. - D. Incorrect. A structured reply with a confidence score gives the routing code something to filter on. An invented label such as
accountcan still come back with high confidence and pass the threshold, so the output is not limited to the three labels the routing logic recognizes.
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.
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.
# 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}")A longer prompt that spells out the target: precise, factual answers with no extra commentary, a single clear statement, a stated expected format with examples ("Tokyo" for Japan), and rules for questions with several parts. In other words, it adds the same parts a careful engineer adds by hand: instruction, constraints and examples.
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= ? ,
)With feedback_value_type=bool, each verdict is a pass or a fail, and MLflow averages those verdicts into a pass rate that you can compare across prompt versions. The judge's instructions already ask it to return true or false, so a boolean type matches.
Source: docs.databricks.comCheckpoint 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?
The comparison only shows which prompt is better when everything except the prompt stays the same. If you change the dataset or the scorers between runs, the gap you measure no longer comes from the prompt alone.
“Use consistent datasets: Evaluate all versions against the same data for fair comparison.”Source: docs.databricks.com
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/mlflow3/genai/tutorials/examples/prompt-optimization-quickstartOfficial docs
“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.
“In the following example, the model doesn't output in a Markdown format.”
↩︎ Diagnosing how the baseline misses the target - 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.https://docs.databricks.com/aws/en/mlflow3/genai/prompt-version-mgmt/prompt-registry/evaluate-promptsOfficial docs
“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.
“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.https://docs.databricks.com/aws/en/mlflow3/genai/prompt-version-mgmt/prompt-registry/automatically-optimize-promptsOfficial docs
“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
“Extract the name, size, price, and color from this product description as a JSON object:”
↩︎ Exam trap 1“Extract the name, size, price, and color from this product description as a JSON object:”
↩︎ Checkpoint- https://docs.databricks.com/aws/en/mlflow3/genai/prompt-version-mgmt/prompt-registry/create-and-edit-promptsOfficial docs
“Include only the most important information - Be written in a neutral, objective tone - Maintain the same level of formality as the original text”
↩︎ Checkpoint