Sub topic 3
Iterate: Refine the Prompt from the Response
Assume you can read basic code, run a program, and run tests. This chapter focuses on improving a prompt after seeing the assistant's first response.
Iterate from evidence
Treat the first response as a draft. Compare it with your goal, constraints, and examples. Record the exact mismatch instead of asking vaguely for a better answer.
A useful refinement names:
- What the response did
- What it should have done
- The rule or example that proves the difference
- The smallest requested change
For example:
> The function keeps underscores, but the specification says every non-alphanumeric run becomes one hyphen. Update only the function and preserve the existing examples.
A large task is easier to refine when you request one step at a time. Ask first for a design, then implementation, then tests. This makes each response easier to inspect.
Verify generated code
Never treat a plausible response as verified. Run the code and test normal cases, boundary cases, and invalid input.
import re
def slugify(text: str) -> str:
text = text.strip().lower()
return re.sub(r"[^a-z0-9]+", "-", text).strip("-")
assert slugify("Hello, World!") == "hello-world"
assert slugify(" Multiple spaces ") == "multiple-spaces"
assert slugify("C++ & Rust") == "c-rust"
assert slugify("") == ""Review whether the implementation follows the requested scope, handles failure safely, and uses only permitted libraries. Tests confirm observed behavior, but they do not prove that untested behavior is correct.
Spot failure modes
Common failures include:
- Invented APIs or libraries
- Ignored constraints
- Correct behavior only for the examples
- Unrequested changes to nearby code
- Missing error handling
- Tests that repeat the implementation instead of checking requirements
Ask for a correction tied to a failing test or explicit requirement.
Protect private data
Remove passwords, access tokens, private keys, personal data, and proprietary source code before prompting. Replace them with placeholders that preserve the structure, such as <API_TOKEN> or <CUSTOMER_ID>. Check copied logs for headers, URLs, and stack traces containing secrets.
Reuse working prompts
Save prompts that produce reliable results as templates:
Task: <specific goal>
Context: <language, version, existing code, and error>
Constraints: <libraries, style, scope, and limits>
Examples: <input -> expected output>
Output format: <exact response shape>
Verification: <tests or review checks>Exercise
The response violates one constraint but passes the examples. What should you do next?
Show answer
Name the violated constraint, provide a failing test or concrete case, and request the smallest correction.