Notes
All notes

Prompt Engineering (AI Engg #3)

Two engineers ask the same model the same question. The first gets prose they must regex apart, guesses at the format, and reruns twice a day. The second gets a validated JSON object on the first try, every time, for a third of the tokens. The difference is not cleverness. It is structure: knowing that a prompt is a specification, not a wish.

This chapter treats prompts the way an engineer treats an API contract. You will learn the anatomy of a production prompt, the handful of techniques that actually move quality, how to force structured output you can trust, and how streaming and caching change the economics. By the end you will be able to take a vague feature request and write the prompt that ships it.

Prompts are specifications

A prompt has four parts, and good ones make each explicit:

\[ \text{answer} = f(\underbrace{\text{role}}_{\text{who}} \oplus \underbrace{\text{context}}_{\text{what is known}} \oplus \underbrace{\text{task}}_{\text{what to do}} \oplus \underbrace{\text{format}}_{\text{what good looks like}}) \]

The most common production bug is a missing format. The model has no idea your parser expects {"priority": 1..5} and will happily return "Priority: High (5)". Specify it, or better, enforce it (Section 5).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=4.9cm, minimum height=0.72cm, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (r) at (0,0) {ROLE — who the model is, its hard rules};
  \node[b, fill=orange!15] (c) at (0,-1.05) {CONTEXT — documents, memory, facts};
  \node[b, fill=green!12] (t) at (0,-2.1) {TASK — one instruction, explicit};
  \node[b, fill=yellow!25] (f) at (0,-3.15) {FORMAT — schema, example, refusal rule};
  \draw[a] (r) -- (c); \draw[a] (c) -- (t); \draw[a] (t) -- (f);
  \node[font=\rmfamily\small, text=black!60, anchor=west, align=left] at (2.8,-1.6) {missing FORMAT\\$\Rightarrow$ parsing bugs\\missing ROLE\\$\Rightarrow$ drift in tone};
\end{tikzpicture}

The technique toolkit (and when each earns its tokens)

Not every technique helps every task. Reach for the cheapest that fixes your failure.

Technique What it does Reach for it when Cost
Zero-shot direct instruction + format task is common and clear cheapest
Few-shot (2–5) shows input→output pattern format is fiddly or style-specific +tokens per example
Chain-of-Thought “think step by step, then answer” arithmetic, logic, multi-hop +output tokens
Self-consistency sample N CoT answers, majority vote high-stakes numeric answers N× cost
ReAct interleave Thought/Action/Observation needs tools (Chapter 11) loop cost
Structured output JSON Schema / function call anything parsed by code ~free (also safer)
Decomposition split into sequential prompts task too big for one call more calls

Few-shot is the highest-return technique for formatting. Two things make examples work: they must be correct (a wrong example is worse than none) and they must be diverse (cover edge cases, not three near-duplicates). Two or three examples usually beat ten; beyond five you are paying tokens for noise.

Chain-of-Thought is the one to add for reasoning. The published result is robust: instructing the model to produce intermediate steps materially improves math and logic accuracy. The production trick is to ask for reasoning and a final field, so your code reads the field and humans can debug the reasoning:

Think step by step. Then output exactly:
{"reasoning": "...", "answer": "..."}
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum height=0.7cm, font=\rmfamily\small, inner sep=5pt},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (q) at (0,0) {Question};
  \node[b, fill=orange!15] (t1) at (2.0,0) {Thought 1};
  \node[b, fill=orange!15] (t2) at (4.0,0) {Thought 2};
  \node[b, fill=green!12] (ans) at (6.0,0) {Answer};
  \draw[a] (q) -- (t1); \draw[a] (t1) -- (t2); \draw[a] (t2) -- (ans);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3,-0.6) {CoT: compute first, commit last};
  \node[b, fill=gray!12] (s1) at (2.0,-1.6) {Sample};
  \node[b, fill=gray!12] (s2) at (4.0,-1.6) {Sample};
  \node[b, fill=gray!12] (s3) at (6.0,-1.6) {Sample};
  \node[font=\rmfamily\small, anchor=west] at (6.6,-1.6) {$\to$ majority vote};
  \draw[a, dashed] (ans.south) -- (s3.north);
\end{tikzpicture}

Structured output: stop parsing vibes

By 2026 every major provider supports schema-constrained generation. Use it instead of asking nicely for JSON. With OpenAI’s SDK and Pydantic, the library generates the schema, the model is constrained to it, and you get a typed object back:

# structured output — parse, don't pray
from pydantic import BaseModel, Field
from openai import OpenAI

