From 18a2722e4dab93eda360e4024def9183add563d8 Mon Sep 17 00:00:00 2001 From: "Rip&Tear (aider)" <84775494+theCyberTech@users.noreply.github.com> Date: Wed, 4 Sep 2024 18:26:12 +0800 Subject: [PATCH 1/8] feat: Improve documentation for Conditional Tasks in crewAI --- docs/how-to/Conditional-Tasks.md | 91 ++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 33 deletions(-) diff --git a/docs/how-to/Conditional-Tasks.md b/docs/how-to/Conditional-Tasks.md index 76be82b1a..4f0bd7598 100644 --- a/docs/how-to/Conditional-Tasks.md +++ b/docs/how-to/Conditional-Tasks.md @@ -1,87 +1,112 @@ --- title: Conditional Tasks -description: Learn how to use conditional tasks in a crewAI kickoff +description: Learn how to use conditional tasks in a crewAI workflow --- +# Conditional Tasks in crewAI + ## Introduction -Conditional Tasks in crewAI allow for dynamic workflow adaptation based on the outcomes of previous tasks. This powerful feature enables crews to make decisions and execute tasks selectively, enhancing the flexibility and efficiency of your AI-driven processes. +Conditional Tasks in crewAI enable dynamic workflow adaptation based on the outcomes of previous tasks. This powerful feature allows crews to make decisions and execute tasks selectively, enhancing the flexibility and efficiency of your AI-driven processes. + +## Key Concepts + +1. **ConditionalTask**: A special type of task that executes only if a specified condition is met. +2. **Condition Function**: A custom function that determines whether the conditional task should be executed. +3. **Task Output**: The result of a previous task, which can be used to make decisions for conditional tasks. + +## How It Works + +1. Define a condition function that takes a `TaskOutput` as input and returns a boolean. +2. Create a `ConditionalTask` with the condition function. +3. Add the conditional task to your crew's workflow. +4. The crew will evaluate the condition and execute the task only if the condition is met. ## Example Usage +Here's a step-by-step example of how to implement conditional tasks in your crewAI workflow: + ```python from typing import List from pydantic import BaseModel -from crewai import Agent, Crew +from crewai import Agent, Crew, Task from crewai.tasks.conditional_task import ConditionalTask from crewai.tasks.task_output import TaskOutput -from crewai.task import Task from crewai_tools import SerperDevTool -# Define a condition function for the conditional task -# if false task will be skipped, true, then execute task +# 1. Define the condition function def is_data_missing(output: TaskOutput) -> bool: - return len(output.pydantic.events) < 10 # this will skip this task + return len(output.pydantic.events) < 10 -# Define the agents +# 2. Define the output model +class EventOutput(BaseModel): + events: List[str] + +# 3. Create agents data_fetcher_agent = Agent( role="Data Fetcher", goal="Fetch data online using Serper tool", - backstory="Backstory 1", + backstory="Expert in retrieving online information", verbose=True, tools=[SerperDevTool()], ) data_processor_agent = Agent( role="Data Processor", - goal="Process fetched data", - backstory="Backstory 2", + goal="Process and augment fetched data", + backstory="Specialist in data analysis and enrichment", verbose=True, ) summary_generator_agent = Agent( role="Summary Generator", - goal="Generate summary from fetched data", - backstory="Backstory 3", + goal="Generate concise summaries from processed data", + backstory="Experienced in creating informative summaries", verbose=True, ) -class EventOutput(BaseModel): - events: List[str] - -task1 = Task( +# 4. Define tasks +initial_fetch_task = Task( description="Fetch data about events in San Francisco using Serper tool", - expected_output="List of 10 things to do in SF this week", + expected_output="List of events in SF this week", agent=data_fetcher_agent, output_pydantic=EventOutput, ) -conditional_task = ConditionalTask( - description=""" - Check if data is missing. If we have less than 10 events, - fetch more events using Serper tool so that - we have a total of 10 events in SF this week.. - """, - expected_output="List of 10 Things to do in SF this week", +conditional_fetch_task = ConditionalTask( + description="Fetch additional events if the initial list is incomplete", + expected_output="Complete list of 10 events in SF this week", condition=is_data_missing, agent=data_processor_agent, ) -task3 = Task( - description="Generate summary of events in San Francisco from fetched data", - expected_output="summary_generated", +summary_task = Task( + description="Generate a summary of events in San Francisco from the fetched data", + expected_output="Concise summary of SF events", agent=summary_generator_agent, ) -# Create a crew with the tasks +# 5. Create and run the crew crew = Crew( agents=[data_fetcher_agent, data_processor_agent, summary_generator_agent], - tasks=[task1, conditional_task, task3], + tasks=[initial_fetch_task, conditional_fetch_task, summary_task], verbose=True, planning=True # Enable planning feature ) -# Run the crew result = crew.kickoff() -print("results", result) -``` \ No newline at end of file +print("Final Result:", result) +``` + +## Best Practices + +1. **Clear Conditions**: Ensure your condition functions are clear and specific. +2. **Error Handling**: Implement proper error handling in your condition functions. +3. **Task Dependencies**: Consider the dependencies between tasks when using conditional tasks. +4. **Testing**: Thoroughly test your conditional workflows with various scenarios. + +## Conclusion + +Conditional Tasks in crewAI provide a powerful way to create dynamic and adaptive AI workflows. By leveraging this feature, you can build more intelligent and efficient systems that respond to changing conditions and data. + +For more advanced usage and additional features, refer to the crewAI documentation or reach out to the community for support. From b955416458b101c5afcbc7eb3be988989db7e508 Mon Sep 17 00:00:00 2001 From: "Rip&Tear (aider)" <84775494+theCyberTech@users.noreply.github.com> Date: Wed, 4 Sep 2024 18:31:09 +0800 Subject: [PATCH 2/8] docs: Improve "Creating and Utilizing Tools in crewAI" documentation --- docs/how-to/Create-Custom-Tools.md | 141 +++++++++++++++++++++++------ 1 file changed, 115 insertions(+), 26 deletions(-) diff --git a/docs/how-to/Create-Custom-Tools.md b/docs/how-to/Create-Custom-Tools.md index 7dc1e8f07..0abdcd03d 100644 --- a/docs/how-to/Create-Custom-Tools.md +++ b/docs/how-to/Create-Custom-Tools.md @@ -1,12 +1,26 @@ --- title: Creating and Utilizing Tools in crewAI -description: Comprehensive guide on crafting, using, and managing custom tools within the crewAI framework, including new functionalities and error handling. +description: A comprehensive guide on crafting, using, and managing custom tools within the crewAI framework, including advanced functionalities and best practices. --- -## Creating and Utilizing Tools in crewAI -This guide provides detailed instructions on creating custom tools for the crewAI framework and how to efficiently manage and utilize these tools, incorporating the latest functionalities such as tool delegation, error handling, and dynamic tool calling. It also highlights the importance of collaboration tools, enabling agents to perform a wide range of actions. +# Creating and Utilizing Tools in crewAI -### Prerequisites +This guide provides detailed instructions on creating custom tools for the crewAI framework, efficiently managing and utilizing these tools, and incorporating advanced functionalities. By mastering tool creation and management, you can significantly enhance the capabilities of your AI agents and improve overall system performance. + +## Table of Contents + +1. [Prerequisites](#prerequisites) +2. [Creating Custom Tools](#creating-custom-tools) + - [Subclassing `BaseTool`](#subclassing-basetool) + - [Using the `tool` Decorator](#using-the-tool-decorator) +3. [Advanced Tool Features](#advanced-tool-features) + - [Implementing Caching](#implementing-caching) + - [Error Handling](#error-handling) + - [Dynamic Tool Calling](#dynamic-tool-calling) +4. [Best Practices](#best-practices) +5. [Conclusion](#conclusion) + +## Prerequisites Before creating your own tools, ensure you have the crewAI extra tools package installed: @@ -14,51 +28,126 @@ Before creating your own tools, ensure you have the crewAI extra tools package i pip install 'crewai[tools]' ``` +## Creating Custom Tools + ### Subclassing `BaseTool` -To create a personalized tool, inherit from `BaseTool` and define the necessary attributes and the `_run` method. +To create a personalized tool, inherit from `BaseTool` and define the necessary attributes and the `_run` method: ```python from crewai_tools import BaseTool class MyCustomTool(BaseTool): - name: str = "Name of my tool" - description: str = "What this tool does. It's vital for effective utilization." + name: str = "My Custom Tool" + description: str = "This tool performs a specific task. Provide a clear description for effective utilization." def _run(self, argument: str) -> str: - # Your tool's logic here - return "Tool's result" + # Implement your tool's logic here + result = f"Processed: {argument}" + return result ``` ### Using the `tool` Decorator -Alternatively, you can use the tool decorator `@tool`. This approach allows you to define the tool's attributes and functionality directly within a function, offering a concise and efficient way to create specialized tools tailored to your needs. +For simpler tools, use the `@tool` decorator to define the tool's attributes and functionality directly within a function: ```python from crewai_tools import tool -@tool("Tool Name") -def my_simple_tool(question: str) -> str: - """Tool description for clarity.""" - # Tool logic here - return "Tool output" +@tool("Simple Calculator") +def simple_calculator(operation: str, a: float, b: float) -> float: + """Performs basic arithmetic operations (add, subtract, multiply, divide).""" + if operation == "add": + return a + b + elif operation == "subtract": + return a - b + elif operation == "multiply": + return a * b + elif operation == "divide": + return a / b if b != 0 else "Error: Division by zero" + else: + return "Error: Invalid operation" ``` -### Defining a Cache Function for the Tool +## Advanced Tool Features -To optimize tool performance with caching, define custom caching strategies using the `cache_function` attribute. +### Implementing Caching + +Optimize tool performance with custom caching strategies: ```python -@tool("Tool with Caching") -def cached_tool(argument: str) -> str: - """Tool functionality description.""" - return "Cacheable result" +from crewai_tools import tool -def my_cache_strategy(arguments: dict, result: str) -> bool: - # Define custom caching logic - return True if some_condition else False +@tool("Cacheable Tool") +def cacheable_tool(input_data: str) -> str: + """Tool that benefits from caching results.""" + # Simulate complex processing + import time + time.sleep(2) + return f"Processed: {input_data}" -cached_tool.cache_function = my_cache_strategy +def cache_strategy(arguments: dict, result: str) -> bool: + # Implement your caching logic here + return len(arguments['input_data']) > 10 # Cache results for longer inputs + +cacheable_tool.cache_function = cache_strategy ``` -By adhering to these guidelines and incorporating new functionalities and collaboration tools into your tool creation and management processes, you can leverage the full capabilities of the crewAI framework, enhancing both the development experience and the efficiency of your AI agents. \ No newline at end of file +### Error Handling + +Implement robust error handling in your tools: + +```python +from crewai_tools import BaseTool + +class RobustTool(BaseTool): + name: str = "Robust Processing Tool" + description: str = "Processes data with error handling." + + def _run(self, data: str) -> str: + try: + # Your processing logic here + result = self._process_data(data) + return result + except ValueError as e: + return f"Error: Invalid input - {str(e)}" + except Exception as e: + return f"Unexpected error occurred: {str(e)}" + + def _process_data(self, data: str) -> str: + # Implement your actual data processing logic here + if not data: + raise ValueError("Empty input") + return f"Successfully processed: {data}" +``` + +### Dynamic Tool Calling + +Implement dynamic tool selection based on input: + +```python +from crewai_tools import tool + +@tool("Dynamic Tool Selector") +def dynamic_tool_selector(task_description: str) -> str: + """Selects and calls the appropriate tool based on the task description.""" + if "calculate" in task_description.lower(): + return simple_calculator("add", 5, 3) # Example usage + elif "process" in task_description.lower(): + return cacheable_tool("Sample input") + else: + return "No suitable tool found for the given task." +``` + +## Best Practices + +1. **Clear Documentation**: Provide detailed descriptions for each tool, including expected inputs and outputs. +2. **Modular Design**: Create small, focused tools that can be combined for complex tasks. +3. **Consistent Naming**: Use clear, descriptive names for your tools and their parameters. +4. **Error Handling**: Implement comprehensive error handling to make your tools robust. +5. **Performance Optimization**: Use caching for expensive operations when appropriate. +6. **Testing**: Thoroughly test your tools with various inputs to ensure reliability. + +## Conclusion + +By adhering to these guidelines and incorporating advanced functionalities into your tool creation and management processes, you can leverage the full capabilities of the crewAI framework. This approach enhances both the development experience and the efficiency of your AI agents, allowing for more sophisticated and powerful AI-driven applications. From d2fab55561c41372043891b94a6210fe2c00275e Mon Sep 17 00:00:00 2001 From: "Rip&Tear (aider)" <84775494+theCyberTech@users.noreply.github.com> Date: Thu, 5 Sep 2024 00:06:11 +0800 Subject: [PATCH 3/8] feat: Improve documentation for TXTSearchTool --- docs/tools/TXTSearchTool.md | 72 ++++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 21 deletions(-) diff --git a/docs/tools/TXTSearchTool.md b/docs/tools/TXTSearchTool.md index e13fb543f..ab844af38 100644 --- a/docs/tools/TXTSearchTool.md +++ b/docs/tools/TXTSearchTool.md @@ -1,62 +1,92 @@ # TXTSearchTool !!! note "Experimental" - We are still working on improving tools, so there might be unexpected behavior or changes in the future. + This tool is currently in an experimental stage. We are actively working on improvements, so there might be unexpected behavior or changes in future versions. ## Description -This tool is used to perform a RAG (Retrieval-Augmented Generation) search within the content of a text file. It allows for semantic searching of a query within a specified text file's content, making it an invaluable resource for quickly extracting information or finding specific sections of text based on the query provided. +The TXTSearchTool is designed to perform RAG (Retrieval-Augmented Generation) searches within the content of text files. It enables semantic searching of queries within specified text file content, making it an invaluable resource for quickly extracting information or locating specific sections of text based on the provided query. ## Installation -To use the TXTSearchTool, you first need to install the crewai_tools package. This can be done using pip, a package manager for Python. Open your terminal or command prompt and enter the following command: +To use the TXTSearchTool, you need to install the crewai_tools package. Use pip, the Python package manager, by running the following command in your terminal or command prompt: ```shell pip install 'crewai[tools]' ``` -This command will download and install the TXTSearchTool along with any necessary dependencies. +This command will install the TXTSearchTool along with all necessary dependencies. -## Example -The following example demonstrates how to use the TXTSearchTool to search within a text file. This example shows both the initialization of the tool with a specific text file and the subsequent search within that file's content. +## Usage -```python -from crewai_tools import TXTSearchTool +### Basic Initialization +There are two ways to initialize the TXTSearchTool: -# Initialize the tool to search within any text file's content the agent learns about during its execution -tool = TXTSearchTool() +1. Without specifying a text file: + ```python + from crewai_tools import TXTSearchTool -# OR + # Initialize the tool to search within any text file's content the agent learns about during its execution + tool = TXTSearchTool() + ``` -# Initialize the tool with a specific text file, so the agent can search within the given text file's content -tool = TXTSearchTool(txt='path/to/text/file.txt') -``` +2. With a specific text file: + ```python + from crewai_tools import TXTSearchTool -## Arguments -- `txt` (str): **Optional**. The path to the text file you want to search. This argument is only required if the tool was not initialized with a specific text file; otherwise, the search will be conducted within the initially provided text file. + # Initialize the tool with a specific text file + tool = TXTSearchTool(txt='path/to/text/file.txt') + ``` -## Custom model and embeddings +### Arguments +- `txt` (str, optional): The path to the text file you want to search. If not provided during initialization, it must be specified when using the tool. -By default, the tool uses OpenAI for both embeddings and summarization. To customize the model, you can use a config dictionary as follows: +### Performing a Search +After initialization, you can use the tool to perform searches. The exact method to do this depends on how you're using the tool within your CrewAI setup. + +## Advanced Configuration: Custom Models and Embeddings + +By default, the TXTSearchTool uses OpenAI for both embeddings and summarization. However, you can customize these settings using a configuration dictionary: ```python tool = TXTSearchTool( config=dict( llm=dict( - provider="ollama", # or google, openai, anthropic, llama2, ... + provider="ollama", # Options: google, openai, anthropic, llama2, etc. config=dict( model="llama2", + # Uncomment and adjust these optional parameters as needed: # temperature=0.5, # top_p=1, - # stream=true, + # stream=True, ), ), embedder=dict( - provider="google", # or openai, ollama, ... + provider="google", # Options: openai, ollama, etc. config=dict( model="models/embedding-001", task_type="retrieval_document", + # Uncomment if needed: # title="Embeddings", ), ), ) ) ``` + +This configuration allows you to specify different providers and models for both the language model (llm) and the embedder. + +## Best Practices +- Ensure the text file is in a readable format and encoding. +- For large text files, consider splitting them into smaller, more manageable chunks. +- Experiment with different query formulations to get the most relevant results. + +## Limitations +- The tool's effectiveness may vary depending on the size and complexity of the text file. +- Performance can be affected by the chosen language model and embedding provider. + +## Troubleshooting +If you encounter issues: +1. Verify that the text file path is correct and accessible. +2. Check that you have the necessary permissions to read the file. +3. Ensure you have a stable internet connection if using cloud-based models. + +For further assistance, please refer to the CrewAI documentation or reach out to the support community. From 503f3a6372da8266353ebf2a09264f1290a8db52 Mon Sep 17 00:00:00 2001 From: Rip&Tear <84775494+theCyberTech@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:17:46 +0800 Subject: [PATCH 4/8] Update README.md Updated GitHub links to point to new Repos --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index fb91fd19a..1a5fadf4e 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,11 @@

