Compare commits

...

29 Commits

Author SHA1 Message Date
Devin AI
99c13585bb Fix import sorting and type checking issues
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-03-21 19:46:57 +00:00
Devin AI
6708d47d39 Fix CI issues and implement PR feedback improvements
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-03-21 19:44:28 +00:00
Devin AI
9315610cc6 Fix import sorting issues
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-03-21 19:33:00 +00:00
Devin AI
c98e29d679 Add standalone deployment tools for CrewAI workflows (fixes #2438)
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-03-21 19:31:00 +00:00
Matisse
bb3829a9ed docs: Update model reference in LLM configuration (#2267)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 15:12:26 -04:00
Fernando Galves
0a116202f0 Update the context window size for Amazon Bedrock FM- llm.py (#2304)
Update the context window size for Amazon Bedrock Foundation Models.

Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-03-21 14:48:25 -04:00
Stefano Baccianella
4daa88fa59 As explained in https://github.com/mangiucugna/json_repair?tab=readme-ov-file#performance-considerations we can skip a wasteful json.loads() here and save quite some time (#2397)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-03-21 14:25:19 -04:00
Parth Patel
53067f8b92 add Mem0 OSS support (#2429)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 13:57:24 -04:00
Saurabh Misra
d3a09c3180 ️ Speed up method CrewAgentParser._clean_action by 427,565% (#2382)
Here is the optimized version of the program.

Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 13:51:14 -04:00
Saurabh Misra
4d7aacb5f2 ️ Speed up method Repository.is_git_repo by 72,270% (#2381)
Here is the optimized version of the `Repository` class.

Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 13:43:48 -04:00
Julio Peixoto
6b1cf78e41 docs: add detailed docstrings to Telemetry class methods (#2377)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 13:34:16 -04:00
Patcher
80f1a88b63 Upgrade OTel SDK version to 1.30.0 (#2375)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 13:26:50 -04:00
Jorge Gonzalez
32da76a2ca Use task in the note about how methods names need to match task names (#2355)
The note is about the task but mentions the agent incorrectly.

Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 13:17:43 -04:00
Gustavo Satheler
3aa48dcd58 fix: move agent tools for a variable instead of use format (#2319)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-21 12:32:54 -04:00
Tony Kipkemboi
03f1d57463 Merge pull request #2430 from crewAIInc/update-llm-docs
docs: add documentation for Local NVIDIA NIM with WSL2
2025-03-20 12:57:37 -07:00
Tony Kipkemboi
4725d0de0d Merge branch 'main' into update-llm-docs 2025-03-20 12:50:06 -07:00
Arthur Chien
b766af75f2 fix the _extract_thought (#2398)
* fix the _extract_thought

the regex string should be same with prompt in en.json:129
...\nThought: I now know the final answer\nFinal Answer: the...

* fix Action match

---------

Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 15:44:44 -04:00
Tony Kipkemboi
b2c8779f4c Add documentation for Local NVIDIA NIM with WSL2 2025-03-20 12:39:37 -07:00
Tony Kipkemboi
df266bda01 Update documentation: Add changelog, fix formatting issues, replace mint.json with docs.json (#2400) 2025-03-20 14:44:21 -04:00
Lorenze Jay
2155acb3a3 docs: Update JSONSearchTool and RagTool configuration parameter from 'embedder' to 'embedding_model' (#2311)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 13:11:37 -04:00
Sir Qasim
794574957e Add note to create ./knowldge folder for source file management (#2297)
This update includes a note in the documentation instructing users to create a ./knowldge folder. All source files (such as .txt, .pdf, .xlsx, .json) should be placed in this folder for centralized management. This change aims to streamline file organization and improve accessibility across projects.

Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 12:54:17 -04:00
Sir Qasim
66b19311a7 Fix crewai run Command Issue for Flow Projects and Cloud Deployment (#2291)
This PR addresses an issue with the crewai run command following the creation of a flow project. Previously, the update command interfered with execution, causing it not to work as expected. With these changes, the command now runs according to the instructions in the readme.md, and it also improves deployment support when using CrewAI Cloud.

Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 12:48:02 -04:00
devin-ai-integration[bot]
9fc84fc1ac Fix incorrect import statement in memory examples documentation (fixes #2395) (#2396)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Joe Moura <joao@crewai.com>
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 12:17:26 -04:00
Amine Saihi
f8f9df6d1d update doc SpaceNewsKnowledgeSource code snippet (#2275)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 12:06:21 -04:00
João Moura
6e94edb777 TYPO 2025-03-20 08:21:17 -07:00
Vini Brasil
bbe896d48c Support wildcard handling in emit() (#2424)
* Support wildcard handling in `emit()`

Change `emit()` to call handlers registered for parent classes using
`isinstance()`. Ensures that base event handlers receive derived
events.

* Fix failing test

* Remove unused variable
2025-03-20 09:59:17 -04:00
Seyed Mostafa Meshkati
9298054436 docs: add base_url env for anthropic llm example (#2204)
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 09:48:11 -04:00
Fernando Galves
90b7937796 Update documentation (#2199)
* Update llms.mdx

Update Amazon Bedrock section with more information about the foundation models available.

* Update llms.mdx

fix the description of Amazon Bedrock section

* Update llms.mdx

Remove the incorrect </tab> tag

* Update llms.mdx

Add Claude 3.7 Sonnet to the Amazon Bedrock list

---------

Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 09:42:23 -04:00
elda27
520933b4c5 Fix: More comfortable validation #2177 (#2178)
* Fix: More confortable validation

* Fix: union type support

---------

Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
2025-03-20 09:28:31 -04:00
41 changed files with 1754 additions and 286 deletions

187
docs/changelog.mdx Normal file
View File

@@ -0,0 +1,187 @@
---
title: Changelog
description: View the latest updates and changes to CrewAI
icon: timeline
---
<Update label="2024-03-17" description="v0.108.0">
**Features**
- Converted tabs to spaces in `crew.py` template
- Enhanced LLM Streaming Response Handling and Event System
- Included `model_name`
- Enhanced Event Listener with rich visualization and improved logging
- Added fingerprints
**Bug Fixes**
- Fixed Mistral issues
- Fixed a bug in documentation
- Fixed type check error in fingerprint property
**Documentation Updates**
- Improved tool documentation
- Updated installation guide for the `uv` tool package
- Added instructions for upgrading crewAI with the `uv` tool
- Added documentation for `ApifyActorsTool`
</Update>
<Update label="2024-03-10" description="v0.105.0">
**Core Improvements & Fixes**
- Fixed issues with missing template variables and user memory configuration
- Improved async flow support and addressed agent response formatting
- Enhanced memory reset functionality and fixed CLI memory commands
- Fixed type issues, tool calling properties, and telemetry decoupling
**New Features & Enhancements**
- Added Flow state export and improved state utilities
- Enhanced agent knowledge setup with optional crew embedder
- Introduced event emitter for better observability and LLM call tracking
- Added support for Python 3.10 and ChatOllama from langchain_ollama
- Integrated context window size support for the o3-mini model
- Added support for multiple router calls
**Documentation & Guides**
- Improved documentation layout and hierarchical structure
- Added QdrantVectorSearchTool guide and clarified event listener usage
- Fixed typos in prompts and updated Amazon Bedrock model listings
</Update>
<Update label="2024-02-12" description="v0.102.0">
**Core Improvements & Fixes**
- Enhanced LLM Support: Improved structured LLM output, parameter handling, and formatting for Anthropic models
- Crew & Agent Stability: Fixed issues with cloning agents/crews using knowledge sources, multiple task outputs in conditional tasks, and ignored Crew task callbacks
- Memory & Storage Fixes: Fixed short-term memory handling with Bedrock, ensured correct embedder initialization, and added a reset memories function in the crew class
- Training & Execution Reliability: Fixed broken training and interpolation issues with dict and list input types
**New Features & Enhancements**
- Advanced Knowledge Management: Improved naming conventions and enhanced embedding configuration with custom embedder support
- Expanded Logging & Observability: Added JSON format support for logging and integrated MLflow tracing documentation
- Data Handling Improvements: Updated excel_knowledge_source.py to process multi-tab files
- General Performance & Codebase Clean-Up: Streamlined enterprise code alignment and resolved linting issues
- Adding new tool: `QdrantVectorSearchTool`
**Documentation & Guides**
- Updated AI & Memory Docs: Improved Bedrock, Google AI, and long-term memory documentation
- Task & Workflow Clarity: Added "Human Input" row to Task Attributes, Langfuse guide, and FileWriterTool documentation
- Fixed Various Typos & Formatting Issues
</Update>
<Update label="2024-01-28" description="v0.100.0">
**Features**
- Add Composio docs
- Add SageMaker as a LLM provider
**Fixes**
- Overall LLM connection issues
- Using safe accessors on training
- Add version check to crew_chat.py
**Documentation**
- New docs for crewai chat
- Improve formatting and clarity in CLI and Composio Tool docs
</Update>
<Update label="2024-01-20" description="v0.98.0">
**Features**
- Conversation crew v1
- Add unique ID to flow states
- Add @persist decorator with FlowPersistence interface
**Integrations**
- Add SambaNova integration
- Add NVIDIA NIM provider in cli
- Introducing VoyageAI
**Fixes**
- Fix API Key Behavior and Entity Handling in Mem0 Integration
- Fixed core invoke loop logic and relevant tests
- Make tool inputs actual objects and not strings
- Add important missing parts to creating tools
- Drop litellm version to prevent windows issue
- Before kickoff if inputs are none
- Fixed typos, nested pydantic model issue, and docling issues
</Update>
<Update label="2024-01-04" description="v0.95.0">
**New Features**
- Adding Multimodal Abilities to Crew
- Programatic Guardrails
- HITL multiple rounds
- Gemini 2.0 Support
- CrewAI Flows Improvements
- Add Workflow Permissions
- Add support for langfuse with litellm
- Portkey Integration with CrewAI
- Add interpolate_only method and improve error handling
- Docling Support
- Weviate Support
**Fixes**
- output_file not respecting system path
- disk I/O error when resetting short-term memory
- CrewJSONEncoder now accepts enums
- Python max version
- Interpolation for output_file in Task
- Handle coworker role name case/whitespace properly
- Add tiktoken as explicit dependency and document Rust requirement
- Include agent knowledge in planning process
- Change storage initialization to None for KnowledgeStorage
- Fix optional storage checks
- include event emitter in flows
- Docstring, Error Handling, and Type Hints Improvements
- Suppressed userWarnings from litellm pydantic issues
</Update>
<Update label="2023-12-05" description="v0.86.0">
**Changes**
- Remove all references to pipeline and pipeline router
- Add Nvidia NIM as provider in Custom LLM
- Add knowledge demo + improve knowledge docs
- Add HITL multiple rounds of followup
- New docs about yaml crew with decorators
- Simplify template crew
</Update>
<Update label="2023-12-04" description="v0.85.0">
**Features**
- Added knowledge to agent level
- Feat/remove langchain
- Improve typed task outputs
- Log in to Tool Repository on crewai login
**Fixes**
- Fixes issues with result as answer not properly exiting LLM loop
- Fix missing key name when running with ollama provider
- Fix spelling issue found
**Documentation**
- Update readme for running mypy
- Add knowledge to mint.json
- Update Github actions
- Update Agents docs to include two approaches for creating an agent
- Improvements to LLM Configuration and Usage
</Update>
<Update label="2023-11-25" description="v0.83.0">
**New Features**
- New before_kickoff and after_kickoff crew callbacks
- Support to pre-seed agents with Knowledge
- Add support for retrieving user preferences and memories using Mem0
**Fixes**
- Fix Async Execution
- Upgrade chroma and adjust embedder function generator
- Update CLI Watson supported models + docs
- Reduce level for Bandit
- Fixing all tests
**Documentation**
- Update Docs
</Update>
<Update label="2023-11-13" description="v0.80.0">
**Fixes**
- Fixing Tokens callback replacement bug
- Fixing Step callback issue
- Add cached prompt tokens info on usage metrics
- Fix crew_train_success test
</Update>

View File

@@ -150,6 +150,8 @@ result = crew.kickoff(
Here are examples of how to use different types of knowledge sources:
Note: Please ensure that you create the ./knowldge folder. All source files (e.g., .txt, .pdf, .xlsx, .json) should be placed in this folder for centralized management.
### Text File Knowledge Source
```python
from crewai.knowledge.source.text_file_knowledge_source import TextFileKnowledgeSource
@@ -460,12 +462,12 @@ class SpaceNewsKnowledgeSource(BaseKnowledgeSource):
data = response.json()
articles = data.get('results', [])
formatted_data = self._format_articles(articles)
formatted_data = self.validate_content(articles)
return {self.api_endpoint: formatted_data}
except Exception as e:
raise ValueError(f"Failed to fetch space news: {str(e)}")
def _format_articles(self, articles: list) -> str:
def validate_content(self, articles: list) -> str:
"""Format articles into readable text."""
formatted = "Space News Articles:\n\n"
for article in articles:

View File

@@ -59,7 +59,7 @@ There are three ways to configure LLMs in CrewAI. Choose the method that best fi
goal: Conduct comprehensive research and analysis
backstory: A dedicated research professional with years of experience
verbose: true
llm: openai/gpt-4o-mini # your model here
llm: openai/gpt-4o-mini # your model here
# (see provider configuration examples below for more)
```
@@ -111,7 +111,7 @@ There are three ways to configure LLMs in CrewAI. Choose the method that best fi
## Provider Configuration Examples
CrewAI supports a multitude of LLM providers, each offering unique features, authentication methods, and model capabilities.
CrewAI supports a multitude of LLM providers, each offering unique features, authentication methods, and model capabilities.
In this section, you'll find detailed examples that help you select, configure, and optimize the LLM that best fits your project's needs.
<AccordionGroup>
@@ -121,7 +121,7 @@ In this section, you'll find detailed examples that help you select, configure,
```toml Code
# Required
OPENAI_API_KEY=sk-...
# Optional
OPENAI_API_BASE=<custom-base-url>
OPENAI_ORGANIZATION=<your-org-id>
@@ -158,7 +158,11 @@ In this section, you'll find detailed examples that help you select, configure,
<Accordion title="Anthropic">
```toml Code
# Required
ANTHROPIC_API_KEY=sk-ant-...
# Optional
ANTHROPIC_API_BASE=<custom-base-url>
```
Example usage in your CrewAI project:
@@ -222,7 +226,7 @@ In this section, you'll find detailed examples that help you select, configure,
AZURE_API_KEY=<your-api-key>
AZURE_API_BASE=<your-resource-url>
AZURE_API_VERSION=<api-version>
# Optional
AZURE_AD_TOKEN=<your-azure-ad-token>
AZURE_API_TYPE=<your-azure-api-type>
@@ -250,8 +254,42 @@ In this section, you'll find detailed examples that help you select, configure,
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0"
)
```
Before using Amazon Bedrock, make sure you have boto3 installed in your environment
[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) is a managed service that provides access to multiple foundation models from top AI companies through a unified API, enabling secure and responsible AI application development.
| Model | Context Window | Best For |
|-------------------------|----------------------|-------------------------------------------------------------------|
| Amazon Nova Pro | Up to 300k tokens | High-performance, model balancing accuracy, speed, and cost-effectiveness across diverse tasks. |
| Amazon Nova Micro | Up to 128k tokens | High-performance, cost-effective text-only model optimized for lowest latency responses. |
| Amazon Nova Lite | Up to 300k tokens | High-performance, affordable multimodal processing for images, video, and text with real-time capabilities. |
| Claude 3.7 Sonnet | Up to 128k tokens | High-performance, best for complex reasoning, coding & AI agents |
| Claude 3.5 Sonnet v2 | Up to 200k tokens | State-of-the-art model specialized in software engineering, agentic capabilities, and computer interaction at optimized cost. |
| Claude 3.5 Sonnet | Up to 200k tokens | High-performance model delivering superior intelligence and reasoning across diverse tasks with optimal speed-cost balance. |
| Claude 3.5 Haiku | Up to 200k tokens | Fast, compact multimodal model optimized for quick responses and seamless human-like interactions |
| Claude 3 Sonnet | Up to 200k tokens | Multimodal model balancing intelligence and speed for high-volume deployments. |
| Claude 3 Haiku | Up to 200k tokens | Compact, high-speed multimodal model optimized for quick responses and natural conversational interactions |
| Claude 3 Opus | Up to 200k tokens | Most advanced multimodal model exceling at complex tasks with human-like reasoning and superior contextual understanding. |
| Claude 2.1 | Up to 200k tokens | Enhanced version with expanded context window, improved reliability, and reduced hallucinations for long-form and RAG applications |
| Claude | Up to 100k tokens | Versatile model excelling in sophisticated dialogue, creative content, and precise instruction following. |
| Claude Instant | Up to 100k tokens | Fast, cost-effective model for everyday tasks like dialogue, analysis, summarization, and document Q&A |
| Llama 3.1 405B Instruct | Up to 128k tokens | Advanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks. |
| Llama 3.1 70B Instruct | Up to 128k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
| Llama 3.1 8B Instruct | Up to 128k tokens | Advanced state-of-the-art model with language understanding, superior reasoning, and text generation. |
| Llama 3 70B Instruct | Up to 8k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
| Llama 3 8B Instruct | Up to 8k tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
| Titan Text G1 - Lite | Up to 4k tokens | Lightweight, cost-effective model optimized for English tasks and fine-tuning with focus on summarization and content generation. |
| Titan Text G1 - Express | Up to 8k tokens | Versatile model for general language tasks, chat, and RAG applications with support for English and 100+ languages. |
| Cohere Command | Up to 4k tokens | Model specialized in following user commands and delivering practical enterprise solutions. |
| Jurassic-2 Mid | Up to 8,191 tokens | Cost-effective model balancing quality and affordability for diverse language tasks like Q&A, summarization, and content generation. |
| Jurassic-2 Ultra | Up to 8,191 tokens | Model for advanced text generation and comprehension, excelling in complex tasks like analysis and content creation. |
| Jamba-Instruct | Up to 256k tokens | Model with extended context window optimized for cost-effective text generation, summarization, and Q&A. |
| Mistral 7B Instruct | Up to 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
| Mistral 8x7B Instruct | Up to 32k tokens | An MOE LLM that follows instructions, completes requests, and generates creative text. |
</Accordion>
<Accordion title="Amazon SageMaker">
```toml Code
AWS_ACCESS_KEY_ID=<your-access-key>
@@ -368,6 +406,46 @@ In this section, you'll find detailed examples that help you select, configure,
| baichuan-inc/baichuan2-13b-chat | 4,096 tokens | Support Chinese and English chat, coding, math, instruction following, solving quizzes |
</Accordion>
<Accordion title="Local NVIDIA NIM Deployed using WSL2">
NVIDIA NIM enables you to run powerful LLMs locally on your Windows machine using WSL2 (Windows Subsystem for Linux).
This approach allows you to leverage your NVIDIA GPU for private, secure, and cost-effective AI inference without relying on cloud services.
Perfect for development, testing, or production scenarios where data privacy or offline capabilities are required.
Here is a step-by-step guide to setting up a local NVIDIA NIM model:
1. Follow installation instructions from [NVIDIA Website](https://docs.nvidia.com/nim/wsl2/latest/getting-started.html)
2. Install the local model. For Llama 3.1-8b follow [instructions](https://build.nvidia.com/meta/llama-3_1-8b-instruct/deploy)
3. Configure your crewai local models:
```python Code
from crewai.llm import LLM
local_nvidia_nim_llm = LLM(
model="openai/meta/llama-3.1-8b-instruct", # it's an openai-api compatible model
base_url="http://localhost:8000/v1",
api_key="<your_api_key|any text if you have not configured it>", # api_key is required, but you can use any text
)
# Then you can use it in your crew:
@CrewBase
class MyCrew():
# ...
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
llm=local_nvidia_nim_llm
)
# ...
```
</Accordion>
<Accordion title="Groq">
Set the following environment variables in your `.env` file:
@@ -396,7 +474,7 @@ In this section, you'll find detailed examples that help you select, configure,
WATSONX_URL=<your-url>
WATSONX_APIKEY=<your-apikey>
WATSONX_PROJECT_ID=<your-project-id>
# Optional
WATSONX_TOKEN=<your-token>
WATSONX_DEPLOYMENT_SPACE_ID=<your-space-id>
@@ -413,7 +491,7 @@ In this section, you'll find detailed examples that help you select, configure,
<Accordion title="Ollama (Local LLMs)">
1. Install Ollama: [ollama.ai](https://ollama.ai/)
2. Run a model: `ollama run llama2`
2. Run a model: `ollama run llama3`
3. Configure:
```python Code
@@ -522,7 +600,7 @@ In this section, you'll find detailed examples that help you select, configure,
```toml Code
OPENROUTER_API_KEY=<your-api-key>
```
Example usage in your CrewAI project:
```python Code
llm = LLM(
@@ -645,7 +723,7 @@ Learn how to get the most out of your LLM configuration:
- Small tasks (up to 4K tokens): Standard models
- Medium tasks (between 4K-32K): Enhanced models
- Large tasks (over 32K): Large context models
```python
# Configure model with appropriate settings
llm = LLM(
@@ -682,11 +760,11 @@ Learn how to get the most out of your LLM configuration:
<Warning>
Most authentication issues can be resolved by checking API key format and environment variable names.
</Warning>
```bash
# OpenAI
OPENAI_API_KEY=sk-...
# Anthropic
ANTHROPIC_API_KEY=sk-ant-...
```
@@ -695,11 +773,11 @@ Learn how to get the most out of your LLM configuration:
<Check>
Always include the provider prefix in model names
</Check>
```python
# Correct
llm = LLM(model="openai/gpt-4")
# Incorrect
llm = LLM(model="gpt-4")
```
@@ -709,4 +787,9 @@ Learn how to get the most out of your LLM configuration:
Use larger context models for extensive tasks
</Tip>
```python
# Large context model
llm = LLM(model="openai/gpt-4o") # 128K tokens
```
</Tab>
</Tabs>

View File

@@ -60,7 +60,8 @@ my_crew = Crew(
```python Code
from crewai import Crew, Process
from crewai.memory import LongTermMemory, ShortTermMemory, EntityMemory
from crewai.memory.storage import LTMSQLiteStorage, RAGStorage
from crewai.memory.storage.rag_storage import RAGStorage
from crewai.memory.storage.ltm_sqlite_storage import LTMSQLiteStorage
from typing import List, Optional
# Assemble your crew with memory capabilities
@@ -119,7 +120,7 @@ Example using environment variables:
import os
from crewai import Crew
from crewai.memory import LongTermMemory
from crewai.memory.storage import LTMSQLiteStorage
from crewai.memory.storage.ltm_sqlite_storage import LTMSQLiteStorage
# Configure storage path using environment variable
storage_path = os.getenv("CREWAI_STORAGE_DIR", "./storage")
@@ -148,7 +149,7 @@ crew = Crew(memory=True) # Uses default storage locations
```python
from crewai import Crew
from crewai.memory import LongTermMemory
from crewai.memory.storage import LTMSQLiteStorage
from crewai.memory.storage.ltm_sqlite_storage import LTMSQLiteStorage
# Configure custom storage paths
crew = Crew(

223
docs/docs.json Normal file
View File

@@ -0,0 +1,223 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "palm",
"name": "CrewAI",
"colors": {
"primary": "#EB6658",
"light": "#F3A78B",
"dark": "#C94C3C"
},
"favicon": "favicon.svg",
"navigation": {
"tabs": [
{
"tab": "Get Started",
"groups": [
{
"group": "Get Started",
"pages": [
"introduction",
"installation",
"quickstart",
"changelog"
]
},
{
"group": "Guides",
"pages": [
{
"group": "Concepts",
"pages": [
"guides/concepts/evaluating-use-cases"
]
},
{
"group": "Agents",
"pages": [
"guides/agents/crafting-effective-agents"
]
},
{
"group": "Crews",
"pages": [
"guides/crews/first-crew"
]
},
{
"group": "Flows",
"pages": [
"guides/flows/first-flow",
"guides/flows/mastering-flow-state"
]
},
{
"group": "Advanced",
"pages": [
"guides/advanced/customizing-prompts",
"guides/advanced/fingerprinting"
]
}
]
},
{
"group": "Core Concepts",
"pages": [
"concepts/agents",
"concepts/tasks",
"concepts/crews",
"concepts/flows",
"concepts/knowledge",
"concepts/llms",
"concepts/processes",
"concepts/collaboration",
"concepts/training",
"concepts/memory",
"concepts/planning",
"concepts/testing",
"concepts/cli",
"concepts/tools",
"concepts/event-listener",
"concepts/langchain-tools",
"concepts/llamaindex-tools"
]
},
{
"group": "How to Guides",
"pages": [
"how-to/create-custom-tools",
"how-to/sequential-process",
"how-to/hierarchical-process",
"how-to/custom-manager-agent",
"how-to/llm-connections",
"how-to/customizing-agents",
"how-to/multimodal-agents",
"how-to/coding-agents",
"how-to/force-tool-output-as-result",
"how-to/human-input-on-execution",
"how-to/kickoff-async",
"how-to/kickoff-for-each",
"how-to/replay-tasks-from-latest-crew-kickoff",
"how-to/conditional-tasks",
"how-to/agentops-observability",
"how-to/langtrace-observability",
"how-to/mlflow-observability",
"how-to/openlit-observability",
"how-to/portkey-observability",
"how-to/langfuse-observability"
]
},
{
"group": "Tools",
"pages": [
"tools/aimindtool",
"tools/apifyactorstool",
"tools/bravesearchtool",
"tools/browserbaseloadtool",
"tools/codedocssearchtool",
"tools/codeinterpretertool",
"tools/composiotool",
"tools/csvsearchtool",
"tools/dalletool",
"tools/directorysearchtool",
"tools/directoryreadtool",
"tools/docxsearchtool",
"tools/exasearchtool",
"tools/filereadtool",
"tools/filewritetool",
"tools/firecrawlcrawlwebsitetool",
"tools/firecrawlscrapewebsitetool",
"tools/firecrawlsearchtool",
"tools/githubsearchtool",
"tools/hyperbrowserloadtool",
"tools/linkupsearchtool",
"tools/llamaindextool",
"tools/serperdevtool",
"tools/s3readertool",
"tools/s3writertool",
"tools/scrapegraphscrapetool",
"tools/scrapeelementfromwebsitetool",
"tools/jsonsearchtool",
"tools/mdxsearchtool",
"tools/mysqltool",
"tools/multiontool",
"tools/nl2sqltool",
"tools/patronustools",
"tools/pdfsearchtool",
"tools/pgsearchtool",
"tools/qdrantvectorsearchtool",
"tools/ragtool",
"tools/scrapewebsitetool",
"tools/scrapflyscrapetool",
"tools/seleniumscrapingtool",
"tools/snowflakesearchtool",
"tools/spidertool",
"tools/txtsearchtool",
"tools/visiontool",
"tools/weaviatevectorsearchtool",
"tools/websitesearchtool",
"tools/xmlsearchtool",
"tools/youtubechannelsearchtool",
"tools/youtubevideosearchtool"
]
},
{
"group": "Telemetry",
"pages": [
"telemetry"
]
}
]
},
{
"tab": "Examples",
"groups": [
{
"group": "Examples",
"pages": [
"examples/example"
]
}
]
}
],
"global": {
"anchors": [
{
"anchor": "Community",
"href": "https://community.crewai.com",
"icon": "discourse"
}
]
}
},
"logo": {
"light": "crew_only_logo.png",
"dark": "crew_only_logo.png"
},
"appearance": {
"default": "dark",
"strict": false
},
"navbar": {
"primary": {
"type": "github",
"href": "https://github.com/crewAIInc/crewAI"
}
},
"search": {
"prompt": "Search CrewAI docs"
},
"seo": {
"indexing": "navigable"
},
"footer": {
"socials": {
"website": "https://crewai.com",
"x": "https://x.com/crewAIInc",
"github": "https://github.com/crewAIInc/crewAI",
"linkedin": "https://www.linkedin.com/company/crewai-inc",
"youtube": "https://youtube.com/@crewAIInc",
"reddit": "https://www.reddit.com/r/crewAIInc/"
}
}
}

View File

@@ -1,4 +1,5 @@
---title: Customizing Prompts
---
title: Customizing Prompts
description: Dive deeper into low-level prompt customization for CrewAI, enabling super custom and complex use cases for different models and languages.
icon: message-pen
---

View File

@@ -0,0 +1,179 @@
# CrewAI Open-Source Deployment
CrewAI Open-Source Deployment provides a simple way to containerize and deploy CrewAI workflows without requiring a CrewAI+ account.
## Installation
```bash
pip install crewai
```
## Quick Start
### 1. Create a deployment configuration file
Create a file named `deployment.yaml`:
```yaml
# CrewAI Deployment Configuration
name: my-crewai-app
port: 8000
host: 127.0.0.1 # Default to localhost for security
# Crews configuration
crews:
- name: research_crew
module_path: ./crews/research_crew.py
class_name: ResearchCrew
- name: analysis_crew
module_path: ./crews/analysis_crew.py
class_name: AnalysisCrew
# Flows configuration
flows:
- name: data_processing_flow
module_path: ./flows/data_processing_flow.py
class_name: DataProcessingFlow
- name: reporting_flow
module_path: ./flows/reporting_flow.py
class_name: ReportingFlow
# Additional configuration
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
- CREWAI_LOG_LEVEL=INFO
```
### 2. Create a deployment
```bash
crewai os-deploy create deployment.yaml
```
This command will:
- Create a deployment directory at `./deployments/{name}`
- Copy your crew and flow modules to the deployment directory
- Generate Docker configuration files
### 3. Build the Docker image
```bash
crewai os-deploy build my-crewai-app
```
### 4. Start the deployment
```bash
crewai os-deploy start my-crewai-app
```
### 5. Use the API
The API will be available at http://localhost:8000 with the following endpoints:
- `GET /`: Get status and list of available crews and flows
- `POST /run/crew/{crew_name}`: Run a crew with specified inputs
- `POST /run/flow/{flow_name}`: Run a flow with specified inputs
Example request:
```bash
curl -X POST http://localhost:8000/run/crew/research_crew \
-H "Content-Type: application/json" \
-d '{"inputs": {"topic": "AI research"}}'
```
### 6. View logs
```bash
crewai os-deploy logs my-crewai-app
```
### 7. Stop the deployment
```bash
crewai os-deploy stop my-crewai-app
```
## API Reference
### GET /
Returns the status of the deployment and lists available crews and flows.
**Response:**
```json
{
"status": "running",
"crews": ["research_crew", "analysis_crew"],
"flows": ["data_processing_flow", "reporting_flow"]
}
```
### POST /run/crew/{crew_name}
Runs a crew with the specified inputs.
**Request Body:**
```json
{
"inputs": {
"key1": "value1",
"key2": "value2"
}
}
```
**Response:**
```json
{
"result": {
"raw": "Crew execution result"
}
}
```
### POST /run/flow/{flow_name}
Runs a flow with the specified inputs.
**Request Body:**
```json
{
"inputs": {
"key1": "value1",
"key2": "value2"
}
}
```
**Response:**
```json
{
"result": {
"value": "Flow execution result"
}
}
```
## CLI Reference
| Command | Description |
|---------|-------------|
| `crewai os-deploy create <config_path>` | Create a new deployment from a configuration file |
| `crewai os-deploy build <deployment_name>` | Build Docker image for deployment |
| `crewai os-deploy start <deployment_name>` | Start a deployment |
| `crewai os-deploy stop <deployment_name>` | Stop a deployment |
| `crewai os-deploy logs <deployment_name>` | Show logs for a deployment |
## Comparison with CrewAI+
| Feature | Open-Source Deployment | CrewAI+ |
|---------|------------------------|---------|
| Requires CrewAI+ account | No | Yes |
| Self-hosted | Yes | No |
| Managed infrastructure | No | Yes |
| Scaling | Manual | Automatic |
| Monitoring | Basic logs | Advanced monitoring |

View File

@@ -1,225 +0,0 @@
{
"name": "CrewAI",
"theme": "venus",
"logo": {
"dark": "crew_only_logo.png",
"light": "crew_only_logo.png"
},
"favicon": "favicon.svg",
"colors": {
"primary": "#EB6658",
"light": "#F3A78B",
"dark": "#C94C3C",
"anchors": {
"from": "#737373",
"to": "#EB6658"
}
},
"seo": {
"indexHiddenPages": false
},
"modeToggle": {
"default": "dark",
"isHidden": false
},
"feedback": {
"suggestEdit": true,
"raiseIssue": true,
"thumbsRating": true
},
"topbarCtaButton": {
"type": "github",
"url": "https://github.com/crewAIInc/crewAI"
},
"primaryTab": {
"name": "Get Started"
},
"tabs": [
{
"name": "Examples",
"url": "examples"
}
],
"anchors": [
{
"name": "Community",
"icon": "discourse",
"url": "https://community.crewai.com"
},
{
"name": "Changelog",
"icon": "timeline",
"url": "https://github.com/crewAIInc/crewAI/releases"
}
],
"navigation": [
{
"group": "Get Started",
"pages": [
"introduction",
"installation",
"quickstart"
]
},
{
"group": "Guides",
"pages": [
{
"group": "Concepts",
"pages": [
"guides/concepts/evaluating-use-cases"
]
},
{
"group": "Agents",
"pages": [
"guides/agents/crafting-effective-agents"
]
},
{
"group": "Crews",
"pages": [
"guides/crews/first-crew"
]
},
{
"group": "Flows",
"pages": [
"guides/flows/first-flow",
"guides/flows/mastering-flow-state"
]
},
{
"group": "Advanced",
"pages": [
"guides/advanced/customizing-prompts",
"guides/advanced/fingerprinting"
]
}
]
},
{
"group": "Core Concepts",
"pages": [
"concepts/agents",
"concepts/tasks",
"concepts/crews",
"concepts/flows",
"concepts/knowledge",
"concepts/llms",
"concepts/processes",
"concepts/collaboration",
"concepts/training",
"concepts/memory",
"concepts/planning",
"concepts/testing",
"concepts/cli",
"concepts/tools",
"concepts/event-listener",
"concepts/langchain-tools",
"concepts/llamaindex-tools"
]
},
{
"group": "How to Guides",
"pages": [
"how-to/create-custom-tools",
"how-to/sequential-process",
"how-to/hierarchical-process",
"how-to/custom-manager-agent",
"how-to/llm-connections",
"how-to/customizing-agents",
"how-to/multimodal-agents",
"how-to/coding-agents",
"how-to/force-tool-output-as-result",
"how-to/human-input-on-execution",
"how-to/kickoff-async",
"how-to/kickoff-for-each",
"how-to/replay-tasks-from-latest-crew-kickoff",
"how-to/conditional-tasks",
"how-to/agentops-observability",
"how-to/langtrace-observability",
"how-to/mlflow-observability",
"how-to/openlit-observability",
"how-to/portkey-observability",
"how-to/langfuse-observability"
]
},
{
"group": "Examples",
"pages": [
"examples/example"
]
},
{
"group": "Tools",
"pages": [
"tools/aimindtool",
"tools/apifyactorstool",
"tools/bravesearchtool",
"tools/browserbaseloadtool",
"tools/codedocssearchtool",
"tools/codeinterpretertool",
"tools/composiotool",
"tools/csvsearchtool",
"tools/dalletool",
"tools/directorysearchtool",
"tools/directoryreadtool",
"tools/docxsearchtool",
"tools/exasearchtool",
"tools/filereadtool",
"tools/filewritetool",
"tools/firecrawlcrawlwebsitetool",
"tools/firecrawlscrapewebsitetool",
"tools/firecrawlsearchtool",
"tools/githubsearchtool",
"tools/hyperbrowserloadtool",
"tools/linkupsearchtool",
"tools/llamaindextool",
"tools/serperdevtool",
"tools/s3readertool",
"tools/s3writertool",
"tools/scrapegraphscrapetool",
"tools/scrapeelementfromwebsitetool",
"tools/jsonsearchtool",
"tools/mdxsearchtool",
"tools/mysqltool",
"tools/multiontool",
"tools/nl2sqltool",
"tools/patronustools",
"tools/pdfsearchtool",
"tools/pgsearchtool",
"tools/qdrantvectorsearchtool",
"tools/ragtool",
"tools/scrapewebsitetool",
"tools/scrapflyscrapetool",
"tools/seleniumscrapingtool",
"tools/snowflakesearchtool",
"tools/spidertool",
"tools/txtsearchtool",
"tools/visiontool",
"tools/weaviatevectorsearchtool",
"tools/websitesearchtool",
"tools/xmlsearchtool",
"tools/youtubechannelsearchtool",
"tools/youtubevideosearchtool"
]
},
{
"group": "Telemetry",
"pages": [
"telemetry"
]
}
],
"search": {
"prompt": "Search CrewAI docs"
},
"footerSocials": {
"website": "https://crewai.com",
"x": "https://x.com/crewAIInc",
"github": "https://github.com/crewAIInc/crewAI",
"linkedin": "https://www.linkedin.com/company/crewai-inc",
"youtube": "https://youtube.com/@crewAIInc"
}
}

View File

@@ -300,7 +300,7 @@ email_summarizer:
```
<Tip>
Note how we use the same name for the agent in the `tasks.yaml` (`email_summarizer_task`) file as the method name in the `crew.py` (`email_summarizer_task`) file.
Note how we use the same name for the task in the `tasks.yaml` (`email_summarizer_task`) file as the method name in the `crew.py` (`email_summarizer_task`) file.
</Tip>
```yaml tasks.yaml

View File

@@ -7,8 +7,10 @@ icon: file-code
# `JSONSearchTool`
<Note>
The JSONSearchTool is currently in an experimental phase. This means the tool is under active development, and users might encounter unexpected behavior or changes.
We highly encourage feedback on any issues or suggestions for improvements.
The JSONSearchTool is currently in an experimental phase. This means the tool
is under active development, and users might encounter unexpected behavior or
changes. We highly encourage feedback on any issues or suggestions for
improvements.
</Note>
## Description
@@ -60,7 +62,7 @@ tool = JSONSearchTool(
# stream=true,
},
},
"embedder": {
"embedding_model": {
"provider": "google", # or openai, ollama, ...
"config": {
"model": "models/embedding-001",
@@ -70,4 +72,4 @@ tool = JSONSearchTool(
},
}
)
```
```

View File

@@ -8,8 +8,8 @@ icon: vector-square
## Description
The `RagTool` is designed to answer questions by leveraging the power of Retrieval-Augmented Generation (RAG) through EmbedChain.
It provides a dynamic knowledge base that can be queried to retrieve relevant information from various data sources.
The `RagTool` is designed to answer questions by leveraging the power of Retrieval-Augmented Generation (RAG) through EmbedChain.
It provides a dynamic knowledge base that can be queried to retrieve relevant information from various data sources.
This tool is particularly useful for applications that require access to a vast array of information and need to provide contextually relevant answers.
## Example
@@ -138,7 +138,7 @@ config = {
"model": "gpt-4",
}
},
"embedder": {
"embedding_model": {
"provider": "openai",
"config": {
"model": "text-embedding-ada-002"
@@ -151,4 +151,4 @@ rag_tool = RagTool(config=config, summarize=True)
## Conclusion
The `RagTool` provides a powerful way to create and query knowledge bases from various data sources. By leveraging Retrieval-Augmented Generation, it enables agents to access and retrieve relevant information efficiently, enhancing their ability to provide accurate and contextually appropriate responses.
The `RagTool` provides a powerful way to create and query knowledge bases from various data sources. By leveraging Retrieval-Augmented Generation, it enables agents to access and retrieve relevant information efficiently, enhancing their ability to provide accurate and contextually appropriate responses.

View File

@@ -0,0 +1,69 @@
from pydantic import BaseModel
from crewai import Agent, Crew, Task
from crewai.flow import Flow, listen, start
class AnalysisState(BaseModel):
topic: str = ""
research_results: str = ""
analysis: str = ""
class AnalysisFlow(Flow[AnalysisState]):
def __init__(self):
super().__init__()
# Create agents
self.researcher = Agent(
role="Researcher",
goal="Research the latest information",
backstory="You are an expert researcher"
)
self.analyst = Agent(
role="Analyst",
goal="Analyze research findings",
backstory="You are an expert analyst"
)
@start()
def start_research(self):
print(f"Starting research on topic: {self.state.topic}")
# Create research task
research_task = Task(
description=f"Research the latest information about {self.state.topic}",
expected_output="A summary of research findings",
agent=self.researcher
)
# Run research task
crew = Crew(agents=[self.researcher], tasks=[research_task])
result = crew.kickoff()
self.state.research_results = result.raw
return result.raw
@listen(start_research)
def analyze_results(self, research_results):
print("Analyzing research results")
# Create analysis task
analysis_task = Task(
description=f"Analyze the following research results: {research_results}",
expected_output="A detailed analysis",
agent=self.analyst
)
# Run analysis task
crew = Crew(agents=[self.analyst], tasks=[analysis_task])
result = crew.kickoff()
self.state.analysis = result.raw
return result.raw
# For testing
if __name__ == "__main__":
flow = AnalysisFlow()
result = flow.kickoff(inputs={"topic": "Artificial Intelligence"})
print(f"Final result: {result}")

View File

@@ -0,0 +1,10 @@
# CrewAI Deployment Configuration
name: analysis-app
port: 8000
host: 127.0.0.1 # Default to localhost for security
# Flows configuration
flows:
- name: analysis_flow
module_path: ./analysis_flow.py
class_name: AnalysisFlow

View File

@@ -17,9 +17,9 @@ dependencies = [
"pdfplumber>=0.11.4",
"regex>=2024.9.11",
# Telemetry and Monitoring
"opentelemetry-api>=1.22.0",
"opentelemetry-sdk>=1.22.0",
"opentelemetry-exporter-otlp-proto-http>=1.22.0",
"opentelemetry-api>=1.30.0",
"opentelemetry-sdk>=1.30.0",
"opentelemetry-exporter-otlp-proto-http>=1.30.0",
# Data Handling
"chromadb>=0.5.23",
"openpyxl>=3.1.5",
@@ -87,6 +87,9 @@ dev-dependencies = [
[project.scripts]
crewai = "crewai.cli.cli:crewai"
[project.entry-points."crewai.cli"]
deploy = "crewai.deployment.cli:deploy"
[tool.mypy]
ignore_missing_imports = true
disable_error_code = 'import-untyped'

View File

@@ -124,9 +124,9 @@ class CrewAgentParser:
)
def _extract_thought(self, text: str) -> str:
thought_index = text.find("\n\nAction")
thought_index = text.find("\nAction")
if thought_index == -1:
thought_index = text.find("\n\nFinal Answer")
thought_index = text.find("\nFinal Answer")
if thought_index == -1:
return ""
thought = text[:thought_index].strip()
@@ -136,7 +136,7 @@ class CrewAgentParser:
def _clean_action(self, text: str) -> str:
"""Clean action string by removing non-essential formatting characters."""
return re.sub(r"^\s*\*+\s*|\s*\*+\s*$", "", text).strip()
return text.strip().strip("*").strip()
def _safe_repair_json(self, tool_input: str) -> str:
UNABLE_TO_REPAIR_JSON_RESULTS = ['""', "{}"]

View File

@@ -8,6 +8,7 @@ from crewai.cli.add_crew_to_flow import add_crew_to_flow
from crewai.cli.create_crew import create_crew
from crewai.cli.create_flow import create_flow
from crewai.cli.crew_chat import run_chat
from crewai.deployment.cli import deploy as deploy_command
from crewai.memory.storage.kickoff_task_outputs_storage import (
KickoffTaskOutputsSQLiteStorage,
)
@@ -356,5 +357,8 @@ def chat():
run_chat()
# Add the open-source deployment command
crewai.add_command(deploy_command, name="os-deploy")
if __name__ == "__main__":
crewai()

View File

@@ -1,4 +1,5 @@
import subprocess
from functools import lru_cache
class Repository:
@@ -35,6 +36,7 @@ class Repository:
encoding="utf-8",
).strip()
@lru_cache(maxsize=None)
def is_git_repo(self) -> bool:
"""Check if the current directory is a git repository."""
try:

View File

@@ -10,6 +10,7 @@ dependencies = [
[project.scripts]
kickoff = "{{folder_name}}.main:kickoff"
run_crew = "{{folder_name}}.main:kickoff"
plot = "{{folder_name}}.main:plot"
[build-system]

View File

View File

@@ -0,0 +1,103 @@
import os
import click
from rich.console import Console
from crewai.deployment.main import Deployment
console = Console()
@click.group()
def deploy():
"""CrewAI deployment tools for containerizing and running CrewAI workflows."""
pass
@deploy.command("create")
@click.argument("config_path", type=click.Path(exists=True))
def create_deployment(config_path):
"""Create a new deployment from a configuration file."""
try:
console.print("Creating deployment...", style="bold blue")
deployment = Deployment(config_path)
deployment.prepare()
console.print(f"Deployment prepared at {deployment.deployment_dir}", style="bold green")
console.print(f"Configuration:", style="bold blue")
console.print(f" Name: {deployment.config.name}")
console.print(f" Port: {deployment.config.port}")
console.print(f" Host: {deployment.config.host}")
console.print(f" Crews: {[c.name for c in deployment.config.crews]}")
console.print(f" Flows: {[f.name for f in deployment.config.flows]}")
except Exception as e:
console.print(f"Error creating deployment: {e}", style="bold red")
@deploy.command("build")
@click.argument("deployment_name")
def build_deployment(deployment_name):
"""Build Docker image for deployment."""
try:
console.print("Building deployment...", style="bold blue")
deployment_dir = f"./deployments/{deployment_name}"
if not os.path.exists(deployment_dir):
console.print(f"Deployment {deployment_name} not found", style="bold red")
return
config_path = f"{deployment_dir}/deployment_config.json"
deployment = Deployment(config_path)
deployment.build()
console.print("Build completed successfully", style="bold green")
except Exception as e:
console.print(f"Error building deployment: {e}", style="bold red")
@deploy.command("start")
@click.argument("deployment_name")
def start_deployment(deployment_name):
"""Start a deployment."""
try:
console.print("Starting deployment...", style="bold blue")
deployment_dir = f"./deployments/{deployment_name}"
if not os.path.exists(deployment_dir):
console.print(f"Deployment {deployment_name} not found", style="bold red")
return
config_path = f"{deployment_dir}/deployment_config.json"
deployment = Deployment(config_path)
deployment.start()
console.print(f"Deployment {deployment_name} started", style="bold green")
console.print(f"API server running at http://{deployment.config.host}:{deployment.config.port}")
except Exception as e:
console.print(f"Error starting deployment: {e}", style="bold red")
@deploy.command("stop")
@click.argument("deployment_name")
def stop_deployment(deployment_name):
"""Stop a deployment."""
try:
console.print("Stopping deployment...", style="bold blue")
deployment_dir = f"./deployments/{deployment_name}"
if not os.path.exists(deployment_dir):
console.print(f"Deployment {deployment_name} not found", style="bold red")
return
config_path = f"{deployment_dir}/deployment_config.json"
deployment = Deployment(config_path)
deployment.stop()
console.print(f"Deployment {deployment_name} stopped", style="bold green")
except Exception as e:
console.print(f"Error stopping deployment: {e}", style="bold red")
@deploy.command("logs")
@click.argument("deployment_name")
def show_logs(deployment_name):
"""Show logs for a deployment."""
try:
console.print("Fetching logs...", style="bold blue")
deployment_dir = f"./deployments/{deployment_name}"
if not os.path.exists(deployment_dir):
console.print(f"Deployment {deployment_name} not found", style="bold red")
return
config_path = f"{deployment_dir}/deployment_config.json"
deployment = Deployment(config_path)
deployment.logs()
except Exception as e:
console.print(f"Error fetching logs: {e}", style="bold red")

View File

@@ -0,0 +1,93 @@
import os
import yaml
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field, validator
class CrewConfig(BaseModel):
"""Configuration for a crew in a deployment."""
name: str = Field(..., min_length=1)
module_path: str = Field(..., min_length=1)
class_name: str = Field(..., min_length=1)
class FlowConfig(BaseModel):
"""Configuration for a flow in a deployment."""
name: str = Field(..., min_length=1)
module_path: str = Field(..., min_length=1)
class_name: str = Field(..., min_length=1)
class DeploymentConfig(BaseModel):
"""Main configuration for a CrewAI deployment."""
name: str = Field(..., min_length=1)
port: int = Field(..., gt=0, lt=65536)
host: Optional[str] = Field(default="127.0.0.1")
crews: List[CrewConfig] = Field(default_factory=list)
flows: List[FlowConfig] = Field(default_factory=list)
environment: List[str] = Field(default_factory=list)
@validator('environment', pre=True)
def parse_environment(cls, v):
if not v:
return []
return v
class Config:
"""
Configuration manager for CrewAI deployments.
"""
def __init__(self, config_path: str):
self.config_path = Path(config_path)
self._config_data = self._load_config()
self.config = self._validate_config()
def _load_config(self) -> Dict[str, Any]:
"""Load configuration from YAML file."""
if not self.config_path.exists():
raise FileNotFoundError(f"Configuration file not found: {self.config_path}")
with open(self.config_path, "r") as f:
try:
return yaml.safe_load(f)
except yaml.YAMLError as e:
raise ValueError(f"Invalid YAML in configuration file: {e}")
def _validate_config(self) -> DeploymentConfig:
"""Validate configuration using Pydantic."""
try:
return DeploymentConfig(**self._config_data)
except Exception as e:
raise ValueError(f"Invalid configuration: {e}")
@property
def name(self) -> str:
"""Get deployment name."""
return self.config.name
@property
def port(self) -> int:
"""Get server port."""
return self.config.port
@property
def host(self) -> str:
"""Get host configuration."""
return self.config.host or "127.0.0.1"
@property
def crews(self) -> List[CrewConfig]:
"""Get crews configuration."""
return self.config.crews
@property
def flows(self) -> List[FlowConfig]:
"""Get flows configuration."""
return self.config.flows
@property
def environment(self) -> List[str]:
"""Get environment variables configuration."""
return self.config.environment

View File

View File

@@ -0,0 +1,79 @@
import os
import shutil
import subprocess
from pathlib import Path
from typing import Dict, List, Optional
from crewai.deployment.docker.exceptions import DockerBuildError, DockerComposeError, DockerRunError
class DockerContainer:
"""
Manages Docker containers for CrewAI deployments.
"""
def __init__(self, deployment_dir: str, name: str):
self.deployment_dir = Path(deployment_dir)
self.name = name
self.dockerfile_path = self.deployment_dir / "Dockerfile"
self.compose_path = self.deployment_dir / "docker-compose.yml"
def generate_dockerfile(self, requirements: Optional[List[str]] = None):
"""Generate a Dockerfile for the deployment."""
template_dir = Path(__file__).parent / "templates"
dockerfile_template = template_dir / "Dockerfile"
os.makedirs(self.deployment_dir, exist_ok=True)
shutil.copy(dockerfile_template, self.dockerfile_path)
# Add requirements if specified
if requirements:
with open(self.dockerfile_path, "a") as f:
f.write("\n# Additional requirements\n")
f.write(f"RUN pip install {' '.join(requirements)}\n")
def generate_compose_file(self, port: int = 8000):
"""Generate a docker-compose.yml file for the deployment."""
template_dir = Path(__file__).parent / "templates"
compose_template = template_dir / "docker-compose.yml"
# Read template and replace placeholders
with open(compose_template, "r") as f:
template = f.read()
compose_content = template.replace("{{name}}", self.name)
compose_content = compose_content.replace("{{port}}", str(port))
with open(self.compose_path, "w") as f:
f.write(compose_content)
def build(self):
"""Build the Docker image."""
try:
cmd = ["docker", "build", "-t", f"crewai-{self.name}", "."]
subprocess.run(cmd, check=True, cwd=self.deployment_dir)
except subprocess.CalledProcessError as e:
raise DockerBuildError(f"Failed to build Docker image: {e}")
def start(self):
"""Start the Docker containers using docker-compose."""
try:
cmd = ["docker-compose", "up", "-d"]
subprocess.run(cmd, check=True, cwd=self.deployment_dir)
except subprocess.CalledProcessError as e:
raise DockerRunError(f"Failed to start Docker containers: {e}")
def stop(self):
"""Stop the Docker containers."""
try:
cmd = ["docker-compose", "down"]
subprocess.run(cmd, check=True, cwd=self.deployment_dir)
except subprocess.CalledProcessError as e:
raise DockerComposeError(f"Failed to stop Docker containers: {e}")
def logs(self):
"""Get container logs."""
try:
cmd = ["docker-compose", "logs"]
subprocess.run(cmd, check=True, cwd=self.deployment_dir)
except subprocess.CalledProcessError as e:
raise DockerComposeError(f"Failed to get Docker logs: {e}")

View File

@@ -0,0 +1,18 @@
class DockerError(Exception):
"""Base exception for Docker-related errors in CrewAI deployments."""
pass
class DockerBuildError(DockerError):
"""Exception raised when Docker build fails."""
pass
class DockerRunError(DockerError):
"""Exception raised when Docker container fails to run."""
pass
class DockerComposeError(DockerError):
"""Exception raised when docker-compose commands fail."""
pass

View File

@@ -0,0 +1,20 @@
FROM python:3.10-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install CrewAI
RUN pip install --no-cache-dir crewai
# Copy application code
COPY . /app/
# Set environment variables
ENV PYTHONUNBUFFERED=1
# Run the application
CMD ["python", "server.py"]

View File

@@ -0,0 +1,14 @@
version: '3'
services:
crewai:
build: .
image: crewai-{{name}}
container_name: crewai-{{name}}
ports:
- "{{port}}:{{port}}"
volumes:
- .:/app
environment:
- PORT={{port}}
restart: unless-stopped

View File

@@ -0,0 +1,161 @@
import json
import logging
import os
import shutil
from pathlib import Path
from typing import Any, Dict, List, Optional
from crewai.deployment.config import Config
from crewai.deployment.docker.container import DockerContainer
from crewai.deployment.docker.exceptions import DockerError
# Configure structured logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("crewai.deployment")
class Deployment:
"""
Handles the deployment of CrewAI crews and flows.
"""
def __init__(self, config_path: str):
logger.info(f"Initializing deployment from config: {config_path}")
self.config = Config(config_path)
self.deployment_dir = Path(f"./deployments/{self.config.name}")
self.docker = DockerContainer(
deployment_dir=str(self.deployment_dir),
name=self.config.name
)
def prepare(self):
"""Prepare the deployment directory and files."""
logger.info(f"Preparing deployment: {self.config.name}")
# Create deployment directory
os.makedirs(self.deployment_dir, exist_ok=True)
# Create deployment config
deployment_config = {
"name": self.config.name,
"port": self.config.port,
"host": self.config.host,
"crews": [],
"flows": []
}
# Process crews
for crew_config in self.config.crews:
name = crew_config.name
module_path = crew_config.module_path
class_name = crew_config.class_name
logger.info(f"Processing crew: {name}")
# Copy crew module to deployment directory
source_path = Path(module_path)
dest_path = self.deployment_dir / source_path.name
if source_path.exists():
shutil.copy(source_path, dest_path)
logger.debug(f"Copied {source_path} to {dest_path}")
else:
logger.warning(f"Crew module not found: {source_path}")
# For testing purposes, create an empty file
with open(dest_path, 'w') as f:
pass
# Add to deployment config
deployment_config["crews"].append({
"name": name,
"module_path": os.path.basename(module_path),
"class_name": class_name
})
# Process flows
for flow_config in self.config.flows:
name = flow_config.name
module_path = flow_config.module_path
class_name = flow_config.class_name
logger.info(f"Processing flow: {name}")
# Copy flow module to deployment directory
source_path = Path(module_path)
dest_path = self.deployment_dir / source_path.name
if source_path.exists():
shutil.copy(source_path, dest_path)
logger.debug(f"Copied {source_path} to {dest_path}")
else:
logger.warning(f"Flow module not found: {source_path}")
# For testing purposes, create an empty file
with open(dest_path, 'w') as f:
pass
# Add to deployment config
deployment_config["flows"].append({
"name": name,
"module_path": os.path.basename(module_path),
"class_name": class_name
})
# Write deployment config
config_file = self.deployment_dir / "deployment_config.json"
with open(config_file, "w") as f:
json.dump(deployment_config, f, indent=2)
logger.info(f"Created deployment config: {config_file}")
# Copy server template
server_template = Path(__file__).parent / "templates" / "server.py"
server_dest = self.deployment_dir / "server.py"
shutil.copy(server_template, server_dest)
logger.info(f"Copied server template to {server_dest}")
# Generate Docker files
try:
self.docker.generate_dockerfile()
self.docker.generate_compose_file(port=self.config.port)
logger.info("Generated Docker configuration files")
except Exception as e:
logger.error(f"Failed to generate Docker files: {e}")
raise
def build(self):
"""Build the Docker image for the deployment."""
logger.info(f"Building Docker image for {self.config.name}")
try:
self.docker.build()
logger.info("Docker image built successfully")
except DockerError as e:
logger.error(f"Failed to build Docker image: {e}")
raise
def start(self):
"""Start the deployment."""
logger.info(f"Starting deployment {self.config.name}")
try:
self.docker.start()
logger.info(f"Deployment started at http://{self.config.host}:{self.config.port}")
except DockerError as e:
logger.error(f"Failed to start deployment: {e}")
raise
def stop(self):
"""Stop the deployment."""
logger.info(f"Stopping deployment {self.config.name}")
try:
self.docker.stop()
logger.info("Deployment stopped")
except DockerError as e:
logger.error(f"Failed to stop deployment: {e}")
raise
def logs(self):
"""Get deployment logs."""
logger.info(f"Fetching logs for {self.config.name}")
try:
self.docker.logs()
except DockerError as e:
logger.error(f"Failed to fetch logs: {e}")
raise

View File

@@ -0,0 +1,29 @@
# CrewAI Deployment Configuration
name: my-crewai-app
port: 8000
host: 127.0.0.1 # Default to localhost for security
# Crews configuration
crews:
- name: research_crew
module_path: ./crews/research_crew.py
class_name: ResearchCrew
- name: analysis_crew
module_path: ./crews/analysis_crew.py
class_name: AnalysisCrew
# Flows configuration
flows:
- name: data_processing_flow
module_path: ./flows/data_processing_flow.py
class_name: DataProcessingFlow
- name: reporting_flow
module_path: ./flows/reporting_flow.py
class_name: ReportingFlow
# Additional configuration
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
- CREWAI_LOG_LEVEL=INFO

View File

@@ -0,0 +1,94 @@
import os
import json
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import uvicorn
import importlib.util
import sys
# Define API models
class RunRequest(BaseModel):
inputs: dict = {}
class RunResponse(BaseModel):
result: dict
# Initialize FastAPI app
app = FastAPI(title="CrewAI Deployment Server")
# Load crew and flow modules
def load_module(module_path, module_name):
if not os.path.exists(module_path):
raise ImportError(f"Module file {module_path} not found")
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
# Load configuration
with open("deployment_config.json", "r") as f:
config = json.load(f)
# Initialize crews and flows
crews = {}
flows = {}
for crew_config in config.get("crews", []):
name = crew_config["name"]
module_path = crew_config["module_path"]
class_name = crew_config["class_name"]
module = load_module(module_path, f"crew_{name}")
crew_class = getattr(module, class_name)
crews[name] = crew_class()
for flow_config in config.get("flows", []):
name = flow_config["name"]
module_path = flow_config["module_path"]
class_name = flow_config["class_name"]
module = load_module(module_path, f"flow_{name}")
flow_class = getattr(module, class_name)
flows[name] = flow_class()
# Define API endpoints
@app.get("/")
def read_root():
return {"status": "running", "crews": list(crews.keys()), "flows": list(flows.keys())}
@app.post("/run/crew/{crew_name}", response_model=RunResponse)
def run_crew(crew_name: str, request: RunRequest):
if crew_name not in crews:
raise HTTPException(
status_code=404,
detail=f"Crew '{crew_name}' not found. Available crews: {list(crews.keys())}"
)
try:
crew_instance = crews[crew_name].crew()
result = crew_instance.kickoff(inputs=request.inputs)
return {"result": {"raw": result.raw}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/run/flow/{flow_name}", response_model=RunResponse)
def run_flow(flow_name: str, request: RunRequest):
if flow_name not in flows:
raise HTTPException(
status_code=404,
detail=f"Flow '{flow_name}' not found. Available flows: {list(flows.keys())}"
)
try:
flow_instance = flows[flow_name]
result = flow_instance.kickoff(inputs=request.inputs)
return {"result": {"value": str(result)}}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error running flow: {str(e)}")
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8000))
host = os.environ.get("HOST", "127.0.0.1") # Default to localhost instead of 0.0.0.0
uvicorn.run(app, host=host, port=port)

View File

View File

@@ -114,6 +114,60 @@ LLM_CONTEXT_WINDOW_SIZES = {
"Llama-3.2-11B-Vision-Instruct": 16384,
"Meta-Llama-3.2-3B-Instruct": 4096,
"Meta-Llama-3.2-1B-Instruct": 16384,
# bedrock
"us.amazon.nova-pro-v1:0": 300000,
"us.amazon.nova-micro-v1:0": 128000,
"us.amazon.nova-lite-v1:0": 300000,
"us.anthropic.claude-3-5-sonnet-20240620-v1:0": 200000,
"us.anthropic.claude-3-5-haiku-20241022-v1:0": 200000,
"us.anthropic.claude-3-5-sonnet-20241022-v2:0": 200000,
"us.anthropic.claude-3-7-sonnet-20250219-v1:0": 200000,
"us.anthropic.claude-3-sonnet-20240229-v1:0": 200000,
"us.anthropic.claude-3-opus-20240229-v1:0": 200000,
"us.anthropic.claude-3-haiku-20240307-v1:0": 200000,
"us.meta.llama3-2-11b-instruct-v1:0": 128000,
"us.meta.llama3-2-3b-instruct-v1:0": 131000,
"us.meta.llama3-2-90b-instruct-v1:0": 128000,
"us.meta.llama3-2-1b-instruct-v1:0": 131000,
"us.meta.llama3-1-8b-instruct-v1:0": 128000,
"us.meta.llama3-1-70b-instruct-v1:0": 128000,
"us.meta.llama3-3-70b-instruct-v1:0": 128000,
"us.meta.llama3-1-405b-instruct-v1:0": 128000,
"eu.anthropic.claude-3-5-sonnet-20240620-v1:0": 200000,
"eu.anthropic.claude-3-sonnet-20240229-v1:0": 200000,
"eu.anthropic.claude-3-haiku-20240307-v1:0": 200000,
"eu.meta.llama3-2-3b-instruct-v1:0": 131000,
"eu.meta.llama3-2-1b-instruct-v1:0": 131000,
"apac.anthropic.claude-3-5-sonnet-20240620-v1:0": 200000,
"apac.anthropic.claude-3-5-sonnet-20241022-v2:0": 200000,
"apac.anthropic.claude-3-sonnet-20240229-v1:0": 200000,
"apac.anthropic.claude-3-haiku-20240307-v1:0": 200000,
"amazon.nova-pro-v1:0": 300000,
"amazon.nova-micro-v1:0": 128000,
"amazon.nova-lite-v1:0": 300000,
"anthropic.claude-3-5-sonnet-20240620-v1:0": 200000,
"anthropic.claude-3-5-haiku-20241022-v1:0": 200000,
"anthropic.claude-3-5-sonnet-20241022-v2:0": 200000,
"anthropic.claude-3-7-sonnet-20250219-v1:0": 200000,
"anthropic.claude-3-sonnet-20240229-v1:0": 200000,
"anthropic.claude-3-opus-20240229-v1:0": 200000,
"anthropic.claude-3-haiku-20240307-v1:0": 200000,
"anthropic.claude-v2:1": 200000,
"anthropic.claude-v2": 100000,
"anthropic.claude-instant-v1": 100000,
"meta.llama3-1-405b-instruct-v1:0": 128000,
"meta.llama3-1-70b-instruct-v1:0": 128000,
"meta.llama3-1-8b-instruct-v1:0": 128000,
"meta.llama3-70b-instruct-v1:0": 8000,
"meta.llama3-8b-instruct-v1:0": 8000,
"amazon.titan-text-lite-v1": 4000,
"amazon.titan-text-express-v1": 8000,
"cohere.command-text-v14": 4000,
"ai21.j2-mid-v1": 8191,
"ai21.j2-ultra-v1": 8191,
"ai21.jamba-instruct-v1:0": 256000,
"mistral.mistral-7b-instruct-v0:2": 32000,
"mistral.mixtral-8x7b-instruct-v0:1": 32000,
# mistral
"mistral-tiny": 32768,
"mistral-small-latest": 32768,

View File

@@ -1,7 +1,7 @@
import os
from typing import Any, Dict, List
from mem0 import MemoryClient
from mem0 import Memory, MemoryClient
from crewai.memory.storage.interface import Storage
@@ -32,13 +32,16 @@ class Mem0Storage(Storage):
mem0_org_id = config.get("org_id")
mem0_project_id = config.get("project_id")
# Initialize MemoryClient with available parameters
if mem0_org_id and mem0_project_id:
self.memory = MemoryClient(
api_key=mem0_api_key, org_id=mem0_org_id, project_id=mem0_project_id
)
# Initialize MemoryClient or Memory based on the presence of the mem0_api_key
if mem0_api_key:
if mem0_org_id and mem0_project_id:
self.memory = MemoryClient(
api_key=mem0_api_key, org_id=mem0_org_id, project_id=mem0_project_id
)
else:
self.memory = MemoryClient(api_key=mem0_api_key)
else:
self.memory = MemoryClient(api_key=mem0_api_key)
self.memory = Memory() # Fallback to Memory if no Mem0 API key is provided
def _sanitize_role(self, role: str) -> str:
"""

View File

@@ -19,6 +19,8 @@ from typing import (
Tuple,
Type,
Union,
get_args,
get_origin,
)
from pydantic import (
@@ -178,15 +180,29 @@ class Task(BaseModel):
"""
if v is not None:
sig = inspect.signature(v)
if len(sig.parameters) != 1:
positional_args = [
param
for param in sig.parameters.values()
if param.default is inspect.Parameter.empty
]
if len(positional_args) != 1:
raise ValueError("Guardrail function must accept exactly one parameter")
# Check return annotation if present, but don't require it
return_annotation = sig.return_annotation
if return_annotation != inspect.Signature.empty:
return_annotation_args = get_args(return_annotation)
if not (
return_annotation == Tuple[bool, Any]
or str(return_annotation) == "Tuple[bool, Any]"
get_origin(return_annotation) is tuple
and len(return_annotation_args) == 2
and return_annotation_args[0] is bool
and (
return_annotation_args[1] is Any
or return_annotation_args[1] is str
or return_annotation_args[1] is TaskOutput
or return_annotation_args[1] == Union[str, TaskOutput]
)
):
raise ValueError(
"If return type is annotated, it must be Tuple[bool, Any]"

View File

@@ -281,8 +281,16 @@ class Telemetry:
return self._safe_telemetry_operation(operation)
def task_ended(self, span: Span, task: Task, crew: Crew):
"""Records task execution in a crew."""
"""Records the completion of a task execution in a crew.
Args:
span (Span): The OpenTelemetry span tracking the task execution
task (Task): The task that was completed
crew (Crew): The crew context in which the task was executed
Note:
If share_crew is enabled, this will also record the task output
"""
def operation():
if crew.share_crew:
self._add_attribute(
@@ -297,8 +305,13 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def tool_repeated_usage(self, llm: Any, tool_name: str, attempts: int):
"""Records the repeated usage 'error' of a tool by an agent."""
"""Records when a tool is used repeatedly, which might indicate an issue.
Args:
llm (Any): The language model being used
tool_name (str): Name of the tool being repeatedly used
attempts (int): Number of attempts made with this tool
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Tool Repeated Usage")
@@ -317,8 +330,13 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def tool_usage(self, llm: Any, tool_name: str, attempts: int):
"""Records the usage of a tool by an agent."""
"""Records the usage of a tool by an agent.
Args:
llm (Any): The language model being used
tool_name (str): Name of the tool being used
attempts (int): Number of attempts made with this tool
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Tool Usage")
@@ -337,8 +355,11 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def tool_usage_error(self, llm: Any):
"""Records the usage of a tool by an agent."""
"""Records when a tool usage results in an error.
Args:
llm (Any): The language model being used when the error occurred
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Tool Usage Error")
@@ -357,6 +378,14 @@ class Telemetry:
def individual_test_result_span(
self, crew: Crew, quality: float, exec_time: int, model_name: str
):
"""Records individual test results for a crew execution.
Args:
crew (Crew): The crew being tested
quality (float): Quality score of the execution
exec_time (int): Execution time in seconds
model_name (str): Name of the model used
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Crew Individual Test Result")
@@ -383,6 +412,14 @@ class Telemetry:
inputs: dict[str, Any] | None,
model_name: str,
):
"""Records the execution of a test suite for a crew.
Args:
crew (Crew): The crew being tested
iterations (int): Number of test iterations
inputs (dict[str, Any] | None): Input parameters for the test
model_name (str): Name of the model used in testing
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Crew Test Execution")
@@ -408,6 +445,7 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def deploy_signup_error_span(self):
"""Records when an error occurs during the deployment signup process."""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Deploy Signup Error")
@@ -417,6 +455,11 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def start_deployment_span(self, uuid: Optional[str] = None):
"""Records the start of a deployment process.
Args:
uuid (Optional[str]): Unique identifier for the deployment
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Start Deployment")
@@ -428,6 +471,7 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def create_crew_deployment_span(self):
"""Records the creation of a new crew deployment."""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Create Crew Deployment")
@@ -437,6 +481,12 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def get_crew_logs_span(self, uuid: Optional[str], log_type: str = "deployment"):
"""Records the retrieval of crew logs.
Args:
uuid (Optional[str]): Unique identifier for the crew
log_type (str, optional): Type of logs being retrieved. Defaults to "deployment".
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Get Crew Logs")
@@ -449,6 +499,11 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def remove_crew_span(self, uuid: Optional[str] = None):
"""Records the removal of a crew.
Args:
uuid (Optional[str]): Unique identifier for the crew being removed
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Remove Crew")
@@ -574,6 +629,11 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def flow_creation_span(self, flow_name: str):
"""Records the creation of a new flow.
Args:
flow_name (str): Name of the flow being created
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Flow Creation")
@@ -584,6 +644,12 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def flow_plotting_span(self, flow_name: str, node_names: list[str]):
"""Records flow visualization/plotting activity.
Args:
flow_name (str): Name of the flow being plotted
node_names (list[str]): List of node names in the flow
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Flow Plotting")
@@ -595,6 +661,12 @@ class Telemetry:
self._safe_telemetry_operation(operation)
def flow_execution_span(self, flow_name: str, node_names: list[str]):
"""Records the execution of a flow.
Args:
flow_name (str): Name of the flow being executed
node_names (list[str]): List of nodes being executed in the flow
"""
def operation():
tracer = trace.get_tracer("crewai.telemetry")
span = tracer.start_span("Flow Execution")

View File

@@ -455,7 +455,7 @@ class ToolUsage:
# Attempt 4: Repair JSON
try:
repaired_input = repair_json(tool_input)
repaired_input = repair_json(tool_input, skip_json_loads=True)
self._printer.print(
content=f"Repaired JSON: {repaired_input}", color="blue"
)

View File

@@ -67,15 +67,12 @@ class CrewAIEventsBus:
source: The object emitting the event
event: The event instance to emit
"""
event_type = type(event)
if event_type in self._handlers:
for handler in self._handlers[event_type]:
handler(source, event)
self._signal.send(source, event=event)
for event_type, handlers in self._handlers.items():
if isinstance(event, event_type):
for handler in handlers:
handler(source, event)
def clear_handlers(self) -> None:
"""Clear all registered event handlers - useful for testing"""
self._handlers.clear()
self._signal.send(source, event=event)
def register_handler(
self, event_type: Type[EventTypes], handler: Callable[[Any, EventTypes], None]

View File

@@ -96,6 +96,10 @@ class CrewPlanner:
tasks_summary = []
for idx, task in enumerate(self.tasks):
knowledge_list = self._get_agent_knowledge(task)
agent_tools = (
f"[{', '.join(str(tool) for tool in task.agent.tools)}]" if task.agent and task.agent.tools else '"agent has no tools"',
f',\n "agent_knowledge": "[\\"{knowledge_list[0]}\\"]"' if knowledge_list and str(knowledge_list) != "None" else ""
)
task_summary = f"""
Task Number {idx + 1} - {task.description}
"task_description": {task.description}
@@ -103,10 +107,7 @@ class CrewPlanner:
"agent": {task.agent.role if task.agent else "None"}
"agent_goal": {task.agent.goal if task.agent else "None"}
"task_tools": {task.tools}
"agent_tools": %s%s""" % (
f"[{', '.join(str(tool) for tool in task.agent.tools)}]" if task.agent and task.agent.tools else '"agent has no tools"',
f',\n "agent_knowledge": "[\\"{knowledge_list[0]}\\"]"' if knowledge_list and str(knowledge_list) != "None" else ""
)
"agent_tools": {"".join(agent_tools)}"""
tasks_summary.append(task_summary)
return " ".join(tasks_summary)

View File

View File

@@ -0,0 +1,67 @@
import os
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from crewai.deployment.config import Config
from crewai.deployment.main import Deployment
class TestDeployment(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.config_path = os.path.join(self.temp_dir.name, "config.yaml")
# Create a test configuration file
with open(self.config_path, "w") as f:
f.write("""
name: test-deployment
port: 8000
host: 127.0.0.1
crews:
- name: test_crew
module_path: ./test_crew.py
class_name: TestCrew
""")
# Create a test crew file
with open(os.path.join(self.temp_dir.name, "test_crew.py"), "w") as f:
f.write("""
from crewai import Agent, Crew, Task
class TestCrew:
def crew(self):
return Crew(agents=[], tasks=[])
""")
def tearDown(self):
self.temp_dir.cleanup()
def test_config_loading(self):
config = Config(self.config_path)
self.assertEqual(config.name, "test-deployment")
self.assertEqual(config.port, 8000)
self.assertEqual(config.host, "127.0.0.1")
self.assertEqual(len(config.crews), 1)
self.assertEqual(config.crews[0].name, "test_crew")
@mock.patch("crewai.deployment.docker.container.DockerContainer.generate_dockerfile")
@mock.patch("crewai.deployment.docker.container.DockerContainer.generate_compose_file")
def test_deployment_prepare(self, mock_generate_compose, mock_generate_dockerfile):
deployment = Deployment(self.config_path)
deployment.deployment_dir = Path(self.temp_dir.name) / "deployment"
deployment.prepare()
# Check that the deployment directory was created
self.assertTrue(os.path.exists(deployment.deployment_dir))
# Check that the deployment config was created
config_file = deployment.deployment_dir / "deployment_config.json"
self.assertTrue(os.path.exists(config_file))
# Check that Docker files were generated
mock_generate_dockerfile.assert_called_once()
mock_generate_compose.assert_called_once_with(port=8000)

View File

@@ -3,6 +3,8 @@
import hashlib
import json
import os
from functools import partial
from typing import Tuple, Union
from unittest.mock import MagicMock, patch
import pytest
@@ -215,6 +217,75 @@ def test_multiple_output_type_error():
)
def test_guardrail_type_error():
desc = "Give me a list of 5 interesting ideas to explore for na article, what makes them unique and interesting."
expected_output = "Bullet point list of 5 interesting ideas."
# Lambda function
Task(
description=desc,
expected_output=expected_output,
guardrail=lambda x: (True, x),
)
# Function
def guardrail_fn(x: TaskOutput) -> tuple[bool, TaskOutput]:
return (True, x)
Task(
description=desc,
expected_output=expected_output,
guardrail=guardrail_fn,
)
class Object:
def guardrail_fn(self, x: TaskOutput) -> tuple[bool, TaskOutput]:
return (True, x)
@classmethod
def guardrail_class_fn(cls, x: TaskOutput) -> tuple[bool, str]:
return (True, x)
@staticmethod
def guardrail_static_fn(x: TaskOutput) -> tuple[bool, Union[str, TaskOutput]]:
return (True, x)
obj = Object()
# Method
Task(
description=desc,
expected_output=expected_output,
guardrail=obj.guardrail_fn,
)
# Class method
Task(
description=desc,
expected_output=expected_output,
guardrail=Object.guardrail_class_fn,
)
# Static method
Task(
description=desc,
expected_output=expected_output,
guardrail=Object.guardrail_static_fn,
)
def error_fn(x: TaskOutput, y: bool) -> Tuple[bool, TaskOutput]:
return (y, x)
Task(
description=desc,
expected_output=expected_output,
guardrail=partial(error_fn, y=True),
)
with pytest.raises(ValidationError):
Task(
description=desc,
expected_output=expected_output,
guardrail=error_fn,
)
@pytest.mark.vcr(filter_headers=["authorization"])
def test_output_pydantic_sequential():
class ScoreOutput(BaseModel):

View File

@@ -0,0 +1,34 @@
from unittest.mock import Mock
from crewai.utilities.events.base_events import CrewEvent
from crewai.utilities.events.crewai_event_bus import crewai_event_bus
class TestEvent(CrewEvent):
pass
def test_specific_event_handler():
mock_handler = Mock()
@crewai_event_bus.on(TestEvent)
def handler(source, event):
mock_handler(source, event)
event = TestEvent(type="test_event")
crewai_event_bus.emit("source_object", event)
mock_handler.assert_called_once_with("source_object", event)
def test_wildcard_event_handler():
mock_handler = Mock()
@crewai_event_bus.on(CrewEvent)
def handler(source, event):
mock_handler(source, event)
event = TestEvent(type="test_event")
crewai_event_bus.emit("source_object", event)
mock_handler.assert_called_once_with("source_object", event)