class Ticket(BaseModel):
    category: str = Field(description="billing | bug | account | other")
    priority: int = Field(ge=1, le=5, description="1 = critical, 5 = low")
    summary: str = Field(description="one sentence, <= 25 words")
    needs_human: bool

client = OpenAI()
resp = client.beta.chat.completions.parse(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "Triage support tickets. Be conservative: set needs_human for refunds and legal."},
        {"role": "user", "content": "Invoice #42 charged twice, I need this fixed before Friday!"},
    ],
    response_format=Ticket,
)
ticket = resp.choices[0].message.parsed
print(ticket)          # Ticket(category='billing', priority=1, ...)

The schema is the prompt for format. This kills a whole class of bugs: no trailing commentary, no unescaped quotes, no missing fields. If the provider supports it, prefer this over “reply with JSON only.” Keep a deterministic fallback (retry once, then route to a human) for the rare schema failure.

Context in the prompt: order and attention

Where you put things matters. Models attend most reliably to the beginning and end of the context (“lost in the middle”). So:

[system] role + rules + format
[user]   <doc id="1">...</doc> <doc id="2">...</doc>   <- middle
         ...
         Question: ...                                  <- end, closest to answer

This is a preview of context engineering: prompt content is only half the job; placement is the other.

Few-shot example, done right

A concrete before/after. Vague prompt:

Summarize this customer feedback nicely.

Structured, few-shot prompt:

You extract actionable feedback. Return JSON only.

Example 1
Input:  "Love the app but export is painfully slow on big files."
Output: {"sentiment":"positive","theme":"performance","action":"speed up export"}

Example 2
Input:  "Cancelled because the price went up with no warning."
Output: {"sentiment":"negative","theme":"pricing","action":"notify before price changes"}

Now do the same for:
Input:  "The new dark mode is great, though settings are buried."

The examples teach the shape — three stable keys, lowercase themes, imperative actions — better than any adjective could. Run it and the model mirrors the schema reliably.

Streaming and caching: UX and economics

Streaming is not about quality; it is about perceived latency. The first token arrives fast (after prefill), so the user sees life immediately. In the SDK:

stream = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Write a 5-line poem about tokens."}],
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

Prompt caching is the cost/latency lever nobody uses early enough. Providers cache a prefix of your prompt (system instructions, a big static document, tool schemas) so repeated calls skip re-encoding it. Keep the stable stuff at the very front and the varying user text at the end; caching then cuts both latency and price on the cached portion. This is why “how you order a prompt” is an engineering decision, not a style one.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum height=0.8cm, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=green!20, minimum width=3.4cm] (s) at (0,0) {stable prefix (cached)};
  \node[b, fill=orange!20, minimum width=2.2cm] (v) at (3.4,0) {variable};
  \draw[a] (s.west) -- ++(-0.6,0);
  \draw[a] (v.east) -- ++(0.6,0);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.7,-0.55) {system + docs + tool schemas};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.4,-1.05) {user msg};
\end{tikzpicture}

A production prompt, assembled

Pulling it together — a support-reply drafter:

SYSTEM = """You are Acme's support assistant.

RULES
- Use ONLY the provided knowledge base excerpts.
- If the answer is not present, reply: {"reply": null, "escalate": true, "reason": "no_kb_match"}.
- Never promise refunds or legal outcomes; escalate those.

FORMAT
{"reply": "<draft or null>", "escalate": <bool>, "reason": "<short>"}
"""
def draft(user_msg, kb_chunks):
    context = "\n".join(f'<doc id="{i}">{c}</doc>' for i, c in enumerate(kb_chunks))
    return client.chat.completions.create(
        model="gpt-4o-mini", temperature=0.2,
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": f"{context}\n\nCustomer: {user_msg}"},
        ],
    ).choices[0].message.content

Everything from this chapter is present: role, hard rules, retrieval slot, a refusal path, and a machine-readable format. That refusal path — a legitimate “I don’t know” — is as important as the answer. Forced answers hallucinate.

Pitfalls

QQuestionSelf-check

What are the four parts of a prompt, and which do teams most often omit? When do you need CoT versus few-shot?

ASolution

Role, context, task, format. Format is omitted most, causing parsing bugs. Few-shot fixes shape and style (fiddly output structure); CoT fixes reasoning (arithmetic, logic, multi-hop). They compose: examples for format, a “think step by step” for the reasoning, then a final JSON field.

Next: Context Engineering (AI Engg #4) — prompt engineering controls the instruction; context engineering controls everything else the model sees.