Prompts Deep Dive
Prompts are the core interface for interacting with AI models. Through carefully designed prompts, you can guide AI to generate more accurate code and suggestions that better meet your needs.
Prompt Basics
What are Prompts
Prompts are instructions or questions sent to AI models, used to:
- Clarify Intent: Clearly express what you want
- Provide Context: Give relevant background information
- Set Constraints: Define output format and requirements
- Guide Output: Influence how AI responds
Prompt Types
System Prompts
System prompts define the AI assistant's role and behavior guidelines:
models:
- name: "guided-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.7
maxTokens: 4000System prompt examples can be defined in .bytebuddy/prompts/system.md:
# System Prompt
You are a professional code assistant, skilled at:
- Writing clear, maintainable code
- Following project coding standards
- Providing detailed code comments
- Considering performance and security
Always:
1. Use project naming conventions
2. Add necessary error handling
3. Write concise comments
4. Consider edge casesUser Prompts
User prompts are specific task requests:
- Code Generation: "Create a user authentication function"
- Code Explanation: "Explain what this code does"
- Code Refactoring: "Optimize this function's performance"
- Problem Diagnosis: "Why does this code throw an error"
Context Prompts
Provide relevant background information:
- Code Context: Current file and related files
- Project Info: Tech stack, architecture patterns
- History: Previous conversations and operations
- Documentation: Relevant API documentation
Prompt Engineering
Basic Principles
1. Clear and Specific
models:
- name: "precise-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.5
maxTokens: 4000Good prompt:
Create a React functional component named UserCard,
accepting a user object as props (with name, email, avatar fields),
styled with Tailwind CSS,
displaying user avatar, name, and email.Poor prompt:
Make a user card2. Provide Context
# Project Context
Current project: React + TypeScript + Vite
State management: Zustand
Styling: Tailwind CSS
Component library: shadcn/ui
Please generate code based on this tech stack.3. Set Constraints
# Code Generation Constraints
- Use TypeScript
- Follow ESLint rules
- Add JSDoc comments
- Include error handling
- Max function length 50 lines4. Specify Format
# Output Format
Please output in the following format:
1. Code implementation
2. Usage example
3. Notes
4. Test casesAdvanced Techniques
Few-Shot Prompting
Provide examples to guide output:
# Naming Convention Examples
Variable naming:
- Good: `userProfile`, `isAuthenticated`, `totalCount`
- Bad: `up`, `auth`, `tc`
Function naming:
- Good: `getUserById()`, `validateEmail()`, `formatDate()`
- Bad: `get()`, `check()`, `format()`
Please name variables and functions following these conventions.Chain-of-Thought
Guide AI to think step by step:
# Problem Analysis
Please analyze this problem following these steps:
1. Identify the root cause
2. List possible solutions
3. Evaluate pros and cons of each
4. Recommend the best solution
5. Provide implementation stepsRole Playing
Have AI assume a specific role:
models:
- name: "security-expert"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 4000# Security Expert Role
You are an experienced security expert, focused on:
- Identifying security vulnerabilities in code
- Providing security best practice recommendations
- Recommending encryption and authentication solutions
- Conducting security code reviews
Please review the following code from a security perspective.Scenario-Based Prompts
Code Generation Scenarios
API Development
# API Development Task
Create a RESTful API endpoint:
**Path**: POST /api/users
**Function**: Create new user
**Request Body**:
```json
{
"name": "string",
"email": "string",
"password": "string"
}
```Requirements:
- Validate email format
- Encrypt password for storage
- Check email uniqueness
- Return created user info (without password)
- Add error handling
Tech Stack: Node.js + Express + PostgreSQL
#### Database Model
```markdown
# Database Model Design
Create a Prisma schema definition:
**Model**: Post (blog post)
**Fields**:
- id: Auto-increment primary key
- title: Title (required, max 200 chars)
- content: Content (required)
- published: Is published (default false)
- authorId: Author ID (foreign key to User)
- createdAt: Creation time
- updatedAt: Update time
**Relations**:
- An author can have multiple posts
- A post belongs to one authorCode Review Scenarios
models:
- name: "code-reviewer"
provider: "anthropic"
model: "claude-3-sonnet"
apiKey: "${ANTHROPIC_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 4000# Code Review Checklist
Please review the following code, focusing on:
1. **Code Quality**
- Readability and maintainability
- Naming conventions
- Code complexity
2. **Security**
- Input validation
- SQL injection risks
- XSS vulnerabilities
3. **Performance**
- Algorithm efficiency
- Database query optimization
- Memory usage
4. **Best Practices**
- Error handling
- Logging
- Unit tests
For each issue found, provide:
- Issue description
- Severity (High/Medium/Low)
- Fix recommendation
- Improved code exampleRefactoring Scenarios
# Code Refactoring Task
Refactor the following code with goals:
1. **Improve Readability**
- Use meaningful variable names
- Simplify complex logic
- Add explanatory comments
2. **Enhance Structure**
- Extract duplicate code
- Break down large functions
- Apply design patterns
3. **Optimize Performance**
- Reduce unnecessary computations
- Optimize data structures
- Cache repeated calls
4. **Increase Robustness**
- Add error handling
- Handle edge cases
- Input validation
Please maintain original functionality.Prompt Templates
Feature Development Template
# Feature Development
**Feature Name**: [Feature name]
**Requirements**: [Detailed feature requirements]
**Tech Stack**:
- Frontend: [Technology]
- Backend: [Technology]
- Database: [Technology]
**Implementation Requirements**:
1. [Requirement 1]
2. [Requirement 2]
3. [Requirement 3]
**Acceptance Criteria**:
- [ ] [Criterion 1]
- [ ] [Criterion 2]
- [ ] [Criterion 3]
**Notes**: [Special considerations]Bug Fix Template
# Bug Fix
**Issue Description**: [Describe bug symptoms]
**Reproduction Steps**:
1. [Step 1]
2. [Step 2]
3. [Step 3]
**Expected Behavior**: [What should happen]
**Actual Behavior**: [What actually happens]
**Environment**:
- OS: [OS]
- Browser: [Browser]
- Version: [Version]
**Related Code**: [Paste relevant code]
**Error Message**: [Paste error stack]
Please analyze the root cause and provide a fix.Performance Optimization Template
# Performance Optimization
**Performance Issue**: [Describe performance problem]
**Performance Metrics**:
- Current response time: [Time]
- Target response time: [Time]
- Memory usage: [Memory]
- CPU usage: [CPU]
**Analysis Requirements**:
1. Identify performance bottleneck
2. Analyze root cause
3. Propose optimization solutions
4. Evaluate optimization impact
**Constraints**: [Technical or business constraints]Prompt Optimization
Iterative Improvement
models:
- name: "iterative-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.6
maxTokens: 4000Optimization process:
- Initial Prompt: Basic requirement description
- Observe Output: Check generated results
- Identify Issues: Find unsatisfactory parts
- Adjust Prompt: Add more details or constraints
- Retest: Validate improvements
A/B Testing
Compare different prompt effectiveness:
# Prompt A
Create a login form
# Prompt B
Create a React login form component,
with email and password input fields,
remember me checkbox,
login button,
using Formik for form validation,
styled with Tailwind CSS.Temperature Tuning
models:
# Creative tasks - high temperature
- name: "creative-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.9
maxTokens: 4000
# Precise tasks - low temperature
- name: "precise-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.2
maxTokens: 4000Temperature selection:
- 0.0-0.3: Code generation, data processing
- 0.4-0.7: General conversation, Q&A
- 0.8-1.0: Brainstorming, creative suggestions
Best Practices
1. Layered Prompting
# Layer 1: System Role
You are a React expert
# Layer 2: Task Context
Current project uses React 18 + TypeScript
# Layer 3: Specific Task
Create a user list component
# Layer 4: Detailed Requirements
Use hooks, support pagination, add search functionality2. Use Checkpoints
Before starting to code, please:
1. Confirm you understand the requirements
2. List implementation steps
3. Point out potential issues
Then proceed with implementation.3. Request Explanations
Please add comments in the code explaining:
- Implementation principles of key logic
- Why this approach was chosen
- Edge cases to be aware of4. Iterative Refinement
Please provide a basic implementation first,
then I'll give feedback,
and you can optimize and improve based on that.Environment Variables
# ~/.bashrc or ~/.zshrc
export OPENAI_API_KEY="your-openai-api-key"
export ANTHROPIC_API_KEY="your-anthropic-api-key"By mastering prompt engineering techniques, you can collaborate more effectively with AI to obtain higher quality code and suggestions.