prompt-engineering
Included with Lifetime
$97 forever
Comprehensive prompting techniques including chain-of-thought, few-shot, zero-shot, system prompts, persona design, and evaluation patterns
ai-promptingpromptingllmchain-of-thoughtfew-shotzero-shotsystem-promptspersonasevaluation
What this skill does
# Prompt Engineering Skill
> Comprehensive prompting techniques for effective LLM interactions across any model or framework.
## Quick Start
```python
import openai
client = openai.OpenAI()
# Basic prompt
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert engineer."},
{"role": "user", "content": "Explain mooring systems."}
]
)
print(response.choices[0].message.content)
```
## When to Use This Skill
**USE when:**
- Designing prompts from scratch for any use case
- Learning core principles applicable across all LLMs
- Need portable patterns not tied to specific frameworks
- Building simple LLM integrations without heavy dependencies
- Optimizing existing prompts for better results
- Creating reusable prompt templates for teams
- Debugging underperforming LLM applications
- Teaching prompt engineering to others
**DON'T USE when:**
- Need framework-specific features (use LangChain/DSPy)
- Require programmatic optimization (use DSPy)
- Building production RAG systems (use LangChain)
- Need conversation memory management (use frameworks)
## Prerequisites
```bash
# OpenAI
pip install openai>=1.0.0
export OPENAI_API_KEY="sk-..."
# Anthropic
pip install anthropic>=0.5.0
export ANTHROPIC_API_KEY="sk-ant-..."
# Azure OpenAI
pip install openai>=1.0.0
export AZURE_OPENAI_ENDPOINT="https://..."
export AZURE_OPENAI_KEY="..."
# Optional: For testing prompts
pip install pytest promptfoo
```
## Core Concepts
### Anatomy of a Prompt
```
[SYSTEM CONTEXT] - Who is the AI, what are its capabilities/constraints
[TASK DESCRIPTION] - What needs to be done
[INPUT DATA] - The specific content to process
[OUTPUT FORMAT] - How the response should be structured
[EXAMPLES] - Optional: demonstrations of desired behavior
[CONSTRAINTS] - Limitations, things to avoid
```
### The Prompt Engineering Loop
```
1. Define Goal -> What do you want to achieve?
2. Draft Prompt -> Initial attempt
3. Test -> Run with diverse inputs
4. Analyze -> Identify failures and patterns
5. Refine -> Improve based on analysis
6. Repeat -> Until quality meets requirements
```
## Core Capabilities
### 1. Zero-Shot Prompting
**Basic Zero-Shot:**
```python
def zero_shot_prompt(task: str, input_text: str) -> str:
"""
Zero-shot prompting: Direct instruction without examples.
Best for simple, well-defined tasks.
"""
prompt = f"""
Task: {task}
Input: {input_text}
Output:
"""
return prompt
# Usage
prompt = zero_shot_prompt(
task="Classify this text as positive, negative, or neutral",
input_text="The mooring analysis passed all safety requirements."
)
# Output: positive
```
**Zero-Shot with Role:**
```python
def zero_shot_with_role(role: str, task: str, input_text: str) -> str:
"""
Zero-shot with explicit role definition.
"""
system = f"You are a {role}. You provide expert analysis."
user = f"""
{task}
{input_text}
"""
return system, user
# Usage
system, user = zero_shot_with_role(
role="senior offshore engineer with 20 years experience",
task="Review this mooring design and identify any concerns:",
input_text="8-line spread mooring in 150m water depth..."
)
```
**Zero-Shot Classification:**
```python
CLASSIFICATION_TEMPLATE = """
Classify the following engineering report into one of these categories:
- ANALYSIS: Technical analysis or simulation results
- INSPECTION: Field inspection or survey findings
- DESIGN: Design specifications or requirements
- INCIDENT: Incident reports or failure analysis
- MAINTENANCE: Maintenance records or procedures
Report:
{report_text}
Category:
"""
def classify_report(report_text: str) -> str:
prompt = CLASSIFICATION_TEMPLATE.format(report_text=report_text)
# Send to LLM
return prompt
```
### 2. Few-Shot Prompting
**Basic Few-Shot:**
```python
def few_shot_prompt(
task_description: str,
examples: list,
input_text: str
) -> str:
"""
Few-shot prompting with examples.
Generally 2-5 examples work best.
"""
prompt = f"{task_description}\n\n"
# Add examples
for i, ex in enumerate(examples, 1):
prompt += f"Example {i}:\n"
prompt += f"Input: {ex['input']}\n"
prompt += f"Output: {ex['output']}\n\n"
# Add actual input
prompt += f"Now process this:\n"
prompt += f"Input: {input_text}\n"
prompt += f"Output:"
return prompt
# Usage
examples = [
{
"input": "Tension: 2500 kN, Limit: 2800 kN",
"output": "PASS - Tension is 89% of limit, within acceptable range."
},
{
"input": "Tension: 3100 kN, Limit: 2800 kN",
"output": "FAIL - Tension exceeds limit by 11%. Redesign required."
},
{
"input": "Tension: 2750 kN, Limit: 2800 kN",
"output": "WARNING - Tension is 98% of limit, minimal margin."
}
]
prompt = few_shot_prompt(
task_description="Evaluate mooring line tension against limits.",
examples=examples,
input_text="Tension: 2200 kN, Limit: 2800 kN"
)
```
**Few-Shot with Diverse Examples:**
```python
def create_balanced_few_shot(examples_by_category: dict, input_text: str) -> str:
"""
Create few-shot prompt with balanced examples across categories.
"""
prompt = "Classify engineering documents into categories.\n\n"
# Include one example from each category
for category, examples in examples_by_category.items():
ex = examples[0] # Take first example from each
prompt += f"Document: {ex['text']}\n"
prompt += f"Category: {category}\n\n"
prompt += f"Document: {input_text}\n"
prompt += f"Category:"
return prompt
# Usage
examples_by_category = {
"ANALYSIS": [
{"text": "FEA results show stress concentration at weld..."}
],
"INSPECTION": [
{"text": "Visual inspection revealed corrosion on flange..."}
],
"DESIGN": [
{"text": "The platform shall be designed for 100-year storm..."}
]
}
prompt = create_balanced_few_shot(
examples_by_category,
input_text="Fatigue analysis indicates 35-year service life..."
)
```
### 3. Chain-of-Thought Prompting
**Basic Chain-of-Thought:**
```python
COT_TEMPLATE = """
Solve this problem step by step.
Problem: {problem}
Let me think through this carefully:
Step 1: First, I'll identify the key information...
Step 2: Next, I'll determine the approach...
Step 3: Then, I'll perform the calculations...
Step 4: Finally, I'll verify and state the answer...
Solution:
"""
def chain_of_thought_prompt(problem: str) -> str:
return COT_TEMPLATE.format(problem=problem)
# Usage
prompt = chain_of_thought_prompt(
problem="""
A mooring line has a breaking load of 5000 kN.
The maximum tension is 2800 kN.
What is the safety factor, and does it meet the API RP 2SK
requirement of 1.67 for intact conditions?
"""
)
```
**Zero-Shot Chain-of-Thought:**
```python
def zero_shot_cot(question: str) -> str:
"""
Zero-shot CoT: Simply append "Let's think step by step"
Surprisingly effective for many reasoning tasks.
"""
return f"{question}\n\nLet's think step by step."
# Usage
prompt = zero_shot_cot(
"If a vessel offsets 50m from its mean position, and the "
"mooring stiffness is 100 kN/m, what is the restoring force?"
)
```
**Structured Chain-of-Thought:**
```python
STRUCTURED_COT_TEMPLATE = """
Analyze this engineering problem using structured reasoning.
Problem: {problem}
## Understanding
What are the key facts and requirements?
## Approach
What method or formula will I use?
## Calculation
Show the step-by-step calculation.
## Verification
How can I verify this is correct?
## Answer
State the final answer clearly.
"""
def structured_cot(problem: str) -> str:
return STRUCTURED_COT_TEMPLATE.format(problem=problem)
```
**Self-Consistency Chain-of-Thought:**
```pythonRelated in ai-prompting
pandasai
IncludedConversational data analysis using natural language queries on DataFrames. Chat with your data using LLMs to generate insights, create visualizations, and explain code.
ai-prompting
agenta
IncludedLLM prompt management and evaluation platform. Version prompts, run A/B tests, evaluate with metrics, and deploy with confidence using Agenta's self-hosted solution.
ai-prompting
dspy
IncludedCompile prompts into self-improving pipelines with signatures, modules, optimizers, and programmatic prompt engineering
ai-prompting
langchain
IncludedBuild production-ready LLM applications with chains, agents, memory, tools, and RAG pipelines using the LangChain framework
ai-prompting