In today's growing world of tech, building AI agents is at the forefront of innovation, transforming how we approach automation and intelligent systems. In this tutorial, we'll explore how to build AI agents using CrewAI, a powerful AI agent framework renowned for its advanced engine capabilities, including flexible rule application and robust memory features. This CrewAI tutorial uses two agents to plan and write a blog. You'll need basic Python, a terminal, and an OpenAI API key.

CrewAI offers a powerful CLI that generates a comprehensive project structure, allowing for AI agent development with prompts written in YAML files. However, for newcomers, this complexity can be overwhelming. That's why we're starting with a straightforward example: creating a fully functional AI agent within a single Python file. Later, we'll dive deeper into leveraging the CrewAI CLI for building more complex projects.

What Is the CrewAI Framework?

CrewAI is an open-source framework for coordinating AI agents and structured workflows. New to agents? Our guide to building an AI agent with Python and OpenAI covers the basics of building one without any framework.

Core Components

A project can use some or all of the nine parts in the CrewAI architecture.

ComponentPurpose
AgentPerforms a defined role
TaskDescribes the work
CrewCoordinates agents and tasks
ProcessSets the execution order
FlowControls state and workflow logic
ToolConnects external systems
MemoryRecalls earlier information
KnowledgeSupplies reference material
LLMReasons and generates text

Which ones do you need first? Agent, Task, and Crew are enough, along with an LLM. The official CrewAI documentation explains each one.

Key Concepts in Building AI Agents: Tasks and Agents

A fundamental concept in the CrewAI framework is the distinction between tasks and agents. When building AI agents, you're essentially orchestrating a set of agents, each assigned to execute specific tasks.

Let's say we want to create an AI agent that writes blog posts for us. (Yes, yet another blog post written by an AI agent!). Let's assume we do it in 2 steps. Given a blog title, the first agent creates an outline of the blog, and the second agent takes the outline as input and writes a full blog post by strictly following that outline.

So here we have 2 agents, each of which performs 1 task:

  • Agent: Blog Outline Generator. Task: Generate Blog Outline
  • Agent: Blog Writer. Task: Write Blog

Role-based AI agents like these are easy to inspect one at a time.

Let's see how we can do this in code!

Tested Technology Stack

We tested main.py against a local server that mimics the OpenAI API. Real model output wasn't part of that run.

ParameterTested Value
Python3.13, also 3.10 and 3.12
CrewAI1.15.45
System and installerLinux, pip
LLMOpenAI gpt-6-luna (API key required)
Testing date27 November 2026
GitHub repository[Add URL before publishing]

Step 1: Setting Up Your AI Agent Framework Project

CrewAI needs Python 3.10 or higher, but below 3.14.

Run pip install crewai to ensure it's available. Also, run pip install python-dotenv to ensure that you have the dotenv package installed.

Create a directory for your project.

mkdir crewaidemo
cd crewaidemo

How to Use CrewAI With OpenAI

Create a .env file and add the following content in it.

MODEL=gpt-6-luna
OPENAI_API_KEY=<Your-Open-AI-key>

Here we are specifying that we are going to use the 'gpt-6-luna' model from OpenAI. To use that model, we will need to provide an OpenAI API key. Keep the .env file out of version control.

AI agent development with CrewAI for automated business decisions and production workflows

Step 2: Writing Code to Build AI Agents

How to Create Your First CrewAI Agent

Create a file main.py and add the following code to it.

from crewai import Agent, Crew, Process, Task
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

blog_outline_generator = Agent(
    role="Blog Outline Generator",
    goal="Given a title: {blog_title}, generate a short blog outline which is only 100 words and only 5 subheadings which will be used to write a blog post with 2000 words",
    backstory="You are a blog outline generator"
)

generate_blog_outline_task = Task(
    description="Given a title: {blog_title}, generate a short blog outline which is only 100 words and only 5 subheadings which will be used to write a blog post with 2000 words",
    expected_output="A blog outline",
    agent=blog_outline_generator,
)

blog_writer = Agent(
    role="Blog Writer",
    goal="Given a blog outline for the title: {blog_title}, write a blog post with 2000 words",
    backstory="You are a blog writer"
)

write_blog_task = Task(
    description="Given a blog outline for the title: {blog_title}, write a blog post with 2000 words",
    expected_output="A blog post, make sure to include main points from blog outline which you have received in the context in the blog post as subheadings",
    agent=blog_writer,
    context=[generate_blog_outline_task]
)

crew = Crew(
    agents=[blog_outline_generator, blog_writer],
    tasks=[generate_blog_outline_task, write_blog_task],
    process=Process.sequential,
    verbose=True
)

result = crew.kickoff(inputs={'blog_title': "Violence in movies"})
print(result)

That's it. In less than 40 lines of Python code, you have your first working AI agent!

Don't worry if it doesn't make a lot of sense. I have explained the code below section by section.

If you want to try it out, just run:

python main.py

It will print the progress of each agent; at the end, this CrewAI Python example should print your blog post! Something like the following:

# Violence in Movies: A Deep Dive into Its Evolution, Impact, and Future

Violence has long been a captivating element within cinema, serving as a
veritable tapestry woven through the various genres and eras of filmmaking. As
we navigate through the numerous layers surrounding this topic, we will
explore the historical context from which depictions of violence in film have
emerged, the psychological ramifications for audiences, the role of
censorship, cultural reflections, and finally, a glimpse into the future of
violence in movies. Let's embark on this journey.

## The Historical Context of Violence in Film

...
...

Step 3: Understanding Code Execution for AI Agent Frameworks

Let's break down the key sections of the code so you can better understand how the AI agent architecture works in CrewAI.

from crewai import Agent, Crew, Process, Task
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

Here, we have imported the Agent, Crew, Process, and Task classes from the CrewAI package. Then, we load the .env file with the load_dotenv function to set up the environment for AI-driven automation.

Older versions of this code enabled LiteLLM debug output. We've removed those lines because CrewAI no longer installs LiteLLM by default.

Now, let's create our blog_outline_generator agent.

blog_outline_generator = Agent(
    role="Blog Outline Generator",
    goal="Given a title: {blog_title}, generate a short blog outline which is only 100 words and only 5 subheadings which will be used to write a blog post with 2000 words",
    backstory="You are a blog outline generator"
)

In this section, we create an instance of the Agent class named blog_outline_generator. This agent has a specific role and goal: to generate a concise blog outline based on a provided title. Always write a meaningful role and a detailed goal. This helps your agent behave predictably. The backstory gives context to the agent's purpose, enhancing its functionality.

Here, note the {blog_title}. This is how we pass external user input to the agent. Later, when we call kickoff, we will pass the actual value for this parameter.

generate_blog_outline_task = Task(
    description="Given a title: {blog_title}, generate a short blog outline which is only 100 words and only 5 subheadings which will be used to write a blog post with 2000 words",
    expected_output="A blog outline",
    agent=blog_outline_generator,
)

Here, we define a Task called generate_blog_outline_task. This task describes what needs to be done (generate a blog outline) and specifies the expected output. It is associated with the blog_outline_generator agent, linking the task to the agent responsible for executing it.

blog_writer = Agent(
    role="Blog Writer",
    goal="Given a blog outline for the title: {blog_title}, write a blog post with 2000 words",
    backstory="You are a blog writer"
)

Next, we create another agent called blog_writer. This AI-powered agent will expand the outline into a full blog post of 2000 words, effectively utilizing AI-driven automation.

write_blog_task = Task(
    description="Given a blog outline for the title: {blog_title}, write a blog post with 2000 words",
    expected_output="A blog post, make sure to include main points from blog outline which you have received in the context in the blog post as subheadings",
    agent=blog_writer,
    context=[generate_blog_outline_task]
)

In this section, we define the write_blog_task, which instructs the blog_writer agent to create a blog post based on the outline provided. The task description specifies the expected output. Most importantly, it includes the context of the previous task, ensuring that the writer has access to the outline. This is how to use CrewAI agents and tasks together.

crew = Crew(
    agents=[blog_outline_generator, blog_writer],
    tasks=[generate_blog_outline_task, write_blog_task],
    process=Process.sequential,
    verbose=True
)

Here, we create a Crew instance that brings together the agents and tasks we defined earlier. The process is set to sequential, meaning the tasks will be executed one after the other. CrewAI also supports a hierarchical process, which we compare below. The verbose flag is set to True, allowing for detailed logging during execution.

result = crew.kickoff(inputs={'blog_title': "Violence in movies"})
print(result)

Finally, we initiate the AI-driven automation process by calling the kickoff method on the crew instance, passing in a dictionary with the blog title as input. The result of the process is printed, which will include the final blog post.

Move to a Structured CrewAI CLI Project

One file suits learning and prototypes. Larger applications are easier to maintain when prompts and logic live apart. The CLI gives CrewAI agent development that structure.

Run these commands inside a virtual environment.

crewai create crew blog_crew --classic --skip-provider
cd blog_crew
crewai install
crewai run

Add your .env file to the project folder before the last command. The classic flag creates Python and YAML files.

  • Agents: define roles, goals, and backstories in config/agents.yaml.
  • Tasks: define descriptions, outputs, and context in config/tasks.yaml.
  • Orchestration: connect them in crew.py, and pass inputs from main.py.

Customer Support Ticket Crew: An Enterprise Example

Where do agent teams help a business? Support tickets need sorting, lookup, drafting, and review. The design below is a practice scenario, not a delivered project.

  • Ticket Classification Agent: identifies category and urgency.
  • Knowledge Retrieval Agent: finds approved support information.
  • Resolution Agent: prepares a proposed reply.
  • Quality Review Agent: checks accuracy and flags escalations.

Deciding which workflow to automate first is where AI implementation consulting can help.

How to Build a Multi-Agent System Using CrewAI

Give each role its own Agent and Task. Pass earlier results forward through each task's context list. Only the retrieval agent needs access to your help articles. A person or an authorized rule then approves the reply.

Remove personal data before a ticket reaches the model. Test with synthetic tickets, then measure correct categories, grounded replies, missed escalations, and cost per ticket. Multi-agent AI systems are worth it only if they beat one agent on those measures.

Sequential vs. Hierarchical Process

ParameterSequentialHierarchical
CoordinationFixed task orderManager delegates
PredictabilityHigherLower
ComplexityLowerHigher
ExampleOutline, then writingOpen-ended research

Choose sequential when you already know the steps, as in invoice processing. Choose hierarchical when the split of work varies, such as research on an unfamiliar topic. It needs a manager_llm or a manager_agent setting. More autonomy isn't automatically better, so compare both on the same inputs.

CrewAI Crews and Flows

A Crew is a team of agents completing tasks. A Flow is Python code that manages state, events, and branching around that work.

ParameterCrewsFlows
FocusRoles and tasksState and execution
ControlProcess settingEvent-driven logic
ExampleResearch a reportValidate and save it

Why Flows Matter for CrewAI Workflow Automation

A Flow can run a crew, check its output, and pick the next step. The start, listen, and router decorators handle that path. Would you let a model decide whether a refund needs approval? A Flow puts such a rule in code you can test. It doesn't guarantee reliability alone, so keep validation and monitoring.

Tools and Integrations in CrewAI

Tools let agents search documents, query databases, call REST APIs, or work with CRM and ERP platforms. Support systems and file processing connect the same way. Need help with these connections? Explore our AI agent integration services.

How to Create Custom Tools in CrewAI

Use the tool decorator for a short function. Subclass BaseTool when you need an input schema. Then attach it through the agent's tools list.

Start with a read-only tool, such as an order status lookup.

  • Validate every input before calling the system.
  • Load credentials from the environment, never from prompts.
  • Grant the smallest permission that works.
  • Set timeouts and return clear error messages.

These steps show how to connect CrewAI agents to external APIs safely.

Reading knowledge differs from taking action. Require approval before a tool sends, deletes, or pays.

MCP Integration in CrewAI

Model Context Protocol (MCP) is an open standard that connects AI applications to outside tools and data. An agent's mcps field attaches MCP servers in CrewAI. A tool filter can limit what the agent sees.

Treat CrewAI MCP integration like any other access grant. Connect only trusted servers, and give each one limited credentials.

Our guide to developing an MCP server for AI agents covers the server side. Keep it in a separate environment, since it uses MCP SDK 2.x and CrewAI 1.15.45 requires 1.x.

Memory and Knowledge in CrewAI

Knowledge supplies reference material you provide, such as policies or product documents. Memory stores facts from earlier runs and recalls them later.

How to Implement Memory in CrewAI Agents

Set memory=True on a Crew to start with the defaults. Add reference files through knowledge_sources. By default, both rely on OpenAI embeddings, and stored data stays on disk between runs.

Decide what may be saved, who can delete it, and how long it stays. Memory doesn't guarantee accuracy, because an outdated record still produces a wrong answer.

Testing and Troubleshooting CrewAI Agents

Common ProblemPossible Resolution
CrewAI installation failureUse Python 3.10 to 3.13 in a fresh environment
No module named litellmRemove the old debug lines
API authentication errorCheck the key and model name
Wrong output or missing contextTighten expected_output and check context
High token use or slow runsLower max_iter and simplify tasks
Tool failureCheck inputs, permissions, and timeouts

Start with verbose=True. In CLI projects, crewai log-tasks-outputs lists recent results, and crewai replay -t TASK_ID reruns from one task. Setting tracing=True after crewai login sends traces to CrewAI's hosted platform. Use output_pydantic for structured results, and catch errors around kickoff.

How to Prepare CrewAI Agents for Production

A demo proves that one run can work. Gartner predicts that over 40% of agentic AI projects will be canceled by the end of 2027. It cites rising costs, unclear value, and weak risk controls.

Check these areas before any CrewAI production deployment.

  • Access: host behind an API with authentication, authorization, and managed secrets.
  • Reliability: plan state, timeouts, limited retries, and failure recovery.
  • Control: add human approval and output validation.
  • Visibility: trace runs, evaluate quality, and track token cost.
  • Release: protect data, lock versions, test integrations, and keep a rollback path.

Don't call a prototype production-ready after one successful run. Our AI software development services team can help you close those gaps.

CrewAI Compared With Other Agent Frameworks

Several AI agent orchestration frameworks solve related problems differently.

FrameworkPrimary Orientation
CrewAIRole-based agent teams and Flows
LangGraphStateful graphs with explicit control
Microsoft Agent FrameworkAgents and workflows in Python and .NET
OpenAI Agents SDKHandoffs, guardrails, and tracing
LlamaIndexData and retrieval-heavy agents

Microsoft Agent Framework succeeds AutoGen, whose repository is now archived. No option wins every case. Our AI agent SDK and framework comparison covers more of them.

Enterprise CrewAI Use Cases

These are potential applications for AI agent development with CrewAI, not reported results.

  • Customer service and sales: ticket triage and lead research.
  • Logistics and manufacturing: exception analysis and maintenance report review.
  • Healthcare and finance: document processing with human review.
  • Retail and HR: inventory analysis and employee onboarding.
  • IT and software teams: incident escalation and code review support.
  • Research and operations: multi-source reports and cross-system coordination.

Conclusion

That's it! That's how easy it is to create a working AI agent using CrewAI. I hope that I have managed to break down the process of creating AI agents in easy-to-understand steps. The harder part starts when that agent touches real systems.

What should you do this week? Run main.py with your own blog title, and check the draft against its outline. Next, pick one process where a mistake is easy to catch. Finally, write down which actions always need a person's approval.

Be sure to subscribe to our blog using the 'Let's Stay Connected' form below!

If you're looking to integrate AI agents into your workflow, AI strategy consulting can help you design an effective plan. Need expert guidance? Contact us to get started.

Ready to Build Production-Ready AI Agents?

Move beyond AI agent prototypes with Mobisoft's AI engineering expertise. We help businesses design, develop, integrate, and deploy custom AI agents and multi-agent systems for real-world workflows.

Discuss Your AI Agent Development Requirements

AI-powered business transformation using intelligent multi-agent AI systems

Frequently Asked Questions

Can CrewAI work with models other than OpenAI models?

Yes. The CrewAI multi-agent framework supports Anthropic, Google Gemini, Azure, AWS Bedrock, Ollama, and others. Change the MODEL value and add that provider's credentials. Some providers need an extra package, such as crewai[anthropic]. Retest your outputs after switching, because behavior differs between models.

When should you use multiple agents instead of one?

Split the work when steps need different tools, permissions, or review standards. Pairing a writer with a separate fact checker is one case. Stay with one agent if it already passes your tests. Extra LLM-powered agents add calls, delay, and failure points.

How much does it cost to run CrewAI?

The open-source library is free under the MIT license. You pay for model tokens, embeddings, external tools, and hosting. CrewAI's hosted platform has separate pricing. Multiply runs by tokens per run and your provider's rate for an estimate. Run your own CrewAI example on real inputs to get the token count.

What are the limitations of CrewAI?

Agents can sometimes misread instructions, invent facts, or choose the wrong tool. Results vary between runs, even with identical inputs. APIs also change from one release to the next, so pin your versions. Give autonomous AI agents narrow permissions until testing on real cases justifies giving any of them anything more.

How do you stop an agent from looping or overspending?

Set limits on each agent. The max_iter value defaults to 25, so lower it for simple jobs. Add max_execution_time in seconds and max_rpm to cap the request rate. Make these limits a habit from the first day of CrewAI agent development.

Can a CrewAI agent wait for human approval?

Yes. Setting human_input=True on a task asks for feedback in the console, which suits scripts you run on your own machine. Flows also offer a human_feedback decorator for review steps inside larger applications. Plan these pauses as part of your CrewAI agent orchestration.

Can CrewAI run tasks in parallel?

Yes. Set async_execution=True on independent tasks, then list them as context for a later one. That later task then waits for all their results before it starts. Watch your provider's rate limits and costs as concurrency grows. The biggest gain goes to CrewAI AI agents that wait on slow, unrelated lookups.

This content is for informational purposes only and may include AI-assisted research or content generation. While we strive for accuracy, information may evolve over time. Readers are advised to independently verify critical information before making decisions.

Pritam Barhate

Pritam Barhate

Head of Technology Innovation

Read more expand

Pritam Barhate, with an experience of 14+ years in technology, heads Technology Innovation at Mobisoft Infotech. He has a rich experience in design and development. He has been a consultant for a variety of industries and startups. At Mobisoft Infotech, he primarily focuses on technology resources and develops the most advanced solutions.