1. Prompt Engineering

The art of asking LLMs the right question

You have access to a model that has read a significant fraction of the internet. It can write code, explain quantum mechanics, draft legal contracts, and translate between languages it was barely trained on. And yet the difference between a useless response and a brilliant one often comes down to how you asked.

Prompt engineering isn't magic — it's applied communication. Every technique in this article works because of something concrete about how language models process text. We'll start simple and build up to the patterns that power tools like Claude Code and ChatGPT's system prompts.

Why Prompts Matter

A language model is a next-token predictor. Given a sequence of tokens, it estimates a probability distribution over what comes next. Your prompt is that sequence. It's the only lever you have. Change the prompt and you change which region of the model's learned distribution you're sampling from.

This has a practical consequence: the model doesn't know what you want unless you tell it. It has no memory of your preferences, no understanding of your project, no context beyond the tokens you've provided in this conversation. A vague prompt activates a vague region of the distribution. A precise prompt narrows the beam to exactly the kind of output you need.

Zero-Shot Prompting

The simplest approach: just ask.

What are the main differences between TCP and UDP?

For well-known topics, this works fine. The model has seen thousands of explanations of TCP vs UDP and can produce a competent answer with no further guidance. Zero-shot prompting relies entirely on the model's pre-training knowledge.

It breaks down when:

  • The task is unusual or domain-specific
  • The expected output format matters (JSON, markdown tables, specific structure)
  • The model needs to follow a specific reasoning process

Few-Shot Prompting

Instead of describing what you want, show examples of input-output pairs:

Convert these function names to snake_case:

getUserName -> get_user_name
setHTTPHeader -> set_http_header
parseXMLDocument -> parse_xml_document
loadUIConfig ->

The model picks up the pattern from your examples and applies it. This is remarkably effective because transformers are, at their core, pattern-completion machines. The attention mechanism literally attends to the structure of your examples when generating the next tokens.

How many examples? Usually 2-5 is enough. More examples help with:

  • Ambiguous tasks where one example could be interpreted multiple ways
  • Edge cases you want handled consistently
  • Complex output formats

Example selection matters. If all your examples are simple cases, the model may fail on complex inputs. Include at least one example that covers an edge case or unusual situation.

System Prompts

Most modern LLM APIs separate the system prompt from the user message. The system prompt sets the model's role, constraints, and behavioral guidelines. The user message contains the actual request.

System: You are a senior TypeScript developer reviewing pull requests.
        Be direct. Flag bugs and security issues. Ignore style nitpicks
        unless they affect readability. Format feedback as a markdown list.

User:   Review this function:
        function getUser(id) {
          return fetch('/api/users/' + id).then(r => r.json())
        }

System prompts work because during training (especially RLHF and constitutional AI), models learn to treat the system message as high-priority instructions. It's not just "context" — it's closer to a behavioral specification.

Effective system prompts share common traits:

  • Role assignment — "You are a ___" activates domain-specific knowledge and communication style
  • Explicit constraints — what to do, what NOT to do, what to prioritize
  • Output format — markdown, JSON, bullet lists, code only
  • Tone and length — "Be concise", "Explain step by step", "Use analogies"

This is exactly how tools like Claude Code work. If you've ever looked at the system prompt of a coding assistant, it's typically thousands of tokens of carefully engineered behavioral instructions.

Chain-of-Thought

For problems that require reasoning — math, logic, multi-step analysis — simply asking for the answer often produces errors. The model generates the answer token in a single forward pass, but the problem requires multiple sequential steps.

The fix is simple: ask the model to think step by step.

Q: A store has 15 apples. They sell 40% of them in the morning and
   receive a shipment of 8 more in the afternoon. How many apples
   do they have at the end of the day?

A: Let me work through this step by step.

This works because each generated token can attend to all previous tokens. When the model writes out intermediate steps, those steps become part of the context for subsequent tokens. The model is literally giving itself scratch paper.

Chain-of-thought variants:

Technique How it works
Zero-shot CoT Add "Let's think step by step" to the prompt
Few-shot CoT Provide examples that include reasoning steps
Self-consistency Generate multiple CoT paths, take the majority answer

Chain-of-thought is most valuable for:

  • Mathematical reasoning
  • Multi-step logic problems
  • Code debugging (trace through execution)
  • Complex analysis with multiple factors

It's less useful (and wastes tokens) for simple factual recall or straightforward generation tasks.

Persona and Role Framing

Beyond system prompts, you can assign roles directly in the conversation:

You are a database performance engineer. A junior developer shows you
this query and says it's slow on a table with 50M rows:

SELECT * FROM orders WHERE customer_email LIKE '%@gmail.com'
ORDER BY created_at DESC;

Explain what's wrong and how to fix it.

Persona framing does two things:

  1. Activates domain knowledge — the model draws more heavily from expert-level training data
  2. Sets the communication register — a "database performance engineer" will talk about indexes and query plans, not vague generalities

