Python 7 min read

Prompt Engineering: Master the Art of AI Communication

Learn prompt engineering techniques for ChatGPT, Claude, and other LLMs. Master zero-shot, few-shot, chain-of-thought, and advanced prompting strategies.

MR

Moshiour Rahman

Advertisement

What is Prompt Engineering?

Prompt engineering is the practice of designing and optimizing inputs to AI language models to get the best possible outputs. It’s a crucial skill for anyone working with LLMs like GPT-4, Claude, or Llama.

Why It Matters

Poor PromptsEngineered Prompts
Vague responsesPrecise answers
Inconsistent outputReliable results
Generic contentTailored responses
HallucinationsGrounded facts

Basic Prompting Techniques

Clear Instructions

❌ Bad: "Write about Python"

✅ Good: "Write a 300-word beginner's guide to Python lists,
including:
- What lists are
- How to create them
- 3 common operations with code examples
Use simple language suitable for someone new to programming."

Role Assignment

System: You are an experienced Python developer who specializes
in writing clean, readable code. You always include helpful
comments and follow PEP 8 style guidelines.

User: Write a function to validate email addresses.

Output Format Specification

Analyze the following customer review and provide:
1. Sentiment: [Positive/Negative/Neutral]
2. Key Topics: [list up to 3 topics]
3. Suggested Action: [one sentence]

Review: "The product arrived late but the quality exceeded
my expectations. Customer service was helpful when I inquired
about the delay."

Respond in JSON format.

Advanced Techniques

Zero-Shot Prompting

Classify the following text into one of these categories:
Technology, Sports, Politics, Entertainment.

Text: "The new smartphone features a revolutionary AI chip
that processes images 50% faster than previous models."

Category:

Few-Shot Prompting

Classify the sentiment of movie reviews.

Review: "An absolute masterpiece of cinema!"
Sentiment: Positive

Review: "Waste of two hours, terrible acting."
Sentiment: Negative

Review: "It was okay, nothing special but not bad either."
Sentiment: Neutral

Review: "The plot twists kept me on the edge of my seat!"
Sentiment:

Chain-of-Thought (CoT)

Solve this step by step:

A store sells apples for $2 each and oranges for $3 each.
If John buys 5 apples and some oranges, spending exactly $19,
how many oranges did he buy?

Let's think through this step by step:
1. First, calculate the cost of apples
2. Then determine remaining budget
3. Finally, calculate number of oranges

Show your reasoning:

Self-Consistency

import anthropic

def get_consistent_answer(question: str, num_samples: int = 5):
    client = anthropic.Anthropic()
    answers = []

    for _ in range(num_samples):
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=500,
            temperature=0.7,
            messages=[{
                "role": "user",
                "content": f"""Solve this problem step by step, then provide
                your final answer on the last line starting with "ANSWER:".

                {question}"""
            }]
        )

        text = response.content[0].text
        # Extract answer
        if "ANSWER:" in text:
            answer = text.split("ANSWER:")[-1].strip()
            answers.append(answer)

    # Return most common answer
    from collections import Counter
    return Counter(answers).most_common(1)[0][0]

Tree of Thoughts

Problem: Design a marketing campaign for a new eco-friendly
water bottle.

Generate 3 different creative directions:

Direction 1: [Environmental Focus]
- Key message:
- Target audience:
- Main channels:
- Pros:
- Cons:

Direction 2: [Health & Wellness Focus]
- Key message:
- Target audience:
- Main channels:
- Pros:
- Cons:

Direction 3: [Lifestyle/Fashion Focus]
- Key message:
- Target audience:
- Main channels:
- Pros:
- Cons:

Now evaluate each direction and recommend the best approach
with justification.

Structured Output

JSON Output

Extract information from the following job posting and return
as JSON:

Job Posting: "Senior Python Developer at TechCorp.
Requirements: 5+ years Python experience, Django/FastAPI,
PostgreSQL, AWS. Remote friendly. Salary: $120k-150k.
Apply by December 31."

Return JSON with these fields:
{
  "title": "",
  "company": "",
  "experience_years": 0,
  "skills": [],
  "work_type": "",
  "salary_range": {"min": 0, "max": 0},
  "deadline": ""
}

Markdown Tables

Compare the following programming languages for web development.
Create a markdown table with columns: Language, Learning Curve,
Performance, Ecosystem, Best For.

Languages to compare: Python, JavaScript, Go, Rust

XML Structure

Generate a product catalog entry in XML format:

Product: Wireless Bluetooth Headphones
Price: $79.99
Features: Noise cancellation, 30-hour battery, foldable design

<product>
  <name></name>
  <price currency="USD"></price>
  <features>
    <feature></feature>
  </features>
  <availability></availability>
</product>

Context Management

System Prompts

