Prompt Engineering Cheat Sheet
Summarizes core prompting techniques such as few-shot examples, chain-of-thought, and system prompts for getting reliable output from large language models.
Core Techniques
Foundational prompting patterns.
- Zero-shot prompting- Asking the model to perform a task with only an instruction, no examples
- Few-shot prompting- Providing a handful of input/output examples in the prompt before the real query, to demonstrate the desired format
- Chain-of-thought (CoT)- Asking the model to reason step by step before giving a final answer, which improves accuracy on multi-step problems
- System prompt- A persistent instruction (role, tone, constraints) set once and applied across the conversation, separate from user turns
- Role prompting- Asking the model to respond "as" a persona (e.g., "You are a senior SQL reviewer") to steer tone and focus
A Well-Structured Prompt
Separate role/context, task, format, and constraints clearly.
SYSTEM: You are a technical writer who explains concepts to beginners.Use plain language and avoid jargon unless you define it.USER:Task: Summarize the following article in 3 bullet points.Constraints: Each bullet must be under 20 words. No introductory sentence.Article: <article text here>
Few-Shot Example Prompt
Show the model the input/output pattern before asking for a new one.
Classify the sentiment as Positive, Negative, or Neutral.Review: "The battery life is incredible and it charges fast."Sentiment: PositiveReview: "It arrived broken and support never replied."Sentiment: NegativeReview: "It's fine, does what it says on the box."Sentiment: NeutralReview: "Setup was confusing but the results were worth it."Sentiment:
Best Practices
What tends to move accuracy most in practice.
- Be explicit about output format- Specify JSON schema, bullet count, or word limits directly rather than hoping the model infers it
- Put instructions near long context- Repeat key instructions before and after long context -- models can under-weight instructions buried before a long document
- Iterate with real failure cases- Collect prompts that fail, adjust wording/examples, and re-test rather than guessing at improvements
- Ask for reasoning then the answer- For complex tasks, request step-by-step reasoning before the final answer, and extract only the final answer downstream
- Use delimiters- Wrap user-supplied content in triple quotes, XML tags, or markdown fences so the model can't confuse it with instructions
Advanced Reasoning Techniques
Patterns that go beyond a single-pass chain-of-thought.
- Self-consistency- Sample multiple chain-of-thought completions at nonzero temperature and take a majority vote over final answers, improving accuracy on arithmetic/logic tasks
- Tree-of-thought- Explore multiple reasoning branches at each step, evaluate/prune them, and backtrack -- suited to search-like problems such as planning or puzzles
- ReAct- Interleave reasoning traces with tool calls and observations ('Thought -> Action -> Observation') so the model can look things up mid-reasoning
- Least-to-most prompting- Decompose a hard problem into an ordered list of simpler subproblems and solve them sequentially, feeding each answer forward
- Program-aided (PAL)- Have the model emit code for the computational part of a task, then execute it rather than trusting arithmetic done 'in its head'
- Meta-prompting- Ask the model to critique or rewrite its own draft output before finalizing, catching errors a single pass would miss
Self-Consistency via Majority Vote
Sample several reasoning paths and keep the most common final answer.
responses = []for _ in range(5): response = client.messages.create( model="claude-sonnet-5", max_tokens=512, temperature=0.7, messages=[{ "role": "user", "content": prompt + "\nThink step by step, then give the final answer after 'Answer:'.", }], ) responses.append(extract_final_answer(response))from collections import Counterfinal_answer = Counter(responses).most_common(1)[0][0]
ReAct-Style Tool-Use Prompt
Interleaving thoughts, tool actions, and observations.
Answer the question using the following tools: search(query), calculator(expr).Use this format:Thought: reasoning about what to do nextAction: tool_name(argument)Observation: <result returned by the tool>... (repeat Thought/Action/Observation as needed)Thought: I now have enough informationAnswer: <final answer>Question: What is the population of the capital of France, divided by 100?Thought: I need to find the capital of France, then its population.Action: search("capital of France")Observation: ParisThought: Now I need the population of Paris.Action: search("population of Paris")Observation: 2,102,650Thought: I now have enough informationAction: calculator(2102650 / 100)Observation: 21026.5Answer: Approximately 21,026.5
Guaranteed JSON via Tool Schema
Force structured output by defining a tool input schema instead of asking nicely.
tools = [{ "name": "extract_invoice", "description": "Extract structured fields from an invoice.", "input_schema": { "type": "object", "properties": { "vendor": {"type": "string"}, "total": {"type": "number"}, "due_date": {"type": "string", "format": "date"}, }, "required": ["vendor", "total", "due_date"], },}]response = client.messages.create( model="claude-sonnet-5", max_tokens=256, tools=tools, tool_choice={"type": "tool", "name": "extract_invoice"}, messages=[{"role": "user", "content": f"Extract fields from:\n{invoice_text}"}],)# response.content contains a tool_use block whose .input matches the schema exactlyfields = response.content[0].input
Prompt Injection Defenses
Practical mitigations when prompts include untrusted retrieved or user content.
- Treat retrieved content as data, not instructions- Wrap it in delimiters and explicitly state that text inside <document> tags is data to analyze, never commands to follow
- Least-privilege tools- Only expose the tools/actions a given prompt actually needs, so an injected instruction has nothing dangerous to invoke
- Output-side validation- Check tool calls and structured outputs against an allowlist/schema before executing them; don't trust the model's plan blindly
- Trust hierarchy- System-prompt instructions should take precedence over anything found in fetched pages, tool results, or user-supplied text
- Canary/red-team injections- Test the pipeline with known injection strings ('ignore previous instructions...') to confirm guardrails hold before shipping
For tasks needing a strict output format (JSON, CSV), show one concrete example of the exact format in the prompt rather than only describing it in words -- models follow a shown pattern far more reliably than a described one.