You can stack personas for interesting effects: "Explain this like a compiler engineer talking to a frontend developer" produces explanations that bridge two domains.

Constrained Generation

Sometimes you need the model to follow exact formatting rules. Being explicit about constraints dramatically improves compliance:

List the 5 most common HTTP status codes. For each one, provide:
- The numeric code
- The standard reason phrase
- A one-sentence explanation

Format as a markdown table with columns: Code | Phrase | Meaning
Do not include any text before or after the table.

Constraint techniques that work:

  • Explicitly state the output format (JSON, CSV, markdown)
  • Say what to include AND what to exclude
  • Provide a template or skeleton for the model to fill in
  • Use delimiters to mark sections: <output>, triple backticks, XML tags

We'll go much deeper on this in the next article on structured output, where we'll look at JSON mode, function calling schemas, and techniques for getting machine-parseable responses every time.

Prompt Decomposition

Complex tasks fail not because the model can't do them, but because the prompt asks for too much at once. The fix: break the task into steps and chain the outputs.

Instead of:

Read this codebase and write comprehensive documentation for it.

Do:

Step 1: List all the public functions in this module with their signatures.
Step 2: For each function, write a one-line summary of what it does.
Step 3: Group the functions by category (data access, validation, transformation).
Step 4: Write a module overview that describes the categories and how they relate.

Each step is simple enough for the model to execute reliably, and each step's output provides context for the next. This is the manual version of what agentic systems automate — and we'll cover that in detail later in this series.

Negative Prompting

Telling the model what NOT to do is often as important as telling it what to do:

Explain how HTTPS works.
- Do not use analogies about locks and keys
- Do not simplify the TLS handshake — include all message types
- Do not say "simply put" or "in other words"

This works because RLHF training teaches models to follow instructions, including negations. Without negative constraints, models default to their most common training patterns — which often means oversimplified analogies and hedging language.

Temperature and Its Interaction with Prompts

Prompt engineering and sampling parameters work together. A well-crafted prompt with temperature=0 produces the most likely completion. The same prompt with temperature=0.8 introduces variety while staying within the distribution your prompt defined.

Practical guidelines:

  • Factual/analytical tasks: low temperature (0-0.3), precise prompts
  • Creative writing: higher temperature (0.7-1.0), looser prompts
  • Code generation: low temperature (0-0.2), very specific prompts with examples

A great prompt at the wrong temperature still fails. A mediocre prompt at the right temperature occasionally gets lucky. Get both right and you have reliable, high-quality output.

Putting It Together: Anatomy of a Production Prompt

Here's a simplified version of what a coding assistant's system prompt looks like, combining multiple techniques:

You are an expert software engineer. You help users modify codebases
by reading files, understanding context, and making precise edits.

RULES:
- Read files before modifying them. Never guess at file contents.
- Make minimal changes. Do not refactor code you weren't asked to change.
- If a task is ambiguous, ask for clarification instead of guessing.
- When you encounter an error, explain what went wrong and suggest a fix.

OUTPUT FORMAT:
- For code changes, show the exact edit as a diff.
- For explanations, be concise. Lead with the answer.
- Never apologize or use filler phrases.

TOOLS AVAILABLE:
- read_file(path): Read a file's contents
- edit_file(path, old, new): Replace text in a file
- run_command(cmd): Execute a shell command

This combines role assignment, explicit constraints, negative instructions, output format specification, and tool definitions. Every major coding assistant uses some version of this structure.

Common Pitfalls

Being too vague. "Make this code better" activates the model's generic "code improvement" distribution, which may not align with what you actually want. Say specifically: "Reduce the time complexity of this function" or "Add error handling for the network call."

Contradictory instructions. "Be concise but thorough" forces the model to balance two opposing goals and usually satisfies neither. Pick one and be specific about the tradeoff.

Ignoring the context window. Your prompt, all examples, and the expected output must fit within the context window. Stuffing in too many examples leaves no room for the model to generate a complete response.

Over-prompting simple tasks. Not everything needs chain-of-thought and a system prompt. "What's 2+2?" doesn't benefit from "Let's think step by step." Match the prompting complexity to the task complexity.

Try It — Prompt Technique Explorer

Temperature Visualizer

Drag the slider to see how temperature reshapes the probability distribution over the next token. Low temperatures concentrate probability on the top choice; high temperatures spread it out.

1.00
Sampled tokens (click temperature to resample):

Technique Comparison

Step through different prompting techniques to see how each one shapes the model's input and output.

PROMPT

  
OUTPUT

  

What's Next

This article covered the fundamentals of talking to LLMs. But human-readable responses are only half the story. The real power of LLMs in production comes from getting them to produce structured output — JSON, function calls, typed schemas — that code can parse and act on. That's exactly what the next article covers.