adding new docs and smaller fixes

This commit is contained in:
João Moura
2024-02-04 11:47:49 -08:00
parent 05dda59cf6
commit 63fb5a22be
22 changed files with 372 additions and 236 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

View File

@@ -68,7 +68,7 @@ os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
# Install duckduckgo-search for this example:
# !pip install -U duckduckgo-search
from langchain.tools import DuckDuckGoSearchRun
from langchain_community.tools import DuckDuckGoSearchRun
search_tool = DuckDuckGoSearchRun()
# Define your agents with roles and goals

View File

@@ -21,9 +21,12 @@ description: What are crewAI Agents and how to use them.
| **Goal** | The individual objective that the agent aims to achieve. It guides the agent's decision-making process. |
| **Backstory** | Provides context to the agent's role and goal, enriching the interaction and collaboration dynamics. |
| **Tools** | Set of capabilities or functions that the agent can use to perform tasks. Tools can be shared or exclusive to specific agents. |
| **Max Iter** | The maximum number of iterations the agent can perform before forced to give its best answer |
| **Max RPM** | The maximum number of requests per minute the agent can perform to avoid rate limits |
| **Verbose** | This allow you to actually see what is going on during the Crew execution. |
| **Allow Delegation** | Agents can delegate tasks or questions to one another, ensuring that each task is handled by the most suitable agent. |
## Creating an Agent
!!! note "Agent Interaction"
@@ -32,18 +35,22 @@ description: What are crewAI Agents and how to use them.
To create an agent, you would typically initialize an instance of the `Agent` class with the desired properties. Here's a conceptual example:
```python
# Example: Creating an agent with all attributes
from crewai import Agent
# Create an agent with a role and a goal
agent = Agent(
role='Data Analyst',
goal='Extract actionable insights',
verbose=True,
backstory="""You're a data analyst at a large company.
You're responsible for analyzing data and providing insights
to the business.
You're currently working on a project to analyze the
performance of our marketing campaigns."""
performance of our marketing campaigns.""",
tools=[my_tool1, my_tool2],
max_iter=10,
max_rpm=10,
verbose=True,
allow_delegation=True
)
```

View File

