Compare commits

..

4 Commits

Author SHA1 Message Date
Devin AI
a8e7e2db6d Fix type-checker issues with proper type annotations
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-27 16:49:18 +00:00
Devin AI
0328a8aaa4 Fix remaining type-checker issues in MCP connector
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-27 16:43:47 +00:00
Devin AI
66d35df858 Fix type-checker issues in SSE client and MCP connector
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-27 16:41:06 +00:00
Devin AI
f738e9ab62 Fix #2698: Implement MCP SSE server connection for tools
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-27 16:35:56 +00:00
132 changed files with 2243 additions and 13329 deletions

View File

@@ -31,4 +31,4 @@ jobs:
run: uv sync --dev --all-extras
- name: Run tests
run: uv run pytest --block-network --timeout=60 -vv
run: uv run pytest tests -vv

View File

@@ -688,6 +688,26 @@ A: Yes, CrewAI can integrate with custom-trained or fine-tuned models, allowing
### Q: Can CrewAI agents interact with external tools and APIs?
A: Absolutely! CrewAI agents can easily integrate with external tools, APIs, and databases, empowering them to leverage real-world data and resources.
CrewAI also supports connecting your tools to the Management Control Plane (MCP) via Server-Sent Events (SSE), enabling real-time tool execution from the Crew Control Plane:
```python
from crewai.tools import MCPToolConnector, Tool
# Define your tools
search_tool = Tool(
name="search",
description="Search for information",
func=lambda query: f"Results for {query}"
)
# Connect tools to MCP
connector = MCPToolConnector(tools=[search_tool])
connector.connect()
# Listen for tool events from MCP
connector.listen() # This will block until interrupted
```
### Q: Is CrewAI suitable for production environments?
A: Yes, CrewAI is explicitly designed with production-grade standards, ensuring reliability, stability, and scalability for enterprise deployments.

View File

