Prompt Engineering

Prompt engineering is the practice of shaping the context a fixed language model uses to predict its next tokens.

The Big Question

The LLM section ended with inference and decoding. The model is trained. Its weights are fixed. At generation time, it receives tokens, predicts a distribution over next tokens, chooses one, appends it, and repeats.

How do you communicate with a machine that already knows a huge amount, but only acts through next-token prediction?

Consider two prompts sent to the same model:

Prompt A

explain quantum mechanics.

The answer is likely to be broad, generic, and uneven.

Prompt B

You are a physics professor teaching mathematically mature undergraduate students. Begin with intuition before introducing Hilbert spaces. Use analogies but do not sacrifice precision. Finish with the double slit experiment.

The answer is likely to be targeted, structured, and better matched to the reader.

Nothing inside the neural network changed. The model was not retrained. Prompt engineering asks why the behavior changed anyway.

Core Intuition

A beginner often thinks prompting means giving commands. But a language model is not a command interpreter in the ordinary sense. It is still doing the same thing it did in the previous chapter:

pθ(xtx<t)p_\theta(x_t\mid x_{<t})

Every word you type becomes tokens in the context window. Those tokens influence the probability distribution of every future token. Prompting works because context changes prediction.

If the prompt says You are an expert historian, the model does not literally become a historian. The tokens pass through embeddings, attention layers, and feed-forward networks. The resulting hidden state resembles contexts from training where expert historical answers followed. The next-token distribution shifts toward that kind of text.

Prompting Is Steering

The weights define what the model has learned. The prompt chooses which part of that learned behavior becomes relevant right now. Prompting does not rewrite the model. It steers generation through the context supplied at inference time.

Interactive Demo

Prompt builder lab

Context

The answer can connect to concepts already in the conversation.

Constraints and examples

Assembled context
Role: You are a clear machine learning teacher.

Task: Explain why prompt engineering works.

Context: The user is reading a chapter about token prediction, attention, and decoding.

Constraints:
- Use one concrete example.
- If information is missing, say what is missing.

Format: Use 4 bullet points.

Examples:
Input: Explain overfitting.
Output: Overfitting happens when a model memorizes training examples instead of learning a pattern that generalizes.
Input: Explain temperature.
Output: Temperature changes how strongly the decoder favors the model's most likely next tokens.
Context quality signal100/100

This score is a teaching aid, not a model metric. It shows how prompts become more useful as they include task, context, constraints, format, and examples.

Likely behavior shift

  • teacher-like explanation
  • context-aware framing
  • pattern follows examples
  • scannable bullets

The assembled prompt is not magic text. It is context. Better context usually gives the model a clearer distribution to continue from.

Mechanics

What A Prompt Becomes

A prompt is first tokenised:

prompt[x1,x2,,xT]\text{prompt}\rightarrow[x_1,x_2,\ldots,x_T]

Token IDs become embeddings, positional information is added, and transformer layers mix the context through attention. The final hidden state produces logits:

z=WouthT+bout\mathbf{z}=W_{\text{out}}h_T+b_{\text{out}}

Softmax converts logits into probabilities:

pi=ezijezjp_i=\frac{e^{z_i}}{\sum_j e^{z_j}}

A prompt changes hTh_T, which changes the logits, which changes the next-token probabilities. This is why wording, examples, documents, and constraints matter even though the weights are unchanged.

Why Roles Work

Role prompts work because training data contains many contexts where roles correlate with style, vocabulary, assumptions, and response structure. You are a lawyer shifts probability toward legal language. You are a kindergarten teacher shifts probability toward simpler explanations.

The role is not a belief. It is a contextual signal.

Why Examples Work

Few-shot examples establish a pattern inside the context window:

Review: Amazing movie.
Sentiment: Positive
Review: Terrible acting.
Sentiment: Negative
Review: The pacing was slow but the ending worked.
Sentiment:

The model notices the input-output rhythm and predicts the next label. Nothing about the weights changes. The pattern is learned in context.

Building Blocks Of A Good Prompt

Good prompts usually combine several ingredients. You rarely need all of them, but knowing the pieces makes prompt design more systematic.

BlockQuestionExample
TaskWhat should be done?Summarise this paper.
ContextWhat information should the model use?This paper studies reinforcement learning from human feedback.
ConstraintsWhat should or should not happen?Use under 200 words. Do not invent information.
FormatWhat should the answer look like?Return a markdown table with columns: claim, evidence, caveat.
ExamplesWhat pattern should the model continue?Input: Amazing movie. Output: Positive.

A Concrete Before And After

Weak prompt

Summarise this meeting.

The model must guess audience, purpose, format, and what counts as important.

Stronger prompt

Summarise this product meeting for an engineering lead. Include decisions, unresolved questions, owners, and deadlines. Use a markdown table. If no owner is mentioned, write Unknown.

The model has a task, audience, schema, and uncertainty rule.

Major Prompting Patterns

PatternPurposeExample
Zero-shotAsk directly without examplesClassify this review as Positive or Negative.
Few-shotShow input-output examplesReview: Great. Positive. Review: Boring. Negative. Review: ...
Role promptingShift style and domain patternsYou are a careful ML instructor.
Structured outputSpecify the response schemaReturn valid JSON with keys: answer, evidence, uncertainty.
DecompositionBreak the task into smaller stepsFirst identify constraints, then propose options, then choose one.
Critique and reviseAsk the model to inspect and improve a draftFind missing assumptions, then rewrite the answer.

