The Agentic AI Codex
Ch 07 · Prompt Engineering
Chapter 07 · Craft

The Craft of Prompting

Prompting is half-software, half-writing. This chapter gives you the patterns, the prompting techniques with formal names (CoT, ToT, ReAct, Self-Consistency), the anatomy of a great system prompt, and the rubric to debug a bad one.

7.1 · The mental model

An LLM samples the most likely continuation of everything you give it. Your prompt is the context that shapes that distribution. Five levers move it:

  1. Role — who is the model?
  2. Task — what should it do?
  3. Examples — what does success look like?
  4. Constraints — what must / must not happen?
  5. Format — what shape should the answer take?

A prompt, anatomically

SYSTEM You are a senior data engineer. Refuse if the task involves PII you cannot verify. CONTEXT Schema: orders(id, customer_id, total, created_at), customers(id, email, country) TASK Write the SQL to find the top-10 customers by revenue in 2025. RULES Postgres syntax · round 2dp · return ONLY the SQL. EXAMPLES Q: top-3 by orders in 2024 → A: SELECT customer_id, COUNT(*) …

7.2 · The anatomy of a great prompt

# --- SYSTEM ---
You are a senior data engineer. You answer in clear, ordered steps.
Refuse if the task involves PII you cannot verify the user owns.

# --- CONTEXT ---
Schema:
  orders(id, customer_id, total, created_at)
  customers(id, email, country)

# --- TASK ---
Write the SQL to find the top-10 customers by revenue in 2025.

# --- CONSTRAINTS ---
- Use Postgres syntax
- Round totals to 2 decimals
- Return ONLY the SQL, no commentary

# --- EXAMPLES (few-shot) ---
Q: top-3 by orders in 2024
A: SELECT customer_id, COUNT(*) c FROM orders
   WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
   GROUP BY customer_id ORDER BY c DESC LIMIT 3;
The rule of three
If a prompt fails twice in the same way, don't tweak words — add a structural fix: a constraint, a counter-example, or a different output shape.

7.3 · Core techniques — definition + example each

Zero-shot

Definition. Ask the model to perform a task with no examples, relying entirely on its pre-training.

Example. Translate to French: "Tomorrow we travel." → "Demain nous voyageons."

Few-shot

Definition. Show 2–5 worked input/output pairs before the real task, so the model can mimic the pattern.

Example. "Classify sentiment. Ex 1: 'love this!' → positive. Ex 2: 'never again' → negative. Now: 'service was okay' →" → neutral.

Role prompting

Definition. Open with a persona that narrows tone, vocabulary, and defaults.

Example. "You are a senior tax accountant in the UAE. Answer cautiously and cite the article number when relevant."

Chain-of-Thought (CoT)

Definition. Instruct the model to think step by step before producing the final answer, so it uses its hidden scratchpad.

Example. "If a shirt costs Rs 1,200 with 17% sales tax included, what's the pre-tax price? Think step by step, then give the final answer."

Self-consistency

Definition. Sample N reasoning paths (high temperature, CoT), then majority-vote the final answer.

Example. A maths problem solved 7 times; 5 paths agree on 42 → answer is 42, even if 2 paths went astray.

ReAct

Definition. Interleave Reasoning, Action (tool call), and Observation in a visible trace.

Example. "Is BTC above $80k today?" → Thought: need price → Action: price.get('BTC') → Observation: 81,440 → Answer: yes.

Tree-of-Thoughts (ToT)

Definition. Branch reasoning into multiple paths, score each, prune the weak ones.

Example. Game of 24 — explore several arithmetic combinations in parallel, drop dead-ends.

Self-Refine

Definition. Generate → critique own output → revise. Repeat 1–2 rounds.

Example. Draft a cover letter → "list 3 weaknesses" → rewrite addressing each.

CoT vs ToT — branching reasoning

CoT — single chain step 1 step 2 answer ToT — branch + score + prune root branch A B (pruned) branch C A.1 ✓ C.1

7.4 · Advanced patterns

