Sub topic 5
Show the behavior with examples
Prose descriptions leave gaps. "Replace runs of symbols with a hyphen" sounds precise, but it doesn't say what happens to C++ & Rust, to leading spaces, or to a title that already contains hyphens. Input and output examples close those gaps. This chapter covers how to write examples, how the assistant uses them, and how to turn them into tests.
This chapter assumes you can read basic Python and run pytest. It also assumes you have read the earlier chapters on goals, context, and constraints, because examples work best when they sit next to those.
Why examples work
An assistant predicts a response from the text you give it. A sentence of prose can be read several ways. An example pair, such as slugify("C++ & Rust") -> "c-rust", can be read only one way. It fixes the exact output for one exact input.
Examples help in three ways:
- They define edge cases that are awkward to describe, such as empty input, extra whitespace, or symbols.
- They show the format of the output, including quoting, casing, and punctuation.
- They give you something to check. The same pairs that guide the assistant can become your tests.
Examples do not replace the goal and the constraints. They pin down behavior inside the limits you have already set.
A prompt with and without examples
Here is the weak prompt and the stronger one from the earlier chapters.
Weak prompt:
Write a function to clean up titles.
Stronger prompt:
Write a Python 3.10 function slugify(text: str) -> str that converts an article title into a URL slug.
Context: it will be used in a small blog tool; titles are plain ASCII.
Constraints: use only the standard library; lowercase the result; replace each run of non-alphanumeric characters with a single hyphen; no leading or trailing hyphens.
Return only the function, with no explanation.The stronger prompt is already specific. Still, a few questions remain open. Does Already-slugged keep its hyphen? Is an apostrophe in Don't removed or turned into a hyphen? Adding examples answers the questions you care about.
Examples of the expected behavior:
slugify("Hello, World!") -> "hello-world"
slugify(" Multiple spaces ") -> "multiple-spaces"
slugify("C++ & Rust") -> "c-rust"
slugify("Already-slugged") -> "already-slugged"Each example covers a different rule:
| Input | Output | Rule it pins down |
|---|---|---|
| `Hello, World!` | `hello-world` | Lowercase, punctuation becomes one hyphen, trailing symbol removed |
| ` Multiple spaces ` | `multiple-spaces` | Runs of spaces collapse, edges are trimmed |
| `C++ & Rust` | `c-rust` | A mixed run of symbols and spaces becomes one hyphen |
| `Already-slugged` | `already-slugged` | Existing hyphens are kept |
What the assistant might return
With the full prompt, a plausible response looks like this.
import re
def slugify(text: str) -> str:
text = text.strip().lower()
text = re.sub(r"[^a-z0-9]+", "-", text)
return text.strip("-")Trace C++ & Rust through it. After strip and lower, the string is c++ & rust. The regular expression [^a-z0-9]+ matches ++ & as one run, because every character in it is neither a letter nor a digit. That run becomes a single -, giving c-rust. The final strip("-") removes nothing here.
Do not assume the assistant's code is right just because it looks right. The next section shows how to check it.
Turn the examples into a test
The pairs you put in the prompt are also your first test cases. Writing them into a test file means you verify the result yourself.
import pytest
from slugify_module import slugify
@pytest.mark.parametrize(
"text, expected",
[
("Hello, World!", "hello-world"),
(" Multiple spaces ", "multiple-spaces"),
("C++ & Rust", "c-rust"),
("Already-slugged", "already-slugged"),
],
)
def test_slugify(text, expected):
assert slugify(text) == expectedSave the generated function as slugify_module.py, put the test next to it, and run pytest. All four cases should pass.
A passing test shows only that the examples work. It says nothing about inputs you did not list. So add a few cases of your own that the prompt did not mention, such as an empty string or a title made only of symbols.
import pytest
from slugify_module import slugify
@pytest.mark.parametrize(
"text, expected",
[
("", ""),
("!!!", ""),
("Don't Panic", "don-t-panic"),
("Version 2.0", "version-2-0"),
],
)
def test_slugify_extra_cases(text, expected):
assert slugify(text) == expectedThese all pass with the function above. Look at Don't Panic closely: the result is don-t-panic, which may not be what you want. If you would rather get dont-panic, that is a requirement the original prompt did not state. The fix is to add an example and let the assistant revise.
Choosing good examples
Not all examples carry equal weight. A handful of well-chosen pairs beats a long list of similar ones.
- Start with a typical case. One ordinary input shows the main behavior, such as
Hello, World!. - Add one example per edge case. Cover whitespace, symbols, empty input, and any boundary that matters for your task.
- Include a case where the input needs no change.
Already-sluggedshows that the function should leave good input alone. Without it, an assistant may transform input that was already correct. - Keep each example about one thing. If an example mixes three rules and fails, you cannot tell which rule the assistant got wrong.
- Use realistic data. Examples drawn from the real inputs your program will see steer the assistant better than invented ones.
Aim for roughly three to six examples for a small function. More is fine for complex rules, but each new example should cover something the others do not.
Showing errors and rejected input
Examples can describe failure behavior as well as success. If a function should raise an error, show it.
Examples of the expected behavior:
parse_port("8080") -> 8080
parse_port(" 443 ") -> 443
parse_port("0") -> raises ValueError
parse_port("70000") -> raises ValueError
parse_port("http") -> raises ValueErrorHere the examples tell the assistant that the valid range excludes 0 and values above 65535, that whitespace is tolerated, and that non-numeric text is an error. Writing all of that in prose would take longer and be easier to misread.
A matching test uses pytest.raises:
import pytest
from ports import parse_port
@pytest.mark.parametrize("text, expected", [("8080", 8080), (" 443 ", 443)])
def test_parse_port_valid(text, expected):
assert parse_port(text) == expected
@pytest.mark.parametrize("text", ["0", "70000", "http"])
def test_parse_port_invalid(text):
with pytest.raises(ValueError):
parse_port(text)How examples can mislead
Examples are strong signals, and that strength creates risks.
- Overfitting. The assistant may write code that handles your listed cases and nothing else, for instance with a lookup table of the exact inputs. Counter this by stating the general rule in prose as well, and by testing inputs you did not list.
- Accidental rules. If every example input is lowercase, the assistant may assume input is always lowercase. If every output is short, it may assume a length limit. Vary the examples on dimensions that should not matter.
- Contradictions. Two examples that disagree with each other, or with the written constraints, produce unpredictable results. Check your examples against each other before sending.
- Wrong examples. A typo in an expected output is treated as truth. The assistant will try to satisfy it. Work out each expected value by hand.
- Copied style. If you paste an example from existing code, the assistant may copy its naming and formatting. That is useful when you want consistency and unwanted when the old code is poor.
Examples and the other parts of the prompt
Examples fit into the prompt structure you have been building. The template from the earlier chapters places them after the constraints and before the output format.
Task: <one-sentence goal>
Context: <language and version, framework, relevant existing code, error message>
Constraints: <allowed libraries, style rules, performance limits, what not to change>
Examples: <input -> expected output pairs>
Output format: <for example, only a unified diff, or only the function>That order is deliberate. The goal says what to build. The context and constraints set the boundaries. The examples then show behavior inside those boundaries. The output format comes last and says how to deliver the result.
When an example conflicts with a constraint, the assistant has to pick one. Say which one wins if it matters: "If an example conflicts with a constraint, follow the constraint and tell me about the conflict."
The diagram shows how examples flow through the work.
When a failing test points at the example
A failing test has two possible causes: the code is wrong, or the example is wrong. Check the example first. Suppose you wrote slugify("Version 2.0") -> "version-2.0" and the function returns version-2-0. The constraints said to replace every run of non-alphanumeric characters, and . is one. The function followed your rule, and your example broke it. Decide which behavior you want, then change either the constraint or the example so they agree.
When the code is the problem, paste the failing case back to the assistant with the actual output. This is covered in the chapter on iteration.
Summary of practice
- Put three to six input and output pairs in the prompt for any function with non-obvious rules.
- Cover the typical case, each edge case, and an input that should pass through unchanged.
- Include error behavior when it matters.
- State the general rule in prose too, so the assistant does not just memorize the pairs.
- Reuse the same pairs as tests, then add cases the prompt did not list.
Exercise
You prompt an assistant to write normalize_phone(text: str) -> str, which should return only digits. You include one example: normalize_phone("555-1234") -> "5551234". The assistant returns code that removes hyphens only. A colleague's input (555) 123 4567 comes back unchanged. Which two changes to the prompt would most improve the result, and why?
Show answer
First, add the general rule in prose, such as "remove every character that is not a digit", so the assistant does not infer a narrower rule from a single example. Second, add examples for the other formats, such as normalize_phone("(555) 123 4567") -> "5551234567" and one for an empty string or already-clean input. Varying the example inputs shows that parentheses and spaces matter, and the extra cases can be reused as tests.
Exercise
A test built from your prompt examples passes, but the function still fails on a real input. Name two reasons this can happen and one action for each.
Show answer
One reason is that the examples did not cover the failing input. The action is to add that input as a new test case and a new example in the prompt. Another reason is that the assistant overfit to the listed pairs without following the general rule. The action is to state the rule in prose and test with several inputs that are not in the prompt. A wrong expected value in an example is a third possible cause, and the action there is to compute the correct value by hand.