Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Prompt Engineering Guide — 26 Techniques + 18 Templates + 15 Anti-Patterns

The complete prompt engineering toolkit. Pure Python — zero dependencies. Use with ChatGPT, Claude, Gemini, or any LLM. 71 passing tests.

Tests Techniques Templates Dependencies Python License

Why this repo?

  • 26 prompt techniques — from Zero-Shot to Tree-of-Thought, ReAct, RAG, Reflexion.
  • 18 ready-to-use templates — summarization, code review, SQL generation, email writing, and more.
  • 15 anti-patterns documented — with bad vs. good examples for each.
  • Pure Python builders — each technique is a function. Pass inputs, get a prompt string.
  • 71 passing tests verify everything.
  • Works with any LLM — ChatGPT, Claude, Gemini, Llama, Mistral, Ollama.

Stop copy-pasting prompts from random blogs. Use a tested, structured library instead.

Quick Start

git clone https://github.com/pyshine-labs/prompt-engineering-guide.git
cd prompt-engineering-guide
python tests/test_prompts.py

30-Second Tour

from prompts import (
    chain_of_thought, few_shot, react, rag,
    review_code, summarize_text, text_to_sql,
)

# 1. Chain-of-Thought for math/reasoning
prompt = chain_of_thought(
    "Compute the total cost",
    "3 items at $12 each plus $5 shipping",
)
print(prompt)
# Instruction: Compute the total cost
# Question: 3 items at $12 each plus $5 shipping
# Let's think step by step.

# 2. Few-shot for classification
examples = [
    {"input": "great", "output": "positive"},
    {"input": "bad",  "output": "negative"},
]
prompt = few_shot("Classify sentiment", examples, "awesome")

# 3. ReAct for tool-using agents
prompt = react(
    "Answer the question",
    "What's the weather in Paris?",
    available_tools=["weather_api", "calculator"],
)

# 4. RAG for grounded answers
prompt = rag(
    "Answer the question",
    "Who founded Apple?",
    context_chunks=[
        "Apple was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.",
        "The company is headquartered in Cupertino, California.",
    ],
)

# 5. Templates for everyday tasks
prompt = review_code("def add(a, b): return a - b", language="python")
prompt = summarize_text(long_article, max_words=100)
prompt = text_to_sql("Find top 10 users by score", "users(id, name, score)")

All 26 Techniques

Basic

Technique When to use Example
zero_shot Simple tasks the model already knows zero_shot("Translate to French", "hello")
instruction Need explicit task + constraints instruction("Summarize", ["max 100 words"])
role_prompt Domain-specific tone/expertise role_prompt("Senior engineer", "Review code")

Example-based

Technique When to use Example
few_shot Format matters more than reasoning few_shot("Classify", examples, query)
one_shot Single demo is enough one_shot("Classify", example, query)

Reasoning

Technique When to use Example
chain_of_thought Math, logic, multi-step chain_of_thought("Solve", "12 * 7")
self_consistency Need reliability on hard problems self_consistency("Solve", "x", n_samples=5)
tree_of_thought Multiple paths, some dead-end tree_of_thought("Solve puzzle", problem)

Decomposition

Technique When to use Example
least_to_most Sequential sub-questions least_to_most("Solve", q, subs)
plan_and_solve Plan first, then execute plan_and_solve("Write report", task)
decompose Generic task splitting decompose("Do X", task, strategy="parallel")

Iterative refinement

Technique When to use Example
self_refine Improve output via critique self_refine("Write haiku", draft)
self_ask Multi-hop QA self_ask("Answer", "Who founded Apple?")
reflexion Learn from failed attempts reflexion("Debug", bug, past_attempts)

Retrieval-augmented

Technique When to use Example
rag Answer from your documents rag("Answer", q, context_chunks)
step_back Need background facts first step_back("Answer", specific_q)

Agent / action

Technique When to use Example
react Interleave reasoning + tool calls react("Answer", task, ["search"])
action_planner Plan a sequence of tool calls action_planner("Plan", goal, tools)

Formatting

Technique When to use Example
xml_tagged Clear structure for context xml_tagged("Summarize", {"article": ...}, q)
json_output Force JSON output json_output("Extract", {"name": "string"})
structured_output Force field-by-field text structured_output("Extract", ["name", "age"])
markdown_output Force Markdown sections markdown_output("Write", ["Intro", "Body"])

Constraints

Technique When to use Example
constrained Must include / avoid / length constrained("Write", must_include=["cite"])
negative_prompt Explicitly forbid behaviors negative_prompt("Write", ["no jargon"])

Meta

Technique When to use Example
meta_prompt Unsure how to phrase the prompt meta_prompt("Task", considerations)
socratic Teach by guiding, not telling socratic("Teach", "What is recursion?")

All 18 Templates

