Prompt Engineering Best Practices
Prompt engineering is a critical skill for optimizing AI model output. This document introduces important best practices to help you write more effective prompts.
Basic Principles
1. Be Clear and Specific
- Use clear, specific language
- Avoid vague or ambiguous expressions
- Explicitly specify the desired output format
Example:
❌ Bad prompt:
"Tell me about artificial intelligence"
✅ Good prompt:
"Please briefly introduce the history of artificial intelligence development, focusing on major breakthroughs in the past 5 years, presented as a timeline"
✅ Better prompt:
"Please present the history of artificial intelligence development as a timeline, focusing on:
1. Major technical breakthroughs in the past 5 years
2. Specific application scenarios for each breakthrough
3. Impact on the industry
Please output in markdown format, with each time point including a title, description, and impact."
2. Structured Prompts
- Use a clear instruction structure
- Break complex tasks into simple steps
- Use markers and delimiters to improve readability
Example:
Please analyze this code following these steps:
1. Code functionality analysis
2. Potential issue identification
3. Optimization suggestions
Code:
[code content]
✅ Better structured prompt:
Please analyze this code following these steps:
1. Code Functionality Analysis
- Main functionality
- Core algorithms
- Key parameters
2. Potential Issue Identification
- Performance issues
- Security issues
- Maintainability issues
3. Optimization Suggestions
- Code structure optimization
- Performance optimization
- Security enhancements
4. Improvement Examples
- Optimized code snippets
- Performance comparison data
Code:
[code content]
3. Context Management
- Provide necessary background information
- Clearly define the task scope and constraints
- Specify output format and length
Example:
Background: This is a Python tutorial for beginners
Task: Explain the following code snippet
Requirements:
- Use simple language
- No more than 200 words
- Include a practical application example
✅ Better context management:
Background: This is a Python tutorial for beginners, targeting programming newcomers
Task: Explain the following code snippet to help readers understand basic concepts
Requirements:
- Use plain, easy-to-understand language, avoiding technical jargon
- No more than 200 words, keep it concise
- Include a practical application example
- Provide the code execution result
- Explain common errors that may be encountered
Advanced Techniques
1. Role Setting
Guide model output by setting a specific role:
You are an experienced Python developer. Please explain the following concept as a mentor:
[concept content]
✅ Better role setting:
You are a senior engineer with 10 years of Python development experience and also an excellent programming mentor. Please explain this concept from the following perspectives:
1. Basic principles (for beginners)
2. Practical applications (for practitioners)
3. Advanced techniques (for intermediate learners)
4. Best practices (for professional developers)
Concept: [concept content]
2. Example-Guided Prompting
Use examples to demonstrate the expected output format:
Please answer questions in the following format:
Question: What is a function?
Answer:
- Definition: A function is a reusable block of code
- Purpose: Used to perform specific tasks
- Example: def greet(name): return f"Hello, {name}"
Now please explain: What is a class?
✅ Better example-guided prompting:
Please answer questions in the following format:
Question: What is a function?
Answer:
1. Definition
- A function is a reusable block of code
- It can receive input parameters
- It returns a result
2. Core Features
- Reusability
- Parameterization
- Return values
3. Use Cases
- Code reuse
- Logic encapsulation
- Modular design
4. Code Example
```python
def greet(name):
return f"Hello, {name}"
# Usage example
result = greet("Alice")
print(result) # Output: Hello, Alice
- Best Practices
- Single responsibility
- Clear naming
- Appropriate comments
Now please explain in the same format: What is a class?
### 3. Constraint Conditions
Clearly specify output limitations:
```text
Please explain quantum computing in no more than 100 words, ensuring:
- Use plain, easy-to-understand language
- Include a practical application scenario
- Avoid technical jargon
✅ Better constraint conditions:
Please explain quantum computing with the following requirements:
1. Content Requirements
- Core concept explanation (50 words or less)
- Brief working principle description (100 words or less)
- Practical application example (50 words or less)
2. Expression Requirements
- Use plain, easy-to-understand language
- Avoid technical jargon
- Use analogies for explanation
3. Format Requirements
- Use bullet points
- Use markdown format
- Include a simple diagram explanation
4. Quality Requirements
- Ensure accuracy
- Clear logic
- Easy to understand
Platform Agent Creation Tool
The GeniSpace platform provides a professional agent creation tool to help you quickly create and configure AI agents. With this tool, you can:
-
Agent Configuration Generation
- Simply describe the agent's functional requirements
- The system automatically generates complete configuration information
- Includes name, description, category, and other basic information
- Automatically generates system prompts and prompt templates
-
Core Capability Definition
- Automatically identifies and lists the agent's core capabilities
- Provides capability descriptions and examples
- Supports custom capability extensions
-
Application Scenario Analysis
- Automatically analyzes and recommends applicable scenarios
- Provides specific usage examples
- Helps users understand the agent's application scope
-
Configuration Optimization Suggestions
- Provides configuration optimization recommendations
- Automatically checks configuration completeness
- Ensures configuration follows best practices
Usage example:
1. Open the agent creation tool
2. Enter the agent functionality description:
"I need an agent that can analyze sales data, identify trends, and generate reports"
3. The system will automatically generate:
- Agent name and description
- System prompt
- Prompt templates
- Core capability list
- Usage examples
- Application scenarios
Common Issue Resolution
1. Output Too Generic
Solution:
- Add specific evaluation criteria
- Request detailed explanations
- Specify output format
✅ Better solution:
Please provide specific analysis, including:
1. Specific Issues
- Issue description
- Impact scope
- Severity level
2. Quantitative Metrics
- Performance data
- Comparison benchmarks
- Improvement targets
3. Real Cases
- Problem scenario
- Reproduction steps
- Impact results
4. Improvement Suggestions
- Specific measures
- Implementation steps
- Expected outcomes
2. Output Deviates from Topic
Solution:
- Clearly define task scope
- Provide relevant background information
- Use constraints to limit output
✅ Better solution:
Please strictly focus on the following topic:
1. Topic Scope
- Core topic: [specific topic]
- Related topics: [related topics]
- Excluded topics: [irrelevant topics]
2. Content Requirements
- Key content: [specific focus]
- Depth requirement: [level of detail]
- Breadth requirement: [coverage scope]
3. Output Constraints
- Word limit: [specific word count]
- Format requirement: [specific format]
- Quality requirement: [specific standards]
3. Inconsistent Output Quality
Solution:
- Use more specific instructions
- Add quality check steps
- Request reasoning process
✅ Better solution:
Please output according to the following standards:
1. Accuracy
- Information verification
- Data validation
- Logic checks
2. Completeness
- Content coverage
- In-depth analysis
- Comprehensive consideration
3. Logical Coherence
- Clear structure
- Sufficient argumentation
- Reasonable conclusions
4. Practicality
- Actionable recommendations
- Specific steps
- Expected outcomes
Prompt Templates
1. Code Analysis Template
Please analyze the following code:
Code:
[code content]
Requirements:
1. Functionality description
2. Potential issues
3. Improvement suggestions
4. Performance optimization plan
Output format:
- Use headings for each section
- Use bullet point lists
- Include code examples
✅ Better code analysis template:
Please analyze the code following this structure:
1. Code Overview
- Main functionality
- Tech stack
- Architecture design
2. Detailed Analysis
- Core algorithms
- Key workflows
- Data structures
3. Issue Identification
- Performance issues
- Security issues
- Maintainability issues
4. Optimization Suggestions
- Code structure optimization
- Performance optimization
- Security enhancements
5. Improvement Examples
- Optimized code
- Performance comparison
- Test results
Code:
[code content]
2. Content Creation Template
Please write an article about [topic]:
Requirements:
1. Target audience: [specify audience]
2. Article length: [word count range]
3. Style: [specify style]
4. Key points: [list points to include]
Output format:
- Title
- Introduction
- Body (in paragraphs)
- Summary
✅ Better content creation template:
Please write an article according to the following requirements:
1. Content Planning
- Topic: [specific topic]
- Target audience: [audience group]
- Core viewpoint: [main viewpoint]
- Article structure: [specific structure]
2. Writing Requirements
- Article length: [word count range]
- Writing style: [specific style]
- Language requirements: [language characteristics]
- Format requirements: [specific format]
3. Content Elements
- Key points: [specific points]
- Case requirements: [case types]
- Data requirements: [data types]
- Citation requirements: [citation standards]
4. Quality Requirements
- Logical coherence
- Readability
- Professionalism
- Practicality
3. Problem-Solving Template
Please solve the following problem:
Problem Description:
[describe the problem in detail]
Background Information:
[relevant background]
Requirements:
1. Problem analysis
2. Solution
3. Implementation steps
4. Notes and caveats
Output format:
- Use numbered lists
- Include code examples (if applicable)
- Provide verification methods
✅ Better problem-solving template:
Please solve the problem following these steps:
1. Problem Analysis
- Problem description
- Impact scope
- Root cause
- Related factors
2. Solution
- Approach
- Technical solution
- Alternative solutions
- Cost assessment
3. Implementation Steps
- Preparation
- Specific steps
- Timeline
- Resource requirements
4. Verification Methods
- Test plan
- Acceptance criteria
- Monitoring metrics
- Contingency plan
5. Notes and Caveats
- Risk warnings
- Key points
- Common issues
- Best practices
Important Notes
-
Avoid Sensitive Information
- Do not include sensitive data in prompts
- Use example data instead of real data
-
Keep Prompts Concise
- Include only necessary information
- Avoid redundant content
-
Test and Iterate
- Test different prompt versions
- Optimize prompts based on results
- Document effective prompt templates
-
Error Handling
- Anticipate possible errors
- Provide fallback options
- Include error handling instructions
Tools and Resources
-
Prompt Engineering Tools
- PromptPerfect - Professional prompt optimization and testing tool
- LangChain - Prompt engineering development framework
- PromptBase - Prompt template marketplace
- Dify - Open-source prompt engineering platform
- PromptFlow - Microsoft's open-source prompt workflow tool
-
Learning Resources
- OpenAI Cookbook - OpenAI official prompt engineering guide
- Learn Prompting - Free prompt engineering learning platform
- Prompt Engineering Guide - Comprehensive prompt engineering guide
- Anthropic Prompt Library - Claude prompt library
- Hugging Face Prompt Engineering - Hugging Face prompt engineering course
-
Best Practice Guides
- Microsoft Prompt Engineering - Microsoft prompt engineering best practices
- Google AI Prompt Engineering - Google AI prompt engineering guide
- Anthropic Prompt Engineering - Anthropic prompt engineering documentation
- DeepLearning.AI Prompt Engineering - DeepLearning.AI prompt engineering course
- Prompt Engineering Institute - Prompt engineering research resources
-
Community Resources
- r/PromptEngineering - Reddit prompt engineering community
- Prompt Engineering Discord - Prompt engineering Discord community
- Hugging Face Forums - Hugging Face discussion forum
- LangChain Discord - LangChain developer community
- OpenAI Community - OpenAI official community
-
Research Papers
- Chain-of-Thought Prompting - Chain-of-thought prompting research
- Self-Consistency - Self-consistency prompting technique
- Tree of Thoughts - Tree of thoughts prompting method
- ReAct - Reasoning and acting prompting framework
- Least-to-Most Prompting - Least-to-most prompting method
Summary
Effective prompt engineering requires:
- Clear instructions
- Appropriate structure
- Sufficient context
- Explicit constraints
- Continuous optimization
By following these best practices, you can significantly improve the output quality and reliability of AI models.