|$ curl https://forge-ai.dev/api/markdown?path=docs/ai/prompt-patterns
$cat docs/prompt-patterns.md
updated Recently·40 min read·published

Prompt Patterns

AIPromptsIntermediate
Introduction

Prompt patterns are reusable prompting techniques that reliably improve LLM output quality across diverse tasks. These patterns encapsulate years of empirical research and production experience into concrete, repeatable strategies.

Each pattern addresses a specific failure mode: lack of structure, missing knowledge, reasoning errors, or format inconsistency. Choosing the right pattern for your task is the most important prompt engineering decision you will make.

Persona Pattern

The persona pattern assigns a specific role, expertise level, or identity to the model. This activates domain-specific knowledge encoded in the model's training data and adjusts tone, vocabulary, and response structure accordingly.

persona-pattern.txt
TEXT
1You are a PhD-level research scientist specializing in computational biology. You have published in Nature and Cell. Review the following research abstract and provide feedback on:
2
31. Methodological rigor — are the statistical tests appropriate?
42. Potential confounding variables that were not addressed
53. Alternative interpretations of the results
64. Suggestions for additional experiments
7
8Be critical and specific. This will be submitted to a peer-reviewed journal.

info

The persona pattern works because LLMs encode expertise-level information in their training data. A prompt that says "explain like I am 5" activates different neural pathways than "explain to a domain expert." Be specific about the persona's background, goals, and constraints.
Chain-of-Thought Pattern

Chain-of-thought (CoT) prompting instructs the model to externalize its reasoning process before producing a final answer. This dramatically improves accuracy on multi-step reasoning tasks by making the intermediate steps explicit and auditable.

chain-of-thought-physics.txt
TEXT
1A ball is thrown upward from ground level with an initial velocity of 20 m/s. How high does it go? Assume g = 9.8 m/s².
2
3Let's reason through this step by step:
4
51. Given: v₀ = 20 m/s, v = 0 m/s (at peak), g = -9.8 m/s² (upward positive)
62. Use kinematic equation: v² = v₀² + 2aΔy
73. Substitute: 0 = (20)² + 2(-9.8)Δy
84. Simplify: 0 = 400 - 19.6Δy
95. Solve: 19.6Δy = 400
106. Result: Δy = 400 / 19.6 ≈ 20.41 m
11
12The ball reaches approximately 20.4 meters above ground level.

For zero-shot CoT, simply append Let's think step by step. or Let's work through this. to any prompt. This single phrase has been shown to improve accuracy on arithmetic and logic tasks by 10-30%.

zero-shot-cot.txt
TEXT
1# Zero-shot CoT — just add one line
2A store has 150 apples. They sell 30% of them in the morning and 40% of the remaining in the afternoon. How many apples are left?
3
4Let's think step by step.

best practice

Always use temperature=0 with chain-of-thought prompts for deterministic reasoning. If you need maximum accuracy, use self-consistency: run CoT 3-5 times with temperature > 0 and take the majority answer.
Few-Shot Pattern

Few-shot prompting provides input-output examples within the prompt to demonstrate the desired behavior. This is one of the most reliable techniques for controlling output format, style, and content.

few-shot-sql.txt
TEXT
1Convert natural language commands to SQL queries.
2
3Table: employees (id, name, department, salary, hire_date)
4Table: departments (id, name, manager)
5
6Command: "Show me all employees in Engineering who earn more than $100k"
7SQL: SELECT e.* FROM employees e JOIN departments d ON e.department = d.id WHERE d.name = 'Engineering' AND e.salary > 100000;
8
9Command: "Who is the manager of the Sales department?"
10SQL: SELECT d.manager FROM departments d WHERE d.name = 'Sales';
11
12Command: "What is the average salary by department?"
13SQL: SELECT d.name, AVG(e.salary) FROM employees e JOIN departments d ON e.department = d.id GROUP BY d.name;
14
15Command: "Find the employee with the highest salary in each department"
16SQL:

info

The optimal number of few-shot examples depends on task complexity. For simple format tasks, 1-2 examples suffice. For complex tasks with nuanced rules, 5-10+ examples may be needed. Always place the most diverse examples first to maximize the in-context learning signal.
Tree-of-Thought Pattern

Tree-of-thought (ToT) extends CoT by exploring multiple reasoning paths simultaneously. The model evaluates intermediate states and branches, pruning unpromising paths and pursuing promising ones. This is especially effective for puzzles, planning, and creative problem-solving.

