06 Prompt Strategy Diagnosis: Influence, Failure Modes, and What Lives Outside the Prompt
April 2026 (8346 Words, 47 Minutes)
Two ways to work through these cards. This page is the full exercise — all 12 cards, their prompts, and the complete instructor key for each one as raw text (classification, evidence, appropriateness, failure modes, what lives outside the prompt, improved prompt, teaching point). Read it linearly to study, or use it as the instructor and group-workshop guide (worksheet, warm-up example, group activity formats, rubric, debrief, grading scale all included below). For a gated self-study version where you classify each prompt yourself before seeing the key, use the interactive quiz — the same 12 cards, each as two graded questions (examples axis, then additive techniques) plus a free-text reflection, with the analysis revealed after you submit.
Goal
In this exercise you treat a dozen real-world software-development prompts as objects of study. For each prompt you classify it along two axes — first the examples axis (zero-shot or few-shot), then the additive techniques present (role, rubric, structured-output, CoT, context grounding, tool-augmented, or none) — identify the textual evidence, name the primary lever and the likely failure modes, decide what cannot be handled inside the prompt at all, and rewrite a stronger version. By the end you will:
- Recognise the named patterns from chapter 16 (pattern library) in unfamiliar prompts;
- Predict failure modes mechanistically rather than after-the-fact;
- Separate influence (what the prompt biases) from enforcement (tests, schemas, CI, review) — the three-layer model from chapter 8;
- Improve weak prompts surgically rather than by making them longer.
Lecture 7 will revisit the agentic and tool-grounded cards in the orchestration-layer story.
Learning objectives
After this exercise, students should be able to:
- Classify prompt strategies used in software-development tasks.
- Identify evidence for that classification in the prompt text.
- Explain why a prompt strategy may be appropriate or inappropriate for a given task.
- Recognize likely failure modes, including factual hallucination, structural hallucination, overconfident explanations, format drift, missing context, and false confidence.
- Separate influence from enforcement by deciding what can be handled through prompting and what requires tools, tests, schemas, CI, review, or other deterministic checks.
- Improve prompts by adding missing context, examples, constraints, output formats, validation steps, or tool instructions.
- Avoid prompt folklore by justifying prompt design decisions mechanistically and practically.
Recommended placement in the lecture
This exercise works best after students have already seen the main prompt patterns.
Recommended sequence:
- Short recap of prompt strategies.
- Introduce the diagnosis worksheet.
- Work through one example together.
- Students work in pairs or small groups on prompt cards.
- Groups present diagnoses.
- Instructor debrief connects answers back to software-engineering practice.
Duration options
Short version: 25–30 minutes
Use 3–4 prompt cards.
- 5 min: explain task and show diagnosis table
- 10–15 min: group work
- 10 min: discussion and debrief
Standard version: 45–60 minutes
Use 6–8 prompt cards.
- 5 min: recap prompt strategies
- 5 min: instructor example
- 20–30 min: group work
- 15–20 min: presentations and debrief
Extended lab version: 90 minutes
Use all prompt cards and require students to rewrite prompts.
- 10 min: recap and instructor example
- 25 min: classify and critique prompts
- 25 min: rewrite prompts
- 20 min: compare rewrites
- 10 min: debrief and takeaways
Required prior concepts
Students should already know the following concepts:
- zero-shot prompting
- few-shot prompting
- role prompting / role priming
- rubric-based prompting
- structured-output prompting
- chain-of-thought / planning prompts
- context grounding
- tool-augmented prompting
- retrieval-augmented generation
- hallucination types (chapter 5)
- influence layer vs. enforcement layer vs. human layer (chapter 8)
- validation through tests, schemas, linters, type checkers, CI, and code review
How this exercise’s categories map to the lecture’s pattern library
Chapter 16 names six patterns. This exercise uses a broader taxonomy that includes orchestration-adjacent categories (tool-augmented, structured-output) and the “outside the prompt” layer. The mapping:
| Lecture pattern (chapter 16) | Exercise category |
|---|---|
| Zero-shot | Zero-shot |
| Temperature | not exercised here — see "Temperature Experiments" exercise |
| Few-shot | Few-shot |
| Chain-of-thought | Chain-of-thought / planning |
| Self-consistency | not exercised here — orchestration concern, Lecture 7 |
| Role priming | Role prompting |
Two axes, not one menu. The most important idea in this exercise is that examples are a separate question from everything else. “Did this prompt use worked examples?” is a binary axis — every prompt is either zero-shot or few-shot, and a prompt can be few-shot and also use a role, a rubric, structured output, and so on. So for each card students answer two questions: the examples axis (zero-shot / few-shot), then which additive techniques are present. This keeps “few-shot” from competing with “structured-output” for a single slot, and makes every answer uniquely derivable from the printed decision rules below.
The additive techniques appear in the reference sheet below because real software-development prompts compose them with the lecture’s six patterns:
- Rubric-based prompting — explicit evaluation criteria layered on top of role priming or structured-output prompting.
- Structured-output prompting — the influence-layer version of constrained decoding (§15.1). Prompting for JSON is not the same as enforcing JSON.
- Context grounding — relevant context sharpens the conditional distribution toward the right continuation; irrelevant or stale context spends window and can mislead the model by adding distractors (it depends on the model and the content, not on the fraction of the window it fills).
- Tool-augmented prompting — moves work out of the prompt and into the orchestration layer (Lecture 7).
Two further concepts are not prompting strategies and are deliberately kept off the technique menu:
- Validation/enforcement — chapter 8’s enforcement layer. Not a prompting choice; it is the thing prompting cannot do. It is the enforcement layer, not a strategy, so it appears only in the “what does the task NEED outside the prompt?” question — never as a technique to check.
- Anti-pattern — a quality judgment, not a strategy. Marks prompts that confuse influence with enforcement, hide uncertainty behind confident style, or omit context the task depends on. The anti-pattern judgment lives in what the task needs, never in the classification itself.
Prompt strategy reference sheet
Give students this compact reference before the exercise. The examples axis (zero-shot / few-shot) is the binary question students answer first; the six additive techniques are the second question. The “How to decide this box” column is the printed rule that makes every answer uniquely derivable.
| Strategy | Axis or technique | Short description | How to decide this box | Main risk |
|---|---|---|---|---|
| Zero-shot vs Few-shot | Examples axis (binary) | Whether the prompt demonstrates the desired behaviour with worked examples | Few-shot iff the prompt contains ≥1 worked example demonstrating the desired input→output behaviour or style to imitate — including an example built on a sibling artifact (a different function/endpoint/record). The single artifact the task operates ON (function-under-test, report-to-classify, diff-to-review) is NOT a demonstration. Otherwise zero-shot. | Zero-shot: generic/underspecified output. Few-shot: examples may bias wrongly or overfit |
| Role priming | Additive technique | Assign a professional role or perspective | An "Act as a <role>" / "You are a <role>" expertise persona. "You are helping in our X project" is membership, not a role. | Role does not guarantee expertise or correctness |
| Rubric-based prompting | Additive technique | Provide evaluation criteria/checklist | An explicit list of evaluation criteria / scoring dimensions to judge against — not a list that merely organises output sections. | May become checklist-like and miss context |
| Structured-output prompting | Additive technique | Request a fixed output format (table, JSON, sections) | A concrete output-format spec — a named serialization (JSON/YAML/table), an enum of allowed values, an "only output X" shape, OR a section schema whose parts are explicitly named/enumerated as a labeled list. Two prose imperatives joined by "and" ("explain the cause AND propose a fix") are a task description, NOT structured-output. | Format is influenced, not guaranteed (§15.1) |
| Chain-of-thought / planning | Additive technique | Ask for stepwise reasoning, plan, or rationale | Explicit "think step by step" / "show your reasoning" / "first plan, then…". A bare "explain" does NOT count. | Visible reasoning may be verbose or unfaithful (§13.5) |
| Context grounding | Additive technique | Provide relevant project/code/docs/context | Embedded background the model conditions on while producing output about something else (project conventions, related/example code, docs, a diff, a stack trace + surrounding code). The artifact that IS the task's direct object does not count. | Irrelevant or stale context can mislead |
| Tool-augmented prompting | Additive technique | Instruct model to use tools, docs, tests, APIs | The prompt names a tool/resource to invoke ("use the web search tool", "run the test suite"). Merely implying tool use ("commit them") does not count. | Tool outputs must be checked and scoped (Lecture 7) |
Note — validation/enforcement is not on the technique menu. External checks (schema validation, tests, CI, review) are chapter 8’s enforcement layer — the thing prompting cannot do. It is the enforcement layer, not a prompting strategy, so it has been removed from the technique menu. It belongs only in the “what does the task NEED outside the prompt?” question.
Important distinction:
Prompting belongs to the influence layer. Tests, schemas, static analysis, CI, sandboxing, and review belong to the enforcement and human layers.
Student worksheet
For each prompt card, students fill out the following table.
| Question | Answer |
|---|---|
| What is the software-development task? | |
| Examples axis (zero-shot / few-shot)? | |
| Which ADDITIVE techniques are present? (role / rubric / structured-output / CoT / context grounding / tool-augmented / none) | |
| Which exact phrases in the prompt reveal these? | |
| Why might this strategy have been chosen? | |
| Is the strategy appropriate for the task? Why or why not? | |
| What are the likely failure modes? | |
| What is missing from the prompt? | |
| What should be handled outside the prompt? | |
| How would you improve the prompt? | |
| Primary lever: of the techniques actually present, which one most shapes output quality? | |
| Final classification in one sentence |
Instructor warm-up example
Warm-up prompt:
You are an expert reviewer for a university Computer Science course on AI-supported Software Development.
Review the attached lecture draft critically. Evaluate conceptual correctness, freshness, pedagogical fit, software-engineering relevance, structure, exercises, and timing.
Use the following output sections:
# Overall verdict
# Highest-priority changes
# What is already strong
# What is outdated or needs updating
# Missing topics to consider adding
# Structural and pedagogical feedback
# Software-engineering relevance
# Exercise feedback
# Suggested revised structure
# Concrete wording suggestions
# Bottom line
Instructor key — click to reveal
Expected classification:
- Examples axis: zero-shot — no example review is demonstrated.
- Additive techniques: role priming + rubric-based + structured-output.
Why:
- Examples axis = zero-shot because no demonstration examples of good reviews are provided.
- It is role-primed because the model is asked to act as an expert reviewer.
- It is rubric-based because it lists explicit evaluation criteria to judge against.
- It uses structured-output prompting because it specifies named answer sections.
- It is not chain-of-thought because it does not ask for a visible reasoning trace.
Primary lever: the rubric. The main risk in a broad expert review is not output format but coverage: without an explicit list of dimensions the model focuses on surface-level feedback. The rubric is what makes the review systematic and comparable across future lecture drafts.
Discussion point:
This card is a clean warm-up because the two axes separate cleanly: it is plainly zero-shot, and the three additive techniques are each visible in distinct phrases. Notice that “no examples → zero-shot” is now its own question, so students never have to wonder whether “zero-shot” belongs in the same list as “structured-output.”
Prompt cards for students
Each group receives one or more cards. The cards intentionally vary in quality. Some are good strategies; others are flawed or incomplete.
Card 1: Simple code generation — a contrastive triple
Task: Generate a helper function for a Python project. Here is the same task written three ways. Compare them.
Version 1a — bare:
Write a Python function `normalize_email` that strips whitespace, lowercases,
and raises ValueError unless there is exactly one @.
Version 1b — with worked examples:
Write a Python function `normalize_email` that strips whitespace, lowercases,
and raises ValueError unless there is exactly one @.
Examples:
normalize_email(" Foo@Bar.COM ") -> "foo@bar.com"
normalize_email("a@@b.com") -> ValueError
Version 1c — with an output constraint:
Write a Python function `normalize_email` that strips whitespace, lowercases,
and raises ValueError unless there is exactly one @.
Only output the function. No prose.
Student task: For each version, name the examples axis (zero-shot / few-shot) and the additive technique it adds (if any). Then say what delta each variant adds and what the task still needs.
Instructor key — click to reveal
Classification of each version:
| Version | Examples axis | Additive technique added | Delta over bare 1a |
|---|---|---|---|
| 1a (bare) | Zero-shot | None | — (the baseline: instruction only) |
| 1b (few-shot) | Few-shot | None | Two worked example calls demonstrating the desired behaviour on edge cases (uppercase normalisation, double-@ error). This is what flips the examples axis to few-shot. |
| 1c (spec'd) | Zero-shot | Structured-output | "Only output the function. No prose." — a constraint on the output shape. |
Primary lever: for all three versions the dominant lever is the bare instruction itself — the precise, enumerated behaviour spec (“strip whitespace, lowercase, raise ValueError unless exactly one @”). That is what actually pins down a correct implementation. The worked examples (1b) sharpen the edge cases; the output constraint (1c) tidies the shape; neither would save a vague instruction. Specify the behaviour first; add examples and shape second.
Why this strategy may be appropriate:
The task is small, familiar, and low-risk. The behaviour is explicitly specified, so even bare 1a is probably enough to get a plausible implementation.
Likely failure modes:
- The model may implement a simplistic email check and overinterpret the validation requirement.
- It may include extra explanation despite “Only output.”
- It may not handle non-string inputs unless specified.
- It may pass obvious examples but fail edge cases.
What belongs outside the prompt:
- Unit tests for whitespace, uppercase, missing
@, multiple@, empty string. - Static analysis or type checking if the project uses type hints.
- None of the three versions includes tests; the examples in 1b are demonstrations for the model, not an executable test suite.
Possible improvement:
Write a Python function called `normalize_email(email: str) -> str`.
Requirements:
- Strip leading and trailing whitespace.
- Convert the result to lowercase.
- Raise `ValueError("invalid email")` if the normalized string contains anything other than exactly one `@`.
- Do not perform full RFC email validation.
- Return the normalized email address.
Only output the function body with the function definition. No explanation.
Teaching point:
Zero-shot is not bad. For small, well-specified, low-risk tasks, it is often appropriate. The important question is not “Did we use an advanced prompting technique?” but “Does the task require one?” The triple also shows the two axes in isolation: 1b changes only the examples axis, 1c changes only an additive technique, neither touches the other.
Card 2: Project-style code generation
Task: Generate code that follows an existing project style.
Prompt:
You are helping in our Python backend project.
Implement a function that loads a user by ID and returns `None` if the user is not found.
Use our project style:
Example 1:
```python
def get_order_by_id(db: Session, order_id: UUID) -> Order | None:
result = db.execute(select(Order).where(Order.id == order_id))
return result.scalar_one_or_none()
```
Example 2:
```python
def get_invoice_by_id(db: Session, invoice_id: UUID) -> Invoice | None:
result = db.execute(select(Invoice).where(Invoice.id == invoice_id))
return result.scalar_one_or_none()
```
Now write:
```python
def get_user_by_id(db: Session, user_id: UUID) -> User | None:
...
```
Only output the completed function.
Student task: Name the examples axis and the additive techniques, and explain why the prompt is likely effective.
Instructor key — click to reveal
Examples axis: few-shot. Two worked demonstrations (get_order_by_id, get_invoice_by_id) built on sibling artifacts — different functions from the one being written. A sibling-artifact example still counts as a demonstration.
Additive techniques: structured-output + context grounding.
- Structured-output: “Only output the completed function” constrains the output to a code completion.
- Context grounding: the example functions embed the project’s naming, return-type, and SQLAlchemy conventions the model conditions on while writing a different function.
- Not role priming: “You are helping in our Python backend project” is project membership, not an “Act as a <role>” expertise persona.
Double-count disclosure: the same Example 1 / Example 2 block legitimately fires both the few-shot axis and the context-grounding box. As worked demonstrations they set the examples axis; as embedded project conventions the model conditions on, they ground the output. The phrase “our Python backend project” alone is only membership — it is the example code that does the grounding.
Primary lever: the worked examples (few-shot). The challenge is not general Python knowledge but matching local conventions, and the examples carry naming, SQLAlchemy usage, return style, and type hints all at once. Remove them and the model falls back to generic ORM code; remove the “only output” constraint and you lose only a little tidiness.
Why this strategy may be appropriate:
The main challenge is not general Python knowledge but matching local project conventions. Few-shot examples are useful because they show naming, SQLAlchemy usage, return style, and type hints.
Likely failure modes:
- The model may assume imports exist.
- It may hallucinate the
Usermodel or table name. - It may not know whether
User.idis the correct field. - It may reproduce a pattern that is locally consistent but architecturally wrong.
What belongs outside the prompt:
- Type checking.
- Unit or integration test using a test database.
- Code review to confirm the query belongs in this layer.
Possible improvement:
Add the relevant imports or surrounding repository context if the model is expected to produce a full patch.
Assume `Session`, `UUID`, `select`, and `User` are already imported. Do not add imports.
Teaching point:
Few-shot is especially useful when the desired behavior is “do it like these examples,” not when the task requires knowing external facts.
Card 3: Code review
Task: Review a pull request for maintainability and security.
Prompt:
Act as a senior backend engineer and security-conscious code reviewer.
Review the following pull request diff. Use this rubric:
1. Correctness risks
2. Security risks
3. Maintainability issues
4. Missing tests
5. Unclear naming or API design
6. Suggestions that are nice-to-have rather than required
For each finding, output:
- severity: critical / major / minor / suggestion
- file or function
- issue
- why it matters
- recommended change
Do not rewrite the whole patch. Focus on review comments.
Here is the diff:
[DIFF]
Student task: Classify the prompt strategy. Is it appropriate for the task?
Instructor key — click to reveal
Examples axis: zero-shot. No example review is demonstrated; the rubric and field list are instructions and a schema, and the diff is the artifact under review — none is a worked demonstration.
Additive techniques: role priming + rubric-based + structured-output + context grounding.
- “Act as a senior backend engineer and security-conscious code reviewer” is role priming.
- The numbered list of evaluation categories is a review rubric (criteria to judge against).
- The per-finding fields (severity / file / issue / why / change) are an explicitly named output schema.
- The
[DIFF]is embedded background the review conditions on (context grounding). - Not chain-of-thought: nothing asks the model to think step by step.
Primary lever: the rubric. Code review is a coverage problem: without an explicit list of dimensions the model flags only what catches its eye. The rubric forces systematic coverage; role priming sets perspective and the schema makes findings actionable, but remove the rubric and the review becomes shallow and uneven.
Why this strategy is appropriate:
Code review is a judgment task. A role helps set the perspective, while a rubric improves coverage. Structured output makes the feedback actionable.
Likely failure modes:
- The model may over-report minor issues.
- It may miss subtle security issues.
- It may misunderstand diff context if surrounding code is missing.
- It may suggest changes inconsistent with team conventions.
- It may sound authoritative even when uncertain.
What belongs outside the prompt:
- Static analysis.
- Security scanners.
- Tests.
- Human review for architecture and business logic.
Possible improvement:
Separate findings into:
- Must fix before merge
- Should consider
- Questions for the author
If a finding depends on missing context, mark it as "needs context" instead of stating it as fact.
Teaching point:
Rubric-based review prompts are strong for systematic critique, but the review remains advisory. A model is not a replacement for CI or human approval.
Card 4: Bug diagnosis with stack trace
Task: Diagnose a runtime bug.
Prompt:
I get this error:
```text
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
```
Here is the buggy function:
```python
def total_price(items):
total = 0
for item in items:
total += item.discounted_price()
return total
```
For reference, from our pricing module `pricing/discounts.py`, here is the
method each item exposes (it returns `None` when no active discount applies):
```python
class Item:
def discounted_price(self) -> float | None:
if self._active_discount is None:
return None
return self.base_price * (1 - self._active_discount.rate)
```
Explain the likely cause and propose a fix.
Student task: Classify the prompt (examples axis + additive techniques) and improve it.
Instructor key — click to reveal
Examples axis: zero-shot. Nothing demonstrates a desired input→output behaviour; the buggy function and the discounted_price() method are artifacts to reason about, not worked example calls.
Additive techniques: context grounding.
- Context grounding: the
Item.discounted_price()method frompricing/discounts.pyis genuine background — distinct from thetotal_pricefunction under diagnosis — that the model conditions on to see thatNoneis an expected return. The buggy function is the task’s direct object; the pricing method is the surrounding background. - Not structured-output: “Explain the likely cause and propose a fix” is two prose imperatives joined by “and” — a task description, not an output-format spec.
- Not chain-of-thought: “Explain” alone does not invoke step-by-step reasoning.
Primary lever: context grounding. The supplied discounted_price() definition is what lets the model see that None is an expected return rather than guessing — it turns a blind diagnosis into an evidence-based one. Remove that background and the model has to assume what discounted_price() does, which is exactly where it collapses uncertainty too early.
Why this may be appropriate:
The error message is unambiguous and the supplied code is small, so with the discounted_price() definition in hand the model can confirm — not just guess — that None is an expected return. The model can infer that discounted_price() sometimes returns None.
Likely failure modes:
- The model may assume too much about
discounted_price(). - It may suggest hiding the bug by treating
Noneas zero. - It may fail to ask whether
Noneis valid domain behavior. - It may propose a fix without tests.
What belongs outside the prompt:
- Reproduction test.
- Unit test for items with missing discounted prices.
- Domain decision: should
Nonebe allowed?
Possible improved prompt:
Diagnose this bug, but separate evidence from assumptions.
For the fix, provide two alternatives:
1. A defensive fix if `None` is expected domain behavior.
2. A stricter fix if `None` indicates invalid data.
Also suggest one regression test.
Error:
[STACK TRACE]
Relevant code:
[CODE]
Teaching point:
Debugging prompts should prevent the model from collapsing uncertainty too early. Ask it to separate evidence, assumptions, alternatives, and validation.
Card 5: Test generation
Task: Generate tests for an existing function.
Prompt:
Write tests for this function:
```python
def is_valid_age(age: int) -> bool:
return age >= 18 and age <= 120
```
Student task: Classify this prompt (examples axis + additive techniques) and critique it.
Instructor key — click to reveal
Examples axis: zero-shot. No example test is demonstrated; the function shown is the unit under test, not a demonstration.
Additive techniques: None of these. No role, no rubric, no output-format spec, no reasoning instruction, no tool. The function source is the unit under test, not embedded background, so it does not trigger context grounding.
Evidence of what is missing:
- No role.
- No examples.
- No test framework specified.
- No coverage criteria specified.
- No output format specified.
Primary lever: there is no additive technique, so the only lever is the bare instruction “Write tests for this function” — and it is far too thin to carry the task. The real fix is not to nominate a present technique but to add one: a coverage specification (a rubric-plus-structured-output upgrade). The lever this task needs is missing.
Why this is weak:
The task is underspecified. The model does not know whether to use pytest, unittest, property-based testing, table-driven tests, or project-specific conventions.
Likely failure modes:
- Tests may use the wrong framework.
- Boundary cases may be incomplete.
- Negative ages may be missed.
- The model may only test happy paths.
- The model may duplicate implementation logic rather than test behavior.
What belongs outside the prompt:
- Running the tests.
- Coverage measurement.
- Mutation testing if desired.
Possible improved prompt:
Write `pytest` tests for `is_valid_age`.
Use table-driven tests and cover:
- below minimum: -1, 0, 17
- lower boundary: 18
- typical valid value: 35
- upper boundary: 120
- above maximum: 121
Only output the test code.
Teaching point:
For test generation, the best prompt is often a coverage-specification prompt, not merely “write tests.”
Card 6: Requirements clarification
Task: Turn vague stakeholder notes into acceptance criteria.
Prompt:
Act as a product-minded requirements engineer.
Turn these stakeholder notes into acceptance criteria.
Use this format:
- User story
- Acceptance criteria in Given/When/Then format
- Open questions
- Assumptions you made
Important: Do not silently invent requirements. If something is unclear, put it under Open questions.
Stakeholder notes:
"Users should be able to export their data. It should be fast and secure. Admins need some kind of overview. Also we need this for compliance next quarter."
Student task: Classify the prompt strategy and explain why it is appropriate.
Instructor key — click to reveal
Examples axis: zero-shot. No example acceptance-criteria document is demonstrated; the bulleted output format is a schema, and the stakeholder notes are the input to transform.
Additive techniques: role priming + structured-output.
- “Act as a product-minded requirements engineer” is an expertise persona (role priming).
- The output sections (User story / Given-When-Then criteria / Open questions / Assumptions) are an explicitly named section schema (structured-output).
- “Do not silently invent requirements” directly targets hallucination; “Open questions” and “Assumptions” force the model to separate what was given from what it inferred.
- Not rubric-based: the four sections organise the output; they are not evaluation criteria to judge the notes against.
- Not context grounding: the notes are the input to transform, not background.
Primary lever: the structured output — specifically the “Open questions” and “Assumptions” sections plus “do not silently invent requirements.” This is what forces the model to separate what was given from what it inferred, the dominant risk for ambiguity-heavy requirements work. Role priming helps set tone, but remove the uncertainty-surfacing structure and the model will quietly invent precision.
Why this strategy is appropriate:
Requirements work is ambiguity-heavy. The prompt is designed to prevent the model from converting uncertainty into invented precision.
Likely failure modes:
- The model may still over-specify compliance requirements.
- It may invent export formats or performance thresholds.
- It may miss security/privacy implications.
- It may produce criteria that are not testable.
What belongs outside the prompt:
- Stakeholder validation.
- Legal/compliance review.
- Product prioritization.
Possible improvement:
Add instruction:
Mark each acceptance criterion as either directly supported by the notes or inferred.
Teaching point:
For requirements tasks, good prompting often means making uncertainty visible rather than asking the model to complete the specification confidently.
Card 7: External API usage
Task: Write code using an unfamiliar third-party API.
Familiar setup, deliberate framing. This prompt is the unaided zero-shot version of the Stack Exchange API task you saw in Lecture 2’s Stack Overflow Challenge and that the lecture worked through in §12.6. Diagnose what the bare zero-shot version gets wrong and explain mechanistically why the model is likely to hallucinate the endpoint.
Prompt:
Write Python code that uses the Stack Exchange API to get the number of questions posted per month for the last six months.
Use the correct endpoint and return a dictionary mapping `YYYY-MM` to question count.
Student task: Classify the prompt (examples axis + additive techniques). Is it sufficient?
Instructor key — click to reveal
Examples axis: zero-shot. No example call, documentation excerpt, or demonstration of the endpoint usage; the prompt assumes the model already knows the current API surface.
Additive techniques: structured-output.
- Structured-output: “return a dictionary mapping
YYYY-MMto question count” is a concrete output-shape spec (a named mapping with a specified key format). - Not tool-augmented: the prompt names no tool or documentation to invoke.
- Not context grounding: no documentation or background is embedded.
The structured-output box is correctly checked — but the shape of the dict is not where this prompt fails.
Primary lever: the present technique (the dict spec) is weak — it shapes the container, not the contents. The quality of this output hinges on a technique that is absent: grounding the model in the real API (documentation or a tool call). So the task’s true lever — context grounding / tool use — is missing, and that gap is exactly what makes this an anti-pattern.
Why this is risky:
This task depends on an external API surface. The model may hallucinate an endpoint, parameter, pagination behavior, rate limit, or response schema.
Likely failure modes:
- Factual hallucination: non-existent endpoint.
- Structural hallucination: plausible but wrong response fields.
- Missing pagination or date handling.
- Code that looks reasonable but fails at runtime.
What belongs outside the prompt:
- Reading official API documentation.
- Running the code against the API.
- Handling HTTP errors and rate limits.
- Tests with mocked API responses.
Possible improved prompt:
Use the official Stack Exchange API documentation provided below. Do not invent endpoints or fields.
First identify which documented endpoint can answer the task. If the API does not provide monthly aggregation directly, say so and compute monthly counts from available data.
Return:
1. A short explanation of the endpoint used.
2. Python code.
3. Assumptions and limitations.
4. Suggested mock tests.
Documentation excerpt:
[PASTE RELEVANT DOCS]
Teaching point:
External API tasks require grounding. Zero-shot prompting is often the wrong tool when the central risk is hallucinating facts about a changing interface.
Card 8: Structured output for pipeline integration
Task: Extract machine-readable metadata from a bug report.
Prompt:
Extract the following fields from the bug report and return JSON:
- title: string
- severity: one of [low, medium, high, critical]
- affected_component: string or null
- reproduction_steps: array of strings
- expected_behavior: string or null
- actual_behavior: string or null
- missing_information: array of strings
Bug report:
"Checkout sometimes crashes after I apply a coupon. I expected the discount to be applied, but instead I got a 500 error. This happened yesterday on mobile. I don't know if it also happens on desktop."
Student task: Classify the prompt strategy and identify what is still missing for production use.
Instructor key — click to reveal
Examples axis: zero-shot. No example extraction is demonstrated; the field list and enum are an output schema, and the bug report is the input to transform.
Additive techniques: structured-output.
- An explicit JSON request, named fields with types, and an enum of allowed
severityvalues — a named serialization with an enumerated schema. - Not rubric-based: the fields are a data schema to fill, not evaluation criteria.
- Not context grounding: the bug report is the input to transform, not background.
Primary lever: the structured-output schema. The named JSON fields, types, and severity enum are what make the output pipeline-consumable. Remove the schema and you get prose no downstream system can ingest. Note the schema biases toward valid JSON but does not enforce it — that is the enforcement layer’s job.
Why this strategy is appropriate:
The output is intended to be machine-readable. A structured format helps integrate the model output into a downstream workflow.
Likely failure modes:
- Invalid JSON.
- Missing required fields.
- Severity may be guessed without enough evidence.
- The model may put inferred information where null is more appropriate.
- The model may violate enum constraints.
What belongs outside the prompt:
- JSON schema validation.
- Retry/repair loop if invalid.
- Human review for severity.
- Possibly constrained decoding or structured output API (§15.1).
Possible improved prompt:
Return only valid JSON matching this schema. Use `null` when the report does not provide the information. Do not infer severity beyond the evidence; if uncertain, use `medium` and include the uncertainty in `missing_information`.
[JSON SCHEMA]
Teaching point:
Prompting for JSON is not the same as enforcing JSON. Production use requires schema validation or constrained decoding.
Card 9: Architecture decision support
Task: Compare architectural options.
Prompt:
Act as a pragmatic software architect.
We need to decide how to process image uploads in our web application.
Compare these options:
1. Process synchronously in the request.
2. Store the image and process it in a background worker.
3. Send it to an external image-processing service.
Use this decision rubric:
- latency
- implementation complexity
- operational complexity
- failure handling
- scalability
- cost
- security/privacy
- developer experience
Output:
1. A comparison table.
2. A recommendation for a small startup team.
3. Conditions under which your recommendation would change.
4. Assumptions you are making.
Student task: Classify the prompt strategy and evaluate its usefulness.
Instructor key — click to reveal
Examples axis: zero-shot. No example comparison is demonstrated; the options, rubric, and output sections are instructions and schema.
Additive techniques: role priming + rubric-based + structured-output.
- “Act as a pragmatic software architect” is an expertise persona (role priming).
- The eight-criterion list (latency, complexity, cost, security, …) is a set of evaluation dimensions to judge each option against (rubric).
- The four numbered output sections (table, recommendation, conditions, assumptions) are an explicitly named section schema (structured-output).
- Not context grounding: the three options are part of the task, not embedded background about the model’s own application.
Primary lever: the rubric. Architecture decisions are trade-off decisions, and the eight-criterion rubric is what prevents a one-dimensional answer (“just use a worker”). Role priming sets tone and the output schema makes the comparison legible, but remove the rubric and the model evaluates on whatever axis it happens to favour.
Why this strategy is appropriate:
Architecture decisions are trade-off decisions. A rubric and structured comparison help prevent a one-dimensional answer.
Likely failure modes:
- Recommendation may depend heavily on unstated context.
- The model may understate operational complexity.
- Security/privacy risks may be generic.
- Cost assumptions may be wrong.
What belongs outside the prompt:
- Real traffic estimates.
- Cost modeling.
- Security review.
- Team capability assessment.
- Architecture decision record reviewed by humans.
Possible improvement:
Before recommending, list the three most important missing pieces of context that could change the decision.
Teaching point:
For architecture, the model is useful as a decision-support tool, not as a decision-maker.
Card 10: Security-sensitive code generation
Task: Add authentication middleware.
Prompt:
Write Express.js middleware that checks whether a request has a valid JWT.
If the token is valid, attach the user ID to `req.userId` and call `next()`.
If invalid, return HTTP 401.
Student task: Classify the prompt strategy and critique it from a security perspective.
Instructor key — click to reveal
Examples axis: zero-shot. No example middleware is demonstrated; the prompt is a bare behavioural instruction.
Additive techniques: None of these. No role, no rubric, no output-format spec, no reasoning instruction, no embedded background, no tool. “Attach the user ID to req.userId” describes behaviour, not an output schema.
Primary lever: there is no additive technique, so the only lever is the bare instruction — and for a security-critical task it is dangerously thin. It specifies the happy path and nothing about the security policy (algorithms, issuer/audience, expiry, error behaviour). What the task actually needs is layered technique (a security-requirements rubric) plus enforcement and review — the present lever is not enough.
Why this is insufficient:
Authentication is security-critical. A generic zero-shot prompt may omit algorithm restrictions, issuer/audience checks, expiration handling, key rotation, error behavior, logging rules, and dependency choices.
Likely failure modes:
- Accepting unsigned tokens or wrong algorithms.
- Not checking expiration.
- Not checking issuer/audience.
- Leaking token details in errors.
- Attaching unvalidated claims to the request.
- Using outdated or unsafe libraries.
What belongs outside the prompt:
- Security review.
- Dependency review.
- Tests with valid, expired, malformed, wrong-audience tokens.
- Static analysis and secret handling checks.
- Runtime configuration management.
Possible improved prompt:
Act as a security-conscious Node.js backend engineer.
Write Express.js middleware for JWT authentication using `[SPECIFIC LIBRARY]`.
Security requirements:
- Verify signature.
- Accept only algorithm `[ALGORITHM]`.
- Validate issuer `[ISSUER]`.
- Validate audience `[AUDIENCE]`.
- Reject expired tokens.
- Do not log token contents.
- Return a generic 401 on failure.
- Attach only the validated subject claim to `req.userId`.
Also provide pytest/jest-style test cases for:
- valid token
- expired token
- wrong issuer
- wrong audience
- malformed token
- missing token
If any required configuration is missing, state it explicitly instead of inventing it.
Teaching point:
Security-sensitive tasks should not rely on prompt influence alone. They require enforcement, testing, and human review.
Card 11: Agentic repository task
Task: Ask an AI coding agent to modify a repository.
Prompt:
Implement issue #214.
Make the necessary changes and commit them.
Stem note. A prompt that merely implies tool use (“commit them”) does not name a tool, so per the tool-augmented decision rule the tool box stays unchecked here. The real point — that this task NEEDS scoped tool use, branch protection, and review — belongs in the reflection, not the classification.
Student task: Classify the prompt (examples axis + additive techniques) and explain why it is dangerous or incomplete.
Instructor key — click to reveal
Examples axis: zero-shot. No demonstration of any kind — two terse imperatives, nothing to imitate.
Additive techniques: None of these. No role, rubric, output schema, reasoning instruction, or embedded context. Crucially, not tool-augmented: “commit them” implies tool use but names no tool and scopes nothing — per the tool-augmented decision rule, an implied action is not a named tool.
Evidence of what is missing:
- Very little context.
- No acceptance criteria.
- No constraints.
- No testing requirements.
- No permission boundaries.
- Allows commit without review.
Primary lever: there is no additive technique, so the only lever is the bare instruction — far too thin for an autonomous agent with write access. The task’s true levers are absent and external: scoped tool use, task boundaries, a stop-before-commit gate, branch protection, and review. The classification correctly shows “None,” and that emptiness is precisely the danger.
Why this is risky:
Agentic coding tasks can modify many files. Without boundaries and validation requirements, the agent may make broad, low-quality, or incorrect changes.
Likely failure modes:
- Misunderstanding the issue.
- Over-modifying unrelated files.
- Not running tests.
- Creating a commit that passes superficially but breaks behavior.
- Ignoring project conventions.
- Failing silently on edge cases.
What belongs outside the prompt:
- Branch protection.
- CI.
- Human review before merge.
- Test suite.
- Commit hooks.
Possible improved prompt:
Work on issue #214 in a new branch.
Before editing:
1. Read the issue description.
2. Identify the relevant files.
3. Summarize the intended change and ask for confirmation if the scope is ambiguous.
While editing:
- Make the smallest change that satisfies the issue.
- Do not refactor unrelated code.
- Follow existing project style.
- Add or update tests that fail before the fix and pass after it.
Before finishing:
- Run the relevant test subset.
- Run the formatter and linter.
- Provide a summary of changed files, tests run, and remaining risks.
- Do not commit unless explicitly instructed after review.
Teaching point:
Agent prompts need task boundaries, validation instructions, and permission control. The more autonomy the tool has, the more important the enforcement layer becomes.
Card 12: Prompt that overuses chain-of-thought
Task: Classify a bug report.
Prompt:
Think step by step in great detail. Show all your reasoning.
Classify this bug report as one of:
- UI
- backend
- database
- infrastructure
- unclear
Bug report:
"The save button turns gray and nothing happens after I upload a profile picture."
Student task: Classify the prompt (examples axis + additive techniques) and critique whether the chosen strategy is appropriate.
Instructor key — click to reveal
Examples axis: zero-shot. No example classification is demonstrated; the five-way label set is the allowed-output enum, not a worked demonstration.
Additive techniques: chain-of-thought + structured-output.
- Chain-of-thought: “Think step by step in great detail. Show all your reasoning” is an explicit reasoning instruction.
- Structured-output: the five-way enum (UI / backend / database / infrastructure / unclear) constrains the output to one of a fixed set of allowed values.
- Not rubric-based: the enum is the allowed answers, not criteria for judging them.
Primary lever: the structured-output enum is the lever that actually helps — it forces a clean, machine-checkable label. The chain-of-thought instruction is present but counter-productive here: for a five-way classification it adds verbosity and false confidence without improving the label. The present lever worth keeping is the enum; the CoT is the technique to drop.
Why this may be inappropriate:
The task is a simple classification with ambiguity. A long visible reasoning chain is not necessary and may create false confidence. What matters is the label, confidence, and missing information.
Likely failure modes:
- Verbose answer.
- Rationalization of a weak guess.
- Overconfident classification.
- Hidden ambiguity gets transformed into an explanation.
Better prompt:
Classify the bug report as one of:
- UI
- backend
- database
- infrastructure
- unclear
Return:
- label
- confidence: low / medium / high
- one-sentence rationale
- what information would make the classification more certain
Teaching point:
Chain-of-thought is not automatically better. For many software tasks, a concise rationale plus uncertainty is more useful than detailed reasoning. The faithfulness caveat from §13.5 and §15.3 applies: visible reasoning is not an audit trail.
Group activity instructions
Option A: Classification only
Each group receives two prompt cards.
For each card:
- Classify the prompt strategy.
- Identify textual evidence.
- Explain whether the strategy fits the task.
- Name the likely failure modes.
- Decide what must be validated outside the prompt.
Each group presents one card in 2 minutes.
Option B: Classification plus rewrite
Each group receives one weak prompt and one stronger prompt.
For the weak prompt:
- Diagnose the prompt.
- Rewrite it.
- Explain which strategies the rewrite uses.
- Explain what still cannot be solved by prompting.
Option C: Prompt design review
Treat the prompt like a code artifact.
Students perform a “prompt review” with comments such as:
- Missing context
- Wrong strategy for task
- Needs examples
- Needs output schema
- Needs tests
- Needs tool grounding
- Overuses chain-of-thought
- Security-sensitive; needs human review
- Prompting cannot enforce this
Debrief questions
Use these questions after group presentations.
- Which prompts looked good at first but were risky after closer inspection?
- Which prompts were simple but sufficient?
- Where was few-shot prompting genuinely useful?
- Where would few-shot prompting not solve the real problem?
- Which tasks required external validation?
- Which tasks required current documentation or tool use?
- Where did role prompting help, and where was it mostly cosmetic?
- Which prompts risked hallucination most strongly?
- Which prompts confused influence with enforcement?
- How would you integrate these prompts into a real development workflow?
Assessment rubric
Use this rubric if the exercise is graded.
| Criterion | Excellent | Satisfactory | Needs improvement |
|---|---|---|---|
| Strategy classification | Correctly answers the examples axis (zero-shot / few-shot) AND the additive techniques, and names the primary lever (which present technique most shapes output quality) | Gets the examples axis right and identifies at least one relevant additive technique | Misclassifies, conflates the two axes, or uses vague labels |
| Evidence | Cites exact prompt phrases as evidence | Gives general evidence | No concrete evidence |
| Appropriateness analysis | Explains why the strategy fits or does not fit the task | Gives basic judgment | Says only "good" or "bad" without reasoning |
| Failure modes | Identifies realistic software-specific risks | Identifies generic risks | Misses key risks |
| Influence vs enforcement | Clearly separates prompt design from validation/testing/review | Mentions some external checks | Treats prompting as sufficient |
| Prompt improvement | Provides a concrete, better prompt | Suggests general improvements | No actionable improvement |
| Software-engineering grounding | Connects to tests, CI, docs, code review, security, maintainability | Some practical connection | Mostly abstract prompt discussion |
Suggested grading scale
For a short in-class activity:
- 2 points: correct classification
- 2 points: explanation and evidence
- 2 points: failure modes
- 2 points: improved prompt
- 2 points: validation/enforcement discussion
Total: 10 points
For a larger homework assignment:
- 20% classification accuracy
- 20% justification and evidence
- 20% failure-mode analysis
- 20% prompt rewrite quality
- 20% software-engineering validation plan
Instructor notes
Common student mistakes
Students may:
- Collapse the two axes — forgetting that “no examples → zero-shot” is its own binary question and that a zero-shot prompt can still carry a role, a rubric, and structured output. The split worksheet (examples axis, then additive techniques) is designed to resolve this: answer the examples axis first, then list the additive techniques, and the old “treat everything as just zero-shot” mistake disappears.
- Overvalue chain-of-thought and assume it is always better.
- Confuse “asking for JSON” with guaranteed valid JSON.
- Assume role prompting makes the model actually expert.
- Forget that prompts cannot verify external APIs.
- Treat tests as optional rather than part of the system.
- Focus on wording style instead of software-engineering risk.
- Improve prompts by making them longer rather than more precise.
- Fail to distinguish model uncertainty from task ambiguity.
- Miss security implications in ordinary-looking coding tasks.
Instructor emphasis
Repeat this sentence several times:
The right question is not “Which prompt trick should I use?” The right question is “What does this task need: context, examples, structure, reasoning, tools, validation, or human judgment?”
Possible homework extension
Ask students to bring a prompt they have used in a real programming task.
They must submit:
- The original prompt.
- Classification of the prompt strategy.
- Explanation of why they used that strategy.
- What went wrong or could have gone wrong.
- An improved version.
- A validation plan.
This creates a direct bridge between the lecture and their own AI-supported development practice.
Final takeaway slide
Use this as the final slide of the exercise.
Prompt strategy diagnosis
A good AI-supported developer does not merely write prompts.
A good AI-supported developer can:
- Identify the task type.
- Choose an appropriate steering strategy.
- Explain why that strategy fits.
- Predict likely failure modes.
- Add the right context, examples, format, or tools.
- Move hard guarantees out of the prompt and into validation.
- Keep human judgment where human judgment is required.
Prompting is influence. Software engineering turns influence into reliable systems.