Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:45:40 +08:00
commit b713f67713
7 changed files with 1240 additions and 0 deletions

View File

@@ -0,0 +1,377 @@
# Prompt Optimization Examples
This document provides before-and-after examples of prompt optimization across different use cases.
## Example 1: Code Review Request
### Before (Poor Quality)
```
Review my code
```
**Problems:**
- No context about what type of review is needed
- No information about the code's purpose
- No guidance on what to focus on
- Missing any quality criteria
### After (Optimized)
```
Review this Python authentication module for a web application. Focus on:
1. Security vulnerabilities (SQL injection, XSS, improper session handling)
2. Code organization and maintainability
3. Error handling completeness
4. Performance considerations for high-traffic scenarios
The code will be used in production serving 100k+ daily users. Prioritize security issues over style concerns.
If any security issue is found, explain the potential impact and provide a secure alternative implementation.
```
**Improvements:**
- Specifies code type and purpose
- Lists explicit review criteria
- Provides usage context
- Sets clear priorities
- Defines expected output detail
---
## Example 2: Content Creation
### Before (Poor Quality)
```
Write a blog post about AI
```
**Problems:**
- Topic too broad
- No target audience specified
- Missing tone/style guidance
- No length constraints
- Unclear purpose or angle
### After (Optimized)
```
Write a 1,200-word blog post about practical applications of AI in small business operations.
Target audience: Small business owners (10-50 employees) with limited technical background who are curious about AI but skeptical about ROI.
Tone: Encouraging but realistic, conversational, no hype
Structure:
1. Opening hook: Common small business challenge
2. 3-4 specific AI use cases with real cost/time savings
3. "Getting started" section with concrete first steps
4. Address common concerns (cost, complexity, data privacy)
5. Closing: Balanced perspective on AI adoption
Include at least one concrete example with specific numbers. Avoid overly technical jargon. If technical terms are necessary, explain them simply.
```
**Improvements:**
- Specific topic scope
- Defined target audience
- Clear tone expectations
- Specified structure and length
- Content requirements (examples, numbers)
- Style guidelines
---
## Example 3: Data Analysis
### Before (Poor Quality)
```
Analyze this sales data
```
**Problems:**
- No analysis objective
- Missing key questions to answer
- No output format specified
- Unclear what insights are valuable
### After (Optimized)
```
Analyze the attached Q4 sales data to identify growth opportunities for Q1 planning.
Key questions to answer:
1. Which product categories showed strongest/weakest growth?
2. Are there regional performance patterns?
3. What seasonal trends are evident?
4. Which customer segments are growing/shrinking?
Context: This analysis will inform Q1 budget allocation across product lines and regions.
Output format:
- Executive summary (3-4 key findings)
- Detailed findings for each question with supporting data
- 3-5 actionable recommendations prioritized by potential impact
If the data is insufficient to answer any question confidently, state what additional data would be needed.
```
**Improvements:**
- Clear analysis objective
- Specific questions to answer
- Business context provided
- Structured output format
- Permits acknowledging data limitations
---
## Example 4: Technical Documentation
### Before (Poor Quality)
```
Document this API
```
**Problems:**
- No audience specified
- Missing documentation scope
- Unclear what level of detail is needed
- No format preferences
### After (Optimized)
```
Create API documentation for the User Management endpoints intended for external third-party developers integrating with our platform.
Audience: Developers with general REST API experience but unfamiliar with our system.
For each endpoint include:
1. Endpoint URL and HTTP method
2. Purpose and use case
3. Authentication requirements
4. Request parameters (with types, required/optional, validation rules)
5. Example request with curl
6. Example successful response
7. Possible error responses with status codes
8. Rate limiting information
Organization: Group endpoints by resource (Users, Permissions, Sessions)
Tone: Professional but friendly, assume the reader is competent but unfamiliar with our specific implementation.
Include a "Quick Start" section at the beginning with a complete authentication and first API call example.
```
**Improvements:**
- Defined target audience
- Explicit scope and structure
- Detailed content requirements
- Clear organization principle
- Tone specification
- Additional helpful section requested
---
## Example 5: Problem Solving
### Before (Poor Quality)
```
My app is slow. Fix it.
```
**Problems:**
- No diagnostic information
- Unclear what "slow" means
- Missing context about the application
- No information about what's been tried
### After (Optimized)
```
Help me diagnose and resolve performance issues in a React web application.
Symptoms:
- Initial page load takes 8-12 seconds (target: under 3 seconds)
- Scrolling feels janky/unresponsive
- Issue affects all users, worse on mobile devices
App context:
- Single-page React app with Redux state management
- Displays data dashboards with charts (using Recharts)
- Fetches data from REST API (responses typically 200-500kb)
- Hosted on AWS CloudFront + S3
What I've tried:
- Checked network tab: API responses are fast (< 500ms)
- Main bundle size is 2.1 MB
- Haven't implemented code splitting yet
Please:
1. Identify likely performance bottlenecks based on symptoms
2. Suggest specific diagnostic steps to confirm root causes
3. Provide prioritized optimization recommendations
4. For top 2-3 recommendations, include example implementation
If you need additional diagnostic information to provide better recommendations, please specify what to check.
```
**Improvements:**
- Quantified the problem ("8-12 seconds")
- Provided relevant technical context
- Listed what's been investigated
- Structured the request with clear steps
- Permits requests for more information
---
## Example 6: Creative Writing
### Before (Poor Quality)
```
Write a story
```
**Problems:**
- No genre, theme, or setting
- Missing tone/mood guidance
- No length specification
- Unclear target audience
- No creative constraints or requirements
### After (Optimized)
```
Write a 1,500-word science fiction short story for adult readers.
Setting: Near-future Earth (2045) where climate change has forced mass migration to underground cities.
Core concept: A maintenance worker discovers an old seed vault and must decide whether to reveal it to the authoritarian government or protect it for a potential resistance movement.
Tone: Thoughtful and character-driven rather than action-focused; bittersweet rather than purely dystopian
Requirements:
- Third-person limited perspective following the protagonist
- Include sensory details about the underground environment
- Show the protagonist's internal conflict, not just external action
- Ending should be ambiguous rather than fully resolved
Avoid:
- Excessive technical jargon
- Obvious "chosen one" tropes
- Overly explanatory world-building dumps
Focus on: Character psychology, moral ambiguity, and atmospheric world-building
```
**Improvements:**
- Specific genre and audience
- Clear setting and premise
- Defined tone and mood
- Structural requirements
- Creative constraints and preferences
- Guidance on what to emphasize
---
## Example 7: Learning/Education
### Before (Poor Quality)
```
Teach me Python
```
**Problems:**
- Scope impossibly broad
- No information about current skill level
- Missing learning goals
- No time constraints or format preference
### After (Optimized)
```
Create a focused Python lesson on list comprehensions for someone who understands basic Python syntax (variables, loops, conditionals, lists) but hasn't used list comprehensions.
Learning objectives:
1. Understand list comprehension syntax and structure
2. Convert simple for loops to list comprehensions
3. Know when list comprehensions improve code readability
4. Recognize when NOT to use list comprehensions
Format:
1. Brief concept explanation (2-3 sentences)
2. Simple example with equivalent for-loop comparison
3. 3-4 progressively complex examples (filtering, transformation, nested)
4. 3 practice problems with solutions
5. "When to use / when to avoid" guidelines
Teaching approach: Show practical examples first, then explain the pattern. Use relatable scenarios (processing shopping lists, filtering student grades, etc.) rather than abstract foo/bar examples.
Keep total lesson under 1,000 words so it can be completed in one focused session.
```
**Improvements:**
- Narrow, specific topic
- Current skill level stated
- Clear learning objectives
- Structured lesson format
- Teaching methodology specified
- Practical length constraint
---
## Example 8: Research Synthesis
### Before (Poor Quality)
```
Summarize these articles
```
**Problems:**
- No synthesis goal or angle
- Missing target length
- Unclear what aspects to focus on
- No guidance on handling contradictions
### After (Optimized)
```
Synthesize findings from the attached 5 research papers on remote work productivity to answer: "What factors most significantly impact productivity in remote work environments?"
Focus areas:
1. Points of consensus across studies
2. Significant contradictions or disagreements
3. Methodological differences that might explain contradictions
4. Practical implications for managers
Output structure:
1. Overview paragraph: Main consensus findings (if any)
2. Key factors section: Organize by factor (communication, environment, autonomy, etc.), noting level of agreement
3. Contradictions section: Highlight disagreements with possible explanations
4. Research gaps: What questions remain unanswered?
5. Practical recommendations: 3-5 evidence-based suggestions
Length: 1,200-1,500 words
If studies use different definitions of "productivity," note this explicitly and explain how it affects comparisons.
```
**Improvements:**
- Clear synthesis goal (answer specific question)
- Defined focus areas
- Structured output format
- Length specification
- Guidance on handling complexity and contradictions
---
## Pattern Summary
Across all examples, effective prompts consistently include:
1. **Specific scope and objective** - Not "analyze data" but "analyze Q4 sales data to identify growth opportunities"
2. **Context about purpose** - Why this is needed, how it will be used
3. **Target audience** - Who will consume this output
4. **Explicit structure** - How to organize the response
5. **Quality criteria** - What makes a good response
6. **Constraints** - Length, tone, format, what to avoid
7. **Permission for uncertainty** - When to say "I don't know" or ask for more info
8. **Current state information** - What's known, what's been tried, current skill level

