Sub topic 8
Iterate: refine the prompt from the response
This chapter assumes you can write a basic prompt with a goal, context, constraints, and examples. It also assumes you can run tests in your language of choice. The examples use Python and pytest.
A first response is rarely the final one. Treat it as evidence about how the assistant read your prompt. Each gap between what you got and what you wanted points to something your prompt left out or left ambiguous. Iteration is the habit of reading that evidence and adjusting the prompt on purpose.
Why the first response is a diagnostic
The assistant sees only your prompt and the conversation so far. When its output misses the mark, one of four things usually happened:
- The goal was ambiguous, so it picked a reasonable but wrong interpretation.
- A piece of context was missing, so it guessed (a library version, a file layout, an existing helper).
- A constraint was absent, so it chose its own default (a third-party package, a different style).
- No example covered the case, so it handled an edge case differently from how you would.
Naming the cause tells you what to add. "Make it better" gives the assistant nothing to act on. "The function uses unicodedata, but I need standard-library re only" gives it a precise correction.
Start from a test result, not an impression
The most useful feedback is something you observed. Run the code before you reply. A failing test, an error message, or a concrete wrong output is better than "this doesn't look right," because the assistant can reason from it directly.
Suppose you asked for a slugify function and got this:
import re
def slugify(text: str) -> str:
text = text.lower()
text = re.sub(r"[^a-z0-9]+", "-", text)
return textYou run your tests, and two fail:
FAILED test_slugify[ Multiple spaces -multiple-spaces] - AssertionError: assert '-multiple-spaces-' == 'multiple-spaces'
FAILED test_slugify[Hello, World!-hello-world] - AssertionError: assert 'hello-world-' == 'hello-world'A weak follow-up is "It has some bugs, fix them." A strong follow-up quotes the evidence and states the rule that was violated:
Two of my tests fail.
slugify("Hello, World!") returns "hello-world-" but should return "hello-world".
slugify(" Multiple spaces ") returns "-multiple-spaces-" but should return "multiple-spaces".
The requirement was: no leading or trailing hyphens.
Change only what is needed to meet that requirement. Keep the rest of the function as it is.
Return only the corrected function.This follow-up gives the inputs, the actual outputs, the expected outputs, and the violated constraint. It also limits the scope of the change.
Kinds of corrections
Different problems call for different kinds of follow-up. The table maps a symptom to the usual fix.
| Symptom in the response | Likely cause | Follow-up that helps |
|---|---|---|
| Wrong behavior on one input | Missing example | Add the input and expected output as an example |
| Uses a library you did not want | Missing constraint | State the allowed and forbidden libraries |
| Code does not run on your version | Missing context | Give the language version and the exact error |
| Rewrites code you did not ask about | Unbounded scope | Say what must not change |
| Too long or includes explanation | Missing output format | Specify "only the function" or "only a diff" |
| Correct but slow | No performance limit | State the input size and the time limit |
Match the fix to the cause. Adding three paragraphs of general instruction when one example would do makes the prompt harder to read and gives the assistant more to misread.
Change one thing at a time
When you change several parts of a prompt at once, you cannot tell which change helped. If you add an example, a new constraint, and a different output format together and the result improves, you do not know what mattered. If the result gets worse, you do not know what to undo.
For short prompts, this matters less. For a prompt you plan to reuse, change one element per round. Keep a record of each version and its result so you can go back.
Refine the prompt or continue the conversation
You have two options after a miss. You can reply in the same conversation, or you can edit the original prompt and start fresh.
Replying in the conversation is quick. The assistant sees its earlier answer and your correction. It works well for small fixes.
Conversations carry baggage, though. After several rounds, the assistant is balancing your original request, three corrections, and its own earlier mistakes. Contradictory instructions pile up. Long conversations also push early details further back, and the assistant may stop following them.
Start a new conversation with a rewritten prompt when:
- You have corrected the same kind of mistake twice.
- The conversation has drifted from the original goal.
- You have learned what the prompt should have said. Fold those lessons into one clean prompt.
A rewritten prompt for the slugify task, after two rounds, might look like this:
Task: Write a Python 3.10 function slugify(text: str) -> str that converts an article title into a URL slug.
Context: used in a small blog tool; titles are plain ASCII.
Constraints: standard library only; lowercase the result; replace each run of non-alphanumeric characters with a single hyphen; no leading or trailing hyphens.
Examples:
slugify("Hello, World!") -> "hello-world"
slugify(" Multiple spaces ") -> "multiple-spaces"
slugify("C++ & Rust") -> "c-rust"
slugify("Already-slugged") -> "already-slugged"
Output format: only the function.Notice that the two failed cases became examples, and the violated rule became an explicit constraint. The new prompt carries what the iteration taught you.
Ask the assistant to explain, then decide
Sometimes you do not know why the output is wrong. You can ask the assistant to walk through its reasoning on a specific input:
Trace slugify(" Multiple spaces ") through your function line by line.
Show the value of text after each statement.A trace makes the bug visible. It is also a check on the assistant's own claim. If the trace disagrees with what you saw when you ran the code, trust your run. The assistant's description of what code does can be wrong, and execution is the authority.
You can also ask for alternatives when the first approach is not what you want: "Give two different ways to do this, and state one trade-off for each." Then pick one and say why. Your reason becomes a constraint for the next round.
Common iteration mistakes
- Vague feedback. "It's wrong" or "try again" repeats the same ambiguity that caused the miss.
- Pasting only the error's last line. Include the full traceback, the input that triggered it, and your language version.
- Fixing the symptom in your prompt but not the cause. If the assistant keeps using a forbidden library, add the constraint explicitly instead of repeating the request more forcefully.
- Letting the scope grow. Each round tends to invite "while you're at it" changes. Keep each round to one problem.
- Accepting a fix without rerunning tests. A change that fixes one case can break another. Run the whole suite after every round.
- Never stopping. If three rounds have not converged, the task may be too large. Split it, as described in the chapter on breaking larger tasks into steps, or write part of it yourself.
Knowing when to stop
Stop when the code meets the stated goal and passes your checks. Do not keep iterating for style preferences the prompt never mentioned, unless they matter to you. Each extra round risks regressions.
Stop and change approach when:
- The same failure recurs after two corrections.
- Your corrections contradict each other.
- You are spending more time prompting than it would take to write the code.
The last point is a legitimate outcome. The assistant is a tool, and for some small or highly specific changes, editing the code yourself is faster.
A worked second round
Here is the response to the corrected prompt:
import re
def slugify(text: str) -> str:
text = text.strip().lower()
text = re.sub(r"[^a-z0-9]+", "-", text)
return text.strip("-")Run your tests against it:
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) == expectedAll six pass. The last two cases, an empty string and a string of only symbols, are ones the prompt never mentioned. They pass here, but you learned to check them by looking at what the first response got wrong at the edges. If they had failed, the next step would be to add them as examples and iterate again.
Exercise
You ask an assistant for a function and it returns code that imports a third-party package, although you wanted the standard library only. You reply, "Please don't use extra packages." The next response still imports a third-party package. What are two better ways to handle this, and why?
Show answer
First, name the constraint precisely in the prompt: "Use only the Python 3.10 standard library. Do not import any third-party package." Vague wording like "extra packages" can be read in more than one way. Second, if the conversation already holds two failed corrections, start a new conversation with a rewritten prompt that includes this constraint from the start, so earlier mistaken output does not influence the response. In both cases, check the imports in the new code before relying on it.
Exercise
A test fails with assert 'hello-world-' == 'hello-world'. Write a follow-up message that gives the assistant what it needs to fix the bug without changing unrelated code.
Show answer
A good follow-up includes the input, the actual output, the expected output, the violated rule, and a scope limit. For example: "slugify("Hello, World!") returns "hello-world-" but should return "hello-world". The requirement is no leading or trailing hyphens. Change only what is needed to meet it, keep the rest of the function as it is, and return only the corrected function."