Why Prompt Engineering Needs Design Patterns
Most developers write prompts by intuition—writing whatever comes to mind and adding a sentence when problems arise. This approach is barely sufficient for simple tasks, but when faced with complex scenarios, the output quality becomes extremely unstable. The introduction of Prompt Design Patterns aims to solve this pain point: distilling proven prompt-writing experience into reusable patterns, enabling everyone to write high-quality prompts.
The concept of design patterns originates from software engineering—just as the GoF's 23 design patterns help developers write more elegant code, prompt design patterns help developers build more efficient and reliable AI interactions. This article will delve into six core patterns, each accompanied by complete code examples and practical scenarios.
Pattern 1: Role Setting Pattern
Role setting is the most basic yet most underestimated pattern. It is not just simply saying "You are an XX expert," but should include three levels: identity definition (who you are), capability boundaries (what you can and cannot do), and behavioral guidelines (how you should act). A well-crafted role prompt can cause a qualitative change in the model's behavior.
The key to role setting is specificity. Instead of saying "You are a Python expert," you should say "You are a Python backend development engineer with 10 years of experience, proficient in Django, FastAPI, asynchronous programming, and database optimization, with code style following PEP 8 and the Google Python Style Guide." The more details, the better the model's role-playing. However, be careful not to over-constrain—an overly narrow role setting can limit the model's creativity.
Below is a complete example of the role setting pattern, demonstrating how to build a professional role for a code review scenario:
from openai import OpenAI
client = OpenAI(
api_key="your-deepseek-api-key",
base_url="https://api.deepseek.com"
)
SYSTEM_PROMPT = """You are a senior code review expert with the following background and capabilities:
【Identity】
- 10 years of Python backend development experience
- 5 years as a technical lead, managing a development team of 20 people
- Open-source project maintainer (10k+ total stars)
【Capabilities】
- Code quality review: naming conventions, code structure, design patterns
- Security review: SQL injection, XSS, permission vulnerabilities
- Performance review: time complexity, memory usage, I/O bottlenecks
- Maintainability review: comment quality, module coupling, test coverage
【Behavioral Guidelines】
- First acknowledge what is done well, then point out areas for improvement
- Provide specific modification suggestions and example code for each issue
- Sort by severity (critical/severe/suggestion)
- Avoid vague language; ensure even newcomers can understand
【What Not to Do】
- Do not make subjective style judgments (unless violating PEP 8)
- Do not make speculative reviews of code without provided context
- Do not criticize the developer personally; only evaluate the code
"""
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": "Please review the following code: 【Code Content】"}
],
temperature=0.3, max_tokens=2000
)
print(response.choices[0].message.content)Pattern 2: Template Pattern
The core idea of the template pattern is to predefine the output structure as a fixed format, allowing the AI to fill in content within the framework. This is particularly useful in scenarios requiring batch generation of consistent outputs—such as generating product descriptions, API documentation, weekly reports, etc. A good template should include: fixed headings and structure, placeholder markers, and format specification instructions.
The biggest advantage of the template pattern is output controllability. When your downstream system (e.g., an automated pipeline) relies on fixed-format input, the template pattern ensures that the AI's output is always structured and parseable. Combined with JSON Schema or Pydantic validation, you can build extremely reliable AI data processing pipelines.
Pattern 3: Constraint Pattern
The constraint pattern controls the AI's output behavior by explicitly defining boundary conditions. This pattern may seem simple, but it is extremely effective in practice. Constraints fall into three categories: format constraints (e.g., output in JSON), content constraints (e.g., no more than 200 words), and behavioral constraints (e.g., if you don't know the answer, say so).
A common mistake is to only give positive instructions while ignoring negative constraints. A good constraint pattern should tell the AI both what to do and what not to do. For example, in a customer service scenario, you should not only tell the AI to be friendly but also tell it not to promise refund amounts, not to discuss political topics, and not to disclose internal company information.
CONSTRAINTS_PROMPT = """Please answer the following question, but you must comply with all constraints.
【Positive Constraints - Must Do】
1. Start each answer with a one-sentence summary
2. Provide at least 2 specific examples
3. If code is involved, it must be complete code that can run directly
4. When citing sources, provide specific references (paper name, year, author)
【Negative Constraints - Must Not Do】
1. Do not use uncertain expressions
2. Do not output more than 500 characters
3. Do not say disclaimers like "As an AI model"
4. Do not fabricate non-existent data or citations
5. Do not use unimported libraries in code
【Boundary Check】
If the question exceeds your knowledge scope, reply directly:
"This question is beyond my knowledge scope. It is recommended to consult the following resources: [provide 2-3 specific resources]"
Question: {user_question}
"""Pattern 4: Step-by-Step Pattern
The step-by-step pattern is the engineering application of Chain-of-Thought. Instead of vaguely saying "think step by step," it is better to explicitly define how many steps there are and what each step does. This not only improves output quality but also allows intermediate results to be used by downstream systems.
The step-by-step pattern is particularly suitable for multi-stage tasks: requirements analysis → solution design → code implementation → test cases → deployment instructions. The output of each step is the input of the next, forming a complete chain of thought. In complex enterprise-level applications, the step-by-step pattern can decompose a large task that cannot be completed at once into smaller tasks that the AI can handle.
STEP_BY_STEP = """Please complete the task according to the following four steps:
## Step 1: Requirements Clarification
- Identify the user's core needs
- List all implicit requirements
- Confirm the priority of requirements
## Step 2: Solution Design
- Propose 2-3 feasible solutions
- Compare the pros and cons of each solution
- Recommend the best solution and explain the reasons
## Step 3: Detailed Implementation
- Provide a detailed implementation of the recommended solution
- Include complete code (if needed)
- Explain key design decisions
## Step 4: Verification and Optimization
- Check whether the solution meets all requirements
- Point out potential risks and edge cases
- Provide suggestions for future optimization
"""
messages = [
{"role": "system", "content": "You are a solution architect, strictly output according to the steps."},
{"role": "user", "content": user_task + "\n\n" + STEP_BY_STEP}
]
response = client.chat.completions.create(
model="deepseek-chat", messages=messages, temperature=0.3
)
print(response.choices[0].message.content)Pattern 5: Reflection Pattern
The reflection pattern allows the AI to self-review its own content after output. This is not a simple re-check but a structured quality assurance process: initial output → multi-dimensional evaluation → identify issues → fix
Correct output. The reflection mode is particularly suitable for scenarios with strict requirements on output quality, such as legal document generation, medical consultation, and financial analysis.
The key to the reflection mode is establishing clear evaluation criteria. Vague criteria (like 'check if there are problems') are ineffective, while specific criteria (like 'check if the factual statements in paragraph 3 contradict paragraph 1') are significantly better. It is recommended to customize an evaluation checklist for each application scenario, containing 5-10 specific check items.
Pattern 6: Combination Pattern
In real projects, a single pattern is often insufficient. The combination pattern merges multiple patterns—for example, first use the role pattern to define the Agent's identity, then the template pattern to standardize output format, and finally the reflection pattern to ensure quality. The key lies in the transition between patterns: the output of one pattern should naturally become the input of the next.
The following code demonstrates how to combine the role, step-by-step, and reflection patterns into a complete code review workflow:
import json
from openai import OpenAI
client = OpenAI(api_key="your-deepseek-api-key", base_url="https://api.deepseek.com")
class CompositePromptEngine:
def __init__(self):
self.role = """You are a senior code review expert with 10 years of Python experience.
Review criteria: correctness > security > performance > maintainability > style."""
self.steps = """Review according to the following steps:
Step 1: Overall structure analysis
Step 2: Function-by-function review
Step 3: Security vulnerability scan
Step 4: Performance bottleneck identification
Step 5: Summary of improvement suggestions"""
self.reflection = """After the review, self-check:
1. Is each suggestion specific and actionable?
2. Have any obvious issues been missed?
3. Is the scoring objective and reasonable?"""
def review(self, code):
full_prompt = f"{self.role}\n\n{self.steps}\n\nCode:\n```python\n{code}\n```\n\n{self.reflection}"
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": full_prompt}],
temperature=0.2
)
return response.choices[0].message.content
engine = CompositePromptEngine()
result = engine.review("def get_user(uid): return db.execute(f'SELECT * FROM users WHERE id={uid}')")
print(result)Pattern Selection Decision Tree
When facing a specific prompt task, how to choose the appropriate pattern? The following decision tree can serve as a reference:
- Need role-playing?→Use the role pattern. Define identity, capabilities, and behavioral guidelines.
- Output needs a fixed format?→Use the template pattern. Define the structure first, and let the AI fill in within the framework.
- Need strict output control?→Use the constraint pattern. Both positive and negative constraints should be explicit.
- High task complexity?→Use the step-by-step pattern. Break down the large task into smaller steps.
- Extremely high quality requirements?→Use the reflection pattern. Let the AI self-review and correct.
- Task involves multiple dimensions?→Use the combination pattern. Integrate multiple patterns as needed.
Rule of thumb: start with the simplest pattern, observe output quality, then gradually add other patterns. Don't pile up all patterns at once—over-engineering prompts not only wastes tokens but may also cause the model to perform mediocrely in all directions.
Practical Application: Designing Prompts for Enterprise-Level Applications
Let's comprehensively apply the above patterns to design prompts for a real business scenario—an intelligent customer service ticket classification system. This system needs to understand customer questions, classify problem types, assess urgency, extract key information, and generate standardized tickets.
CLASSIFIER_PROMPT = """
【Role】You are the intelligent ticket classification system for a SaaS platform.
【Capabilities】
- Understand Chinese customer questions and determine problem types
- Assess urgency (P0-P3)
- Extract key entities (username, product, version, etc.)
【Constraints】
- Only use the following categories: [account issues, payment issues, functional failures, feature inquiries, complaints and suggestions]
- If the problem description is unclear, classify as "pending confirmation"
- Urgency P0 is only for "system completely unavailable" scenarios
【Output Template】
{
"category": "category", "priority": "P0/P1/P2/P3",
"summary": "summary within 20 characters",
"entities": {"user": "", "product": "", "version": ""},
"confidence": 0.0
}
【Step-by-Step Reasoning】
Step 1: Read the customer message thoroughly and identify the core issue
Step 2: Match the most appropriate category
Step 3: Determine urgency based on impact scope
Step 4: Extract all identifiable entities
Step 5: Evaluate classification confidence
【Self-Check】
Before output, check: Is the category in the allowed list? Is the P0 judgment too lenient? Is entity extraction complete?
"""
messages = [
{"role": "system", "content": CLASSIFIER_PROMPT},
{"role": "user", "content": "Hello, our company bought your professional version, but the report download function keeps spinning, no response after 10 minutes. Latest version v3.2.1, account zhangsan@company.com, very urgent because we need to prepare a monthly report at the end of the month."}
]
response = client.chat.completions.create(model="deepseek-chat", messages=messages, temperature=0.1)
print(json.loads(response.choices[0].message.content))Common Mistakes and Improvement Methods
Mistake 1: Role setting is too generic. Improvement: Change "You are an AI assistant" to "You are a front-end architect proficient in React 18 and TypeScript, skilled in performance optimization and component design". The more specific, the better.
Mistake 2: Too many constraints causing the model to be at a loss. Improvement: Keep constraints to 5-8 items; if more than 10, the model may ignore some.
Mistake 3: Template too flexible. Improvement: Optional fields in templates are a common cause of unstable output; try to make all fields required.
Mistake 4: Reflection mode becomes a formality. Improvement: Make reflection criteria specific and quantifiable, change from "check if there are problems" to "check if paragraphs 1 and 3 have data contradictions".
Summary and Outlook
The value of prompt design patterns lies not in the patterns themselves, but in transforming prompt writing from a mystical art into an engineering discipline. Mastering these six patterns gives you a systematic toolbox—for any prompt task, you can quickly select the appropriate pattern combination and produce high-quality results. The future of prompt engineering
Want to orchestrate this skill chain yourself?
Open in Skill Chain →