Introduction
Imagine having a team of specialized AI agents working together to create professional blog posts, complete with research, writing, editing, and SEO optimization. This is not science fiction but the reality of Agentic AI systems. In this tutorial, we will build a sophisticated content creation agency powered by CrewAI, where multiple AI agents collaborate like a real editorial team to produce high-quality articles.
Traditional AI applications typically involve a single model responding to prompts. Agentic AI systems, however, orchestrate multiple specialized agents that work together, delegate tasks, share information, and collectively solve complex problems. Think of it as the difference between hiring a single freelancer versus assembling a complete editorial team with researchers, writers, editors, and SEO specialists.
Our running example will be a Content Creation Agency that takes a topic and produces a complete, publication-ready blog post. The system will feature four specialized agents: a Research Agent that gathers information, a Writer Agent that crafts the initial draft, an Editor Agent that refines the content, and an SEO Specialist Agent that optimizes for search engines. This mirrors how professional content teams actually work, making it both practical and educational.
Understanding Agentic AI Systems
Before diving into code, we need to understand what makes Agentic AI different from traditional AI applications. An agent is an autonomous entity that can perceive its environment, make decisions, and take actions to achieve specific goals. In the context of AI, agents are language models equipped with tools, memory, and the ability to reason about tasks.
The key characteristics of agentic systems include autonomy, where agents can operate independently without constant human intervention. They possess reactivity, allowing them to respond to changes in their environment. Proactivity enables them to take initiative to achieve goals rather than simply responding to requests. Finally, social ability lets them communicate and collaborate with other agents, sharing information and coordinating their efforts.
CrewAI is a framework specifically designed for orchestrating multiple AI agents. It provides abstractions for defining agents with specific roles, creating tasks for those agents, and managing the flow of information between them. Unlike single-agent systems, CrewAI enables agents to work together in crews, sharing context and building upon each other's work. This collaborative approach mirrors how human teams function, with each member contributing their specialized expertise to a common goal.
The framework handles the complexity of inter-agent communication, task sequencing, and context management. When you define a crew, you specify which agents are involved and what tasks they need to accomplish. CrewAI then orchestrates the execution, ensuring that each agent receives the information it needs from previous agents and that the overall workflow proceeds smoothly.
Setting Up Your Development Environment
The first step in building our content creation agency is setting up a proper development environment that supports various hardware configurations. Modern AI development requires flexibility in terms of GPU support, as developers work with different hardware from NVIDIA CUDA to AMD ROCm, Intel GPUs, and Apple's Metal Performance Shaders.
We will start by creating a new Python project and installing the necessary dependencies. The beauty of our approach is that it will work whether you are running on a high-end NVIDIA GPU, an AMD graphics card, an Intel Arc GPU, or Apple Silicon with MPS acceleration. We will also support running models remotely via APIs for those without local GPU resources.
Create a new directory for your project and set up a virtual environment. Open your terminal and execute the following commands:
mkdir content-creation-agency
cd content-creation-agency
python -m venv venv
source venv/bin/activate
On Windows systems, you would use a slightly different activation command. Instead of the source command, you would run venv\Scripts\activate. This creates an isolated Python environment where we can install our dependencies without affecting your system Python installation.
Now we need to install the core dependencies. CrewAI will be our orchestration framework, and we will use LangChain as the underlying framework for agent interactions. For local LLM support, we will use llama-cpp-python, which provides excellent cross-platform GPU acceleration:
pip install crewai crewai-tools langchain langchain-community
pip install llama-cpp-python
pip install openai anthropic
pip install python-dotenv pydantic requests beautifulsoup4
The llama-cpp-python library automatically detects and uses available GPU acceleration. For NVIDIA GPUs, it uses CUDA. For AMD graphics cards, it uses ROCm. For Intel GPUs, it uses oneAPI. For Apple Silicon, it uses Metal. This makes our system truly hardware-agnostic, adapting to whatever hardware you have available.
The other dependencies serve specific purposes. The openai and anthropic packages allow us to connect to remote API services when local execution is not desired or feasible. The python-dotenv package helps us manage environment variables and API keys securely. Pydantic provides data validation and settings management. The requests and beautifulsoup4 libraries will be used by our agents to gather information from the web.
Creating the Configuration System
Let us create a configuration system that allows users to choose between local and remote models. We will use environment variables and a configuration class to manage this flexibility. This approach separates configuration from code, making our system adaptable to different deployment scenarios without code changes.
Start by creating a file named config.py in your project directory. This file will contain all the configuration logic:
# config.py
import os
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
from dotenv import load_dotenv
load_dotenv()
class ModelProvider(str, Enum):
"""Enumeration of supported model providers"""
LOCAL = "local"
OPENAI = "openai"
ANTHROPIC = "anthropic"
OLLAMA = "ollama"
class GPUBackend(str, Enum):
"""Enumeration of supported GPU backends"""
CUDA = "cuda"
ROCM = "rocm"
METAL = "metal"
ONEAPI = "oneapi"
CPU = "cpu"
These enumerations define the valid options for model providers and GPU backends. Using enumerations rather than plain strings provides type safety and prevents configuration errors. If someone tries to specify an invalid provider, Python will raise an error immediately rather than failing later during execution.
The ModelProvider enumeration includes four options. LOCAL means we will run a model directly on the machine using llama-cpp-python. OPENAI connects to OpenAI's API services. ANTHROPIC uses Claude models from Anthropic. OLLAMA connects to a local Ollama server, which is useful for developers who want local execution but prefer Ollama's model management.
The GPUBackend enumeration covers all major GPU acceleration frameworks. CUDA is for NVIDIA graphics cards. ROCM supports AMD GPUs. METAL is for Apple Silicon. ONEAPI works with Intel GPUs. CPU is the fallback when no GPU acceleration is available.
Now let us create the main configuration class:
class ModelConfig(BaseModel):
"""Configuration for language model selection and parameters"""
provider: ModelProvider = Field(
default=ModelProvider.LOCAL,
description="The model provider to use"
)
model_name: str = Field(
default="mistral-7b-instruct",
description="Name of the model to use"
)
temperature: float = Field(
default=0.7,
ge=0.0,
le=2.0,
description="Sampling temperature for generation"
)
max_tokens: int = Field(
default=2048,
gt=0,
description="Maximum tokens to generate"
)
gpu_backend: Optional[GPUBackend] = Field(
default=None,
description="GPU backend for local models"
)
api_key: Optional[str] = Field(
default=None,
description="API key for remote providers"
)
model_path: Optional[str] = Field(
default=None,
description="Path to local model file"
)
This configuration class uses Pydantic for validation and type safety. Each field has a type annotation, a default value, and constraints. The temperature field, for example, must be between zero and two. The max_tokens field must be greater than zero. These constraints ensure that configuration values are always valid.
The Field function provides additional metadata for each configuration parameter. The description helps developers understand what each parameter does. The ge parameter means greater than or equal, while gt means greater than. These validation rules prevent common configuration mistakes.
Notice that some fields are Optional, meaning they can be None. The gpu_backend field is optional because we can auto-detect it. The api_key is optional because it might come from environment variables. The model_path is only needed for local models.
Now we add initialization logic that handles defaults and auto-detection:
def __init__(self, **data):
super().__init__(**data)
if self.provider == ModelProvider.LOCAL and self.gpu_backend is None:
self.gpu_backend = self._detect_gpu_backend()
if self.provider == ModelProvider.OPENAI and self.api_key is None:
self.api_key = os.getenv("OPENAI_API_KEY")
elif self.provider == ModelProvider.ANTHROPIC and self.api_key is None:
self.api_key = os.getenv("ANTHROPIC_API_KEY")
@staticmethod
def _detect_gpu_backend() -> GPUBackend:
"""Automatically detect available GPU backend"""
try:
import torch
if torch.cuda.is_available():
return GPUBackend.CUDA
elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
return GPUBackend.METAL
except ImportError:
pass
if os.path.exists('/opt/rocm'):
return GPUBackend.ROCM
if os.getenv('ONEAPI_ROOT'):
return GPUBackend.ONEAPI
return GPUBackend.CPU
The initialization method performs smart defaults. If the user chooses a local provider but does not specify a GPU backend, we automatically detect what hardware is available. This makes the system user-friendly because developers do not need to know the technical details of their GPU setup.
The GPU detection logic tries multiple approaches. First, it attempts to import PyTorch and check for CUDA or MPS availability. PyTorch provides reliable GPU detection for these backends. If PyTorch is not installed, we fall back to checking for ROCm and oneAPI installations by looking for their characteristic directories and environment variables.
For API keys, we check environment variables if the user did not provide them directly. This follows security best practices by keeping sensitive credentials out of code. Developers can create a .env file in their project directory with their API keys, and the load_dotenv function will load them automatically.
Building the Model Factory
With our configuration system in place, we need a factory pattern to instantiate the appropriate language model based on the configuration. This factory will handle the complexity of initializing different model types while presenting a uniform interface to the rest of our application.
Create a new file named model_factory.py. This file will contain the logic for creating model instances:
# model_factory.py
from typing import Union
from langchain.llms.base import BaseLLM
from langchain_community.llms import LlamaCpp, Ollama
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from config import ModelConfig, ModelProvider, GPUBackend
class ModelFactory:
"""Factory for creating language model instances based on configuration"""
@staticmethod
def create_model(config: ModelConfig) -> BaseLLM:
"""Create and configure a language model instance"""
if config.provider == ModelProvider.LOCAL:
return ModelFactory._create_local_model(config)
elif config.provider == ModelProvider.OPENAI:
return ModelFactory._create_openai_model(config)
elif config.provider == ModelProvider.ANTHROPIC:
return ModelFactory._create_anthropic_model(config)
elif config.provider == ModelProvider.OLLAMA:
return ModelFactory._create_ollama_model(config)
else:
raise ValueError(f"Unsupported model provider: {config.provider}")
The factory pattern is particularly useful here because it encapsulates the logic for creating different types of models. The create_model method is the public interface. It examines the configuration and delegates to the appropriate private method. This separation of concerns makes the code easier to maintain and extend.
Each provider requires different initialization parameters and different LangChain classes. By hiding these details inside the factory, we keep the rest of our application clean. The agents and tasks do not need to know whether they are using a local model or a remote API. They just receive a BaseLLM instance that works the same way regardless of the underlying implementation.
Let us look at how we create local models with GPU acceleration:
@staticmethod
def _create_local_model(config: ModelConfig) -> LlamaCpp:
"""Create a local model using llama-cpp-python with GPU acceleration"""
if config.model_path is None:
raise ValueError("model_path must be specified for local models")
n_gpu_layers = ModelFactory._get_gpu_layers(config.gpu_backend)
model_params = {
"model_path": config.model_path,
"temperature": config.temperature,
"max_tokens": config.max_tokens,
"n_gpu_layers": n_gpu_layers,
"n_ctx": 4096,
"n_batch": 512,
"verbose": False,
}
if config.gpu_backend == GPUBackend.METAL:
model_params["n_gpu_layers"] = 1
model_params["f16_kv"] = True
elif config.gpu_backend == GPUBackend.CUDA:
model_params["n_gpu_layers"] = -1
elif config.gpu_backend == GPUBackend.ROCM:
model_params["n_gpu_layers"] = -1
return LlamaCpp(**model_params)
Creating a local model involves several important parameters. The model_path points to the GGUF format model file on disk. The n_gpu_layers parameter controls how many transformer layers are offloaded to the GPU. Setting this to negative one means all layers go to the GPU for maximum acceleration.
The n_ctx parameter sets the context window size, which determines how much text the model can process at once. We use 4096 tokens, which is a good balance between capability and memory usage. The n_batch parameter controls how many tokens are processed in parallel during prompt evaluation, affecting speed.
Different GPU backends require different configurations. Apple's Metal Performance Shaders handle layer offloading differently than CUDA, so we set n_gpu_layers to 1 for Metal. We also enable f16_kv, which uses 16-bit floating point precision for the key-value cache, reducing memory usage on Apple Silicon.
For NVIDIA CUDA and AMD ROCm, we set n_gpu_layers to negative one, which tells llama-cpp-python to offload all layers to the GPU. This provides maximum performance on these platforms.
Now let us look at creating remote API models:
@staticmethod
def _create_openai_model(config: ModelConfig) -> ChatOpenAI:
"""Create an OpenAI model instance"""
if config.api_key is None:
raise ValueError("API key must be provided for OpenAI models")
return ChatOpenAI(
model_name=config.model_name,
temperature=config.temperature,
max_tokens=config.max_tokens,
openai_api_key=config.api_key
)
@staticmethod
def _create_anthropic_model(config: ModelConfig) -> ChatAnthropic:
"""Create an Anthropic Claude model instance"""
if config.api_key is None:
raise ValueError("API key must be provided for Anthropic models")
return ChatAnthropic(
model=config.model_name,
temperature=config.temperature,
max_tokens=config.max_tokens,
anthropic_api_key=config.api_key
)
Creating remote API models is simpler because the complexity is handled by the API provider. We just need to pass the API key and generation parameters. The LangChain wrappers handle all the HTTP communication, error handling, and response parsing.
Notice that we validate the API key is present before attempting to create the model. This fail-fast approach catches configuration errors immediately rather than waiting until the first API call fails.
The helper method for determining GPU layers encapsulates the backend-specific logic:
@staticmethod
def _get_gpu_layers(backend: GPUBackend) -> int:
"""Determine optimal number of GPU layers based on backend"""
if backend == GPUBackend.CPU:
return 0
elif backend == GPUBackend.METAL:
return 1
else:
return -1
This method returns zero for CPU-only execution, one for Metal, and negative one for full GPU offloading on other backends. By centralizing this logic, we ensure consistency across the codebase.
Defining Specialized Agents
Now we arrive at the heart of our agentic system: defining the specialized agents that will work together to create content. Each agent in our crew has a specific role, expertise, and set of responsibilities. This specialization allows agents to focus on what they do best, just like members of a real content team.
Create a new file named agents.py. This file will contain our agent definitions:
# agents.py
from crewai import Agent
from langchain.llms.base import BaseLLM
class ContentCreationAgents:
"""Factory class for creating specialized content creation agents"""
def __init__(self, llm: BaseLLM):
"""Initialize the agent factory with a language model"""
self.llm = llm
We use a factory class pattern here as well. The ContentCreationAgents class holds a reference to the language model and provides methods for creating each type of agent. This keeps agent creation logic organized and makes it easy to create multiple agents with the same underlying model.
Let us start by creating the Research Agent. This agent is responsible for gathering information about the topic, finding relevant facts, statistics, and expert opinions:
def create_research_agent(self) -> Agent:
"""Create a research agent specialized in gathering information"""
return Agent(
role="Senior Research Analyst",
goal="Conduct comprehensive research on the given topic and gather "
"accurate, relevant, and up-to-date information from credible sources",
backstory="You are an experienced research analyst with a background in "
"investigative journalism and academic research. You have spent "
"over a decade honing your skills in finding reliable information, "
"fact-checking, and synthesizing complex topics into clear insights. "
"Your expertise lies in identifying authoritative sources, extracting "
"key data points, and understanding the nuances of various subjects. "
"You take pride in the accuracy and depth of your research, never "
"settling for surface-level information.",
verbose=True,
allow_delegation=False,
llm=self.llm
)
Each agent definition contains several critical components. The role describes what the agent is, creating an identity that influences how it approaches tasks. Think of the role as the agent's job title. It sets expectations for what kind of work this agent does.
The goal specifies what the agent is trying to achieve. This provides direction for the agent's decision-making process. When the agent is working on a task, it keeps this goal in mind, shaping how it interprets instructions and what outputs it produces.
The backstory is particularly powerful because it gives the agent context and expertise. This is essentially creating a persona that shapes how the agent responds. By giving the Research Agent a background in investigative journalism and academic research, we prime it to approach tasks with thoroughness and attention to credibility.
The verbose parameter controls whether the agent prints its thought process during execution. Setting this to True is helpful during development because you can see what the agent is thinking and doing. In production, you might set it to False for cleaner output.
The allow_delegation parameter determines whether the agent can delegate tasks to other agents. We set this to False because our workflow is sequential. Each agent has a specific job to do in order, so delegation is not necessary.
Now let us create the Writer Agent, which transforms research findings into compelling prose:
def create_writer_agent(self) -> Agent:
"""Create a writer agent specialized in crafting engaging content"""
return Agent(
role="Expert Content Writer",
goal="Transform research findings into compelling, well-structured "
"articles that engage readers and communicate ideas clearly",
backstory="You are a seasoned content writer with fifteen years of "
"experience creating articles for major publications. Your "
"writing style is clear, engaging, and accessible. You excel "
"at taking complex information and making it understandable "
"without dumbing it down. You understand narrative structure, "
"pacing, and how to keep readers engaged from the first "
"sentence to the last. You have a talent for finding the "
"perfect examples and analogies to illustrate complex concepts.",
verbose=True,
allow_delegation=False,
llm=self.llm
)
The Writer Agent has a different persona than the Research Agent. While the researcher focuses on accuracy and thoroughness, the writer focuses on clarity and engagement. This specialization is key to the agentic approach. Each agent brings different strengths to the table.
Notice how the backstory emphasizes communication skills and the ability to make complex topics accessible. This primes the agent to produce content that is not just accurate but also readable and engaging. The mention of narrative structure and pacing guides the agent toward well-organized writing.
The Editor Agent comes next in our pipeline. After the Writer Agent produces a draft, the Editor Agent reviews it with a critical eye:
def create_editor_agent(self) -> Agent:
"""Create an editor agent specialized in refining content"""
return Agent(
role="Senior Content Editor",
goal="Review and refine written content to ensure clarity, coherence, "
"grammatical correctness, and stylistic excellence",
backstory="You are a meticulous editor with a sharp eye for detail and "
"a deep understanding of language. With twenty years of editorial "
"experience at top-tier publications, you have developed an "
"instinct for what makes writing great. You catch grammatical "
"errors, awkward phrasing, logical inconsistencies, and structural "
"problems. You improve clarity without changing the author's voice. "
"You ensure every sentence serves a purpose and every paragraph "
"flows naturally into the next.",
verbose=True,
allow_delegation=False,
llm=self.llm
)
The Editor Agent's backstory emphasizes attention to detail and quality. This agent is the quality gatekeeper, ensuring that the content meets professional standards. The mention of preserving the author's voice is important because we want the editor to improve the writing without completely rewriting it.
Finally, we create the SEO Specialist Agent, which optimizes content for search engines:
def create_seo_agent(self) -> Agent:
"""Create an SEO specialist agent for optimizing content"""
return Agent(
role="SEO Optimization Specialist",
goal="Optimize content for search engines while maintaining readability "
"and user engagement, ensuring the article ranks well and attracts "
"organic traffic",
backstory="You are an SEO expert with deep knowledge of search engine "
"algorithms, keyword research, and content optimization strategies. "
"You have helped hundreds of articles achieve top rankings in "
"search results. You understand how to naturally incorporate "
"keywords, optimize meta descriptions, create compelling titles, "
"and structure content for both search engines and human readers. "
"You know that the best SEO serves the user first and the algorithm "
"second.",
verbose=True,
allow_delegation=False,
llm=self.llm
)
The SEO Specialist has expertise in search engine optimization. This agent knows how to make content discoverable without sacrificing quality. The backstory emphasizes the balance between optimization and readability, ensuring that SEO improvements do not make the content feel artificial or keyword-stuffed.
Together, these four agents form a complete content creation pipeline. Each agent has a clear role and expertise, and they work in sequence to produce high-quality, optimized articles.
Creating Tasks for the Agents
Agents need tasks to work on. While agents define who is doing the work, tasks define what work needs to be done. In CrewAI, tasks are explicit instructions given to agents, complete with descriptions, expected outputs, and context.
Create a new file named tasks.py for our task definitions:
# tasks.py
from crewai import Task
from agents import ContentCreationAgents
class ContentCreationTasks:
"""Factory class for creating content creation tasks"""
def __init__(self, agents: ContentCreationAgents):
"""Initialize with agent factory"""
self.research_agent = agents.create_research_agent()
self.writer_agent = agents.create_writer_agent()
self.editor_agent = agents.create_editor_agent()
self.seo_agent = agents.create_seo_agent()
The ContentCreationTasks class creates all the agents it needs during initialization. This ensures that the same agent instances are used consistently across all tasks. We create one instance of each agent type and reuse them for all the tasks we define.
Now let us create the research task:
def create_research_task(self, topic: str) -> Task:
"""Create a task for researching the given topic"""
return Task(
description=f"""Conduct comprehensive research on the topic: {topic}
Your research should include:
- Key facts and statistics about the topic
- Current trends and recent developments
- Expert opinions and authoritative perspectives
- Common questions and misconceptions
- Relevant examples and case studies
Focus on finding credible, up-to-date information from authoritative sources.
Organize your findings in a clear, structured format that will be useful
for a writer creating an article on this topic.
Your output should be a detailed research report covering all important
aspects of the topic.""",
agent=self.research_agent,
expected_output="A comprehensive research report with facts, statistics, "
"trends, expert opinions, and relevant examples organized "
"in a clear structure"
)
The Task object contains three main components. The description is the detailed instruction given to the agent. This is where we specify exactly what we want the agent to do. Notice how we provide specific bullet points about what the research should include. This level of detail helps guide the agent toward producing useful output.
The agent parameter assigns this task to a specific agent. In this case, we assign it to the research_agent. This creates the connection between the task and the agent who will execute it.
The expected_output parameter describes what the task should produce. This helps the agent understand what format and level of detail is required. It also helps CrewAI validate that the task was completed successfully.
The topic parameter is passed into the task description using an f-string. This makes our tasks reusable. We can create research tasks for any topic by passing different values to this method.
Now let us create the writing task:
def create_writing_task(self, topic: str, research_task: Task) -> Task:
"""Create a task for writing an article based on research"""
return Task(
description=f"""Using the research findings, write a comprehensive,
engaging article on the topic: {topic}
Your article should:
- Have a compelling introduction that hooks the reader
- Present information in a logical, well-structured flow
- Use clear, accessible language appropriate for a general audience
- Include relevant examples and explanations
- Maintain reader engagement throughout
- Conclude with a strong summary or call to action
Aim for an article length of 1500-2000 words. Write in a professional
yet conversational tone. Make complex ideas accessible without
oversimplifying them.
Base your article on the research findings provided, but transform
the information into engaging narrative prose rather than simply
listing facts.""",
agent=self.writer_agent,
expected_output="A well-written, engaging article of 1500-2000 words "
"with clear structure, compelling narrative, and "
"accessible explanations",
context=[research_task]
)
The writing task introduces a new concept: context. The context parameter is a list of other tasks whose outputs this task depends on. By including research_task in the context, we tell CrewAI that the writing task needs the output from the research task.
This creates a dependency chain. CrewAI will ensure that the research task completes before the writing task begins. When the writer agent starts working, it will have access to the research findings produced by the research agent.
This context mechanism is how information flows between agents in CrewAI. Each agent builds upon the work of previous agents, creating a collaborative workflow.
The editing task follows a similar pattern:
def create_editing_task(self, writing_task: Task) -> Task:
"""Create a task for editing the written article"""
return Task(
description="""Review and refine the written article to ensure
the highest quality.
Your editing should address:
- Grammar, spelling, and punctuation errors
- Sentence structure and clarity
- Paragraph flow and transitions
- Logical consistency and coherence
- Tone and style consistency
- Removal of redundancy and wordiness
Improve the writing while preserving the author's voice and intent.
Ensure every sentence is clear and every paragraph serves a purpose.
The final article should read smoothly from beginning to end.
Provide the edited version of the complete article.""",
agent=self.editor_agent,
expected_output="A polished, error-free article with improved clarity, "
"flow, and coherence",
context=[writing_task]
)
The editing task depends on the writing task through its context parameter. The editor agent receives the draft article from the writer agent and refines it. Notice how the description focuses on improvement rather than rewriting. We want the editor to enhance the existing work, not start from scratch.
Finally, the SEO optimization task:
def create_seo_task(self, topic: str, editing_task: Task) -> Task:
"""Create a task for SEO optimization"""
return Task(
description=f"""Optimize the edited article for search engines while
maintaining readability and user engagement.
Your optimization should include:
- A compelling, SEO-friendly title incorporating the main keyword: {topic}
- A meta description that encourages clicks from search results
- Natural incorporation of relevant keywords throughout the article
- Proper heading structure (H1, H2, H3) for both readability and SEO
- Suggestions for internal and external linking opportunities
Ensure that all SEO improvements feel natural and do not compromise
the quality or readability of the content. The article should serve
human readers first while also being discoverable by search engines.
Provide the final, SEO-optimized version of the article along with
the title and meta description.""",
agent=self.seo_agent,
expected_output="A complete, SEO-optimized article with title, meta "
"description, proper heading structure, and natural "
"keyword integration",
context=[editing_task]
)
The SEO task is the final step in our pipeline. It depends on the editing task, ensuring that SEO optimization happens after the content has been refined. The SEO agent receives a polished article and adds the final touches that make it discoverable in search engines.
Notice how we pass the topic parameter to this task as well. The SEO agent needs to know the main keyword to optimize for, so we provide it explicitly.
Assembling the Crew
Now that we have defined our agents and tasks, we need to assemble them into a crew. The crew is the orchestration layer that manages the execution of tasks and the flow of information between agents.
Create a new file named crew.py:
# crew.py
from crewai import Crew, Process
from langchain.llms.base import BaseLLM
from agents import ContentCreationAgents
from tasks import ContentCreationTasks
class ContentCreationCrew:
"""Orchestrates the content creation process using multiple specialized agents"""
def __init__(self, llm: BaseLLM):
"""Initialize the crew with a language model"""
self.llm = llm
self.agents = ContentCreationAgents(llm)
self.task_factory = ContentCreationTasks(self.agents)
The ContentCreationCrew class brings everything together. It holds references to the language model, the agent factory, and the task factory. This organization keeps our code clean and modular.
Now let us create the method that runs the content creation process:
def create_article(self, topic: str) -> str:
"""
Create a complete article on the given topic using the agent crew.
Args:
topic: The topic to write about
Returns:
The final, SEO-optimized article
"""
research_task = self.task_factory.create_research_task(topic)
writing_task = self.task_factory.create_writing_task(topic, research_task)
editing_task = self.task_factory.create_editing_task(writing_task)
seo_task = self.task_factory.create_seo_task(topic, editing_task)
crew = Crew(
agents=[
self.agents.create_research_agent(),
self.agents.create_writer_agent(),
self.agents.create_editor_agent(),
self.agents.create_seo_agent()
],
tasks=[research_task, writing_task, editing_task, seo_task],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
return result
The create_article method orchestrates the entire content creation process. It starts by creating all four tasks, passing the topic and establishing the dependency chain through context parameters.
Then it creates a Crew object. The agents parameter lists all the agents involved in the crew. The tasks parameter lists all the tasks to be executed. The order of tasks in this list matters when using sequential processing.
The process parameter specifies how tasks should be executed. Process.sequential means tasks run one after another in order. CrewAI also supports hierarchical processes where agents can delegate to each other, but sequential is appropriate for our linear workflow.
The verbose parameter controls output verbosity. Setting it to True shows detailed information about what each agent is doing, which is helpful for understanding and debugging the system.
Finally, we call crew.kickoff() to start the execution. This method runs all the tasks in order, managing the flow of information between agents. It returns the output of the final task, which in our case is the SEO-optimized article.
Creating Tools for Web Research
Our agents would be more powerful if they could actually search the web for information rather than relying solely on their training data. CrewAI supports equipping agents with tools that extend their capabilities. Let us create a simple web search tool.
Create a new file named tools.py:
# tools.py
from crewai_tools import tool
import requests
from bs4 import BeautifulSoup
from typing import List
@tool("Web Search Tool")
def web_search(query: str) -> str:
"""
Search the web for information on a given query.
Args:
query: The search query
Returns:
Relevant information found on the web
"""
try:
search_url = f"https://html.duckduckgo.com/html/?q={query}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get(search_url, headers=headers, timeout=10)
if response.status_code != 200:
return f"Search failed with status code {response.status_code}"
soup = BeautifulSoup(response.content, 'html.parser')
results = []
for result in soup.find_all('div', class_='result')[:5]:
title_elem = result.find('a', class_='result__a')
snippet_elem = result.find('a', class_='result__snippet')
if title_elem and snippet_elem:
title = title_elem.get_text(strip=True)
snippet = snippet_elem.get_text(strip=True)
results.append(f"{title}: {snippet}")
if not results:
return "No results found"
return "\n\n".join(results)
except Exception as e:
return f"Error performing web search: {str(e)}"
The tool decorator from CrewAI marks this function as a tool that agents can use. The decorator takes a name parameter that identifies the tool to agents. When an agent needs to search the web, it can invoke this tool by name.
The function uses DuckDuckGo's HTML interface for searching because it does not require an API key. We send a request with a user agent header to avoid being blocked. The BeautifulSoup library parses the HTML response and extracts search results.
We limit the results to the top five to keep the output manageable. Each result includes a title and snippet, giving the agent enough context to understand what information is available.
Error handling is important for tools because network requests can fail. If something goes wrong, we return an error message rather than crashing. This allows the agent to handle failures gracefully.
Now let us update our research agent to use this tool:
# agents.py (updated)
from tools import web_search
class ContentCreationAgents:
def __init__(self, llm: BaseLLM):
self.llm = llm
def create_research_agent(self) -> Agent:
"""Create a research agent with web search capability"""
return Agent(
role="Senior Research Analyst",
goal="Conduct comprehensive research on the given topic and gather "
"accurate, relevant, and up-to-date information from credible sources",
backstory="You are an experienced research analyst with a background in "
"investigative journalism and academic research. You have spent "
"over a decade honing your skills in finding reliable information, "
"fact-checking, and synthesizing complex topics into clear insights.",
verbose=True,
allow_delegation=False,
llm=self.llm,
tools=[web_search]
)
By adding the tools parameter with our web_search function, we give the research agent the ability to search the web. When the agent is working on a research task, it can decide to use this tool to find current information.
The agent does not automatically use the tool for every task. Instead, it reasons about whether the tool would be helpful for the current task. If the agent determines that web search would provide valuable information, it invokes the tool with an appropriate query.
This tool-using capability transforms our agents from being limited to their training data to being able to access current information from the internet. This is especially valuable for the research agent, which needs up-to-date facts and statistics.
Building the Main Application
Now we need to tie everything together into a main application that users can run. This application will handle configuration, model initialization, and crew execution.
Create a file named main.py:
# main.py
import sys
from config import ModelConfig, ModelProvider
from model_factory import ModelFactory
from crew import ContentCreationCrew
def main():
"""Main entry point for the content creation agency"""
if len(sys.argv) < 2:
print("Usage: python main.py <topic>")
print("Example: python main.py 'The Future of Renewable Energy'")
sys.exit(1)
topic = " ".join(sys.argv[1:])
print(f"Creating article on topic: {topic}")
print("=" * 60)
config = ModelConfig(
provider=ModelProvider.LOCAL,
model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
temperature=0.7,
max_tokens=2048
)
print(f"Initializing {config.provider} model...")
llm = ModelFactory.create_model(config)
print("Creating content creation crew...")
crew = ContentCreationCrew(llm)
print("Starting content creation process...")
print("=" * 60)
result = crew.create_article(topic)
print("\n" + "=" * 60)
print("FINAL ARTICLE")
print("=" * 60)
print(result)
with open(f"article_{topic.replace(' ', '_')}.txt", 'w') as f:
f.write(result)
print(f"\nArticle saved to article_{topic.replace(' ', '_')}.txt")
if __name__ == "__main__":
main()
The main function orchestrates the entire application. It starts by checking command-line arguments to get the topic. If no topic is provided, it prints usage instructions and exits.
The configuration is created with sensible defaults. In this example, we use a local model, but users can easily modify this to use OpenAI or Anthropic by changing the provider and adding an API key.
After creating the configuration, we use the ModelFactory to instantiate the appropriate language model. This abstracts away the complexity of model initialization.
Then we create the ContentCreationCrew and call its create_article method with the topic. The crew handles all the orchestration, running each agent in sequence and managing the flow of information.
Finally, we print the result and save it to a file. The filename is derived from the topic, making it easy to find the generated article.
This main application provides a clean command-line interface for our content creation system. Users can generate articles on any topic with a single command.
Running the System
To run the system, users need to download a model file if using local execution. GGUF format models are available from Hugging Face. For example, to download a Mistral model:
mkdir models
cd models
wget https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.2-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_K_M.gguf
cd ..
Then run the application with a topic:
python main.py "The Impact of Artificial Intelligence on Healthcare"
The system will initialize the model, create the crew, and execute each task in sequence. You will see output from each agent as they work through their tasks. The research agent will gather information, the writer will craft an article, the editor will refine it, and the SEO specialist will optimize it.
For users who prefer remote APIs, modify the configuration in main.py:
config = ModelConfig(
provider=ModelProvider.OPENAI,
model_name="gpt-4",
api_key="your-api-key-here",
temperature=0.7,
max_tokens=2048
)
Or use environment variables by creating a .env file:
OPENAI_API_KEY=your-api-key-here
Then the configuration can omit the api_key parameter and it will be loaded automatically:
config = ModelConfig(
provider=ModelProvider.OPENAI,
model_name="gpt-4",
temperature=0.7,
max_tokens=2048
)
The system works identically regardless of which model provider you choose. This flexibility is one of the key benefits of our abstraction layers.
Understanding the Execution Flow
Let us trace through what happens when you run the system. When you execute the main.py script with a topic, the following sequence occurs.
First, the configuration is created and validated. Pydantic ensures all values are valid and performs auto-detection of GPU backends if needed. If you are using a remote API, it loads the API key from environment variables.
Second, the ModelFactory creates the appropriate language model instance. For local models, it configures GPU acceleration based on your hardware. For remote APIs, it sets up the HTTP client with authentication.
Third, the ContentCreationCrew is instantiated. It creates the agent factory and task factory, preparing everything needed for execution.
Fourth, when you call create_article, the task factory creates all four tasks with their dependencies. The research task has no dependencies. The writing task depends on research. The editing task depends on writing. The SEO task depends on editing.
Fifth, the Crew object is created with all agents and tasks. CrewAI analyzes the task dependencies to determine the execution order.
Sixth, crew.kickoff() starts the execution. CrewAI runs the research task first because it has no dependencies. The research agent receives the task description and begins working. If equipped with the web search tool, it may use it to find current information.
Seventh, once the research task completes, its output is stored. CrewAI then starts the writing task, providing the research output as context. The writer agent receives both the task description and the research findings.
Eighth, the writer agent crafts an article based on the research. It structures the information into a narrative, adds examples and explanations, and produces a complete draft.
Ninth, the editing task begins once writing completes. The editor agent receives the draft article and refines it, improving clarity, fixing errors, and enhancing flow.
Tenth, finally, the SEO task runs. The SEO agent receives the polished article and optimizes it for search engines, adding a title, meta description, and proper heading structure.
The final output from the SEO task is returned by crew.kickoff() and becomes the result of create_article. This result is then printed and saved to a file.
This sequential flow ensures that each agent builds upon the work of previous agents, creating a collaborative process that produces high-quality content.
Extending the System
The system we have built is extensible. You can add new agents and tasks to enhance functionality. For example, you might add a fact-checking agent that verifies claims in the article. Or a formatting agent that converts the article to HTML or Markdown.
To add a new agent, create a method in the ContentCreationAgents class:
def create_factchecker_agent(self) -> Agent:
"""Create a fact-checking agent"""
return Agent(
role="Fact Checker",
goal="Verify the accuracy of claims and statistics in the article",
backstory="You are a meticulous fact-checker with expertise in "
"verifying information and identifying misinformation.",
verbose=True,
allow_delegation=False,
llm=self.llm,
tools=[web_search]
)
Then create a corresponding task:
def create_factchecking_task(self, editing_task: Task) -> Task:
"""Create a fact-checking task"""
return Task(
description="""Review the article and verify all factual claims,
statistics, and assertions. Flag any information that cannot be
verified or appears questionable. Provide corrections for any
inaccuracies found.""",
agent=self.factchecker_agent,
expected_output="A verified article with corrections for any "
"inaccuracies and notes on unverifiable claims",
context=[editing_task]
)
Add this task to the crew between editing and SEO:
factcheck_task = self.task_factory.create_factchecking_task(editing_task)
seo_task = self.task_factory.create_seo_task(topic, factcheck_task)
The fact-checking agent will now verify the article before SEO optimization. This demonstrates how easy it is to extend the system with new capabilities.
You can also create tools for other purposes. For example, a tool that checks readability scores:
@tool("Readability Checker")
def check_readability(text: str) -> str:
"""Calculate readability metrics for the given text"""
sentences = text.count('.') + text.count('!') + text.count('?')
words = len(text.split())
if sentences == 0:
return "Unable to calculate readability: no sentences found"
avg_words_per_sentence = words / sentences
if avg_words_per_sentence < 15:
level = "Easy"
elif avg_words_per_sentence < 20:
level = "Medium"
else:
level = "Difficult"
return f"Readability: {level} (avg {avg_words_per_sentence:.1f} words/sentence)"
Equip the editor agent with this tool to help it assess and improve readability.
Advanced Configuration Options
Our configuration system supports many options beyond what we have shown. You can create different configurations for different use cases.
For maximum quality with remote APIs:
config = ModelConfig(
provider=ModelProvider.ANTHROPIC,
model_name="claude-3-opus-20240229",
temperature=0.5,
max_tokens=4096
)
For fast local execution on CPU:
config = ModelConfig(
provider=ModelProvider.LOCAL,
model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
temperature=0.7,
max_tokens=1024,
gpu_backend=GPUBackend.CPU
)
For creative writing with higher temperature:
config = ModelConfig(
provider=ModelProvider.OPENAI,
model_name="gpt-4",
temperature=1.2,
max_tokens=3000
)
The temperature parameter controls randomness in generation. Lower values like 0.5 produce more focused, deterministic output. Higher values like 1.2 produce more creative, varied output. For factual content, use lower temperatures. For creative content, use higher temperatures.
The max_tokens parameter controls output length. Longer articles require higher values. However, higher values also mean slower generation and higher costs for API-based models.
Error Handling and Robustness
Production systems need robust error handling. Let us enhance our main application with better error handling:
def main():
"""Main entry point with error handling"""
try:
if len(sys.argv) < 2:
print("Usage: python main.py <topic>")
sys.exit(1)
topic = " ".join(sys.argv[1:])
print(f"Creating article on topic: {topic}")
print("=" * 60)
config = ModelConfig(
provider=ModelProvider.LOCAL,
model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
temperature=0.7,
max_tokens=2048
)
print(f"Initializing {config.provider} model...")
llm = ModelFactory.create_model(config)
print("Creating content creation crew...")
crew = ContentCreationCrew(llm)
print("Starting content creation process...")
print("=" * 60)
result = crew.create_article(topic)
print("\n" + "=" * 60)
print("FINAL ARTICLE")
print("=" * 60)
print(result)
filename = f"article_{topic.replace(' ', '_')}.txt"
with open(filename, 'w', encoding='utf-8') as f:
f.write(result)
print(f"\nArticle saved to {filename}")
except FileNotFoundError as e:
print(f"Error: Model file not found. {e}")
print("Please download a model file and update the model_path in the configuration.")
sys.exit(1)
except ValueError as e:
print(f"Configuration error: {e}")
sys.exit(1)
except Exception as e:
print(f"An unexpected error occurred: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
This enhanced version catches specific exceptions and provides helpful error messages. If the model file is not found, it tells the user to download one. If there is a configuration error, it explains what went wrong. For unexpected errors, it prints the full traceback to aid debugging.
Performance Considerations
The performance of your agentic system depends on several factors. The choice between local and remote models has the biggest impact. Local models require powerful hardware but have no per-request costs and no latency from network calls. Remote APIs are convenient and powerful but incur costs and network latency.
For local execution, GPU acceleration is crucial. A model running entirely on CPU might take minutes to generate a response. The same model on a GPU might take only seconds. Our system automatically uses available GPU acceleration, but you need appropriate hardware.
The number of GPU layers offloaded affects both speed and memory usage. Offloading all layers to GPU is fastest but requires more VRAM. If you run out of GPU memory, reduce the number of layers or use a smaller model.
Model size also matters. Larger models like 13B or 70B parameter models produce better output but run slower and require more memory. Smaller models like 7B parameters are faster but may produce lower quality output. Choose based on your quality requirements and hardware capabilities.
For production deployments, consider caching. If you generate articles on similar topics frequently, you might cache research results to avoid redundant work. You could also cache model outputs for common queries.
Testing Your Agentic System
Testing agentic systems is challenging because outputs are non-deterministic. The same input can produce different outputs due to the randomness in language model generation. However, you can still write useful tests.
Create a file named test_system.py:
# test_system.py
import unittest
from config import ModelConfig, ModelProvider
from model_factory import ModelFactory
from crew import ContentCreationCrew
class TestContentCreationSystem(unittest.TestCase):
"""Tests for the content creation system"""
def setUp(self):
"""Set up test fixtures"""
self.config = ModelConfig(
provider=ModelProvider.LOCAL,
model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
temperature=0.7,
max_tokens=512
)
self.llm = ModelFactory.create_model(self.config)
self.crew = ContentCreationCrew(self.llm)
def test_article_generation(self):
"""Test that article generation completes without errors"""
topic = "Test Topic"
result = self.crew.create_article(topic)
self.assertIsNotNone(result)
self.assertIsInstance(result, str)
self.assertGreater(len(result), 100)
def test_article_contains_topic(self):
"""Test that generated article mentions the topic"""
topic = "Quantum Computing"
result = self.crew.create_article(topic)
self.assertIn("quantum", result.lower())
if __name__ == "__main__":
unittest.main()
These tests verify basic functionality. The first test ensures that article generation completes and produces a non-empty string. The second test checks that the generated article actually relates to the requested topic.
For more comprehensive testing, you might evaluate output quality using metrics like readability scores, keyword density, or structural completeness. You could also use human evaluation, having people rate the quality of generated articles.
Deployment Considerations
When deploying an agentic system to production, consider several factors. First, decide between local and remote model execution based on your requirements. Local execution gives you control and eliminates per-request costs but requires infrastructure. Remote APIs are easier to deploy but incur ongoing costs.
For local deployment, containerization helps ensure consistency. Create a Dockerfile:
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "main.py"]
This creates a container with all dependencies installed. You can deploy this container to any server with Docker support.
For scaling, consider using a task queue. Instead of generating articles synchronously, accept requests and queue them for processing. This allows you to handle multiple requests concurrently and scale horizontally.
Monitor your system in production. Track metrics like generation time, error rates, and output quality. Set up alerts for failures or performance degradation.
Secure your API keys and sensitive configuration. Never commit API keys to version control. Use environment variables or secret management services.
Conclusion
We have built a complete agentic AI system using CrewAI. This system demonstrates the key concepts of agentic AI: specialized agents working together, task orchestration, tool usage, and collaborative workflows.
Our content creation agency mirrors how human teams work, with each agent bringing specific expertise. The research agent gathers information, the writer crafts prose, the editor refines quality, and the SEO specialist optimizes discoverability. By breaking down the complex task of content creation into specialized subtasks, we achieve better results than a single generalist agent could produce.
The system is flexible and extensible. It supports both local and remote model execution, works with various GPU backends, and can be easily extended with new agents and tools. The clean architecture with separated concerns makes the code maintainable and testable.
This tutorial has covered the fundamental concepts you need to build agentic AI systems. You can apply these patterns to many domains beyond content creation. Any complex task that can be broken down into specialized subtasks is a candidate for an agentic approach.
The future of AI applications lies in these collaborative, multi-agent systems. As you build more sophisticated agents and crews, you will discover new ways to combine AI capabilities to solve real-world problems.
COMPLETE RUNNING EXAMPLE
Below is the complete, production-ready code for the content creation agency. This code includes all functionality discussed in the tutorial and is ready to run. Note: the listing below contains multiple files.
# config.py
import os
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
from dotenv import load_dotenv
load_dotenv()
class ModelProvider(str, Enum):
"""Enumeration of supported model providers"""
LOCAL = "local"
OPENAI = "openai"
ANTHROPIC = "anthropic"
OLLAMA = "ollama"
class GPUBackend(str, Enum):
"""Enumeration of supported GPU backends"""
CUDA = "cuda"
ROCM = "rocm"
METAL = "metal"
ONEAPI = "oneapi"
CPU = "cpu"
class ModelConfig(BaseModel):
"""Configuration for language model selection and parameters"""
provider: ModelProvider = Field(
default=ModelProvider.LOCAL,
description="The model provider to use"
)
model_name: str = Field(
default="mistral-7b-instruct",
description="Name of the model to use"
)
temperature: float = Field(
default=0.7,
ge=0.0,
le=2.0,
description="Sampling temperature for generation"
)
max_tokens: int = Field(
default=2048,
gt=0,
description="Maximum tokens to generate"
)
gpu_backend: Optional[GPUBackend] = Field(
default=None,
description="GPU backend for local models"
)
api_key: Optional[str] = Field(
default=None,
description="API key for remote providers"
)
model_path: Optional[str] = Field(
default=None,
description="Path to local model file"
)
class Config:
use_enum_values = True
def __init__(self, **data):
super().__init__(**data)
if self.provider == ModelProvider.LOCAL and self.gpu_backend is None:
self.gpu_backend = self._detect_gpu_backend()
if self.provider == ModelProvider.OPENAI and self.api_key is None:
self.api_key = os.getenv("OPENAI_API_KEY")
elif self.provider == ModelProvider.ANTHROPIC and self.api_key is None:
self.api_key = os.getenv("ANTHROPIC_API_KEY")
@staticmethod
def _detect_gpu_backend() -> GPUBackend:
"""Automatically detect available GPU backend"""
try:
import torch
if torch.cuda.is_available():
return GPUBackend.CUDA
elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
return GPUBackend.METAL
except ImportError:
pass
if os.path.exists('/opt/rocm'):
return GPUBackend.ROCM
if os.getenv('ONEAPI_ROOT'):
return GPUBackend.ONEAPI
return GPUBackend.CPU
# model_factory.py
from typing import Union
from langchain.llms.base import BaseLLM
from langchain_community.llms import LlamaCpp, Ollama
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from config import ModelConfig, ModelProvider, GPUBackend
class ModelFactory:
"""Factory for creating language model instances based on configuration"""
@staticmethod
def create_model(config: ModelConfig) -> BaseLLM:
"""
Create and configure a language model instance.
Args:
config: Model configuration specifying provider and parameters
Returns:
Configured language model instance
Raises:
ValueError: If the provider is not supported or configuration is invalid
"""
if config.provider == ModelProvider.LOCAL:
return ModelFactory._create_local_model(config)
elif config.provider == ModelProvider.OPENAI:
return ModelFactory._create_openai_model(config)
elif config.provider == ModelProvider.ANTHROPIC:
return ModelFactory._create_anthropic_model(config)
elif config.provider == ModelProvider.OLLAMA:
return ModelFactory._create_ollama_model(config)
else:
raise ValueError(f"Unsupported model provider: {config.provider}")
@staticmethod
def _create_local_model(config: ModelConfig) -> LlamaCpp:
"""Create a local model using llama-cpp-python with GPU acceleration"""
if config.model_path is None:
raise ValueError("model_path must be specified for local models")
n_gpu_layers = ModelFactory._get_gpu_layers(config.gpu_backend)
model_params = {
"model_path": config.model_path,
"temperature": config.temperature,
"max_tokens": config.max_tokens,
"n_gpu_layers": n_gpu_layers,
"n_ctx": 4096,
"n_batch": 512,
"verbose": False,
}
if config.gpu_backend == GPUBackend.METAL:
model_params["n_gpu_layers"] = 1
model_params["f16_kv"] = True
elif config.gpu_backend == GPUBackend.CUDA:
model_params["n_gpu_layers"] = -1
elif config.gpu_backend == GPUBackend.ROCM:
model_params["n_gpu_layers"] = -1
return LlamaCpp(**model_params)
@staticmethod
def _create_openai_model(config: ModelConfig) -> ChatOpenAI:
"""Create an OpenAI model instance"""
if config.api_key is None:
raise ValueError("API key must be provided for OpenAI models")
return ChatOpenAI(
model_name=config.model_name,
temperature=config.temperature,
max_tokens=config.max_tokens,
openai_api_key=config.api_key
)
@staticmethod
def _create_anthropic_model(config: ModelConfig) -> ChatAnthropic:
"""Create an Anthropic Claude model instance"""
if config.api_key is None:
raise ValueError("API key must be provided for Anthropic models")
return ChatAnthropic(
model=config.model_name,
temperature=config.temperature,
max_tokens=config.max_tokens,
anthropic_api_key=config.api_key
)
@staticmethod
def _create_ollama_model(config: ModelConfig) -> Ollama:
"""Create an Ollama model instance for local API server"""
return Ollama(
model=config.model_name,
temperature=config.temperature,
num_predict=config.max_tokens
)
@staticmethod
def _get_gpu_layers(backend: GPUBackend) -> int:
"""
Determine optimal number of GPU layers based on backend.
Returns -1 for full GPU offloading, 0 for CPU only, or specific
layer count for backends with special requirements.
"""
if backend == GPUBackend.CPU:
return 0
elif backend == GPUBackend.METAL:
return 1
else:
return -1
# tools.py
from crewai_tools import tool
import requests
from bs4 import BeautifulSoup
from typing import List
@tool("Web Search Tool")
def web_search(query: str) -> str:
"""
Search the web for information on a given query.
Args:
query: The search query
Returns:
Relevant information found on the web
"""
try:
search_url = f"https://html.duckduckgo.com/html/?q={query}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get(search_url, headers=headers, timeout=10)
if response.status_code != 200:
return f"Search failed with status code {response.status_code}"
soup = BeautifulSoup(response.content, 'html.parser')
results = []
for result in soup.find_all('div', class_='result')[:5]:
title_elem = result.find('a', class_='result__a')
snippet_elem = result.find('a', class_='result__snippet')
if title_elem and snippet_elem:
title = title_elem.get_text(strip=True)
snippet = snippet_elem.get_text(strip=True)
results.append(f"{title}: {snippet}")
if not results:
return "No results found"
return "\n\n".join(results)
except Exception as e:
return f"Error performing web search: {str(e)}"
@tool("Readability Checker")
def check_readability(text: str) -> str:
"""
Calculate readability metrics for the given text.
Args:
text: The text to analyze
Returns:
Readability assessment and metrics
"""
sentences = text.count('.') + text.count('!') + text.count('?')
words = len(text.split())
if sentences == 0:
return "Unable to calculate readability: no sentences found"
avg_words_per_sentence = words / sentences
if avg_words_per_sentence < 15:
level = "Easy"
recommendation = "Good for general audiences"
elif avg_words_per_sentence < 20:
level = "Medium"
recommendation = "Appropriate for most readers"
else:
level = "Difficult"
recommendation = "Consider simplifying for broader appeal"
return f"Readability: {level}\nAverage words per sentence: {avg_words_per_sentence:.1f}\nRecommendation: {recommendation}"
# agents.py
from crewai import Agent
from langchain.llms.base import BaseLLM
from tools import web_search, check_readability
class ContentCreationAgents:
"""Factory class for creating specialized content creation agents"""
def __init__(self, llm: BaseLLM):
"""
Initialize the agent factory with a language model.
Args:
llm: The language model to be used by all agents
"""
self.llm = llm
def create_research_agent(self) -> Agent:
"""
Create a research agent specialized in gathering information.
This agent acts as an investigative researcher, gathering facts,
statistics, expert opinions, and relevant information about the
given topic. It excels at finding credible sources and extracting
key insights that will form the foundation of the content.
Returns:
Configured research agent instance
"""
return Agent(
role="Senior Research Analyst",
goal="Conduct comprehensive research on the given topic and gather "
"accurate, relevant, and up-to-date information from credible sources",
backstory="You are an experienced research analyst with a background in "
"investigative journalism and academic research. You have spent "
"over a decade honing your skills in finding reliable information, "
"fact-checking, and synthesizing complex topics into clear insights. "
"Your expertise lies in identifying authoritative sources, extracting "
"key data points, and understanding the nuances of various subjects. "
"You take pride in the accuracy and depth of your research, never "
"settling for surface-level information.",
verbose=True,
allow_delegation=False,
llm=self.llm,
tools=[web_search]
)
def create_writer_agent(self) -> Agent:
"""
Create a writer agent specialized in crafting engaging content.
This agent takes research findings and transforms them into compelling,
well-structured prose. It understands narrative flow, audience engagement,
and how to present information in an accessible way.
Returns:
Configured writer agent instance
"""
return Agent(
role="Expert Content Writer",
goal="Transform research findings into compelling, well-structured "
"articles that engage readers and communicate ideas clearly",
backstory="You are a seasoned content writer with fifteen years of "
"experience creating articles for major publications. Your "
"writing style is clear, engaging, and accessible. You excel "
"at taking complex information and making it understandable "
"without dumbing it down. You understand narrative structure, "
"pacing, and how to keep readers engaged from the first "
"sentence to the last. You have a talent for finding the "
"perfect examples and analogies to illustrate complex concepts.",
verbose=True,
allow_delegation=False,
llm=self.llm
)
def create_editor_agent(self) -> Agent:
"""
Create an editor agent specialized in refining and polishing content.
This agent reviews written content with a critical eye, checking for
clarity, coherence, grammar, and style. It acts as a quality gatekeeper,
ensuring that the content meets professional standards.
Returns:
Configured editor agent instance
"""
return Agent(
role="Senior Content Editor",
goal="Review and refine written content to ensure clarity, coherence, "
"grammatical correctness, and stylistic excellence",
backstory="You are a meticulous editor with a sharp eye for detail and "
"a deep understanding of language. With twenty years of editorial "
"experience at top-tier publications, you have developed an "
"instinct for what makes writing great. You catch grammatical "
"errors, awkward phrasing, logical inconsistencies, and structural "
"problems. You improve clarity without changing the author's voice. "
"You ensure every sentence serves a purpose and every paragraph "
"flows naturally into the next.",
verbose=True,
allow_delegation=False,
llm=self.llm,
tools=[check_readability]
)
def create_seo_agent(self) -> Agent:
"""
Create an SEO specialist agent for optimizing content.
This agent optimizes content for search engines while maintaining
readability and user engagement. It ensures the article ranks well
and attracts organic traffic.
Returns:
Configured SEO agent instance
"""
return Agent(
role="SEO Optimization Specialist",
goal="Optimize content for search engines while maintaining readability "
"and user engagement, ensuring the article ranks well and attracts "
"organic traffic",
backstory="You are an SEO expert with deep knowledge of search engine "
"algorithms, keyword research, and content optimization strategies. "
"You have helped hundreds of articles achieve top rankings in "
"search results. You understand how to naturally incorporate "
"keywords, optimize meta descriptions, create compelling titles, "
"and structure content for both search engines and human readers. "
"You know that the best SEO serves the user first and the algorithm "
"second.",
verbose=True,
allow_delegation=False,
llm=self.llm
)
# tasks.py
from crewai import Task
from agents import ContentCreationAgents
class ContentCreationTasks:
"""Factory class for creating content creation tasks"""
def __init__(self, agents: ContentCreationAgents):
"""
Initialize with agent factory.
Args:
agents: Agent factory for creating specialized agents
"""
self.research_agent = agents.create_research_agent()
self.writer_agent = agents.create_writer_agent()
self.editor_agent = agents.create_editor_agent()
self.seo_agent = agents.create_seo_agent()
def create_research_task(self, topic: str) -> Task:
"""
Create a task for researching the given topic.
Args:
topic: The topic to research
Returns:
Configured research task
"""
return Task(
description=f"""Conduct comprehensive research on the topic: {topic}
Your research should include:
- Key facts and statistics about the topic
- Current trends and recent developments
- Expert opinions and authoritative perspectives
- Common questions and misconceptions
- Relevant examples and case studies
- Historical context where applicable
Focus on finding credible, up-to-date information from authoritative sources.
Use the web search tool to find current information when needed.
Organize your findings in a clear, structured format that will be useful
for a writer creating an article on this topic.
Your output should be a detailed research report covering all important
aspects of the topic, with clear sections and well-organized information.""",
agent=self.research_agent,
expected_output="A comprehensive research report with facts, statistics, "
"trends, expert opinions, and relevant examples organized "
"in a clear structure with distinct sections"
)
def create_writing_task(self, topic: str, research_task: Task) -> Task:
"""
Create a task for writing an article based on research.
Args:
topic: The topic to write about
research_task: The research task providing context
Returns:
Configured writing task
"""
return Task(
description=f"""Using the research findings, write a comprehensive,
engaging article on the topic: {topic}
Your article should:
- Have a compelling introduction that hooks the reader and clearly
states what the article will cover
- Present information in a logical, well-structured flow with clear
sections and smooth transitions
- Use clear, accessible language appropriate for a general audience
while maintaining accuracy and depth
- Include relevant examples, analogies, and explanations to illustrate
complex concepts
- Maintain reader engagement throughout with varied sentence structure
and interesting presentation
- Conclude with a strong summary that reinforces key points and
provides actionable takeaways or thought-provoking insights
Aim for an article length of 1500-2000 words. Write in a professional
yet conversational tone. Make complex ideas accessible without
oversimplifying them.
Base your article on the research findings provided, but transform
the information into engaging narrative prose rather than simply
listing facts. Tell a story with the information.""",
agent=self.writer_agent,
expected_output="A well-written, engaging article of 1500-2000 words "
"with clear structure, compelling narrative, accessible "
"explanations, and strong introduction and conclusion",
context=[research_task]
)
def create_editing_task(self, writing_task: Task) -> Task:
"""
Create a task for editing the written article.
Args:
writing_task: The writing task providing context
Returns:
Configured editing task
"""
return Task(
description="""Review and refine the written article to ensure
the highest quality.
Your editing should address:
- Grammar, spelling, and punctuation errors
- Sentence structure and clarity
- Paragraph flow and transitions between ideas
- Logical consistency and coherence of arguments
- Tone and style consistency throughout the article
- Removal of redundancy and wordiness
- Factual accuracy and precision of language
- Overall readability and accessibility
Use the readability checker tool to assess the article's readability
and make improvements if needed.
Improve the writing while preserving the author's voice and intent.
Ensure every sentence is clear and every paragraph serves a purpose.
The final article should read smoothly from beginning to end with
natural flow and engaging presentation.
Provide the edited version of the complete article with all
improvements incorporated.""",
agent=self.editor_agent,
expected_output="A polished, error-free article with improved clarity, "
"flow, and coherence, maintaining the original voice while "
"enhancing overall quality",
context=[writing_task]
)
def create_seo_task(self, topic: str, editing_task: Task) -> Task:
"""
Create a task for SEO optimization.
Args:
topic: The main topic/keyword to optimize for
editing_task: The editing task providing context
Returns:
Configured SEO task
"""
return Task(
description=f"""Optimize the edited article for search engines while
maintaining readability and user engagement.
Your optimization should include:
- A compelling, SEO-friendly title (60 characters or less) that
incorporates the main keyword: {topic}
- A meta description (150-160 characters) that encourages clicks
from search results and includes the main keyword
- Natural incorporation of relevant keywords and semantic variations
throughout the article without keyword stuffing
- Proper heading structure (H1 for title, H2 for main sections,
H3 for subsections) that improves both readability and SEO
- Suggestions for internal linking opportunities (where this article
could link to related content)
- Suggestions for external linking to authoritative sources
- Image alt text suggestions if images were to be included
Ensure that all SEO improvements feel natural and do not compromise
the quality or readability of the content. The article should serve
human readers first while also being discoverable by search engines.
Provide the final, SEO-optimized version of the article along with
the title, meta description, and any additional SEO recommendations.""",
agent=self.seo_agent,
expected_output="A complete, SEO-optimized article with compelling title, "
"meta description, proper heading structure, natural keyword "
"integration, and linking suggestions",
context=[editing_task]
)
# crew.py
from crewai import Crew, Process
from langchain.llms.base import BaseLLM
from agents import ContentCreationAgents
from tasks import ContentCreationTasks
class ContentCreationCrew:
"""Orchestrates the content creation process using multiple specialized agents"""
def __init__(self, llm: BaseLLM):
"""
Initialize the crew with a language model.
Args:
llm: The language model to be used by all agents
"""
self.llm = llm
self.agents = ContentCreationAgents(llm)
self.task_factory = ContentCreationTasks(self.agents)
def create_article(self, topic: str) -> str:
"""
Create a complete article on the given topic using the agent crew.
This method orchestrates the entire content creation process, running
each agent in sequence to produce a high-quality, SEO-optimized article.
The process follows these steps:
1. Research Agent gathers comprehensive information on the topic
2. Writer Agent crafts an engaging article based on the research
3. Editor Agent refines and polishes the written content
4. SEO Agent optimizes the article for search engines
Args:
topic: The topic to write about
Returns:
The final, SEO-optimized article with title and meta description
"""
research_task = self.task_factory.create_research_task(topic)
writing_task = self.task_factory.create_writing_task(topic, research_task)
editing_task = self.task_factory.create_editing_task(writing_task)
seo_task = self.task_factory.create_seo_task(topic, editing_task)
crew = Crew(
agents=[
self.agents.create_research_agent(),
self.agents.create_writer_agent(),
self.agents.create_editor_agent(),
self.agents.create_seo_agent()
],
tasks=[research_task, writing_task, editing_task, seo_task],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
return result
# main.py
import sys
import os
from config import ModelConfig, ModelProvider, GPUBackend
from model_factory import ModelFactory
from crew import ContentCreationCrew
def print_banner():
"""Print application banner"""
print("\n" + "=" * 70)
print(" " * 15 + "CONTENT CREATION AGENCY")
print(" " * 10 + "Powered by CrewAI and Agentic AI")
print("=" * 70 + "\n")
def print_usage():
"""Print usage instructions"""
print("Usage: python main.py <topic> [options]")
print("\nOptions:")
print(" --provider <provider> Model provider (local, openai, anthropic, ollama)")
print(" --model <model> Model name")
print(" --temperature <temp> Sampling temperature (0.0-2.0)")
print(" --max-tokens <tokens> Maximum tokens to generate")
print(" --model-path <path> Path to local model file (for local provider)")
print("\nExamples:")
print(" python main.py 'The Future of Renewable Energy'")
print(" python main.py 'AI in Healthcare' --provider openai --model gpt-4")
print(" python main.py 'Quantum Computing' --provider local --model-path ./models/mistral.gguf")
def parse_arguments():
"""Parse command line arguments"""
if len(sys.argv) < 2 or sys.argv[1] in ['-h', '--help']:
print_usage()
sys.exit(0 if len(sys.argv) >= 2 else 1)
topic = sys.argv[1]
config_params = {
"provider": ModelProvider.LOCAL,
"model_name": "mistral-7b-instruct",
"temperature": 0.7,
"max_tokens": 2048,
}
i = 2
while i < len(sys.argv):
arg = sys.argv[i]
if arg == "--provider" and i + 1 < len(sys.argv):
config_params["provider"] = ModelProvider(sys.argv[i + 1])
i += 2
elif arg == "--model" and i + 1 < len(sys.argv):
config_params["model_name"] = sys.argv[i + 1]
i += 2
elif arg == "--temperature" and i + 1 < len(sys.argv):
config_params["temperature"] = float(sys.argv[i + 1])
i += 2
elif arg == "--max-tokens" and i + 1 < len(sys.argv):
config_params["max_tokens"] = int(sys.argv[i + 1])
i += 2
elif arg == "--model-path" and i + 1 < len(sys.argv):
config_params["model_path"] = sys.argv[i + 1]
i += 2
else:
print(f"Unknown argument: {arg}")
print_usage()
sys.exit(1)
if config_params["provider"] == ModelProvider.LOCAL and "model_path" not in config_params:
config_params["model_path"] = "./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf"
return topic, ModelConfig(**config_params)
def main():
"""Main entry point for the content creation agency"""
try:
print_banner()
topic, config = parse_arguments()
print(f"Topic: {topic}")
print(f"Provider: {config.provider}")
print(f"Model: {config.model_name}")
print(f"Temperature: {config.temperature}")
print(f"Max Tokens: {config.max_tokens}")
if config.provider == ModelProvider.LOCAL:
print(f"GPU Backend: {config.gpu_backend}")
print(f"Model Path: {config.model_path}")
print("\n" + "-" * 70 + "\n")
print("Initializing language model...")
llm = ModelFactory.create_model(config)
print("Model initialized successfully.\n")
print("Creating content creation crew...")
crew = ContentCreationCrew(llm)
print("Crew created successfully.\n")
print("Starting content creation process...")
print("This may take several minutes depending on your hardware.\n")
print("-" * 70 + "\n")
result = crew.create_article(topic)
print("\n" + "=" * 70)
print(" " * 25 + "FINAL ARTICLE")
print("=" * 70 + "\n")
print(result)
print("\n" + "=" * 70 + "\n")
filename = f"article_{topic.replace(' ', '_').replace('/', '_')}.txt"
with open(filename, 'w', encoding='utf-8') as f:
f.write(f"Topic: {topic}\n")
f.write(f"Generated by: Content Creation Agency\n")
f.write(f"Provider: {config.provider}\n")
f.write(f"Model: {config.model_name}\n")
f.write("\n" + "=" * 70 + "\n\n")
f.write(result)
print(f"Article saved to: {filename}\n")
except FileNotFoundError as e:
print(f"\nError: Model file not found.")
print(f"Details: {e}")
print("\nFor local models, please download a GGUF model file and specify")
print("its path using --model-path or place it at the default location:")
print(" ./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf")
print("\nYou can download models from Hugging Face:")
print(" https://huggingface.co/TheBloke")
sys.exit(1)
except ValueError as e:
print(f"\nConfiguration Error: {e}")
print("\nPlease check your configuration and try again.")
print_usage()
sys.exit(1)
except KeyboardInterrupt:
print("\n\nProcess interrupted by user.")
sys.exit(0)
except Exception as e:
print(f"\nAn unexpected error occurred: {e}")
print("\nStack trace:")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()
# requirements.txt
crewai>=0.1.0
crewai-tools>=0.1.0
langchain>=0.1.0
langchain-community>=0.0.1
langchain-openai>=0.0.1
langchain-anthropic>=0.0.1
llama-cpp-python>=0.2.0
openai>=1.0.0
anthropic>=0.7.0
python-dotenv>=1.0.0
pydantic>=2.0.0
requests>=2.31.0
beautifulsoup4>=4.12.0
This complete running example includes all the code discussed in the tutorial. It is production-ready and supports local and remote model execution across various GPU architectures. The system is modular, extensible, and follows clean architecture principles. You can run it immediately after installing dependencies and obtaining a model file.