Reasoning Prompts

Prompts that ask the model to decompose a task often improve results. The useful part is not a magic phrase. The useful part is structuring the context so intermediate checks happen before the final answer.

First identify the user's constraints.
Then list two possible solutions.
Then choose the safer option and explain why.

Modern frontier models may reason internally even when they do not expose their full reasoning process. The practical lesson remains: difficult tasks often improve when the system creates useful intermediate structure, whether it is visible to the user or not.

When Prompting Fails

Prompting cannot create knowledge that is not in the model or supplied context. If you ask about tomorrow's events, a model can only guess unless it has a tool or data source. If you ask about a private company document the model cannot see, it may hallucinate a plausible answer.

FailureCauseBetter response
Missing knowledgeThe answer is not in the model or contextUse retrieval, tools, or ask for the missing source.
Ambiguous taskThe model must guess what success meansDefine the goal, audience, and evaluation criteria.
Weak contextThe prompt lacks the documents or facts neededProvide the relevant material or connect retrieval.
Conflicting instructionsDifferent prompt parts point in different directionsResolve priority and remove contradictions.
Unverifiable outputThe answer sounds plausible but may be falseAsk for citations, uncertainty, or external checks.

Hallucinations

A language model is optimized to produce likely continuations, not to verify truth. When asked Who won the Nobel Prize in Physics in 2045?, it may still produce a confident-looking answer because a confident answer is a plausible continuation. Prompting can encourage uncertainty, but factual reliability often requires retrieval, tools, verification, or human review.

Prompting, Fine-tuning, And Retrieval

Prompting changes the input. Fine-tuning changes the weights. Retrieval changes the information available in the context.

NeedBest first toolWhy
One-off task instructionsPromptingCheap, temporary, and easy to change
Stable repeated behaviorFine-tuningThe same behavior is needed every day
Current or private factsRetrievalThe model needs information outside its weights
External actionsToolsThe model must calculate, search, write, or call software

From Prompt Engineering To Context Engineering

Early prompting focused heavily on wording because context windows were small and models were brittle. Modern models can often process much larger contexts, so the bigger question is not merely how to phrase one sentence. It is what information the model should see.

Context engineering asks:

  • What documents should be included?
  • What examples are most representative?
  • What constraints and policies matter?
  • What tools can the model access?
  • What user or task memory is relevant?
  • What information is missing?

Think of the model as a knowledgeable but amnesiac researcher. Each conversation begins with an empty desk. The prompt lays out documents, instructions, examples, and constraints on that desk before work begins. The quality of those materials largely determines the quality of the answer.

Implementation

In an application, prompt engineering usually becomes a function that assembles context from structured pieces.

def build_prompt(task, context, constraints, examples):
    sections = []

    sections.append("Role: You are a careful machine learning tutor.")
    sections.append(f"Task: {task}")

    if context:
        sections.append(f"Context:\n{context}")

    if constraints:
        sections.append(
            "Constraints:\n" + "\n".join(f"- {item}" for item in constraints)
        )

    if examples:
        formatted_examples = []
        for example in examples:
            formatted_examples.append(
                f"Input: {example['input']}\nOutput: {example['output']}"
            )
        sections.append("Examples:\n" + "\n\n".join(formatted_examples))

    sections.append("Answer:")
    return "\n\n".join(sections)

The important engineering move is that prompts become testable artifacts. You can version them, run evaluation cases, compare outputs, and inspect failures instead of relying on vibes.

Interview Discussion

Why does prompting work if the weights do not change?

The prompt changes the context tokens, which changes hidden states, logits, and next-token probabilities.

Why do few-shot examples work?

They establish an input-output pattern in the context window, and the model continues that pattern.

What is the difference between prompting and fine-tuning?

Prompting changes the input for one inference run. Fine-tuning changes model weights through training.

When is retrieval better than prompting?

When the missing ingredient is external, private, current, or too large to be stored reliably in the model weights.

What is context engineering?

The broader practice of assembling the right instructions, examples, documents, memory, tool outputs, and constraints for the model.

Active Recall

1. Why can two prompts produce different answers from the same model?

2. What does a prompt become inside the transformer?

3. Why do role prompts shift model behavior?

4. What are the five common building blocks of a strong prompt?

5. What is the difference between zero-shot and few-shot prompting?

6. Why can prompting fail on missing or future information?

7. When should you consider fine-tuning instead of prompting?

8. Why is prompt engineering evolving into context engineering?

Common Mistakes

  • Treating prompt engineering as memorizing tricks. The deeper principle is that context changes token prediction.
  • Expecting prompting to create missing knowledge. If the model lacks the information, supply it or retrieve it.
  • Adding long instructions without resolving ambiguity. More words are not always better context.
  • Ignoring output format. Applications often need structured outputs, not just fluent prose.
  • Evaluating prompts by one example. Prompt changes should be tested across representative cases.

Connection To Retrieval-Augmented Generation

Prompting is powerful when the model has the right information in its context. But many useful applications depend on information that is private, changing, too long, or absent from the model weights.

The next lesson introduces retrieval-augmented generation. Instead of hoping the model already knows the answer, the system searches for relevant external information and places it into the context before generation.