tree-of-thought.txt
TEXT
1We need to plan a 3-day team offsite for 20 people with a $15k budget. Consider three approaches:
2
3Approach A: Local conference room + catered meals
4- Venue cost: $3k for 3 days
5- Catering: $2.5k ($42/person/day)
6- Activities: $2k (team building games)
7- Contingency: $1k
8Total: ~$8.5k ✓ within budget
9
10Approach B: Offsite retreat center (2 hours away)
11- Venue: $6k (includes lodging for 2 nights)
12- Meals: $3k (included in venue)
13- Transportation: $1.5k (bus rental)
14- Activities: $2k (hiking, ropes course)
15Total: ~$12.5k ✓ within budget
16
17Approach C: Destination (flight required)
18- Flights: $8k ($400/person)
19- Hotel: $6k (3 nights, $100/night)
20- Meals: $4k
21- Venue/Activities: $3k
22Total: ~$21k ✗ over budget
23
24Evaluation: Approach B offers the best balance of team bonding, cost efficiency, and engagement. Recommend B.
🔥

pro tip

Tree-of-thought prompting can be implemented programmatically by sampling multiple completions at each reasoning step, evaluating them with the model, and branching on promising paths. This is computationally expensive but can solve problems that standard CoT cannot.
Generated Knowledge Pattern

Generated knowledge prompting asks the model to first generate relevant facts or context about a topic before answering a question. This primes the model with relevant information, improving accuracy on knowledge-intensive tasks.

generated-knowledge.txt
TEXT
1Question: What are the main causes of coral bleaching and how do they interact?
2
3First, let me recall relevant facts about coral bleaching:
4
51. Coral bleaching occurs when corals expel symbiotic algae (zooxanthellae) living in their tissues
62. Primary cause: elevated sea surface temperatures (1-2°C above normal)
73. Secondary causes: ocean acidification, pollution, overexposure to sunlight
84. These stressors damage the algae's photosynthetic machinery
95. Without algae, coral tissue becomes transparent, revealing white skeleton
106. Prolonged bleaching leads to coral death and ecosystem collapse
117. Mass bleaching events have increased in frequency from once per 25 years to once per 6 years
12
13Now answering the question:
14
15The main cause of coral bleaching is elevated sea surface temperatures due to climate change. When temperatures exceed normal ranges by 1-2°C, the symbiotic zooxanthellae experience oxidative stress, producing toxic compounds. This causes corals to expel them. Ocean acidification compounds this by reducing the corals' ability to rebuild their calcium carbonate skeletons. Local factors like pollution and sedimentation add additional stress, lowering the temperature threshold at which bleaching occurs. The interaction of global warming with local stressors creates a compounding effect where corals have less recovery time between events.

best practice

Use generated knowledge for questions that require up-to-date or domain-specific information. Combine it with retrieval-augmented generation (RAG) for the best results: first retrieve relevant documents, then generate knowledge summaries from those documents, then answer.
Self-Consistency Pattern

Self-consistency samples multiple reasoning paths and selects the most consistent answer via majority voting or weighted aggregation. This reduces variance and improves accuracy on tasks with multiple valid reasoning approaches.

self-consistency.py
Python
1import openai
2from collections import Counter
3
4client = openai.OpenAI()
5
6def self_consistency(prompt, n_samples=5, temperature=0.5):
7 """Sample multiple reasoning paths and return majority answer."""
8 responses = []
9 for i in range(n_samples):
10 response = client.chat.completions.create(
11 model="gpt-4o",
12 messages=[
13 {"role": "user", "content": prompt + "\n\nLet's think step by step."}
14 ],
15 temperature=temperature,
16 max_tokens=300,
17 )
18 responses.append(response.choices[0].message.content)
19
20 # Extract final answers and take majority vote
21 # This assumes the model outputs "Answer: ..." at the end
22 answers = []
23 for r in responses:
24 if "Answer:" in r:
25 answer = r.split("Answer:")[-1].strip()
26 answers.append(answer)
27
28 if not answers:
29 return responses[0]
30
31 most_common = Counter(answers).most_common(1)[0][0]
32 return most_common
33
34
35# Example: arithmetic reasoning
36prompt = "A bat and a ball cost $1.10 in total. The bat costs $1.00 more than the ball. How much does the ball cost?"
37result = self_consistency(prompt, n_samples=5)
38print(f"Consensus answer: {result}")

warning

Self-consistency increases token usage and latency linearly with the number of samples (n_samples × tokens_per_sample). Use it only for high-stakes reasoning tasks where accuracy is more important than cost or speed. For production, start with 3 samples and increase only if needed.
ReAct Pattern

