Compare commits

..

2 Commits

Author SHA1 Message Date
Devin AI
f46d19e193 fix: address PR feedback with improved validation, documentation, and tests
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-03 11:09:30 +00:00
Devin AI
d8571dc196 feat: add ToolWithInstruction wrapper for tool-specific usage instructions (issue #2515)
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-03 11:04:12 +00:00
11 changed files with 396 additions and 246 deletions

159
README.md
View File

@@ -4,7 +4,7 @@
# **CrewAI**
🤖 **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.
🤖 **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.
<h3>
@@ -22,17 +22,13 @@
- [Why CrewAI?](#why-crewai)
- [Getting Started](#getting-started)
- [Key Features](#key-features)
- [Understanding Flows and Crews](#understanding-flows-and-crews)
- [CrewAI vs LangGraph](#how-crewai-compares)
- [Examples](#examples)
- [Quick Tutorial](#quick-tutorial)
- [Write Job Descriptions](#write-job-descriptions)
- [Trip Planner](#trip-planner)
- [Stock Analysis](#stock-analysis)
- [Using Crews and Flows Together](#using-crews-and-flows-together)
- [Connecting Your Crew to a Model](#connecting-your-crew-to-a-model)
- [How CrewAI Compares](#how-crewai-compares)
- [Frequently Asked Questions (FAQ)](#frequently-asked-questions-faq)
- [Contribution](#contribution)
- [Telemetry](#telemetry)
- [License](#license)
@@ -40,40 +36,10 @@
## Why CrewAI?
The power of AI collaboration has too much to offer.
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.
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.
## 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
@@ -298,16 +264,14 @@ In addition to the sequential process, you can use the hierarchical process, whi
## Key Features
**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.
- **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.
- **Tool Instructions**: Attach specific usage instructions to tools for better control over when and how agents use them.
- **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!
![CrewAI Mind Map](./docs/crewAI-mindmap.png "CrewAI Mind Map")
@@ -342,98 +306,6 @@ You can test different real life examples of AI crews in the [CrewAI-examples re
[![Stock Analysis](https://img.youtube.com/vi/e0Uj4yWdaAg/maxresdefault.jpg)](https://www.youtube.com/watch?v=e0Uj4yWdaAg "Stock Analysis")
### Using Crews and Flows Together
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:
```python
from crewai.flow.flow import Flow, listen, start, router
from crewai import Crew, Agent, Task
from pydantic import BaseModel
# Define structured state for precise control
class MarketState(BaseModel):
sentiment: str = "neutral"
confidence: float = 0.0
recommendations: list = []
class AdvancedAnalysisFlow(Flow[MarketState]):
@start()
def fetch_market_data(self):
# 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)
def analyze_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
)
return analysis_crew.kickoff(inputs=market_data) # Pass market_data as named inputs
@router(analyze_with_crew)
def determine_next_steps(self):
# Show flow control with conditional routing
if self.state.confidence > 0.8:
return "high_confidence"
elif self.state.confidence > 0.5:
return "medium_confidence"
return "low_confidence"
@listen("high_confidence")
def execute_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")
]
)
return strategy_crew.kickoff()
@listen("medium_confidence", "low_confidence")
def request_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.
@@ -442,13 +314,9 @@ Please refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-
## How CrewAI Compares
**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.
**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.
- **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.
- **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.
@@ -573,8 +441,5 @@ 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.

View File

@@ -171,58 +171,6 @@ 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.",
knowledge_sources=[product_specs] # Agent-specific knowledge
)
# Create a task that requires product knowledge
support_task = Task(
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.

View File

@@ -0,0 +1,153 @@
# Tool Instructions
CrewAI allows you to provide specific instructions for when and how to use tools. This is useful when you want to guide agents on proper tool usage without cluttering their backstory.
## Basic Usage
```python
from crewai import Agent
from crewai_tools import ScrapeWebsiteTool
from crewai.tools import ToolWithInstruction
# Create a tool with instructions
scrape_tool = ScrapeWebsiteTool()
scrape_with_instructions = ToolWithInstruction(
tool=scrape_tool,
instructions="""
ALWAYS use this tool when making a joke.
NEVER use this tool when making joke about someone's mom.
"""
)
# Use the tool with an agent
agent = Agent(
role="Comedian",
goal="Create hilarious and engaging jokes",
backstory="""
You are a professional stand-up comedian with years of experience in crafting jokes.
You have a great sense of humor and can create jokes about any topic
while keeping them appropriate and entertaining.
""",
tools=[scrape_with_instructions],
)
```
## Real-World Examples
### Example 1: Research Assistant with Web Search Tool
```python
from crewai import Agent
from crewai_tools import SearchTool
from crewai.tools import ToolWithInstruction
search_tool = SearchTool()
search_with_instructions = ToolWithInstruction(
tool=search_tool,
instructions="""
Use this tool ONLY for factual information that requires up-to-date data.
ALWAYS verify information by searching multiple sources.
DO NOT use this tool for speculative questions or opinions.
"""
)
research_agent = Agent(
role="Research Analyst",
goal="Provide accurate and well-sourced information",
backstory="You are a meticulous research analyst with attention to detail and fact-checking.",
tools=[search_with_instructions],
)
```
### Example 2: Data Scientist with Multiple Analysis Tools
```python
from crewai import Agent
from crewai_tools import PythonTool, DataVisualizationTool
from crewai.tools import ToolWithInstruction
# Python tool for data processing
python_tool = PythonTool()
python_with_instructions = ToolWithInstruction(
tool=python_tool,
instructions="""
Use this tool for data cleaning, transformation, and statistical analysis.
ALWAYS include comments in your code.
DO NOT use this tool for creating visualizations.
"""
)
# Visualization tool
viz_tool = DataVisualizationTool()
viz_with_instructions = ToolWithInstruction(
tool=viz_tool,
instructions="""
Use this tool ONLY for creating data visualizations.
ALWAYS label axes and include titles in your charts.
PREFER simple visualizations that clearly communicate the main insight.
"""
)
data_scientist = Agent(
role="Data Scientist",
goal="Analyze data and create insightful visualizations",
backstory="You are an experienced data scientist who excels at finding patterns in data.",
tools=[python_with_instructions, viz_with_instructions],
)
```
## How Instructions Are Presented to Agents
When an agent considers using a tool, the instructions are included in the tool's description. For example, a tool with instructions might appear to the agent like this:
```
Tool: search_web
Description: Search the web for information on a given topic.
Instructions: Use this tool ONLY for factual information that requires up-to-date data.
ALWAYS verify information by searching multiple sources.
DO NOT use this tool for speculative questions or opinions.
```
This clear presentation helps the agent understand when and how to use the tool appropriately.
## Dynamically Updating Instructions
You can update tool instructions dynamically during execution:
```python
# Create a tool with initial instructions
search_with_instructions = ToolWithInstruction(
tool=search_tool,
instructions="Initial instructions for tool usage"
)
# Later, update the instructions based on new requirements
search_with_instructions.update_instructions("Updated instructions for tool usage")
```
## Error Handling and Best Practices
### Validation
The `ToolWithInstruction` class includes validation to ensure instructions are not empty and don't exceed a maximum length. If you provide invalid instructions, a `ValueError` will be raised.
### Best Practices for Writing Instructions
1. **Be specific and clear** about when to use and when not to use the tool
2. **Use imperative language** like "ALWAYS", "NEVER", "USE", "DO NOT USE"
3. **Keep instructions concise** but comprehensive
4. **Include examples** of good and bad usage scenarios when possible
5. **Format instructions** with line breaks for readability
## When to Use Tool Instructions
Tool instructions are useful when:
1. You want to specify precise conditions for tool usage
2. You have multiple similar tools that should be used in different situations
3. You want to keep the agent's backstory focused on its role and personality,
not technical details about tools
4. You need to provide technical guidance on how to format inputs or interpret outputs
5. You want to enforce consistent tool usage across multiple agents
Tool instructions are semantically more correct than putting tool usage guidelines in the agent's backstory.

View File

@@ -26,7 +26,7 @@ class CrewAgentExecutorMixin:
def _should_force_answer(self) -> bool:
"""Determine if a forced answer is required based on iteration count."""
return self.iterations >= self.max_iter
return (self.iterations >= self.max_iter) and not self.have_forced_answer
def _create_short_term_memory(self, output) -> None:
"""Create and save a short-term memory item if conditions are met."""

View File

@@ -14,13 +14,13 @@ class Knowledge(BaseModel):
Knowledge is a collection of sources and setup for the vector store to save and query relevant context.
Args:
sources: List[BaseKnowledgeSource] = Field(default_factory=list)
storage: Optional[KnowledgeStorage] = Field(default=None)
storage: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
embedder_config: Optional[Dict[str, Any]] = None
"""
sources: List[BaseKnowledgeSource] = Field(default_factory=list)
model_config = ConfigDict(arbitrary_types_allowed=True)
storage: Optional[KnowledgeStorage] = Field(default=None)
storage: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
embedder_config: Optional[Dict[str, Any]] = None
collection_name: Optional[str] = None
@@ -49,13 +49,8 @@ class Knowledge(BaseModel):
"""
Query across all knowledge sources to find the most relevant information.
Returns the top_k most relevant chunks.
Raises:
ValueError: If storage is not initialized.
"""
if self.storage is None:
raise ValueError("Storage is not initialized.")
results = self.storage.search(
query,
limit,

View File

@@ -22,14 +22,13 @@ class BaseFileKnowledgeSource(BaseKnowledgeSource, ABC):
default_factory=list, description="The path to the file"
)
content: Dict[Path, str] = Field(init=False, default_factory=dict)
storage: Optional[KnowledgeStorage] = Field(default=None)
storage: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
safe_file_paths: List[Path] = Field(default_factory=list)
@field_validator("file_path", "file_paths", mode="before")
def validate_file_path(cls, v, info):
def validate_file_path(cls, v, values):
"""Validate that at least one of file_path or file_paths is provided."""
# Single check if both are None, O(1) instead of nested conditions
if v is None and info.data.get("file_path" if info.field_name == "file_paths" else "file_paths") is None:
if v is None and ("file_path" not in values or values.get("file_path") is None):
raise ValueError("Either file_path or file_paths must be provided")
return v
@@ -63,10 +62,7 @@ class BaseFileKnowledgeSource(BaseKnowledgeSource, ABC):
def _save_documents(self):
"""Save the documents to the storage."""
if self.storage:
self.storage.save(self.chunks)
else:
raise ValueError("No storage found to save documents.")
self.storage.save(self.chunks)
def convert_to_path(self, path: Union[Path, str]) -> Path:
"""Convert a path to a Path object."""

View File

@@ -16,7 +16,7 @@ class BaseKnowledgeSource(BaseModel, ABC):
chunk_embeddings: List[np.ndarray] = Field(default_factory=list)
model_config = ConfigDict(arbitrary_types_allowed=True)
storage: Optional[KnowledgeStorage] = Field(default=None)
storage: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
metadata: Dict[str, Any] = Field(default_factory=dict) # Currently unused
collection_name: Optional[str] = Field(default=None)
@@ -46,7 +46,4 @@ class BaseKnowledgeSource(BaseModel, ABC):
Save the documents to the storage.
This method should be called after the chunks and embeddings are generated.
"""
if self.storage:
self.storage.save(self.chunks)
else:
raise ValueError("No storage found to save documents.")
self.storage.save(self.chunks)

View File

@@ -1 +1,2 @@
from .base_tool import BaseTool, tool
from .tool_with_instruction import ToolWithInstruction

View File

@@ -0,0 +1,110 @@
from typing import Any, List, Optional, Dict, Callable, Union, ClassVar
from pydantic import Field, model_validator, field_validator, ConfigDict
from crewai.tools.base_tool import BaseTool
from crewai.tools.structured_tool import CrewStructuredTool
class ToolWithInstruction(BaseTool):
"""A wrapper for tools that adds specific usage instructions.
This allows users to provide specific instructions on when and how to use a tool,
without having to include these instructions in the agent's backstory.
Attributes:
tool: The tool to wrap
instructions: Specific instructions about when and how to use this tool
name: Name of the tool (inherited from the wrapped tool)
description: Description of the tool (inherited from the wrapped tool with instructions)
"""
MAX_INSTRUCTION_LENGTH: ClassVar[int] = 2000
name: str = Field(default="", description="Name of the tool")
description: str = Field(default="", description="Description of the tool")
tool: BaseTool = Field(description="The tool to wrap")
instructions: str = Field(description="Instructions about when and how to use this tool")
model_config = ConfigDict(arbitrary_types_allowed=True)
@field_validator("instructions")
@classmethod
def validate_instructions(cls, value: str) -> str:
"""Validate that instructions are not empty and not too long.
Args:
value: The instructions string to validate
Returns:
str: The validated and sanitized instructions
Raises:
ValueError: If instructions are empty or exceed maximum length
"""
if not value or not value.strip():
raise ValueError("Instructions cannot be empty")
if len(value) > cls.MAX_INSTRUCTION_LENGTH:
raise ValueError(
f"Instructions exceed maximum length of {cls.MAX_INSTRUCTION_LENGTH} characters"
)
return value.strip()
@model_validator(mode="after")
def set_tool_attributes(self) -> "ToolWithInstruction":
"""Sets name, description, and args_schema from the wrapped tool.
Returns:
ToolWithInstruction: The validated instance with updated attributes.
"""
self.name = self.tool.name
self.description = f"{self.tool.description}\nInstructions: {self.instructions}"
self.args_schema = self.tool.args_schema
return self
def update_instructions(self, new_instructions: str) -> None:
"""Updates the tool's usage instructions.
Args:
new_instructions (str): New instructions for tool usage.
Raises:
ValueError: If new instructions are empty or exceed maximum length
"""
if not new_instructions or not new_instructions.strip():
raise ValueError("Instructions cannot be empty")
if len(new_instructions) > self.MAX_INSTRUCTION_LENGTH:
raise ValueError(
f"Instructions exceed maximum length of {self.MAX_INSTRUCTION_LENGTH} characters"
)
self.instructions = new_instructions.strip()
self.description = f"{self.tool.description}\nInstructions: {self.instructions}"
def _run(self, *args: Any, **kwargs: Any) -> Any:
"""Run the wrapped tool.
Args:
*args: Positional arguments to pass to the wrapped tool
**kwargs: Keyword arguments to pass to the wrapped tool
Returns:
Any: The result from the wrapped tool's _run method
"""
return self.tool._run(*args, **kwargs)
def to_structured_tool(self) -> CrewStructuredTool:
"""Convert this tool to a CrewStructuredTool instance.
Returns:
CrewStructuredTool: A structured tool with instructions included in the description
"""
structured_tool = self.tool.to_structured_tool()
structured_tool.description = f"{structured_tool.description}\nInstructions: {self.instructions}"
return structured_tool

View File

@@ -584,28 +584,3 @@ def test_docling_source_with_local_file():
docling_source = CrewDoclingSource(file_paths=[pdf_path])
assert docling_source.file_paths == [pdf_path]
assert docling_source.content is not None
def test_file_path_validation():
"""Test file path validation for knowledge sources."""
current_dir = Path(__file__).parent
pdf_path = current_dir / "crewai_quickstart.pdf"
# Test valid single file_path
source = PDFKnowledgeSource(file_path=pdf_path)
assert source.safe_file_paths == [pdf_path]
# Test valid file_paths list
source = PDFKnowledgeSource(file_paths=[pdf_path])
assert source.safe_file_paths == [pdf_path]
# Test both file_path and file_paths provided (should use file_paths)
source = PDFKnowledgeSource(file_path=pdf_path, file_paths=[pdf_path])
assert source.safe_file_paths == [pdf_path]
# Test neither file_path nor file_paths provided
with pytest.raises(
ValueError,
match="file_path/file_paths must be a Path, str, or a list of these types"
):
PDFKnowledgeSource()

View File

@@ -0,0 +1,110 @@
import pytest
from unittest.mock import MagicMock, patch
from typing import Any, Dict, Optional
from crewai.tools.base_tool import BaseTool, Tool
from crewai.tools.tool_with_instruction import ToolWithInstruction
class MockTool(BaseTool):
"""Mock tool for testing."""
name: str = "mock_tool"
description: str = "A mock tool for testing"
def _run(self, *args: Any, **kwargs: Any) -> str:
return "mock result"
class TestToolWithInstruction:
"""Test suite for ToolWithInstruction."""
def test_initialization(self):
"""Test tool initialization with instructions."""
tool = MockTool()
instructions = "Only use this tool for XYZ"
wrapped_tool = ToolWithInstruction(tool=tool, instructions=instructions)
assert wrapped_tool.name == tool.name
assert "Instructions: Only use this tool for XYZ" in wrapped_tool.description
assert wrapped_tool.args_schema == tool.args_schema
def test_run_method(self):
"""Test that the run method delegates to the original tool."""
tool = MockTool()
instructions = "Only use this tool for XYZ"
wrapped_tool = ToolWithInstruction(tool=tool, instructions=instructions)
result = wrapped_tool.run()
assert result == "mock result"
def test_to_structured_tool(self):
"""Test that to_structured_tool includes instructions."""
tool = MockTool()
instructions = "Only use this tool for XYZ"
wrapped_tool = ToolWithInstruction(tool=tool, instructions=instructions)
structured_tool = wrapped_tool.to_structured_tool()
assert "Instructions: Only use this tool for XYZ" in structured_tool.description
def test_with_function_tool(self):
"""Test tool wrapping with a function tool."""
def sample_func():
return "sample result"
tool = Tool(
name="sample_tool",
description="A sample tool",
func=sample_func
)
instructions = "Only use this tool for XYZ"
wrapped_tool = ToolWithInstruction(tool=tool, instructions=instructions)
assert wrapped_tool.name == tool.name
assert "Instructions: Only use this tool for XYZ" in wrapped_tool.description
def test_empty_instructions(self):
"""Test that empty instructions raise ValueError."""
tool = MockTool()
with pytest.raises(ValueError, match="Instructions cannot be empty"):
ToolWithInstruction(tool=tool, instructions="")
with pytest.raises(ValueError, match="Instructions cannot be empty"):
ToolWithInstruction(tool=tool, instructions=" ")
def test_too_long_instructions(self):
"""Test that instructions exceeding maximum length raise ValueError."""
tool = MockTool()
long_instructions = "x" * (ToolWithInstruction.MAX_INSTRUCTION_LENGTH + 1)
with pytest.raises(ValueError, match="Instructions exceed maximum length"):
ToolWithInstruction(tool=tool, instructions=long_instructions)
def test_update_instructions(self):
"""Test updating instructions dynamically."""
tool = MockTool()
initial_instructions = "Initial instructions"
new_instructions = "Updated instructions"
wrapped_tool = ToolWithInstruction(tool=tool, instructions=initial_instructions)
assert "Instructions: Initial instructions" in wrapped_tool.description
wrapped_tool.update_instructions(new_instructions)
assert "Instructions: Updated instructions" in wrapped_tool.description
assert wrapped_tool.instructions == new_instructions
def test_update_instructions_validation(self):
"""Test validation when updating instructions."""
tool = MockTool()
wrapped_tool = ToolWithInstruction(tool=tool, instructions="Valid instructions")
with pytest.raises(ValueError, match="Instructions cannot be empty"):
wrapped_tool.update_instructions("")
long_instructions = "x" * (ToolWithInstruction.MAX_INSTRUCTION_LENGTH + 1)
with pytest.raises(ValueError, match="Instructions exceed maximum length"):
wrapped_tool.update_instructions(long_instructions)