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,12 @@
{
"name": "prompt-optimizer",
"description": "Optimize and refine prompts for AI models using comprehensive prompt engineering best practices",
"version": "0.0.0-2025.11.28",
"author": {
"name": "Kanner",
"email": "kanner.chen@gmail.com"
},
"skills": [
"./skills/prompt-optimizer"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# prompt-optimizer
Optimize and refine prompts for AI models using comprehensive prompt engineering best practices

56
plugin.lock.json Normal file
View File

@@ -0,0 +1,56 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:hikanner/agent-skills:prompt-optimizer",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "23767b37b7e4818aaa751949220023a0d91035a4",
"treeHash": "6861e18b30c4f6dc8b92b7ff0281a57176e93c1315d34e6cb564d41927522e90",
"generatedAt": "2025-11-28T10:17:27.680549Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "prompt-optimizer",
"description": "Optimize and refine prompts for AI models using comprehensive prompt engineering best practices"
},
"content": {
"files": [
{
"path": "README.md",
"sha256": "622b091ce06a2a55175a519b997e62d3792c62e884d1d91417e563caf59f34e7"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "9933762ff8e4618a3880c4b6f73fca79909ee9f8c4c8693d3d4e67773aebab26"
},
{
"path": "skills/prompt-optimizer/SKILL.md",
"sha256": "732c264a15ca455dd8385e2e57d75e99ef905964b0ea2835c2c0a8f3e7b4006b"
},
{
"path": "skills/prompt-optimizer/LICENSE.txt",
"sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"
},
{
"path": "skills/prompt-optimizer/references/examples.md",
"sha256": "ad4e3faf4585c881b5a78a28dfc0582fe6d53ace0cfc2b9155e6f1ae38a992cf"
},
{
"path": "skills/prompt-optimizer/references/prompt-best-practices.md",
"sha256": "44192d07560a44415aabbced41b2be9cb1daf8becc01a2037216242a84890ac5"
}
],
"dirSha256": "6861e18b30c4f6dc8b92b7ff0281a57176e93c1315d34e6cb564d41927522e90"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,240 @@
---
name: prompt-optimizer
description: This skill should be used when users request help optimizing, improving, or refining their prompts or instructions for AI models. Use this skill when users provide vague, unclear, or poorly structured prompts and need assistance transforming them into clear, effective, and well-structured instructions that AI models can better understand and execute. This skill applies comprehensive prompt engineering best practices to enhance prompt quality, clarity, and effectiveness.
license: Complete terms in LICENSE.txt
---
# Prompt Optimizer
## Overview
This skill transforms user-provided prompts into high-quality, clear, and effective instructions optimized for AI models. Apply proven prompt engineering principles to enhance clarity, specificity, structure, and effectiveness. The skill uses a systematic workflow to analyze, identify improvement opportunities, and restructure prompts based on industry best practices.
## When to Use This Skill
Activate this skill when users:
- Explicitly request prompt optimization or improvement
- Provide vague or unclear instructions that need refinement
- Ask for help making their requests more effective
- Submit poorly structured prompts that would benefit from reorganization
- Request guidance on how to better communicate with AI models
- Present complex tasks that need to be broken down into clearer instructions
## Optimization Workflow
Follow this systematic process to optimize any prompt:
### Step 1: Analyze the Original Prompt
Examine the user's prompt and identify:
**Clarity issues:**
- Ambiguous terms or vague requirements
- Implicit assumptions that should be explicit
- Missing context or background information
**Specificity gaps:**
- Lack of concrete constraints or requirements
- Undefined success criteria
- Missing audience or purpose information
- Unclear scope or boundaries
**Structure problems:**
- Disorganized or stream-of-consciousness format
- Missing logical flow
- Lack of clear sections or hierarchy
**Format considerations:**
- No specified output format
- Unclear expectations about length, tone, or style
- Missing examples or templates
**Complexity assessment:**
- Determine if the task is too complex for a single prompt
- Identify if the request would benefit from prompt chaining
- Assess if step-by-step reasoning is needed
### Step 2: Identify the Core Intent
Determine the fundamental objective behind the user's request:
- What is the user ultimately trying to accomplish?
- What problem are they trying to solve?
- What would constitute a successful output?
- Who is the intended audience or consumer of the output?
Clarify these points with the user if they are not evident from the original prompt.
### Step 3: Apply Optimization Principles
Enhance the prompt using these core principles:
**Make it clear and direct:**
- State requirements explicitly without assuming inference
- Remove ambiguity and vague language
- Use concrete, specific terms
**Provide context and motivation:**
- Explain WHY certain requirements matter
- Include relevant background information
- Describe the use case or scenario
**Add specificity:**
- Define concrete constraints (length, format, scope)
- Specify target audience
- Include quality criteria
- State any limitations or boundaries
**Structure the request:**
- Organize information logically
- Use clear sections or numbered points
- Separate different types of information (context, requirements, format)
**Include examples when helpful:**
- Provide input-output examples for complex formats
- Show desired tone or style through examples
- Demonstrate edge case handling
**Allow for uncertainty:**
- Explicitly permit expressing "I don't know"
- Request acknowledgment of limitations
- Prevent hallucination by encouraging honesty
### Step 4: Consider Advanced Techniques
Evaluate if any advanced techniques would enhance the prompt:
**Chain of Thought:**
- Apply when the task requires reasoning or analysis
- Request step-by-step thinking for complex problems
- Use structured format to separate reasoning from answer
**Prefilling:**
- Use when a specific format is absolutely required (JSON, XML)
- Apply to eliminate unwanted preambles
- Utilize to establish immediate tone or style
**Prompt Chaining:**
- Break complex tasks into sequential steps
- Create a multi-stage workflow for intricate projects
- Design each prompt to build on previous outputs
**Structured Output:**
- Specify exact format requirements
- Provide schemas or templates
- Use tags or delimiters for different sections
Consult `references/prompt-best-practices.md` for detailed guidance on these techniques.
### Step 5: Present the Optimized Prompt
Deliver the optimization in this format:
**Analysis Section:**
```
Original prompt issues identified:
- [List key problems with the original prompt]
```
**Optimized Prompt:**
```
[Present the complete optimized prompt in a code block for easy copying]
```
**Improvement Explanation:**
```
Key improvements made:
- [Explain major enhancements]
- [Highlight added specificity]
- [Note structural changes]
- [Mention any advanced techniques applied]
```
**Optional - Usage Tips:**
```
[If applicable, provide brief tips on how to further customize or use the optimized prompt]
```
### Step 6: Iterate Based on Feedback
After presenting the optimized prompt:
- Ask if the optimization meets the user's needs
- Offer to adjust tone, length, or specificity
- Provide alternative formulations if requested
- Refine based on user feedback
## Practical Guidelines
**Balance is key:** Not every prompt needs all advanced techniques. Match the optimization level to the task complexity.
**Preserve user intent:** Enhance clarity without changing the fundamental goal or adding unwanted requirements.
**Consider the model:** Modern models like Claude 4.x have strong instruction-following capabilities; leverage this by being direct and specific.
**Stay practical:** Focus on improvements that materially impact output quality, not cosmetic changes.
**Be educational:** When appropriate, briefly explain why certain changes improve the prompt, helping users learn to write better prompts independently.
## Reference Resources
This skill includes comprehensive reference materials:
**references/prompt-best-practices.md**
- Detailed explanations of all core principles
- Advanced techniques with examples
- Troubleshooting guide for common issues
- Quality checklist and decision frameworks
Load this reference when:
- Users ask about specific prompt engineering concepts
- Deep explanation of a technique is needed
- Troubleshooting unusual or complex prompting challenges
- Users want to learn prompt engineering principles
**references/examples.md**
- Before-and-after optimization examples across multiple domains
- Real-world scenarios demonstrating transformation
- Pattern library showing common improvements
Load this reference when:
- Users want to see concrete examples
- Illustrating a specific type of optimization
- Users are learning and need to understand patterns
- Demonstrating the impact of optimization
## Quality Standards
Ensure every optimized prompt includes:
- [ ] Clear, unambiguous objective
- [ ] Sufficient context for the AI to understand the goal
- [ ] Specific constraints and requirements
- [ ] Target audience or use case (when relevant)
- [ ] Expected output format or structure
- [ ] Quality criteria or success definition
- [ ] Permission to express uncertainty (when appropriate)
## Common Optimization Patterns
**Pattern 1: Vague Request → Specific Structured Task**
- Original: "Write about marketing"
- Optimized: Adds audience, scope, length, structure, key points, tone
**Pattern 2: Implicit Context → Explicit Context**
- Original: Assumes AI knows the background
- Optimized: States context, explains why it matters, provides relevant details
**Pattern 3: Single Complex Prompt → Prompt Chain**
- Original: Tries to do everything in one request
- Optimized: Breaks into logical sequential steps with clear outputs
**Pattern 4: Generic Output → Formatted Output**
- Original: No format specification
- Optimized: Provides schema, template, or explicit structure
**Pattern 5: Assumed Constraints → Stated Constraints**
- Original: Expects AI to infer limits
- Optimized: Explicitly states length, tone, scope, what to include/exclude
Consult `references/examples.md` for detailed examples of each pattern.

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