Giao diện
💬 Prompting Patterns
🎓 Page Overview
Trang này cung cấp các patterns và best practices cho prompt engineering, từ system prompts đến few-shot learning và cách tránh các anti-patterns phổ biến.
Level: Core Solves: Thiết kế prompts hiệu quả cho production LLM applications với consistency và reliability
🎯 System Prompt Engineering
Anatomy of a System Prompt
markdown
# Role Definition
You are [ROLE] with expertise in [DOMAIN].
Your purpose is to [PRIMARY_OBJECTIVE].
# Behavioral Guidelines
- Always [POSITIVE_BEHAVIOR]
- Never [PROHIBITED_BEHAVIOR]
- When uncertain, [UNCERTAINTY_HANDLING]
# Output Format
Respond in [FORMAT] with the following structure:
[STRUCTURE_DEFINITION]
# Constraints
- Maximum response length: [LIMIT]
- Language: [LANGUAGE]
- Tone: [TONE]
# Examples (Optional)
[FEW_SHOT_EXAMPLES]System Prompt Components
| Component | Purpose | Example |
|---|---|---|
| Role Definition | Establish persona và expertise | "You are a senior software engineer reviewing code" |
| Task Framing | Define primary objective | "Help users debug and optimize their code" |
| Behavioral Rules | Set guardrails | "Never provide code that could cause security vulnerabilities" |
| Output Format | Standardize responses | "Respond in JSON with keys: analysis, suggestion, code" |
| Constraints | Limit scope | "Focus only on Python; redirect other languages politely" |
📐 Prompt Structure Patterns
1. Instruction-Input-Output (IIO) Pattern
markdown
## Instruction
Analyze the following customer feedback and extract:
1. Sentiment (positive/negative/neutral)
2. Key topics mentioned
3. Action items if any
## Input
{customer_feedback}
## Output Format
Return JSON:
{
"sentiment": "...",
"topics": [...],
"action_items": [...]
}2. Chain-of-Thought (CoT) Pattern
markdown
Solve this step by step:
1. First, identify the core problem
2. Then, analyze the constraints
3. Consider possible approaches
4. Select the best approach with reasoning
5. Provide the final solution
Problem: {problem_description}
Show your reasoning at each step.3. Role-Task-Format (RTF) Pattern
markdown
# Role
You are an expert data analyst at a Fortune 500 company.
# Task
Analyze the sales data and provide insights on:
- Trends over the past quarter
- Top performing products
- Recommendations for next quarter
# Format
Structure your response as:
1. Executive Summary (2-3 sentences)
2. Key Findings (bullet points)
3. Recommendations (numbered list)
4. Supporting Data (table format)🎓 Few-Shot Learning Patterns
Static Few-Shot
markdown
Extract entities from the text.
Example 1:
Text: "Apple announced new iPhone 15 in Cupertino on September 12"
Entities: {"company": "Apple", "product": "iPhone 15", "location": "Cupertino", "date": "September 12"}
Example 2:
Text: "Microsoft CEO Satya Nadella spoke at Build 2024 in Seattle"
Entities: {"company": "Microsoft", "person": "Satya Nadella", "event": "Build 2024", "location": "Seattle"}
Now extract from:
Text: "{input_text}"
Entities:Dynamic Few-Shot (Retrieval-Augmented)
Implementation Pattern:
- Maintain example bank with embeddings
- Retrieve semantically similar examples
- Select diverse, representative examples
- Include in prompt with recency/relevance weighting
Few-Shot Best Practices
| Practice | Rationale |
|---|---|
| 3-5 examples | Enough diversity without overwhelming context |
| Diverse examples | Cover edge cases và variations |
| Ordered by complexity | Simple → Complex for gradual learning |
| Include negative examples | Show what NOT to do |
| Match target distribution | Examples should reflect real queries |
🚫 Prompt Anti-Patterns
1. Ambiguous Instructions
❌ Bad:
Help me with this data.✅ Good:
Analyze this CSV data and:
1. Calculate the average sales per region
2. Identify the top 3 performing products
3. Return results as a markdown table2. Overloaded Prompts
❌ Bad:
You are an expert in everything. Help with any question about coding,
writing, math, science, history, cooking, legal advice, medical diagnosis...✅ Good:
You are a Python code reviewer specializing in:
- Code quality and PEP8 compliance
- Performance optimization
- Security best practices
Redirect other topics with: "This is outside my expertise."3. Missing Output Format
❌ Bad:
Extract the information from this document.✅ Good:
Extract information and return as JSON:
{
"title": "string",
"date": "YYYY-MM-DD",
"key_points": ["string"],
"confidence": 0.0-1.0
}4. Inconsistent Examples
❌ Bad:
Example 1: Return "positive" or "negative"
Example 2: Return {"sentiment": "good", "score": 0.8}✅ Good:
Example 1: {"sentiment": "positive", "confidence": 0.95}
Example 2: {"sentiment": "negative", "confidence": 0.87}🔧 Advanced Techniques
Prompt Chaining
Self-Consistency
markdown
Solve this problem 3 times with different approaches.
Then compare your answers and provide the most likely correct answer.
Problem: {problem}
Approach 1: [reasoning and answer]
Approach 2: [reasoning and answer]
Approach 3: [reasoning and answer]
Final Answer: [most common/confident answer with explanation]Constitutional AI Pattern
markdown
# Base Instruction
{original_instruction}
# Constitutional Principles
Before responding, verify your answer against:
1. Accuracy: Is the information factually correct?
2. Helpfulness: Does this actually help the user?
3. Safety: Could this cause harm?
4. Honesty: Am I being transparent about limitations?
If any principle is violated, revise your response.📋 Prompt Engineering Checklist
Design Phase
- [ ] Define clear objective and success criteria
- [ ] Identify required output format
- [ ] Prepare diverse few-shot examples
- [ ] Document edge cases và expected behaviors
Testing Phase
- [ ] Test with diverse inputs
- [ ] Verify output format consistency
- [ ] Check handling of edge cases
- [ ] Measure latency impact of prompt length
Production Phase
- [ ] Version control prompts
- [ ] A/B test prompt variations
- [ ] Monitor output quality metrics
- [ ] Set up prompt injection detection
🔗 Cross-References
- 📎 RAG Engineering - Combining prompts with retrieved context
- 📎 LLM Evaluation - Measuring prompt effectiveness
- 📎 LLM Safety - Prompt injection defense
📚 Further Reading
- "The Prompt Engineering Guide" - DAIR.AI
- "Anthropic Prompt Engineering" - Anthropic Documentation
- "OpenAI Best Practices" - OpenAI Cookbook