* test: Add test demonstrating knowledge not included in planning process
Issue #1703: Add test to verify that agent knowledge sources are not currently
included in the planning process. This test will help validate the fix once
implemented.
- Creates agent with knowledge sources
- Verifies knowledge context missing from planning
- Checks other expected components are present
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Include agent knowledge in planning process
Issue #1703: Integrate agent knowledge sources into planning summaries
- Add agent_knowledge field to task summaries in planning_handler
- Update test to verify knowledge inclusion
- Ensure knowledge context is available during planning phase
The planning agent now has access to agent knowledge when creating
task execution plans, allowing for better informed planning decisions.
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: Fix import sorting in test_knowledge_planning.py
- Reorganize imports according to ruff linting rules
- Fix I001 linting error
Co-Authored-By: Joe Moura <joao@crewai.com>
* test: Update task summary assertions to include knowledge field
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update ChromaDB mock path and fix knowledge string formatting
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Improve knowledge integration in planning process with error handling
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update task summary format for empty tools and knowledge
- Change empty tools message to 'agent has no tools'
- Remove agent_knowledge field when empty
- Update test assertions to match new format
- Improve test messages for clarity
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update string formatting for agent tools in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update string formatting for agent tools in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update string formatting for agent tools and knowledge in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update knowledge field formatting in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: Fix import sorting in test_planning_handler.py
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: Fix import sorting order in test_planning_handler.py
Co-Authored-By: Joe Moura <joao@crewai.com>
* test: Add ChromaDB mocking to test_create_tasks_summary_with_knowledge_and_tools
Co-Authored-By: Joe Moura <joao@crewai.com>
---------
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: João Moura <joaomdmoura@gmail.com>
* test: Add test demonstrating knowledge not included in planning process
Issue #1703: Add test to verify that agent knowledge sources are not currently
included in the planning process. This test will help validate the fix once
implemented.
- Creates agent with knowledge sources
- Verifies knowledge context missing from planning
- Checks other expected components are present
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Include agent knowledge in planning process
Issue #1703: Integrate agent knowledge sources into planning summaries
- Add agent_knowledge field to task summaries in planning_handler
- Update test to verify knowledge inclusion
- Ensure knowledge context is available during planning phase
The planning agent now has access to agent knowledge when creating
task execution plans, allowing for better informed planning decisions.
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: Fix import sorting in test_knowledge_planning.py
- Reorganize imports according to ruff linting rules
- Fix I001 linting error
Co-Authored-By: Joe Moura <joao@crewai.com>
* test: Update task summary assertions to include knowledge field
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update ChromaDB mock path and fix knowledge string formatting
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Improve knowledge integration in planning process with error handling
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update task summary format for empty tools and knowledge
- Change empty tools message to 'agent has no tools'
- Remove agent_knowledge field when empty
- Update test assertions to match new format
- Improve test messages for clarity
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update string formatting for agent tools in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update string formatting for agent tools in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update string formatting for agent tools and knowledge in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: Update knowledge field formatting in task summary
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: Fix import sorting in test_planning_handler.py
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: Fix import sorting order in test_planning_handler.py
Co-Authored-By: Joe Moura <joao@crewai.com>
* test: Add ChromaDB mocking to test_create_tasks_summary_with_knowledge_and_tools
Co-Authored-By: Joe Moura <joao@crewai.com>
---------
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: João Moura <joaomdmoura@gmail.com>
* docs: add comprehensive docstrings to Flow class and methods
- Added NumPy-style docstrings to all decorator functions
- Added detailed documentation to Flow class methods
- Included parameter types, return types, and examples
- Enhanced documentation clarity and completeness
Co-Authored-By: Joe Moura <joao@crewai.com>
* feat: add secure path handling utilities
- Add path_utils.py with safe path handling functions
- Implement path validation and security checks
- Integrate secure path handling in flow_visualizer.py
- Add path validation in html_template_handler.py
- Add comprehensive error handling for path operations
Co-Authored-By: Joe Moura <joao@crewai.com>
* docs: add comprehensive docstrings and type hints to flow utils (#1819)
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: add type annotations and fix import sorting
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: add type annotations to flow utils and visualization utils
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: resolve import sorting and type annotation issues
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: properly initialize and update edge_smooth variable
Co-Authored-By: Joe Moura <joao@crewai.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Joe Moura <joao@crewai.com>
* docs: add comprehensive docstrings to Flow class and methods
- Added NumPy-style docstrings to all decorator functions
- Added detailed documentation to Flow class methods
- Included parameter types, return types, and examples
- Enhanced documentation clarity and completeness
Co-Authored-By: Joe Moura <joao@crewai.com>
* feat: add secure path handling utilities
- Add path_utils.py with safe path handling functions
- Implement path validation and security checks
- Integrate secure path handling in flow_visualizer.py
- Add path validation in html_template_handler.py
- Add comprehensive error handling for path operations
Co-Authored-By: Joe Moura <joao@crewai.com>
* docs: add comprehensive docstrings and type hints to flow utils (#1819)
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: add type annotations and fix import sorting
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: add type annotations to flow utils and visualization utils
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: resolve import sorting and type annotation issues
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: properly initialize and update edge_smooth variable
Co-Authored-By: Joe Moura <joao@crewai.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Joe Moura <joao@crewai.com>
* feat: add tiktoken as explicit dependency and document Rust requirement
- Add tiktoken>=0.8.0 as explicit dependency to ensure pre-built wheels are used
- Document Rust compiler requirement as fallback in README.md
- Addresses issue #1824 tiktoken build failure
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: adjust tiktoken version to ~=0.7.0 for dependency compatibility
- Update tiktoken dependency to ~=0.7.0 to resolve conflict with embedchain
- Maintain compatibility with crewai-tools dependency chain
- Addresses CI build failures
Co-Authored-By: Joe Moura <joao@crewai.com>
* docs: add troubleshooting section and make tiktoken optional
Co-Authored-By: Joe Moura <joao@crewai.com>
* Update README.md
---------
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: João Moura <joaomdmoura@gmail.com>
* feat: add tiktoken as explicit dependency and document Rust requirement
- Add tiktoken>=0.8.0 as explicit dependency to ensure pre-built wheels are used
- Document Rust compiler requirement as fallback in README.md
- Addresses issue #1824 tiktoken build failure
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix: adjust tiktoken version to ~=0.7.0 for dependency compatibility
- Update tiktoken dependency to ~=0.7.0 to resolve conflict with embedchain
- Maintain compatibility with crewai-tools dependency chain
- Addresses CI build failures
Co-Authored-By: Joe Moura <joao@crewai.com>
* docs: add troubleshooting section and make tiktoken optional
Co-Authored-By: Joe Moura <joao@crewai.com>
* Update README.md
---------
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: João Moura <joaomdmoura@gmail.com>
* fix(manager_llm): handle coworker role name case/whitespace properly
- Add .strip() to agent name and role comparisons in base_agent_tools.py
- Add test case for varied role name cases and whitespace
- Fix issue #1503 with manager LLM delegation
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix(manager_llm): improve error handling and add debug logging
- Add debug logging for better observability
- Add sanitize_agent_name helper method
- Enhance error messages with more context
- Add parameterized tests for edge cases:
- Embedded quotes
- Trailing newlines
- Multiple whitespace
- Case variations
- None values
- Improve error handling with specific exceptions
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: fix import sorting in base_agent_tools and test_manager_llm_delegation
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix(manager_llm): improve whitespace normalization in role name matching
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: fix import sorting in base_agent_tools and test_manager_llm_delegation
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix(manager_llm): add error message template for agent tool execution errors
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: fix import sorting in test_manager_llm_delegation.py
Co-Authored-By: Joe Moura <joao@crewai.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Joe Moura <joao@crewai.com>
* fix(manager_llm): handle coworker role name case/whitespace properly
- Add .strip() to agent name and role comparisons in base_agent_tools.py
- Add test case for varied role name cases and whitespace
- Fix issue #1503 with manager LLM delegation
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix(manager_llm): improve error handling and add debug logging
- Add debug logging for better observability
- Add sanitize_agent_name helper method
- Enhance error messages with more context
- Add parameterized tests for edge cases:
- Embedded quotes
- Trailing newlines
- Multiple whitespace
- Case variations
- None values
- Improve error handling with specific exceptions
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: fix import sorting in base_agent_tools and test_manager_llm_delegation
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix(manager_llm): improve whitespace normalization in role name matching
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: fix import sorting in base_agent_tools and test_manager_llm_delegation
Co-Authored-By: Joe Moura <joao@crewai.com>
* fix(manager_llm): add error message template for agent tool execution errors
Co-Authored-By: Joe Moura <joao@crewai.com>
* style: fix import sorting in test_manager_llm_delegation.py
Co-Authored-By: Joe Moura <joao@crewai.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Joe Moura <joao@crewai.com>
* fix: Change storage initialization to None for KnowledgeStorage
* refactor: Change storage field to optional and improve error handling when saving documents
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* fix: Change storage initialization to None for KnowledgeStorage
* refactor: Change storage field to optional and improve error handling when saving documents
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* Create Portkey-Observability-and-Guardrails.md
* crewAI update with new changes
* small change
---------
Co-authored-by: siddharthsambharia-portkey <siddhath.s@portkey.ai>
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* Create Portkey-Observability-and-Guardrails.md
* crewAI update with new changes
* small change
---------
Co-authored-by: siddharthsambharia-portkey <siddhath.s@portkey.ai>
Co-authored-by: João Moura <joaomdmoura@gmail.com>
As mentioned in issue #1759, listing crewai-tools as dev-dependencies makes pip install it a required dependency, and not an optional
Co-authored-by: João Moura <joaomdmoura@gmail.com>
As mentioned in issue #1759, listing crewai-tools as dev-dependencies makes pip install it a required dependency, and not an optional
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* added tool for docling support
* docling support installation
* use file_paths instead of file_path
* fix import
* organized imports
* run_type docs
* needs to be list
* fixed logic
* logged but file_path is backwards compatible
* use file_paths instead of file_path 2
* added test for multiple sources for file_paths
* fix run-types
* enabling local files to work and type cleanup
* linted
* fix test and types
* fixed run types
* fix types
* renamed to CrewDoclingSource
* linted
* added docs
* resolve conflicts
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
Co-authored-by: Brandon Hancock <brandon@brandonhancock.io>
* added tool for docling support
* docling support installation
* use file_paths instead of file_path
* fix import
* organized imports
* run_type docs
* needs to be list
* fixed logic
* logged but file_path is backwards compatible
* use file_paths instead of file_path 2
* added test for multiple sources for file_paths
* fix run-types
* enabling local files to work and type cleanup
* linted
* fix test and types
* fixed run types
* fix types
* renamed to CrewDoclingSource
* linted
* added docs
* resolve conflicts
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
Co-authored-by: Brandon Hancock <brandon@brandonhancock.io>
* Update llms.mdx (Gemini 2.0)
- Add Gemini 2.0 flash to Gemini table.
- Add link to 2 hosting paths for Gemini in Tip.
- Change to lower case model slugs vs names, user convenience.
- Add https://artificialanalysis.ai/ as alternate leaderboard.
- Move Gemma to "other" tab.
* Update llm.py (gemini 2.0)
Add setting for Gemini 2.0 context window to llm.py
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* Update llms.mdx (Gemini 2.0)
- Add Gemini 2.0 flash to Gemini table.
- Add link to 2 hosting paths for Gemini in Tip.
- Change to lower case model slugs vs names, user convenience.
- Add https://artificialanalysis.ai/ as alternate leaderboard.
- Move Gemma to "other" tab.
* Update llm.py (gemini 2.0)
Add setting for Gemini 2.0 context window to llm.py
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* apply agent ops changes and resolve merge conflicts
* Trying to fix tests
* add back in vcr
* update tools
* remove pkg_resources which was causing issues
* Fix tests
* experimenting to see if unique content is an issue with knowledge
* experimenting to see if unique content is an issue with knowledge
* update chromadb which seems to have issues with upsert
* generate new yaml for failing test
* Investigating upsert
* Drop patch
* Update casettes
* Fix duplicate document issue
* more fixes
* add back in vcr
* new cassette for test
---------
Co-authored-by: Lorenze Jay <lorenzejaytech@gmail.com>
* apply agent ops changes and resolve merge conflicts
* Trying to fix tests
* add back in vcr
* update tools
* remove pkg_resources which was causing issues
* Fix tests
* experimenting to see if unique content is an issue with knowledge
* experimenting to see if unique content is an issue with knowledge
* update chromadb which seems to have issues with upsert
* generate new yaml for failing test
* Investigating upsert
* Drop patch
* Update casettes
* Fix duplicate document issue
* more fixes
* add back in vcr
* new cassette for test
---------
Co-authored-by: Lorenze Jay <lorenzejaytech@gmail.com>
When using agentops, we have the option to pass the `skip_auto_end_session` parameter, which is supposed to not end the session if the `end_session` function is called by Crew.
Now the way it works is, the `agentops.end_session` accepts `is_auto_end` flag and crewai should have passed it as `True` (its `False` by default).
I have changed the code to pass is_auto_end=True
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
When using agentops, we have the option to pass the `skip_auto_end_session` parameter, which is supposed to not end the session if the `end_session` function is called by Crew.
Now the way it works is, the `agentops.end_session` accepts `is_auto_end` flag and crewai should have passed it as `True` (its `False` by default).
I have changed the code to pass is_auto_end=True
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* drop 3.13
* revert
* Drop test cassette that was causing error
* trying to fix failing test
* adding thiago changes
* resolve final tests
* Drop skip
* drop pipeline
* drop 3.13
* revert
* Drop test cassette that was causing error
* trying to fix failing test
* adding thiago changes
* resolve final tests
* Drop skip
* drop pipeline
* drop 3.13
* revert
* Drop test cassette that was causing error
* trying to fix failing test
* adding thiago changes
* resolve final tests
* Drop skip
* drop 3.13
* revert
* Drop test cassette that was causing error
* trying to fix failing test
* adding thiago changes
* resolve final tests
* Drop skip
* Fix disk I/O error when resetting short-term memory.
Reset chromadb client and nullifies references before
removing directory.
* Nit for clarity
* did the same for knowledge_storage
* cleanup
* cleanup order
* Cleanup after the rm of the directories
---------
Co-authored-by: Lorenze Jay <lorenzejaytech@gmail.com>
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
* Fix disk I/O error when resetting short-term memory.
Reset chromadb client and nullifies references before
removing directory.
* Nit for clarity
* did the same for knowledge_storage
* cleanup
* cleanup order
* Cleanup after the rm of the directories
---------
Co-authored-by: Lorenze Jay <lorenzejaytech@gmail.com>
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
* drop metadata requirement
* fix linting
* Update docs for new knowledge
* more linting
* more linting
* make save_documents private
* update docs to the new way we use knowledge and include clearing memory
* drop metadata requirement
* fix linting
* Update docs for new knowledge
* more linting
* more linting
* make save_documents private
* update docs to the new way we use knowledge and include clearing memory
* incorporate #1683
* add in --version flag to cli. closes#1679.
* Fix env issue
* Add in suggestions from @caike to make sure ragstorage doesnt exceed os file limit. Also, included additional checks to support windows.
* remove poetry.lock as pointed out by @sanders41 in #1574.
* Incorporate feedback from crewai reviewer
* Incorporate @lorenzejay feedback
* incorporate #1683
* add in --version flag to cli. closes#1679.
* Fix env issue
* Add in suggestions from @caike to make sure ragstorage doesnt exceed os file limit. Also, included additional checks to support windows.
* remove poetry.lock as pointed out by @sanders41 in #1574.
* Incorporate feedback from crewai reviewer
* Incorporate @lorenzejay feedback
* v1 of HITL working
* Drop print statements
* HITL code more robust. Still needs to be refactored.
* refactor and more clear messages
* Fix type issue
* fix tests
* Fix test again
* Drop extra print
* v1 of HITL working
* Drop print statements
* HITL code more robust. Still needs to be refactored.
* refactor and more clear messages
* Fix type issue
* fix tests
* Fix test again
* Drop extra print
Corrected the statement which says users can not disable telemetry, but now users can disable by setting the environment variable OTEL_SDK_DISABLED to true.
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
Corrected the statement which says users can not disable telemetry, but now users can disable by setting the environment variable OTEL_SDK_DISABLED to true.
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* Knowledge project directory standard
* fixed types
* comment fix
* made base file knowledge source an abstract class
* cleaner validator on model_post_init
* fix type checker
* cleaner refactor
* better template
* Knowledge project directory standard
* fixed types
* comment fix
* made base file knowledge source an abstract class
* cleaner validator on model_post_init
* fix type checker
* cleaner refactor
* better template
* added path to RAGStorage
* added path to short term and entity memory
* add path for long_term_storage for completeness
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* added path to RAGStorage
* added path to short term and entity memory
* add path for long_term_storage for completeness
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* Update example of how to use LangChain tools with correct syntax
* Use .env
* Add Code back
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* Update example of how to use LangChain tools with correct syntax
* Use .env
* Add Code back
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* docs: improve tasks documentation clarity and structure
- Add Task Execution Flow section
- Add variable interpolation explanation
- Add Task Dependencies section with examples
- Improve overall document structure and readability
- Update code examples with proper syntax highlighting
* docs: update agent documentation with improved examples and formatting
- Replace DuckDuckGoSearchRun with SerperDevTool
- Update code block formatting to be consistent
- Improve template examples with actual syntax
- Update LLM examples to use current models
- Clean up formatting and remove redundant comments
* docs: enhance LLM documentation with Cerebras provider and formatting improvements
* docs: simplify LLMs documentation title
* docs: improve installation guide clarity and structure
- Add clear Python version requirements with check command
- Simplify installation options to recommended method
- Improve upgrade section clarity for existing users
- Add better visual structure with Notes and Tips
- Update description and formatting
* docs: improve introduction page organization and clarity
- Update organizational analogy in Note section
- Improve table formatting and alignment
- Remove emojis from component table for cleaner look
- Add 'helps you' to make the note more action-oriented
* docs: add enterprise and community cards
- Add Enterprise deployment card in quickstart
- Add community card focused on open source discussions
- Remove deployment reference from community description
- Clean up introduction page cards
- Remove link from Enterprise description text
* docs: add code snippet to Getting Started section in flows.mdx
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* docs: improve tasks documentation clarity and structure
- Add Task Execution Flow section
- Add variable interpolation explanation
- Add Task Dependencies section with examples
- Improve overall document structure and readability
- Update code examples with proper syntax highlighting
* docs: update agent documentation with improved examples and formatting
- Replace DuckDuckGoSearchRun with SerperDevTool
- Update code block formatting to be consistent
- Improve template examples with actual syntax
- Update LLM examples to use current models
- Clean up formatting and remove redundant comments
* docs: enhance LLM documentation with Cerebras provider and formatting improvements
* docs: simplify LLMs documentation title
* docs: improve installation guide clarity and structure
- Add clear Python version requirements with check command
- Simplify installation options to recommended method
- Improve upgrade section clarity for existing users
- Add better visual structure with Notes and Tips
- Update description and formatting
* docs: improve introduction page organization and clarity
- Update organizational analogy in Note section
- Improve table formatting and alignment
- Remove emojis from component table for cleaner look
- Add 'helps you' to make the note more action-oriented
* docs: add enterprise and community cards
- Add Enterprise deployment card in quickstart
- Add community card focused on open source discussions
- Remove deployment reference from community description
- Clean up introduction page cards
- Remove link from Enterprise description text
* docs: add code snippet to Getting Started section in flows.mdx
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
* docs: improve tasks documentation clarity and structure
- Add Task Execution Flow section
- Add variable interpolation explanation
- Add Task Dependencies section with examples
- Improve overall document structure and readability
- Update code examples with proper syntax highlighting
* docs: update agent documentation with improved examples and formatting
- Replace DuckDuckGoSearchRun with SerperDevTool
- Update code block formatting to be consistent
- Improve template examples with actual syntax
- Update LLM examples to use current models
- Clean up formatting and remove redundant comments
* docs: enhance LLM documentation with Cerebras provider and formatting improvements
* docs: simplify LLMs documentation title
* docs: improve installation guide clarity and structure
- Add clear Python version requirements with check command
- Simplify installation options to recommended method
- Improve upgrade section clarity for existing users
- Add better visual structure with Notes and Tips
- Update description and formatting
* docs: improve introduction page organization and clarity
- Update organizational analogy in Note section
- Improve table formatting and alignment
- Remove emojis from component table for cleaner look
- Add 'helps you' to make the note more action-oriented
* docs: add enterprise and community cards
- Add Enterprise deployment card in quickstart
- Add community card focused on open source discussions
- Remove deployment reference from community description
- Clean up introduction page cards
- Remove link from Enterprise description text
* docs: improve tasks documentation clarity and structure
- Add Task Execution Flow section
- Add variable interpolation explanation
- Add Task Dependencies section with examples
- Improve overall document structure and readability
- Update code examples with proper syntax highlighting
* docs: update agent documentation with improved examples and formatting
- Replace DuckDuckGoSearchRun with SerperDevTool
- Update code block formatting to be consistent
- Improve template examples with actual syntax
- Update LLM examples to use current models
- Clean up formatting and remove redundant comments
* docs: enhance LLM documentation with Cerebras provider and formatting improvements
* docs: simplify LLMs documentation title
* docs: improve installation guide clarity and structure
- Add clear Python version requirements with check command
- Simplify installation options to recommended method
- Improve upgrade section clarity for existing users
- Add better visual structure with Notes and Tips
- Update description and formatting
* docs: improve introduction page organization and clarity
- Update organizational analogy in Note section
- Improve table formatting and alignment
- Remove emojis from component table for cleaner look
- Add 'helps you' to make the note more action-oriented
* docs: add enterprise and community cards
- Add Enterprise deployment card in quickstart
- Add community card focused on open source discussions
- Remove deployment reference from community description
- Clean up introduction page cards
- Remove link from Enterprise description text
* added knowledge to agent level
* linted
* added doc
* added from suggestions
* added test
* fixes from discussion
* fix docs
* fix test
* rm cassette for knowledge_sources test as its a mock and update agent doc string
* fix test
* rm unused
* linted
* added knowledge to agent level
* linted
* added doc
* added from suggestions
* added test
* fixes from discussion
* fix docs
* fix test
* rm cassette for knowledge_sources test as its a mock and update agent doc string
* fix test
* rm unused
* linted
* V1 working
* clean up imports and prints
* more clean up and add tests
* fixing tests
* fix test
* fix linting
* Fix tests
* Fix linting
* add doc string as requested by eduardo
* V1 working
* clean up imports and prints
* more clean up and add tests
* fixing tests
* fix test
* fix linting
* Fix tests
* Fix linting
* add doc string as requested by eduardo
This commit adds an extra step to `crewai login` to ensure users also
log in to Tool Repository, that is, exchanging their Auth0 tokens for a
Tool Repository username and password to be used by UV downloads and API
tool uploads.
This commit adds an extra step to `crewai login` to ensure users also
log in to Tool Repository, that is, exchanging their Auth0 tokens for a
Tool Repository username and password to be used by UV downloads and API
tool uploads.
* initial knowledge
* WIP
* Adding core knowledge sources
* Improve types and better support for file paths
* added additional sources
* fix linting
* update yaml to include optional deps
* adding in lorenze feedback
* ensure embeddings are persisted
* improvements all around Knowledge class
* return this
* properly reset memory
* properly reset memory+knowledge
* consolodation and improvements
* linted
* cleanup rm unused embedder
* fix test
* fix duplicate
* generating cassettes for knowledge test
* updated default embedder
* None embedder to use default on pipeline cloning
* improvements
* fixed text_file_knowledge
* mypysrc fixes
* type check fixes
* added extra cassette
* just mocks
* linted
* mock knowledge query to not spin up db
* linted
* verbose run
* put a flag
* fix
* adding docs
* better docs
* improvements from review
* more docs
* linted
* rm print
* more fixes
* clearer docs
* added docstrings and type hints for cli
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
Co-authored-by: Lorenze Jay <lorenzejaytech@gmail.com>
This commit replaces .netrc with uv environment variables for installing
tools from private repositories. To store credentials, I created a new
and reusable settings file for the CLI in
`$HOME/.config/crewai/settings.json`.
The issue with .netrc files is that they are applied system-wide and are
scoped by hostname, meaning we can't differentiate tool repositories
requests from regular requests to CrewAI's API.
Allow passing additional options from `crewai install` directly to
`uv sync`. This enables commands like `crewai install --locked` to work
as expected by forwarding all flags and options to the underlying uv
command.
* updated CLI to allow for submitting API keys
* updated click prompt to remove default number
* removed all unnecessary comments
* feat: implement crew creation CLI command
- refactor code to multiple functions
- Added ability for users to select provider and model when uing crewai create command and ave API key to .env
* refactered select_choice function for early return
* refactored select_provider to have an ealry return
* cleanup of comments
* refactor/Move functions into utils file, added new provider file and migrated fucntions thre, new constants file + general function refactor
* small comment cleanup
* fix unnecessary deps
* Added docs for new CLI provider + fixed missing API prompt
* Minor doc updates
* allow user to bypass api key entry + incorect number selected logic + ruff formatting
* ruff updates
* Fix spelling mistake
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
Co-authored-by: Brandon Hancock <brandon@brandonhancock.io>
* ensure original embedding config works
* some fixes
* raise error on unsupported provider
* WIP: brandons notes
* fixes
* rm prints
* fixed docs
* fixed run types
* updates to add more docs and correct imports with huggingface embedding server enabled
---------
Co-authored-by: Brandon Hancock <brandon@brandonhancock.io>
* byom - short/entity memory
* better
* rm uneeded
* fix text
* use context
* rm dep and sync
* type check fix
* fixed test using new cassete
* fixing types
* fixed types
* fix types
* fixed types
* fixing types
* fix type
* cassette update
* just mock the return of short term mem
* remove print
* try catch block
* added docs
* dding error handling here
* updated CLI to allow for submitting API keys
* updated click prompt to remove default number
* removed all unnecessary comments
* feat: implement crew creation CLI command
- refactor code to multiple functions
- Added ability for users to select provider and model when uing crewai create command and ave API key to .env
* refactered select_choice function for early return
* refactored select_provider to have an ealry return
* cleanup of comments
* refactor/Move functions into utils file, added new provider file and migrated fucntions thre, new constants file + general function refactor
* small comment cleanup
* fix unnecessary deps
---------
Co-authored-by: Brandon Hancock (bhancock_ai) <109994880+bhancockio@users.noreply.github.com>
Co-authored-by: Brandon Hancock <brandon@brandonhancock.io>
* feat: Start migrating to UV
* feat: add uv to flows
* feat: update docs on Poetry -> uv
* feat: update docs and uv.locl
* feat: update tests and github CI
* feat: run ruff format
* feat: update typechecking
* feat: fix type checking
* feat: update python version
* feat: type checking gic
* feat: adapt uv command to run the tool repo
* Adapt tool build command to uv
* feat: update logic to let only projects with crew to be deployed
* feat: add uv to tools
* fix; tests
* fix: remove breakpoint
* fix :test
* feat: add crewai update to migrate from poetry to uv
* fix: tests
* feat: add validation for ˆ character on pyproject
* feat: add run_crew to pyproject if doesnt exist
* feat: add validation for poetry migration
* fix: warning
---------
Co-authored-by: Vinicius Brasil <vini@hey.com>
* Change all instaces of crewAI to CrewAI and fix installation step
* Update the example to use YAML format
* Update to come after setup and edits
* Remove double tool instance
This commit adds a new command for adding custom PyPI indexes
credentials to the project. This was changed because credentials are now
user-scoped instead of organization.
* Almost working!
* It fully works but not clean enought
* Working but not clean engouth
* Everything is workign
* WIP. Working on adding and & or to flows. In the middle of setting up template for flow as well
* template working
* Everything is working
* More changes and todos
* Add more support for @start
* Router working now
* minor tweak to
* minor tweak to conditions and event handling
* Update logs
* Too trigger happy with cleanup
* Added in Thiago fix
* Flow passing results again
* Working on docs.
* made more progress updates on docs
* Finished talking about controlling flows
* add flow output
* fixed flow output section
* add crews to flows section is looking good now
* more flow doc changes
* Update docs and add more examples
* drop visualizer
* save visualizer
* pyvis is beginning to work
* pyvis working
* it is working
* regular methods and triggers working. Need to work on router next.
* properly identifying router and router children nodes. Need to fix color
* children router working. Need to support loops
* curving cycles but need to add curve conditionals
* everythin is showing up properly need to fix curves
* all working. needs to be cleaned up
* adjust padding
* drop lib
* clean up prior to PR
* incorporate joao feedback
* final tweaks for joao
* Refactor to make crews easier to understand
* update CLI and templates
* Fix crewai version in flows
* Fix merge conflict
* Almost working!
* It fully works but not clean enought
* Working but not clean engouth
* Everything is workign
* WIP. Working on adding and & or to flows. In the middle of setting up template for flow as well
* template working
* Everything is working
* More changes and todos
* Add more support for @start
* Router working now
* minor tweak to
* minor tweak to conditions and event handling
* Update logs
* Too trigger happy with cleanup
* Added in Thiago fix
* Flow passing results again
* Working on docs.
* made more progress updates on docs
* Finished talking about controlling flows
* add flow output
* fixed flow output section
* add crews to flows section is looking good now
* more flow doc changes
* Update docs and add more examples
* drop visualizer
* save visualizer
* pyvis is beginning to work
* pyvis working
* it is working
* regular methods and triggers working. Need to work on router next.
* properly identifying router and router children nodes. Need to fix color
* children router working. Need to support loops
* curving cycles but need to add curve conditionals
* everythin is showing up properly need to fix curves
* all working. needs to be cleaned up
* adjust padding
* drop lib
* clean up prior to PR
* incorporate joao feedback
* final tweaks for joao
This commit adds two commands to the CLI:
- `crewai tool publish`
- Builds the project using Poetry
- Uploads the tarball to CrewAI's tool repository
- `crewai tool install my-tool`
- Adds my-tool's index to Poetry and its credentials
- Installs my-tool from the custom index
* Prevent double slashes when joining URLs
* Move crewai.cli.deploy.utils to crewai.cli.utils
This commit moves this package so it's reusable across commands.
* Update Tasks.md
Current formating of the page Tasks has been broken, fix the markdown formatting.
* Update LLM-Connections.md
LLM class has been moved to llm.py file
* rebuilding executor
* removing langchain
* Making all tests good
* fixing types and adding ability for nor using system prompts
* improving types
* pleasing the types gods
* pleasing the types gods
* fixing parser, tools and executor
* making sure all tests pass
* final pass
* fixing type
* Updating Docs
* preparing to cut new version
* Updated CrewAI Documentation and Repository link in tools.poetry.urls
* Update pyproject.toml
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* feat: set basic structure deploy commands
* feat: add first iteration of CLI Deploy
* feat: some minor refactor
* feat: Add api, Deploy command and update cli
* feat: Remove test token
* feat: add auth0 lib, update cli and improve code
* feat: update code and decouple auth
* fix: parts of the code
* feat: Add token manager to encrypt access token and get and save tokens
* feat: add audience to costants
* feat: add subsystem saving credentials and remove comment of type hinting
* feat: add get crew version to send on header of request
* feat: add docstrings
* feat: add tests for authentication module
* feat: add tests for utils
* feat: add unit tests for cl
* feat: add tests
* feat: add deploy man tests
* feat: fix type checking issue
* feat: rename tests to pass ci
* feat: fix pr issues
* feat: fix get crewai versoin
* fix: add timeout for tests.yml
* Fixed agents. Now need to fix tasks.
* Add type fixes and fix task decorator
* Clean up logs
* fix more type errors
* Revert back to required
* Undo changes.
* Remove default none for properties that cannot be none
* Clean up comments
* Implement all of Guis feedback
* Clean up pipeline
* Make versioning dynamic in templates
* fix .env issues when openai is trying to use invalid keys
* Fix type checker issue in pipeline
* Fix tests.
* Add name and expected_output to TaskOutput
This commit adds task information to the TaskOutput class. This is
useful to provide extra context to callbacks.
* Populate task name from function names
This commit populates task name from function names when using
annotations.
As per (https://github.com/langchain-ai/langchain/pull/16395), OpenAI functions don't accept tool names with space. Therefore, I added an exception handling snippet to raise an issue if a custom tool name has a space.
* WIP. Procedure appears to be working well. Working on mocking properly for tests
* All tests are passing now
* rshift working
* Add back in Gui's tool_usage fix
* WIP
* Going to start refactoring for pipeline_output
* Update terminology
* new pipeline flow with traces and usage metrics working. need to add more tests and make sure PipelineOutput behaves likew CrewOutput
* Fix pipelineoutput to look more like crewoutput and taskoutput
* Implemented additional tests for pipeline. One test is failing. Need team support
* Update docs for pipeline
* Update pipeline to properly process input and ouput dictionary
* Update Pipeline docs
* Add back in commentary at top of pipeline file
* Starting to work on router
* Drop router for now. will add in separately
* In the middle of fixing router. A ton of circular dependencies. Moving over to a new design.
* WIP.
* Fix circular dependencies and updated PipelineRouter
* Add in Eduardo feedback. Still need to add in more commentary describing the design decisions for pipeline
* Add developer notes to explain what is going on in pipelines.
* Add doc strings
* Fix missing rag datatype
* WIP. Converting usage metrics from a dict to an object
* Fix tests that were checking usage metrics
* Drop todo
* Fix 1 type error in pipeline
* Update pipeline to use UsageMetric
* Add missing doc string
* WIP.
* Change names
* Rename variables based on joaos feedback
* Fix critical circular dependency issues. Now needing to fix trace issue.
* Tests working now!
* Add more tests which showed underlying issue with traces
* Fix tests
* Remove overly complicated test
* Add router example to docs
* Clean up end of docs
* Clean up docs
* Working on creating Crew templates and pipeline templates
* WIP.
* WIP
* Fix poetry install from templates
* WIP
* Restructure
* changes for lorenze
* more todos
* WIP: create pipelines cli working
* wrapped up router
* ignore mypy src on templates
* ignored signature of copy
* fix all verbose
* rm print statements
* brought back correct folders
* fixes missing folders and then rm print statements
* fixed tests
* fixed broken test
* fixed type checker
* fixed type ignore
* ignore types for templates
* needed
* revert
* exclude only required
* rm type errors on templates
* rm excluding type checks for template files on github action
* fixed missing quotes
---------
Co-authored-by: Brandon Hancock <brandon@brandonhancock.io>
* patching for non-gpt model
* removal of json_object tool name assignment
* fixed issue for smaller models due to instructions prompt
* fixing for ollama llama3 models
* WIP: generated summary from documents split, could also create memgpt approach
* WIP: need tests but user inputted summarization strategy implemented - handling context window exceeding errors
* rm extra line
* removed type ignores
* added tests
* handling n to summarize prompt
* code cleanup, using click for cli asker
* rm not used class
* better refactor
* reverted poetry lock
* reverted poetry.locl
* improved context window exceeding exception class
* feat: Add execution time to both task and testing feature
* feat: Remove unused functions
* feat: change test_crew to evalaute_crew to avoid issues with testing libs
* feat: fix tests
I think there is some mistake, because there is no such parameter as force_output_result, and as the code shows, the correct parameter result_as_answer is set during agent creation, not task.
* Performed spell check across the entire documentation
Thank you once again!
* Performed spell check across the most of code base
Folders been checked:
- agents
- cli
- memory
- project
- tasks
- telemetry
- tools
- translations
* Trying to add a max_token for the agents, so they limited by number of tokens.
* Performed spell check across the rest of code base, and enahnced the yaml paraser code a little
* Small change in the main agent doc
* Improve _save_file method to handle both dict and str inputs
- Add check for dict type input
- Use json.dump for dict serialization
- Convert non-dict inputs to string
- Remove type ignore comments
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* Fixed special character issue when converting json to models. Added numerous tests to ensure thigns work properly.
* Fix linting error and cleaned up tests
* Fix customer_converter_cls test failure
* Fixed tests. Thank you lorenze for pointing that out. added a few more to ensure converter creation works properly
* Address lorenze feedback
* Fix linting issues
* patching for non-gpt model
* removal of json_object tool name assignment
* fixed issue for smaller models due to instructions prompt
* fixing for ollama llama3 models
* closing brackets
* removed not used and fixes
* WIP: hierarchical unblock for async tasks
* added better test
* update name change
* added more test and crew manager cleanup
* remove prints
* code cleanup, no need to pass manager
* feat: add ability to set LLM for AgentPLanner on Crew
* feat: fixes issue on instantiating the ChatOpenAI on the crew
* docs: add docs for the planning_llm new parameter
* docs: change message to ChatOpenAI llm
* feat: add tests
* feat: add crew Testing/evalauting feature
* feat: add docs and add unit test
* feat: improve testing output table
* feat: add tests
* feat: fix type checking issue
* feat: add raise ValueError when testing if output is not the expected
* docs: add docs for Testing
* feat: improve tests and fix some issue
* feat: back to sync
* feat: change opdeai model
* feat: fix test
* WIP: yaml proper mapping for agents and agent
* WIP: added output_json and output_pydantic setup
* WIP: core logic added, need cleanup
* code cleanup
* updated docs and example template to use yaml to reference agents within tasks
* cleanup type errors
* Update Start-a-New-CrewAI-Project.md
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
To solve :
I encountered an error while trying to use the tool. This was the error: DuckDuckGoSearchRun._run() got an unexpected keyword argument 'q'.
Tool duckduckgo_search accepts these inputs: A wrapper around DuckDuckGo Search. Useful for when you need to answer questions about current events. Input should be a search query.
refer : https://github.com/joaomdmoura/crewAI/issues/316
The memory documentation left me with a lot of questions. After I went through the code to find an answer. I added this paragraph to explain what I found. Hope this is helpful.
* feat: add planning feature to crew
* feat: add test to planning handler and change to execute_async method
* docs: add planning parameter to the Core documentation
* docs: add planning docs
* fix: fix type checking issue
* fix: test and logic
* Cleaned up task execution to now have separate paths for async and sync execution. Updating all kickoff functions to return CrewOutput. WIP. Waiting for Joao feedback on async task execution with task_output
* Consistently storing async and sync output for context
* outline tests I need to create going forward
* Major rehaul of TaskOutput and CrewOutput. Updated all tests to work with new change. Need to add in a few final tricky async tests and add a few more to verify output types on TaskOutput and CrewOutput.
* Encountering issues with callback. Need to test on main. WIP
* working on tests. WIP
* WIP. Figuring out disconnect issue.
* Cleaned up logs now that I've isolated the issue to the LLM
* more wip.
* WIP. It looks like usage metrics has always been broken for async
* Update parent crew who is managing for_each loop
* Merge in main to bugfix/kickoff-for-each-usage-metrics
* Clean up code for review
* Add new tests
* Final cleanup. Ready for review.
* Moving copy functionality from Agent to BaseAgent
* Fix renaming issue
* Fix linting errors
* use BaseAgent instead of Agent where applicable
* Fixing missing function. Working on tests.
* WIP. Needing team to review change
* Fixing issues brought about by merge
* WIP: need to fix json encoder
* WIP need to fix encoder
* WIP
* WIP: replay working with async. need to add tests
* Implement major fixes from yesterdays group conversation. Now working on tests.
* The majority of tasks are working now. Need to fix converter class
* Fix final failing test
* Fix linting and type-checker issues
* Add more tests to fully test CrewOutput and TaskOutput changes
* Add in validation for async cannot depend on other async tasks.
* WIP: working replay feat fixing inputs, need tests
* WIP: core logic of seq and heir for executing tasks added into one
* Update validators and tests
* better logic for seq and hier
* replay working for both seq and hier just need tests
* fixed context
* added cli command + code cleanup TODO: need better refactoring
* refactoring for cleaner code
* added better tests
* removed todo comments and fixed some tests
* fix logging now all tests should pass
* cleaner code
* ensure replay is delcared when replaying specific tasks
* ensure hierarchical works
* better typing for stored_outputs and separated task_output_handler
* added better tests
* added replay feature to crew docs
* easier cli command name
* fixing changes
* using sqllite instead of .json file for logging previous task_outputs
* tools fix
* added to docs and fixed tests
* fixed .db
* fixed docs and removed unneeded comments
* separating ltm and replay db
* fixed printing colors
* added how to doc
---------
Co-authored-by: Brandon Hancock <brandon@brandonhancock.io>
* feat: add max retry limit to agent execution
* feat: add test to max retry limit feature
* feat: add code execution docstring
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* Exploring output being passed to tool selector to see if we can better format data
* WIP. Adding JSON repair functionality
* Almost done implementing JSON repair. Testing fixes vs current base case.
* More action cleanup with additional tests
* WIP. Trying to figure out what is going on with tool descriptions
* Update tool description generation
* WIP. Trying to find out what is causing the tools to duplicate
* Replacing tools properly instead of duplicating them accidentally
* Fixing issues for MR
* Update dependencies for JSON_REPAIR
* More cleaning up pull request
* preppering for call
* Fix type-checking issues
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* Cleaned up task execution to now have separate paths for async and sync execution. Updating all kickoff functions to return CrewOutput. WIP. Waiting for Joao feedback on async task execution with task_output
* Consistently storing async and sync output for context
* outline tests I need to create going forward
* Major rehaul of TaskOutput and CrewOutput. Updated all tests to work with new change. Need to add in a few final tricky async tests and add a few more to verify output types on TaskOutput and CrewOutput.
* Encountering issues with callback. Need to test on main. WIP
* working on tests. WIP
* WIP. Figuring out disconnect issue.
* Cleaned up logs now that I've isolated the issue to the LLM
* more wip.
* WIP. It looks like usage metrics has always been broken for async
* Update parent crew who is managing for_each loop
* Merge in main to bugfix/kickoff-for-each-usage-metrics
* Clean up code for review
* Add new tests
* Final cleanup. Ready for review.
* Moving copy functionality from Agent to BaseAgent
* Fix renaming issue
* Fix linting errors
* use BaseAgent instead of Agent where applicable
* Fixing missing function. Working on tests.
* WIP. Needing team to review change
* Fixing issues brought about by merge
* WIP
* Implement major fixes from yesterdays group conversation. Now working on tests.
* The majority of tasks are working now. Need to fix converter class
* Fix final failing test
* Fix linting and type-checker issues
* Add more tests to fully test CrewOutput and TaskOutput changes
* Add in validation for async cannot depend on other async tasks.
* Update validators and tests
* Performed spell check across the entire documentation
Thank you once again!
* Performed spell check across the most of code base
Folders been checked:
- agents
- cli
- memory
- project
- tasks
- telemetry
- tools
- translations
* fix: call asserts
* fix: test_increment_tool_errors
* fix: test_increment_delegations_for_sequential_process
* fix: test_increment_delegations_for_hierarchical_process
* fix: test_code_execution_flag_adds_code_tool_upon_kickoff
* fix: test_tool_usage_information_is_appended_to_agent
* fix: try to fix test_crew_full_output
* fix: try to fix test_crew_full_output
* fix: test remove vcr to test crew_test test
* fix: comment test to see if ci passes
* fix: comment test to see if ci passes
* fix: test changing prompt tokens to get error on CI
* fix: test changing prompt tokens to get error on CI
* fix: test changing prompt tokens to get error on CI
* fix: test changing prompt tokens to get error on CI
* fix: test new approach
* fix: comment funciont not working in CI
* fix: github python version
* fix: remove need of vcr
* fix: fix and add comments for all type checking errors
* Adding support to force a tool return to be the final answer.
This will at the end of the execution return the tool output.
It will return the output of the latest tool with the flag
* Update src/crewai/agent.py
Co-authored-by: Gui Vieira <guilherme_vieira@me.com>
* Update tests/agent_test.py
Co-authored-by: Gui Vieira <guilherme_vieira@me.com>
---------
Co-authored-by: Gui Vieira <guilherme_vieira@me.com>
* fixed bug for manager overriding task agent and then added pydanic valditors to sequential when no agent is added to task
* better test and fixed task.agent logic
* fixed tests and better validator message
* added validator for async_execution true in tasks whenever in hierarchical run
* WIP. Figuring out disconnect issue.
* Cleaned up logs now that I've isolated the issue to the LLM
* more wip.
* WIP. It looks like usage metrics has always been broken for async
* Update parent crew who is managing for_each loop
* Merge in main to bugfix/kickoff-for-each-usage-metrics
* Clean up code for review
* Add new tests
* Final cleanup. Ready for review.
* Moving copy functionality from Agent to BaseAgent
* Fix renaming issue
* Fix linting errors
* use BaseAgent instead of Agent where applicable
- Added detailed steps for training the crew programmatically.
- Clarified the distinction between using the CLI and programmatic approaches.
This update makes it easier for users to understand how to train their crew both through the CLI and programmatically, whether using a UI or API endpoints.
Again Thank you to the author for the great project and the excellent foundation provided!
* Fix issue agentop poetry install issue
* Updated install requirements tests to fail if .lock becomes out of sync with poetry install. Cleaned up old issues that were merged back in.
* implements agentops with a langchain handler, agent tracking and tool call recording
* track tool usage
* end session after completion
* track tool usage time
* better tool and llm tracking
* code cleanup
* make agentops optional
* optional dependency usage
* remove telemetry code
* optional agentops
* agentops version bump
* remove org key
* true dependency
* add crew org key to agentops
* cleanup
* Update pyproject.toml
* Revert "true dependency"
This reverts commit e52e8e9568.
* Revert "cleanup"
This reverts commit 7f5635fb9e.
* optional parent key
* agentops 0.1.5
* Revert "Revert "cleanup""
This reverts commit cea33d9a5d.
* Revert "Revert "true dependency""
This reverts commit 4d1b460b
* cleanup
* Forcing version 0.1.5
* Update pyproject.toml
* agentops update
* noop
* add crew tag
* black formatting
* use langchain callback handler to support all LLMs
* agentops version bump
* track task evaluator
* merge upstream
* Fix typo in instruction en.json (#676)
* Enable search in docs (#663)
* Clarify text in docstring (#662)
* Update agent.py (#655)
Changed default model value from gpt-4 to gpt-4o.
Reasoning.
gpt-4 costs 30$ per million tokens while gpt-4o costs 5$.
This is more cost friendly for default option.
* Update README.md (#652)
Rework example so that if you use a custom LLM it doesn't throw code errors by uncommenting.
* Update BrowserbaseLoadTool.md (#647)
* Update crew.py (#644)
Fixed Type on line 53
* fixes#665 (#666)
* Added timestamp to logger (#646)
* Added timestamp to logger
Updated the logger.py file to include timestamps when logging output. For example:
[2024-05-20 15:32:48][DEBUG]: == Working Agent: Researcher
[2024-05-20 15:32:48][INFO]: == Starting Task: Research the topic
[2024-05-20 15:33:22][DEBUG]: == [Researcher] Task output:
* Update tool_usage.py
* Revert "Update tool_usage.py"
This reverts commit 95d18d5b6f.
incorrect bramch for this commit
* support skip auto end session
* conditional protect agentops use
* fix crew logger bug
* fix crew logger bug
* Update crew.py
* Update tool_usage.py
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
Co-authored-by: Howard Gil <howardbgil@gmail.com>
Co-authored-by: Olivier Roberdet <niox5199@gmail.com>
Co-authored-by: Paul Sanders <psanders1@gmail.com>
Co-authored-by: Anudeep Kolluri <50168940+Anudeep-Kolluri@users.noreply.github.com>
Co-authored-by: Mike Heavers <heaversm@users.noreply.github.com>
Co-authored-by: Mish Ushakov <10400064+mishushakov@users.noreply.github.com>
Co-authored-by: theCyberTech - Rip&Tear <84775494+theCyberTech@users.noreply.github.com>
Co-authored-by: Saif Mahmud <60409889+vmsaif@users.noreply.github.com>
To Resolve :
pydantic_core._pydantic_core.ValidationError: 1 validation error for Task
expected_output
Field required [type=missing, input_value=, input_type=dict]
For further information visit https://errors.pydantic.dev/2.6/v/missing
"Expected Output" is mandatory now as it forces people to be specific about the expected result and get better result
refer : https://github.com/joaomdmoura/crewAI/issues/308
- Added a "Parameters" column to attribute tables. Improved overall document formatting for enhanced readability and ease of use.
Thank you to the author for the great project and the excellent foundation provided!
Revised to utilize Ollama from langchain.llms instead as the functionality from the other method simply doesn't work when delegating.
Co-authored-by: João Moura <joaomdmoura@gmail.com>
fixed error for some cases with Pandas DataFrame:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
* better spacing
* works with llama index
* works on langchain custom just need delegation to work
* cleanup for custom_agent class
* works with different argument expectations for agent_executor
* cleanup for hierarchial process, better agent_executor args handler and added to the crew agent doc page
* removed code examples for langchain + llama index, added to docs instead
* added key output if return is not a str for and added some tests
* added hinting for CustomAgent class
* removed pass as it was not needed
* closer just need to figuire ou agentTools
* running agents - llamaindex and langchain with base agent
* some cleanup on baseAgent
* minimum for agent to run for base class and ensure it works with hierarchical process
* cleanup for original agent to take on BaseAgent class
* Agent takes on langchainagent and cleanup across
* token handling working for usage_metrics to continue working
* installed llama-index, updated docs and added better name
* fixed some type errors
* base agent holds token_process
* heirarchail process uses proper tools and no longer relies on hasattr for token_processes
* removal of test_custom_agent_executions
* this fixes copying agents
* leveraging an executor class for trigger llamaindex agent
* llama index now has ask_human
* executor mixins added
* added output converter base class
* type listed
* cleanup for output conversions and tokenprocess eliminated redundancy
* properly handling tokens
* simplified token calc handling
* original agent with base agent builder structure setup
* better docs
* no more llama-index dep
* cleaner docs
* test fixes
* poetry reverts and better docs
* base_agent_tools set for third party agents
* updated task and test fix
* feat: add CodeInterpreterTool to run when enable code execution is allowed on agent
* feat: change to allow_code_execution
* feat: add readme for CodeInterpreterTool
* feat: add training logic to agent and crew
* feat: add training logic to agent executor
* feat: add input parameter to cli command
* feat: add utilities for the training logic
* feat: polish code, logic and add private variables
* feat: add docstring and type hinting to executor
* feat: add constant file, add constant to code
* feat: fix name of training handler function
* feat: remove unused var
* feat: change file handler file name
* feat: Add training handler file, class and change on the code
* feat: fix name error from file
* fix: change import to adapt to logic
* feat: add training handler test
* feat: add tests for file and training_handler
* feat: add test for task evaluator function
* feat: change text to fit in-screen
* feat: add test for train function
* feat: add test for agent training_handler function
* feat: add test for agent._use_trained_data
* removed hyphen in co-workers
* Fix issue with AgentTool agent selection. The LLM included double quotes in the agent name which messed up the string comparison. Added additional types. Cleaned up error messaging.
* Remove duplicate import
* Improve explanation
* Revert poetry.lock changes
* Fix missing line in poetry.lock
---------
Co-authored-by: madmag77 <goncharov.artemv@gmail.com>
* added extra parameter for kickoff to return token usage count after result
* added output_token_usage to class and in full_output
* logger duplicated
* added more types
* added usage_metrics to full output instead
* added more to the description on full_output
* possible mispacing
* updated kickoff return types to be either string or dict applicable when full_output is set
* removed duplicates
* updates instructor to the latest version. adds jsonref, which instructor seems to depend on.
* updates embedchain reference, necessary for python 3.12
* added extra parameter for kickoff to return token usage count after result
* added output_token_usage to class and in full_output
* logger duplicated
* added more types
* added usage_metrics to full output instead
* added more to the description on full_output
* possible mispacing
* fix: 'from datetime import datetime for logging' to print the timestamp
* fix: correct default model (gpt-4o), correct token counts, and correct TaskOutput attributes (added agent)
* test: verify Task callback data is an instance of TaskOutput
* Sync with deep copy working now
* async working!!
* Clean up code for review
* Fix naming
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* Added timestamp to logger
Updated the logger.py file to include timestamps when logging output. For example:
[2024-05-20 15:32:48][DEBUG]: == Working Agent: Researcher
[2024-05-20 15:32:48][INFO]: == Starting Task: Research the topic
[2024-05-20 15:33:22][DEBUG]: == [Researcher] Task output:
* Update tool_usage.py
* Revert "Update tool_usage.py"
This reverts commit 95d18d5b6f.
incorrect bramch for this commit
Changed default model value from gpt-4 to gpt-4o.
Reasoning.
gpt-4 costs 30$ per million tokens while gpt-4o costs 5$.
This is more cost friendly for default option.
* mentioning ollama on the docs as embedder
* lowering barrier to match tool with simialr name
* Fixing agent tools to support co_worker
* Adding new tests
* Fixing type"
* updating tests
* fixing conflict
* fix: fix test actually running
* fix: fix test to not send request to openai
* fix: fix linting to remove cli files
* fix: exclude only files that breaks black
* fix: Fix all Ruff checkings on the code and Fix Test with repeated name
* fix: Change linter name on yml file
* feat: update pre-commit
* feat: remove need for isort on the code
* feat: add mypy as type checker, update code and add comment to reference
* feat: remove black linter
* feat: remove poetry to run the command
* feat: change logic to test mypy
* feat: update tests yml to try to fix the tests gh action
* feat: try to add just mypy to run on gh action
* feat: fix yml file
* feat: add comment to avoid issue on gh action
* feat: decouple pytest from the necessity of poetry install
* feat: change tests.yml to test different approach
* feat: change to poetry run
* fix: parameter field on yml file
* fix: update parameters to be on the pyproject
* fix: update pyproject to remove import untyped errors
* fix: fix test actually running
* fix: fix test to not send request to openai
* fix: fix linting to remove cli files
* fix: exclude only files that breaks black
* fix: Fix all Ruff checkings on the code and Fix Test with repeated name
* fix: Change linter name on yml file
* feat: update pre-commit
* feat: remove need for isort on the code
* feat: remove black linter
* feat: update tests yml to try to fix the tests gh action
* Bug/curly_braces_yaml
Added parser to help users on yaml syntax
* context error
Patch and later will prioritize this again to have context work with the yaml
* fix: fix test actually running
* fix: fix test to not send request to openai
* fix: fix linting to remove cli files
* fix: exclude only files that breaks black
* Update task.py: try to find json in task output using regex
Sometimes the model replies with a valid and additional text, let's try to extract and validate it first. It's cheaper than calling LLM for that.
* Update task.py
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* adding variations of ask question and delegate work tools
* Revert "adding variations of ask question and delegate work tools"
This reverts commit 38d4589be8.
* adding distance calculation for tool names.
* proper formatting
* remove brackets
This commit adds a conditional check to ensure that the output file directory exists before attempting to create it. This ensures that the code does not
fail in cases where the directory does not exist and needs to be created. The condition is added in the `_save_file` method of the `Task` class, ensuring
that the correct behavior is maintained for saving results to a file.
Reworded "If you want to also install crewai-tools, which is a package with tools that can be used by the agents, but more dependencies, you can install it with, example below uses it:" for clarity
Created a short documentation on how to use Llama2 locally with crewAI thanks to the help of Ollama.
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* fix the issue where the suggestions were split at character level
* Update contextual_memory.py
---------
Co-authored-by: rajib76 <rajib76@yahoo.com>
Co-authored-by: João Moura <joaomdmoura@gmail.com>
I saw a rendedered whitespace inconsistency in the Tasks docs here:
c87d887efc/docs/core-concepts/Tasks.md (L173)
So I set out to patch that up to make it easier to read. I then noticed
there were a few whitespace inconsistencies:
- 2 spaces
- 4 whitespaces
- tabs
It appears that the 4 whitespaces is the prevalent whitesapce usage, so
I overwrote other whitespace usages with that in this commit.
Co-authored-by: Rueben Ramirez <rramirez@ruebens-mbp.tail7c016.ts.net>
Co-authored-by: João Moura <joaomdmoura@gmail.com>
* log_file
feature: added a new parameter for crew that creates a txt file to log agent execution
* unit tests and documentation
unit test if file is created but not what is inside the file
* tasks.py: don't call Converter when model response is valid
Try to convert the task output to the expected Pydantic model before sending it to Converter, maybe the model got it right.
* feature: human input per task
* Update executor.py
* Update executor.py
* Update executor.py
* Update executor.py
* Update executor.py
* feat: change human input for unit testing
added documentation and unit test
* Create test_agent_human_input.yaml
add yaml for test
---------
Co-authored-by: João Moura <joaomdmoura@gmail.com>
Added the langchain "Tool" functionality by creating a python function and then adding the functionality of that function to the tool by 'func' variable in the 'Tool' function.
This now will allow to add a max_inter option to agents while also making sure to force the agent to give it's best final answer before running out of it's max_inter.
* fixing identation for AgentTools
* updating gitignore to exclude quick test script
* startingprompt translation
* supporting individual task output
* adding agent to task output
* cutting new version
* Updating README example
* Refactoring task cache to be a tool
The previous implementation of the task caching system was early exiting
the agent executor due to the fact it was returning an AgentFinish object.
This now refactors it to use a cache specific tool that is dynamically
added and forced into the agent in case of a task execution that was
already executed with the same input.
New CrewAIBaseModel:
Base for Agent, Crew, Task.
Includes generated, frozen UUID.
Adds hashing capability
Migrate to ConfigDict:
Replaces class Config with model_config, see this deprecation note .
Benefits:
Adds auditing capability with frozen UUIDs.
* Adding tool caching a loop execution prevention.
This adds some guardrails, to both prevent the same tool to be used
consecutively and also caching tool's results across the entire crew
so it cuts down execution time and eventual LLM calls.
This plays a huge role for smaller opensource models that usually fall
into those behaviors patterns.
It also includes some smaller improvements around the tool prompt and
agent tools, all with the same intention of guiding models into
better conform with agent instructions.
Update to Pydantic v2:
Transitioned all references from pydantic.v1 to pydantic (v2), ensuring compatibility with the latest Pydantic features and improvements.
Affected components include agent tools, prompts, crew, and task modules.
Refactoring & Alignment with Pydantic Standards:
Refactored the agent module away from traditional __init__ to align more closely with Pydantic best practices.
Updated the crew module to Pydantic v2 and enhanced configurations, allowing JSON and dictionary inputs. Additionally, some (not all) exceptions have been migrated to leverage Pydantic's error-handling capabilities.
Enhancements to Validators and Typings:
Improved validators and type annotations across multiple modules, enhancing code readability and maintainability.
Streamlined the validation process in line with Pydantic v2's methodologies.
Import and Configuration Adjustments:
Updated to test-related absolute imports due to issues with Pytest finding packages through relative imports.
Increased minimum Python version from 3.81 to 3.9 - most projects align with this; added pre-commit hooks, isort, black, & autoflake for code quality; updated lock file.
🤖 **CrewAI**: Cutting-edge framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.
🤖 **CrewAI**: Production-grade framework for orchestrating sophisticated AI agent systems. From simple automations to complex real-world applications, CrewAI provides precise control and deep customization. By fostering collaborative intelligence through flexible, production-ready architecture, CrewAI empowers agents to work together seamlessly, tackling complex business challenges with predictable, consistent results.
<h3>
@@ -22,13 +22,17 @@
- [Why CrewAI?](#why-crewai)
- [Getting Started](#getting-started)
- [Key Features](#key-features)
- [Understanding Flows and Crews](#understanding-flows-and-crews)
The power of AI collaboration has too much to offer.
CrewAI is designed to enable AI agents to assume roles, share goals, and operate in a cohesive unit - much like a well-oiled crew. Whether you're building a smart assistant platform, an automated customer service ensemble, or a multi-agent research team, CrewAI provides the backbone for sophisticated multi-agent interactions.
CrewAI is a standalone framework, built from the ground up without dependencies on Langchain or other agent frameworks. It's designed to enable AI agents to assume roles, share goals, and operate in a cohesive unit - much like a well-oiled crew. Whether you're building a smart assistant platform, an automated customer service ensemble, or a multi-agent research team, CrewAI provides the backbone for sophisticated multi-agent interactions.
## Getting Started
### Learning Resources
Learn CrewAI through our comprehensive courses:
- [Multi AI Agent Systems with CrewAI](https://www.deeplearning.ai/short-courses/multi-ai-agent-systems-with-crewai/) - Master the fundamentals of multi-agent systems
- [Practical Multi AI Agents and Advanced Use Cases](https://www.deeplearning.ai/short-courses/practical-multi-ai-agents-and-advanced-use-cases-with-crewai/) - Deep dive into advanced implementations
### Understanding Flows and Crews
CrewAI offers two powerful, complementary approaches that work seamlessly together to build sophisticated AI applications:
1.**Crews**: Teams of AI agents with true autonomy and agency, working together to accomplish complex tasks through role-based collaboration. Crews enable:
- Natural, autonomous decision-making between agents
- Dynamic task delegation and collaboration
- Specialized roles with defined goals and expertise
- Flexible problem-solving approaches
2.**Flows**: Production-ready, event-driven workflows that deliver precise control over complex automations. Flows provide:
- Fine-grained control over execution paths for real-world scenarios
- Secure, consistent state management between tasks
- Clean integration of AI agents with production Python code
- Conditional branching for complex business logic
The true power of CrewAI emerges when combining Crews and Flows. This synergy allows you to:
- Build complex, production-grade applications
- Balance autonomy with precise control
- Handle sophisticated real-world scenarios
- Maintain clean, maintainable code structure
### Getting Started with Installation
To get started with CrewAI, follow these simple steps:
### 1. Installation
Ensure you have Python >=3.10 <=3.13 installed on your system. CrewAI uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
Ensure you have Python >=3.10 <3.13 installed on your system. CrewAI uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
First, install CrewAI:
```shell
pip install crewai
```
If you want to install the 'crewai' package along with its optional features that include additional tools for agents, you can do so by using the following command:
```shell
@@ -59,6 +92,22 @@ pip install 'crewai[tools]'
```
The command above installs the basic package and also adds extra components which require more dependencies to function.
### Troubleshooting Dependencies
If you encounter issues during installation or usage, here are some common solutions:
#### Common Issues
1.**ModuleNotFoundError: No module named 'tiktoken'**
- If using embedchain or other tools: `pip install 'crewai[tools]'`
2.**Failed building wheel for tiktoken**
- Ensure Rust compiler is installed (see installation steps above)
- For Windows: Verify Visual C++ Build Tools are installed
- Try upgrading pip: `pip install --upgrade pip`
- If issues persist, use a pre-built wheel: `pip install tiktoken --prefer-binary`
### 2. Setting Up Your Crew with the YAML Configuration
To create a new CrewAI project, run the following CLI (Command Line Interface) command:
@@ -121,7 +170,7 @@ researcher:
You're a seasoned researcher with a knack for uncovering the latest
developments in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
reporting_analyst:
role:>
{topic} Reporting Analyst
@@ -205,7 +254,7 @@ class LatestAiDevelopmentCrew():
tasks=self.tasks,# Automatically created by the @task decorator
process=Process.sequential,
verbose=True,
)
)
```
**main.py**
@@ -264,13 +313,16 @@ In addition to the sequential process, you can use the hierarchical process, whi
## Key Features
- **Role-Based Agent Design**: Customize agents with specific roles, goals, and tools.
- **Autonomous Inter-Agent Delegation**: Agents can autonomously delegate tasks and inquire amongst themselves, enhancing problem-solving efficiency.
- **Flexible Task Management**: Define tasks with customizable tools and assign them to agents dynamically.
- **Processes Driven**: Currently only supports `sequential` task execution and `hierarchical` processes, but more complex processes like consensual and autonomous are being worked on.
- **Save output as file**: Save the output of individual tasks as a file, so you can use it later.
- **Parse output as Pydantic or Json**: Parse the output of individual tasks as a Pydantic model or as a Json if you want to.
- **Works with Open Source Models**: Run your crew using Open AI or open source models refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-Connections/) page for details on configuring your agents' connections to models, even ones running locally!
**Note**: CrewAI is a standalone framework built from the ground up, without dependencies on Langchain or other agent frameworks.
- **Deep Customization**: Build sophisticated agents with full control over the system - from overriding inner prompts to accessing low-level APIs. Customize roles, goals, tools, and behaviors while maintaining clean abstractions.
- **Autonomous Inter-Agent Delegation**: Agents can autonomously delegate tasks and inquire amongst themselves, enabling complex problem-solving in real-world scenarios.
- **Flexible Task Management**: Define and customize tasks with granular control, from simple operations to complex multi-step processes.
- **Production-Grade Architecture**: Support for both high-level abstractions and low-level customization, with robust error handling and state management.
- **Predictable Results**: Ensure consistent, accurate outputs through programmatic guardrails, agent training capabilities, and flow-based execution control. See our [documentation on guardrails](https://docs.crewai.com/how-to/guardrails/) for implementation details.
- **Model Flexibility**: Run your crew using OpenAI or open source models with production-ready integrations. See [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-Connections/) for detailed configuration options.
- **Event-Driven Flows**: Build complex, real-world workflows with precise control over execution paths, state management, and conditional logic.
- **Process Orchestration**: Achieve any workflow pattern through flows - from simple sequential and hierarchical processes to complex, custom orchestration patterns with conditional branching and parallel execution.

@@ -305,6 +357,98 @@ You can test different real life examples of AI crews in the [CrewAI-examples re
CrewAI's power truly shines when combining Crews with Flows to create sophisticated automation pipelines. Here's how you can orchestrate multiple Crews within a Flow:
# Demonstrate low-level control with structured state
self.state.sentiment="analyzing"
return{"sector":"tech","timeframe":"1W"}# These parameters match the task description template
@listen(fetch_market_data)
defanalyze_with_crew(self,market_data):
# Show crew agency through specialized roles
analyst=Agent(
role="Senior Market Analyst",
goal="Conduct deep market analysis with expert insight",
backstory="You're a veteran analyst known for identifying subtle market patterns"
)
researcher=Agent(
role="Data Researcher",
goal="Gather and validate supporting market data",
backstory="You excel at finding and correlating multiple data sources"
)
analysis_task=Task(
description="Analyze {sector} sector data for the past {timeframe}",
expected_output="Detailed market analysis with confidence score",
agent=analyst
)
research_task=Task(
description="Find supporting data to validate the analysis",
expected_output="Corroborating evidence and potential contradictions",
agent=researcher
)
# Demonstrate crew autonomy
analysis_crew=Crew(
agents=[analyst,researcher],
tasks=[analysis_task,research_task],
process=Process.sequential,
verbose=True
)
returnanalysis_crew.kickoff(inputs=market_data)# Pass market_data as named inputs
@router(analyze_with_crew)
defdetermine_next_steps(self):
# Show flow control with conditional routing
ifself.state.confidence>0.8:
return"high_confidence"
elifself.state.confidence>0.5:
return"medium_confidence"
return"low_confidence"
@listen("high_confidence")
defexecute_strategy(self):
# Demonstrate complex decision making
strategy_crew=Crew(
agents=[
Agent(role="Strategy Expert",
goal="Develop optimal market strategy")
],
tasks=[
Task(description="Create detailed strategy based on analysis",
expected_output="Step-by-step action plan")
]
)
returnstrategy_crew.kickoff()
@listen("medium_confidence","low_confidence")
defrequest_additional_analysis(self):
self.state.recommendations.append("Gather more data")
return"Additional analysis required"
```
This example demonstrates how to:
1. Use Python code for basic data operations
2. Create and execute Crews as steps in your workflow
3. Use Flow decorators to manage the sequence of operations
4. Implement conditional branching based on Crew results
## Connecting Your Crew to a Model
CrewAI supports using various LLMs through a variety of connection options. By default your agents will use the OpenAI API when querying the model. However, there are several other ways to allow your agents to connect to models. For example, you can configure your agents to use a local model via the Ollama tool.
@@ -313,9 +457,13 @@ Please refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-
## How CrewAI Compares
**CrewAI's Advantage**: CrewAI is built with production in mind. It offers the flexibility of Autogen's conversational agents and the structured process approach of ChatDev, but without the rigidity. CrewAI's processes are designed to be dynamic and adaptable, fitting seamlessly into both development and production workflows.
**CrewAI's Advantage**: CrewAI combines autonomous agent intelligence with precise workflow control through its unique Crews and Flows architecture. The framework excels at both high-level orchestration and low-level customization, enabling complex, production-grade systems with granular control.
- **Autogen**: While Autogen does good in creating conversational agents capable of working together, it lacks an inherent concept of process. In Autogen, orchestrating agents' interactions requires additional programming, which can become complex and cumbersome as the scale of tasks grows.
- **LangGraph**: While LangGraph provides a foundation for building agent workflows, its approach requires significant boilerplate code and complex state management patterns. The framework's tight coupling with LangChain can limit flexibility when implementing custom agent behaviors or integrating with external systems.
*P.S. CrewAI demonstrates significant performance advantages over LangGraph, executing 5.76x faster in certain cases like this QA task example ([see comparison](https://github.com/crewAIInc/crewAI-examples/tree/main/Notebooks/CrewAI%20Flows%20%26%20Langgraph/QA%20Agent)) while achieving higher evaluation scores with faster completion times in certain coding tasks, like in this example ([detailed analysis](https://github.com/crewAIInc/crewAI-examples/blob/main/Notebooks/CrewAI%20Flows%20%26%20Langgraph/Coding%20Assistant/coding_assistant_eval.ipynb)).*
- **Autogen**: While Autogen excels at creating conversational agents capable of working together, it lacks an inherent concept of process. In Autogen, orchestrating agents' interactions requires additional programming, which can become complex and cumbersome as the scale of tasks grows.
- **ChatDev**: ChatDev introduced the idea of processes into the realm of AI agents, but its implementation is quite rigid. Customizations in ChatDev are limited and not geared towards production environments, which can hinder scalability and flexibility in real-world applications.
@@ -357,7 +505,7 @@ uv run pytest .
### Running static type checks
```bash
uvx mypy
uvx mypy src
```
### Packaging
@@ -376,7 +524,7 @@ pip install dist/*.tar.gz
CrewAI uses anonymous telemetry to collect usage data with the main purpose of helping us improve the library by focusing our efforts on the most used features, integrations and tools.
It's pivotal to understand that **NO data is collected** concerning prompts, task descriptions, agents' backstories or goals, usage of tools, API calls, responses, any data processed by the agents, or secrets and environment variables, with the exception of the conditions mentioned. When the `share_crew` feature is enabled, detailed data including task descriptions, agents' backstories or goals, and other specific attributes are collected to provide deeper insights while respecting user privacy. We don't offer a way to disable it now, but we will in the future.
It's pivotal to understand that **NO data is collected** concerning prompts, task descriptions, agents' backstories or goals, usage of tools, API calls, responses, any data processed by the agents, or secrets and environment variables, with the exception of the conditions mentioned. When the `share_crew` feature is enabled, detailed data including task descriptions, agents' backstories or goals, and other specific attributes are collected to provide deeper insights while respecting user privacy. Users can disable telemetry by setting the environment variable OTEL_SDK_DISABLED to true.
Data collected includes:
@@ -440,5 +588,8 @@ A: CrewAI uses anonymous telemetry to collect usage data for improvement purpose
### Q: Where can I find examples of CrewAI in action?
A: You can find various real-life examples in the [CrewAI-examples repository](https://github.com/crewAIInc/crewAI-examples), including trip planners, stock analysis tools, and more.
### Q: What is the difference between Crews and Flows?
A: Crews and Flows serve different but complementary purposes in CrewAI. Crews are teams of AI agents working together to accomplish specific tasks through role-based collaboration, delivering accurate and predictable results. Flows, on the other hand, are event-driven workflows that can orchestrate both Crews and regular Python code, allowing you to build complex automation pipelines with secure state management and conditional execution paths.
### Q: How can I contribute to CrewAI?
A: Contributions are welcome! You can fork the repository, create a new branch for your feature, add your improvement, and send a pull request. Check the Contribution section in the README for more details.
description: What are CrewAI Agents and how to use them.
description: Detailed guide on creating and managing agents within the CrewAI framework.
icon: robot
---
## What is an agent?
## Overview of an Agent
An agent is an **autonomous unit** programmed to:
<ul>
<li class='leading-3'>Perform tasks</li>
<li class='leading-3'>Make decisions</li>
<li class='leading-3'>Communicate with other agents</li>
</ul>
In the CrewAI framework, an `Agent` is an autonomous unit that can:
- Perform specific tasks
- Make decisions based on its role and goal
- Use tools to accomplish objectives
- Communicate and collaborate with other agents
- Maintain memory of interactions
- Delegate tasks when allowed
<Tip>
Think of an agent as a member of a team, with specific skills and a particular job to do. Agents can have different roles like `Researcher`, `Writer`, or `Customer Support`, each contributing to the overall goal of the crew.
Think of an agent as a specialized team member with specific skills, expertise, and responsibilities. For example, a `Researcher` agent might excel at gathering and analyzing information, while a `Writer` agent might be better at creating content.
| **Role** | `role` | Defines the agent's function within the crew. It determines the kind of tasks the agent is best suited for. |
| **Goal** | `goal` | The individual objective that the agent aims to achieve. It guides the agent's decision-making process. |
| **Backstory** | `backstory`| Provides context to the agent's role and goal, enriching the interaction and collaboration dynamics. |
| **LLM** *(optional)* | `llm` | Represents the language model that will run the agent. It dynamically fetches the model name from the `OPENAI_MODEL_NAME` environment variable, defaulting to "gpt-4" if not specified. |
| **Tools** *(optional)* | `tools` | Set of capabilities or functions that the agent can use to perform tasks. Expected to be instances of custom classes compatible with the agent's execution environment. Tools are initialized with a default value of an empty list. |
| **Function Calling LLM** *(optional)* | `function_calling_llm` | Specifies the language model that will handle the tool calling for this agent, overriding the crew function calling LLM if passed. Default is `None`. |
| **Max Iter** *(optional)* | `max_iter` | Max Iter is the maximum number of iterations the agent can perform before being forced to give its best answer. Default is `25`. |
| **Max RPM** *(optional)* | `max_rpm` | Max RPM is the maximum number of requests per minute the agent can perform to avoid rate limits. It's optional and can be left unspecified, with a default value of `None`. |
| **Max Execution Time** *(optional)* | `max_execution_time` | Max Execution Time is the maximum execution time for an agent to execute a task. It's optional and can be left unspecified, with a default value of `None`, meaning no max execution time. |
| **Verbose** *(optional)*| `verbose` | Setting this to `True` configures the internal logger to provide detailed execution logs, aiding in debugging and monitoring. Default is `False`. |
| **Allow Delegation** *(optional)* | `allow_delegation` | Agents can delegate tasks or questions to one another, ensuring that each task is handled by the most suitable agent. Default is `False`. |
| **Step Callback** *(optional)* | `step_callback` | A function that is called after each step of the agent. This can be used to log the agent's actions or to perform other operations. It will overwrite the crew `step_callback`. |
| **Cache** *(optional)*| `cache` | Indicates if the agent should use a cache for tool usage. Default is `True`. |
| **System Template** *(optional)*| `system_template` | Specifies the system format for the agent. Default is `None`. |
| **Prompt Template** *(optional)* | `prompt_template` | Specifies the prompt format for the agent. Default is `None`. |
| **Response Template** *(optional)* | `response_template` | Specifies the response format for the agent. Default is `None`. |
| **Allow Code Execution** *(optional)* | `allow_code_execution` | Enable code execution for the agent. Default is `False`. |
| **Max Retry Limit** *(optional)* | `max_retry_limit` | Maximum number of retries for an agent to execute a task when an error occurs. Default is `2`. |
| **Use System Prompt** *(optional)* | `use_system_prompt` | Adds the ability to not use system prompt (to support o1 models). Default is `True`. |
| **Respect Context Window** *(optional)* | `respect_context_window` | Summary strategy to avoid overflowing the context window. Default is `True`. |
| **Code Execution Mode** *(optional)* | `code_execution_mode` | Determines the mode for code execution: 'safe' (using Docker) or 'unsafe' (direct execution on the host machine). Default is `safe`. |
| **Role** | `role` | `str`| Defines the agent's function and expertise within the crew. |
| **Goal** | `goal` | `str` | The individual objective that guides the agent's decision-making. |
| **Backstory** | `backstory` | `str` | Provides context and personality to the agent, enriching interactions. |
| **LLM** _(optional)_ | `llm` | `Union[str, LLM, Any]` | Language model that powers the agent. Defaults to the model specified in `OPENAI_MODEL_NAME` or "gpt-4". |
| **Tools** _(optional)_ | `tools` | `List[BaseTool]` | Capabilities or functions available to the agent. Defaults to an empty list. |
| **Function Calling LLM** _(optional)_ | `function_calling_llm` | `Optional[Any]` | Language model for tool calling, overrides crew's LLM if specified. |
| **Max Iterations** _(optional)_ | `max_iter` | `int` | Maximum iterations before the agent must provide its best answer. Default is 20. |
| **Max RPM** _(optional)_ | `max_rpm` | `Optional[int]` | Maximum requests per minute to avoid rate limits. |
| **Max Execution Time** _(optional)_ | `max_execution_time` | `Optional[int]` | Maximum time (in seconds) for task execution. |
| **Memory** _(optional)_ | `memory` | `bool`| Whether the agent should maintain memory of interactions. Default is True. |
| **Verbose** _(optional)_ | `verbose` | `bool` | Enable detailed execution logs for debugging. Default is False. |
| **Allow Delegation** _(optional)_ | `allow_delegation` | `bool` | Allow the agent to delegate tasks to other agents. Default is False. |
| **Step Callback** _(optional)_ | `step_callback` | `Optional[Any]` | Function called after each agent step, overrides crew callback. |
| **Cache** _(optional)_ | `cache` | `bool`| Enable caching for tool usage. Default is True. |
| **System Template** _(optional)_ | `system_template` | `Optional[str]` | Custom system prompt template for the agent. |
| **Prompt Template** _(optional)_ | `prompt_template` | `Optional[str]` | Custom prompt template for the agent. |
| **Response Template** _(optional)_ | `response_template` | `Optional[str]` | Custom response template for the agent. |
| **Allow Code Execution** _(optional)_ | `allow_code_execution` | `Optional[bool]` | Enable code execution for the agent. Default is False. |
| **Max Retry Limit** _(optional)_ | `max_retry_limit` | `int` | Maximum number of retries when an error occurs. Default is 2. |
| **Respect Context Window** _(optional)_ | `respect_context_window` | `bool` | Keep messages under context window size by summarizing. Default is True. |
| **Code Execution Mode** _(optional)_ | `code_execution_mode` | `Literal["safe", "unsafe"]` | Mode for code execution: 'safe' (using Docker) or 'unsafe' (direct). Default is 'safe'. |
| **Embedder Config** _(optional)_ | `embedder_config` | `Optional[Dict[str, Any]]` | Configuration for the embedder used by the agent. |
| **Knowledge Sources** _(optional)_ | `knowledge_sources` | `Optional[List[BaseKnowledgeSource]]` | Knowledge sources available to the agent. |
| **Use System Prompt** _(optional)_ | `use_system_prompt` | `Optional[bool]` | Whether to use system prompt (for o1 model support). Default is True. |
## Creating an agent
## Creating Agents
There are two ways to create agents in CrewAI: using **YAML configuration (recommended)** or defining them **directly in code**.
### YAML Configuration (Recommended)
Using YAML configuration provides a cleaner, more maintainable way to define agents. We strongly recommend using this approach in your CrewAI projects.
After creating your CrewAI project as outlined in the [Installation](/installation) section, navigate to the `src/latest_ai_development/config/agents.yaml` file and modify the template to match your requirements.
<Note>
**Agent interaction**: Agents can interact with each other using CrewAI's built-in delegation and communication mechanisms. This allows for dynamic task management and problem-solving within the crew.
Variables in your YAML files (like `{topic}`) will be replaced with values from your inputs when running the crew:
```python Code
crew.kickoff(inputs={'topic': 'AI Agents'})
```
</Note>
To create an agent, you would typically initialize an instance of the `Agent` class with the desired properties. Here's a conceptual example including all attributes:
Here's an example of how to configure agents using YAML:
```python Code example
```yaml agents.yaml
# src/latest_ai_development/config/agents.yaml
researcher:
role: >
{topic} Senior Data Researcher
goal: >
Uncover cutting-edge developments in {topic}
backstory: >
You're a seasoned researcher with a knack for uncovering the latest
developments in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
reporting_analyst:
role: >
{topic} Reporting Analyst
goal: >
Create detailed reports based on {topic} data analysis and research findings
backstory: >
You're a meticulous analyst with a keen eye for detail. You're known for
your ability to turn complex data into clear and concise reports, making
it easy for others to understand and act on the information you provide.
```
To use this YAML configuration in your code, create a crew class that inherits from `CrewBase`:
```python Code
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process
from crewai.project import CrewBase, agent, crew
from crewai_tools import SerperDevTool
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
verbose=True,
tools=[SerperDevTool()]
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'],
verbose=True
)
```
<Note>
The names you use in your YAML files (`agents.yaml`) should match the method names in your Python code.
</Note>
### Direct Code Definition
You can create agents directly in code by instantiating the `Agent` class. Here's a comprehensive example showing all available parameters:
```python Code
from crewai import Agent
from crewai_tools import SerperDevTool
# Create an agent with all available parameters
agent = Agent(
role='Data Analyst',
goal='Extract actionable insights',
backstory="""You're a data analyst at a large company.
You're responsible for analyzing data and providing insights
to the business.
You're currently working on a project to analyze the
performance of our marketing campaigns.""",
tools=[my_tool1, my_tool2], # Optional, defaults to an empty list
step_callback=None, # Optional: Callback function for monitoring
)
```
## Setting prompt templates
Let's break down some key parameter combinations for common use cases:
Prompt templates are used to format the prompt for the agent. You can use to update the system, regular and response templates for the agent. Here's an example of how to set prompt templates:
#### Basic Research Agent
```python Code
research_agent = Agent(
role="Research Analyst",
goal="Find and summarize information about specific topics",
backstory="You are an experienced researcher with attention to detail",
When using custom templates, you can use variables like `{role}`, `{goal}`, and `{input}` in your templates. These will be automatically populated during execution.
</Note>
CrewAI is a universal multi-agent framework that allows for all agents to work together to automate tasks and solve problems.
## Agent Tools
```python Code example
from crewai import Agent, Task, Crew
from custom_agent import CustomAgent # You need to build and extend your own agent logic with the CrewAI BaseAgent class then import it here.
Agents can be equipped with various tools to enhance their capabilities. CrewAI supports tools from:
Agents are the building blocks of the CrewAI framework. By understanding how to define and interact with agents,
you can create sophisticated AI systems that leverage the power of collaborative intelligence. The `code_execution_mode` attribute provides flexibility in how agents execute code, allowing for both secure and direct execution options.
Agents can maintain memory of their interactions and use context from previous tasks. This is particularly useful for complex workflows where information needs to be retained across multiple tasks.
```python Code
from crewai import Agent
analyst = Agent(
role="Data Analyst",
goal="Analyze and remember complex data patterns",
memory=True, # Enable memory
verbose=True
)
```
<Note>
When `memory` is enabled, the agent will maintain context across multiple interactions, improving its ability to handle complex, multi-step tasks.
</Note>
## Important Considerations and Best Practices
### Security and Code Execution
- When using `allow_code_execution`, be cautious with user input and always validate it
- Use `code_execution_mode: "safe"` (Docker) in production environments
- Consider setting appropriate `max_execution_time` limits to prevent infinite loops
### Performance Optimization
- Use `respect_context_window: true` to prevent token limit issues
- Set appropriate `max_rpm` to avoid rate limiting
- Enable `cache: true` to improve performance for repetitive tasks
- Adjust `max_iter` and `max_retry_limit` based on task complexity
### Memory and Context Management
- Use `memory: true` for tasks requiring historical context
- Leverage `knowledge_sources` for domain-specific information
- Configure `embedder_config` when using custom embedding models
- Use custom templates (`system_template`, `prompt_template`, `response_template`) for fine-grained control over agent behavior
### Agent Collaboration
- Enable `allow_delegation: true` when agents need to work together
- Use `step_callback` to monitor and log agent interactions
- Consider using different LLMs for different purposes:
- Main `llm` for complex reasoning
- `function_calling_llm` for efficient tool usage
### Model Compatibility
- Set `use_system_prompt: false` for older models that don't support system messages
- Ensure your chosen `llm` supports the features you need (like function calling)
## Troubleshooting Common Issues
1. **Rate Limiting**: If you're hitting API rate limits:
- Implement appropriate `max_rpm`
- Use caching for repetitive operations
- Consider batching requests
2. **Context Window Errors**: If you're exceeding context limits:
- Enable `respect_context_window`
- Use more efficient prompts
- Clear agent memory periodically
3. **Code Execution Issues**: If code execution fails:
- Verify Docker is installed for safe mode
- Check execution permissions
- Review code sandbox settings
4. **Memory Issues**: If agent responses seem inconsistent:
- Verify memory is enabled
- Check knowledge source configuration
- Review conversation history management
Remember that agents are most effective when configured according to their specific use case. Take time to understand your requirements and adjust these parameters accordingly.
@@ -32,7 +32,6 @@ A crew in crewAI represents a collaborative group of agents working together to
| **Share Crew** _(optional)_ | `share_crew` | Whether you want to share the complete crew information and execution with the crewAI team to make the library better, and allow us to train models. |
| **Output Log File** _(optional)_ | `output_log_file` | Whether you want to have a file with the complete crew output and execution. You can set it using True and it will default to the folder you are currently in and it will be called logs.txt or passing a string with the full path and name of the file. |
| **Manager Agent** _(optional)_ | `manager_agent` | `manager` sets a custom agent that will be used as a manager. |
| **Manager Callbacks** _(optional)_ | `manager_callbacks` | `manager_callbacks` takes a list of callback handlers to be executed by the manager agent when a hierarchical process is used. |
| **Prompt File** _(optional)_ | `prompt_file` | Path to the prompt JSON file to be used for the crew. |
| **Planning** *(optional)* | `planning` | Adds planning ability to the Crew. When activated before each Crew iteration, all Crew data is sent to an AgentPlanner that will plan the tasks and this plan will be added to each task description. |
| **Planning LLM** *(optional)* | `planning_llm` | The language model used by the AgentPlanner in a planning process. |
@@ -41,6 +40,155 @@ A crew in crewAI represents a collaborative group of agents working together to
**Crew Max RPM**: 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.
</Tip>
## Creating Crews
There are two ways to create crews in CrewAI: using **YAML configuration (recommended)** or defining them **directly in code**.
### YAML Configuration (Recommended)
Using YAML configuration provides a cleaner, more maintainable way to define crews and is consistent with how agents and tasks are defined in CrewAI projects.
After creating your CrewAI project as outlined in the [Installation](/installation) section, you can define your crew in a class that inherits from `CrewBase` and uses decorators to define agents, tasks, and the crew itself.
#### Example Crew Class with Decorators
```python code
from crewai import Agent, Crew, Task, Process
from crewai.project import CrewBase, agent, task, crew, before_kickoff, after_kickoff
@CrewBase
class YourCrewName:
"""Description of your crew"""
# Paths to your YAML configuration files
# To see an example agent and task defined in YAML, checkout the following:
@@ -18,63 +18,60 @@ Flows allow you to create structured, event-driven workflows. They provide a sea
4. **Flexible Control Flow**: Implement conditional logic, loops, and branching within your workflows.
5. **Input Flexibility**: Flows can accept inputs to initialize or update their state, with different handling for structured and unstructured state management.
## Getting Started
Let's create a simple Flow where you will use OpenAI to generate a random city in one task and then use that city to generate a fun fact in another task.
### Passing Inputs to Flows
```python Code
Flows can accept inputs to initialize or update their state before execution. The way inputs are handled depends on whether the flow uses structured or unstructured state management.
#### Structured State Management
In structured state management, the flow's state is defined using a Pydantic `BaseModel`. Inputs must match the model's schema, and any updates will overwrite the default values.
```python
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel
from dotenv import load_dotenv
from litellm import completion
class ExampleState(BaseModel):
counter: int = 0
message: str = ""
class StructuredExampleFlow(Flow[ExampleState]):
class ExampleFlow(Flow):
model = "gpt-4o-mini"
@start()
def first_method(self):
# Implementation
def generate_city(self):
print("Starting flow")
flow = StructuredExampleFlow()
flow.kickoff(inputs={"counter": 10})
```
response = completion(
model=self.model,
messages=[
{
"role": "user",
"content": "Return the name of a random city in the world.",
},
],
)
In this example, the `counter` is initialized to `10`, while `message` retains its default value.
Here, both `counter` and `message` are updated based on the provided inputs.
flow = ExampleFlow()
result = flow.kickoff()
**Note:** Ensure that inputs for structured state management adhere to the defined schema to avoid validation errors.
### Example Flow
```python
# Existing example code
print(f"Generated fun fact: {result}")
```
In the above example, we have created a simple Flow that generates a random city using OpenAI and then generates a fun fact about that city. The Flow consists of two tasks: `generate_city` and `generate_fun_fact`. The `generate_city` task is the starting point of the Flow, and the `generate_fun_fact` task listens for the output of the `generate_city` task.
@@ -97,14 +94,14 @@ The `@listen()` decorator can be used in several ways:
1. **Listening to a Method by Name**: You can pass the name of the method you want to listen to as a string. When that method completes, the listener method will be triggered.
```python
```python Code
@listen("generate_city")
def generate_fun_fact(self, random_city):
# Implementation
```
2. **Listening to a Method Directly**: You can pass the method itself. When that method completes, the listener method will be triggered.
```python
```python Code
@listen(generate_city)
def generate_fun_fact(self, random_city):
# Implementation
@@ -121,7 +118,7 @@ When you run a Flow, the final output is determined by the last method that comp
Here's how you can access the final output:
<CodeGroup>
```python
```python Code
from crewai.flow.flow import Flow, listen, start
class OutputExampleFlow(Flow):
@@ -133,17 +130,18 @@ class OutputExampleFlow(Flow):
def second_method(self, first_output):
return f"Second method received: {first_output}"
flow = OutputExampleFlow()
final_output = flow.kickoff()
print("---- Final Output ----")
print(final_output)
```
````
```text
```text Output
---- Final Output ----
Second method received: Output from first_method
```
````
</CodeGroup>
@@ -158,7 +156,7 @@ Here's an example of how to update and access the state:
<CodeGroup>
```python
```python Code
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel
@@ -186,7 +184,7 @@ print("Final State:")
print(flow.state)
```
```text
```text Output
Final Output: Hello from first_method - updated by second_method
Final State:
counter=2 message='Hello from first_method - updated by second_method'
@@ -210,10 +208,10 @@ allowing developers to choose the approach that best fits their application's ne
In unstructured state management, all state is stored in the `state` attribute of the `Flow` class.
This approach offers flexibility, enabling developers to add or modify state attributes on the fly without defining a strict schema.
```python
```python Code
from crewai.flow.flow import Flow, listen, start
class UnstructuredExampleFlow(Flow):
class UntructuredExampleFlow(Flow):
@start()
def first_method(self):
@@ -232,7 +230,8 @@ class UnstructuredExampleFlow(Flow):
print(f"State after third_method: {self.state}")
flow = UnstructuredExampleFlow()
flow = UntructuredExampleFlow()
flow.kickoff()
```
@@ -246,14 +245,16 @@ flow.kickoff()
Structured state management leverages predefined schemas to ensure consistency and type safety across the workflow.
By using models like Pydantic's `BaseModel`, developers can define the exact shape of the state, enabling better validation and auto-completion in development environments.
```python
```python Code
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel
class ExampleState(BaseModel):
counter: int = 0
message: str = ""
class StructuredExampleFlow(Flow[ExampleState]):
@start()
@@ -272,6 +273,7 @@ class StructuredExampleFlow(Flow[ExampleState]):
print(f"State after third_method: {self.state}")
flow = StructuredExampleFlow()
flow.kickoff()
```
@@ -305,7 +307,7 @@ The `or_` function in Flows allows you to listen to multiple methods and trigger
<CodeGroup>
```python
```python Code
from crewai.flow.flow import Flow, listen, or_, start
class OrExampleFlow(Flow):
@@ -322,11 +324,13 @@ class OrExampleFlow(Flow):
def logger(self, result):
print(f"Logger: {result}")
flow = OrExampleFlow()
flow.kickoff()
```
```text
```text Output
Logger: Hello from the start method
Logger: Hello from the second method
```
@@ -342,7 +346,7 @@ The `and_` function in Flows allows you to listen to multiple methods and trigge
<CodeGroup>
```python
```python Code
from crewai.flow.flow import Flow, and_, listen, start
class AndExampleFlow(Flow):
@@ -364,7 +368,7 @@ flow = AndExampleFlow()
flow.kickoff()
```
```text
```text Output
---- Logger ----
{'greeting': 'Hello from the start method', 'joke': 'What do computers eat? Microchips.'}
```
@@ -381,7 +385,7 @@ You can specify different routes based on the output of the method, allowing you
<CodeGroup>
```python
```python Code
import random
from crewai.flow.flow import Flow, listen, router, start
from pydantic import BaseModel
@@ -412,11 +416,12 @@ class RouterFlow(Flow[ExampleState]):
def fourth_method(self):
print("Fourth method running")
flow = RouterFlow()
flow.kickoff()
```
```text
```text Output
Starting the structured flow
Third method running
Fourth method running
@@ -479,7 +484,7 @@ The `main.py` file is where you create your flow and connect the crews together.
Here's an example of how you can connect the `poem_crew` in the `main.py` file:
```python
```python Code
#!/usr/bin/env python
from random import randint
@@ -555,42 +560,6 @@ uv run kickoff
The flow will execute, and you should see the output in the console.
### Adding Additional Crews Using the CLI
Once you have created your initial flow, you can easily add additional crews to your project using the CLI. This allows you to expand your flow's capabilities by integrating new crews without starting from scratch.
To add a new crew to your existing flow, use the following command:
```bash
crewai flow add-crew <crew_name>
```
This command will create a new directory for your crew within the `crews` folder of your flow project. It will include the necessary configuration files and a crew definition file, similar to the initial setup.
#### Folder Structure
After adding a new crew, your folder structure will look like this:
| └── `name_of_crew/` | Directory for the new crew. |
| ├── `config/` | Configuration files directory for the new crew. |
| │ ├── `agents.yaml` | YAML file defining the agents for the new crew. |
| │ └── `tasks.yaml` | YAML file defining the tasks for the new crew. |
| └── `name_of_crew.py` | Script for the new crew functionality. |
You can then customize the `agents.yaml` and `tasks.yaml` files to define the agents and tasks for your new crew. The `name_of_crew.py` file will contain the crew's logic, which you can modify to suit your needs.
By using the CLI to add additional crews, you can efficiently build complex AI workflows that leverage multiple crews working together.
## Plot Flows
Visualizing your AI workflows can provide valuable insights into the structure and execution paths of your flows. CrewAI offers a powerful visualization tool that allows you to generate interactive plots of your flows, making it easier to understand and optimize your AI workflows.
@@ -607,7 +576,7 @@ CrewAI provides two convenient methods to generate plots of your flows:
If you are working directly with a flow instance, you can generate a plot by calling the `plot()` method on your flow object. This method will create an HTML file containing the interactive plot of your flow.
```python
```python Code
# Assuming you have a flow instance
flow.plot("my_flow_plot")
```
@@ -630,114 +599,13 @@ The generated plot will display nodes representing the tasks in your flow, with
By visualizing your flows, you can gain a clearer understanding of the workflow's structure, making it easier to debug, optimize, and communicate your AI processes to others.
### Conclusion
## Advanced
In this section, we explore more complex use cases of CrewAI Flows, starting with a self-evaluation loop. This pattern is crucial for developing AI systems that can iteratively improve their outputs through feedback.
### 1) Self-Evaluation Loop
The self-evaluation loop is a powerful pattern that allows AI workflows to automatically assess and refine their outputs. This example demonstrates how to set up a flow that generates content, evaluates it, and iterates based on feedback until the desired quality is achieved.
#### Overview
The self-evaluation loop involves two main Crews:
1. **ShakespeareanXPostCrew**: Generates a Shakespearean-style post on a given topic.
2. **XPostReviewCrew**: Evaluates the generated post, providing feedback on its validity and quality.
The process iterates until the post meets the criteria or a maximum retry limit is reached. This approach ensures high-quality outputs through iterative refinement.
#### Importance
This pattern is essential for building robust AI systems that can adapt and improve over time. By automating the evaluation and feedback loop, developers can ensure that their AI workflows produce reliable and high-quality results.
#### Main Code Highlights
Below is the `main.py` file for the self-evaluation loop flow:
```python
from typing import Optional
from crewai.flow.flow import Flow, listen, router, start
from pydantic import BaseModel
from self_evaluation_loop_flow.crews.shakespeare_crew.shakespeare_crew import (
ShakespeareanXPostCrew,
)
from self_evaluation_loop_flow.crews.x_post_review_crew.x_post_review_crew import (
XPostReviewCrew,
)
class ShakespeareXPostFlowState(BaseModel):
x_post: str = ""
feedback: Optional[str] = None
valid: bool = False
retry_count: int = 0
class ShakespeareXPostFlow(Flow[ShakespeareXPostFlowState]):
result = XPostReviewCrew().crew().kickoff(inputs={"x_post": self.state.x_post})
self.state.valid = result["valid"]
self.state.feedback = result["feedback"]
print("valid", self.state.valid)
print("feedback", self.state.feedback)
self.state.retry_count += 1
if self.state.valid:
return "complete"
return "retry"
@listen("complete")
def save_result(self):
print("X post is valid")
print("X post:", self.state.x_post)
with open("x_post.txt", "w") as file:
file.write(self.state.x_post)
@listen("max_retry_exceeded")
def max_retry_exceeded_exit(self):
print("Max retry count exceeded")
print("X post:", self.state.x_post)
print("Feedback:", self.state.feedback)
def kickoff():
shakespeare_flow = ShakespeareXPostFlow()
shakespeare_flow.kickoff()
def plot():
shakespeare_flow = ShakespeareXPostFlow()
shakespeare_flow.plot()
if __name__ == "__main__":
kickoff()
```
#### Code Highlights
- **Retry Mechanism**: The flow uses a retry mechanism to regenerate the post if it doesn't meet the criteria, up to a maximum of three retries.
- **Feedback Loop**: Feedback from the `XPostReviewCrew` is used to refine the post iteratively.
- **State Management**: The flow maintains state using a Pydantic model, ensuring type safety and clarity.
For a complete example and further details, please refer to the [Self Evaluation Loop Flow repository](https://github.com/crewAIInc/crewAI-examples/tree/main/self_evaluation_loop_flow).
Plotting your flows is a powerful feature of CrewAI that enhances your ability to design and manage complex AI workflows. Whether you choose to use the `plot()` method or the command line, generating plots will provide you with a visual representation of your workflows, aiding in both development and presentation.
## Next Steps
If you're interested in exploring additional examples of flows, we have a variety of recommendations in our examples repository. Here are five specific flow examples, each showcasing unique use cases to help you match your current problem type to a specific example:
If you're interested in exploring additional examples of flows, we have a variety of recommendations in our examples repository. Here are four specific flow examples, each showcasing unique use cases to help you match your current problem type to a specific example:
1. **Email Auto Responder Flow**: This example demonstrates an infinite loop where a background job continually runs to automate email responses. It's a great use case for tasks that need to be performed repeatedly without manual intervention. [View Example](https://github.com/crewAIInc/crewAI-examples/tree/main/email_auto_responder_flow)
@@ -747,8 +615,6 @@ If you're interested in exploring additional examples of flows, we have a variet
4. **Meeting Assistant Flow**: This flow demonstrates how to broadcast one event to trigger multiple follow-up actions. For instance, after a meeting is completed, the flow can update a Trello board, send a Slack message, and save the results. It's a great example of handling multiple outcomes from a single event, making it ideal for comprehensive task management and notification systems. [View Example](https://github.com/crewAIInc/crewAI-examples/tree/main/meeting_assistant_flow)
5. **Self Evaluation Loop Flow**: This flow demonstrates a self-evaluation loop where AI workflows automatically assess and refine their outputs through feedback. It involves generating content, evaluating it, and iterating until the desired quality is achieved. This pattern is crucial for developing robust AI systems that can adapt and improve over time. [View Example](https://github.com/crewAIInc/crewAI-examples/tree/main/self_evaluation_loop_flow)
By exploring these examples, you can gain insights into how to leverage CrewAI Flows for various use cases, from automating repetitive tasks to managing complex, multi-step processes with dynamic decision-making and human feedback.
Also, check out our YouTube video on how to use flows in CrewAI below!
@@ -762,4 +628,4 @@ Also, check out our YouTube video on how to use flows in CrewAI below!
The Knowledge class in CrewAI provides a powerful way to manage and query knowledge sources for your AI agents. This guide will show you how to implement knowledge management in your CrewAI projects.
Additionally, we have specific tools for generate knowledge sources for strings, text files, PDF's, and Spreadsheets. You can expand on any source type by extending the `KnowledgeSource` class.
Knowledge in CrewAI is a powerful system that allows AI agents to access and utilize external information sources during their tasks.
Think of it as giving your agents a reference library they can consult while working.
## Basic Implementation
<Info>
Key benefits of using Knowledge:
- Enhance agents with domain-specific information
- Support decisions with real-world data
- Maintain context across conversations
- Ground responses in factual information
</Info>
Here's a simple example of how to use the Knowledge class:
## Supported Knowledge Sources
```python
CrewAI supports various types of knowledge sources out of the box:
<CardGroup cols={2}>
<Card title="Text Sources" icon="text">
- Raw strings
- Text files (.txt)
- PDF documents
</Card>
<Card title="Structured Data" icon="table">
- CSV files
- Excel spreadsheets
- JSON documents
</Card>
</CardGroup>
## Quick Start
Here's an example using string-based knowledge:
```python Code
from crewai import Agent, Task, Crew, Process, LLM
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# Create a knowledge source
content = "Users name is John. He is 30 years old and lives in San Francisco."
# Create an LLM with a temperature of 0 to ensure deterministic outputs
llm = LLM(model="gpt-4o-mini", temperature=0)
# Create an agent with the knowledge store
# Create an agent with the knowledge store
agent = Agent(
role="About User",
goal="You know everything about the user.",
@@ -47,29 +73,348 @@ crew = Crew(
tasks=[task],
verbose=True,
process=Process.sequential,
knowledge={"sources": [string_source], "metadata": {"preference": "personal"}}, # Enable knowledge by adding the sources here. You can also add more sources to the sources list.
knowledge_sources=[string_source], # Enable knowledge by adding the sources here. You can also add more sources to the sources list.
)
result = crew.kickoff(inputs={"question": "What city does John live in and how old is he?"})
```
Here's another example with the `CrewDoclingSource`
```python Code
from crewai import LLM, Agent, Crew, Process, Task
from crewai.knowledge.source.crew_docling_source import CrewDoclingSource
# Create an LLM with a temperature of 0 to ensure deterministic outputs
llm = LLM(model="gpt-4o-mini", temperature=0)
# Create an agent with the knowledge store
agent = Agent(
role="About papers",
goal="You know everything about the papers.",
backstory="""You are a master at understanding papers and their content.""",
verbose=True,
allow_delegation=False,
llm=llm,
)
task = Task(
description="Answer the following questions about the papers: {question}",
expected_output="An answer to the question.",
agent=agent,
)
crew = Crew(
agents=[agent],
tasks=[task],
verbose=True,
process=Process.sequential,
knowledge_sources=[
content_source
], # Enable knowledge by adding the sources here. You can also add more sources to the sources list.
)
result = crew.kickoff(
inputs={
"question": "What is the reward hacking paper about? Be sure to provide sources."
}
)
```
## Knowledge Configuration
### Chunking Configuration
Control how content is split for processing by setting the chunk size and overlap.
```python Code
knowledge_source = StringKnowledgeSource(
content="Long content...",
chunk_size=4000, # Characters per chunk (default)
chunk_overlap=200 # Overlap between chunks (default)
)
```
## Embedder Configuration
You can also configure the embedder for the knowledge store. This is useful if you want to use a different embedder for the knowledge store than the one used for the agents.
```python
```python Code
...
string_source = StringKnowledgeSource(
content="Users name is John. He is 30 years old and lives in San Francisco.",
If you need to clear the knowledge stored in CrewAI, you can use the `crewai reset-memories` command with the `--knowledge` option.
```bash Command
crewai reset-memories --knowledge
```
This is useful when you've updated your knowledge sources and want to ensure that the agents are using the most recent information.
## Agent-Specific Knowledge
While knowledge can be provided at the crew level using `crew.knowledge_sources`, individual agents can also have their own knowledge sources using the `knowledge_sources` parameter:
```python Code
from crewai import Agent, Task, Crew
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
# Create agent-specific knowledge about a product
product_specs = StringKnowledgeSource(
content="""The XPS 13 laptop features:
- 13.4-inch 4K display
- Intel Core i7 processor
- 16GB RAM
- 512GB SSD storage
- 12-hour battery life""",
metadata={"category": "product_specs"}
)
# Create a support agent with product knowledge
support_agent = Agent(
role="Technical Support Specialist",
goal="Provide accurate product information and support.",
backstory="You are an expert on our laptop products and specifications.",
description="Answer this customer question: {question}",
agent=support_agent
)
# Create and run the crew
crew = Crew(
agents=[support_agent],
tasks=[support_task]
)
# Get answer about the laptop's specifications
result = crew.kickoff(
inputs={"question": "What is the storage capacity of the XPS 13?"}
)
```
<Info>
Benefits of agent-specific knowledge:
- Give agents specialized information for their roles
- Maintain separation of concerns between agents
- Combine with crew-level knowledge for layered information access
</Info>
## Custom Knowledge Sources
CrewAI allows you to create custom knowledge sources for any type of data by extending the `BaseKnowledgeSource` class. Let's create a practical example that fetches and processes space news articles.
#### Space News Knowledge Source Example
<CodeGroup>
```python Code
from crewai import Agent, Task, Crew, Process, LLM
from crewai.knowledge.source.base_knowledge_source import BaseKnowledgeSource
import requests
from datetime import datetime
from typing import Dict, Any
from pydantic import BaseModel, Field
class SpaceNewsKnowledgeSource(BaseKnowledgeSource):
"""Knowledge source that fetches data from Space News API."""
goal="Answer questions about space news accurately and comprehensively",
backstory="""You are a space industry analyst with expertise in space exploration,
satellite technology, and space industry trends. You excel at answering questions
about space news and providing detailed, accurate information.""",
knowledge_sources=[recent_news],
llm=LLM(model="gpt-4", temperature=0.0)
)
# Create task that handles user questions
analysis_task = Task(
description="Answer this question about space news: {user_question}",
expected_output="A detailed answer based on the recent space news articles",
agent=space_analyst
)
# Create and run the crew
crew = Crew(
agents=[space_analyst],
tasks=[analysis_task],
verbose=True,
process=Process.sequential
)
# Example usage
result = crew.kickoff(
inputs={"user_question": "What are the latest developments in space exploration?"}
)
```
```output Output
# Agent: Space News Analyst
## Task: Answer this question about space news: What are the latest developments in space exploration?
# Agent: Space News Analyst
## Final Answer:
The latest developments in space exploration, based on recent space news articles, include the following:
1. SpaceX has received the final regulatory approvals to proceed with the second integrated Starship/Super Heavy launch, scheduled for as soon as the morning of Nov. 17, 2023. This is a significant step in SpaceX's ambitious plans for space exploration and colonization. [Source: SpaceNews](https://spacenews.com/starship-cleared-for-nov-17-launch/)
2. SpaceX has also informed the US Federal Communications Commission (FCC) that it plans to begin launching its first next-generation Starlink Gen2 satellites. This represents a major upgrade to the Starlink satellite internet service, which aims to provide high-speed internet access worldwide. [Source: Teslarati](https://www.teslarati.com/spacex-first-starlink-gen2-satellite-launch-2022/)
3. AI startup Synthetaic has raised $15 million in Series B funding. The company uses artificial intelligence to analyze data from space and air sensors, which could have significant applications in space exploration and satellite technology. [Source: SpaceNews](https://spacenews.com/ai-startup-synthetaic-raises-15-million-in-series-b-funding/)
4. The Space Force has formally established a unit within the U.S. Indo-Pacific Command, marking a permanent presence in the Indo-Pacific region. This could have significant implications for space security and geopolitics. [Source: SpaceNews](https://spacenews.com/space-force-establishes-permanent-presence-in-indo-pacific-region/)
5. Slingshot Aerospace, a space tracking and data analytics company, is expanding its network of ground-based optical telescopes to increase coverage of low Earth orbit. This could improve our ability to track and analyze objects in low Earth orbit, including satellites and space debris. [Source: SpaceNews](https://spacenews.com/slingshots-space-tracking-network-to-extend-coverage-of-low-earth-orbit/)
6. The National Natural Science Foundation of China has outlined a five-year project for researchers to study the assembly of ultra-large spacecraft. This could lead to significant advancements in spacecraft technology and space exploration capabilities. [Source: SpaceNews](https://spacenews.com/china-researching-challenges-of-kilometer-scale-ultra-large-spacecraft/)
7. The Center for AEroSpace Autonomy Research (CAESAR) at Stanford University is focusing on spacecraft autonomy. The center held a kickoff event on May 22, 2024, to highlight the industry, academia, and government collaboration it seeks to foster. This could lead to significant advancements in autonomous spacecraft technology. [Source: SpaceNews](https://spacenews.com/stanford-center-focuses-on-spacecraft-autonomy/)
CrewAI seamlessly integrates with LangChain’s comprehensive [list of tools](https://python.langchain.com/docs/integrations/tools/), all of which can be used with CrewAI.
CrewAI seamlessly integrates with LangChain's comprehensive [list of tools](https://python.langchain.com/docs/integrations/tools/), all of which can be used with CrewAI.
</Info>
```python Code
import os
from crewai import Agent
from langchain.agents import Tool
from langchain.utilities import GoogleSerperAPIWrapper
from dotenv import load_dotenv
from crewai import Agent, Task, Crew
from crewai.tools import BaseTool
from pydantic import Field
from langchain_community.utilities import GoogleSerperAPIWrapper
# Setup API keys
os.environ["SERPER_API_KEY"] = "Your Key"
# Setup your SERPER_API_KEY key in an .env file, eg:
# SERPER_API_KEY=<your api key>
load_dotenv()
search = GoogleSerperAPIWrapper()
# Create and assign the search tool to an agent
serper_tool = Tool(
name="Intermediate Answer",
func=search.run,
description="Useful for search-based queries",
)
class SearchTool(BaseTool):
name: str = "Search"
description: str = "Useful for search-based queries. Use this to find current information about markets, companies, and trends."
backstory='An expert analyst with a keen eye for market trends.',
tools=[serper_tool]
def _run(self, query: str) -> str:
"""Execute the search query and return results"""
try:
return self.search.run(query)
except Exception as e:
return f"Error performing search: {str(e)}"
# Create Agents
researcher = Agent(
role='Research Analyst',
goal='Gather current market data and trends',
backstory="""You are an expert research analyst with years of experience in
gathering market intelligence. You're known for your ability to find
relevant and up-to-date market information and present it in a clear,
actionable format.""",
tools=[SearchTool()],
verbose=True
)
# rest of the code ...
@@ -40,6 +53,6 @@ agent = Agent(
## Conclusion
Tools are pivotal in extending the capabilities of CrewAI agents, enabling them to undertake a broad spectrum of tasks and collaborate effectively.
When building solutions with CrewAI, leverage both custom and existing tools to empower your agents and enhance the AI ecosystem. Consider utilizing error handling, caching mechanisms,
and the flexibility of tool arguments to optimize your agents' performance and capabilities.
Tools are pivotal in extending the capabilities of CrewAI agents, enabling them to undertake a broad spectrum of tasks and collaborate effectively.
When building solutions with CrewAI, leverage both custom and existing tools to empower your agents and enhance the AI ecosystem. Consider utilizing error handling, caching mechanisms,
and the flexibility of tool arguments to optimize your agents' performance and capabilities.
description: Detailed guide on managing and creating tasks within the CrewAI framework, reflecting the latest codebase updates.
description: Detailed guide on managing and creating tasks within the CrewAI framework.
icon: list-check
---
## Overview of a Task
In the CrewAI framework, a `Task` is a specific assignment completed by an `Agent`.
They provide all necessary details for execution, such as a description, the agent responsible, required tools, and more, facilitating a wide range of action complexities.
In the CrewAI framework, a `Task` is a specific assignment completed by an `Agent`.
Tasks provide all necessary details for execution, such as a description, the agent responsible, required tools, and more, facilitating a wide range of action complexities.
Tasks within CrewAI can be collaborative, requiring multiple agents to work together. This is managed through the task properties and orchestrated by the Crew's process, enhancing teamwork and efficiency.
### Task Execution Flow
Tasks can be executed in two ways:
- **Sequential**: Tasks are executed in the order they are defined
- **Hierarchical**: Tasks are assigned to agents based on their roles and expertise
The execution flow is defined when creating the crew:
```python Code
crew = Crew(
agents=[agent1, agent2],
tasks=[task1, task2],
process=Process.sequential # or Process.hierarchical
| **Description** | `description` | `str` | A clear, concise statement of what the task entails. |
| **Agent** | `agent` | `Optional[BaseAgent]` | The agent responsible for the task, assigned either directly or by the crew's process. |
| **Expected Output** | `expected_output` | `str` | A detailed description of what the task's completion looks like. |
| **Tools** _(optional)_ | `tools` | `Optional[List[Any]]` | The functions or capabilities the agent can utilize to perform the task. Defaults to an empty list. |
| **Async Execution** _(optional)_ | `async_execution` | `Optional[bool]` | If set, the task executes asynchronously, allowing progression without waiting for completion. Defaults to False. |
| **Context** _(optional)_ | `context` | `Optional[List["Task"]]` | Specifies tasks whose outputs are used as context for this task. |
| **Config** _(optional)_ | `config` | `Optional[Dict[str, Any]]` | Additional configuration details for the agent executing the task, allowing further customization. Defaults to None. |
| **Output JSON** _(optional)_ | `output_json` | `Optional[Type[BaseModel]]` | Outputs a JSON object, requiring an OpenAI client. Only one output format can be set. |
| **Output Pydantic** _(optional)_ | `output_pydantic` | `Optional[Type[BaseModel]]` | Outputs a Pydantic model object, requiring an OpenAI client. Only one output format can be set. |
| **Output File** _(optional)_ | `output_file` | `Optional[str]` | Saves the task output to a file. If used with `Output JSON` or `Output Pydantic`, specifies how the output is saved. |
| **Output** _(optional)_ | `output` | `Optional[TaskOutput]` | An instance of `TaskOutput`, containing the raw, JSON, and Pydantic output plus additional details. |
| **Callback** _(optional)_ | `callback` | `Optional[Any]` | A callable that is executed with the task's output upon completion. |
| **Human Input** _(optional)_ | `human_input` | `Optional[bool]` | Indicates if the task should involve human review at the end, useful for tasks needing human oversight. Defaults to False.|
| **Converter Class** _(optional)_ | `converter_cls` | `Optional[Type[Converter]]` | A converter class used to export structured output. Defaults to None. |
| **Name** _(optional)_ | `name` | `Optional[str]` | A name identifierfor the task. |
| **Agent** _(optional)_ | `agent` | `Optional[BaseAgent]` | The agent responsible for executing the task. |
| **Tools** _(optional)_ | `tools` | `List[BaseTool]` | The tools/resources the agent is limited to use for this task. |
| **Context** _(optional)_ | `context` | `Optional[List["Task"]]` | Other tasks whose outputs will be used as context for this task. |
| **Async Execution** _(optional)_ | `async_execution` | `Optional[bool]` | Whether the task should be executed asynchronously. Defaults to False. |
| **Output File** _(optional)_ | `output_file` | `Optional[str]` | File path for storing the task output. |
| **Output JSON** _(optional)_ | `output_json` | `Optional[Type[BaseModel]]` | A Pydantic model to structure the JSON output. |
| **Output Pydantic** _(optional)_ | `output_pydantic` | `Optional[Type[BaseModel]]` | A Pydantic model for task output. |
| **Callback** _(optional)_ | `callback` | `Optional[Any]` | Function/object to be executed after task completion. |
## Creating a Task
## Creating Tasks
Creating a task involves defining its scope, responsible agent, and any additional attributes for flexibility:
There are two ways to create tasks in CrewAI: using **YAML configuration (recommended)** or defining them **directly in code**.
### YAML Configuration (Recommended)
Using YAML configuration provides a cleaner, more maintainable way to define tasks. We strongly recommend using this approach to define tasks in your CrewAI projects.
After creating your CrewAI project as outlined in the [Installation](/installation) section, navigate to the `src/latest_ai_development/config/tasks.yaml` file and modify the template to match your specific task requirements.
<Note>
Variables in your YAML files (like `{topic}`) will be replaced with values from your inputs when running the crew:
```python Code
crew.kickoff(inputs={'topic': 'AI Agents'})
```
</Note>
Here's an example of how to configure tasks using YAML:
```yaml tasks.yaml
research_task:
description: >
Conduct a thorough research about {topic}
Make sure you find any interesting and relevant information given
the current year is 2024.
expected_output: >
A list with 10 bullet points of the most relevant information about {topic}
agent: researcher
reporting_task:
description: >
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
expected_output: >
A fully fledge reports with the mains topics, each with a full section of information.
Formatted as markdown without '```'
agent: reporting_analyst
output_file: report.md
```
To use this YAML configuration in your code, create a crew class that inherits from `CrewBase`:
```python crew.py
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
verbose=True,
tools=[SerperDevTool()]
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'],
verbose=True
)
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task']
)
@task
def reporting_task(self) -> Task:
return Task(
config=self.tasks_config['reporting_task']
)
@crew
def crew(self) -> Crew:
return Crew(
agents=[
self.researcher(),
self.reporting_analyst()
],
tasks=[
self.research_task(),
self.reporting_task()
],
process=Process.sequential
)
```
<Note>
The names you use in your YAML files (`agents.yaml` and `tasks.yaml`) should match the method names in your Python code.
</Note>
### Direct Code Definition (Alternative)
Alternatively, you can define tasks directly in your code without using YAML configuration:
```python task.py
from crewai import Task
task = Task(
description='Find and summarize the latest and most relevant news on AI',
agent=sales_agent,
expected_output='A bullet list summary of the top 5 most important AI news',
research_task = Task(
description="""
Conduct a thorough research about AI Agents.
Make sure you find any interesting and relevant information given
the current year is 2024.
""",
expected_output="""
A list with 10 bullet points of the most relevant information about AI Agents
""",
agent=researcher
)
reporting_task = Task(
description="""
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
""",
expected_output="""
A fully fledge reports with the mains topics, each with a full section of information.
Formatted as markdown without '```'
""",
agent=reporting_analyst,
output_file="report.md"
)
```
@@ -52,6 +182,8 @@ task = Task(
## Task Output
Understanding task outputs is crucial for building effective AI workflows. CrewAI provides a structured way to handle task results through the `TaskOutput` class, which supports multiple output formats and can be easily passed between tasks.
The output of a task in CrewAI framework is encapsulated within the `TaskOutput` class. This class provides a structured way to access results of a task, including various formats such as raw output, JSON, and Pydantic models.
By default, the `TaskOutput` will only include the `raw` output. A `TaskOutput` will only include the `pydantic` or `json_dict` output if the original `Task` object was configured with `output_pydantic` or `output_json`, respectively.
@@ -112,6 +244,326 @@ if task_output.pydantic:
print(f"Pydantic Output: {task_output.pydantic}")
```
## Task Dependencies and Context
Tasks can depend on the output of other tasks using the `context` attribute. For example:
```python Code
research_task = Task(
description="Research the latest developments in AI",
expected_output="A list of recent AI developments",
agent=researcher
)
analysis_task = Task(
description="Analyze the research findings and identify key trends",
expected_output="Analysis report of AI trends",
agent=analyst,
context=[research_task] # This task will wait for research_task to complete
)
```
## Task Guardrails
Task guardrails provide a way to validate and transform task outputs before they
are passed to the next task. This feature helps ensure data quality and provides
efeedback to agents when their output doesn't meet specific criteria.
### Using Task Guardrails
To add a guardrail to a task, provide a validation function through the `guardrail` parameter:
## Getting Structured Consistent Outputs from Tasks
<Note>
It's also important to note that the output of the final task of a crew becomes the final output of the actual crew itself.
</Note>
### Using `output_pydantic`
The `output_pydantic` property allows you to define a Pydantic model that the task output should conform to. This ensures that the output is not only structured but also validated according to the Pydantic model.
Here’s an example demonstrating how to use output_pydantic:
```python Code
import json
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
class Blog(BaseModel):
title: str
content: str
blog_agent = Agent(
role="Blog Content Generator Agent",
goal="Generate a blog title and content",
backstory="""You are an expert content creator, skilled in crafting engaging and informative blog posts.""",
verbose=False,
allow_delegation=False,
llm="gpt-4o",
)
task1 = Task(
description="""Create a blog title and content on a given topic. Make sure the content is under 200 words.""",
expected_output="A compelling blog title and well-written content.",
agent=blog_agent,
output_pydantic=Blog,
)
# Instantiate your crew with a sequential process
crew = Crew(
agents=[blog_agent],
tasks=[task1],
verbose=True,
process=Process.sequential,
)
result = crew.kickoff()
# Option 1: Accessing Properties Using Dictionary-Style Indexing
print("Accessing Properties - Option 1")
title = result["title"]
content = result["content"]
print("Title:", title)
print("Content:", content)
# Option 2: Accessing Properties Directly from the Pydantic Model
print("Accessing Properties - Option 2")
title = result.pydantic.title
content = result.pydantic.content
print("Title:", title)
print("Content:", content)
# Option 3: Accessing Properties Using the to_dict() Method
print("Accessing Properties - Option 3")
output_dict = result.to_dict()
title = output_dict["title"]
content = output_dict["content"]
print("Title:", title)
print("Content:", content)
# Option 4: Printing the Entire Blog Object
print("Accessing Properties - Option 5")
print("Blog:", result)
```
In this example:
* A Pydantic model Blog is defined with title and content fields.
* The task task1 uses the output_pydantic property to specify that its output should conform to the Blog model.
* After executing the crew, you can access the structured output in multiple ways as shown.
#### Explanation of Accessing the Output
1. Dictionary-Style Indexing: You can directly access the fields using result["field_name"]. This works because the CrewOutput class implements the __getitem__ method.
2. Directly from Pydantic Model: Access the attributes directly from the result.pydantic object.
3. Using to_dict() Method: Convert the output to a dictionary and access the fields.
4. Printing the Entire Object: Simply print the result object to see the structured output.
### Using `output_json`
The `output_json` property allows you to define the expected output in JSON format. This ensures that the task's output is a valid JSON structure that can be easily parsed and used in your application.
Here’s an example demonstrating how to use `output_json`:
```python Code
import json
from crewai import Agent, Crew, Process, Task
from pydantic import BaseModel
# Define the Pydantic model for the blog
class Blog(BaseModel):
title: str
content: str
# Define the agent
blog_agent = Agent(
role="Blog Content Generator Agent",
goal="Generate a blog title and content",
backstory="""You are an expert content creator, skilled in crafting engaging and informative blog posts.""",
verbose=False,
allow_delegation=False,
llm="gpt-4o",
)
# Define the task with output_json set to the Blog model
task1 = Task(
description="""Create a blog title and content on a given topic. Make sure the content is under 200 words.""",
expected_output="A JSON object with 'title' and 'content' fields.",
agent=blog_agent,
output_json=Blog,
)
# Instantiate the crew with a sequential process
crew = Crew(
agents=[blog_agent],
tasks=[task1],
verbose=True,
process=Process.sequential,
)
# Kickoff the crew to execute the task
result = crew.kickoff()
# Option 1: Accessing Properties Using Dictionary-Style Indexing
print("Accessing Properties - Option 1")
title = result["title"]
content = result["content"]
print("Title:", title)
print("Content:", content)
# Option 2: Printing the Entire Blog Object
print("Accessing Properties - Option 2")
print("Blog:", result)
```
In this example:
* A Pydantic model Blog is defined with title and content fields, which is used to specify the structure of the JSON output.
* The task task1 uses the output_json property to indicate that it expects a JSON output conforming to the Blog model.
* After executing the crew, you can access the structured JSON output in two ways as shown.
#### Explanation of Accessing the Output
1. Accessing Properties Using Dictionary-Style Indexing: You can access the fields directly using result["field_name"]. This is possible because the CrewOutput class implements the __getitem__ method, allowing you to treat the output like a dictionary. In this option, we're retrieving the title and content from the result.
2. Printing the Entire Blog Object: By printing result, you get the string representation of the CrewOutput object. Since the __str__ method is implemented to return the JSON output, this will display the entire output as a formatted string representing the Blog object.
---
By using output_pydantic or output_json, you ensure that your tasks produce outputs in a consistent and structured format, making it easier to process and utilize the data within your application or across multiple tasks.
## Integrating Tools with Tasks
Leverage tools from the [CrewAI Toolkit](https://github.com/joaomdmoura/crewai-tools) and [LangChain Tools](https://python.langchain.com/docs/integrations/tools) for enhanced task performance and agent interaction.
@@ -167,16 +619,16 @@ This is useful when you have a task that depends on the output of another task t
# ...
research_ai_task = Task(
description='Find and summarize the latest AI news',
expected_output='A bullet list summary of the top 5 most important AI news',
description="Research the latest developments in AI",
expected_output="A list of recent AI developments",
async_execution=True,
agent=research_agent,
tools=[search_tool]
)
research_ops_task = Task(
description='Find and summarize the latest AI Ops news',
expected_output='A bullet list summary of the top 5 most important AI Ops news',
description="Research the latest developments in AI Ops",
expected_output="A list of recent AI Ops developments",
async_execution=True,
agent=research_agent,
tools=[search_tool]
@@ -184,7 +636,7 @@ research_ops_task = Task(
write_blog_task = Task(
description="Write a full blog post about the importance of AI and its latest news",
expected_output='Full blog post that is 4 paragraphs long',
expected_output="Full blog post that is 4 paragraphs long",
agent=writer_agent,
context=[research_ai_task, research_ops_task]
)
@@ -296,6 +748,114 @@ While creating and executing tasks, certain validation mechanisms are in place t
These validations help in maintaining the consistency and reliability of task executions within the crewAI framework.
## Task Guardrails
Task guardrails provide a powerful way to validate, transform, or filter task outputs before they are passed to the next task. Guardrails are optional functions that execute before the next task starts, allowing you to ensure that task outputs meet specific requirements or formats.
return (False, "Output must be a 10-digit phone number")
```
### Advanced Features
#### Chaining Multiple Validations
```python Code
def chain_validations(*validators):
"""Chain multiple validators together."""
def combined_validator(result):
for validator in validators:
success, data = validator(result)
if not success:
return (False, data)
result = data
return (True, result)
return combined_validator
# Usage
task = Task(
description="Get user contact info",
expected_output="Email and phone",
guardrail=chain_validations(
validate_email_format,
filter_sensitive_info
)
)
```
#### Custom Retry Logic
```python Code
task = Task(
description="Generate data",
expected_output="Valid data",
guardrail=validate_data,
max_retries=5 # Override default retry limit
)
```
## Creating Directories when Saving Files
You can now specify if a task should create directories when saving its output to a file. This is particularly useful for organizing outputs and ensuring that file paths are correctly structured.
@@ -317,7 +877,7 @@ save_output_task = Task(
## Conclusion
Tasks are the driving force behind the actions of agents in CrewAI.
By properly defining tasks and their outcomes, you set the stage for your AI agents to work effectively, either independently or as a collaborative unit.
Equipping tasks with appropriate tools, understanding the execution process, and following robust validation practices are crucial for maximizing CrewAI's potential,
ensuring agents are effectively prepared for their assignments and that tasks are executed as intended.
Tasks are the driving force behind the actions of agents in CrewAI.
By properly defining tasks and their outcomes, you set the stage for your AI agents to work effectively, either independently or as a collaborative unit.
Equipping tasks with appropriate tools, understanding the execution process, and following robust validation practices are crucial for maximizing CrewAI's potential,
ensuring agents are effectively prepared for their assignments and that tasks are executed as intended.
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.",
[Portkey](https://portkey.ai/?utm_source=crewai&utm_medium=crewai&utm_campaign=crewai) is a 2-line upgrade to make your CrewAI agents reliable, cost-efficient, and fast.
Portkey adds 4 core production capabilities to any CrewAI agent:
To build CrewAI Agents with Portkey, you'll need two keys:
- **Portkey API Key**: Sign up on the [Portkey app](https://app.portkey.ai/?utm_source=crewai&utm_medium=crewai&utm_campaign=crewai) and copy your API key
- **Virtual Key**: Virtual Keys securely manage your LLM API keys in one place. Store your LLM provider API keys securely in Portkey's vault
virtual_key="YOUR_VIRTUAL_KEY",# Enter your Virtual key from Portkey
)
)
```
3.**Create and Run Your First Agent:**
```python
fromcrewaiimportAgent,Task,Crew
# Define your agents with roles and goals
coder=Agent(
role='Software developer',
goal='Write clear, concise code on demand',
backstory='An expert coder with a keen eye for software trends.',
llm=gpt_llm
)
# Create tasks for your agents
task1=Task(
description="Define the HTML for making a simple website with heading- Hello World! Portkey is working!",
expected_output="A clear and concise HTML code",
agent=coder
)
# Instantiate your crew
crew=Crew(
agents=[coder],
tasks=[task1],
)
result=crew.kickoff()
print(result)
```
## Key Features
| Feature | Description |
|---------|-------------|
| 🌐 Multi-LLM Support | Access OpenAI, Anthropic, Gemini, Azure, and 250+ providers through a unified interface |
| 🛡️ Production Reliability | Implement retries, timeouts, load balancing, and fallbacks |
| 📊 Advanced Observability | Track 40+ metrics including costs, tokens, latency, and custom metadata |
| 🔍 Comprehensive Logging | Debug with detailed execution traces and function call logs |
| 🚧 Security Controls | Set budget limits and implement role-based access control |
| 🔄 Performance Analytics | Capture and analyze feedback for continuous improvement |
| 💾 Intelligent Caching | Reduce costs and latency with semantic or simple caching |
## Production Features with Portkey Configs
All features mentioned below are through Portkey's Config system. Portkey's Config system allows you to define routing strategies using simple JSON objects in your LLM API calls. You can create and manage Configs directly in your code or through the Portkey Dashboard. Each Config has a unique ID for easy reference.
Access various LLMs like Anthropic, Gemini, Mistral, Azure OpenAI, and more with minimal code changes. Switch between providers or use them together seamlessly. [Learn more about Universal API](https://portkey.ai/docs/product/ai-gateway/universal-api)
Easily switch between different LLM providers:
```python
# Anthropic Configuration
anthropic_llm=LLM(
model="claude-3-5-sonnet-latest",
base_url=PORTKEY_GATEWAY_URL,
api_key="dummy",
extra_headers=createHeaders(
api_key="YOUR_PORTKEY_API_KEY",
virtual_key="YOUR_ANTHROPIC_VIRTUAL_KEY",#You don't need provider when using Virtual keys
trace_id="anthropic_agent"
)
)
# Azure OpenAI Configuration
azure_llm=LLM(
model="gpt-4",
base_url=PORTKEY_GATEWAY_URL,
api_key="dummy",
extra_headers=createHeaders(
api_key="YOUR_PORTKEY_API_KEY",
virtual_key="YOUR_AZURE_VIRTUAL_KEY",#You don't need provider when using Virtual keys
trace_id="azure_agent"
)
)
```
### 2. Caching
Improve response times and reduce costs with two powerful caching modes:
- **Simple Cache**: Perfect for exact matches
- **Semantic Cache**: Matches responses for requests that are semantically similar
[Learn more about Caching](https://portkey.ai/docs/product/ai-gateway/cache-simple-and-semantic)
```py
config={
"cache":{
"mode":"semantic",# or "simple" for exact matching
[Learn more about Reliability Features](https://portkey.ai/docs/product/ai-gateway/)
### 4. Metrics
Agent runs are complex. Portkey automatically logs **40+ comprehensive metrics** for your AI agents, including cost, tokens used, latency, etc. Whether you need a broad overview or granular insights into your agent runs, Portkey's customizable filters provide the metrics you need.
Logs are essential for understanding agent behavior, diagnosing issues, and improving performance. They provide a detailed record of agent activities and tool use, which is crucial for debugging and optimizing processes.
Access a dedicated section to view records of agent executions, including parameters, outcomes, function calls, and errors. Filter logs based on multiple parameters such as trace ID, model, tokens used, and metadata.
description: Learn how to use before and after kickoff hooks in CrewAI
---
CrewAI provides hooks that allow you to execute code before and after a crew's kickoff. These hooks are useful for preprocessing inputs or post-processing results.
## Before Kickoff Hook
The before kickoff hook is executed before the crew starts its tasks. It receives the input dictionary and can modify it before passing it to the crew. You can use this hook to set up your environment, load necessary data, or preprocess your inputs. This is useful in scenarios where the input data might need enrichment or validation before being processed by the crew.
Here's an example of defining a before kickoff function in your `crew.py`:
```python
from crewai import CrewBase, before_kickoff
@CrewBase
class MyCrew:
@before_kickoff
def prepare_data(self, inputs):
# Preprocess or modify inputs
inputs['processed'] = True
return inputs
#...
```
In this example, the prepare_data function modifies the inputs by adding a new key-value pair indicating that the inputs have been processed.
## After Kickoff Hook
The after kickoff hook is executed after the crew has completed its tasks. It receives the result object, which contains the outputs of the crew's execution. This hook is ideal for post-processing results, such as logging, data transformation, or further analysis.
Here's how you can define an after kickoff function in your `crew.py`:
```python
from crewai import CrewBase, after_kickoff
@CrewBase
class MyCrew:
@after_kickoff
def log_results(self, result):
# Log or modify the results
print("Crew execution completed with result:", result)
return result
# ...
```
In the `log_results` function, the results of the crew execution are simply printed out. You can extend this to perform more complex operations such as sending notifications or integrating with other services.
## Utilizing Both Hooks
Both hooks can be used together to provide a comprehensive setup and teardown process for your crew's execution. They are particularly useful in maintaining clean code architecture by separating concerns and enhancing the modularity of your CrewAI implementations.
## Conclusion
Before and after kickoff hooks in CrewAI offer powerful ways to interact with the lifecycle of a crew's execution. By understanding and utilizing these hooks, you can greatly enhance the robustness and flexibility of your AI agents.
For a complete and up-to-date list of supported providers, please refer to the [LiteLLM Providers documentation](https://docs.litellm.ai/docs/providers).
@@ -125,10 +126,10 @@ You can connect to OpenAI-compatible LLMs using either environment variables or
</Tab>
<Tab title="Using LLM Class Attributes">
<CodeGroup>
```python Code
llm = LLM(
model="custom-model-name",
api_key="your-api-key",
```python Code
llm = LLM(
model="custom-model-name",
api_key="your-api-key",
base_url="https://api.your-provider.com/v1"
)
agent = Agent(llm=llm, ...)
@@ -179,4 +180,4 @@ This is particularly useful when working with OpenAI-compatible APIs or when you
## Conclusion
By leveraging LiteLLM, CrewAI offers seamless integration with a vast array of LLMs. This flexibility allows you to choose the most suitable model for your specific needs, whether you prioritize performance, cost-efficiency, or local deployment. Remember to consult the [LiteLLM documentation](https://docs.litellm.ai/docs/) for the most up-to-date information on supported models and configuration options.
By leveraging LiteLLM, CrewAI offers seamless integration with a vast array of LLMs. This flexibility allows you to choose the most suitable model for your specific needs, whether you prioritize performance, cost-efficiency, or local deployment. Remember to consult the [LiteLLM documentation](https://docs.litellm.ai/docs/) for the most up-to-date information on supported models and configuration options.
description: Learn how to enable and use multimodal capabilities in your agents for processing images and other non-text content within the CrewAI framework.
icon: image
---
# Using Multimodal Agents
CrewAI supports multimodal agents that can process both text and non-text content like images. This guide will show you how to enable and use multimodal capabilities in your agents.
## Enabling Multimodal Capabilities
To create a multimodal agent, simply set the `multimodal` parameter to `True` when initializing your agent:
```python
from crewai import Agent
agent = Agent(
role="Image Analyst",
goal="Analyze and extract insights from images",
backstory="An expert in visual content interpretation with years of experience in image analysis",
multimodal=True # This enables multimodal capabilities
)
```
When you set `multimodal=True`, the agent is automatically configured with the necessary tools for handling non-text content, including the `AddImageTool`.
## Working with Images
The multimodal agent comes pre-configured with the `AddImageTool`, which allows it to process images. You don't need to manually add this tool - it's automatically included when you enable multimodal capabilities.
Here's a complete example showing how to use a multimodal agent to analyze an image:
```python
from crewai import Agent, Task, Crew
# Create a multimodal agent
image_analyst = Agent(
role="Product Analyst",
goal="Analyze product images and provide detailed descriptions",
backstory="Expert in visual product analysis with deep knowledge of design and features",
multimodal=True
)
# Create a task for image analysis
task = Task(
description="Analyze the product image at https://example.com/product.jpg and provide a detailed description",
agent=image_analyst
)
# Create and run the crew
crew = Crew(
agents=[image_analyst],
tasks=[task]
)
result = crew.kickoff()
```
### Advanced Usage with Context
You can provide additional context or specific questions about the image when creating tasks for multimodal agents. The task description can include specific aspects you want the agent to focus on:
```python
from crewai import Agent, Task, Crew
# Create a multimodal agent for detailed analysis
expert_analyst = Agent(
role="Visual Quality Inspector",
goal="Perform detailed quality analysis of product images",
backstory="Senior quality control expert with expertise in visual inspection",
multimodal=True # AddImageTool is automatically included
)
# Create a task with specific analysis requirements
inspection_task = Task(
description="""
Analyze the product image at https://example.com/product.jpg with focus on:
1. Quality of materials
2. Manufacturing defects
3. Compliance with standards
Provide a detailed report highlighting any issues found.
""",
agent=expert_analyst
)
# Create and run the crew
crew = Crew(
agents=[expert_analyst],
tasks=[inspection_task]
)
result = crew.kickoff()
```
### Tool Details
When working with multimodal agents, the `AddImageTool` is automatically configured with the following schema:
```python
class AddImageToolSchema:
image_url: str # Required: The URL or path of the image to process
action: Optional[str] = None # Optional: Additional context or specific questions about the image
```
The multimodal agent will automatically handle the image processing through its built-in tools, allowing it to:
- Access images via URLs or local file paths
- Process image content with optional context or specific questions
- Provide analysis and insights based on the visual information and task requirements
## Best Practices
When working with multimodal agents, keep these best practices in mind:
1. **Image Access**
- Ensure your images are accessible via URLs that the agent can reach
- For local images, consider hosting them temporarily or using absolute file paths
- Verify that image URLs are valid and accessible before running tasks
2. **Task Description**
- Be specific about what aspects of the image you want the agent to analyze
- Include clear questions or requirements in the task description
- Consider using the optional `action` parameter for focused analysis
3. **Resource Management**
- Image processing may require more computational resources than text-only tasks
- Some language models may require base64 encoding for image data
- Consider batch processing for multiple images to optimize performance
4. **Environment Setup**
- Verify that your environment has the necessary dependencies for image processing
- Ensure your language model supports multimodal capabilities
- Test with small images first to validate your setup
5. **Error Handling**
- Implement proper error handling for image loading failures
- Have fallback strategies for when image processing fails
- Monitor and log image processing operations for debugging
description: Quickly start monitoring your Agents in just a single line of code with OpenTelemetry.
icon: magnifying-glass-chart
---
# OpenLIT Overview
[OpenLIT](https://github.com/openlit/openlit?src=crewai-docs) is an open-source tool that makes it simple to monitor the performance of AI agents, LLMs, VectorDBs, and GPUs with just **one** line of code.
It provides OpenTelemetry-native tracing and metrics to track important parameters like cost, latency, interactions and task sequences.
This setup enables you to track hyperparameters and monitor for performance issues, helping you find ways to enhance and fine-tune your agents over time.
<Frame caption="OpenLIT Dashboard">
<img src="/images/openlit1.png" alt="Overview Agent usage including cost and tokens" />
<img src="/images/openlit2.png" alt="Overview of agent otel traces and metrics" />
<img src="/images/openlit3.png" alt="Overview of agent traces in details" />
</Frame>
### Features
- **Analytics Dashboard**: Monitor your Agents health and performance with detailed dashboards that track metrics, costs, and user interactions.
- **OpenTelemetry-native Observability SDK**: Vendor-neutral SDKs to send traces and metrics to your existing observability tools like Grafana, DataDog and more.
- **Cost Tracking for Custom and Fine-Tuned Models**: Tailor cost estimations for specific models using custom pricing files for precise budgeting.
- **Exceptions Monitoring Dashboard**: Quickly spot and resolve issues by tracking common exceptions and errors with a monitoring dashboard.
- **Compliance and Security**: Detect potential threats such as profanity and PII leaks.
goal="Conduct thorough research and analysis on AI and AI agents",
backstory="You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.",
allow_delegation=False,
llm='command-r'
)
# Define your task
task = Task(
description="Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.",
expected_output="5 bullet points, each with a paragraph and accompanying notes.",
)
# Define the manager agent
manager = Agent(
role="Project Manager",
goal="Efficiently manage the crew and ensure high-quality task completion",
backstory="You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.",
allow_delegation=True,
llm='command-r'
)
# Instantiate your crew with a custom manager
crew = Crew(
agents=[researcher],
tasks=[task],
manager_agent=manager,
process=Process.hierarchical,
)
# Start the crew's work
result = crew.kickoff()
print(result)
```
</Tab>
<Tab title="Setup using Environment Variables">
Add the following two lines to your application code:
```python
import openlit
openlit.init()
```
Run the following command to configure the OTEL export endpoint:
goal="Analyze data and provide insights using Python",
backstory="You are an experienced data analyst with strong Python skills.",
allow_code_execution=True,
llm="command-r"
)
# Create a task that requires code execution
data_analysis_task = Task(
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
agent=coding_agent,
expected_output="5 bullet points, each with a paragraph and accompanying notes.",
)
# Create a crew and add the task
analysis_crew = Crew(
agents=[coding_agent],
tasks=[data_analysis_task]
)
# Async function to kickoff the crew asynchronously
async def async_crew_execution():
result = await analysis_crew.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
print("Crew Result:", result)
# Run the async function
asyncio.run(async_crew_execution())
```
</Tab>
</Tabs>
Refer to OpenLIT [Python SDK repository](https://github.com/openlit/openlit/tree/main/sdk/python) for more advanced configurations and use cases.
</Step>
<Step title="Visualize and Analyze">
With the Agent Observability data now being collected and sent to OpenLIT, the next step is to visualize and analyze this data to get insights into your Agent's performance, behavior, and identify areas of improvement.
Just head over to OpenLIT at `127.0.0.1:3000` on your browser to start exploring. You can login using the default credentials
- **Email**: `user@openlit.io`
- **Password**: `openlituser`
<Frame caption="OpenLIT Dashboard">
<img src="/images/openlit1.png" alt="Overview Agent usage including cost and tokens" />
<img src="/images/openlit2.png" alt="Overview of agent otel traces and metrics" />
You can now start developing your crew by editing the files in the `src/my_project` folder.
The `main.py` file is the entry point of the project, the `crew.py` file is where you define your crew, the `agents.yaml` file is where you define your agents,
and the `tasks.yaml` file is where you define your tasks.
This creates a new project with the following structure:
<Frame>
```
my_project/
├── .gitignore
├── pyproject.toml
├── README.md
├── .env
└── src/
└── my_project/
├── __init__.py
├── main.py
├── crew.py
├── tools/
│ ├── custom_tool.py
│ └── __init__.py
└── config/
├── agents.yaml
└── tasks.yaml
```
</Frame>
</Step>
<Step title="Customize your project">
To customize your project, you can:
- Modify `src/my_project/config/agents.yaml` to define your agents.
- Modify `src/my_project/config/tasks.yaml` to define your tasks.
- Modify `src/my_project/crew.py` to add your own logic, tools, and specific arguments.
- Modify `src/my_project/main.py` to add custom inputs for your agents and tasks.
- Add your environment variables into the `.env` file.
<Step title="Customize Your Project">
Your project will contain these essential files:
| File | Purpose |
| --- | --- |
| `agents.yaml` | Define your AI agents and their roles |
| `tasks.yaml` | Set up agent tasks and workflows |
| `.env` | Store API keys and environment variables |
| `main.py` | Project entry point and execution flow |
| `crew.py` | Crew orchestration and coordination |
| `tools/` | Directory for custom agent tools |
<Tip>
Start by editing `agents.yaml` and `tasks.yaml` to define your crew's behavior.
Keep sensitive information like API keys in `.env`.
</Tip>
</Step>
</Steps>
## Next steps
## Next Steps
Now that you have installed `crewai` and `crewai-tools`, you're ready to spin up your first crew!
- 👨💻 Build your first agent with CrewAI by following the [Quickstart](/quickstart) guide.
- 💬 Join the [Community](https://community.crewai.com) to get help and share your feedback.
<CardGroup cols={2}>
<Card
title="Build Your First Agent"
icon="code"
href="/quickstart"
>
Follow our quickstart guide to create your first CrewAI agent and get hands-on experience.
</Card>
<Card
title="Join the Community"
icon="comments"
href="https://community.crewai.com"
>
Connect with other developers, get help, and share your CrewAI experiences.
Think of it as assembling your dream team - each member (agent) brings unique skills and expertise, collaborating seamlessly to achieve your objectives.
## Why CrewAI?
- 🤼♀️ **Role-Playing Agents**: Agents can take on different roles and personas to better understand and interact with complex systems.
- 🤖 **Autonomous Decision Making**: Agents can make decisions autonomously based on the given context and available tools.
- 🤝 **Seamless Collaboration**: Agents can work together seamlessly, sharing information and resources to achieve common goals.
- 🧠 **Complex Task Tackling**: CrewAI is designed to tackle complex tasks, such as multi-step workflows, decision making, and problem solving.
## How CrewAI Works
# Get Started with CrewAI
<Note>
Just like a company has departments (Sales, Engineering, Marketing) working together under leadership to achieve business goals, CrewAI helps you create an organization of AI agents with specialized roles collaborating to accomplish complex tasks.
| **Crew** | The top-level organization | • Manages AI agent teams<br/>• Oversees workflows<br/>• Ensures collaboration<br/>• Delivers outcomes |
| **AI Agents** | Specialized team members | • Have specific roles (researcher, writer)<br/>• Use designated tools<br/>• Can delegate tasks<br/>• Make autonomous decisions |
| **Tasks** | Individual assignments | • Have clear objectives<br/>• Use specific tools<br/>• Feed into larger process<br/>• Produce actionable results |
### How It All Works Together
1. The **Crew** organizes the overall operation
2. **AI Agents** work on their specialized tasks
3. The **Process** ensures smooth collaboration
4. **Tasks** get completed to achieve the goal
## Key Features
<CardGroup cols={2}>
<Card title="Role-Based Agents" icon="users">
Create specialized agents with defined roles, expertise, and goals - from researchers to analysts to writers
Let's create a simple crew that will help us `research` and `report` on the `latest AI developments` for a given topic or subject.
Before we proceed, make sure you have `crewai` and `crewai-tools` installed.
Before we proceed, make sure you have `crewai` and `crewai-tools` installed.
If you haven't installed them yet, you can do so by following the [installation guide](/installation).
Follow the steps below to get crewing! 🚣♂️
@@ -23,7 +23,7 @@ Follow the steps below to get crewing! 🚣♂️
```
</CodeGroup>
</Step>
<Step title="Modify your `agents.yaml` file">
<Step title="Modify your `agents.yaml` file">
<Tip>
You can also modify the agents as needed to fit your use case or copy and paste as is to your project.
Any variable interpolated in your `agents.yaml` and `tasks.yaml` files like `{topic}` will be replaced by the value of the variable in the `main.py` file.
@@ -39,7 +39,7 @@ Follow the steps below to get crewing! 🚣♂️
You're a seasoned researcher with a knack for uncovering the latest
developments in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
reporting_analyst:
role: >
{topic} Reporting Analyst
@@ -51,7 +51,7 @@ Follow the steps below to get crewing! 🚣♂️
it easy for others to understand and act on the information you provide.
```
</Step>
<Step title="Modify your `tasks.yaml` file">
<Step title="Modify your `tasks.yaml` file">
```yaml tasks.yaml
# src/latest_ai_development/config/tasks.yaml
research_task:
@@ -73,8 +73,8 @@ Follow the steps below to get crewing! 🚣♂️
agent: reporting_analyst
output_file: report.md
```
</Step>
<Step title="Modify your `crew.py` file">
</Step>
<Step title="Modify your `crew.py` file">
```python crew.py
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
@@ -121,10 +121,34 @@ Follow the steps below to get crewing! 🚣♂️
tasks=self.tasks, # Automatically created by the @task decorator
process=Process.sequential,
verbose=True,
)
)
```
</Step>
<Step title="Feel free to pass custom inputs to your crew">
<Step title="[Optional] Add before and after crew functions">
```python crew.py
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task, before_kickoff, after_kickoff
from crewai_tools import SerperDevTool
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
@before_kickoff
def before_kickoff_function(self, inputs):
print(f"Before kickoff function with inputs: {inputs}")
return inputs # You can return the inputs or modify them as needed
@after_kickoff
def after_kickoff_function(self, result):
print(f"After kickoff function with result: {result}")
return result # You can return the result or modify it as needed
# ... remaining code
```
</Step>
<Step title="Feel free to pass custom inputs to your crew">
For example, you can pass the `topic` input to your crew to customize the research and reporting.
```python main.py
#!/usr/bin/env python
@@ -237,14 +261,14 @@ Follow the steps below to get crewing! 🚣♂️
### Note on Consistency in Naming
The names you use in your YAML files (`agents.yaml` and `tasks.yaml`) should match the method names in your Python code.
For example, you can reference the agent for specific tasks from `tasks.yaml` file.
For example, you can reference the agent for specific tasks from `tasks.yaml` file.
This naming consistency allows CrewAI to automatically link your configurations with your code; otherwise, your task won't recognize the reference properly.
#### Example References
<Tip>
Note how we use the same name for the agent in the `agents.yaml` (`email_summarizer`) file as the method name in the `crew.py` (`email_summarizer`) file.
</Tip>
</Tip>
```yaml agents.yaml
email_summarizer:
@@ -281,6 +305,8 @@ Use the annotations to properly reference the agent and task in the `crew.py` fi
In addition to the [sequential process](../how-to/sequential-process), you can use the [hierarchical process](../how-to/hierarchical-process),
which automatically assigns a manager to the defined crew to properly coordinate the planning and execution of tasks through delegation and validation of results.
which automatically assigns a manager to the defined crew to properly coordinate the planning and execution of tasks through delegation and validation of results.
You can learn more about the core concepts [here](/concepts).
</Tip>
@@ -323,11 +349,28 @@ Replace `<task_id>` with the ID of the task you want to replay.
If you need to reset the memory of your crew before running it again, you can do so by calling the reset memory feature:
```shell
crewai reset-memory
crewai reset-memories --all
```
This will clear the crew's memory, allowing for a fresh start.
## Deploying Your Project
The easiest way to deploy your crew is through [CrewAI Enterprise](http://app.crewai.com/), where you can deploy your crew in a few clicks.
The easiest way to deploy your crew is through CrewAI Enterprise, where you can deploy your crew in a few clicks.
<CardGroup cols={2}>
<Card
title="Deploy on Enterprise"
icon="rocket"
href="http://app.crewai.com"
>
Get started with CrewAI Enterprise and deploy your crew in a production environment with just a few clicks.
</Card>
<Card
title="Join the Community"
icon="comments"
href="https://community.crewai.com"
>
Join our open source community to discuss ideas, share your projects, and connect with other CrewAI developers.
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."
@@ -4,7 +4,7 @@ Welcome to the {{crew_name}} Crew project, powered by [crewAI](https://crewai.co
## Installation
Ensure you have Python >=3.10 <=3.13 installed on your system. This project uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
Ensure you have Python >=3.10 <3.13 installed on your system. This project uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
@@ -4,7 +4,7 @@ Welcome to the {{crew_name}} Crew project, powered by [crewAI](https://crewai.co
## Installation
Ensure you have Python >=3.10 <=3.13 installed on your system. This project uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
Ensure you have Python >=3.10 <3.13 installed on your system. This project uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
Welcome to the {{crew_name}} Crew project, powered by [crewAI](https://crewai.com). This template is designed to help you set up a multi-agent AI system with ease, leveraging the powerful and flexible framework provided by crewAI. Our goal is to enable your agents to collaborate effectively on complex tasks, maximizing their collective intelligence and capabilities.
## Installation
Ensure you have Python >=3.10 <=3.13 installed on your system. This project uses [Poetry](https://python-poetry.org/) for dependency management and package handling, offering a seamless setup and execution experience.
First, if you haven't already, install Poetry:
```bash
pip install poetry
```
Next, navigate to your project directory and install the dependencies:
1. First lock the dependencies and then install them:
```bash
crewai install
```
### Customizing
**Add your `OPENAI_API_KEY` into the `.env` file**
- Modify `src/{{folder_name}}/config/agents.yaml` to define your agents
- Modify `src/{{folder_name}}/config/tasks.yaml` to define your tasks
- Modify `src/{{folder_name}}/crew.py` to add your own logic, tools and specific args
- Modify `src/{{folder_name}}/main.py` to add custom inputs for your agents and tasks
## Running the Project
To kickstart your crew of AI agents and begin task execution, run this from the root folder of your project:
```bash
crewai run
```
This command initializes the {{name}} Crew, assembling the agents and assigning them tasks as defined in your configuration.
This example, unmodified, will run the create a `report.md` file with the output of a research on LLMs in the root folder.
## Understanding Your Crew
The {{name}} Crew is composed of multiple AI agents, each with unique roles, goals, and tools. These agents collaborate on a series of tasks, defined in `config/tasks.yaml`, leveraging their collective skills to achieve complex objectives. The `config/agents.yaml` file outlines the capabilities and configurations of each agent in your crew.
## Support
For support, questions, or feedback regarding the {{crew_name}} Crew or crewAI.
Welcome to the {{crew_name}} Crew project, powered by [crewAI](https://crewai.com). This template is designed to help you set up a multi-agent AI system with ease, leveraging the powerful and flexible framework provided by crewAI. Our goal is to enable your agents to collaborate effectively on complex tasks, maximizing their collective intelligence and capabilities.
## Installation
Ensure you have Python >=3.10 <=3.13 installed on your system. This project uses [Poetry](https://python-poetry.org/) for dependency management and package handling, offering a seamless setup and execution experience.
First, if you haven't already, install Poetry:
```bash
pip install poetry
```
Next, navigate to your project directory and install the dependencies:
1. First lock the dependencies and then install them:
```bash
crewai install
```
### Customizing
**Add your `OPENAI_API_KEY` into the `.env` file**
- Modify `src/{{folder_name}}/config/agents.yaml` to define your agents
- Modify `src/{{folder_name}}/config/tasks.yaml` to define your tasks
- Modify `src/{{folder_name}}/crew.py` to add your own logic, tools and specific args
- Modify `src/{{folder_name}}/main.py` to add custom inputs for your agents and tasks
## Running the Project
To kickstart your crew of AI agents and begin task execution, run this from the root folder of your project:
```bash
crewai run
```
This command initializes the {{name}} Crew, assembling the agents and assigning them tasks as defined in your configuration.
This example, unmodified, will run the create a `report.md` file with the output of a research on LLMs in the root folder.
## Understanding Your Crew
The {{name}} Crew is composed of multiple AI agents, each with unique roles, goals, and tools. These agents collaborate on a series of tasks, defined in `config/tasks.yaml`, leveraging their collective skills to achieve complex objectives. The `config/agents.yaml` file outlines the capabilities and configurations of each agent in your crew.
## Support
For support, questions, or feedback regarding the {{crew_name}} Crew or crewAI.
Classify the email: {email} as urgent or normal from a score of 1 to 10, where 1 is not urgent and 10 is urgent. Return the urgency score only.`
backstory:>
You are a highly efficient and experienced email classifier, trained to quickly assess and classify emails. Your ability to remain calm under pressure and provide concise, actionable responses has made you an invaluable asset in managing normal situations and maintaining smooth operations.
Process normal emails and create an email to respond to the sender.
backstory:>
You are a highly efficient and experienced normal email handler, trained to quickly assess and respond to normal communications. Your ability to remain calm under pressure and provide concise, actionable responses has made you an invaluable asset in managing normal situations and maintaining smooth operations.
Process urgent emails and create an email to respond to the sender.
backstory:>
You are a highly efficient and experienced urgent email handler, trained to quickly assess and respond to time-sensitive communications. Your ability to remain calm under pressure and provide concise, actionable responses has made you an invaluable asset in managing critical situations and maintaining smooth operations.
I'm reaching out regarding our upcoming marketing campaign that requires your immediate attention and swift action. We're facing a critical deadline, and our success hinges on our ability to mobilize quickly.
Key points:
Campaign launch: 48 hours from now
Target audience: 250,000 potential customers
Expected ROI: 35% increase in Q3 sales
What we need from you NOW:
Final approval on creative assets (due in 3 hours)
Confirmation of media placements (due by end of day)
Last-minute budget allocation for paid social media push
Our competitors are poised to launch similar campaigns, and we must act fast to maintain our market advantage. Delays could result in significant lost opportunities and potential revenue.
Please prioritize this campaign above all other tasks. I'll be available for the next 24 hours to address any concerns or roadblocks.
Let's make this happen!
[Your Name]
Marketing Director
P.S. I'll be scheduling an emergency team meeting in 1 hour to discuss our action plan. Attendance is mandatory.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.