ReAct (Reasoning + Acting) interleaves reasoning traces with tool calls. The model thinks about what information it needs, calls tools to get it, observes results, and continues reasoning. This is the pattern underlying modern agent frameworks.

react-pattern.txt
TEXT
1Question: What is the current population of Tokyo and how does it compare to New York City?
2
3Thought: I need to find current population data for both cities. Let me search for this information.
4
5Action: search[Tokyo population 2025]
6Observation: Tokyo has approximately 37.2 million people in the metropolitan area (2025 estimate).
7
8Action: search[New York City population 2025]
9Observation: New York City has approximately 8.3 million people in the city proper, 19.0 million in the metropolitan area.
10
11Thought: Now I can compare. Tokyo's metropolitan area (37.2M) is roughly twice the size of NYC's metro area (19.0M). The city proper comparison is not directly comparable since Tokyo's city proper definition is different.
12
13Action: search[Tokyo city proper vs metropolitan area]
14Observation: Tokyo's 23 special wards (city proper) have about 9.7 million people. The metropolitan area includes surrounding prefectures.
15
16Thought: For a fair comparison, metropolitan area to metropolitan area: Tokyo 37.2M vs NYC 19.0M. Tokyo is about 96% larger.
17
18Answer: Tokyo's metropolitan area has approximately 37.2 million people, while New York City's metropolitan area has about 19.0 million. Tokyo is roughly 96% larger than NYC in metro population. When comparing city proper, Tokyo's 23 wards (9.7M) are slightly larger than NYC's 8.3M, but metro area is the more appropriate comparison for these sprawling cities.

info

The ReAct pattern is the foundation of agentic AI systems. In production, implement this with structured tool definitions and a loop that checks for tool calls in the model's output. The key insight is that reasoning traces improve tool selection and tool results improve reasoning.
Skeleton-of-Thought Pattern

Skeleton-of-thought asks the model to first generate a structured outline or skeleton of the response, then expand each section. This improves coherence and structure in long-form generation by separating planning from execution.

skeleton-of-thought.txt
TEXT
1Write a comprehensive guide to Kubernetes for DevOps engineers.
2
3First, generate a skeleton outline:
4
5# Kubernetes Guide for DevOps Engineers
6
7## 1. Core Concepts
8 - 1.1 Clusters, Nodes, and Pods
9 - 1.2 Deployments and ReplicaSets
10 - 1.3 Services and Networking
11
12## 2. Configuration & Management
13 - 2.1 ConfigMaps and Secrets
14 - 2.2 Namespaces and RBAC
15 - 2.3 Helm Charts
16
17## 3. Observability
18 - 3.1 Logging with Fluentd
19 - 3.2 Monitoring with Prometheus
20 - 3.3 Tracing with Jaeger
21
22## 4. Production Best Practices
23 - 4.1 Resource Requests and Limits
24 - 4.2 Horizontal Pod Autoscaling
25 - 4.3 Pod Disruption Budgets
26
27Now expand each section with detailed content and code examples.
28
29[Section 1.1 — Clusters, Nodes, and Pods]
30A Kubernetes cluster consists of a control plane and worker nodes. Pods are the smallest deployable units, wrapping one or more containers...
🔥

pro tip

Skeleton-of-thought is excellent for generating long documents, reports, and tutorials. The skeleton phase ensures logical structure and coverage, while the expansion phase produces detailed content. You can also manually edit the skeleton before expansion for maximum control.
Choosing the Right Pattern
Task TypeRecommended PatternWhy
ClassificationFew-Shot + PersonaExamples define boundaries, persona sets expertise
Math / LogicChain-of-ThoughtExternalizes reasoning steps for verification
Creative WritingSkeleton-of-Thought + PersonaStructure + voice = coherent long-form content
Research QuestionsGenerated KnowledgePrimes relevant facts before answering
Planning / PuzzlesTree-of-ThoughtExplores multiple paths, prunes dead ends
Multi-step ResearchReActInterleaves search, reasoning, and synthesis
High-Stakes ReasoningSelf-Consistency + CoTMajority vote reduces error variance

best practice

The best prompt engineers do not commit to a single pattern. They start with the simplest pattern (few-shot or zero-shot CoT), evaluate, then layer on complexity as needed. Use the pattern selection guide above as a starting point, but always validate with your specific task and data.
$Blueprint — Engineering Documentation·Section ID: AI-03·Revision: 1.0