← Back to DevBytes

Building a Marketing Agency with CrewAI: Complete Walkthrough

What Is a Marketing Agency Built with CrewAI?

CrewAI is an open-source Python framework designed to orchestrate autonomous AI agents that collaborate on complex tasks. In a marketing context, you can assemble a virtual agency where each agent plays a specialized role—strategist, copywriter, SEO analyst, social media manager, email marketer—and they work together through structured workflows. The framework handles agent communication, task delegation, and memory, allowing you to simulate a full-service marketing operation with minimal orchestration code.

Think of it as a multi-agent LLM system where you define roles, goals, backstories, and tools, then let the agents plan, execute, and refine marketing campaigns. CrewAI gives you the building blocks: Agent, Task, Crew, and Process. By composing these, you create an intelligent pipeline that can research audiences, generate ad copy, optimize content for search engines, and report on performance—all without switching between disconnected tools.

Why This Matters for Modern Marketing Teams

Traditional marketing workflows involve multiple human specialists handing off work across spreadsheets, docs, and chat. This introduces friction, delays, and inconsistent outputs. A CrewAI-powered agency automates the collaboration itself: agents pass structured data, critique each other's work, and iterate based on a shared goal. This unlocks several advantages:

Setting Up Your Development Environment

First, install CrewAI and its dependencies. You’ll need Python 3.10+ and an API key from a supported LLM provider (OpenAI, Anthropic, Azure, or local models via Ollama/LiteLLM). We’ll use OpenAI for this walkthrough, but the code adapts easily.

# Create and activate a virtual environment (recommended)
python -m venv marketing_agency_env
source marketing_agency_env/bin/activate  # On Windows: venv\Scripts\activate

# Install CrewAI with tools support
pip install crewai crewai-tools

Set your API key as an environment variable or directly in the script (not recommended for production):

import os
os.environ["OPENAI_API_KEY"] = "sk-..."   # Replace with your actual key
os.environ["OPENAI_MODEL_NAME"] = "gpt-4o"  # or gpt-3.5-turbo

Optionally, install additional tools like serpapi for Google search integration, or beautifulsoup4 for web scraping. These will be used later by our agents.

pip install serpapi beautifulsoup4 requests

Designing the Marketing Agency Structure

A realistic marketing agency needs several distinct roles. We’ll model the following agents:

These agents will be organized into a sequential workflow (one task’s output feeds the next). CrewAI supports sequential and hierarchical processes; we’ll start with sequential, then touch on hierarchical for advanced use cases.

Implementing Agents with CrewAI

Each agent is defined by its role, goal, backstory, and optional tools. The backstory influences the LLM’s persona and decision-making style. Below we create the core agents. Note that we import Agent from CrewAI and use crewai_tools for search capabilities.

from crewai import Agent
from crewai_tools import SerperDevTool, ScrapeWebsiteTool

# Shared tool instances
search_tool = SerperDevTool()          # Requires SERPER_API_KEY env var
scrape_tool = ScrapeWebsiteTool()      # Fetches and parses web pages

# 1. Market Researcher
researcher = Agent(
    role="Senior Market Research Analyst",
    goal="Uncover deep audience insights, competitor strategies, and market gaps for the given product.",
    backstory=(
        "You're a seasoned analyst at a top-tier marketing firm. "
        "You love finding patterns in messy data and always back your claims with sources. "
        "You're skeptical of assumptions and insist on evidence."
    ),
    tools=[search_tool, scrape_tool],
    verbose=True,
    allow_delegation=False
)

# 2. Campaign Strategist
strategist = Agent(
    role="Principal Campaign Strategist",
    goal="Synthesize research into a coherent, innovative campaign blueprint with messaging pillars, channel plan, and KPIs.",
    backstory=(
        "You are the strategic brain of the agency. You've launched campaigns for Fortune 500 brands. "
        "You structure plans clearly, prioritize high-impact channels, and always tie recommendations to business objectives."
    ),
    verbose=True,
    allow_delegation=False
)

# 3. Creative Copywriter
copywriter = Agent(
    role="Head of Creative & Copywriting",
    goal="Craft compelling, on-brand copy for ads, emails, landing pages, and social media based on the strategy brief.",
    backstory=(
        "A multi-award-winning copywriter with a knack for turning dry briefs into magnetic copy. "
        "You obsess over tone, hooks, and emotional triggers. You provide multiple variants per asset."
    ),
    verbose=True,
    allow_delegation=True  # Can delegate micro-tasks like generating subject lines
)

