Prompt Engineering Techniques in Skill Files
Skill files are, at their core, prompts — structured instructions that guide AI agent behavior. Applying prompt engineering techniques to skill file writing…
Skill files are, at their core, prompts — structured instructions that guide AI agent behavior. Applying prompt engineering techniques to skill file writing dramatically improves how well agents follow the skill's guidance. This skill covers embedding few-shot examples, chain-of-thought reasoning guides, constraint specification, role framing, and other prompt engineering patterns within the skill file format. ## Key Points 1. Does it do one thing? (Single Responsibility) 2. Are inputs validated? 3. Are errors handled? 4. Is the naming clear? - Naming: Function name `p` is not descriptive. Rename to - Naming: Parameter `d` is not descriptive. Rename to `person`. - Input validation: No check if 'name' and 'age' keys exist. - Error handling: `str(d['age'])` will fail if age is None. - Single responsibility: OK — function does one thing. - Naming: Clear and descriptive. Good. - Input validation: Present and thorough. Good. - Error handling: Appropriate ValueError for invalid inputs. Good. ## Quick Example ``` DON'T: ``` ``` Why: ├── Agents learn boundaries from negative examples ├── Prevents pattern matching on wrong patterns ├── Clarifies gray areas (what does "descriptive" really mean?) └── More memorable than rules alone (contrast aids understanding) ```
skilldb get skill-writing-skills/prompt-engineering-in-skillsFull skill: 396 linesPrompt Engineering Techniques in Skill Files
Purpose
Skill files are, at their core, prompts — structured instructions that guide AI agent behavior. Applying prompt engineering techniques to skill file writing dramatically improves how well agents follow the skill's guidance. This skill covers embedding few-shot examples, chain-of-thought reasoning guides, constraint specification, role framing, and other prompt engineering patterns within the skill file format.
Why Prompt Engineering Matters for Skills
Skill File as a Prompt:
┌──────────────────────────────────────────────────┐
│ System context (set by platform) │
│ + Skill file content (your prompt) │
│ + User task (runtime input) │
│ = Agent behavior │
└──────────────────────────────────────────────────┘
You control the skill file content.
The better your prompt engineering, the better the agent performs.
What prompt engineering improves:
├── Accuracy: Agent produces correct output
├── Consistency: Agent behaves the same way each time
├── Relevance: Agent stays on topic
├── Completeness: Agent covers all required aspects
└── Safety: Agent avoids harmful or incorrect outputs
Core Techniques
Technique 1: Few-Shot Examples
Providing examples of input-output pairs is the most powerful technique for guiding agent behavior:
Pattern: Show 2-3 examples before stating the general rule
Example in a Code Review Skill:
When reviewing a function, evaluate:
1. Does it do one thing? (Single Responsibility)
2. Are inputs validated?
3. Are errors handled?
4. Is the naming clear?
Example review:
Input:
```python
def p(d):
return d['name'] + ' ' + str(d['age'])
Review output:
- Naming: Function name
pis not descriptive. Rename toformat_person_stringor similar. - Naming: Parameter
dis not descriptive. Rename toperson. - Input validation: No check if 'name' and 'age' keys exist.
Add
if 'name' not in person: raise ValueError(...). - Error handling:
str(d['age'])will fail if age is None. Handle None case. - Single responsibility: OK — function does one thing.
Example review 2:
Input:
def calculate_tax(income: float, rate: float) -> float:
if income < 0:
raise ValueError("Income cannot be negative")
if rate < 0 or rate > 1:
raise ValueError("Rate must be between 0 and 1")
return round(income * rate, 2)
Review output:
- Naming: Clear and descriptive. Good.
- Input validation: Present and thorough. Good.
- Error handling: Appropriate ValueError for invalid inputs. Good.
- Single responsibility: Function calculates tax only. Good.
- Suggestion: Consider adding a docstring explaining parameters.
Now apply this review pattern to the user's code.
### Technique 2: Chain-of-Thought Scaffolding
Guide the agent's reasoning process step by step:
Pattern: "Before [action], first [analysis], then [decision], then [action]"
Example in a Database Index Skill:
Before adding an index, follow this analysis:
Step 1: Identify the slow query └── Run EXPLAIN ANALYZE on the query └── Look for "Seq Scan" on large tables (> 10K rows)
Step 2: Determine the index type └── If WHERE clause on equality (=): B-tree index (default) └── If WHERE clause on range (<, >, BETWEEN): B-tree index └── If WHERE clause on text search (LIKE 'abc%'): B-tree on text └── If WHERE clause on full-text: GIN index └── If WHERE clause on JSON field: GIN index └── If geospatial query: GiST index
Step 3: Evaluate trade-offs └── Check table write frequency (indexes slow writes) └── Check disk space (each index adds storage) └── Check if column cardinality is high enough (low cardinality = useless index)
Step 4: Create the index └── Use CREATE INDEX CONCURRENTLY in production (avoids table lock)
Step 5: Verify improvement └── Re-run EXPLAIN ANALYZE └── Confirm "Index Scan" instead of "Seq Scan" └── Measure query time improvement
This chain ensures the agent doesn't jump to "add an index" without first analyzing whether an index is appropriate.
### Technique 3: Constraint Specification
Explicit constraints prevent common agent mistakes:
Pattern: State what the agent MUST do, MUST NOT do, and SHOULD prefer
Constraints for a Migration Skill:
MUST: ├── Create a new migration file (never modify existing migrations) ├── Include both up and down migration directions ├── Use parameterized queries (never string interpolation for SQL) ├── Test migration on a copy of production data first └── Back up the database before running on production
MUST NOT: ├── Drop columns without a deprecation period ├── Run destructive migrations during business hours ├── Modify migrations that have already been applied ├── Use ORM-specific migration syntax (use raw SQL for portability) └── Include seed data in structural migrations
SHOULD PREFER: ├── Additive changes over destructive changes ├── Small, focused migrations over large batch changes ├── Reversible operations over one-way operations ├── Column renames via add-copy-drop over ALTER RENAME └── Concurrent index creation over standard (avoids locks)
Constraint Format Benefits: ├── MUST = hard requirements (agent must comply) ├── MUST NOT = guardrails (prevent common mistakes) ├── SHOULD PREFER = soft guidance (room for judgment) └── Clear hierarchy helps agent prioritize when instructions conflict
### Technique 4: Role Framing
Establishing a role/persona for the agent improves output quality:
Pattern: "When applying this skill, act as a [specific expert role]"
Examples:
Security Review Skill: "When reviewing code for security issues, evaluate as a security auditor who assumes all user input is malicious and all network communication is intercepted."
Code Review Skill: "When reviewing this code, evaluate as a senior developer who prioritizes: maintainability > performance > cleverness. Suggest changes only when they provide clear benefit."
Architecture Skill: "When designing the system architecture, think as a principal engineer who has maintained systems at this scale for 5+ years. Prioritize operational simplicity and debuggability over theoretical elegance."
Why Role Framing Works: ├── Sets the perspective for evaluation ├── Establishes priority ordering implicitly ├── Activates relevant knowledge in the model └── Provides a consistent voice for recommendations
### Technique 5: Output Format Specification
Specify the exact format you want the agent to produce:
Pattern: Show the output template, then instruct the agent to fill it
Example in an API Design Skill:
When designing a new API endpoint, document it in this format:
Endpoint: [METHOD] /api/v1/[resource]
Description: [One sentence describing what this endpoint does]
Request:
Headers:
Authorization: Bearer {token}
Content-Type: application/json
Body:
{field}: {type} — {description} [required|optional]
Response (200):
{
"data": { ... },
"meta": { "total": number, "page": number }
}
Response (4xx):
{
"error": { "code": "ERROR_CODE", "message": "Human-readable message" }
}
Example:
curl -X [METHOD] https://api.example.com/api/v1/[resource] \
-H "Authorization: Bearer TOKEN" \
-d '{"field": "value"}'
Apply this template for each endpoint in the API.
Why Format Specification Works: ├── Agent produces consistent, predictable output ├── Easier to validate (structure matches template) ├── Reduces agent "creativity" where consistency is needed └── Downstream tools can parse structured output reliably
### Technique 6: Negative Examples
Showing what NOT to do is as valuable as showing what to do:
Pattern: "Do this: [good example]. Not this: [bad example]."
Example in a Naming Convention Skill:
Variable naming:
DO:
const userCount = users.length;
const isAuthenticated = token !== null;
const maxRetryAttempts = 3;
const fetchUserProfile = async (userId) => { ... };
DON'T:
const n = users.length; // Single letter, cryptic
const flag = token !== null; // "flag" says nothing
const MAX = 3; // Ambiguous abbreviation
const doStuff = async (id) => { ... }; // Vague name
Why: ├── Agents learn boundaries from negative examples ├── Prevents pattern matching on wrong patterns ├── Clarifies gray areas (what does "descriptive" really mean?) └── More memorable than rules alone (contrast aids understanding)
### Technique 7: Conditional Instruction Blocks
Structure instructions so the agent can follow the right branch:
Pattern: Use clear if/then/else for context-dependent behavior
Example:
Determine the deployment approach:
IF the application is a static site (HTML/CSS/JS only): → Deploy to CDN (Cloudflare Pages, Netlify, Vercel) → No server required → Set cache headers for static assets (max-age=31536000)
IF the application is a server-rendered app (Next.js, Nuxt): → Deploy to container platform (Cloud Run, Fly.io) → Or use platform-specific hosting (Vercel for Next.js) → Configure health check endpoint at /api/health → Set memory limit based on expected traffic
IF the application is an API only (Express, FastAPI): → Deploy to container platform → Configure auto-scaling (min 1, max 10 instances) → Set up load balancer with health checks → Configure connection pooling for database
IF the application uses WebSockets: → Ensure platform supports persistent connections → Configure sticky sessions on load balancer → Set appropriate idle timeout (> heartbeat interval) → Cloud Run and Fly.io support WebSockets; Lambda does not
Agent can match its current context to the right branch.
## Combining Techniques
Effective skills use multiple techniques together:
- Role framing (sets context)
- Chain-of-thought (guides reasoning)
- Few-shot examples (shows expected behavior)
- Constraints (prevents mistakes)
- Output format (ensures consistency)
Example combination:
"When optimizing database queries [ROLE: as a DBA], follow this analysis process [CHAIN-OF-THOUGHT]:
- Run EXPLAIN ANALYZE on the query
- Identify the bottleneck (see examples below)
- Apply the appropriate optimization
Example 1 [FEW-SHOT]: [input query → analysis → optimization]
Example 2 [FEW-SHOT]: [different scenario → analysis → optimization]
Constraints [CONSTRAINTS]:
- Never modify table structure for query optimization alone
- Always test on staging before production
Present results as [OUTPUT FORMAT]:
Query: [original query]
Issue: [identified bottleneck]
Solution: [optimized query or index]
Expected improvement: [estimated % improvement]
```"
Anti-Patterns
Prompt Engineering Anti-Patterns in Skills:
1. Contradictory instructions:
"Always use prepared statements"
... later ...
"For simple queries, string concatenation is fine"
→ Agent follows the most recent instruction
2. Unqualified superlatives:
"Always", "Never", "Best" without context
→ Real situations have exceptions; qualify with "when..."
3. Implicit priorities:
Listing 10 guidelines without indicating which override which
→ Add "In case of conflict, prioritize security over performance"
4. Too many examples:
5+ examples of the same pattern wastes context tokens
→ 2-3 well-chosen examples are sufficient
5. Prompt injection vulnerability:
Skill instructions that could be overridden by user input
→ Structure skill as system-level instruction, not user-level
When to Apply This Skill
Use this skill when:
- Writing skill files that will directly guide AI agent behavior
- Improving skills where agents produce inconsistent results
- Embedding decision-making logic into skill instructions
- Creating skills that must produce structured output
- Designing skills for complex, multi-step workflows
- Debugging skills where agents make unexpected choices
Install this skill directly: skilldb add skill-writing-skills
Related Skills
Skill Composition Patterns
Skills rarely exist in isolation. Complex tasks require combining multiple skills, and understanding composition patterns helps you design skills that work…
Managing Skill Dependencies
Skills rarely exist in complete isolation. A skill about deploying a Next.js app implicitly depends on knowledge of Node.js, Docker, and cloud platforms.…
Skill Discovery Optimization
A skill that can't be found can't be used. Discovery optimization ensures that when a user or AI agent needs a specific capability, they can locate the right…
Skill File Structure and Anatomy
This skill teaches the foundational structure of a well-formed skill file for SkillDB. A skill file is a markdown document that teaches an AI agent how to…
Skill File Templates and Archetypes
Not all skill files follow the same structure. A tutorial skill differs from a reference skill, which differs from a troubleshooting skill. This skill provides…
Skill Pack Organization and Planning
A skill pack is a curated collection of related skills that together provide comprehensive coverage of a domain. Thoughtful organization transforms a pile of…