Cheat sheets

Prompt Engineering

Write the prompt, add examples and reasoning, vote, and budget the context window. Python from the lessons.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

What goes in the window#

totalSystem promptabout 500 tokensTool definitions2K to 8K tokensRetrieved context2K to 10K tokensConversationhistory2K to 20K tokensFew-shot examples1K to 3K tokensUser query100 to 500 tokensGeneration budget2K to 8K tokensContext windowinput plus outputtotalSystem promptabout 500 tokensTool definitions2K to 8K tokensRetrieved context2K to 10K tokensConversationhistory2K to 20K tokensFew-shot examples1K to 3K tokensUser query100 to 500 tokensGeneration budget2K to 8K tokensContext windowinput plus output

From Lesson 11.05

Assemble context per query#

1ContextBudgetavailable tokens are max_tokens minusgeneration_reserve.2System promptallocate it first, up to 1000 tokens.3select_toolsclassify_intent picks intents. Keep matchingtools within 2000 tokens.4score_relevancekeep documents with word overlap of 0.05 ormore.5reorder_lost_in_middlebest documents at both ends. Allocate up to3000.6ConversationManagersummarized old turns plus recent turns, up to5000.7User queryallocate it last, up to 500 tokens.

From 11.05 code/main.py, Lesson 11.05

Tasks in code#

TaskCode
Build a prompt from a patternbuild_prompt("persona", <variables>)
Build a multi-turn message listbuild_multi_turn(<pattern>, <turns>)
Score one outputscore_response(<text>, <criteria>)
Few-shot CoT promptbuild_cot_prompt(question, examples, num_examples=3)
Majority vote over samplesself_consistency_solve(question, examples, client, model, n_samples=5)
CoT, then vote, then ToTsolve_with_escalation(question, examples, client, model)
Budget the windowContextBudget(max_tokens=128000, generation_reserve=4000)
Prune tools by intentselect_tools(query, token_budget=2000)

From 11.01 code/prompt_engineering.py, 11.02 code/advanced_prompting.py, 11.05 code/main.py

Self-consistency vote#

system, user = build_cot_prompt(question, examples)3 worked examples
answers = []
for _ in range(n_samples):n_samples=5
text = call_llm(client, model, system, user, temperature=0.7)
answer = extract_answer(text)reads "The answer is <n>"
if answer is not None:
answers.append(answer)
vote_counts = Counter(answers)
best_answer = vote_counts.most_common(1)[0][0]majority answer
confidence = vote_counts[best_answer] / len(answers)
if confidence >= 0.8 and single_answer == sc_answer:
...accept the vote
tree_of_thought_solve(question, client, model, breadth=3, depth=2)else

From 11.02 code/advanced_prompting.py

Defaults and numbers#

SettingDefaultNote
Temperature, extraction and code0.0Top-p 1.0. Also for prompt tests
Temperature, summarization0.3Top-p 0.9
Temperature, general Q&A0.7Top-p 0.95
Few-shot examples3-5One per label for many labels
n_samples5At temperature 0.7. N=3 is the minimum vote
Vote confidence to accept0.8Below it, escalate to Tree-of-Thought
generation_reserve4000Tokens kept free for the answer
System prompt sizeunder 500 tokensFor most tasks

From Lesson 11.01, Lesson 11.02, 11.02 code/advanced_prompting.py, 11.05 code/main.py

Pick a reasoning technique#

CommandWhat it does
Zero-shotSimple tasks. 1 call, no overhead
Few-shotFormat matching. 200-500 extra tokens
Zero-shot CoTAdd "Let's think step by step". 50-200 tokens
Few-shot CoTBest single-call accuracy. 300-600 tokens
Self-consistency, N=5High-stakes reasoning. 5x token cost
Tree-of-ThoughtSearch and planning. 10-40+ calls
ReActKnowledge-grounded reasoning. 3-10+ calls
Prompt chainingComplex multi-step tasks. 2-5 calls

From Lesson 11.02

Prompt anatomy and patterns#

System message
identity, rules and constraints. Persists across turns.
User message
the task. Changes every turn.
Assistant prefill
a partial response such as { that sets the format.
Role
a specific role narrows the output distribution.
Constraints
negative "Do NOT", positive "Always", conditional "If X then Y".
Delimiters
XML tags such as <analysis> keep sections apart.
Clarity
state format, length, audience, include and exclude, one example.
Lost in the middle
85-90% accuracy first or last, 60-70% in the middle.

From Lesson 11.01, Lesson 11.05

Troubleshooting#

SymptomCauseFix
Generic, median-quality outputVague task, generic roleGive a specific role, format, length, audience
Confident nonsenseRole too rare in training dataUse a less narrow role
Model follows one rule, drops anotherContradictory instructionsAudit the prompt for conflicts
Task quality drops2,000 words of rulesKeep the system prompt under 500 tokens
User text overrides the rulesPrompt injectionValidate input, use delimiters, filter output
All votes identicalSamples at temperature 0.0Sample at 0.7
Votes cannot be comparedNo fixed answer formatEnd with "The answer is [number]"
Key fact ignoredFact in the middle of a long contextPut it first or last, or repeat it at the end

From Lesson 11.01, Lesson 11.02, Lesson 11.05

Abbreviations#

CoT
Chain-of-Thought. Reasoning tokens before the final answer.
ToT
Tree-of-Thought. Generate, score and prune reasoning branches.
ReAct
Thought, Action, Observation loop with tools.
Self-consistency
N samples at temperature above 0, majority vote.
Top-p
nucleus sampling. Smallest token set with cumulative probability p.
Few-shot
2-10 input and output examples in the prompt.
NIAH
Needle in a Haystack. Tests recall by position in long context.

From Lesson 11.01, Lesson 11.02, Lesson 11.05

Questions#

Why does CoT help?
Each reasoning token is context for the next. It extends computation depth.
When does CoT hurt?
Simple recall and single-step classification. It adds 50-200 tokens.
CoT on a reasoning model?
No. It reasons internally. The phrase is redundant.
Why test at temperature 0 first?
It separates prompt quality from sampling noise.
Temperature and top-p together?
No. Use one. They interact unpredictably.

From Lesson 11.01, Lesson 11.02

Tips#

  • Pick examples similar to the input. Cover every label.
  • Put critical instructions first and the query last.
  • Drop retrieved chunks below a relevance threshold. Bad retrieval is worse than none.
  • Include only the tools the intent needs. Tool tokens drop 60-80%.
  • Summarize history past a threshold such as 5,000 tokens.
  • Put stable parts at the top and variable parts at the bottom for prompt caching.

From Lesson 11.02, Lesson 11.05, Lesson 11.15