# 4. SEO & Content Specialist
seo_specialist = Agent(
    role="SEO and Content Optimization Expert",
    goal="Ensure all copy is search-engine friendly, includes target keywords naturally, and follows on-page SEO guidelines.",
    backstory=(
        "You live and breathe Google algorithms. You know how to weave keywords without sacrificing readability. "
        "You also optimize meta tags, URL slugs, and internal linking suggestions."
    ),
    tools=[search_tool],
    verbose=True,
    allow_delegation=False
)

# 5. Social Media Manager
social_media_manager = Agent(
    role="Social Media Distribution Lead",
    goal="Adapt campaign content into platform-specific posts, schedule them optimally, and maintain consistent voice.",
    backstory=(
        "You run social for major brands. You understand the nuances of Twitter/X, LinkedIn, Instagram, and TikTok. "
        "You always include hashtags, optimal post lengths, and engagement tactics."
    ),
    verbose=True,
    allow_delegation=False
)

# 6. Performance Analyst
analyst = Agent(
    role="Campaign Performance Analyst",
    goal="Analyze campaign results, identify underperforming assets, and recommend data-backed improvements.",
    backstory=(
        "A data scientist turned marketing analyst. You love dashboards, A/B test results, and ROI calculations. "
        "You're brutally honest about what works and what doesn't."
    ),
    tools=[search_tool, scrape_tool],
    verbose=True,
    allow_delegation=False
)

A few points: allow_delegation enables an agent to assign sub-tasks to other agents in hierarchical mode. verbose=True prints thought processes, helpful for debugging. Tools are passed as a list; the agent decides when to use them. For production, you can add custom tools for analytics APIs or CMS publishing.

Defining Tasks and Workflows

Tasks are the actionable units that agents execute. Each task has a description, expected output, and assigned agent. You can also define context dependencies: a task can receive the output of previous tasks, creating a chain. Here we’ll build a full campaign workflow for a hypothetical product: “EcoCharge – a portable solar-powered battery pack.”

from crewai import Task
from textwrap import dedent

# Helper to format multi-line prompts neatly
def make_task(description, expected_output, agent, context=None):
    return Task(
        description=dedent(description),
        expected_output=dedent(expected_output),
        agent=agent,
        context=context or []
    )

# Task 1: Market Research
research_task = make_task(
    description="""
        Conduct thorough research on the target market for EcoCharge, a portable solar battery pack.
        Identify:
        - Primary customer personas (demographics, pain points, motivations)
        - Top 3 competitors and their positioning, pricing, weaknesses
        - Current search trends and high-volume keywords around portable solar chargers
        - Any recent news or social sentiment related to sustainable tech
        Use trusted sources and provide citations.
    """,
    expected_output="""
        A structured research report with sections:
        1. Audience Personas (at least 2 detailed profiles)
        2. Competitive Landscape (with URLs)
        3. Keyword Opportunities (list with monthly search volumes if possible)
        4. Market Trends & Sentiment Summary
    """,
    agent=researcher
)

# Task 2: Campaign Strategy (uses research output)
strategy_task = make_task(
    description="""
        Using the provided research report, design a comprehensive marketing campaign for EcoCharge.
        Define:
        - Campaign name and overarching message
        - 3 key messaging pillars (e.g., sustainability, convenience, cost savings)
        - Recommended channels (organic social, paid search, influencer, email) with rationale
        - Primary KPIs and targets for a 4-week sprint
        - Any creative hooks or angles to differentiate from competitors
    """,
    expected_output="""
        A campaign strategy document (max 2 pages equivalent) containing:
        - Campaign Name & Tagline
        - Messaging Pillars (3, each with a one-line description)
        - Channel Plan with budget allocation suggestions (%)
        - KPIs (impressions, CTR, conversions, etc.)
        - Creative Hooks (at least 3)
    """,
    agent=strategist,
    context=[research_task]  # feeds the research output into this task
)