View File

@@ -0,0 +1,351 @@
# Prompt Engineering Best Practices
This reference document contains comprehensive best practices for crafting effective prompts for AI models like Claude.
## Core Principles
### 1. Be Clear and Direct
**Principle:** Tell the model explicitly what is wanted, without assuming it will infer the intent.
**Why it matters:** Modern AI models follow instructions literally. Vague requests lead to generic or misaligned outputs.
**Examples:**
**Poor:** "Create an analytics dashboard"
- Problem: No clarity on scope, features, or requirements
**Better:** "Create an analytics dashboard. Include as many relevant features and interactions as possible"
- Improvement: Specifies scope and expectations
**Poor:** "Write a summary"
- Problem: Unclear about length, focus, or audience
**Better:** "Write a 3-paragraph executive summary highlighting key financial metrics and strategic recommendations for C-level executives"
- Improvement: Defines length, focus, and audience
### 2. Provide Context and Motivation
**Principle:** Explain WHY certain requirements matter to help the AI understand the underlying goal.
**Why it matters:** Context helps the AI make better decisions when facing ambiguous situations or trade-offs.
**Examples:**
**Less effective:** "NEVER use bullet points"
- Problem: Sounds arbitrary, AI doesn't understand the reasoning
**More effective:** "I prefer responses in natural paragraph form rather than bullet points because I find flowing prose easier to read and more suitable for formal reports"
- Improvement: Explains the reasoning, helps AI understand when to apply this preference
**Less effective:** "Use simple language"
- Problem: Vague definition of "simple"
**More effective:** "Use simple language suitable for a general audience without technical background, as this content will be published in a consumer-facing blog"
- Improvement: Defines audience and purpose
### 3. Be Specific with Requirements
**Principle:** Provide concrete details about constraints, requirements, and desired outcomes.
**Why it matters:** Specificity reduces ambiguity and ensures outputs match expectations.
**Examples:**
**Vague:** "Create a meal plan for a Mediterranean diet"
- Problem: No constraints on calories, dietary restrictions, or goals
**Specific:** "Design a Mediterranean diet meal plan for pre-diabetic management. 1,800 calories daily, emphasis on low glycemic foods, avoid processed sugars, include 5-6 small meals throughout the day"
- Improvement: Defines medical context, caloric target, food restrictions, and meal frequency
**Vague:** "Analyze this code for issues"
- Problem: Unclear what types of issues to focus on
**Specific:** "Analyze this Python code for security vulnerabilities, focusing on SQL injection risks, XSS vulnerabilities, and improper input validation. Also check for performance bottlenecks in database queries"
- Improvement: Specifies analysis focus areas
### 4. Use Examples (Few-Shot Learning)
**Principle:** Show concrete examples of desired input-output patterns.
**Why it matters:** Modern models like Claude 4.x pay close attention to examples, often more than written instructions.
**Structure:**
```
[Task description]
Example 1:
Input: [example input]
Output: [example output]
Example 2:
Input: [example input]
Output: [example output]
Now process:
Input: [actual input]
```
**Use cases:**
- Defining output format
- Establishing tone and style
- Showing edge case handling
- Demonstrating complex transformations
### 5. Allow Expression of Uncertainty
**Principle:** Explicitly permit the AI to say "I don't know" rather than guessing or fabricating information.
**Why it matters:** Prevents hallucination and builds trust through honesty.
**Examples:**
**Standard prompt:** "What was the Q4 revenue for Company X?"
- Problem: AI may fabricate numbers if data is unavailable
**Better prompt:** "What was the Q4 revenue for Company X? If the data is insufficient to draw conclusions, say so rather than speculating"
- Improvement: Explicitly permits uncertainty
**Standard prompt:** "Analyze this medical report"
- Problem: AI may overreach its capabilities
**Better prompt:** "Analyze this medical report. Focus on factual observations from the data. If any medical interpretation requires expertise beyond pattern recognition, clearly state that and recommend consulting a medical professional"
- Improvement: Sets boundaries and encourages appropriate caution
## Advanced Techniques
### 1. Prefill (Response Priming)
**Technique:** Start the AI's response to guide format, tone, or structure.
**Use cases:**
- Forcing specific output formats (JSON, XML)
- Eliminating preamble text
- Establishing tone immediately
- Starting with specific phrases
**Example - JSON Output:**
```
User: Extract the name and price from this product description into JSON.
Assistant: {
```
Result: The AI continues directly with JSON, no preamble.
**Example - Direct Answer:**
```
User: What's the capital of France?
Assistant: The capital is
```
Result: AI completes with "Paris" instead of adding "The capital of France is Paris"
### 2. Chain of Thought (Step-by-Step Reasoning)
**Technique:** Request explicit step-by-step reasoning before the final answer.
**Why it matters:** Improves accuracy on complex reasoning tasks, makes logic transparent.
**Three approaches:**
**a) Basic Chain of Thought:**
```
Solve this problem step-by-step: [problem]
```
**b) Guided Chain of Thought:**
```
Analyze this contract clause. Follow these reasoning stages:
1. Identify the key obligations
2. Note any ambiguous language
3. Assess potential risks
4. Provide final interpretation
```
**c) Structured Chain of Thought:**
```
Solve this problem. Use this format:
<reasoning>
[Your step-by-step thinking]
</reasoning>
<answer>
[Your final answer]
</answer>
```
### 3. Control Output Format
**Principle:** Explicitly specify the desired output structure.
**Guidelines:**
- Tell the AI what TO do, not what NOT to do
- Match prompt style to desired output style
- Use prefilling for strict format requirements
- Provide format examples
**Examples:**
**For structured data:**
```
Extract key information in this JSON format:
{
"company": "string",
"revenue": "number with currency",
"year": "YYYY"
}
```
**For analytical reports:**
```
Provide analysis in this structure:
1. Executive Summary (2-3 sentences)
2. Key Findings (bullet points)
3. Detailed Analysis (paragraphs)
4. Recommendations (numbered list)
```
### 4. Prompt Chaining
**Technique:** Break complex tasks into sequential prompts where each builds on previous outputs.
**Why it matters:**
- Improves quality by focusing on one aspect at a time
- Allows intermediate verification
- Enables iterative refinement
**Example - Research Summary:**
**Prompt 1:** "Summarize the key findings from this 50-page research paper"
**Prompt 2:** "Review this summary for accuracy. Identify any misrepresentations or missing critical points"
**Prompt 3:** "Based on the review feedback, create an improved summary"
**Example - Code Review:**
**Prompt 1:** "Analyze this code for security vulnerabilities"
**Prompt 2:** "Now review the same code for performance issues"
**Prompt 3:** "Based on both analyses, prioritize the issues and suggest an implementation order"
## Common Patterns to Avoid
### 1. Over-Constraining with Roles
**Problem:** Overly specific role definitions can limit helpfulness.
**Poor:** "You are a Senior Java Enterprise Architect with exactly 15 years of experience who only uses Spring Boot and refuses to discuss other frameworks"
- Too rigid, may prevent useful suggestions
**Better:** "Provide architectural guidance for a Java Spring Boot application, focusing on enterprise-scale best practices"
- Provides context without unnecessary constraints
### 2. Assuming Mind-Reading
**Problem:** Leaving requirements implicit rather than explicit.
**Poor:** "Make it better"
- AI doesn't know what "better" means in this context
**Better:** "Improve code readability by: adding descriptive variable names, extracting complex logic into well-named functions, and adding explanatory comments for non-obvious algorithms"
- Explicitly defines improvement criteria
### 3. Negative Instructions
**Problem:** Telling AI what NOT to do is less effective than saying what TO do.
**Less effective:** "Don't be too technical, don't use jargon, don't make it too long"
**More effective:** "Use conversational language suitable for a general audience, explain concepts with everyday analogies, keep the response under 300 words"
### 4. Over-Engineering
**Problem:** Using all advanced techniques when simple clarity would suffice.
**When to use simple prompts:** Single-step tasks, straightforward requests, well-defined operations
**When to use advanced techniques:** Multi-step reasoning, complex analysis, tasks requiring specific formats, ambiguous requirements
## Troubleshooting Guide
### Response is too generic
**Solutions:**
- Add specific constraints and requirements
- Provide concrete examples
- Include context about the use case
- Specify the audience and purpose
### AI goes off-topic
**Solutions:**
- State the objective more clearly at the beginning
- Provide more context about the goal
- Break complex requests into smaller prompts
- Use structured output format
### Format is inconsistent
**Solutions:**
- Add explicit format examples
- Use prefilling to start the response
- Provide a template or schema
- Use structured tags (e.g., `<answer>`, `<reasoning>`)
### Includes unnecessary preamble
**Solutions:**
- Use prefilling to skip straight to content
- Add explicit instruction: "Begin directly with [content type], no introduction"
- Provide example that starts immediately with content
### Task is too complex
**Solutions:**
- Use prompt chaining to break into steps
- Apply chain of thought reasoning
- Create a multi-stage workflow
- Simplify the request scope
### Contains fabricated information
**Solutions:**
- Explicitly permit expressions of uncertainty
- Request citations or source attribution
- Ask for confidence levels
- Request "I don't know" when data is insufficient
## Quality Checklist
Before finalizing a prompt, verify:
- [ ] **Clarity:** Is the request unambiguous?
- [ ] **Specificity:** Are constraints and requirements concrete?
- [ ] **Context:** Does the AI understand WHY this matters?
- [ ] **Examples:** Are there examples for complex or ambiguous requirements?
- [ ] **Format:** Is the desired output structure clear?
- [ ] **Uncertainty:** Is the AI permitted to express limitations?
- [ ] **Scope:** Is the task appropriately scoped (not too complex)?
- [ ] **Tone:** Is the desired communication style specified?
- [ ] **Success criteria:** Is it clear what constitutes a good output?
## Decision Framework
Use this flowchart to select appropriate techniques:
1. **Is the request clear and specific?**
- No → Add clarity, specificity, context
- Yes → Continue
2. **Is the task simple and straightforward?**
- Yes → Use basic clear prompt
- No → Continue
3. **Is a specific format required?**
- Yes → Add format specification or prefilling
- No → Continue
4. **Is the task complex or multi-faceted?**
- Yes → Consider prompt chaining
- No → Continue
5. **Does it require reasoning or analysis?**
- Yes → Use chain of thought
- No → Use basic prompt
6. **Are there ambiguous or nuanced requirements?**
- Yes → Add examples (few-shot)
- No → Proceed with current prompt