@@ -17,7 +17,8 @@ Tasks in CrewAI can be designed to require collaboration between agents. For exa
| **Agent** | Optionally, you can specify which agent is responsible for the task. If not, the crew's process will determine who takes it on. |
| **Expected Output** *(optional)* | Clear and detailed definition of expected output for the task. |
| **Tools** *(optional)* | These are the functions or capabilities the agent can utilize to perform the task. They can be anything from simple actions like 'search' to more complex interactions with other agents or APIs. |
| **Context** *(optional)* | Other tasks that will have their output used as context for this task. |
| **Async Execution** *(optional)* | If the task should be executed asynchronously. |
| **Context** *(optional)* | Other tasks that will have their output used as context for this task, if one is an asynchronous task it will wait for that to finish |
| **Callback** *(optional)* | A function to be executed after the task is completed. |
## Creating a Task
@@ -35,7 +36,6 @@ task = Task(
!!! note "Task Assignment"
Tasks can be assigned directly by specifying an `agent` to them, or they can be assigned in run time if you are using the `hierarchical` through CrewAI's process, considering roles, availability, or other criteria.
## Integrating Tools with Tasks
Tools from the [crewAI Toolkit](https://github.com/joaomdmoura/crewai-tools) and [LangChain Tools](https://python.langchain.com/docs/integrations/tools) enhance task performance, allowing agents to interact more effectively with their environment. Assigning specific tools to tasks can tailor agent capabilities to particular needs.
@@ -108,6 +108,39 @@ write_blog_task = Task(
#...
```
## Asynchronous Execution
You can define a task to be executed asynchronously, this means that the crew will not wait for it to be completed to continue with the next task. This is useful for tasks that take a long time to be completed, or that are not crucial for the next tasks to be performed.
You can then use the `context` attribute to define in a future task that it should wait for the output of the asynchronous task to be completed.
```python
#...
list_ideas = Task(
description="List of 5 interesting ideas to explore for na article about AI.",
expected_output="Bullet point list of 5 ideas for an article.",
agent=researcher,
async_execution=True # Will be executed asynchronously
)
list_important_history = Task(
description="Research the history of AI and give me the 5 most important events.",
expected_output="Bullet point list of 5 important events.",
agent=researcher,
async_execution=True # Will be executed asynchronously
)
write_article = Task(
description="Write an article about AI, it's history and interesting ideas.",
expected_output="A 4 paragraph article about AI.",
agent=writer,
context=[list_ideas, list_important_history] # Will wait for the output of the two tasks to be completed
)
#...
```
## Callback Mechanism
You can define a callback function that will be executed after the task is completed. This is useful for tasks that need to trigger some side effect after they are completed, while the crew is still running.
@@ -135,6 +168,40 @@ research_task = Task(
#...
```
## Accessing a specific Task Output
Once a crew finishes running, you can access the output of a specific task by using the `output` attribute of the task object:
```python
# ...
task1 = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
agent=research_agent,
tools=[search_tool]
)
#...
crew = Crew(
agents=[research_agent],
tasks=[task1, task2, task3],
verbose=2
)
result = crew.kickoff()
# Returns a TaskOutput object with the description and results of the task
print(f"""
Task completed!
Task: {task1.output.description}
Output: {task1.output.result}
""")
```
## Tool Override Mechanism
Specifying tools in a task allows for dynamic adaptation of agent capabilities, emphasizing CrewAI's flexibility.

View File

@@ -28,7 +28,7 @@ os.environ["OPENAI_API_KEY"] = "YOUR KEY"
# Install duckduckgo-search for this example:
# !pip install -U duckduckgo-search
from langchain.tools import DuckDuckGoSearchRun
from langchain_community.tools import DuckDuckGoSearchRun
search_tool = DuckDuckGoSearchRun()
# Define your agents with roles and goals

View File

@@ -1,75 +1,104 @@
# Get a crew working
---
title: Assembling and Activating Your CrewAI Team
description: A step-by-step guide to creating a cohesive CrewAI team for your projects.
---
Assembling a Crew in CrewAI is like casting characters for a play. Each agent you create is a cast member with a unique part to play. When your crew is assembled, you'll give the signal, and they'll spring into action, each performing their role in the grand scheme of your project.
## Introduction
Assembling a crew in CrewAI is akin to casting for a play, where each agent plays a unique role. This guide walks you through creating a crew, assigning roles and tasks, and activating them to work in harmony.
# Step 1: Assemble Your Agents
Start by creating your agents, each with its own role and backstory. These backstories add depth to the agents, influencing how they approach their tasks and interact with one another.
## Step 1: Assemble Your Agents
Begin by defining your agents with distinct roles and backstories. These elements not only add depth but also guide their task execution and interaction within the crew.
```python
import os
os.environ["OPENAI_API_KEY"] = "Your Key"
from crewai import Agent
# Create a researcher agent
# Topic that will be used in the crew run
topic = 'AI in healthcare'
# Creating a senior researcher agent
researcher = Agent(
role='Senior Researcher',
goal='Discover groundbreaking technologies',
goal=f'Uncover groundbreaking technologies around {topic}',
verbose=True,
backstory='A curious mind fascinated by cutting-edge innovation and the potential to change the world, you know everything about tech.'
backstory="""Driven by curiosity, you're at the forefront of
innovation, eager to explore and share knowledge that could change
the world."""
)
# Create a writer agent
# Creating a writer agent
writer = Agent(
role='Writer',
goal='Craft compelling stories about tech discoveries',
goal=f'Narrate compelling tech stories around {topic}',
verbose=True,
backstory='A creative soul who translates complex tech jargon into engaging narratives for the masses, you write using simple words in a friendly and inviting tone that does not sounds like AI.'
backstory="""With a flair for simplifying complex topics, you craft
engaging narratives that captivate and educate, bringing new
discoveries to light in an accessible manner."""
)
```
# Step 2: Define the Tasks
Outline the tasks that your agents need to tackle. These tasks are their missions, the specific objectives they need to achieve.
## Step 2: Define the Tasks
Detail the specific objectives for your agents. These tasks guide their focus and ensure a targeted approach to their roles.
```python
from crewai import Task
# Task for the researcher
# Install duckduckgo-search for this example:
# !pip install -U duckduckgo-search
from langchain_community.tools import DuckDuckGoSearchRun
search_tool = DuckDuckGoSearchRun()
# Research task for identifying AI trends
research_task = Task(
description='Identify the next big trend in AI',
agent=researcher # Assigning the task to the researcher
description=f"""Identify the next big trend in {topic}.
Focus on identifying pros and cons and the overall narrative.
Your final report should clearly articulate the key points,
its market opportunities, and potential risks.
""",
expected_output='A comprehensive 3 paragraphs long report on the latest AI trends.',
max_inter=3,
tools=[search_tool],
agent=researcher
)
# Task for the writer
# Writing task based on research findings
write_task = Task(
description='Write an article on AI advancements leveraging the research made.',
agent=writer # Assigning the task to the writer
description=f"""Compose an insightful article on {topic}.
Focus on the latest trends and how it's impacting the industry.
This article should be easy to understand, engaging and positive.
""",
expected_output=f'A 4 paragraph article on {topic} advancements.',
tools=[search_tool],
agent=writer
)
```
# Step 3: Form the Crew
Bring your agents together into a crew. This is where you define the process they'll follow to complete their tasks.
## Step 3: Form the Crew
Combine your agents into a crew, setting the workflow process they'll follow to accomplish the tasks.
```python
from crewai import Crew, Process
# Instantiate your crew
tech_crew = Crew(
# Forming the tech-focused crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential # Tasks will be executed one after the other
process=Process.sequential # Sequential task execution
)
```
# Step 4: Kick It Off
With the crew formed and the stage set, it's time to start the show. Kick off the process and watch as your agents collaborate to achieve their goals.
## Step 4: Kick It Off
With your crew ready and the stage set, initiate the process. Watch as your agents collaborate, each contributing their expertise to achieve the collective goal.
```python
# Begin the task execution
tech_crew.kickoff()
# Starting the task execution process
result = crew.kickoff()
print(result)
```
# Conclusion
Creating a crew and setting it into motion is a straightforward process in CrewAI. With each agent playing their part and a clear set of tasks, your AI ensemble is ready to take on any challenge. Remember, the richness of their backstories and the clarity of their goals will greatly enhance their performance and the outcomes of their collaboration.
## Conclusion
Building and activating a crew in CrewAI is a seamless process. By carefully assigning roles, tasks, and a clear process, your AI team is equipped to tackle challenges efficiently. The depth of agent backstories and the precision of their objectives enrich the collaboration, leading to successful project outcomes.

View File

@@ -1,45 +1,45 @@
# Customizable Attributes
---
title: Customizing Agents in CrewAI
description: A guide to tailoring agents for specific roles and tasks within the CrewAI framework.
---
Customizing your AI agents is a cornerstone of creating an effective CrewAI team. Each agent can be tailored to fit the unique needs of your project, allowing for a dynamic and versatile AI workforce.
## Customizable Attributes
Tailoring your AI agents is pivotal in crafting an efficient CrewAI team. Customization allows agents to be dynamically adapted to the unique requirements of any project.
When you initialize an Agent, you can set various attributes that define its behavior and role within the Crew:
### Key Attributes for Customization
- **Role**: Defines the agent's job within the crew, such as 'Analyst' or 'Customer Service Rep'.
- **Goal**: The agent's objective, aligned with its role and the crew's overall goals.
- **Backstory**: Adds depth to the agent's character, enhancing its role and motivations within the crew.
- **Tools**: The capabilities or methods the agent employs to accomplish tasks, ranging from simple functions to complex integrations.
- **Role**: The job title or function of the agent within your crew. This can be anything from 'Analyst' to 'Customer Service Rep'.
- **Goal**: What the agent is aiming to achieve. Goals should be aligned with the agent's role and the overall objectives of the crew.
- **Backstory**: A narrative that provides depth to the agent's character. This could include previous experience, motivations, or anything that adds context to their role.
- **Tools**: The abilities or methods the agent uses to complete tasks. This could be as simple as a 'search' function or as complex as a custom-built analysis tool.
## Understanding Tools in CrewAI
Tools empower agents with functionalities to interact and manipulate their environment, from generic utilities to specialized functions. Integrating with LangChain offers access to a broad range of tools for diverse tasks.
# Understanding Tools in CrewAI
Tools in CrewAI are functions that empower agents to interact with the world around them. These can range from generic utilities like a search function to more complex ones like integrating with an external API. The integration with LangChain allows you to utilize a suite of ready-to-use tools such as [Google Serper](https://python.langchain.com/docs/integrations/tools/google_serper), which enables agents to perform web searches and gather data.
# Customizing Agents and Tools
You can customize an agent by passing parameters when creating an instance. Each parameter tweaks how the agent behaves and interacts within the crew.
Customizing an agent's tools is particularly important. Tools define what an agent can do and how it interacts with tasks. For instance, if a task requires data analysis, assigning an agent with data-related tools would be optimal.
When initializing your agents, you can equip them with a set of tools that enable them to perform their roles more effectively:
## Customizing Agents and Tools
Agents are customized by defining their attributes during initialization, with tools being a critical aspect of their functionality.
### Example: Assigning Tools to an Agent
```python
from crewai import Agent
from langchain.agents import Tool
from langchain.utilities import GoogleSerperAPIWrapper
import os
# Initialize SerpAPI tool with your API key
# Set API keys for tool initialization
os.environ["OPENAI_API_KEY"] = "Your Key"
os.environ["SERPER_API_KEY"] = "Your Key"
search = GoogleSerperAPIWrapper()
# Initialize a search tool
search_tool = GoogleSerperAPIWrapper()
# Create tool to be used by agent
# Define and assign the tool to an agent
serper_tool = Tool(
name="Intermediate Answer",
func=search.run,
description="useful for when you need to ask with search",
func=search_tool.run,
description="Useful for search-based queries"
)
# Create an agent and assign the search tool
# Initialize the agent with the tool
agent = Agent(
role='Research Analyst',
goal='Provide up-to-date market analysis',
@@ -49,18 +49,17 @@ agent = Agent(
```
## Delegation and Autonomy
Agents in CrewAI can delegate tasks or ask questions, enhancing the crew's collaborative dynamics. This feature can be disabled to ensure straightforward task execution.
One of the most powerful aspects of CrewAI agents is their ability to delegate tasks to one another. Each agent by default can delegate work or ask question to anyone in the crew, but you can disable that by setting `allow_delegation` to `false`, this is particularly useful for straightforward agents that should execute their tasks in isolation.
### Example: Disabling Delegation for an Agent
```python
agent = Agent(
role='Content Writer',
goal='Write the most amazing content related to market trends an business.',
backstory='An expert writer with many years of experience in market trends, stocks and all business related things.',
goal='Write engaging content on market trends',
backstory='A seasoned writer with expertise in market analysis.',
allow_delegation=False
)
```
## Conclusion
Customization is what makes CrewAI powerful. By adjusting the attributes of each agent, you can ensure that your AI team is well-equipped to handle the challenges you set for them. Remember, the more thought you put into your agents' roles, goals, backstories, and tools, the more nuanced and effective their interactions and task execution will be.
Customizing agents is key to leveraging the full potential of CrewAI. By thoughtfully setting agents' roles, goals, backstories, and tools, you craft a nuanced and capable AI team ready to tackle complex challenges.

View File

@@ -0,0 +1,55 @@
---
title: Implementing the Hierarchical Process in CrewAI
description: Understanding and applying the hierarchical process within your CrewAI projects.
---
## Introduction
The hierarchical process in CrewAI introduces a structured approach to task management, mimicking traditional organizational hierarchies for efficient task delegation and execution.
!!! note "Complexity"
The current implementation of the hierarchical process relies on tools usage that usually require more complex models like GPT-4 and usually imply of a higher token usage.
## Hierarchical Process Overview
In this process, tasks are assigned and executed based on a defined hierarchy, where a 'manager' agent coordinates the workflow, delegating tasks to other agents and validating their outcomes before proceeding.
### Key Features
- **Task Delegation**: A manager agent oversees task distribution among crew members.
- **Result Validation**: The manager reviews outcomes before passing tasks along, ensuring quality and relevance.
- **Efficient Workflow**: Mimics corporate structures for a familiar and organized task management approach.
## Implementing the Hierarchical Process
To utilize the hierarchical process, you must define a crew with a designated manager and a clear chain of command for task execution.
!!! note "Tools on the hierarchical process"
For tools when using the hierarchical process, you want to make sure to assign them to the agents instead of the tasks, as the manager will be the one delegating the tasks and the agents will be the ones executing them.
```python
from crewai import Crew, Process, Agent
# Define your agents, no need to define a manager
researcher = Agent(
role='Researcher',
goal='Conduct in-depth analysis',
# tools = [...]
)
writer = Agent(
role='Writer',
goal='Create engaging content',
# tools = [...]
)
# Form the crew with a hierarchical process
project_crew = Crew(
tasks=[...], # Tasks that that manager will figure out how to complete
agents=[researcher, writer],
process=Process.hierarchical # Designating the hierarchical approach
)
```
### Workflow in Action
1. **Task Assignment**: The manager assigns tasks based on agent roles and capabilities.
2. **Execution and Review**: Agents perform their tasks, with the manager reviewing outcomes for approval.
3. **Sequential Task Progression**: Tasks are completed in a sequence dictated by the manager, ensuring orderly progression.
## Conclusion
The hierarchical process in CrewAI offers a familiar, structured way to manage tasks within a project. By leveraging a chain of command, it enhances efficiency and quality control, making it ideal for complex projects requiring meticulous oversight.

View File

@@ -1,7 +1,7 @@
# Human Input on Execution
Human inputs is important in many agent execution use cases, humans are AGI so they can can be prompted to step in and provide extra details ins necessary.
Using it with crewAI is pretty straightforward and you can do it through a LangChain Tool.
Using it with crewAI is pretty straightforward and you can do it through a LangChain Tool.
Check [LangChain Integration](https://python.langchain.com/docs/integrations/tools/human_tools) for more details:
Example:
@@ -9,7 +9,7 @@ Example:
```python
import os
from crewai import Agent, Task, Crew, Process
from langchain.tools import DuckDuckGoSearchRun
from langchain_community.tools import DuckDuckGoSearchRun
from langchain.agents import load_tools
search_tool = DuckDuckGoSearchRun()
@@ -45,7 +45,7 @@ writer = Agent(
task1 = Task(
description="""Conduct a comprehensive analysis of the latest advancements in AI in 2024.
Identify key trends, breakthrough technologies, and potential industry impacts.
Compile your findings in a detailed report.
Compile your findings in a detailed report.
Make sure to check with the human if the draft is good before returning your Final Answer.
Your final answer MUST be a full analysis report""",
agent=researcher
@@ -56,7 +56,7 @@ task2 = Task(
post that highlights the most significant AI advancements.
Your post should be informative yet accessible, catering to a tech-savvy audience.
Aim for a narrative that captures the essence of these breakthroughs and their
implications for the future.
implications for the future.
Your final answer MUST be the full blog post of at least 3 paragraphs.""",
agent=writer
)

View File

@@ -1,147 +1,69 @@
# Connect CrewAI to LLMs
---
title: Connect CrewAI to LLMs
description: Guide on integrating CrewAI with various Large Language Models (LLMs).
---
There are different types of connections.
Ollama is the recommended way to connect to local LLMs.
Azure uses a slightly different API and therefore has it's own connection object.
## Connect CrewAI to LLMs
!!! note "Default LLM"
By default, crewAI uses OpenAI's GPT-4 model for language processing. However, you can configure your agents to use a different model or API. This guide will show you how to connect your agents to different LLMs.
crewAI is compatible with any of the LangChain LLM components. See this page for more information: https://python.langchain.com/docs/integrations/llms/
CrewAI offers flexibility in connecting to various LLMs, including local models via [Ollama](https://ollama.ai) and different APIs like Azure. It's compatible with all [LangChain LLM](https://python.langchain.com/docs/integrations/llms/) components, enabling diverse integrations for tailored AI solutions.
## Ollama
crewAI supports integration with local models thorugh [Ollama](https://ollama.ai/) for enhanced flexibility and customization. This allows you to utilize your own models, which can be particularly useful for specialized tasks or data privacy concerns. We will conver other options for using local models in later sections. However, ollama is the recommended tool to use to host local models when possible.
## Ollama Integration
Ollama is preferred for local LLM integration, offering customization and privacy benefits. It requires installation and configuration, including model adjustments via a Modelfile to optimize performance.
### Setting Up Ollama
- **Install Ollama**: Ensure that Ollama is properly installed in your environment. Follow the installation guide provided by Ollama for detailed instructions.
- **Configure Ollama**: Set up Ollama to work with your local model. You will probably need to [tweak the model using a Modelfile](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md). I'd recommend adding `Observation` as a stop word and playing with `top_p` and `temperature`.
- **Installation**: Follow Ollama's guide for setup.
- **Configuration**: [Adjust your local model with a Modelfile](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md), considering adding `Observation` as a stop word and playing with parameters like `top_p` and `temperature`.
### Integrating Ollama with CrewAI
- Instantiate Ollama Model: Create an instance of the Ollama model. You can specify the model and the base URL during instantiation. For example:
Instantiate Ollama and pass it to your agents within CrewAI, enhancing them with the local model's capabilities.
```python
from langchain.llms import Ollama
# Assuming you have Ollama installed and downloaded the openhermes model
ollama_openhermes = Ollama(model="openhermes")
# Pass Ollama Model to Agents: When creating your agents within the CrewAI framework, you can pass the Ollama model as an argument to the Agent constructor. For instance:
local_expert = Agent(
role='Local Expert at this city',
goal='Provide the BEST insights about the selected city',
backstory="""A knowledgeable local guide with extensive information
about the city, it's attractions and customs""",
tools=[
SearchTools.search_internet,
BrowserTools.scrape_and_summarize_website,
],
llm=ollama_openhermes, # Ollama model passed here
role='Local Expert',
goal='Provide insights about the city',
backstory="A knowledgeable local guide.",
tools=[SearchTools.search_internet, BrowserTools.scrape_and_summarize_website],
llm=ollama_openhermes,
verbose=True
)
```
## Open AI Compatible API Endpoints
## OpenAI Compatible API Endpoints
You can use environment variables for easy switch between APIs and models, supporting diverse platforms like FastChat, LM Studio, and Mistral AI.
In the context of integrating various language models with CrewAI, the flexibility to switch between different API endpoints is a crucial feature. By utilizing environment variables for configuration details such as `OPENAI_API_BASE`, `OPENAI_API_KEY`, and `MODEL_NAME`, you can easily transition between different APIs or models. For instance, if you want to switch from using the standard OpenAI GPT model to a custom or alternative version, simply update the values of these environment variables.
The `OPENAI_API_BASE` variable allows you to define the base URL of the API to connect to, while `OPENAI_API_KEY` is used for authentication purposes. Lastly, the `MODEL_NAME` variable specifies the particular language model to be used, such as "gpt-3.5-turbo" or any other available model.
This method offers an easy way to adapt the system to different models or plataforms, be it for testing, scaling, or accessing different features available on various platforms. By centralizing the configuration in environment variables, the process becomes streamlined, reducing the need for extensive code modifications when switching between APIs or models.
```python
from dotenv import load_dotenv
from langchain.chat_models.openai import ChatOpenAI
load_dotenv()
defalut_llm = ChatOpenAI(openai_api_base=os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1"),
openai_api_key=os.environ.get("OPENAI_API_KEY", "NA"),
model_name=os.environ.get("MODEL_NAME", "gpt-3.5-turbo"))
# Create an agent and assign the LLM
example_agent = Agent(
role='Example Agent',
goal='Show how to assign a custom configured LLM',
backstory='You hang out in the docs section of GitHub repos.',
llm=default_llm
)
```
The following sections show examples of the configuration settings for various OpenAI API compatible applications and services. We have included links to relavant documentation for the various application and services.
### Open AI
OpenAI is the default LLM that will be used if you do not specify a value for the `llm` argument when creating an agent. It will also use default values for the `OPENAI_API_BASE` and `MODEL_NAME`. So the only value you need to set when using the OpenAI endpoint is the API key that from your account.
```sh
# Required
OPENAI_API_KEY="sk-..."
# Optional
OPENAI_API_BASE=https://api.openai.com/v1
MODEL_NAME="gpt-3.5-turbo"
```
### Configuration Examples
### FastChat
FastChat is an open platform for training, serving, and evaluating large language model based chatbots.
[GitHub](https://github.com/lm-sys/FastChat)
[API Documentation](https://github.com/lm-sys/FastChat?tab=readme-ov-file#api)
Configuration settings:
```sh
# Required
OPENAI_API_BASE="http://localhost:8001/v1"
OPENAI_API_KEY=NA
MODEL_NAME='oh-2.5m7b-q51'
MODEL_NAME='oh-2.5m7b-q51' # Depending on the model you have available
```
### LM Studio
Discover, download, and run local LLMs
[lmstudio.ai](https://lmstudio.ai/)
Configuration settings:
```sh
# Required
OPENAI_API_BASE="http://localhost:8000/v1"
OPENAI_API_KEY=NA
MODEL_NAME=NA
```
### Mistral API
Mistral AI's API endpoints
[Mistral AI](https://mistral.ai/)
[Documentation](https://docs.mistral.ai/)
```sh
OPENAI_API_KEY=your-mistral-api-key
OPENAI_API_BASE=https://api.mistral.ai/v1
MODEL_NAME="mistral-small" # Check documentation for available models
```
### text-gen-web-ui
A Gradio web UI for Large Language Models.
[GitHub](https://github.com/oobabooga/text-generation-webui)
[API Documentation](https://github.com/oobabooga/text-generation-webui/wiki/12-%E2%80%90-OpenAI-API)
Configuration settings:
```sh
# Required
API_BASE_URL=http://localhost:5000
@@ -149,39 +71,8 @@ OPENAI_API_KEY=NA
MODEL_NAME=NA
```
## Other Inference API Endpoints
Other platforms offer inference APIs such as Anthropic, Azure, and HuggingFace to name a few. Unfortunately, the APIs on the following platforms are not compatible with the OpenAI API specification. So, the following platforms will require a slightly different configuration than the examples in the previous section.
### Azure Open AI
Azure hosted OpenAI API endpoints have their own LLM component that needs to be imported from `langchain_openai`.
For more information, check out the langchain documenation for [Azure OpenAI](https://python.langchain.com/docs/integrations/llms/azure_openai).
```python
from dotenv import load_dotenv
from langchain_openai import AzureChatOpenAI
load_dotenv()
default_llm = AzureChatOpenAI(
openai_api_version=os.environ.get("AZURE_OPENAI_VERSION", "2023-07-01-preview"),
azure_deployment=os.environ.get("AZURE_OPENAI_DEPLOYMENT", "gpt35"),
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT", "https://<your-endpoint>.openai.azure.com/"),
api_key=os.environ.get("AZURE_OPENAI_KEY")
)
# Create an agent and assign the LLM
example_agent = Agent(
role='Example Agent',
goal='Show how to assign a custom configured LLM',
backstory='You hang out in the docs section of GitHub repos.',
llm=default_llm
)
```
Azure's OpenAI API needs a distinct setup, utilizing the `langchain_openai` component for Azure-specific configurations.
Configuration settings:
```sh
@@ -190,3 +81,25 @@ AZURE_OPENAI_DEPLOYMENT=""
AZURE_OPENAI_ENDPOINT=""
AZURE_OPENAI_KEY=""
```
```python
from dotenv import load_dotenv
from langchain_openai import AzureChatOpenAI
load_dotenv()
default_llm = AzureChatOpenAI(
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
api_key=os.environ.get("AZURE_OPENAI_KEY")
)
example_agent = Agent(
role='Example Agent',
goal='Demonstrate custom LLM configuration',
backstory='A diligent explorer of GitHub docs.',
llm=default_llm
)
```
## Conclusion
Integrating CrewAI with different LLMs expands the framework's versatility, allowing for customized, efficient AI solutions across various domains and platforms.

50
docs/how-to/Sequential.md Normal file
View File

@@ -0,0 +1,50 @@
---
title: Implementing the Sequential Process in CrewAI
description: A guide to utilizing the sequential process for task execution in CrewAI projects.
---
## Introduction
The sequential process in CrewAI ensures tasks are executed one after the other, following a linear progression. This approach is akin to a relay race, where each agent completes their task before passing the baton to the next.
## Sequential Process Overview
This process is straightforward and effective, particularly for projects where tasks must be completed in a specific order to achieve the desired outcome.
### Key Features
- **Linear Task Flow**: Tasks are handled in a predetermined sequence, ensuring orderly progression.
- **Simplicity**: Ideal for projects with clearly defined, step-by-step tasks.
- **Easy Monitoring**: Task completion can be easily tracked, offering clear insights into project progress.
## Implementing the Sequential Process
To apply the sequential process, assemble your crew and define the tasks in the order they need to be executed.
!!! note "Task assignment"
In the sequential process you need to make sure all tasks are assigned to the agents, as the agents will be the ones executing them.
```python
from crewai import Crew, Process, Agent, Task
# Define your agents
researcher = Agent(role='Researcher', goal='Conduct foundational research')
analyst = Agent(role='Data Analyst', goal='Analyze research findings')
writer = Agent(role='Writer', goal='Draft the final report')
# Define the tasks in sequence
research_task = Task(description='Gather relevant data', agent=researcher)
analysis_task = Task(description='Analyze the data', agent=analyst)
writing_task = Task(description='Compose the report', agent=writer)
# Form the crew with a sequential process
report_crew = Crew(
agents=[researcher, analyst, writer],
tasks=[research_task, analysis_task, writing_task],
process=Process.sequential
)
```
### Workflow in Action
1. **Initial Task**: The first agent completes their task and signals completion.
2. **Subsequent Tasks**: Following agents pick up their tasks in the order defined, using the outcomes of preceding tasks as inputs.
3. **Completion**: The process concludes once the final task is executed, culminating in the project's completion.
## Conclusion
The sequential process in CrewAI provides a clear, straightforward path for task execution. It's particularly suited for projects requiring a logical progression of tasks, ensuring each step is completed before the next begins, thereby facilitating a cohesive final product.

View File

@@ -28,21 +28,6 @@ Cutting-edge framework for orchestrating role-playing, autonomous AI agents. By
Processes
</a>
</li>
<!-- <li>
<a href="./core-concepts/Managing-Processes">
Managing Processes
</a>
</li>
<li>
<a href="./core-concepts/Delegation-and-Collaboration">
Collaboration and Delegation
</a>
</li>
<li>
<a href="./core-concepts/Agent-Tools">
Agent Tools
</a>
</li> -->
</ul>
</div>
<div style="width:30%">
@@ -74,17 +59,32 @@ Cutting-edge framework for orchestrating role-playing, autonomous AI agents. By
<h2>Examples</h2>
<ul>
<li>
<a href="https://github.com/joaomdmoura/crewAI-examples/tree/main/trip_planner">
<a target='_blank' href="https://github.com/joaomdmoura/crewAI-examples/tree/main/trip_planner">
Trip Planner Crew
</a>
</li>
<li>
<a href="https://github.com/joaomdmoura/crewAI-examples/tree/main/stock_analysis">
<a target='_blank' href="https://github.com/joaomdmoura/crewAI-examples/tree/main/instagram_post">
Create Instagram Post
</a>
</li>
<li>
<a target='_blank' href="https://github.com/joaomdmoura/crewAI-examples/tree/main/stock_analysis">
Stock Analysis
</a>
</li>
<li>
<a href="https://github.com/joaomdmoura/crewAI-examples/tree/main/landing_page_generator">
<a target='_blank' href="https://github.com/joaomdmoura/crewAI-examples/tree/main/game-builder-crew">
Game Generator
</a>
</li>
<li>
<a target='_blank' href="https://github.com/joaomdmoura/crewAI-examples/tree/main/CrewAI-LangGraph">
Drafting emails with LangGraph
</a>
</li>
<li>
<a target='_blank' href="https://github.com/joaomdmoura/crewAI-examples/tree/main/landing_page_generator">
Landing Page Generator
</a>
</li>

View File

@@ -126,16 +126,19 @@ nav:
- Processes: 'core-concepts/Processes.md'
- Collaboration: 'core-concepts/Collaboration.md'
- How to Guides:
- Creating a Crew Automation: 'how-to/Creating-a-Crew-and-kick-it-off.md'
- Using Sequential Process: 'how-to/Sequential.md'
- Using Hierarchical Process: 'how-to/Hierarchical.md'
- Connecting to any LLM: 'how-to/LLM-Connections.md'
- Customizing Agents: 'how-to/Customizing-Agents.md'
- Human Input on Execution: 'how-to/Human-Input-on-Execution.md'
- Examples:
- Example 1: 'examples/Example-1.md'
- Example 2: 'examples/Example-2.md'
- Example 3: 'examples/Example-3.md'
- Trip Planner Crew: https://github.com/joaomdmoura/crewAI-examples/tree/main/trip_planner"
- Create Instagram Post: https://github.com/joaomdmoura/crewAI-examples/tree/main/instagram_post"
- Stock Analysis: https://github.com/joaomdmoura/crewAI-examples/tree/main/stock_analysis"
- Game Generator: https://github.com/joaomdmoura/crewAI-examples/tree/main/game-builder-crew"
- Drafting emails with LangGraph: https://github.com/joaomdmoura/crewAI-examples/tree/main/CrewAI-LangGraph"
- Landing Page Generator: https://github.com/joaomdmoura/crewAI-examples/tree/main/landing_page_generator"
extra_css:
- stylesheets/output.css
- stylesheets/extra.css

View File

@@ -155,7 +155,10 @@ class Crew(BaseModel):
task_output = ""
for task in self.tasks:
if task.agent is not None and task.agent.allow_delegation:
task.tools += AgentTools(agents=self.agents).tools()
agents_for_delegation = [
agent for agent in self.agents if agent != task.agent
]
task.tools += AgentTools(agents=agents_for_delegation).tools()
role = task.agent.role if task.agent is not None else "None"
self._logger.log("debug", f"Working Agent: {role}")
@@ -187,9 +190,12 @@ class Crew(BaseModel):
task_output = ""
for task in self.tasks:
self._logger.log("debug", f"Working Agent: {manager.role}")
self._logger.log("info", f"Starting Task: {task.description}")
task_output = task.execute(agent=manager, context=task_output)
task_output = task.execute(
agent=manager, context=task_output, tools=manager.tools
)
self._logger.log(
"debug", f"[{manager.role}] Task output: {task_output}\n\n"

View File

@@ -66,7 +66,12 @@ class Task(BaseModel):
self.tools.extend(self.agent.tools)
return self
def execute(self, agent: Agent | None = None, context: Optional[str] = None) -> str:
def execute(
self,
agent: Agent | None = None,
context: Optional[str] = None,
tools: Optional[List[Any]] = None,
) -> str:
"""Execute the task.
Returns:
@@ -87,9 +92,11 @@ class Task(BaseModel):
context.append(task.output.result)
context = "\n".join(context)
tools = tools or self.tools
if self.async_execution:
self.thread = threading.Thread(
target=self._execute, args=(agent, self._prompt(), context, self.tools)
target=self._execute, args=(agent, self._prompt(), context, tools)
)
self.thread.start()
else:
@@ -97,7 +104,7 @@ class Task(BaseModel):
agent=agent,
task_prompt=self._prompt(),
context=context,
tools=self.tools,
tools=tools,
)
return result