Summarization

  • summarize_text(text, max_words, style) — plain text summary
  • summarize_meeting(transcript, attendees) — decisions, action items, owners

Code

  • review_code(code, language, focus) — find bugs and suggest fixes
  • generate_code(spec, language, style) — generate code from spec
  • explain_code(code, language, audience) — line-by-line explanation
  • debug_code(code, error_message, language) — diagnose and fix bugs
  • refactor_code(code, goal, language) — improve structure

Writing

  • write_email(purpose, recipient, tone, key_points) — emails
  • write_blog_post(topic, audience, word_count, tone) — blog drafts
  • write_documentation(code_or_api, doc_type, audience) — docs

Data

  • extract_data(text, fields) — structured extraction → JSON
  • classify_text(text, categories, multi_label) — text classification
  • translate_text(text, target_language, source_language, formality) — translation

Analysis

  • analyze_tradeoffs(options, criteria, context) — compare options
  • root_cause_analysis(problem, symptoms) — 5-Whys analysis

SQL

  • text_to_sql(question, schema, dialect) — natural language → SQL

Education

  • explain_concept(concept, audience, analogy) — teaching
  • create_quiz(topic, n_questions, difficulty, question_types) — quizzes

15 Anti-Patterns (Avoid These!)

# Anti-pattern What goes wrong
1 Vague instruction Off-target output
2 No output format specified Wrong format (prose vs JSON)
3 Conflicting constraints Model silently drops one
4 Asking for too much in one prompt Later steps forgotten
5 Negative-only instruction Desired behavior undefined
6 Assuming the model knows your context Hallucinations
7 Overloading the role Tone confusion
8 Trusting the model's confidence Confident wrong answers
9 Open-ended length Runaway output
10 Ignoring failure modes Fabricated answers
11 Prompt injection vulnerability User overrides your rules
12 Wrong few-shot distribution Bias toward examples
13 Asking for "the best" answer Alternatives hidden
14 Premature prompt optimization Hard to debug
15 Not specifying the audience Generic tone

See anti_patterns.py for the bad-vs-good examples.

from prompts import get_anti_pattern

ap = get_anti_pattern("Vague instruction")
print(ap["bad"])   # "Write something about Python."
print(ap["good"])  # "Write a 200-word introduction to Python for absolute beginners..."

Run Tests

python tests/test_prompts.py
# Passed: 71/71
# All tests passed.

Project Structure

prompt-engineering-guide/
├── prompts/
│   ├── __init__.py        # Public API
│   ├── techniques.py      # 26 prompt technique builders
│   ├── templates.py       # 18 task-specific templates
│   └── anti_patterns.py   # 15 anti-patterns with fixes
└── tests/
    └── test_prompts.py    # 71 tests

How to Combine Techniques

Real-world prompts often combine multiple techniques:

from prompts import role_prompt, few_shot, chain_of_thought

# Role + Few-shot + CoT
base = role_prompt("Senior data scientist", "Analyze the dataset")
examples = [{"input": "small dataset", "output": "use simpler model"}]
demo = few_shot("Recommend a model", examples, "1M rows, 50 features")
reasoning = chain_of_thought("Recommend a model", "1M rows, 50 features")

full_prompt = base + "\n\n" + demo + "\n\n" + reasoning
from prompts import rag, structured_output

# RAG + structured output
context = ["Apple was founded in 1976.", "Apple makes iPhones."]
grounded = rag("Extract facts", "Apple founding", context)
fmt = structured_output("Extract", ["year", "founders", "product"])

full_prompt = grounded + "\n\n" + fmt

When to Use Which Technique

Simple task (translate, summarize)        → zero_shot
Need specific format                      → json_output / structured_output
Format is critical, reasoning is not      → few_shot
Multi-step reasoning (math, logic)        → chain_of_thought
Hard reasoning, need reliability          → self_consistency
Multiple paths, some dead-end             → tree_of_thought
Sequential sub-questions                  → least_to_most
Improve a draft                           → self_refine
Multi-hop question answering              → self_ask
Learn from prior failures                 → reflexion
Answer from your documents                → rag
Need background facts first               → step_back
Tool-using agent                          → react
Plan a sequence of tool calls             → action_planner
Domain-specific tone                      → role_prompt
Unsure how to phrase                      → meta_prompt
Teaching/tutoring                         → socratic

Learn More

Master Python, AI, and prompt engineering with tutorials from pyshine.com:

Contributing

  1. Fork the repo
  2. Add a technique, template, or anti-pattern (keep it pure Python — no external dependencies)
  3. All tests must pass: python tests/test_prompts.py
  4. Submit a pull request

License

MIT — free to use, modify, and distribute.


More tutorials at pyshine.com — Star this repo if it helped you.

About

26 prompt engineering techniques + 18 templates + 15 anti-patterns. Pure Python builders for ChatGPT/Claude/Gemini. Zero deps. 71 tests.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages