Runoob Tutorial ArchiveEnglish

Building Agents with CrewAI

Creating Agents with CrewAI

CrewAI is an open-source framework for multi-agent collaboration, specifically designed to orchestrate and coordinate multiple AI Agents to work together.

CrewAI can break down a complex task into multiple roles, with each role responsible for a part, and complete it through process collaboration.

Comparative Understanding:

CrewAI is a tool for coordinating, managing, and framing AI Agents, built on LangChain and Pydantic, used to facilitate role-playing, autonomy, and collaborative Agent teams.

Simply put, crewAI provides a structured way to define who (Agent) performs what (Task) under what workflow (Process) to achieve a team goal.

The flowchart below clearly illustrates how the various core components in the crewAI framework work together:

db4e3f11 c7 1 493 ab19 1d 9ba1a f 7

The process begins by defining agents with specific roles and goals, and then creating specific tasks for them.

Next, these agents and their tasks are assembled into a crew, and a workflow (Process) for collaboration is chosen for the crew, such as sequential or parallel execution. Finally, the team executes all tasks according to the defined process to produce the final result.


Environment setup and installation

Before starting the build, we need to prepare the development environment.

Prerequisites

Python version requirements:

CrewAI usageUVTo manage dependencies and packages, there is only one goal:
To make multi-Agent projects more stable and not be dragged down by environmental issues.

UV Getting Started Tutorial: UV - Python package and environment management tool

API Key:

crewAI itself does not provide AI models; it needs to connect to large language models like GPT from OpenAI or Claude from Anthropic.

Install crewAI

Open your terminal or command-line tool and use the pip command to install the crewAI package.

Original prompt (Chinese, left untranslated)



# Normal installation

pip install crewai

# Other dependencies

pip install langchain

pip install openai





# If installation is slow, you can use a domestic mirror to install

pip install crewai -i https://mirrors.aliyun.com/pypi/simple/

pip install langchain -i https://mirrors.aliyun.com/pypi/simple/

pip install openai -i https://mirrors.aliyun.com/pypi/simple/

If you want to use some advanced tools built into crewAI (such as web search), you can install additional dependencies:

Original prompt (Chinese, left untranslated)



# Normal installation

pip install 'crewai[tools]'



# If installation is slow, you can use a domestic mirror to install

pip install 'crewai[tools]' -i https://mirrors.aliyun.com/pypi/simple/

Domestically, we can use the DeepSeek large model for testing. If you don't have one yet, you need to create one first.https://platform.deepseek.com/api_keysCreate an API key.

DeepSeek API documentation reference:https://api-docs.deepseek.com/zh-cn/.

After installation, create a new Python file, for examplemy_first_crew.py, and import the necessary libraries.

CrewAI's LLM must use LiteLLM as the underlying layer for third-party models (including DeepSeek). Before using it, we need to install:



pip install -U litellm

instance

from

crewai

import

Agent

,

Task

,

Crew

,

Process

from

crewai.

llm

import

LLM

=====================================================

LLM Configuration (DeepSeek | LiteLLM Standard Syntax)

=====================================================

llm

=

LLM

(

    model

=

"deepseek/deepseek-v4-flash"

,

 

Key: Must include the service provider deepseek, followed by the model name deepseek-v4-flash or deepseek-v4-pro

api_key

=

"sk-xxxxx"

,

 

Set API key

api_base

=

"https://api.deepseek.com/v1"

,

temperature

=

0.7

,

)

=====================================================

Agents

=====================================================

researcher

=

Agent

(

role

=

"Technical Researcher"

,

goal

=

"Find the latest, accurate, and verifiable technical documentation, and provide code proof."

,

backstory

=

"Skilled in systematic analysis of technical problems, focusing on facts and reproducibility."

,

llm

=

llm

,

verbose

=

True

,

allow_delegation

=

False

,

)

writer

=

Agent

(

role

=

"Technical Blogger"

,

goal

=

"Organize research findings into technical articles suitable for beginners to read."

,

backstory

=

Proficient in breaking down complex concepts into clear steps and providing complete examples.

,

llm

=

llm

,

verbose

=

True

,

allow_delegation

=

True

,

)

=====================================================

Tasks

=====================================================

research_task

=

Task

(

description

=

(

       

"In-depth study: Automated data cleaning using Python."

       

"Focus includes: pandas, numpy, missing values, duplicate values, and format inconsistency issues."

       

"Must provide complete, runnable code examples."

   

)

,

agent

=

researcher

,

expected_output

=

(

       

"A research report containing problem classification, solution code, and a complete cleaning process."

   

)

,

)

write_task

=

Task

(

description

=

(

       

Write an introductory-level technical blog post based on research reports.

       

Title: "Introduction to Python Data Cleaning: Bidding Farewell to Dirty Data with pandas".

   

)

,

agent

=

writer

,

context

=

[

research_task

]

,

expected_output

=

"A Markdown technical blog post of at least 800 words."

,

)

=====================================================

Crew

=====================================================

crew

=

Crew

(

agents

=

[

researcher

,

writer

]

,

tasks

=

[

research_task

,

write_task

]

,

process

=

Process.

sequential

,

verbose

=

True

,

)

=====================================================

Run

=====================================================

if

name

==

"main"

:

result

=

crew.

kickoff

(

)

output

=

result.

raw

   

with

open

(

"python_data_cleaning_blog.md"

,

"w"

,

encoding

=

"utf-8"

)

as

f:

f.

write

(

output

)

Next, the task will start executing and output relevant information:

18f1d 8 5c 44 3 8edf e fa d657d6

After completion, the output content will be written to python_data_cleaning_blog.md file.

The following is an explanation of the relevant attributes in the code.

LLM (Model Layer) Key Attributes

Attribute Example Value Function Error Consequence
model deepseek/deepseek-v4-flash LiteLLM Specification Syntax:服务商/模型名 Missingdeepseek/Will report directlyLLM Provider NOT provided
api_key sk-xxxxx Model authentication Empty or error directly 401 / LLM Failed
api_base https://api.deepseek.com/v1 DeepSeek API address Based on the address of the specific model
temperature 0.7 Control output randomness Too high content divergence, too low text rigidity

Agent (intelligent agent) key attributes

Attributes Function Essence
role The Agent's "Identity Tag" Written into the system prompt
goal The core goal of the current Agent Determines the direction of the answer
backstory Behavioral constraints and style Stable output quality
llm Which model to use Must explicitly bind
verbose Print execution process Affects only logs
allow_delegation Whether task delegation is allowed Very easy to fall into pitfalls

researcher

Attribute Value Design intent
allow_delegation False Prevent infinite task splitting
goal Find materials + provide code Output is "raw material"

writer (writing)

Attribute Value Risk
allow_delegation True May trigger delegate for further research
context [research_task] Already have input, delegation is not necessary

Conclusion
Writing Agent in the sequential pipelineDelegation should be turned offOtherwise, it is easy for secondary delegation to fail.

Task Key Attributes

Task General Fields:

Attribute Function Key Points
description The task text actually sent to the LLM The more specific, the more stable
agent Who will execute Must be unique
expected_output Result constraint Not mandatory, but strongly recommended
context Upstream task dependency Core sequential execution

research_task:

Attribute Description
agent=researcher Bind Researcher
Nonecontext Phase One Task
Output Structured Research Content

write_task:

Attribute Description
context=[research_task] Force read research results
agent=writer Only organize and express
Output Final Markdown text

Crew (Executor) key attributes

Attribute Example value Function Error consequences
agents [researcher, writer] All available Agents Missing one will cause a direct error
tasks [research_task, write_task] Execution queue Sequential according to the list
process Process.sequential Execution strategy Parallel execution will scramble dependencies
verbose True Logging switch Must be bool

kickoff() and output structure

Expression Type Usage
crew.kickoff() CrewOutput Execution result container
result.raw str Final text output
result.tasks_output list/dict Output of each Task
result.token_usage dict Statistics

crewai command

We can use the crewai command to generate the complete project structure:

Original prompt (Chinese, left untranslated)

crewai create crew <项目名>

For example, we create a project runoob-agent-test and run the following command:

crewai create crew runoob-agent-test

The following content appears next, you can first select the large model provider:

Creating folder runoob_agent_test...

Cache expired or not found. Fetching provider data from the web...

Downloading  [####################################]  1102019/56339

Select a provider to set up:

1. openai

2. anthropic

3. gemini

4. nvidia_nim

5. groq

6. huggingface

7. ollama

8. watson

9. bedrock

10. azure

11. cerebras

12. sambanova

13. other

q. Quit

In this chapter, we choose DeepSeek, first enter 13 to select other, then you can scroll with the mouse to see DeepSeek at 23, and enter the number 23:

8abbadb1 53cd 4e78 bda8 5eef6b761b48

If you have API keys for other models, select the corresponding number.

After completion, the generated directory will look like this:

Project structure description:

Original prompt (Chinese, left untranslated)

my_project/

├── .env                # 环境变量(API Key)

├── pyproject.toml      # 项目依赖声明

├── README.md

└── src/

    └── my_project/

        ├── main.py     # 程序入口

        ├── crew.py     # Crew 与 Agent 的核心逻辑

        ├── tools/      # 自定义工具

        └── config/

            ├── agents.yaml  # Agent 定义

            └── tasks.yaml   # Task 定义

Run your Crew

Enter the project root directory:



cd my_project

Lock and install dependencies:



crewai install

Run:



crewai run

Or directly:



python src/my_project/main.py

Configure API Key

For security reasons, it is not recommended to hardcode the API Key in the code; we can set it as an environment variable.

Set in code (for testing only):

Original prompt (Chinese, left untranslated)



import os

os.environ["OPENAI_API_KEY"] = "你的-openai-api-key-here"

Recommended method: Use.envFile

Create a file named.envin the project root directory.

Writing to a file:OPENAI_API_KEY=你的-openai-api-key-here

In Python code, usepython-dotenvto load the package.

Installation command:



pip install python-dotenv

Next, load it in the code:

Original prompt (Chinese, left untranslated)



from dotenv import load_dotenv

load_dotenv() # 这会自动加载 .env 文件中的变量

# Now os.environ["OPENAI_API_KEY"] has a value


Detailed explanation and practical application of core components

Now, let's build our AI team step by step, just like building a company, and we will simulate a technical blog creation team.

Step one: Define the Agent

AgentIs your team member. Several key attributes need to be defined when creating:

Parameter Description Example
role The role or position of the agent. 资深技术作家
goal The ultimate goal of the agent. 创作深入浅出、实用的技术教程
backstory The character's background story, used to shape their behavior and tone. 你是一位拥有10年全栈开发经验的开发者,热爱分享,擅长将复杂概念简单化。
llm The large language model used by the agent. ChatOpenAI(model="gpt-4", temperature=0.7)
verbose Set toTrueoutputs the agent's detailed thought process. True(Very useful for debugging)
allow_delegation Whether this agent is allowed to delegate tasks to other agents. True

Let's create two agents: oneResearcherand oneWriter.

Instance

First, define a shared LLM so that all agents can use the same model configuration

llm

=

ChatOpenAI

(

model

=

"gpt-3.5-turbo"

,

temperature

=

0.7

)

Create researcher agent

researcher

=

Agent

(

    role

=

'Technical Researcher'

,

    goal

=

Find the latest, most accurate, and most relevant technical information for the theme assigned to you.

,

backstory

=

You are a focused and rigorous technical analyst, skilled at filtering key points from massive amounts of information and verifying the reliability of their sources.

,

llm

=

llm

,

Use the model defined above

verbose

=

True

,

Output detailed logs

allow_delegation

=

False

Researchers do not need to delegate tasks

)

Create writer agent

writer

=

Agent

(

    role

=

'Technical blogger'

,

    goal

=

Write a technical blog post with a clear structure, engaging and interesting content, and complete code examples, based on the materials provided by the researcher.

,

backstory

=

You are a popular tech blogger with a friendly writing style, rigorous logic, and a particular talent for explaining complex concepts through metaphors and examples.

,

llm

=

llm

,

verbose

=

True

,

allow_delegation

=

True

If the author feels it is necessary, they can delegate a task (such as asking the researcher to supplement materials)

)

Step 2: Create a Task

TaskIt is a specific work item that needs to be assigned toAgentcomplete. Key attributes include:

Parameters Description Example
description A clear description of the task. 研究 "Python异步编程asyncio" 在 2023 年后的核心应用场景和最佳实践。
agent The object responsible for executing this task.Agentexpected_output researcher
A detailed description of the task output. Detailed description of the task output. 一份结构化的研究报告,包含概述、3-4个核心应用场景、2-3个代码片段示例以及总结。

We create one task for researchers and one for writers.

Instance

Create research task

research_task

=

Task

(

description

=

(

       

"Conduct an in-depth study on the topic of 'Automated Data Cleaning using Python'.\n"

       

"Focus on the latest usage of the pandas and numpy libraries (after 2023), common dirty data issues (such as missing values, duplicate values, inconsistent formats), and efficient cleaning workflows.\n"

       

"Please provide specific code snippets to illustrate each step."

   

)

,

agent

=

researcher

,

Assign this task to the researcher

expected_output

=

(

       

"A complete research report, formatted as follows:\n"

       

"1. Topic Overview\n"

       

"2. Common Data Issue Categories (At least 3 categories)\n"

       

"3. pandas/numpy Solutions for Each Category (with code snippets)\n"

       

"4. An Example of a Complete End-to-End Cleaning Workflow\n"

       

"5. Summary and Recommendations"

   

)

)

Create writing task

write_task

=

Task

(

description

=

(

       

"Write a technical blog post for beginners using the research report provided by the researcher."

       

"The article title is: 'Introduction to Python Data Cleaning: Bidding Farewell to Dirty Data with pandas'."

       

"Article requirements: The language must be easy to understand, the logic must progress step-by-step, and it must include all key code snippets provided by the researcher with detailed comments."

       

Finally, provide a complete, runnable example demonstrating the entire process of cleaning a simulated dataset.

   

)

,

agent

=

writer

,

Assign this task to the writer

expected_output

=

(

       

"A Markdown formatted blog post of no less than 800 words.\n"

       

Includes introduction, body (divided into subsections), code blocks, and conclusion.

       

A complete Python script including simulated data and cleaning code must be attached at the end of the document.

   

)

,

   

The context parameter is very important! It specifies the dependencies for this task, which is that research_task must be completed first.

context

=

[

research_task

]

)

Note write_taskincontext=[research_task]This establishes dependencies between tasks, meaning the writer needs to wait for the researcher to complete the task before starting work.

Step 3: Assemble the team and set up the process (Crew & Process)

Now, assembleAgentandTaskintoCrew, and define their workProcess.

Instance

Assemble team

blog_crew

=

Crew

(

agents

=

[

researcher

,

writer

]

,

What members constitute the team

tasks

=

[

research_task

,

write_task

]

,

What tasks does the team have

    process

=

Process.

sequential

,

Workflow type: sequential execution. Researcher finishes, then writer does.

verbose

=

2

Set the logging detail level when executing a team (0=quiet, 1=basic, 2=detailed)

)

crewAI mainly supports two workflows:

Step four: Execute tasks and get results

Everything is ready, launch your AI team!

Instance

Execute team task

result

=

blog_crew.

kickoff

(

)

Print final result

print

(

"###################### Final Results ######################"

)

print

(

result

)

Run your Python script (python my_first_crew.py). Because we setverbose=Trueandverbose=2, you will see the thinking process and task execution logs of each Agent in the terminal, and finally see the generated blog post.


Advanced Tip: Equip Agents with Tools

crewAI allowsAgentto call externalTool, such as searching the web, querying databases, or performing calculations.

The following examples are equipped withweb searchandcomputationtools:

instance

from

crewai_tools

import

SerperDevTool

,

CalculatorTool

Initialize tools

Note: SerperDevTool requires a separate API Key, please register and obtain it at https://serper.dev/

search_tool

=

SerperDevTool

(

serper_api_key

=

"your-serper-api-key"

)

calc_tool

=

CalculatorTool

(

)

Create a researcher equipped with tools

advanced_researcher

=

Agent

(

role

=

'Senior Technical Researcher'

,

goal

=

'Search for the latest technical trends and conduct quantitative analysis'

,

backstory

=

'You are not only good at finding information but can also perform simple calculations and comparisons on data.'

,

tools

=

[

search_tool

,

calc_tool

]

,

Assign the list of tools to the agent

    llm

=

llm

,

verbose

=

True

)

Create a task that uses tools

analysis_task

=

Task

(

description

=

(

       

"Search and compare the Star growth count of 'FastAPI' and 'Django' on GitHub over the past year."

       

Calculate the growth rate of both and analyze the possible reasons.

   

)

,

agent

=

advanced_researcher

,

expected_output

=

"A brief report containing specific data, calculation process, and root cause analysis."

)