system_prompt = """You are an expert code reviewer with 10+ years
of experience. When reviewing code:

1. First identify any bugs or errors
2. Then suggest performance improvements
3. Finally recommend code style improvements

Always be constructive and explain WHY changes are beneficial.
Format your response with clear sections using markdown headers.
If the code is good, acknowledge what's done well before suggestions."""

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=2000,
    system=system_prompt,
    messages=[{
        "role": "user",
        "content": f"Review this code:\n```python\n{code}\n```"
    }]
)

Context Window Optimization

def chunk_document(text: str, chunk_size: int = 4000) -> list[str]:
    """Split document into chunks for processing."""
    words = text.split()
    chunks = []
    current_chunk = []
    current_size = 0

    for word in words:
        if current_size + len(word) > chunk_size:
            chunks.append(' '.join(current_chunk))
            current_chunk = [word]
            current_size = len(word)
        else:
            current_chunk.append(word)
            current_size += len(word) + 1

    if current_chunk:
        chunks.append(' '.join(current_chunk))

    return chunks

def summarize_long_document(document: str) -> str:
    """Summarize a long document using map-reduce."""
    chunks = chunk_document(document)
    summaries = []

    # Map: Summarize each chunk
    for chunk in chunks:
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=500,
            messages=[{
                "role": "user",
                "content": f"Summarize this text in 2-3 sentences:\n\n{chunk}"
            }]
        )
        summaries.append(response.content[0].text)

    # Reduce: Combine summaries
    combined = "\n".join(summaries)
    final_response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": f"Create a cohesive summary from these section summaries:\n\n{combined}"
        }]
    )

    return final_response.content[0].text

Task-Specific Prompts

Code Generation

Write a Python function with the following specifications:

Function name: calculate_compound_interest
Parameters:
  - principal (float): Initial investment amount
  - rate (float): Annual interest rate (as decimal, e.g., 0.05 for 5%)
  - time (int): Number of years
  - n (int): Number of times interest compounds per year (default: 12)

Returns: float (final amount)

Requirements:
- Include type hints
- Add docstring with example usage
- Handle edge cases (negative values, zero values)
- Round result to 2 decimal places

Data Analysis

I have a dataset with the following columns:
- user_id (int)
- purchase_date (datetime)
- product_category (string)
- amount (float)
- is_returned (boolean)

Write Python code using pandas to:
1. Calculate total revenue by category (excluding returns)
2. Find the top 10 customers by total spend
3. Calculate monthly revenue trends
4. Identify products with return rate > 10%

Include comments explaining each step.

Content Writing

Write a blog post introduction (150-200 words) about
"The Future of Remote Work in 2025"

Requirements:
- Start with a compelling hook
- Include a relevant statistic or trend
- Preview 3 main points the article will cover
- End with a transition to the main content
- Tone: Professional but conversational
- Target audience: HR professionals and business leaders

Prompt Templates

Analysis Template

analysis_template = """
Analyze the following {content_type}:

{content}

Provide your analysis in this format:

## Summary
[2-3 sentence overview]

## Key Points
- [Point 1]
- [Point 2]
- [Point 3]

## Strengths
[What works well]

## Areas for Improvement
[Constructive suggestions]

## Recommendations
[Actionable next steps]
"""

Comparison Template

comparison_template = """
Compare {item_a} and {item_b} for {use_case}.

Create a detailed comparison covering:

| Aspect | {item_a} | {item_b} |
|--------|----------|----------|
| [Aspect 1] | | |
| [Aspect 2] | | |
| [Aspect 3] | | |

## When to Choose {item_a}
[Scenarios and reasons]

## When to Choose {item_b}
[Scenarios and reasons]

## Recommendation
[Your verdict based on {use_case}]
"""

Best Practices

Do’s

  • Be specific and detailed
  • Provide examples when possible
  • Specify output format
  • Break complex tasks into steps
  • Use consistent formatting

Don’ts

  • Don’t be vague or ambiguous
  • Don’t assume context
  • Don’t ask multiple unrelated questions
  • Don’t use jargon without definition
  • Don’t expect perfection on first try

Summary

TechniqueUse Case
Zero-shotSimple, clear tasks
Few-shotPattern-based tasks
Chain-of-thoughtReasoning problems
Role promptingSpecialized expertise
Structured outputData extraction

Prompt engineering is an iterative process—test, refine, and improve your prompts for optimal results.

Advertisement

MR

Moshiour Rahman

Software Architect & AI Engineer

Share:
MR

Moshiour Rahman

Software Architect & AI Engineer

Enterprise software architect with deep expertise in financial systems, distributed architecture, and AI-powered applications. Building large-scale systems at Fortune 500 companies. Specializing in LLM orchestration, multi-agent systems, and cloud-native solutions. I share battle-tested patterns from real enterprise projects.

Related Articles

Comments

Comments are powered by GitHub Discussions.

Configure Giscus at giscus.app to enable comments.