@@ -4,69 +4,12 @@ description: View the latest updates and changes to CrewAI
icon: timeline
---
<Update label="2025-04-30" description="v0.117.1">
## Release Highlights
<Frame>
<img src="/images/releases/v01171.png" />
</Frame>
<div style={{ textAlign: 'center', marginBottom: '1rem' }}>
<a href="https://github.com/crewAIInc/crewAI/releases/tag/0.117.1">View on GitHub</a>
</div>
**Core Improvements & Fixes**
- Upgraded **crewai-tools** to latest version
- Upgraded **liteLLM** to latest version
- Fixed **Mem0 OSS**
</Update>
<Update label="2025-04-28" description="v0.117.0">
## Release Highlights
<Frame>
<img src="/images/releases/v01170.png" />
</Frame>
<div style={{ textAlign: 'center', marginBottom: '1rem' }}>
<a href="https://github.com/crewAIInc/crewAI/releases/tag/0.117.0">View on GitHub</a>
</div>
**New Features & Enhancements**
- Added `result_as_answer` parameter support in `@tool` decorator.
- Introduced support for new language models: GPT-4.1, Gemini-2.0, and Gemini-2.5 Pro.
- Enhanced knowledge management capabilities.
- Added Huggingface provider option in CLI.
- Improved compatibility and CI support for Python 3.10+.
**Core Improvements & Fixes**
- Fixed issues with incorrect template parameters and missing inputs.
- Improved asynchronous flow handling with coroutine condition checks.
- Enhanced memory management with isolated configuration and correct memory object copying.
- Fixed initialization of lite agents with correct references.
- Addressed Python type hint issues and removed redundant imports.
- Updated event placement for improved tool usage tracking.
- Raised explicit exceptions when flows fail.
- Removed unused code and redundant comments from various modules.
- Updated GitHub App token action to v2.
**Documentation & Guides**
- Enhanced documentation structure, including enterprise deployment instructions.
- Automatically create output folders for documentation generation.
- Fixed broken link in WeaviateVectorSearchTool documentation.
- Fixed guardrail documentation usage and import paths for JSON search tools.
- Updated documentation for CodeInterpreterTool.
- Improved SEO, contextual navigation, and error handling for documentation pages.
</Update>
<Update label="2025-04-07" description="v0.114.0">
## Release Highlights
<Frame>
<img src="/images/releases/v01140.png" />
<img src="/images/v01140.png" />
</Frame>
<div style={{ textAlign: 'center', marginBottom: '1rem' }}>
<a href="https://github.com/crewAIInc/crewAI/releases/tag/0.114.0">View on GitHub</a>
</div>
**New Features & Enhancements**
- Agents as an atomic unit. (`Agent(...).kickoff()`)
- Support for [Custom LLM implementations](https://docs.crewai.com/guides/advanced/custom-llm).
@@ -92,16 +35,7 @@ icon: timeline
</Update>
<Update label="2025-03-17" description="v0.108.0">
## Release Highlights
<Frame>
<img src="/images/releases/v01080.png" />
</Frame>
<div style={{ textAlign: 'center', marginBottom: '1rem' }}>
<a href="https://github.com/crewAIInc/crewAI/releases/tag/0.108.0">View on GitHub</a>
</div>
**New Features & Enhancements**
**Features**
- Converted tabs to spaces in `crew.py` template
- Enhanced LLM Streaming Response Handling and Event System
- Included `model_name`

View File

@@ -255,11 +255,7 @@ custom_agent = Agent(
- `response_template`: Formats agent responses
<Note>
When using custom templates, ensure that both `system_template` and `prompt_template` are defined. The `response_template` is optional but recommended for consistent output formatting.
</Note>
<Note>
When using custom templates, you can use variables like `{role}`, `{goal}`, and `{backstory}` in your templates. These will be automatically populated during execution.
When using custom templates, you can use variables like `{role}`, `{goal}`, and `{input}` in your templates. These will be automatically populated during execution.
</Note>
## Agent Tools

View File

@@ -322,10 +322,6 @@ blog_task = Task(
- On success: it returns a tuple of `(bool, Any)`. For example: `(True, validated_result)`
- On Failure: it returns a tuple of `(bool, str)`. For example: `(False, "Error message explain the failure")`
### LLMGuardrail
The `LLMGuardrail` class offers a robust mechanism for validating task outputs.
### Error Handling Best Practices
1. **Structured Error Responses**:
@@ -754,8 +750,6 @@ Task guardrails provide a powerful way to validate, transform, or filter task ou
### Basic Usage
#### Define your own logic to validate
```python Code
from typing import Tuple, Union
from crewai import Task
@@ -775,57 +769,6 @@ task = Task(
)
```
#### Leverage a no-code approach for validation
```python Code
from crewai import Task
task = Task(
description="Generate JSON data",
expected_output="Valid JSON object",
guardrail="Ensure the response is a valid JSON object"
)
```
#### Using YAML
```yaml
research_task:
...
guardrail: make sure each bullet contains a minimum of 100 words
...
```
```python Code
@CrewBase
class InternalCrew:
agents_config = "config/agents.yaml"
tasks_config = "config/tasks.yaml"
...
@task
def research_task(self):
return Task(config=self.tasks_config["research_task"]) # type: ignore[index]
...
```
#### Use custom models for code generation
```python Code
from crewai import Task
from crewai.llm import LLM
task = Task(
description="Generate JSON data",
expected_output="Valid JSON object",
guardrail=LLMGuardrail(
description="Ensure the response is a valid JSON object",
llm=LLM(model="gpt-4o-mini"),
)
)
```
### How Guardrails Work
1. **Optional Attribute**: Guardrails are an optional attribute at the task level, allowing you to add validation only where needed.

View File

@@ -190,6 +190,48 @@ def my_tool(question: str) -> str:
return "Result from your custom tool"
```
### Structured Tools
The `StructuredTool` class wraps functions as tools, providing flexibility and validation while reducing boilerplate. It supports custom schemas and dynamic logic for seamless integration of complex functionalities.
#### Example:
Using `StructuredTool.from_function`, you can wrap a function that interacts with an external API or system, providing a structured interface. This enables robust validation and consistent execution, making it easier to integrate complex functionalities into your applications as demonstrated in the following example:
```python
from crewai.tools.structured_tool import CrewStructuredTool
from pydantic import BaseModel
# Define the schema for the tool's input using Pydantic
class APICallInput(BaseModel):
endpoint: str
parameters: dict
# Wrapper function to execute the API call
def tool_wrapper(*args, **kwargs):
# Here, you would typically call the API using the parameters
# For demonstration, we'll return a placeholder string
return f"Call the API at {kwargs['endpoint']} with parameters {kwargs['parameters']}"
# Create and return the structured tool
def create_structured_tool():
return CrewStructuredTool.from_function(
name='Wrapper API',
description="A tool to wrap API calls with structured input.",
args_schema=APICallInput,
func=tool_wrapper,
)
# Example usage
structured_tool = create_structured_tool()
# Execute the tool with structured input
result = structured_tool._run(**{
"endpoint": "https://example.com/api",
"parameters": {"key1": "value1", "key2": "value2"}
})
print(result) # Output: Call the API at https://example.com/api with parameters {'key1': 'value1', 'key2': 'value2'}
```
### Custom Caching Mechanism
<Tip>

View File

@@ -4,16 +4,16 @@ description: "A Crew is a group of agents that work together to complete a task.
icon: "people-arrows"
---
## Overview
<Tip>
[CrewAI Enterprise](https://app.crewai.com) streamlines the process of **creating**, **deploying**, and **managing** your AI agents in production environments.
</Tip>
## Getting Started
<iframe
width="100%"
height="400"
src="https://www.youtube.com/embed/-kSOTtYzgEw"
src="https://www.youtube.com/embed/d1Yp8eeknDk?si=tIxnTRI5UlyCp3z_"
title="Building Crews with CrewAI CLI"
frameborder="0"
style={{ borderRadius: '10px' }}

View File

@@ -4,13 +4,13 @@ description: "Deploy your local CrewAI project to the Enterprise platform"
icon: "cloud-arrow-up"
---
## Overview
This guide will walk you through the process of deploying your locally developed CrewAI project to the CrewAI Enterprise platform,
transforming it into a production-ready API endpoint.
## Option 1: CLI Deployment
<Tip>
This video tutorial walks you through the process of deploying your locally developed CrewAI project to the CrewAI Enterprise platform,
transforming it into a production-ready API endpoint.
</Tip>
<iframe
width="100%"
height="400"
@@ -22,7 +22,7 @@ transforming it into a production-ready API endpoint.
allowfullscreen
></iframe>
### Prerequisites
## Prerequisites
Before starting the deployment process, make sure you have:
@@ -35,159 +35,138 @@ For a quick reference project, you can clone our example repository at [github.c
</Note>
<Steps>
<Step title="Authenticate with the Enterprise Platform">
First, you need to authenticate your CLI with the CrewAI Enterprise platform:
### Step 1: Authenticate with the Enterprise Platform
```bash
# If you already have a CrewAI Enterprise account
crewai login
First, you need to authenticate your CLI with the CrewAI Enterprise platform:
# If you're creating a new account
crewai signup
```
```bash
# If you already have a CrewAI Enterprise account
crewai login
When you run either command, the CLI will:
1. Display a URL and a unique device code
2. Open your browser to the authentication page
3. Prompt you to confirm the device
4. Complete the authentication process
# If you're creating a new account
crewai signup
```
Upon successful authentication, you'll see a confirmation message in your terminal!
When you run either command, the CLI will:
1. Display a URL and a unique device code
2. Open your browser to the authentication page
3. Prompt you to confirm the device
4. Complete the authentication process
</Step>
Upon successful authentication, you'll see a confirmation message in your terminal!
<Step title="Create a Deployment">
### Step 2: Create a Deployment
From your project directory, run:
From your project directory, run:
```bash
crewai deploy create
```
```bash
crewai deploy create
```
This command will:
1. Detect your GitHub repository information
2. Identify environment variables in your local `.env` file
3. Securely transfer these variables to the Enterprise platform
4. Create a new deployment with a unique identifier
This command will:
1. Detect your GitHub repository information
2. Identify environment variables in your local `.env` file
3. Securely transfer these variables to the Enterprise platform
4. Create a new deployment with a unique identifier
On successful creation, you'll see a message like:
```shell
Deployment created successfully!
Name: your_project_name
Deployment ID: 01234567-89ab-cdef-0123-456789abcdef
Current Status: Deploy Enqueued
```
On successful creation, you'll see a message like:
```shell
Deployment created successfully!
Name: your_project_name
Deployment ID: 01234567-89ab-cdef-0123-456789abcdef
Current Status: Deploy Enqueued
```
</Step>
### Step 3: Monitor Deployment Progress
<Step title="Monitor Deployment Progress">
Track the deployment status with:
Track the deployment status with:
```bash
crewai deploy status
```
```bash
crewai deploy status
```
For detailed logs of the build process:
For detailed logs of the build process:
```bash
crewai deploy logs
```
```bash
crewai deploy logs
```
<Tip>
The first deployment typically takes 10-15 minutes as it builds the container images. Subsequent deployments are much faster.
</Tip>
<Tip>
The first deployment typically takes 10-15 minutes as it builds the container images. Subsequent deployments are much faster.
</Tip>
</Step>
</Steps>
## Additional CLI Commands
### Additional CLI Commands
The CrewAI CLI offers several commands to manage your deployments:
```bash
# List all your deployments
crewai deploy list
```bash
# List all your deployments
crewai deploy list
# Get the status of your deployment
crewai deploy status
# Get the status of your deployment
crewai deploy status
# View the logs of your deployment
crewai deploy logs
# View the logs of your deployment
crewai deploy logs
# Push updates after code changes
crewai deploy push
# Push updates after code changes
crewai deploy push
# Remove a deployment
crewai deploy remove <deployment_id>
```
# Remove a deployment
crewai deploy remove <deployment_id>
```
## Option 2: Deploy Directly via Web Interface
You can also deploy your crews directly through the CrewAI Enterprise web interface by connecting your GitHub account. This approach doesn't require using the CLI on your local machine.
<Steps>
### Step 1: Pushing to GitHub
<Step title="Pushing to GitHub">
First, you need to push your crew to a GitHub repository. If you haven't created a crew yet, you can [follow this tutorial](/quickstart).
You need to push your crew to a GitHub repository. If you haven't created a crew yet, you can [follow this tutorial](/quickstart).
### Step 2: Connecting GitHub to CrewAI Enterprise
</Step>
1. Log in to [CrewAI Enterprise](https://app.crewai.com)
2. Click on the button "Connect GitHub"
<Step title="Connecting GitHub to CrewAI Enterprise">
<Frame>
![Connect GitHub Button](/images/enterprise/connect-github.png)
</Frame>
1. Log in to [CrewAI Enterprise](https://app.crewai.com)
2. Click on the button "Connect GitHub"
### Step 3: Select the Repository
<Frame>
![Connect GitHub Button](/images/enterprise/connect-github.png)
</Frame>
After connecting your GitHub account, you'll be able to select which repository to deploy:
</Step>
<Frame>
![Select Repository](/images/enterprise/select-repo.png)
</Frame>
<Step title="Select the Repository">
### Step 4: Set Environment Variables
After connecting your GitHub account, you'll be able to select which repository to deploy:
Before deploying, you'll need to set up your environment variables to connect to your LLM provider or other services:
<Frame>
![Select Repository](/images/enterprise/select-repo.png)
</Frame>
1. You can add variables individually or in bulk
2. Enter your environment variables in `KEY=VALUE` format (one per line)
</Step>
<Frame>
![Set Environment Variables](/images/enterprise/set-env-variables.png)
</Frame>
<Step title="Set Environment Variables">
### Step 5: Deploy Your Crew
Before deploying, you'll need to set up your environment variables to connect to your LLM provider or other services:
1. Click the "Deploy" button to start the deployment process
2. You can monitor the progress through the progress bar
3. The first deployment typically takes around 10-15 minutes; subsequent deployments will be faster
1. You can add variables individually or in bulk
2. Enter your environment variables in `KEY=VALUE` format (one per line)
<Frame>
![Deploy Progress](/images/enterprise/deploy-progress.png)
</Frame>
<Frame>
![Set Environment Variables](/images/enterprise/set-env-variables.png)
</Frame>
</Step>
<Step title="Deploy Your Crew">
1. Click the "Deploy" button to start the deployment process
2. You can monitor the progress through the progress bar
3. The first deployment typically takes around 10-15 minutes; subsequent deployments will be faster
<Frame>
![Deploy Progress](/images/enterprise/deploy-progress.png)
</Frame>
Once deployment is complete, you'll see:
- Your crew's unique URL
- A Bearer token to protect your crew API
- A "Delete" button if you need to remove the deployment
</Step>
</Steps>
Once deployment is complete, you'll see:
- Your crew's unique URL
- A Bearer token to protect your crew API
- A "Delete" button if you need to remove the deployment
### Interact with Your Deployed Crew
@@ -214,7 +193,7 @@ From the Enterprise dashboard, you can:
3. Enter the required inputs in the modal that appears
4. Monitor progress as the execution moves through the pipeline
### Monitoring and Analytics
## Monitoring and Analytics
The Enterprise platform provides comprehensive observability features:
@@ -223,7 +202,7 @@ The Enterprise platform provides comprehensive observability features:
- **Metrics**: Token usage, execution times, and costs
- **Timeline View**: Visual representation of task sequences
### Advanced Features
## Advanced Features
The Enterprise platform also offers:

View File

@@ -4,7 +4,7 @@ description: "Kickoff a Crew on CrewAI Enterprise"
icon: "flag-checkered"
---
## Overview
# Kickoff a Crew on CrewAI Enterprise
Once you've deployed your crew to the CrewAI Enterprise platform, you can kickoff executions through the web interface or the API. This guide covers both approaches.

View File

@@ -8,10 +8,6 @@ icon: "globe"
CrewAI Enterprise provides a platform for deploying, monitoring, and scaling your crews and agents in a production environment.
<Frame>
<img src="/images/enterprise/crewai-enterprise-dashboard.png" alt="CrewAI Enterprise Dashboard" />
</Frame>
CrewAI Enterprise extends the power of the open-source framework with features designed for production deployments, collaboration, and scalability. Deploy your crews to a managed infrastructure and monitor their execution in real-time.
## Key Features
@@ -56,43 +52,15 @@ CrewAI Enterprise extends the power of the open-source framework with features d
<Steps>
<Step title="Sign up for an account">
Create your account at [app.crewai.com](https://app.crewai.com)
<Card
title="Sign Up"
icon="user"
href="https://app.crewai.com/signup"
>
Sign Up
</Card>
</Step>
<Step title="Create your first crew">
Use code or Crew Studio to create your crew
<Card
title="Create Crew"
icon="paintbrush"
href="/enterprise/guides/create-crew"
>
Create Crew
</Card>
</Step>
<Step title="Deploy your crew">
Deploy your crew to the Enterprise platform
<Card
title="Deploy Crew"
icon="rocket"
href="/enterprise/guides/deploy-crew"
>
Deploy Crew
</Card>
</Step>
<Step title="Access your crew">
Integrate with your crew via the generated API endpoints
<Card
title="API Access"
icon="code"
href="/enterprise/guides/use-crew-api"
>
Use the Crew API
</Card>
</Step>
</Steps>

View File

@@ -93,6 +93,12 @@ icon: "code"
<Card href="https://docs.crewai.com/concepts/memory" icon="brain">CrewAI Memory</Card>
</Accordion>
<Accordion title="How can I create custom tools for my CrewAI agents?">
You can create custom tools by subclassing the `BaseTool` class provided by CrewAI or by using the tool decorator. Subclassing involves defining a new class that inherits from `BaseTool`, specifying the name, description, and the `_run` method for operational logic. The tool decorator allows you to create a `Tool` object directly with the required attributes and a functional logic.
Click here for more details:
<Card href="https://docs.crewai.com/how-to/create-custom-tools" icon="code">CrewAI Tools</Card>
</Accordion>
<Accordion title="How do I use Output Pydantic in a Task?">
To use Output Pydantic in a task, you need to define the expected output of the task as a Pydantic model. Here's an example:
<Steps>
@@ -172,793 +178,4 @@ icon: "code"
allowfullscreen></iframe>
</Frame>
</Accordion>
<Accordion title="How can I create custom tools for my CrewAI agents?">
You can create custom tools by subclassing the `BaseTool` class provided by CrewAI or by using the tool decorator. Subclassing involves defining a new class that inherits from `BaseTool`, specifying the name, description, and the `_run` method for operational logic. The tool decorator allows you to create a `Tool` object directly with the required attributes and a functional logic.
Click here for more details:
<Card href="https://docs.crewai.com/how-to/create-custom-tools" icon="code">CrewAI Tools</Card>
</Accordion>
<Accordion title="How to Kickoff a Crew from Slack">
This guide explains how to start a crew directly from Slack using the CrewAI integration.
**Prerequisites:**
<ul>
<li>CrewAI integration installed and connected to your Slack workspace</li>
<li>At least one crew configured in CrewAI</li>
</ul>
**Steps:**
<Steps>
<Step title="Ensure the CrewAI Slack integration is set up">
In the CrewAI dashboard, navigate to the **Integrations** section.
<Frame>
<img src="/images/enterprise/slack-integration.png" alt="CrewAI Slack Integration" />
</Frame>
Verify that Slack is listed and is connected.
</Step>
<Step title="Open your Slack channel">
- Navigate to the channel where you want to kickoff the crew.
- Type the slash command "**/kickoff**" to initiate the crew kickoff process.
- You should see a "**Kickoff crew**" appear as you type:
<Frame>
<img src="/images/enterprise/kickoff-slack-crew.png" alt="Kickoff crew" />
</Frame>
- Press Enter or select the "**Kickoff crew**" option. A dialog box titled "**Kickoff an AI Crew**" will appear.
</Step>
<Step title="Select the crew you want to start">
- In the dropdown menu labeled "**Select of the crews online:**", choose the crew you want to start.
- In the example below, "**prep-for-meeting**" is selected:
<Frame>
<img src="/images/enterprise/kickoff-slack-crew-dropdown.png" alt="Kickoff crew dropdown" />
</Frame>
- If your crew requires any inputs, click the "**Add Inputs**" button to provide them.
<Note>
The "**Add Inputs**" button is shown in the example above but is not yet clicked.
</Note>
</Step>
<Step title="Click Kickoff and wait for the crew to complete">
- Once you've selected the crew and added any necessary inputs, click "**Kickoff**" to start the crew.
<Frame>
<img src="/images/enterprise/kickoff-slack-crew-kickoff.png" alt="Kickoff crew" />
</Frame>
- The crew will start executing and you will see the results in the Slack channel.
<Frame>
<img src="/images/enterprise/kickoff-slack-crew-results.png" alt="Kickoff crew results" />
</Frame>
</Step>
</Steps>
<Tip>
- Make sure you have the necessary permissions to use the `/kickoff` command in your Slack workspace.
- If you don't see your desired crew in the dropdown, ensure it's properly configured and online in CrewAI.
</Tip>
</Accordion>
<Accordion title="How to export and use a React Component">
Click on the ellipsis (three dots on the right of your deployed crew) and select the export option and save the file locally. We will be using `CrewLead.jsx` for our example.
<Frame>
<img src="/images/enterprise/export-react-component.png" alt="Export React Component" />
</Frame>
To run this React component locally, you'll need to set up a React development environment and integrate this component into a React project. Here's a step-by-step guide to get you started:
<Steps>
<Step title="Install Node.js">
- Download and install Node.js from the official website: https://nodejs.org/
- Choose the LTS (Long Term Support) version for stability.
</Step>
<Step title="Create a new React project">
- Open Command Prompt or PowerShell
- Navigate to the directory where you want to create your project
- Run the following command to create a new React project:
```bash
npx create-react-app my-crew-app
```
- Change into the project directory:
```bash
cd my-crew-app
```
</Step>
<Step title="Install necessary dependencies">
```bash
npm install react-dom
```
</Step>
<Step title="Create the CrewLead component">
- Move the downloaded file `CrewLead.jsx` into the `src` folder of your project,
</Step>
<Step title="Modify your `App.js` to use the `CrewLead` component">
- Open `src/App.js`
- Replace its contents with something like this:
```jsx
import React from 'react';
import CrewLead from './CrewLead';
function App() {
return (
<div className="App">
<CrewLead baseUrl="YOUR_API_BASE_URL" bearerToken="YOUR_BEARER_TOKEN" />
</div>
);
}
export default App;
```
- Replace `YOUR_API_BASE_URL` and `YOUR_BEARER_TOKEN` with the actual values for your API.
</Step>
<Step title="Start the development server">
- In your project directory, run:
```bash
npm start
```
- This will start the development server, and your default web browser should open automatically to http://localhost:3000, where you'll see your React app running.
</Step>
</Steps>
You can then customise the `CrewLead.jsx` to add color, title etc
<Frame>
<img src="/images/enterprise/customise-react-component.png" alt="Customise React Component" />
</Frame>
<Frame>
<img src="/images/enterprise/customise-react-component-2.png" alt="Customise React Component" />
</Frame>
</Accordion>
<Accordion title="How to Invite Team Members to Your CrewAI Enterprise Organization">
As an administrator of a CrewAI Enterprise account, you can easily invite new team members to join your organization. This article will guide you through the process step-by-step.
<Steps>
<Step title="Access the Settings Page">
- Log in to your CrewAI Enterprise account
- Look for the gear icon (⚙️) in the top right corner of the dashboard
- Click on the gear icon to access the **Settings** page:
<Frame>
<img src="/images/enterprise/settings-page.png" alt="Settings Page" />
</Frame>
</Step>
<Step title="Navigate to the Members Section">
- On the Settings page, you'll see a `General configuration` header
- Below this, find and click on the `Members` tab
</Step>
<Step title="Invite New Members">
- In the Members section, you'll see a list of current members (including yourself)
- At the bottom of the list, locate the `Email` input field
- Enter the email address of the person you want to invite
- Click the `Invite` button next to the email field
</Step>
<Step title="Repeat as Needed">
- You can repeat this process to invite multiple team members
- Each invited member will receive an email invitation to join your organization
</Step>
<Step title="Important Notes">
- Only users with administrative privileges can invite new members
- Ensure you have the correct email addresses for your team members
- Invited members will need to accept the invitation to join your organization
- You may want to inform your team members to check their email (including spam folders) for the invitation
</Step>
</Steps>
By following these steps, you can easily expand your team and collaborate more effectively within your CrewAI Enterprise organization.
</Accordion>
<Accordion title="Using Webhooks in CrewAI Enterprise">
CrewAI Enterprise allows you to automate your workflow using webhooks.
This article will guide you through the process of setting up and using webhooks to kickoff your crew execution, with a focus on integration with ActivePieces,
a workflow automation platform similar to Zapier and Make.com. We will be setting up webhooks in the CrewAI Enterprise UI.
<Steps>
<Step title="Accessing the Kickoff Interface">
- Navigate to the CrewAI Enterprise dashboard
- Look for the `/kickoff` section, which is used to start the crew execution
<Frame>
<img src="/images/enterprise/kickoff-interface.png" alt="Kickoff Interface" />
</Frame>
</Step>
<Step title="Configuring the JSON Content">
In the JSON Content section, you'll need to provide the following information:
- **inputs**: A JSON object containing:
- `company`: The name of the company (e.g., "tesla")
- `product_name`: The name of the product (e.g., "crewai")
- `form_response`: The type of response (e.g., "financial")
- `icp_description`: A brief description of the Ideal Customer Profile
- `product_description`: A short description of the product
- `taskWebhookUrl`, `stepWebhookUrl`, `crewWebhookUrl`: URLs for various webhook endpoints (ActivePieces, Zapier, Make.com or another compatible platform)
</Step>
<Step title="Integrating with ActivePieces">
In this example we will be using ActivePieces. You can use other platforms such as Zapier and Make.com
To integrate with ActivePieces:
1. Set up a new flow in ActivePieces
2. Add a trigger (e.g., `Every Day` schedule)
<Frame>
<img src="/images/enterprise/activepieces-trigger.png" alt="ActivePieces Trigger" />
</Frame>
3. Add an HTTP action step
- Set the action to `Send HTTP request`
- Use `POST` as the method
- Set the URL to your CrewAI Enterprise kickoff endpoint
- Add necessary headers (e.g., `Bearer Token`)
<Frame>
<img src="/images/enterprise/activepieces-headers.png" alt="ActivePieces Headers" />
</Frame>
- In the body, include the JSON content as configured in step 2
<Frame>
<img src="/images/enterprise/activepieces-body.png" alt="ActivePieces Body" />
</Frame>
- The crew will then kickoff at the pre-defined time.
</Step>
<Step title="Setting Up the Webhook">
1. Create a new flow in ActivePieces and name it
<Frame>
<img src="/images/enterprise/activepieces-flow.png" alt="ActivePieces Flow" />
</Frame>
2. Add a webhook step as the trigger:
- Select `Catch Webhook` as the trigger type
- This will generate a unique URL that will receive HTTP requests and trigger your flow
<Frame>
<img src="/images/enterprise/activepieces-webhook.png" alt="ActivePieces Webhook" />
</Frame>
- Configure the email to use crew webhook body text
<Frame>
<img src="/images/enterprise/activepieces-email.png" alt="ActivePieces Email" />
</Frame>
</Step>
<Step title="Generated output">
1. `stepWebhookUrl` - Callback that will be executed upon each agent inner thought
```json
{
"action": "**Preliminary Research Report on the Financial Industry for crewai Enterprise Solution**\n1. Industry Overview and Trends\nThe financial industry in ....\nConclusion:\nThe financial industry presents a fertile ground for implementing AI solutions like crewai, particularly in areas such as digital customer engagement, risk management, and regulatory compliance. Further engagement with the lead is recommended to better tailor the crewai solution to their specific needs and scale.",
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0"
}
```
2. `taskWebhookUrl` - Callback that will be executed upon the end of each task
```json
{
"description": "Using the information gathered from the lead's data, conduct preliminary research on the lead's industry, company background, and potential use cases for crewai. Focus on finding relevant data that can aid in scoring the lead and planning a strategy to pitch them crewai.The financial industry presents a fertile ground for implementing AI solutions like crewai, particularly in areas such as digital customer engagement, risk management, and regulatory compliance. Further engagement with the lead is recommended to better tailor the crewai solution to their specific needs and scale.",
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0"
}
```
3. `crewWebhookUrl` - Callback that will be executed upon the end of the crew execution
```json
{
"task_id": "97eba64f-958c-40a0-b61c-625fe635a3c0",
"result": {
"lead_score": "Customer service enhancement, and compliance are particularly relevant.",
"talking_points": [
"Highlight how crewai's AI solutions can transform customer service with automated, personalized experiences and 24/7 support, improving both customer satisfaction and operational efficiency.",
"Discuss crewai's potential to help the institution achieve its sustainability goals through better data analysis and decision-making, contributing to responsible investing and green initiatives.",
"Emphasize crewai's ability to enhance compliance with evolving regulations through efficient data processing and reporting, reducing the risk of non-compliance penalties.",
"Stress the adaptability of crewai to support both extensive multinational operations and smaller, targeted projects, ensuring the solution grows with the institution's needs."
]
}
}
```
</Step>
</Steps>
</Accordion>
<Accordion title="How to use the crewai custom GPT to create a crew">
<Steps>
<Step title="Navigate to the CrewAI custom GPT">
Click here https://chatgpt.com/g/g-qqTuUWsBY-crewai-assistant to access the CrewAI custom GPT
<Card href="https://chatgpt.com/g/g-qqTuUWsBY-crewai-assistant" icon="comments">CrewAI custom GPT</Card>
</Step>
<Step title="Describe your project idea">
For example:
```text
Suggest some agents and tasks to retrieve LinkedIn profile details for a given person and a domain.
```
</Step>
<Step title="The GPT will provide you with a list of suggested agents and tasks">
Here's an example of the response you will get:
<Frame>
<img src="/images/enterprise/crewai-custom-gpt-1.png" alt="CrewAI custom GPT 1" />
</Frame>
</Step>
<Step title="Create the project structure in your terminal by entering:">
```bash
crewai create crew linkedin-profile
```
This will create a new crew called `linkedin-profile` in the current directory.
Follow the full instructions in the https://docs.crewai.com/quickstart to create a crew.
<Card href="https://docs.crewai.com/quickstart" icon="code">CrewAI Docs</Card>
</Step>
<Step title="Ask the GPT to convert the agents and tasks to YAML format.">
Here's an example of the final output you will have to save in the `agents.yaml` and `tasks.yaml` files:
<Frame>
<img src="/images/enterprise/crewai-custom-gpt-2.png" alt="CrewAI custom GPT 2" />
</Frame>
- Now replace the `agents.yaml` and `tasks.yaml` with the above code
- Ask GPT to create the custom LinkedIn Tool
- Ask the GPT to put everything together into the `crew.py` file
- You will now have a fully working crew.
</Step>
</Steps>
</Accordion>
<Accordion title="How to generate images using Dall-E">
CrewAI supports integration with OpenAI's DALL-E, allowing your AI agents to generate images as part of their tasks. This guide will walk you through how to set up and use the DALL-E tool in your CrewAI projects.
**Prerequisites**
- crewAI installed (latest version)
- OpenAI API key with access to DALL-E
**Setting Up the DALL-E Tool**
To use the DALL-E tool in your CrewAI project, follow these steps:
<Steps>
<Step title="Import the DALL-E tool">
```python
from crewai_tools import DallETool
```
</Step>
<Step title="Add the DALL-E tool to your agent configuration">
```python
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
tools=[SerperDevTool(), DallETool()], # Add DallETool to the list of tools
allow_delegation=False,
verbose=True
)
```
</Step>
</Steps>
**Using the DALL-E Tool**
Once you've added the DALL-E tool to your agent, it can generate images based on text prompts.
The tool will return a URL to the generated image, which can be used in the agent's output or passed to other agents for further processing.
Example usage within a task:
```YAML
role: >
LinkedIn Profile Senior Data Researcher
goal: >
Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}
Generate a Dall-e image based on domain {domain}
backstory: >
You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.
Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting
professional information clearly and concisely.
```
The agent with the DALL-E tool will be able to generate the image and provide a URL in its response. You can then download the image.
<Frame>
<img src="/images/enterprise/dall-e-image.png" alt="DALL-E Image" />
</Frame>
**Best Practices**
1. Be specific in your image generation prompts to get the best results.
2. Remember that image generation can take some time, so factor this into your task planning.
3. Always comply with OpenAI's usage policies when generating images.
**Troubleshooting**
1. Ensure your OpenAI API key has access to DALL-E.
2. Check that you're using the latest version of crewAI and crewai-tools.
3. Verify that the DALL-E tool is correctly added to the agent's tool list.
</Accordion>
<Accordion title="How to use Annotations in crew.py">
This guide explains how to use annotations to properly reference **agents**, **tasks**, and other components in the `crew.py` file.
**Introduction**
Annotations in the framework are used to decorate classes and methods, providing metadata and functionality to various components of your crew.
These annotations help in organizing and structuring your code, making it more readable and maintainable.
**Available Annotations**
The CrewAI framework provides the following annotations:
- `@CrewBase`: Used to decorate the main crew class.
- `@agent`: Decorates methods that define and return Agent objects.
- `@task`: Decorates methods that define and return Task objects.
- `@crew`: Decorates the method that creates and returns the Crew object.
- `@llm`: Decorates methods that initialize and return Language Model objects.
- `@tool`: Decorates methods that initialize and return Tool objects.
- `@callback`: (Not shown in the example, but available) Used for defining callback methods.
- `@output_json`: (Not shown in the example, but available) Used for methods that output JSON data.
- `@output_pydantic`: (Not shown in the example, but available) Used for methods that output Pydantic models.
- `@cache_handler`: (Not shown in the example, but available) Used for defining cache handling methods.
**Usage Examples**
Let's go through examples of how to use these annotations based on the provided LinkedinProfileCrew class:
**1. Crew Base Class**
```python
@CrewBase
class LinkedinProfileCrew():
"""LinkedinProfile crew"""
agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'
```
The `@CrewBase` annotation is used to decorate the main crew class.
This class typically contains configurations and methods for creating agents, tasks, and the crew itself.
**2. Tool Definition**
```python
@tool
def myLinkedInProfileTool(self):
return LinkedInProfileTool()
```
The `@tool` annotation is used to decorate methods that return tool objects. These tools can be used by agents to perform specific tasks.
**3. LLM Definition**
```python
@llm
def groq_llm(self):
api_key = os.getenv('api_key')
return ChatGroq(api_key=api_key, temperature=0, model_name="mixtral-8x7b-32768")
```
The `@llm` annotation is used to decorate methods that initialize and return Language Model objects. These LLMs are used by agents for natural language processing tasks.
**4. Agent Definition**
```python
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher']
)
```
The `@agent` annotation is used to decorate methods that define and return Agent objects.
**5. Task Definition**
```python
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_linkedin_task'],
agent=self.researcher()
)
```
The `@task` annotation is used to decorate methods that define and return Task objects. These methods specify the task configuration and the agent responsible for the task.
**6. Crew Creation**
```python
@crew
def crew(self) -> Crew:
"""Creates the LinkedinProfile crew"""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
```
The `@crew` annotation is used to decorate the method that creates and returns the `Crew` object. This method assembles all the components (agents and tasks) into a functional crew.
**YAML Configuration**
The agent configurations are typically stored in a YAML file. Here's an example of how the `agents.yaml` file might look for the researcher agent:
```yaml
researcher:
role: >
LinkedIn Profile Senior Data Researcher
goal: >
Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}
Generate a Dall-E image based on domain {domain}
backstory: >
You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.
Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting
professional information clearly and concisely.
allow_delegation: False
verbose: True
llm: groq_llm
tools:
- myLinkedInProfileTool
- mySerperDevTool
- myDallETool
```
This YAML configuration corresponds to the researcher agent defined in the `LinkedinProfileCrew` class. The configuration specifies the agent's role, goal, backstory, and other properties such as the LLM and tools it uses.
Note how the `llm` and `tools` in the YAML file correspond to the methods decorated with `@llm` and `@tool` in the Python class. This connection allows for a flexible and modular design where you can easily update agent configurations without changing the core code.
**Best Practices**
- **Consistent Naming**: Use clear and consistent naming conventions for your methods. For example, agent methods could be named after their roles (e.g., researcher, reporting_analyst).
- **Environment Variables**: Use environment variables for sensitive information like API keys.
- **Flexibility**: Design your crew to be flexible by allowing easy addition or removal of agents and tasks.
- **YAML-Code Correspondence**: Ensure that the names and structures in your YAML files correspond correctly to the decorated methods in your Python code.
By following these guidelines and properly using annotations, you can create well-structured and maintainable crews using the CrewAI framework.
</Accordion>
<Accordion title="How to Integrate CrewAI Enterprise with Zapier">
This guide will walk you through the process of integrating CrewAI Enterprise with Zapier, allowing you to automate workflows between CrewAI Enterprise and other applications.
**Prerequisites**
- A CrewAI Enterprise account
- A Zapier account
- A Slack account (for this specific integration)
**Step-by-Step Guide**
<Steps>
<Step title="Set Up the Slack Trigger">
- In Zapier, create a new Zap.
<Frame>
<img src="/images/enterprise/zapier-1.png" alt="Zapier 1" />
</Frame>
</Step>
<Step title="Choose Slack as your trigger app.">
<Frame>
<img src="/images/enterprise/zapier-2.png" alt="Zapier 2" />
</Frame>
- Select `New Pushed Message` as the Trigger Event.
- Connect your Slack account if you haven't already.
</Step>
<Step title="Configure the CrewAI Enterprise Action">
- Add a new action step to your Zap.
- Choose CrewAI+ as your action app and Kickoff as the Action Event
<Frame>
<img src="/images/enterprise/zapier-3.png" alt="Zapier 5" />
</Frame>
</Step>
<Step title="Connect your CrewAI Enterprise account.">
- Connect your CrewAI Enterprise account.
- Select the appropriate Crew for your workflow.
<Frame>
<img src="/images/enterprise/zapier-4.png" alt="Zapier 6" />
</Frame>
- Configure the inputs for the Crew using the data from the Slack message.
</Step>
<Step title="Format the CrewAI Enterprise Output">
- Add another action step to format the text output from CrewAI Enterprise.
- Use Zapier's formatting tools to convert the Markdown output to HTML.
<Frame>
<img src="/images/enterprise/zapier-5.png" alt="Zapier 8" />
</Frame>
<Frame>
<img src="/images/enterprise/zapier-6.png" alt="Zapier 9" />
</Frame>
</Step>
<Step title="Send the Output via Email">
- Add a final action step to send the formatted output via email.
- Choose your preferred email service (e.g., Gmail, Outlook).
- Configure the email details, including recipient, subject, and body.
- Insert the formatted CrewAI Enterprise output into the email body.
<Frame>
<img src="/images/enterprise/zapier-7.png" alt="Zapier 7" />
</Frame>
</Step>
<Step title="Kick Off the crew from Slack">
- Enter the text in your Slack channel
<Frame>
<img src="/images/enterprise/zapier-7b.png" alt="Zapier 10" />
</Frame>
- Select the 3 ellipsis button and then chose Push to Zapier
<Frame>
<img src="/images/enterprise/zapier-8.png" alt="Zapier 11" />
</Frame>
</Step>
<Step title="Select the crew and then Push to Kick Off">
<Frame>
<img src="/images/enterprise/zapier-9.png" alt="Zapier 12" />
</Frame>
</Step>
</Steps>
**Tips for Success**
- Ensure that your CrewAI Enterprise inputs are correctly mapped from the Slack message.
- Test your Zap thoroughly before turning it on to catch any potential issues.
- Consider adding error handling steps to manage potential failures in the workflow.
By following these steps, you'll have successfully integrated CrewAI Enterprise with Zapier, allowing for automated workflows triggered by Slack messages and resulting in email notifications with CrewAI Enterprise output.
</Accordion>
<Accordion title="How to Integrate CrewAI Enterprise with HubSpot">
This guide provides a step-by-step process to integrate CrewAI Enterprise with HubSpot, enabling you to initiate crews directly from HubSpot Workflows.
**Prerequisites**
- A CrewAI Enterprise account
- A HubSpot account with the [HubSpot Workflows](https://knowledge.hubspot.com/workflows/create-workflows) feature
**Step-by-Step Guide**
<Steps>
<Step title="Connect your HubSpot account with CrewAI Enterprise">
- Log in to your `CrewAI Enterprise account > Integrations`
- Select `HubSpot` from the list of available integrations
- Choose the HubSpot account you want to integrate with CrewAI Enterprise
- Follow the on-screen prompts to authorize CrewAI Enterprise access to your HubSpot account
- A confirmation message will appear once HubSpot is successfully linked with CrewAI Enterprise
</Step>
<Step title="Create a HubSpot Workflow">
- Log in to your `HubSpot account > Automations > Workflows > New workflow`
- Select the workflow type that fits your needs (e.g., Start from scratch)
- In the workflow builder, click the Plus (+) icon to add a new action.
- Choose `Integrated apps > CrewAI > Kickoff a Crew`.
- Select the Crew you want to initiate.
- Click `Save` to add the action to your workflow
<Frame>
<img src="/images/enterprise/hubspot-workflow-1.png" alt="HubSpot Workflow 1" />
</Frame>
</Step>
<Step title="Use Crew results with other actions">
- After the Kickoff a Crew step, click the Plus (+) icon to add a new action.
- For example, to send an internal email notification, choose `Communications > Send internal email notification`
- In the Body field, click `Insert data`, select `View properties or action outputs from > Action outputs > Crew Result` to include Crew data in the email
<Frame>
<img src="/images/enterprise/hubspot-workflow-2.png" alt="HubSpot Workflow 2" />
</Frame>
- Configure any additional actions as needed
- Review your workflow steps to ensure everything is set up correctly
- Activate the workflow
<Frame>
<img src="/images/enterprise/hubspot-workflow-3.png" alt="HubSpot Workflow 3" />
</Frame>
</Step>
</Steps>
For more detailed information on available actions and customization options, refer to the [HubSpot Workflows Documentation](https://knowledge.hubspot.com/workflows/create-workflows).
</Accordion>
<Accordion title="How to connect Azure OpenAI with Crew Studio?">
1. In Azure, go to `Azure AI Services > select your deployment > open Azure OpenAI Studio`.
2. On the left menu, click `Deployments`. If you dont have one, create a deployment with your desired model.
3. Once created, select your deployment and locate the `Target URI` and `Key` on the right side of the page. Keep this page open, as youll need this information.
<Frame>
<img src="/images/enterprise/azure-openai-studio.png" alt="Azure OpenAI Studio" />
</Frame>
4. In another tab, open `CrewAI Enterprise > LLM Connections`. Name your LLM Connection, select Azure as the provider, and choose the same model you selected in Azure.
5. On the same page, add environment variables from step 3:
- One named `AZURE_DEPLOYMENT_TARGET_URL` (using the Target URI). The URL should look like this: https://your-deployment.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview
- Another named `AZURE_API_KEY` (using the Key).
6. Click `Add Connection` to save your LLM Connection.
7. In `CrewAI Enterprise > Settings > Defaults > Crew Studio LLM Settings`, set the new LLM Connection and model as defaults.
8. Ensure network access settings:
- In Azure, go to `Azure OpenAI > select your deployment`.
- Navigate to `Resource Management > Networking`.
- Ensure that `Allow access from all networks` is enabled. If this setting is restricted, CrewAI may be blocked from accessing your Azure OpenAI endpoint.
You're all set! Crew Studio will now use your Azure OpenAI connection.
</Accordion>
<Accordion title="How to use HITL?">
Human-in-the-Loop (HITL) Instructions
HITL is a powerful approach that combines artificial intelligence with human expertise to enhance decision-making and improve task outcomes. Follow these steps to implement HITL within CrewAI:
<Steps>
<Step title="Configure Your Task">
Set up your task with human input enabled:
<Frame>
<img src="/images/enterprise/crew-human-input.png" alt="Crew Human Input" />
</Frame>
</Step>
<Step title="Provide Webhook URL">
When kicking off your crew, include a webhook URL for human input:
<Frame>
<img src="/images/enterprise/crew-webhook-url.png" alt="Crew Webhook URL" />
</Frame>
</Step>
<Step title="Receive Webhook Notification">
Once the crew completes the task requiring human input, you'll receive a webhook notification containing:
- Execution ID
- Task ID
- Task output
</Step>
<Step title="Review Task Output">
The system will pause in the `Pending Human Input` state. Review the task output carefully.
</Step>
<Step title="Submit Human Feedback">
Call the resume endpoint of your crew with the following information:
<Frame>
<img src="/images/enterprise/crew-resume-endpoint.png" alt="Crew Resume Endpoint" />
</Frame>
<Warning>
**Feedback Impact on Task Execution**:
It's crucial to exercise care when providing feedback, as the entire feedback content will be incorporated as additional context for further task executions.
</Warning>
This means:
- All information in your feedback becomes part of the task's context.
- Irrelevant details may negatively influence it.
- Concise, relevant feedback helps maintain task focus and efficiency.
- Always review your feedback carefully before submission to ensure it contains only pertinent information that will positively guide the task's execution.
</Step>
<Step title="Handle Negative Feedback">
If you provide negative feedback:
- The crew will retry the task with added context from your feedback.
- You'll receive another webhook notification for further review.
- Repeat steps 4-6 until satisfied.
</Step>
<Step title="Execution Continuation">
When you submit positive feedback, the execution will proceed to the next steps.
</Step>
</Steps>
</Accordion>
<Accordion title="How to configure Salesforce with CrewAI Enterprise">
**Salesforce Demo**
Salesforce is a leading customer relationship management (CRM) platform that helps businesses streamline their sales, service, and marketing operations.
<Frame>
<iframe width="100%" height="400" src="https://www.youtube.com/embed/oJunVqjjfu4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</Frame>
</Accordion>
<Accordion title="How can you control the maximum number of requests per minute that the entire crew can perform?">
The `max_rpm` attribute sets the maximum number of requests per minute the crew can perform to avoid rate limits and will override individual agents' `max_rpm` settings if you set it.
</Accordion>
</AccordionGroup>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

View File

Before

Width:  |  Height:  |  Size: 2.4 MiB

After

Width:  |  Height:  |  Size: 2.4 MiB

View File

@@ -0,0 +1,67 @@
import logging
import os
import signal
import sys
import time
from crewai.tools import MCPToolConnector, Tool
def setup_logging():
"""Set up logging configuration."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler()]
)
def handle_exit(signum, frame):
"""Handle exit signals gracefully."""
print("\nExiting...")
sys.exit(0)
def main():
"""Main function to demonstrate MCP SSE tool connection."""
setup_logging()
signal.signal(signal.SIGINT, handle_exit)
print("CrewAI MCP SSE Tool Connection Example")
print("--------------------------------------")
print("This example connects tools to the MCP SSE server.")
print("Make sure you're logged in with 'crewai login' first.")
print("Press Ctrl+C to exit.")
print()
def search(query: str) -> str:
"""Search for information."""
return f"Searching for: {query}"
search_tool = Tool(
name="search",
description="Search for information",
func=search
)
tools = [search_tool]
connector = MCPToolConnector(tools=tools)
try:
print("Connecting to MCP SSE server...")
connector.connect()
print("Connected! Listening for tool events...")
connector.listen()
except KeyboardInterrupt:
print("\nExiting...")
except Exception as e:
print(f"Error: {str(e)}")
finally:
connector.close()
if __name__ == "__main__":
main()

View File

@@ -1,6 +1,6 @@
[project]
name = "crewai"
version = "0.118.0"
version = "0.114.0"
description = "Cutting-edge framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks."
readme = "README.md"
requires-python = ">=3.10,<3.13"
@@ -11,7 +11,7 @@ dependencies = [
# Core Dependencies
"pydantic>=2.4.2",
"openai>=1.13.3",
"litellm==1.68.0",
"litellm==1.60.2",
"instructor>=1.3.3",
# Text Processing
"pdfplumber>=0.11.4",
@@ -45,7 +45,7 @@ Documentation = "https://docs.crewai.com"
Repository = "https://github.com/crewAIInc/crewAI"
[project.optional-dependencies]
tools = ["crewai-tools~=0.42.2"]
tools = ["crewai-tools~=0.40.1"]
embeddings = [
"tiktoken~=0.7.0"
]
@@ -60,7 +60,7 @@ pandas = [
openpyxl = [
"openpyxl>=3.1.5",
]
mem0 = ["mem0ai>=0.1.94"]
mem0 = ["mem0ai>=0.1.29"]
docling = [
"docling>=2.12.0",
]
@@ -85,8 +85,6 @@ dev-dependencies = [
"pytest-asyncio>=0.23.7",
"pytest-subprocess>=1.5.2",
"pytest-recording>=0.13.2",
"pytest-randomly>=3.16.0",
"pytest-timeout>=2.3.1",
]
[project.scripts]

View File

@@ -17,7 +17,7 @@ warnings.filterwarnings(
category=UserWarning,
module="pydantic.main",
)
__version__ = "0.118.0"
__version__ = "0.114.0"
__all__ = [
"Agent",
"Crew",

View File

@@ -1 +0,0 @@
"""LangGraph adapter for crewAI."""

View File

@@ -1 +0,0 @@
"""OpenAI agent adapters for crewAI."""

View File

@@ -201,22 +201,9 @@ def install(context):
@crewai.command()
@click.option(
"--record",
is_flag=True,
help="Record LLM responses for later replay",
)
@click.option(
"--replay",
is_flag=True,
help="Replay from recorded LLM responses without making network calls",
)
def run(record: bool = False, replay: bool = False):
def run():
"""Run the Crew."""
if record and replay:
raise click.UsageError("Cannot use --record and --replay simultaneously")
click.echo("Running the Crew")
run_crew(record=record, replay=replay)
run_crew()
@crewai.command()

View File

@@ -2,7 +2,7 @@ import subprocess
import click
from crewai.cli.utils import get_crews
from crewai.cli.utils import get_crew
def reset_memories_command(
@@ -26,47 +26,35 @@ def reset_memories_command(
"""
try:
if not any([long, short, entity, kickoff_outputs, knowledge, all]):
crew = get_crew()
if not crew:
raise ValueError("No crew found.")
if all:
crew.reset_memories(command_type="all")
click.echo("All memories have been reset.")
return
if not any([long, short, entity, kickoff_outputs, knowledge]):
click.echo(
"No memory type specified. Please specify at least one type to reset."
)
return
crews = get_crews()
if not crews:
raise ValueError("No crew found.")
for crew in crews:
if all:
crew.reset_memories(command_type="all")
click.echo(
f"[Crew ({crew.name if crew.name else crew.id})] Reset memories command has been completed."
)
continue
if long:
crew.reset_memories(command_type="long")
click.echo(
f"[Crew ({crew.name if crew.name else crew.id})] Long term memory has been reset."
)
if short:
crew.reset_memories(command_type="short")
click.echo(
f"[Crew ({crew.name if crew.name else crew.id})] Short term memory has been reset."
)
if entity:
crew.reset_memories(command_type="entity")
click.echo(
f"[Crew ({crew.name if crew.name else crew.id})] Entity memory has been reset."
)
if kickoff_outputs:
crew.reset_memories(command_type="kickoff_outputs")
click.echo(
f"[Crew ({crew.name if crew.name else crew.id})] Latest Kickoff outputs stored has been reset."
)
if knowledge:
crew.reset_memories(command_type="knowledge")
click.echo(
f"[Crew ({crew.name if crew.name else crew.id})] Knowledge has been reset."
)
if long:
crew.reset_memories(command_type="long")
click.echo("Long term memory has been reset.")
if short:
crew.reset_memories(command_type="short")
click.echo("Short term memory has been reset.")
if entity:
crew.reset_memories(command_type="entity")
click.echo("Entity memory has been reset.")
if kickoff_outputs:
crew.reset_memories(command_type="kickoff_outputs")
click.echo("Latest Kickoff outputs stored has been reset.")
if knowledge:
crew.reset_memories(command_type="knowledge")
click.echo("Knowledge has been reset.")
except subprocess.CalledProcessError as e:
click.echo(f"An error occurred while resetting the memories: {e}", err=True)

View File

@@ -14,17 +14,13 @@ class CrewType(Enum):
FLOW = "flow"
def run_crew(record: bool = False, replay: bool = False) -> None:
def run_crew() -> None:
"""
Run the crew or flow by running a command in the UV environment.
Starting from version 0.103.0, this command can be used to run both
standard crews and flows. For flows, it detects the type from pyproject.toml
and automatically runs the appropriate command.
Args:
record (bool, optional): Whether to record LLM responses. Defaults to False.
replay (bool, optional): Whether to replay from recorded LLM responses. Defaults to False.
"""
crewai_version = get_crewai_version()
min_required_version = "0.71.0"
@@ -48,24 +44,17 @@ def run_crew(record: bool = False, replay: bool = False) -> None:
click.echo(f"Running the {'Flow' if is_flow else 'Crew'}")
# Execute the appropriate command
execute_command(crew_type, record, replay)
execute_command(crew_type)
def execute_command(crew_type: CrewType, record: bool = False, replay: bool = False) -> None:
def execute_command(crew_type: CrewType) -> None:
"""
Execute the appropriate command based on crew type.
Args:
crew_type: The type of crew to run
record: Whether to record LLM responses
replay: Whether to replay from recorded LLM responses
"""
command = ["uv", "run", "kickoff" if crew_type == CrewType.FLOW else "run_crew"]
if record:
command.append("--record")
if replay:
command.append("--replay")
try:
subprocess.run(command, capture_output=False, text=True, check=True)

View File

@@ -5,7 +5,7 @@ description = "{{name}} using crewAI"
authors = [{ name = "Your Name", email = "you@example.com" }]
requires-python = ">=3.10,<3.13"
dependencies = [
"crewai[tools]>=0.118.0,<1.0.0"
"crewai[tools]>=0.114.0,<1.0.0"
]
[project.scripts]

View File

@@ -1 +0,0 @@
"""Poem crew template."""

View File

@@ -5,7 +5,7 @@ description = "{{name}} using crewAI"
authors = [{ name = "Your Name", email = "you@example.com" }]
requires-python = ">=3.10,<3.13"
dependencies = [
"crewai[tools]>=0.118.0,<1.0.0",
"crewai[tools]>=0.114.0,<1.0.0",
]
[project.scripts]

View File

@@ -5,7 +5,7 @@ description = "Power up your crews with {{folder_name}}"
readme = "README.md"
requires-python = ">=3.10,<3.13"
dependencies = [
"crewai[tools]>=0.118.0"
"crewai[tools]>=0.114.0"
]
[tool.crewai]

View File

@@ -2,8 +2,7 @@ import os
import shutil
import sys
from functools import reduce
from inspect import isfunction, ismethod
from typing import Any, Dict, List, get_type_hints
from typing import Any, Dict, List
import click
import tomli
@@ -11,7 +10,6 @@ from rich.console import Console
from crewai.cli.constants import ENV_VARS
from crewai.crew import Crew
from crewai.flow import Flow
if sys.version_info >= (3, 11):
import tomllib
@@ -252,11 +250,11 @@ def write_env_file(folder_path, env_vars):
file.write(f"{key}={value}\n")
def get_crews(crew_path: str = "crew.py", require: bool = False) -> list[Crew]:
"""Get the crew instances from the a file."""
crew_instances = []
def get_crew(crew_path: str = "crew.py", require: bool = False) -> Crew | None:
"""Get the crew instance from the crew.py file."""
try:
import importlib.util
import os
for root, _, files in os.walk("."):
if crew_path in files:
@@ -273,10 +271,12 @@ def get_crews(crew_path: str = "crew.py", require: bool = False) -> list[Crew]:
spec.loader.exec_module(module)
for attr_name in dir(module):
module_attr = getattr(module, attr_name)
attr = getattr(module, attr_name)
try:
crew_instances.extend(fetch_crews(module_attr))
if callable(attr) and hasattr(attr, "crew"):
crew_instance = attr().crew()
return crew_instance
except Exception as e:
print(f"Error processing attribute {attr_name}: {e}")
continue
@@ -286,6 +286,7 @@ def get_crews(crew_path: str = "crew.py", require: bool = False) -> list[Crew]:
import traceback
print(f"Traceback: {traceback.format_exc()}")
except (ImportError, AttributeError) as e:
if require:
console.print(
@@ -299,6 +300,7 @@ def get_crews(crew_path: str = "crew.py", require: bool = False) -> list[Crew]:
if require:
console.print("No valid Crew instance found in crew.py", style="bold red")
raise SystemExit
return None
except Exception as e:
if require:
@@ -306,36 +308,4 @@ def get_crews(crew_path: str = "crew.py", require: bool = False) -> list[Crew]:
f"Unexpected error while loading crew: {str(e)}", style="bold red"
)
raise SystemExit
return crew_instances
def get_crew_instance(module_attr) -> Crew | None:
if (
callable(module_attr)
and hasattr(module_attr, "is_crew_class")
and module_attr.is_crew_class
):
return module_attr().crew()
if (ismethod(module_attr) or isfunction(module_attr)) and get_type_hints(
module_attr
).get("return") is Crew:
return module_attr()
elif isinstance(module_attr, Crew):
return module_attr
else:
return None
def fetch_crews(module_attr) -> list[Crew]:
crew_instances: list[Crew] = []
if crew_instance := get_crew_instance(module_attr):
crew_instances.append(crew_instance)
if isinstance(module_attr, type) and issubclass(module_attr, Flow):
instance = module_attr()
for attr_name in dir(instance):
attr = getattr(instance, attr_name)
if crew_instance := get_crew_instance(attr):
crew_instances.append(crew_instance)
return crew_instances

View File

@@ -6,17 +6,7 @@ import warnings
from concurrent.futures import Future
from copy import copy as shallow_copy
from hashlib import md5
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Set,
Tuple,
Union,
cast,
)
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union, cast
from pydantic import (
UUID4,
@@ -34,7 +24,6 @@ from crewai.agent import Agent
from crewai.agents.agent_builder.base_agent import BaseAgent
from crewai.agents.cache import CacheHandler
from crewai.crews.crew_output import CrewOutput
from crewai.flow.flow_trackable import FlowTrackable
from crewai.knowledge.knowledge import Knowledge
from crewai.knowledge.source.base_knowledge_source import BaseKnowledgeSource
from crewai.llm import LLM, BaseLLM
@@ -80,7 +69,7 @@ from crewai.utilities.training_handler import CrewTrainingHandler
warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")
class Crew(FlowTrackable, BaseModel):
class Crew(BaseModel):
"""
Represents a group of agents, defining how they should collaborate and the tasks they should perform.
@@ -244,15 +233,6 @@ class Crew(FlowTrackable, BaseModel):
default_factory=SecurityConfig,
description="Security configuration for the crew, including fingerprinting.",
)
record_mode: bool = Field(
default=False,
description="Whether to record LLM responses for later replay.",
)
replay_mode: bool = Field(
default=False,
description="Whether to replay from recorded LLM responses without making network calls.",
)
_llm_response_cache_handler: Optional[Any] = PrivateAttr(default=None)
@field_validator("id", mode="before")
@classmethod
@@ -324,9 +304,7 @@ class Crew(FlowTrackable, BaseModel):
"""Initialize private memory attributes."""
self._external_memory = (
# External memory doesnt support a default value since it was designed to be managed entirely externally
self.external_memory.set_crew(self)
if self.external_memory
else None
self.external_memory.set_crew(self) if self.external_memory else None
)
self._long_term_memory = self.long_term_memory
@@ -355,7 +333,6 @@ class Crew(FlowTrackable, BaseModel):
embedder=self.embedder,
collection_name="crew",
)
self.knowledge.add_sources()
except Exception as e:
self._logger.log(
@@ -642,19 +619,6 @@ class Crew(FlowTrackable, BaseModel):
self._task_output_handler.reset()
self._logging_color = "bold_purple"
if self.record_mode and self.replay_mode:
raise ValueError("Cannot use both record_mode and replay_mode at the same time")
if self.record_mode or self.replay_mode:
from crewai.utilities.llm_response_cache_handler import (
LLMResponseCacheHandler,
)
self._llm_response_cache_handler = LLMResponseCacheHandler()
if self.record_mode:
self._llm_response_cache_handler.start_recording()
elif self.replay_mode:
self._llm_response_cache_handler.start_replaying()
if inputs is not None:
self._inputs = inputs
self._interpolate_inputs(inputs)
@@ -673,12 +637,6 @@ class Crew(FlowTrackable, BaseModel):
if not agent.step_callback: # type: ignore # "BaseAgent" has no attribute "step_callback"
agent.step_callback = self.step_callback # type: ignore # "BaseAgent" has no attribute "step_callback"
if self._llm_response_cache_handler:
if hasattr(agent, "llm") and agent.llm:
agent.llm.set_response_cache_handler(self._llm_response_cache_handler)
if hasattr(agent, "function_calling_llm") and agent.function_calling_llm:
agent.function_calling_llm.set_response_cache_handler(self._llm_response_cache_handler)
agent.create_agent_executor()
@@ -1315,9 +1273,6 @@ class Crew(FlowTrackable, BaseModel):
def _finish_execution(self, final_string_output: str) -> None:
if self.max_rpm:
self._rpm_controller.stop_rpm_counter()
if self._llm_response_cache_handler:
self._llm_response_cache_handler.stop()
def calculate_usage_metrics(self) -> UsageMetrics:
"""Calculates and returns the usage metrics."""
@@ -1414,6 +1369,8 @@ class Crew(FlowTrackable, BaseModel):
else:
self._reset_specific_memory(command_type)
self._logger.log("info", f"{command_type} memory has been reset")
except Exception as e:
error_msg = f"Failed to reset {command_type} memory: {str(e)}"
self._logger.log("error", error_msg)
@@ -1434,14 +1391,8 @@ class Crew(FlowTrackable, BaseModel):
if system is not None:
try:
system.reset()
self._logger.log(
"info",
f"[Crew ({self.name if self.name else self.id})] {name} memory has been reset",
)
except Exception as e:
raise RuntimeError(
f"[Crew ({self.name if self.name else self.id})] Failed to reset {name} memory: {str(e)}"
) from e
raise RuntimeError(f"Failed to reset {name} memory") from e
def _reset_specific_memory(self, memory_type: str) -> None:
"""Reset a specific memory system.
@@ -1470,11 +1421,5 @@ class Crew(FlowTrackable, BaseModel):
try:
memory_system.reset()
self._logger.log(
"info",
f"[Crew ({self.name if self.name else self.id})] {name} memory has been reset",
)
except Exception as e:
raise RuntimeError(
f"[Crew ({self.name if self.name else self.id})] Failed to reset {name} memory: {str(e)}"
) from e
raise RuntimeError(f"Failed to reset {name} memory") from e

View File

@@ -1,44 +0,0 @@
import inspect
from typing import Optional
from pydantic import BaseModel, Field, InstanceOf, model_validator
from crewai.flow import Flow
class FlowTrackable(BaseModel):
"""Mixin that tracks the Flow instance that instantiated the object, e.g. a
Flow instance that created a Crew or Agent.
Automatically finds and stores a reference to the parent Flow instance by
inspecting the call stack.
"""
parent_flow: Optional[InstanceOf[Flow]] = Field(
default=None,
description="The parent flow of the instance, if it was created inside a flow.",
)
@model_validator(mode="after")
def _set_parent_flow(self, max_depth: int = 5) -> "FlowTrackable":
frame = inspect.currentframe()
try:
if frame is None:
return self
frame = frame.f_back
for _ in range(max_depth):
if frame is None:
break
candidate = frame.f_locals.get("self")
if isinstance(candidate, Flow):
self.parent_flow = candidate
break
frame = frame.f_back
finally:
del frame
return self

View File

@@ -41,6 +41,7 @@ class Knowledge(BaseModel):
)
self.sources = sources
self.storage.initialize_knowledge_storage()
self._add_sources()
def query(
self, query: List[str], results_limit: int = 3, score_threshold: float = 0.35
@@ -62,7 +63,7 @@ class Knowledge(BaseModel):
)
return results
def add_sources(self):
def _add_sources(self):
try:
for source in self.sources:
source.storage = self.storage

View File

@@ -1 +0,0 @@
"""Knowledge utilities for crewAI."""

View File

@@ -13,7 +13,6 @@ from crewai.agents.parser import (
AgentFinish,
OutputParserException,
)
from crewai.flow.flow_trackable import FlowTrackable
from crewai.llm import LLM
from crewai.tools.base_tool import BaseTool
from crewai.tools.structured_tool import CrewStructuredTool
@@ -81,7 +80,7 @@ class LiteAgentOutput(BaseModel):
return self.raw
class LiteAgent(FlowTrackable, BaseModel):
class LiteAgent(BaseModel):
"""
A lightweight agent that can process messages and use tools.
@@ -163,7 +162,7 @@ class LiteAgent(FlowTrackable, BaseModel):
_messages: List[Dict[str, str]] = PrivateAttr(default_factory=list)
_iterations: int = PrivateAttr(default=0)
_printer: Printer = PrivateAttr(default_factory=Printer)
@model_validator(mode="after")
def setup_llm(self):
"""Set up the LLM and other components after initialization."""

View File

@@ -65,7 +65,7 @@ class FilteredStream:
if (
"Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new"
in s
or "LiteLLM.Info: If you need to debug this error, use `litellm._turn_on_debug()`"
or "LiteLLM.Info: If you need to debug this error, use `litellm.set_verbose=True`"
in s
):
return 0
@@ -296,7 +296,6 @@ class LLM(BaseLLM):
self.additional_params = kwargs
self.is_anthropic = self._is_anthropic_model(model)
self.stream = stream
self._response_cache_handler = None
litellm.drop_params = True
@@ -484,7 +483,6 @@ class LLM(BaseLLM):
full_response += chunk_content
# Emit the chunk event
assert hasattr(crewai_event_bus, "emit")
crewai_event_bus.emit(
self,
event=LLMStreamChunkEvent(chunk=chunk_content),
@@ -613,7 +611,6 @@ class LLM(BaseLLM):
return full_response
# Emit failed event and re-raise the exception
assert hasattr(crewai_event_bus, "emit")
crewai_event_bus.emit(
self,
event=LLMCallFailedEvent(error=str(e)),
@@ -636,7 +633,7 @@ class LLM(BaseLLM):
current_tool_accumulator.function.arguments += (
tool_call.function.arguments
)
assert hasattr(crewai_event_bus, "emit")
crewai_event_bus.emit(
self,
event=LLMStreamChunkEvent(
@@ -809,7 +806,6 @@ class LLM(BaseLLM):
function_name, lambda: None
) # Ensure fn is always a callable
logging.error(f"Error executing function '{function_name}': {e}")
assert hasattr(crewai_event_bus, "emit")
crewai_event_bus.emit(
self,
event=LLMCallFailedEvent(error=f"Tool execution error: {str(e)}"),
@@ -847,7 +843,6 @@ class LLM(BaseLLM):
LLMContextLengthExceededException: If input exceeds model's context limit
"""
# --- 1) Emit call started event
assert hasattr(crewai_event_bus, "emit")
crewai_event_bus.emit(
self,
event=LLMCallStartedEvent(
@@ -870,43 +865,25 @@ class LLM(BaseLLM):
for message in messages:
if message.get("role") == "system":
message["role"] = "assistant"
if self._response_cache_handler and self._response_cache_handler.is_replaying():
cached_response = self._response_cache_handler.get_cached_response(
self.model, messages
)
if cached_response:
# Emit completion event for the cached response
self._handle_emit_call_events(cached_response, LLMCallType.LLM_CALL)
return cached_response
# --- 6) Set up callbacks if provided
# --- 5) Set up callbacks if provided
with suppress_warnings():
if callbacks and len(callbacks) > 0:
self.set_callbacks(callbacks)
try:
# --- 7) Prepare parameters for the completion call
# --- 6) Prepare parameters for the completion call
params = self._prepare_completion_params(messages, tools)
# --- 8) Make the completion call and handle response
# --- 7) Make the completion call and handle response
if self.stream:
response = self._handle_streaming_response(
return self._handle_streaming_response(
params, callbacks, available_functions
)
else:
response = self._handle_non_streaming_response(
return self._handle_non_streaming_response(
params, callbacks, available_functions
)
if (self._response_cache_handler and
self._response_cache_handler.is_recording() and
isinstance(response, str)):
self._response_cache_handler.cache_response(
self.model, messages, response
)
return response
except LLMContextLengthExceededException:
# Re-raise LLMContextLengthExceededException as it should be handled
@@ -914,7 +891,6 @@ class LLM(BaseLLM):
# whether to summarize the content or abort based on the respect_context_window flag
raise
except Exception as e:
assert hasattr(crewai_event_bus, "emit")
crewai_event_bus.emit(
self,
event=LLMCallFailedEvent(error=str(e)),
@@ -929,7 +905,6 @@ class LLM(BaseLLM):
response (str): The response from the LLM call.
call_type (str): The type of call, either "tool_call" or "llm_call".
"""
assert hasattr(crewai_event_bus, "emit")
crewai_event_bus.emit(
self,
event=LLMCallCompletedEvent(response=response, call_type=call_type),
@@ -1126,18 +1101,3 @@ class LLM(BaseLLM):
litellm.success_callback = success_callbacks
litellm.failure_callback = failure_callbacks
def set_response_cache_handler(self, handler):
"""
Sets the response cache handler for record/replay functionality.
Args:
handler: An instance of LLMResponseCacheHandler.
"""
self._response_cache_handler = handler
def clear_response_cache_handler(self):
"""
Clears the response cache handler.
"""
self._response_cache_handler = None

View File

@@ -1 +0,0 @@
"""LLM implementations for crewAI."""

View File

@@ -1 +0,0 @@
"""Third-party LLM implementations for crewAI."""

View File

@@ -1 +0,0 @@
"""Memory storage implementations for crewAI."""

View File

@@ -1,296 +0,0 @@
import hashlib
import json
import logging
import sqlite3
import threading
from typing import Any, Dict, List, Optional
from crewai.utilities import Printer
from crewai.utilities.crew_json_encoder import CrewJSONEncoder
from crewai.utilities.paths import db_storage_path
logger = logging.getLogger(__name__)
class LLMResponseCacheStorage:
"""
SQLite storage for caching LLM responses.
Used for offline record/replay functionality.
"""
def __init__(
self, db_path: str = f"{db_storage_path()}/llm_response_cache.db"
) -> None:
self.db_path = db_path
self._printer: Printer = Printer()
self._connection_pool = {}
self._initialize_db()
def _get_connection(self) -> sqlite3.Connection:
"""
Gets a connection from the connection pool or creates a new one.
Uses thread-local storage to ensure thread safety.
"""
thread_id = threading.get_ident()
if thread_id not in self._connection_pool:
try:
conn = sqlite3.connect(self.db_path)
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
self._connection_pool[thread_id] = conn
except sqlite3.Error as e:
error_msg = f"Failed to create SQLite connection: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
raise
return self._connection_pool[thread_id]
def _close_connections(self) -> None:
"""
Closes all connections in the connection pool.
"""
for thread_id, conn in list(self._connection_pool.items()):
try:
conn.close()
del self._connection_pool[thread_id]
except sqlite3.Error as e:
error_msg = f"Failed to close SQLite connection: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
def _initialize_db(self) -> None:
"""
Initializes the SQLite database and creates the llm_response_cache table
"""
try:
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS llm_response_cache (
request_hash TEXT PRIMARY KEY,
model TEXT,
messages TEXT,
response TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
)
conn.commit()
except sqlite3.Error as e:
error_msg = f"Failed to initialize database: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
raise
def _compute_request_hash(self, model: str, messages: List[Dict[str, str]]) -> str:
"""
Computes a hash for the request based on the model and messages.
This hash is used as the key for caching.
Sensitive information like API keys should not be included in the hash.
"""
try:
message_str = json.dumps(messages, sort_keys=True)
request_hash = hashlib.sha256(f"{model}:{message_str}".encode()).hexdigest()
return request_hash
except Exception as e:
error_msg = f"Failed to compute request hash: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
raise
def add(self, model: str, messages: List[Dict[str, str]], response: str) -> None:
"""
Adds a response to the cache.
"""
try:
request_hash = self._compute_request_hash(model, messages)
messages_json = json.dumps(messages, cls=CrewJSONEncoder)
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute(
"""
INSERT OR REPLACE INTO llm_response_cache
(request_hash, model, messages, response)
VALUES (?, ?, ?, ?)
""",
(
request_hash,
model,
messages_json,
response,
),
)
conn.commit()
except sqlite3.Error as e:
error_msg = f"Failed to add response to cache: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
raise
except Exception as e:
error_msg = f"Unexpected error when adding response: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
raise
def get(self, model: str, messages: List[Dict[str, str]]) -> Optional[str]:
"""
Retrieves a response from the cache based on the model and messages.
Returns None if not found.
"""
try:
request_hash = self._compute_request_hash(model, messages)
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute(
"""
SELECT response
FROM llm_response_cache
WHERE request_hash = ?
""",
(request_hash,),
)
result = cursor.fetchone()
return result[0] if result else None
except sqlite3.Error as e:
error_msg = f"Failed to retrieve response from cache: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
return None
except Exception as e:
error_msg = f"Unexpected error when retrieving response: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
return None
def delete_all(self) -> None:
"""
Deletes all records from the llm_response_cache table.
"""
try:
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("DELETE FROM llm_response_cache")
conn.commit()
except sqlite3.Error as e:
error_msg = f"Failed to clear cache: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
raise
def cleanup_expired_cache(self, max_age_days: int = 7) -> None:
"""
Removes cache entries older than the specified number of days.
Args:
max_age_days: Maximum age of cache entries in days. Defaults to 7.
If set to 0, all entries will be deleted.
"""
try:
conn = self._get_connection()
cursor = conn.cursor()
if max_age_days <= 0:
cursor.execute("DELETE FROM llm_response_cache")
deleted_count = cursor.rowcount
logger.info("Deleting all cache entries (max_age_days <= 0)")
else:
cursor.execute(
f"""
DELETE FROM llm_response_cache
WHERE timestamp < datetime('now', '-{max_age_days} days')
"""
)
deleted_count = cursor.rowcount
conn.commit()
if deleted_count > 0:
self._printer.print(
content=f"LLM RESPONSE CACHE: Removed {deleted_count} expired cache entries",
color="green",
)
logger.info(f"Removed {deleted_count} expired cache entries")
except sqlite3.Error as e:
error_msg = f"Failed to cleanup expired cache: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
raise
def get_cache_stats(self) -> Dict[str, Any]:
"""
Returns statistics about the cache.
Returns:
A dictionary containing cache statistics.
"""
try:
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM llm_response_cache")
total_count = cursor.fetchone()[0]
cursor.execute("SELECT model, COUNT(*) FROM llm_response_cache GROUP BY model")
model_counts = {model: count for model, count in cursor.fetchall()}
cursor.execute("SELECT MIN(timestamp), MAX(timestamp) FROM llm_response_cache")
oldest, newest = cursor.fetchone()
return {
"total_entries": total_count,
"entries_by_model": model_counts,
"oldest_entry": oldest,
"newest_entry": newest,
}
except sqlite3.Error as e:
error_msg = f"Failed to get cache stats: {e}"
self._printer.print(
content=f"LLM RESPONSE CACHE ERROR: {error_msg}",
color="red",
)
logger.error(error_msg)
return {"error": str(e)}
def __del__(self) -> None:
"""
Closes all connections when the object is garbage collected.
"""
self._close_connections()

View File

@@ -88,9 +88,7 @@ class Mem0Storage(Storage):
}
if params:
if isinstance(self.memory, MemoryClient):
params["output_format"] = "v1.1"
self.memory.add(value, **params)
self.memory.add(value, **params | {"output_format": "v1.1"})
def search(
self,
@@ -98,7 +96,7 @@ class Mem0Storage(Storage):
limit: int = 3,
score_threshold: float = 0.35,
) -> List[Any]:
params = {"query": query, "limit": limit, "output_format": "v1.1"}
params = {"query": query, "limit": limit}
if user_id := self._get_user_id():
params["user_id"] = user_id
@@ -118,11 +116,8 @@ class Mem0Storage(Storage):
# Discard the filters for now since we create the filters
# automatically when the crew is created.
if isinstance(self.memory, Memory):
del params["metadata"], params["output_format"]
results = self.memory.search(**params)
return [r for r in results["results"] if r["score"] >= score_threshold]
return [r for r in results if r["score"] >= score_threshold]
def _get_user_id(self) -> str:
return self._get_config().get("user_id", "")

View File

@@ -8,6 +8,8 @@ from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.WARNING)
T = TypeVar("T", bound=type)
"""Base decorator for creating crew classes with configuration and function management."""
@@ -246,9 +248,6 @@ def CrewBase(cls: T) -> T:
callback_functions[callback]() for callback in callbacks
]
if guardrail := task_info.get("guardrail"):
self.tasks_config[task_name]["guardrail"] = guardrail
# Include base class (qual)name in the wrapper class (qual)name.
WrappedClass.__name__ = CrewBase.__name__ + "(" + cls.__name__ + ")"
WrappedClass.__qualname__ = CrewBase.__qualname__ + "(" + cls.__name__ + ")"

View File

@@ -140,9 +140,9 @@ class Task(BaseModel):
default=None,
)
processed_by_agents: Set[str] = Field(default_factory=set)
guardrail: Optional[Union[Callable[[TaskOutput], Tuple[bool, Any]], str]] = Field(
guardrail: Optional[Callable[[TaskOutput], Tuple[bool, Any]]] = Field(
default=None,
description="Function or string description of a guardrail to validate task output before proceeding to next task",
description="Function to validate task output before proceeding to next task",
)
max_retries: int = Field(
default=3, description="Maximum number of retries when guardrail fails"
@@ -157,12 +157,8 @@ class Task(BaseModel):
@field_validator("guardrail")
@classmethod
def validate_guardrail_function(
cls, v: Optional[str | Callable]
) -> Optional[str | Callable]:
"""
If v is a callable, validate that the guardrail function has the correct signature and behavior.
If v is a string, return it as is.
def validate_guardrail_function(cls, v: Optional[Callable]) -> Optional[Callable]:
"""Validate that the guardrail function has the correct signature and behavior.
While type hints provide static checking, this validator ensures runtime safety by:
1. Verifying the function accepts exactly one parameter (the TaskOutput)
@@ -175,16 +171,16 @@ class Task(BaseModel):
- Clear error messages help users debug guardrail implementation issues
Args:
v: The guardrail function to validate or a string describing the guardrail task
v: The guardrail function to validate
Returns:
The validated guardrail function or a string describing the guardrail task
The validated guardrail function
Raises:
ValueError: If the function signature is invalid or return annotation
doesn't match Tuple[bool, Any]
"""
if v is not None and callable(v):
if v is not None:
sig = inspect.signature(v)
positional_args = [
param
@@ -215,7 +211,6 @@ class Task(BaseModel):
)
return v
_guardrail: Optional[Callable] = PrivateAttr(default=None)
_original_description: Optional[str] = PrivateAttr(default=None)
_original_expected_output: Optional[str] = PrivateAttr(default=None)
_original_output_file: Optional[str] = PrivateAttr(default=None)
@@ -236,20 +231,6 @@ class Task(BaseModel):
)
return self
@model_validator(mode="after")
def ensure_guardrail_is_callable(self) -> "Task":
if callable(self.guardrail):
self._guardrail = self.guardrail
elif isinstance(self.guardrail, str):
from crewai.tasks.llm_guardrail import LLMGuardrail
assert self.agent is not None
self._guardrail = LLMGuardrail(
description=self.guardrail, llm=self.agent.llm
)
return self
@field_validator("id", mode="before")
@classmethod
def _deny_user_set_id(cls, v: Optional[UUID4]) -> None:
@@ -426,8 +407,10 @@ class Task(BaseModel):
output_format=self._get_output_format(),
)
if self._guardrail:
guardrail_result = self._process_guardrail(task_output)
if self.guardrail:
guardrail_result = GuardrailResult.from_tuple(
self.guardrail(task_output)
)
if not guardrail_result.success:
if self.retry_count >= self.max_retries:
raise Exception(
@@ -481,46 +464,13 @@ class Task(BaseModel):
)
)
self._save_file(content)
crewai_event_bus.emit(
self, TaskCompletedEvent(output=task_output, task=self)
)
crewai_event_bus.emit(self, TaskCompletedEvent(output=task_output, task=self))
return task_output
except Exception as e:
self.end_time = datetime.datetime.now()
crewai_event_bus.emit(self, TaskFailedEvent(error=str(e), task=self))
raise e # Re-raise the exception after emitting the event
def _process_guardrail(self, task_output: TaskOutput) -> GuardrailResult:
assert self._guardrail is not None
from crewai.utilities.events import (
LLMGuardrailCompletedEvent,
LLMGuardrailStartedEvent,
)
from crewai.utilities.events.crewai_event_bus import crewai_event_bus
result = self._guardrail(task_output)
crewai_event_bus.emit(
self,
LLMGuardrailStartedEvent(
guardrail=self._guardrail, retry_count=self.retry_count
),
)
guardrail_result = GuardrailResult.from_tuple(result)
crewai_event_bus.emit(
self,
LLMGuardrailCompletedEvent(
success=guardrail_result.success,
result=guardrail_result.result,
error=guardrail_result.error,
retry_count=self.retry_count,
),
)
return guardrail_result
def prompt(self) -> str:
"""Prompt the task.

View File

@@ -1,92 +0,0 @@
from typing import Any, Optional, Tuple
from pydantic import BaseModel, Field
from crewai.agent import Agent, LiteAgentOutput
from crewai.llm import LLM
from crewai.task import Task
from crewai.tasks.task_output import TaskOutput
class LLMGuardrailResult(BaseModel):
valid: bool = Field(
description="Whether the task output complies with the guardrail"
)
feedback: str | None = Field(
description="A feedback about the task output if it is not valid",
default=None,
)
class LLMGuardrail:
"""It validates the output of another task using an LLM.
This class is used to validate the output from a Task based on specified criteria.
It uses an LLM to validate the output and provides a feedback if the output is not valid.
Args:
description (str): The description of the validation criteria.
llm (LLM, optional): The language model to use for code generation.
"""
def __init__(
self,
description: str,
llm: LLM,
):
self.description = description
self.llm: LLM = llm
def _validate_output(self, task_output: TaskOutput) -> LiteAgentOutput:
agent = Agent(
role="Guardrail Agent",
goal="Validate the output of the task",
backstory="You are a expert at validating the output of a task. By providing effective feedback if the output is not valid.",
llm=self.llm,
)
query = f"""
Ensure the following task result complies with the given guardrail.
Task result:
{task_output.raw}
Guardrail:
{self.description}
Your task:
- Confirm if the Task result complies with the guardrail.
- If not, provide clear feedback explaining what is wrong (e.g., by how much it violates the rule, or what specific part fails).
- Focus only on identifying issues — do not propose corrections.
- If the Task result complies with the guardrail, saying that is valid
"""
result = agent.kickoff(query, response_format=LLMGuardrailResult)
return result
def __call__(self, task_output: TaskOutput) -> Tuple[bool, Any]:
"""Validates the output of a task based on specified criteria.
Args:
task_output (TaskOutput): The output to be validated.
Returns:
Tuple[bool, Any]: A tuple containing:
- bool: True if validation passed, False otherwise
- Any: The validation result or error message
"""
try:
result = self._validate_output(task_output)
assert isinstance(
result.pydantic, LLMGuardrailResult
), "The guardrail result is not a valid pydantic model"
if result.pydantic.valid:
return True, task_output.raw
else:
return False, result.pydantic.feedback
except Exception as e:
return False, f"Error while validating the task output: {str(e)}"

View File

@@ -2,7 +2,6 @@ from __future__ import annotations
import asyncio
import json
import logging
import os
import platform
import warnings
@@ -15,8 +14,6 @@ from crewai.telemetry.constants import (
CREWAI_TELEMETRY_SERVICE_NAME,
)
logger = logging.getLogger(__name__)
@contextmanager
def suppress_warnings():
@@ -31,10 +28,7 @@ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
)
from opentelemetry.sdk.resources import SERVICE_NAME, Resource # noqa: E402
from opentelemetry.sdk.trace import TracerProvider # noqa: E402
from opentelemetry.sdk.trace.export import ( # noqa: E402
BatchSpanProcessor,
SpanExportResult,
)
from opentelemetry.sdk.trace.export import BatchSpanProcessor # noqa: E402
from opentelemetry.trace import Span, Status, StatusCode # noqa: E402
if TYPE_CHECKING:
@@ -42,15 +36,6 @@ if TYPE_CHECKING:
from crewai.task import Task
class SafeOTLPSpanExporter(OTLPSpanExporter):
def export(self, spans) -> SpanExportResult:
try:
return super().export(spans)
except Exception as e:
logger.error(e)
return SpanExportResult.FAILURE
class Telemetry:
"""A class to handle anonymous telemetry for the crewai package.
@@ -79,7 +64,7 @@ class Telemetry:
self.provider = TracerProvider(resource=self.resource)
processor = BatchSpanProcessor(
SafeOTLPSpanExporter(
OTLPSpanExporter(
endpoint=f"{CREWAI_TELEMETRY_BASE_URL}/v1/traces",
timeout=30,
)

View File

@@ -1 +1,15 @@
from .base_tool import BaseTool, tool
__all__ = [
"BaseTool",
"tool",
]
from .base_tool import Tool, to_langchain
from .mcp_connector import MCPToolConnector
__all__ += [
"Tool",
"to_langchain",
"MCPToolConnector",
]

View File

@@ -1 +0,0 @@
"""Agent tools for crewAI."""

View File

@@ -0,0 +1,115 @@
import logging
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
from crewai.cli.authentication.utils import TokenManager
from crewai.tools import BaseTool
from crewai.utilities.sse_client import SSEClient
class MCPToolConnector:
"""Connects tools to the Management Control Plane (MCP) via SSE."""
MCP_BASE_URL = "https://app.crewai.com"
SSE_ENDPOINT = "/api/v1/tools/events"
def __init__(
self,
tools: Optional[List[BaseTool]] = None,
timeout: int = 30
):
"""Initialize the MCP Tool Connector.
Args:
tools: List of tools to connect to the MCP.
timeout: Connection timeout in seconds.
"""
self.tools = tools or []
self.timeout = timeout
self.logger = logging.getLogger(__name__)
self.token_manager = TokenManager()
self._sse_client: Optional[SSEClient] = None
def connect(self) -> None:
"""Connect to the MCP SSE server for tools."""
token = self.token_manager.get_token()
if not token:
self.logger.error("Authentication token not found. Please log in first.")
raise ValueError("Authentication token not found. Please log in first.")
headers = {
"Authorization": f"Bearer {token}",
"Accept": "text/event-stream",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest",
}
tool_data = {}
for tool in self.tools:
tool_data[tool.name] = {
"name": tool.name,
"description": tool.description,
"schema": tool.args_schema.model_json_schema() if hasattr(tool.args_schema, "model_json_schema") else {},
}
self._sse_client = SSEClient(
base_url=self.MCP_BASE_URL,
endpoint=self.SSE_ENDPOINT,
headers=headers,
timeout=self.timeout
)
try:
if self._sse_client is not None:
self._sse_client.connect()
except Exception as e:
self.logger.error(f"Failed to connect to MCP SSE server: {str(e)}")
raise
def listen(self) -> None:
"""Listen for tool events from the MCP SSE server."""
if not self._sse_client:
self.connect()
event_handlers = {
"tool_request": self._handle_tool_request,
"connection_closed": self._handle_connection_closed,
}
try:
if self._sse_client is not None:
self._sse_client.listen(event_handlers)
else:
self.logger.error("SSE client is not initialized")
raise ValueError("SSE client is not initialized")
except Exception as e:
self.logger.error(f"Error listening to MCP SSE events: {str(e)}")
raise
def _handle_tool_request(self, data: Dict[str, Any]) -> None:
"""Handle a tool request event from the MCP SSE server."""
try:
tool_name = data.get("tool_name")
arguments = data.get("arguments", {})
request_id = data.get("request_id")
tool = next((t for t in self.tools if t.name == tool_name), None)
if not tool:
self.logger.error(f"Tool '{tool_name}' not found")
return
result = tool.run(**arguments)
except Exception as e:
self.logger.error(f"Error handling tool request: {str(e)}")
def _handle_connection_closed(self, data: Any) -> None:
"""Handle a connection closed event from the MCP SSE server."""
self.logger.info("MCP SSE connection closed")
def close(self) -> None:
"""Close the MCP SSE connection."""
if self._sse_client:
self._sse_client.close()
self._sse_client = None

View File

@@ -1 +0,0 @@
"""Evaluators for crewAI."""

View File

@@ -9,10 +9,6 @@ from .crew_events import (
CrewTestCompletedEvent,
CrewTestFailedEvent,
)
from .llm_guardrail_events import (
LLMGuardrailCompletedEvent,
LLMGuardrailStartedEvent,
)
from .agent_events import (
AgentExecutionStartedEvent,
AgentExecutionCompletedEvent,

View File

@@ -70,12 +70,7 @@ class CrewAIEventsBus:
for event_type, handlers in self._handlers.items():
if isinstance(event, event_type):
for handler in handlers:
try:
handler(source, event)
except Exception as e:
print(
f"[EventBus Error] Handler '{handler.__name__}' failed for event '{event_type.__name__}': {e}"
)
handler(source, event)
self._signal.send(source, event=event)

View File

@@ -29,10 +29,6 @@ from .llm_events import (
LLMCallStartedEvent,
LLMStreamChunkEvent,
)
from .llm_guardrail_events import (
LLMGuardrailCompletedEvent,
LLMGuardrailStartedEvent,
)
from .task_events import (
TaskCompletedEvent,
TaskFailedEvent,
@@ -72,6 +68,4 @@ EventTypes = Union[
LLMCallCompletedEvent,
LLMCallFailedEvent,
LLMStreamChunkEvent,
LLMGuardrailStartedEvent,
LLMGuardrailCompletedEvent,
]

View File

@@ -1,38 +0,0 @@
from typing import Any, Callable, Optional, Union
from crewai.utilities.events.base_events import BaseEvent
class LLMGuardrailStartedEvent(BaseEvent):
"""Event emitted when a guardrail task starts
Attributes:
guardrail: The guardrail callable or LLMGuardrail instance
retry_count: The number of times the guardrail has been retried
"""
type: str = "llm_guardrail_started"
guardrail: Union[str, Callable]
retry_count: int
def __init__(self, **data):
from inspect import getsource
from crewai.tasks.llm_guardrail import LLMGuardrail
super().__init__(**data)
if isinstance(self.guardrail, LLMGuardrail):
self.guardrail = self.guardrail.description.strip()
elif isinstance(self.guardrail, Callable):
self.guardrail = getsource(self.guardrail).strip()
class LLMGuardrailCompletedEvent(BaseEvent):
"""Event emitted when a guardrail task completes"""
type: str = "llm_guardrail_completed"
success: bool
result: Any
error: Optional[str] = None
retry_count: int

View File

@@ -1 +0,0 @@
"""Event utilities for crewAI."""

View File

@@ -1 +0,0 @@
"""Exceptions for crewAI."""

View File

@@ -1,156 +0,0 @@
import logging
from typing import Any, Dict, List, Optional
from crewai.memory.storage.llm_response_cache_storage import LLMResponseCacheStorage
logger = logging.getLogger(__name__)
class LLMResponseCacheHandler:
"""
Handler for the LLM response cache storage.
Used for record/replay functionality.
"""
def __init__(self, max_cache_age_days: int = 7) -> None:
"""
Initializes the LLM response cache handler.
Args:
max_cache_age_days: Maximum age of cache entries in days. Defaults to 7.
"""
self.storage = LLMResponseCacheStorage()
self._recording = False
self._replaying = False
self.max_cache_age_days = max_cache_age_days
try:
self.storage.cleanup_expired_cache(self.max_cache_age_days)
except Exception as e:
logger.warning(f"Failed to cleanup expired cache on initialization: {e}")
def start_recording(self) -> None:
"""
Starts recording LLM responses.
"""
self._recording = True
self._replaying = False
logger.info("Started recording LLM responses")
def start_replaying(self) -> None:
"""
Starts replaying LLM responses from the cache.
"""
self._recording = False
self._replaying = True
logger.info("Started replaying LLM responses from cache")
try:
stats = self.storage.get_cache_stats()
logger.info(f"Cache statistics: {stats}")
except Exception as e:
logger.warning(f"Failed to get cache statistics: {e}")
def stop(self) -> None:
"""
Stops recording or replaying.
"""
was_recording = self._recording
was_replaying = self._replaying
self._recording = False
self._replaying = False
if was_recording:
logger.info("Stopped recording LLM responses")
if was_replaying:
logger.info("Stopped replaying LLM responses")
def is_recording(self) -> bool:
"""
Returns whether recording is active.
"""
return self._recording
def is_replaying(self) -> bool:
"""
Returns whether replaying is active.
"""
return self._replaying
def cache_response(self, model: str, messages: List[Dict[str, str]], response: str) -> None:
"""
Caches an LLM response if recording is active.
Args:
model: The model used for the LLM call.
messages: The messages sent to the LLM.
response: The response from the LLM.
"""
if not self._recording:
return
try:
self.storage.add(model, messages, response)
logger.debug(f"Cached response for model {model}")
except Exception as e:
logger.error(f"Failed to cache response: {e}")
def get_cached_response(self, model: str, messages: List[Dict[str, str]]) -> Optional[str]:
"""
Retrieves a cached LLM response if replaying is active.
Returns None if not found or if replaying is not active.
Args:
model: The model used for the LLM call.
messages: The messages sent to the LLM.
Returns:
The cached response, or None if not found or if replaying is not active.
"""
if not self._replaying:
return None
try:
response = self.storage.get(model, messages)
if response:
logger.debug(f"Retrieved cached response for model {model}")
else:
logger.debug(f"No cached response found for model {model}")
return response
except Exception as e:
logger.error(f"Failed to retrieve cached response: {e}")
return None
def clear_cache(self) -> None:
"""
Clears the LLM response cache.
"""
try:
self.storage.delete_all()
logger.info("Cleared LLM response cache")
except Exception as e:
logger.error(f"Failed to clear cache: {e}")
def cleanup_expired_cache(self) -> None:
"""
Removes cache entries older than the maximum age.
"""
try:
self.storage.cleanup_expired_cache(self.max_cache_age_days)
logger.info(f"Cleaned up expired cache entries (older than {self.max_cache_age_days} days)")
except Exception as e:
logger.error(f"Failed to cleanup expired cache: {e}")
def get_cache_stats(self) -> Dict[str, Any]:
"""
Returns statistics about the cache.
Returns:
A dictionary containing cache statistics.
"""
try:
return self.storage.get_cache_stats()
except Exception as e:
logger.error(f"Failed to get cache stats: {e}")
return {"error": str(e)}

View File

@@ -54,12 +54,10 @@ class Prompts(BaseModel):
response_template=None,
) -> str:
"""Constructs a prompt string from specified components."""
if not system_template or not prompt_template:
# If any of the required templates are missing, fall back to the default format
if not system_template and not prompt_template:
prompt_parts = [self.i18n.slice(component) for component in components]
prompt = "".join(prompt_parts)
else:
# All templates are provided, use them
prompt_parts = [
self.i18n.slice(component)
for component in components
@@ -69,12 +67,8 @@ class Prompts(BaseModel):
prompt = prompt_template.replace(
"{{ .Prompt }}", "".join(self.i18n.slice("task"))
)
# Handle missing response_template
if response_template:
response = response_template.split("{{ .Response }}")[0]
prompt = f"{system}\n{prompt}\n{response}"
else:
prompt = f"{system}\n{prompt}"
response = response_template.split("{{ .Response }}")[0]
prompt = f"{system}\n{prompt}\n{response}"
prompt = (
prompt.replace("{goal}", self.agent.goal)

View File

@@ -0,0 +1,152 @@
import json
import logging
from typing import Any, Callable, Dict, Mapping, Optional, Union
from urllib.parse import urljoin
import requests
import sseclient
from crewai.utilities.events import crewai_event_bus
from crewai.utilities.events.base_events import BaseEvent
class SSEConnectionStartedEvent(BaseEvent):
"""Event emitted when an SSE connection is started"""
type: str = "sse_connection_started"
endpoint: str
headers: Dict[str, str]
class SSEConnectionErrorEvent(BaseEvent):
"""Event emitted when an SSE connection encounters an error"""
type: str = "sse_connection_error"
endpoint: str
error: str
class SSEMessageReceivedEvent(BaseEvent):
"""Event emitted when an SSE message is received"""
type: str = "sse_message_received"
endpoint: str
event: str
data: Any
class SSEClient:
"""Client for connecting to Server-Sent Events (SSE) endpoints"""
def __init__(
self,
base_url: str,
endpoint: str = "",
headers: Optional[Dict[str, str]] = None,
timeout: int = 30,
):
"""Initialize the SSE client.
Args:
base_url: Base URL for the SSE server.
endpoint: Endpoint path to connect to (will be joined with base_url).
headers: Headers to include in the SSE request.
timeout: Connection timeout in seconds.
"""
self.base_url = base_url
self.endpoint = endpoint
self.headers = headers or {}
self.timeout = timeout
self.logger = logging.getLogger(__name__)
self._client: Optional[sseclient.SSEClient] = None
self._response: Optional[requests.Response] = None
def connect(self) -> None:
"""Establish a connection to the SSE server."""
try:
url = urljoin(self.base_url, self.endpoint)
self.logger.info(f"Connecting to SSE server at {url}")
crewai_event_bus.emit(
self,
event=SSEConnectionStartedEvent(
endpoint=url,
headers=self.headers
)
)
self._response = requests.get(
url,
headers=self.headers,
stream=True,
timeout=self.timeout
)
if self._response is not None:
self._response.raise_for_status()
self._client = sseclient.SSEClient(self._response)
except Exception as e:
self.logger.error(f"Error connecting to SSE server: {str(e)}")
crewai_event_bus.emit(
self,
event=SSEConnectionErrorEvent(
endpoint=urljoin(self.base_url, self.endpoint),
error=str(e)
)
)
raise
def listen(self, event_handlers: Optional[Mapping[str, Callable[[Any], None]]] = None) -> None:
"""Listen for SSE events and process them with registered handlers.
Args:
event_handlers: Dictionary mapping event types to handler functions.
"""
if self._client is None:
self.connect()
event_handlers = event_handlers or {}
try:
if self._client is None:
self.logger.error("SSE client is not initialized")
return
for event in self._client:
event_type = event.event or "message"
data = None
try:
data = json.loads(event.data)
except (json.JSONDecodeError, TypeError):
data = event.data
crewai_event_bus.emit(
self,
event=SSEMessageReceivedEvent(
endpoint=urljoin(self.base_url, self.endpoint),
event=event_type,
data=data
)
)
handler = event_handlers.get(event_type)
if handler:
handler(data)
except Exception as e:
self.logger.error(f"Error processing SSE events: {str(e)}")
crewai_event_bus.emit(
self,
event=SSEConnectionErrorEvent(
endpoint=urljoin(self.base_url, self.endpoint),
error=str(e)
)
)
raise
finally:
self.close()
def close(self) -> None:
"""Close the SSE connection."""
if self._response:
self._response.close()
self._response = None
self._client = None

View File

@@ -72,54 +72,9 @@ def test_agent_creation():
assert agent.role == "test role"
assert agent.goal == "test goal"
assert agent.backstory == "test backstory"
def test_agent_with_only_system_template():
"""Test that an agent with only system_template works without errors."""
agent = Agent(
role="Test Role",
goal="Test Goal",
backstory="Test Backstory",
allow_delegation=False,
system_template="You are a test agent...",
# prompt_template is intentionally missing
)
assert agent.role == "Test Role"
assert agent.goal == "Test Goal"
assert agent.backstory == "Test Backstory"
def test_agent_with_only_prompt_template():
"""Test that an agent with only system_template works without errors."""
agent = Agent(
role="Test Role",
goal="Test Goal",
backstory="Test Backstory",
allow_delegation=False,
prompt_template="You are a test agent...",
# prompt_template is intentionally missing
)
assert agent.role == "Test Role"
assert agent.goal == "Test Goal"
assert agent.backstory == "Test Backstory"
assert agent.tools == []
def test_agent_with_missing_response_template():
"""Test that an agent with system_template and prompt_template but no response_template works without errors."""
agent = Agent(
role="Test Role",
goal="Test Goal",
backstory="Test Backstory",
allow_delegation=False,
system_template="You are a test agent...",
prompt_template="This is a test prompt...",
# response_template is intentionally missing
)
assert agent.role == "Test Role"
assert agent.goal == "Test Goal"
assert agent.backstory == "Test Backstory"
def test_agent_default_values():
agent = Agent(role="test role", goal="test goal", backstory="test backstory")
assert agent.llm.model == "gpt-4o-mini"

View File

@@ -1 +0,0 @@
"""Tests for agent adapters."""

View File

@@ -1 +0,0 @@
"""Tests for agent builder."""

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More