Advanced Prompting for CrewAI Agents

Why Advanced Prompting Matters

The quality of your agent's output depends almost entirely on the quality of your prompt. Basic prompts produce basic results. Advanced prompting techniques — chain-of-thought, few-shot examples, role prompting, and structured output — dramatically improve accuracy, consistency, and usefulness.

Why this matters for your career:

  • Prompt engineering is one of the highest-value skills in the AI era
  • Good prompts can 10x the quality of agent outputs without changing any code
  • Advanced prompting techniques separate basic from professional agent implementations
  • These techniques transfer to any LLM application (ChatGPT, Claude, Gemini)

1. Chain of Thought (CoT)

Chain of Thought prompting asks the model to show its reasoning step by step before giving the final answer. This dramatically improves accuracy on complex tasks.

Without CoT

Agent: "Calculate the total cost of 3 nights camping at $45/night plus 8% tax."
Output: "$135.00"  ❌ Wrong (forgot tax)

With CoT

Agent: "Calculate the total cost of 3 nights camping at $45/night plus 8% tax.
Show your work step by step."

Output: |
Step 1: Base cost = 3 nights × $45 = $135
Step 2: Tax = $135 × 8% = $10.80
Step 3: Total = $135 + $10.80 = $145.80

Answer: $145.80

CoT in CrewAI

analyst = Agent(
    role='Financial Analyst',
    goal='Calculate camping trip costs accurately.',
    backstory='You are a meticulous financial analyst who always shows your work.',
    verbose=True
)

task = Task(
    description='''
    Calculate the total cost for a 3-night camping trip:
    - Campsite: $45/night for 3 nights
    - Equipment rental: $65 total
    - Park entrance fee: $30 per vehicle
    - Food and supplies: $120 total
    - Sales tax: 8% on campsite and equipment only
    
    Show your work step by step, then provide the final total.
    ''',
    agent=analyst
)

2. Few-Shot Prompting

Provide examples of the desired input/output format to guide the model.

classifier = Agent(
    role='Campsite Classifier',
    goal='Classify campsites into categories based on their description.',
    backstory='You are an expert at categorizing outdoor locations.',
    verbose=True
)

task = Task(
    description='''
    Classify each campsite into one of these categories:
    - RIVERSIDE: Near a river or creek
    - MOUNTAIN: High elevation, mountain views
    - FOREST: Surrounded by trees, shaded
    - LAKESIDE: On a lake shore
    - COASTAL: Near the ocean or coast
    
    Examples:
    1. "A peaceful spot next to a babbling brook with fishing opportunities."
       → RIVERSIDE
    2. "Panoramic views at 2000m elevation with hiking trails."
       → MOUNTAIN
    3. "Shaded campsite among old-growth redwoods."
       → FOREST
    4. "Camp on the sandy shore of a clear mountain lake."
       → LAKESIDE
    5. "Ocean views from your tent, steps from the beach."
       → COASTAL
    
    Now classify this campsite:
    "A shaded campground next to a mountain stream at 1500m elevation."
    ''',
    agent=classifier
)

3. Role Prompting

Assign a specific role with detailed context to shape the agent's behavior.

agent = Agent(
    role='Taiwan Camping Expert',
    goal='Provide expert camping recommendations across Taiwan.',
    backstory='''
    You have been camping in Taiwan for 20 years. You know every campground,
    every trail, and every hidden spot. You understand:
    - Taiwan's climate patterns by season
    - Road conditions and accessibility
    - Local regulations and permit requirements
    - What gear is appropriate for different elevations
    - Which campsites are best for families vs. solo adventurers
    
    You always consider:
    1. Safety first — weather, terrain, accessibility
    2. Seasonality — what's open and when
    3. Skill level — beginner vs. expert
    4. Amenities — water, toilets, fire pits
    ''',
    verbose=True
)

4. Structured Output

Force the agent to output in a specific format like JSON:

from pydantic import BaseModel
from typing import Literal, List