-[Homepage](https://www.crewai.io/) | [Documentation](https://docs.crewai.com/) | [Chat with Docs](https://chatg.pt/DWjSBZn) | [Examples](https://github.com/joaomdmoura/crewai-examples) | [Discord](https://discord.com/invite/X4JWnZnxPb) +[Homepage](https://www.crewai.com/) | [Documentation](https://docs.crewai.com/) | [Chat with Docs](https://chatg.pt/DWjSBZn) | [Examples](https://github.com/crewAIInc/crewAI-examples) | [Discord](https://discord.com/invite/X4JWnZnxPb)

-[![GitHub Repo stars](https://img.shields.io/github/stars/joaomdmoura/crewAI)](https://github.com/joaomdmoura/crewAI) +[![GitHub Repo stars](https://img.shields.io/github/stars/joaomdmoura/crewAI)](https://github.com/crewAIInc/crewAI) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) @@ -154,12 +154,12 @@ In addition to the sequential process, you can use the hierarchical process, whi ## Examples -You can test different real life examples of AI crews in the [crewAI-examples repo](https://github.com/joaomdmoura/crewAI-examples?tab=readme-ov-file): +You can test different real life examples of AI crews in the [crewAI-examples repo](https://github.com/crewAIInc/crewAI-examples?tab=readme-ov-file): -- [Landing Page Generator](https://github.com/joaomdmoura/crewAI-examples/tree/main/landing_page_generator) +- [Landing Page Generator](https://github.com/crewAIInc/crewAI-examples/tree/main/landing_page_generator) - [Having Human input on the execution](https://docs.crewai.com/how-to/Human-Input-on-Execution) -- [Trip Planner](https://github.com/joaomdmoura/crewAI-examples/tree/main/trip_planner) -- [Stock Analysis](https://github.com/joaomdmoura/crewAI-examples/tree/main/stock_analysis) +- [Trip Planner](https://github.com/crewAIInc/crewAI-examples/tree/main/trip_planner) +- [Stock Analysis](https://github.com/crewAIInc/crewAI-examples/tree/main/stock_analysis) ### Quick Tutorial @@ -167,19 +167,19 @@ You can test different real life examples of AI crews in the [crewAI-examples re ### Write Job Descriptions -[Check out code for this example](https://github.com/joaomdmoura/crewAI-examples/tree/main/job-posting) or watch a video below: +[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/job-posting) or watch a video below: [![Jobs postings](https://img.youtube.com/vi/u98wEMz-9to/maxresdefault.jpg)](https://www.youtube.com/watch?v=u98wEMz-9to "Jobs postings") ### Trip Planner -[Check out code for this example](https://github.com/joaomdmoura/crewAI-examples/tree/main/trip_planner) or watch a video below: +[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/trip_planner) or watch a video below: [![Trip Planner](https://img.youtube.com/vi/xis7rWp-hjs/maxresdefault.jpg)](https://www.youtube.com/watch?v=xis7rWp-hjs "Trip Planner") ### Stock Analysis -[Check out code for this example](https://github.com/joaomdmoura/crewAI-examples/tree/main/stock_analysis) or watch a video below: +[Check out code for this example](https://github.com/crewAIInc/crewAI-examples/tree/main/stock_analysis) or watch a video below: [![Stock Analysis](https://img.youtube.com/vi/e0Uj4yWdaAg/maxresdefault.jpg)](https://www.youtube.com/watch?v=e0Uj4yWdaAg "Stock Analysis") From 1d77c8de10465de81fe4f2e37f6c5cc040387b87 Mon Sep 17 00:00:00 2001 From: Rip&Tear <84775494+theCyberTech@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:27:11 +0800 Subject: [PATCH 5/8] feat: Improve documentation for TXTSearchTool Updated wording positioning --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1a5fadf4e..0853ccbbd 100644 --- a/README.md +++ b/README.md @@ -191,13 +191,12 @@ 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. + - **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. - **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. -**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. - - ## Contribution CrewAI is open-source and we welcome contributions. If you're looking to contribute, please: From b857afe45b66aa51540a06b7383b0aac93d717a3 Mon Sep 17 00:00:00 2001 From: Rip&Tear <84775494+theCyberTech@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:29:03 +0800 Subject: [PATCH 6/8] Revert "feat: Improve documentation for TXTSearchTool" This reverts commit d2fab55561c41372043891b94a6210fe2c00275e. --- docs/tools/TXTSearchTool.md | 72 +++++++++++-------------------------- 1 file changed, 21 insertions(+), 51 deletions(-) diff --git a/docs/tools/TXTSearchTool.md b/docs/tools/TXTSearchTool.md index ab844af38..e13fb543f 100644 --- a/docs/tools/TXTSearchTool.md +++ b/docs/tools/TXTSearchTool.md @@ -1,92 +1,62 @@ # TXTSearchTool !!! note "Experimental" - This tool is currently in an experimental stage. We are actively working on improvements, so there might be unexpected behavior or changes in future versions. + We are still working on improving tools, so there might be unexpected behavior or changes in the future. ## Description -The TXTSearchTool is designed to perform RAG (Retrieval-Augmented Generation) searches within the content of text files. It enables semantic searching of queries within specified text file content, making it an invaluable resource for quickly extracting information or locating specific sections of text based on the provided query. +This tool is used to perform a RAG (Retrieval-Augmented Generation) search within the content of a text file. It allows for semantic searching of a query within a specified text file's content, making it an invaluable resource for quickly extracting information or finding specific sections of text based on the query provided. ## Installation -To use the TXTSearchTool, you need to install the crewai_tools package. Use pip, the Python package manager, by running the following command in your terminal or command prompt: +To use the TXTSearchTool, you first need to install the crewai_tools package. This can be done using pip, a package manager for Python. Open your terminal or command prompt and enter the following command: ```shell pip install 'crewai[tools]' ``` -This command will install the TXTSearchTool along with all necessary dependencies. +This command will download and install the TXTSearchTool along with any necessary dependencies. -## Usage +## Example +The following example demonstrates how to use the TXTSearchTool to search within a text file. This example shows both the initialization of the tool with a specific text file and the subsequent search within that file's content. -### Basic Initialization -There are two ways to initialize the TXTSearchTool: +```python +from crewai_tools import TXTSearchTool -1. Without specifying a text file: - ```python - from crewai_tools import TXTSearchTool +# Initialize the tool to search within any text file's content the agent learns about during its execution +tool = TXTSearchTool() - # Initialize the tool to search within any text file's content the agent learns about during its execution - tool = TXTSearchTool() - ``` +# OR -2. With a specific text file: - ```python - from crewai_tools import TXTSearchTool +# Initialize the tool with a specific text file, so the agent can search within the given text file's content +tool = TXTSearchTool(txt='path/to/text/file.txt') +``` - # Initialize the tool with a specific text file - tool = TXTSearchTool(txt='path/to/text/file.txt') - ``` +## Arguments +- `txt` (str): **Optional**. The path to the text file you want to search. This argument is only required if the tool was not initialized with a specific text file; otherwise, the search will be conducted within the initially provided text file. -### Arguments -- `txt` (str, optional): The path to the text file you want to search. If not provided during initialization, it must be specified when using the tool. +## Custom model and embeddings -### Performing a Search -After initialization, you can use the tool to perform searches. The exact method to do this depends on how you're using the tool within your CrewAI setup. - -## Advanced Configuration: Custom Models and Embeddings - -By default, the TXTSearchTool uses OpenAI for both embeddings and summarization. However, you can customize these settings using a configuration dictionary: +By default, the tool uses OpenAI for both embeddings and summarization. To customize the model, you can use a config dictionary as follows: ```python tool = TXTSearchTool( config=dict( llm=dict( - provider="ollama", # Options: google, openai, anthropic, llama2, etc. + provider="ollama", # or google, openai, anthropic, llama2, ... config=dict( model="llama2", - # Uncomment and adjust these optional parameters as needed: # temperature=0.5, # top_p=1, - # stream=True, + # stream=true, ), ), embedder=dict( - provider="google", # Options: openai, ollama, etc. + provider="google", # or openai, ollama, ... config=dict( model="models/embedding-001", task_type="retrieval_document", - # Uncomment if needed: # title="Embeddings", ), ), ) ) ``` - -This configuration allows you to specify different providers and models for both the language model (llm) and the embedder. - -## Best Practices -- Ensure the text file is in a readable format and encoding. -- For large text files, consider splitting them into smaller, more manageable chunks. -- Experiment with different query formulations to get the most relevant results. - -## Limitations -- The tool's effectiveness may vary depending on the size and complexity of the text file. -- Performance can be affected by the chosen language model and embedding provider. - -## Troubleshooting -If you encounter issues: -1. Verify that the text file path is correct and accessible. -2. Check that you have the necessary permissions to read the file. -3. Ensure you have a stable internet connection if using cloud-based models. - -For further assistance, please refer to the CrewAI documentation or reach out to the support community. From 9b558ddc517617a7152cc9b6d3c77c64bcaedd01 Mon Sep 17 00:00:00 2001 From: Rip&Tear <84775494+theCyberTech@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:30:00 +0800 Subject: [PATCH 7/8] Revert "docs: Improve "Creating and Utilizing Tools in crewAI" documentation" This reverts commit b955416458b101c5afcbc7eb3be988989db7e508. --- docs/how-to/Create-Custom-Tools.md | 141 ++++++----------------------- 1 file changed, 26 insertions(+), 115 deletions(-) diff --git a/docs/how-to/Create-Custom-Tools.md b/docs/how-to/Create-Custom-Tools.md index 0abdcd03d..7dc1e8f07 100644 --- a/docs/how-to/Create-Custom-Tools.md +++ b/docs/how-to/Create-Custom-Tools.md @@ -1,26 +1,12 @@ --- title: Creating and Utilizing Tools in crewAI -description: A comprehensive guide on crafting, using, and managing custom tools within the crewAI framework, including advanced functionalities and best practices. +description: Comprehensive guide on crafting, using, and managing custom tools within the crewAI framework, including new functionalities and error handling. --- -# Creating and Utilizing Tools in crewAI +## Creating and Utilizing Tools in crewAI +This guide provides detailed instructions on creating custom tools for the crewAI framework and how to efficiently manage and utilize these tools, incorporating the latest functionalities such as tool delegation, error handling, and dynamic tool calling. It also highlights the importance of collaboration tools, enabling agents to perform a wide range of actions. -This guide provides detailed instructions on creating custom tools for the crewAI framework, efficiently managing and utilizing these tools, and incorporating advanced functionalities. By mastering tool creation and management, you can significantly enhance the capabilities of your AI agents and improve overall system performance. - -## Table of Contents - -1. [Prerequisites](#prerequisites) -2. [Creating Custom Tools](#creating-custom-tools) - - [Subclassing `BaseTool`](#subclassing-basetool) - - [Using the `tool` Decorator](#using-the-tool-decorator) -3. [Advanced Tool Features](#advanced-tool-features) - - [Implementing Caching](#implementing-caching) - - [Error Handling](#error-handling) - - [Dynamic Tool Calling](#dynamic-tool-calling) -4. [Best Practices](#best-practices) -5. [Conclusion](#conclusion) - -## Prerequisites +### Prerequisites Before creating your own tools, ensure you have the crewAI extra tools package installed: @@ -28,126 +14,51 @@ Before creating your own tools, ensure you have the crewAI extra tools package i pip install 'crewai[tools]' ``` -## Creating Custom Tools - ### Subclassing `BaseTool` -To create a personalized tool, inherit from `BaseTool` and define the necessary attributes and the `_run` method: +To create a personalized tool, inherit from `BaseTool` and define the necessary attributes and the `_run` method. ```python from crewai_tools import BaseTool class MyCustomTool(BaseTool): - name: str = "My Custom Tool" - description: str = "This tool performs a specific task. Provide a clear description for effective utilization." + name: str = "Name of my tool" + description: str = "What this tool does. It's vital for effective utilization." def _run(self, argument: str) -> str: - # Implement your tool's logic here - result = f"Processed: {argument}" - return result + # Your tool's logic here + return "Tool's result" ``` ### Using the `tool` Decorator -For simpler tools, use the `@tool` decorator to define the tool's attributes and functionality directly within a function: +Alternatively, you can use the tool decorator `@tool`. This approach allows you to define the tool's attributes and functionality directly within a function, offering a concise and efficient way to create specialized tools tailored to your needs. ```python from crewai_tools import tool -@tool("Simple Calculator") -def simple_calculator(operation: str, a: float, b: float) -> float: - """Performs basic arithmetic operations (add, subtract, multiply, divide).""" - if operation == "add": - return a + b - elif operation == "subtract": - return a - b - elif operation == "multiply": - return a * b - elif operation == "divide": - return a / b if b != 0 else "Error: Division by zero" - else: - return "Error: Invalid operation" +@tool("Tool Name") +def my_simple_tool(question: str) -> str: + """Tool description for clarity.""" + # Tool logic here + return "Tool output" ``` -## Advanced Tool Features +### Defining a Cache Function for the Tool -### Implementing Caching - -Optimize tool performance with custom caching strategies: +To optimize tool performance with caching, define custom caching strategies using the `cache_function` attribute. ```python -from crewai_tools import tool +@tool("Tool with Caching") +def cached_tool(argument: str) -> str: + """Tool functionality description.""" + return "Cacheable result" -@tool("Cacheable Tool") -def cacheable_tool(input_data: str) -> str: - """Tool that benefits from caching results.""" - # Simulate complex processing - import time - time.sleep(2) - return f"Processed: {input_data}" +def my_cache_strategy(arguments: dict, result: str) -> bool: + # Define custom caching logic + return True if some_condition else False -def cache_strategy(arguments: dict, result: str) -> bool: - # Implement your caching logic here - return len(arguments['input_data']) > 10 # Cache results for longer inputs - -cacheable_tool.cache_function = cache_strategy +cached_tool.cache_function = my_cache_strategy ``` -### Error Handling - -Implement robust error handling in your tools: - -```python -from crewai_tools import BaseTool - -class RobustTool(BaseTool): - name: str = "Robust Processing Tool" - description: str = "Processes data with error handling." - - def _run(self, data: str) -> str: - try: - # Your processing logic here - result = self._process_data(data) - return result - except ValueError as e: - return f"Error: Invalid input - {str(e)}" - except Exception as e: - return f"Unexpected error occurred: {str(e)}" - - def _process_data(self, data: str) -> str: - # Implement your actual data processing logic here - if not data: - raise ValueError("Empty input") - return f"Successfully processed: {data}" -``` - -### Dynamic Tool Calling - -Implement dynamic tool selection based on input: - -```python -from crewai_tools import tool - -@tool("Dynamic Tool Selector") -def dynamic_tool_selector(task_description: str) -> str: - """Selects and calls the appropriate tool based on the task description.""" - if "calculate" in task_description.lower(): - return simple_calculator("add", 5, 3) # Example usage - elif "process" in task_description.lower(): - return cacheable_tool("Sample input") - else: - return "No suitable tool found for the given task." -``` - -## Best Practices - -1. **Clear Documentation**: Provide detailed descriptions for each tool, including expected inputs and outputs. -2. **Modular Design**: Create small, focused tools that can be combined for complex tasks. -3. **Consistent Naming**: Use clear, descriptive names for your tools and their parameters. -4. **Error Handling**: Implement comprehensive error handling to make your tools robust. -5. **Performance Optimization**: Use caching for expensive operations when appropriate. -6. **Testing**: Thoroughly test your tools with various inputs to ensure reliability. - -## Conclusion - -By adhering to these guidelines and incorporating advanced functionalities into your tool creation and management processes, you can leverage the full capabilities of the crewAI framework. This approach enhances both the development experience and the efficiency of your AI agents, allowing for more sophisticated and powerful AI-driven applications. +By adhering to these guidelines and incorporating new functionalities and collaboration tools into your tool creation and management processes, you can leverage the full capabilities of the crewAI framework, enhancing both the development experience and the efficiency of your AI agents. \ No newline at end of file From 0b9eeb7cdb0fd19459c081b341caa60d5b336ba3 Mon Sep 17 00:00:00 2001 From: Rip&Tear <84775494+theCyberTech@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:30:08 +0800 Subject: [PATCH 8/8] Revert "feat: Improve documentation for Conditional Tasks in crewAI" This reverts commit 18a2722e4dab93eda360e4024def9183add563d8. --- docs/how-to/Conditional-Tasks.md | 91 ++++++++++++-------------------- 1 file changed, 33 insertions(+), 58 deletions(-) diff --git a/docs/how-to/Conditional-Tasks.md b/docs/how-to/Conditional-Tasks.md index 4f0bd7598..76be82b1a 100644 --- a/docs/how-to/Conditional-Tasks.md +++ b/docs/how-to/Conditional-Tasks.md @@ -1,112 +1,87 @@ --- title: Conditional Tasks -description: Learn how to use conditional tasks in a crewAI workflow +description: Learn how to use conditional tasks in a crewAI kickoff --- -# Conditional Tasks in crewAI - ## Introduction -Conditional Tasks in crewAI enable dynamic workflow adaptation based on the outcomes of previous tasks. This powerful feature allows crews to make decisions and execute tasks selectively, enhancing the flexibility and efficiency of your AI-driven processes. - -## Key Concepts - -1. **ConditionalTask**: A special type of task that executes only if a specified condition is met. -2. **Condition Function**: A custom function that determines whether the conditional task should be executed. -3. **Task Output**: The result of a previous task, which can be used to make decisions for conditional tasks. - -## How It Works - -1. Define a condition function that takes a `TaskOutput` as input and returns a boolean. -2. Create a `ConditionalTask` with the condition function. -3. Add the conditional task to your crew's workflow. -4. The crew will evaluate the condition and execute the task only if the condition is met. +Conditional Tasks in crewAI allow for dynamic workflow adaptation based on the outcomes of previous tasks. This powerful feature enables crews to make decisions and execute tasks selectively, enhancing the flexibility and efficiency of your AI-driven processes. ## Example Usage -Here's a step-by-step example of how to implement conditional tasks in your crewAI workflow: - ```python from typing import List from pydantic import BaseModel -from crewai import Agent, Crew, Task +from crewai import Agent, Crew from crewai.tasks.conditional_task import ConditionalTask from crewai.tasks.task_output import TaskOutput +from crewai.task import Task from crewai_tools import SerperDevTool -# 1. Define the condition function +# Define a condition function for the conditional task +# if false task will be skipped, true, then execute task def is_data_missing(output: TaskOutput) -> bool: - return len(output.pydantic.events) < 10 + return len(output.pydantic.events) < 10 # this will skip this task -# 2. Define the output model -class EventOutput(BaseModel): - events: List[str] - -# 3. Create agents +# Define the agents data_fetcher_agent = Agent( role="Data Fetcher", goal="Fetch data online using Serper tool", - backstory="Expert in retrieving online information", + backstory="Backstory 1", verbose=True, tools=[SerperDevTool()], ) data_processor_agent = Agent( role="Data Processor", - goal="Process and augment fetched data", - backstory="Specialist in data analysis and enrichment", + goal="Process fetched data", + backstory="Backstory 2", verbose=True, ) summary_generator_agent = Agent( role="Summary Generator", - goal="Generate concise summaries from processed data", - backstory="Experienced in creating informative summaries", + goal="Generate summary from fetched data", + backstory="Backstory 3", verbose=True, ) -# 4. Define tasks -initial_fetch_task = Task( +class EventOutput(BaseModel): + events: List[str] + +task1 = Task( description="Fetch data about events in San Francisco using Serper tool", - expected_output="List of events in SF this week", + expected_output="List of 10 things to do in SF this week", agent=data_fetcher_agent, output_pydantic=EventOutput, ) -conditional_fetch_task = ConditionalTask( - description="Fetch additional events if the initial list is incomplete", - expected_output="Complete list of 10 events in SF this week", +conditional_task = ConditionalTask( + description=""" + Check if data is missing. If we have less than 10 events, + fetch more events using Serper tool so that + we have a total of 10 events in SF this week.. + """, + expected_output="List of 10 Things to do in SF this week", condition=is_data_missing, agent=data_processor_agent, ) -summary_task = Task( - description="Generate a summary of events in San Francisco from the fetched data", - expected_output="Concise summary of SF events", +task3 = Task( + description="Generate summary of events in San Francisco from fetched data", + expected_output="summary_generated", agent=summary_generator_agent, ) -# 5. Create and run the crew +# Create a crew with the tasks crew = Crew( agents=[data_fetcher_agent, data_processor_agent, summary_generator_agent], - tasks=[initial_fetch_task, conditional_fetch_task, summary_task], + tasks=[task1, conditional_task, task3], verbose=True, planning=True # Enable planning feature ) +# Run the crew result = crew.kickoff() -print("Final Result:", result) -``` - -## Best Practices - -1. **Clear Conditions**: Ensure your condition functions are clear and specific. -2. **Error Handling**: Implement proper error handling in your condition functions. -3. **Task Dependencies**: Consider the dependencies between tasks when using conditional tasks. -4. **Testing**: Thoroughly test your conditional workflows with various scenarios. - -## Conclusion - -Conditional Tasks in crewAI provide a powerful way to create dynamic and adaptive AI workflows. By leveraging this feature, you can build more intelligent and efficient systems that respond to changing conditions and data. - -For more advanced usage and additional features, refer to the crewAI documentation or reach out to the community for support. +print("results", result) +``` \ No newline at end of file