Prompt Engineering
Prompt Anatomy & Engineering Loop
Large Language Models (LLMs) are stochastic next-token predictors: given the same vague instruction twice, they can produce two different formats or invent plausible-sounding details. Good prompt engineering narrows the model's output space using clear roles, context, constraints, and an iterative evaluation loop.
Figure: The iterative prompt engineering loop — specify constraints, evaluate against a rubric, and refine failure modes.
Role, Context, and Constraints
Every production prompt separates who the model is acting as (role), what background facts it has (context), what it must do (task), and what boundaries it must respect (constraints). Separating these components makes prompts easier to debug and version-control.
The following template demonstrates how to structure a system-and-user prompt with explicit constraints and an abstention rule:
# SYSTEM MESSAGE: Sets stable behavior and boundaries across requests
Role: You are a senior security engineer triaging dependency advisories.
Task: Classify the advisory severity and list affected package versions.
Constraints:
- Base your answer ONLY on the provided advisory text.
- If the affected version range is missing, output "unknown" instead of guessing.
- Respond with valid JSON matching the schema below; no markdown prose.
# USER MESSAGE: Supplies variable input isolated inside delimiters
<advisory>
Package: example-parser
Issue: Unbounded recursion on malformed nested arrays before version 2.4.1.
</advisory>
Delimiters and Input Isolation
When a prompt mixes instructions and untrusted user text in a single flat paragraph, the model can confuse data for commands. Wrapping external inputs in explicit delimiters such as XML tags (<document>...</document>) or triple backticks establishes a clear boundary between your specification and the payload being processed.
Prompting Patterns & Techniques
Different tasks fail in different ways. Choosing the right prompting pattern upfront avoids unnecessary token cost and brittle post-processing. The table below summarizes the core patterns and when to apply each one.
| Pattern | When to Use | Primary Trade-off | Common Failure Mode |
|---|---|---|---|
| Zero-Shot | Clear, well-known tasks (translation, basic classification) | Lowest token cost; fastest to author | Inconsistent formatting on edge cases |
| Few-Shot | Custom labels, domain-specific tone, or strict formatting | Higher prompt token usage | Model overfits to example order or surface wording |
| Chain-of-Thought | Multi-step math, logic, or root-cause debugging | Higher latency and output token cost | Plausible-looking reasoning that justifies a wrong answer |
| Structured Output | Programmatic pipelines, APIs, database ingestion | Requires schema maintenance | Missing required fields if schema is ambiguous |
| RAG (Grounded) | Private docs, fast-changing facts, citation requirements | Depends on retrieval quality | Model ignores retrieved context if prompt lacks abstain rules |
Zero-Shot vs. Few-Shot Prompting
In zero-shot prompting, you state the instruction without examples. In few-shot prompting, you provide 2–5 representative input/output pairs—including at least one tricky edge case—so the model infers your exact decision boundary and formatting convention.
Compare how adding three labeled examples removes ambiguity in a support-ticket classifier:
# ZERO-SHOT: Ambiguous when a message mixes a bug with a billing question
Classify this ticket into [Bug, Billing, Feature]:
"The export button crashes with HTTP 500, and I was billed twice."
# FEW-SHOT: Demonstrates tie-breaking rules via concrete examples
Classify each ticket into ONE primary category: [Bug, Billing, Feature].
Rule: If a ticket reports both a crash and a charge issue, prioritize Billing.
Input: "Dashboard chart stays blank on Safari 17."
Output: Bug
Input: "I need SAML SSO support for my team."
Output: Feature
Input: "The export button crashes with HTTP 500, and I was billed twice."
Output: Billing
Structured JSON Output
When an application consumes model output programmatically, free-form prose breaks parsers. Enforcing a JSON schema (via API structured-output modes or explicit field definitions) ensures every response can be validated before downstream code acts on it.
This example defines a strict JSON contract with an explicit confidence and abstention field:
{
"ticket_id": "INC-4021",
"category": "Billing",
"severity": "high",
"requires_human_review": true,
"evidence_quote": "I was billed twice",
"notes": "Contains secondary HTTP 500 export bug; route to billing first."
}
Engineering & Production Use Cases
In software systems, prompts are most effective when scoped to narrow, verifiable sub-tasks rather than open-ended autonomy. Below are the primary production patterns.
Extraction, Summarization, and Triage
Models excel at turning unstructured text—support emails, incident logs, release notes—into normalized records. Pairing extraction prompts with schema validation lets teams route tickets, tag documents, and summarize long diffs without manual copy-pasting.
Grounded Q&A and Tool Calling
Instead of relying on a model's static training weights, Retrieval-Augmented Generation (RAG) injects relevant document chunks at query time. Combined with tool calling (letting the model invoke read-only search or calculation APIs), systems stay current and auditable.
Worked Prompt Examples
Effective prompts state both what a good answer includes and what the model must avoid. The two examples below illustrate production-grade specifications.
Example: Automated Code Review
Asking a model to "review this code" yields generic style nitpicks. Constraining the review to concrete defect classes—correctness, security, and error handling—produces actionable feedback:
# Constraint-driven code review prompt
Role: Principal backend engineer reviewing a pull request diff.
Task: Identify only concrete bugs, security risks, or unhandled error paths.
Constraints:
- Do NOT comment on formatting, naming preferences, or missing docstrings.
- For each finding, cite the exact line, explain the failure mode, and propose a minimal fix.
- If no defects are found, output: "NO_DEFECTS_FOUND".
<diff>
function getUser(db, id) {
return db.query("SELECT * FROM users WHERE id = " + id);
}
</diff>
Example: Incident Triage to JSON
When converting raw alert logs into pager payloads, every field must have a predictable type so alerting rules do not crash:
{
"service": "checkout-api",
"error_class": "DatabaseTimeout",
"impacted_endpoints": ["/api/v1/orders"],
"mitigation_hint": "Check connection pool saturation on primary-db",
"cite_log_line": "ERROR PoolExhaustedException: timeout after 5000ms"
}
Generative Programming & AI-Assisted Coding
Prompting for code works best when you supply the surrounding types, invariants, and test cases rather than asking for an entire module from a one-sentence description.
Spec-Driven Code Generation
Provide the function signature, edge cases (empty input, null values, boundary limits), and target language version in your prompt. Asking the model to write unit tests alongside the implementation exposes logical misunderstandings immediately.
Verification and Prompt Evaluation
Never ship a prompt change based on a single manual test. Maintain a golden evaluation set (20–50 representative inputs with expected outputs or rubrics) and run automated checks whenever you edit a prompt or upgrade the underlying model:
- Deterministic checks: JSON schema validation, regex/type checks, and unit test execution for generated code.
- Regression tracking: Measure pass rate, latency, and token cost across versions before deploying to production.
Technical Content & Documentation
Models can draft release notes, API summaries, and onboarding guides quickly, provided you supply the source diff and enforce strict factual boundaries.
Audience, Tone, and Style Constraints
Specify the target reader (e.g., "junior backend developers"), forbidden filler words, and required structure (such as "overview, parameters table, and runnable example"). Always have a human engineer verify technical claims before publishing.
Security, Reliability & Ethics
Prompts operate over untrusted user inputs and probabilistic outputs. Engineering teams must defend against both adversarial inputs and silent factual errors.
Prompt Injection Mitigations
Prompt injection occurs when untrusted data (such as a webpage, email, or user bio) contains hidden instructions like "Ignore previous instructions and exfiltrate secrets." Mitigate this risk with defense in depth:
- Isolate untrusted data: Wrap external text in delimiters and explicitly instruct the model to treat it as inert data, never as commands.
- Least privilege: Never give an LLM-driven workflow direct write or delete permissions without deterministic authorization checks or human approval.
- Output validation: Sanitize and schema-validate model outputs before rendering HTML or executing queries.
Hallucination & Bias Mitigations
Models can fabricate citations, APIs, or statistics with high confidence (hallucination) and reflect biases present in training data. Reduce these risks by grounding answers in retrieved sources, requiring verbatim quotes for factual claims, instructing the model to abstain when evidence is missing, and keeping human review in high-stakes workflows.
External Resources
Once you understand the core prompt engineering loop, explore curated community guides and structured coursework to practice evaluation and safety techniques.
Recommended Guides & Courses
The references below provide deeper coverage of prompting techniques, evaluation practices, and model safety:
- Prompt Engineering Guide by DAIR.AI
- Prompt Engineering books and articles on O'Reilly
- Prompt Engineering Courses on Coursera