# Task 3: Copywriting (uses strategy output)
copywriting_task = make_task(
    description="""
        Based on the campaign strategy, produce copy for the following assets:
        - 3 Google Ads responsive search ads (headlines + descriptions)
        - 1 long-form landing page hero section (headline, subhead, CTA)
        - 2 email variants for a welcome series (subject line + body)
        - 3 social media posts (one each for LinkedIn, Instagram, Twitter/X)
        Maintain the campaign voice: friendly, aspirational, eco-conscious but not preachy.
        Include placeholders for [Product Name] and [Discount] where appropriate.
    """,
    expected_output="""
        A copy deck with clearly labeled sections:
        - Google Ads (3 sets, each with up to 15 headlines and 4 descriptions)
        - Landing Page Hero (headline, subhead, CTA button text)
        - Email Variants (Subject line + body, approx 100 words each)
        - Social Posts (platform-specific, with hashtags and character counts noted)
    """,
    agent=copywriter,
    context=[strategy_task]
)

# Task 4: SEO Optimization (uses copy output)
seo_task = make_task(
    description="""
        Take the copy deck and the keyword opportunities from the research, and:
        - Integrate primary and secondary keywords naturally into all assets
        - Ensure meta title and meta description recommendations for landing page
        - Check that headlines include high-value keywords
        - Suggest internal linking anchor text for the landing page (if part of a site)
        - Flag any keyword stuffing or awkward phrasing
    """,
    expected_output="""
        An optimized copy deck with:
        - Inline annotations showing keyword insertions
        - Meta title (max 60 chars) and meta description (max 155 chars) for landing page
        - Internal link suggestions
        - A brief note on any issues found and fixes applied
    """,
    agent=seo_specialist,
    context=[research_task, copywriting_task]  # needs both research (keywords) and copy
)

# Task 5: Social Media Adaptation & Scheduling Plan
social_task = make_task(
    description="""
        From the optimized copy deck, finalize social media posts for each platform with:
        - Platform-specific formatting (e.g., LinkedIn line breaks, Instagram hashtags)
        - Best posting times (assume US timezones, target audience behavior from research)
        - A 7-day posting schedule for launch week
        - Engagement prompts (questions, polls) for each post
        - Image/video content suggestions (e.g., lifestyle shot, product close-up)
    """,
    expected_output="""
        A social media calendar for 7 days containing:
        - Date, time, platform, post content, hashtags, media suggestion
        - At least 2 posts per day across platforms
        - Engagement strategy notes
    """,
    agent=social_media_manager,
    context=[seo_task, research_task]
)

# Task 6: Performance Analysis Simulation (runs after campaign "launch")
analyst_task = make_task(
    description="""
        Given the campaign plan and assets, simulate a post-launch performance analysis.
        Assume we have initial data:
        - Google Ads: 10K impressions, 250 clicks, 15 conversions (sign-ups)
        - Landing Page: 2K visits, 3.5% conversion rate
        - Emails: 25% open rate, 4% click-through
        - Social: 50K impressions, 1.2% engagement rate
        Identify top-performing assets, underperformers, and recommend 3 concrete optimizations for week 2.
    """,
    expected_output="""
        A performance report with:
        - Executive summary (3 bullet takeaways)
        - Channel-by-channel breakdown (metrics vs targets)
        - Top 3 recommendations (e.g., pause underperforming ad, test new subject line)
        - Suggested A/B tests for week 2
    """,
    agent=analyst,
    context=[strategy_task, social_task, copywriting_task]
)

The context parameter creates a sequential dependency chain: research → strategy → copy → SEO → social → analysis. CrewAI automatically passes the previous task’s raw output (or a summary) into the next agent’s prompt context. This simulates real-world handoffs.

Assembling the Crew and Running the Agency

Now we instantiate a Crew object, passing all agents and tasks. We set process=Process.sequential to enforce the order we defined. (For hierarchical, you’d use Process.hierarchical and a manager LLM would dynamically assign tasks.)

from crewai import Crew, Process

marketing_crew = Crew(
    agents=[
        researcher,
        strategist,
        copywriter,
        seo_specialist,
        social_media_manager,
        analyst
    ],
    tasks=[
        research_task,
        strategy_task,
        copywriting_task,
        seo_task,
        social_task,
        analyst_task
    ],
    process=Process.sequential,  # tasks executed in order of the list
    verbose=True,               # shows agent reasoning and outputs
    memory=True                 # enables short-term memory across tasks
)