class CampsiteRecommendation(BaseModel):
    name: str
    difficulty: Literal['beginner', 'intermediate', 'expert']
    season: Literal['spring', 'summer', 'fall', 'winter', 'year-round']
    elevation: int
    amenities: List[str]
    reason: str

task = Task(
    description='''
    Recommend a campsite based on these requirements:
    - The user is a beginner camper
    - They want to go in July
    - They need water and toilet facilities
    - They prefer mountain views
    
    Output ONLY valid JSON matching this schema:
    {
      "name": "campsite name",
      "difficulty": "beginner",
      "season": "summer",
      "elevation": 1200,
      "amenities": ["water", "toilet"],
      "reason": "why this campsite fits"
    }
    
    Do NOT include any text outside the JSON.
    ''',
    expected_output='A JSON object matching the CampsiteRecommendation schema.',
    agent=expert
)

5. Constraint Enforcement

Explicitly state constraints to prevent common errors:

# Constraints: Define them clearly in the task description
task = Task(
    description='''
    Generate a camping itinerary.
    
    Constraints (MUST follow):
    1. Each day must include exactly one hiking activity
    2. Total budget must not exceed $500
    3. All campsites must be within Taiwan
    4. The itinerary must fit within 3 days
    5. Include meal plans for each day
    6. Account for travel time between locations
    7. Consider weather conditions for the season
    8. Provide a backup plan in case of rain
    
    Output format:
    Day 1: [Location] — [Activities] — [Meals] — [Campsite]
    Day 2: ...
    Day 3: ...
    Total Cost: $...
    ''',
    agent=planner
)

6. Prompt Chaining

Break a complex task into sequential steps, each handled by a different agent:

# Step 1: Research agent gathers options
research_task = Task(
    description='Find 5 campsites near Taroko Gorge open in summer.',
    agent=researcher
)

# Step 2: Planner creates an itinerary using research results
planning_task = Task(
    description='''
    Using the research results, create a 3-day itinerary.
    Consider travel time, weather, and user skill level.
    ''',
    agent=planner,
    context=[research_task]  # Pass research results as context
)

# Step 3: Writer formats the plan nicely
writing_task = Task(
    description='''
    Format the itinerary as a clean, readable document with
    sections, emoji headers, and a summary table.
    ''',
    agent=writer,
    context=[planning_task]
)

crew = Crew(
    agents=[researcher, planner, writer],
    tasks=[research_task, planning_task, writing_task],
    verbose=True
)

Prompting Best Practices

| Practice | Why | |----------|-----| | Be specific and detailed | Vague prompts → vague results | | Provide examples (few-shot) | Models learn from patterns better than instructions | | Show your work (CoT) | Step-by-step reasoning reduces errors | | Define output format explicitly | Consistent output = easier to parse | | State constraints upfront | Prevents common mistakes by default | | Use positive instructions | "Do this" works better than "Don't do that" | | Break complex tasks into steps | Each agent focuses on one thing | | Set a clear goal for each agent | The goal field in CrewAI is used in prompts | | Include context from previous tasks | Task chaining with context preserves information | | Test and iterate | Prompt quality improves with feedback cycles |

Summary

Advanced prompting techniques dramatically improve CrewAI agent outputs. Use chain-of-thought for complex reasoning, few-shot prompting for consistent formatting, role prompting for expert behavior, and structured output for parseable results. Prompt chaining breaks complex workflows into manageable steps.

Key takeaways:

  • Chain of Thought: "Show your work step by step" reduces reasoning errors
  • Few-shot prompting: Provide 3-5 examples of desired output format
  • Role prompting: Give the agent a detailed backstory and expertise statement
  • Structured output: Define the exact JSON schema for parseable results
  • Constraint enforcement: List constraints explicitly with bullet points
  • Prompt chaining: Break complex tasks across multiple agents with context passing
  • Positive instructions: "Do this" is more effective than "Don't do that"
  • Test and iterate: Prompt quality improves through testing and refinement

What's Next: Handling Hallucinations

The next chapter covers handling hallucinations in CrewAI agents — validation techniques, confidence scores, fact-checking, and graceful error handling.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!