Tree-of-Thoughts (ToT)
Branch reasoning into multiple paths, score each, prune. Useful for puzzles, math, and planning. The cost is high so reserve it for problems where wrong answers are expensive.
Skeleton-of-Thought
First ask the model for a bullet skeleton; then expand each bullet in parallel. Cuts latency on long answers.
Self-Refine / Reflexion
Ask the model to critique and improve its own draft. Two rounds of refinement usually saturates the gain.
Plan-and-Execute
Step 1 — produce a numbered plan. Step 2 — execute each step (often calling tools). Separates strategy from tactics; easier to debug than one big prompt.
Meta-prompting
"Write the best prompt for X" — let the model design its own prompt, then run it. Excellent for bootstrapping new tasks.
Prompt chaining
Pipeline two or more LLM calls where the output of one feeds the next. Each call is simpler, easier to test, and cheaper than a monolithic prompt.

7.5 · Structured outputs — making LLMs machine-readable

Free text is for humans; downstream systems need structure. Three good techniques:

  1. JSON mode / response_format — most APIs let you constrain output to valid JSON.
  2. Schema-guided — pass a JSON Schema or Pydantic model; the API enforces it.
  3. Tool calling — declare a tool whose schema is your output (Ch 11).
# Tip: describe each field's meaning AND give one good example.
Return a JSON object exactly matching:
{
  "intent":  "billing" | "support" | "sales",
  "urgency": 1..5,
  "summary": <= 120 chars
}
Examples:
  Input:  "my card was charged twice"
  Output: {"intent":"billing","urgency":4,"summary":"duplicate charge"}

7.6 · System prompts that work in production

  • State the role. Senior, careful, concise.
  • State the goal. What does success look like for the user?
  • State the rules. What must never happen?
  • State the tools. When to use each, when not to.
  • State the format. Headings, JSON, length limits.
  • State the fallback. What to do if data is missing or the request is unsafe.

7.7 · Five reusable templates

Summarise the <DOC> below in 5 bullets.
Each bullet:
- starts with a verb
- <= 14 words
- preserves numbers verbatim
<DOC>…
Classify the user message into exactly one label:
[billing | support | sales | spam | other]
If uncertain, choose "other". Return only the label.
Message: "{{text}}"
From the contract below extract:
- parties
- effective date (ISO 8601)
- jurisdiction
- termination clauses (verbatim)
Return as JSON. If a field is missing use null.
Think step by step. Show your reasoning under "Thinking:".
Then give the final answer under "Answer:".
If a step needs data you don't have, request it instead of guessing.
Write a 150-word LinkedIn post by <persona> about <topic>.
Voice: confident, specific, never breathless.
Open with a 1-line hook, end with one question.
Avoid: emojis, hashtags, the words "thrilled" and "leverage".

7.8 · Debugging a bad prompt — a 7-step rubric

  1. Is the task stated explicitly, in one sentence?
  2. Are the inputs separated from the instructions (e.g. <DOC> tags)?
  3. Did you give an example of the desired output?
  4. Are constraints testable (lengths, must-include, must-avoid)?
  5. Are edge cases covered (missing data, refusal)?
  6. Is the output format machine-parseable?
  7. Did you try a stronger model as a sanity check?

7.9 · Five anti-patterns

  1. "Be helpful." Empty calorie. Specify how.
  2. 10 paragraphs of system prompt. Truncates and dilutes.
  3. Conflicting rules. "Be concise" + "list every detail" — the model picks one.
  4. Trusting free text. Always validate JSON; never eval() output.
  5. Prompt-only solutions. If you need fresh data, that's RAG, not prompting (Ch 9).

7.10 · Self-check

Q1 · Which technique most reliably boosts arithmetic / reasoning quality?
Role prompting
Chain-of-Thought
JSON mode
Higher temperature
Q2 · Best way to make output machine-readable?
Ask "please return JSON"
Use the API's structured-output / tool-calling schema
Regex-parse the free text
Higher temperature