# Kick off the agency for our product
result = marketing_crew.kickoff()

print("\n================ FINAL CAMPAIGN OUTPUT ================")
print(result)

The kickoff() method runs the entire pipeline and returns the final task’s output as a string (the performance report in our case). You can also access intermediate results via the crew’s tasks_output attribute or by enabling callbacks. With verbose=True, you’ll see each agent’s thought process, tool usage, and final response in the console—invaluable for debugging.

Integrating Tools for Enhanced Capabilities

The power of CrewAI multiplies when agents can fetch live data. We used SerperDevTool (Google search) and ScrapeWebsiteTool out of the box. You can also define custom tools. For example, a tool that fetches real-time keyword data from an API like SEMrush or Google Trends, or a tool that posts to a social media scheduler via API. Below is a minimal custom tool that simulates checking brand sentiment using a mock function—you’d replace it with a real API call.

from crewai_tools import tool

@tool("SentimentAnalyzer")
def sentiment_analyzer(query: str) -> str:
    """
    Analyzes brand or keyword sentiment across recent news/social mentions.
    Input: a search query string (e.g., 'EcoCharge portable solar reviews').
    Output: a structured sentiment summary with positive/negative/neutral percentages and key themes.
    """
    # Replace with actual API call (e.g., NewsAPI, Brand24, or custom scraper)
    # Mock response for demonstration
    mock_data = {
        "positive": 65,
        "negative": 10,
        "neutral": 25,
        "key_themes": ["eco-friendly", "charging speed", "durability concerns"],
        "sample_quote": "Love the concept but wish it charged faster."
    }
    return (
        f"Sentiment Analysis for '{query}':\n"
        f"Positive: {mock_data['positive']}%, Negative: {mock_data['negative']}%, Neutral: {mock_data['neutral']}%\n"
        f"Key Themes: {', '.join(mock_data['key_themes'])}\n"
        f"Sample: \"{mock_data['sample_quote']}\""
    )

# Assign this tool to the researcher or analyst
researcher.tools.append(sentiment_analyzer)  # Alternatively, pass directly in Agent init

Tools are invoked automatically when the agent’s LLM decides they’re needed. The framework handles the tool execution and feeds results back into the agent’s context window.

Best Practices for Production-Grade Marketing AI Agents

Scaling to a Hierarchical Agency (Advanced)

When tasks become highly dynamic—e.g., handling dozens of simultaneous client campaigns—a sequential process may be too rigid. CrewAI supports Process.hierarchical, where a manager agent (typically an LLM with delegation capabilities) dynamically assigns tasks to specialist agents. This mimics a real agency’s traffic manager. To enable it, set process=Process.hierarchical and designate one agent (often the strategist or a dedicated manager) with allow_delegation=True. The manager will spawn sub-tasks and route them. This requires a more powerful model (gpt-4o or equivalent) because the manager needs to plan and coordinate.

# Example of a hierarchical crew
hierarchical_crew = Crew(
    agents=[strategist, copywriter, seo_specialist, social_media_manager],
    tasks=[],  # tasks are created dynamically by manager
    process=Process.hierarchical,
    manager_llm=ChatOpenAI(model="gpt-4o"),
    verbose=True
)
# You'd feed an initial high-level goal, and the manager breaks it down.

This approach works best when you have unpredictable workflows—e.g., a client requests a “complete rebrand” and you want the AI to figure out the steps. For most campaign generation pipelines, sequential with context is sufficient and more predictable.

Conclusion

Building a marketing agency with CrewAI turns a multi-step, collaborative creative process into an automated, reliable pipeline. You define specialized agents, give them tools to interact with real-world data, and structure tasks that pass insights like a relay race. The result is a system that can research audiences, strategize, write SEO-optimized copy, schedule social posts, and analyze performance—all with minimal human intervention beyond initial goal setting and final approval.

Start small: model a single campaign workflow sequentially, then expand to hierarchical when you need dynamic delegation. Invest time in crafting agent backstories and task descriptions; they are the steering wheel for the AI’s behavior. As you grow, layer on Pydantic validation, human-in-the-loop checkpoints, and monitoring to transform your prototype into a production-grade virtual agency that rivals a human team’s output—at a fraction of the cost and turnaround time.

— Ad —

Google AdSense will appear here after approval

← Back to all articles