mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-29 18:18:13 +00:00
Compare commits
8 Commits
devin/1747
...
ea413ae03b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea413ae03b | ||
|
|
f1299f484d | ||
|
|
a0c322a535 | ||
|
|
86f58c95de | ||
|
|
99fe91586d | ||
|
|
0c2d23dfe0 | ||
|
|
2433819c4f | ||
|
|
97fc44c930 |
158
README.md
158
README.md
@@ -4,7 +4,7 @@
|
||||
|
||||
# **CrewAI**
|
||||
|
||||
🤖 **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)
|
||||
- [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)
|
||||
@@ -36,10 +40,40 @@
|
||||
## Why CrewAI?
|
||||
|
||||
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
|
||||
@@ -264,13 +298,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 +342,98 @@ You can test different real life examples of AI crews in the [CrewAI-examples re
|
||||
|
||||
[](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.
|
||||
@@ -313,9 +442,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.
|
||||
|
||||
@@ -440,5 +573,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.
|
||||
|
||||
@@ -171,6 +171,58 @@ 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.
|
||||
|
||||
@@ -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) and not self.have_forced_answer
|
||||
return self.iterations >= self.max_iter
|
||||
|
||||
def _create_short_term_memory(self, output) -> None:
|
||||
"""Create and save a short-term memory item if conditions are met."""
|
||||
|
||||
@@ -113,10 +113,6 @@ class Crew(BaseModel):
|
||||
default=False,
|
||||
description="Whether the crew should use memory to store memories of it's execution",
|
||||
)
|
||||
memory_verbose: bool = Field(
|
||||
default=False,
|
||||
description="Whether to show verbose logs about memory operations",
|
||||
)
|
||||
memory_config: Optional[Dict[str, Any]] = Field(
|
||||
default=None,
|
||||
description="Configuration for the memory to be used for the crew.",
|
||||
@@ -261,7 +257,7 @@ class Crew(BaseModel):
|
||||
"""Set private attributes."""
|
||||
if self.memory:
|
||||
self._long_term_memory = (
|
||||
self.long_term_memory if self.long_term_memory else LongTermMemory(memory_verbose=self.memory_verbose)
|
||||
self.long_term_memory if self.long_term_memory else LongTermMemory()
|
||||
)
|
||||
self._short_term_memory = (
|
||||
self.short_term_memory
|
||||
@@ -269,17 +265,16 @@ class Crew(BaseModel):
|
||||
else ShortTermMemory(
|
||||
crew=self,
|
||||
embedder_config=self.embedder,
|
||||
memory_verbose=self.memory_verbose,
|
||||
)
|
||||
)
|
||||
self._entity_memory = (
|
||||
self.entity_memory
|
||||
if self.entity_memory
|
||||
else EntityMemory(crew=self, embedder_config=self.embedder, memory_verbose=self.memory_verbose)
|
||||
else EntityMemory(crew=self, embedder_config=self.embedder)
|
||||
)
|
||||
if hasattr(self, "memory_config") and self.memory_config is not None:
|
||||
self._user_memory = (
|
||||
self.user_memory if self.user_memory else UserMemory(crew=self, memory_verbose=self.memory_verbose)
|
||||
self.user_memory if self.user_memory else UserMemory(crew=self)
|
||||
)
|
||||
else:
|
||||
self._user_memory = None
|
||||
|
||||
@@ -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: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
|
||||
storage: Optional[KnowledgeStorage] = Field(default=None)
|
||||
embedder_config: Optional[Dict[str, Any]] = None
|
||||
"""
|
||||
|
||||
sources: List[BaseKnowledgeSource] = Field(default_factory=list)
|
||||
model_config = ConfigDict(arbitrary_types_allowed=True)
|
||||
storage: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
|
||||
storage: Optional[KnowledgeStorage] = Field(default=None)
|
||||
embedder_config: Optional[Dict[str, Any]] = None
|
||||
collection_name: Optional[str] = None
|
||||
|
||||
@@ -49,8 +49,13 @@ 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,
|
||||
|
||||
@@ -22,13 +22,14 @@ class BaseFileKnowledgeSource(BaseKnowledgeSource, ABC):
|
||||
default_factory=list, description="The path to the file"
|
||||
)
|
||||
content: Dict[Path, str] = Field(init=False, default_factory=dict)
|
||||
storage: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
|
||||
storage: Optional[KnowledgeStorage] = Field(default=None)
|
||||
safe_file_paths: List[Path] = Field(default_factory=list)
|
||||
|
||||
@field_validator("file_path", "file_paths", mode="before")
|
||||
def validate_file_path(cls, v, values):
|
||||
def validate_file_path(cls, v, info):
|
||||
"""Validate that at least one of file_path or file_paths is provided."""
|
||||
if v is None and ("file_path" not in values or values.get("file_path") is None):
|
||||
# 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:
|
||||
raise ValueError("Either file_path or file_paths must be provided")
|
||||
return v
|
||||
|
||||
@@ -62,7 +63,10 @@ class BaseFileKnowledgeSource(BaseKnowledgeSource, ABC):
|
||||
|
||||
def _save_documents(self):
|
||||
"""Save the documents to the storage."""
|
||||
self.storage.save(self.chunks)
|
||||
if self.storage:
|
||||
self.storage.save(self.chunks)
|
||||
else:
|
||||
raise ValueError("No storage found to save documents.")
|
||||
|
||||
def convert_to_path(self, path: Union[Path, str]) -> Path:
|
||||
"""Convert a path to a Path object."""
|
||||
|
||||
@@ -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: KnowledgeStorage = Field(default_factory=KnowledgeStorage)
|
||||
storage: Optional[KnowledgeStorage] = Field(default=None)
|
||||
metadata: Dict[str, Any] = Field(default_factory=dict) # Currently unused
|
||||
collection_name: Optional[str] = Field(default=None)
|
||||
|
||||
@@ -46,4 +46,7 @@ class BaseKnowledgeSource(BaseModel, ABC):
|
||||
Save the documents to the storage.
|
||||
This method should be called after the chunks and embeddings are generated.
|
||||
"""
|
||||
self.storage.save(self.chunks)
|
||||
if self.storage:
|
||||
self.storage.save(self.chunks)
|
||||
else:
|
||||
raise ValueError("No storage found to save documents.")
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from crewai.memory.entity.entity_memory_item import EntityMemoryItem
|
||||
from crewai.memory.memory import Memory, MemoryOperationError
|
||||
from crewai.memory.memory import Memory
|
||||
from crewai.memory.storage.rag_storage import RAGStorage
|
||||
|
||||
|
||||
@@ -10,24 +8,9 @@ class EntityMemory(Memory):
|
||||
EntityMemory class for managing structured information about entities
|
||||
and their relationships using SQLite storage.
|
||||
Inherits from the Memory class.
|
||||
|
||||
Attributes:
|
||||
memory_provider: The memory provider to use, if any.
|
||||
storage: The storage backend for the memory.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
|
||||
def __init__(self, crew=None, embedder_config=None, storage=None, path=None, memory_verbose=False):
|
||||
"""
|
||||
Initialize an EntityMemory instance.
|
||||
|
||||
Args:
|
||||
crew: The crew to associate with this memory.
|
||||
embedder_config: Configuration for the embedder.
|
||||
storage: The storage backend for the memory.
|
||||
path: Path to the storage file, if any.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
def __init__(self, crew=None, embedder_config=None, storage=None, path=None):
|
||||
if hasattr(crew, "memory_config") and crew.memory_config is not None:
|
||||
self.memory_provider = crew.memory_config.get("provider")
|
||||
else:
|
||||
@@ -53,48 +36,23 @@ class EntityMemory(Memory):
|
||||
path=path,
|
||||
)
|
||||
)
|
||||
super().__init__(storage, memory_verbose=memory_verbose)
|
||||
super().__init__(storage)
|
||||
|
||||
def save(self, item: EntityMemoryItem) -> None: # type: ignore # BUG?: Signature of "save" incompatible with supertype "Memory"
|
||||
"""
|
||||
Saves an entity item into storage.
|
||||
|
||||
Args:
|
||||
item: The entity memory item to save.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error saving the entity to memory.
|
||||
"""
|
||||
try:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Saving entity", f"{item.name} ({item.type})")
|
||||
self._log_operation("Description", item.description)
|
||||
|
||||
if self.memory_provider == "mem0":
|
||||
data = f"""
|
||||
Remember details about the following entity:
|
||||
Name: {item.name}
|
||||
Type: {item.type}
|
||||
Entity Description: {item.description}
|
||||
"""
|
||||
else:
|
||||
data = f"{item.name}({item.type}): {item.description}"
|
||||
super().save(data, item.metadata)
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error saving entity", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "save entity", self.__class__.__name__)
|
||||
"""Saves an entity item into the SQLite storage."""
|
||||
if self.memory_provider == "mem0":
|
||||
data = f"""
|
||||
Remember details about the following entity:
|
||||
Name: {item.name}
|
||||
Type: {item.type}
|
||||
Entity Description: {item.description}
|
||||
"""
|
||||
else:
|
||||
data = f"{item.name}({item.type}): {item.description}"
|
||||
super().save(data, item.metadata)
|
||||
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
Reset the entity memory.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error resetting the memory.
|
||||
"""
|
||||
try:
|
||||
self.storage.reset()
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error resetting", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "reset", self.__class__.__name__)
|
||||
raise Exception(f"An error occurred while resetting the entity memory: {e}")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from crewai.memory.long_term.long_term_memory_item import LongTermMemoryItem
|
||||
from crewai.memory.memory import Memory, MemoryOperationError
|
||||
from crewai.memory.memory import Memory
|
||||
from crewai.memory.storage.ltm_sqlite_storage import LTMSQLiteStorage
|
||||
|
||||
|
||||
@@ -12,90 +12,25 @@ class LongTermMemory(Memory):
|
||||
Inherits from the Memory class and utilizes an instance of a class that
|
||||
adheres to the Storage for data storage, specifically working with
|
||||
LongTermMemoryItem instances.
|
||||
|
||||
Attributes:
|
||||
storage: The storage backend for the memory.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
|
||||
def __init__(self, storage=None, path=None, memory_verbose=False):
|
||||
"""
|
||||
Initialize a LongTermMemory instance.
|
||||
|
||||
Args:
|
||||
storage: The storage backend for the memory.
|
||||
path: Path to the storage file, if any.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
def __init__(self, storage=None, path=None):
|
||||
if not storage:
|
||||
storage = LTMSQLiteStorage(db_path=path) if path else LTMSQLiteStorage()
|
||||
super().__init__(storage, memory_verbose=memory_verbose)
|
||||
super().__init__(storage)
|
||||
|
||||
def save(self, item: LongTermMemoryItem) -> None: # type: ignore # BUG?: Signature of "save" incompatible with supertype "Memory"
|
||||
"""
|
||||
Save a long-term memory item to storage.
|
||||
|
||||
Args:
|
||||
item: The long-term memory item to save.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error saving the item to memory.
|
||||
"""
|
||||
try:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Saving task", item.task)
|
||||
self._log_operation("Agent", item.agent)
|
||||
self._log_operation("Quality", str(item.metadata.get('quality')))
|
||||
|
||||
metadata = item.metadata
|
||||
metadata.update({"agent": item.agent, "expected_output": item.expected_output})
|
||||
self.storage.save( # type: ignore # BUG?: Unexpected keyword argument "task_description","score","datetime" for "save" of "Storage"
|
||||
task_description=item.task,
|
||||
score=metadata["quality"],
|
||||
metadata=metadata,
|
||||
datetime=item.datetime,
|
||||
)
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error saving task", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "save task", self.__class__.__name__)
|
||||
metadata = item.metadata
|
||||
metadata.update({"agent": item.agent, "expected_output": item.expected_output})
|
||||
self.storage.save( # type: ignore # BUG?: Unexpected keyword argument "task_description","score","datetime" for "save" of "Storage"
|
||||
task_description=item.task,
|
||||
score=metadata["quality"],
|
||||
metadata=metadata,
|
||||
datetime=item.datetime,
|
||||
)
|
||||
|
||||
def search(self, task: str, latest_n: int = 3) -> List[Dict[str, Any]]: # type: ignore # signature of "search" incompatible with supertype "Memory"
|
||||
"""
|
||||
Search for long-term memories related to a task.
|
||||
|
||||
Args:
|
||||
task: The task description to search for.
|
||||
latest_n: Maximum number of results to return.
|
||||
|
||||
Returns:
|
||||
A list of matching long-term memories.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error searching memory.
|
||||
"""
|
||||
try:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Searching for task", task)
|
||||
results = self.storage.load(task, latest_n) # type: ignore # BUG?: "Storage" has no attribute "load"
|
||||
if self.memory_verbose and results:
|
||||
self._log_operation("Found", f"{len(results)} results")
|
||||
return results
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error searching", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "search", self.__class__.__name__)
|
||||
return self.storage.load(task, latest_n) # type: ignore # BUG?: "Storage" has no attribute "load"
|
||||
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
Reset the long-term memory.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error resetting the memory.
|
||||
"""
|
||||
try:
|
||||
self.storage.reset()
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error resetting", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "reset", self.__class__.__name__)
|
||||
self.storage.reset()
|
||||
|
||||
@@ -1,67 +1,15 @@
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from crewai.memory.storage.rag_storage import RAGStorage
|
||||
from crewai.utilities.logger import Logger
|
||||
|
||||
|
||||
class MemoryOperationError(Exception):
|
||||
"""
|
||||
Exception raised for errors in memory operations.
|
||||
|
||||
Attributes:
|
||||
message: Explanation of the error
|
||||
operation: The operation that failed (e.g., "save", "search")
|
||||
memory_type: The type of memory where the error occurred
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, operation: str, memory_type: str):
|
||||
self.operation = operation
|
||||
self.memory_type = memory_type
|
||||
super().__init__(f"{memory_type} {operation} error: {message}")
|
||||
|
||||
|
||||
class Memory:
|
||||
"""
|
||||
Base class for memory, now supporting agent tags and generic metadata.
|
||||
|
||||
Attributes:
|
||||
storage: The storage backend for the memory.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
|
||||
def __init__(self, storage: RAGStorage, memory_verbose: bool = False):
|
||||
"""
|
||||
Initialize a Memory instance.
|
||||
|
||||
Args:
|
||||
storage: The storage backend for the memory.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
def __init__(self, storage: RAGStorage):
|
||||
self.storage = storage
|
||||
self.memory_verbose = memory_verbose
|
||||
self._logger = Logger(verbose=memory_verbose)
|
||||
|
||||
def _log_operation(self, operation: str, details: str, agent: Optional[str] = None, level: str = "info", color: str = "cyan") -> None:
|
||||
"""
|
||||
Log a memory operation if memory_verbose is enabled.
|
||||
|
||||
Args:
|
||||
operation: The type of operation (e.g., "Saving", "Searching").
|
||||
details: Details about the operation.
|
||||
agent: The agent performing the operation, if any.
|
||||
level: The log level.
|
||||
color: The color to use for the log message.
|
||||
"""
|
||||
if not self.memory_verbose:
|
||||
return
|
||||
|
||||
sanitized_details = str(details)
|
||||
if len(sanitized_details) > 100:
|
||||
sanitized_details = f"{sanitized_details[:100]}..."
|
||||
|
||||
memory_type = self.__class__.__name__
|
||||
agent_info = f" from agent '{agent}'" if agent else ""
|
||||
self._logger.log(level, f"{memory_type}: {operation}{agent_info}: {sanitized_details}", color=color)
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -69,30 +17,11 @@ class Memory:
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
agent: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Save a value to memory.
|
||||
|
||||
Args:
|
||||
value: The value to save.
|
||||
metadata: Additional metadata to store with the value.
|
||||
agent: The agent saving the value, if any.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error saving the value to memory.
|
||||
"""
|
||||
metadata = metadata or {}
|
||||
if agent:
|
||||
metadata["agent"] = agent
|
||||
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Saving", str(value), agent)
|
||||
|
||||
try:
|
||||
self.storage.save(value, metadata)
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error saving", str(e), agent, level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "save", self.__class__.__name__)
|
||||
self.storage.save(value, metadata)
|
||||
|
||||
def search(
|
||||
self,
|
||||
@@ -100,33 +29,6 @@ class Memory:
|
||||
limit: int = 3,
|
||||
score_threshold: float = 0.35,
|
||||
) -> List[Any]:
|
||||
"""
|
||||
Search for values in memory.
|
||||
|
||||
Args:
|
||||
query: The search query.
|
||||
limit: Maximum number of results to return.
|
||||
score_threshold: Minimum similarity score for results.
|
||||
|
||||
Returns:
|
||||
A list of matching values.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error searching memory.
|
||||
"""
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Searching for", query)
|
||||
|
||||
try:
|
||||
results = self.storage.search(
|
||||
query=query, limit=limit, score_threshold=score_threshold
|
||||
)
|
||||
|
||||
if self.memory_verbose and results:
|
||||
self._log_operation("Found", f"{len(results)} results")
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error searching", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "search", self.__class__.__name__)
|
||||
return self.storage.search(
|
||||
query=query, limit=limit, score_threshold=score_threshold
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from crewai.memory.memory import Memory, MemoryOperationError
|
||||
from crewai.memory.memory import Memory
|
||||
from crewai.memory.short_term.short_term_memory_item import ShortTermMemoryItem
|
||||
from crewai.memory.storage.rag_storage import RAGStorage
|
||||
|
||||
@@ -12,24 +12,9 @@ class ShortTermMemory(Memory):
|
||||
Inherits from the Memory class and utilizes an instance of a class that
|
||||
adheres to the Storage for data storage, specifically working with
|
||||
MemoryItem instances.
|
||||
|
||||
Attributes:
|
||||
memory_provider: The memory provider to use, if any.
|
||||
storage: The storage backend for the memory.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
|
||||
def __init__(self, crew=None, embedder_config=None, storage=None, path=None, memory_verbose=False):
|
||||
"""
|
||||
Initialize a ShortTermMemory instance.
|
||||
|
||||
Args:
|
||||
crew: The crew to associate with this memory.
|
||||
embedder_config: Configuration for the embedder.
|
||||
storage: The storage backend for the memory.
|
||||
path: Path to the storage file, if any.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
def __init__(self, crew=None, embedder_config=None, storage=None, path=None):
|
||||
if hasattr(crew, "memory_config") and crew.memory_config is not None:
|
||||
self.memory_provider = crew.memory_config.get("provider")
|
||||
else:
|
||||
@@ -54,7 +39,7 @@ class ShortTermMemory(Memory):
|
||||
path=path,
|
||||
)
|
||||
)
|
||||
super().__init__(storage, memory_verbose=memory_verbose)
|
||||
super().__init__(storage)
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -62,68 +47,26 @@ class ShortTermMemory(Memory):
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
agent: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Save a value to short-term memory.
|
||||
|
||||
Args:
|
||||
value: The value to save.
|
||||
metadata: Additional metadata to store with the value.
|
||||
agent: The agent saving the value, if any.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error saving to memory.
|
||||
"""
|
||||
try:
|
||||
item = ShortTermMemoryItem(data=value, metadata=metadata, agent=agent)
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Saving item", str(item.data), agent)
|
||||
|
||||
if self.memory_provider == "mem0":
|
||||
item.data = f"Remember the following insights from Agent run: {item.data}"
|
||||
item = ShortTermMemoryItem(data=value, metadata=metadata, agent=agent)
|
||||
if self.memory_provider == "mem0":
|
||||
item.data = f"Remember the following insights from Agent run: {item.data}"
|
||||
|
||||
super().save(value=item.data, metadata=item.metadata, agent=item.agent)
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error saving item", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "save", self.__class__.__name__)
|
||||
super().save(value=item.data, metadata=item.metadata, agent=item.agent)
|
||||
|
||||
def search(
|
||||
self,
|
||||
query: str,
|
||||
limit: int = 3,
|
||||
score_threshold: float = 0.35,
|
||||
) -> List[Any]:
|
||||
"""
|
||||
Search for values in short-term memory.
|
||||
|
||||
Args:
|
||||
query: The search query.
|
||||
limit: Maximum number of results to return.
|
||||
score_threshold: Minimum similarity score for results.
|
||||
|
||||
Returns:
|
||||
A list of matching values.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error searching memory.
|
||||
"""
|
||||
try:
|
||||
return super().search(query=query, limit=limit, score_threshold=score_threshold)
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error searching", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "search", self.__class__.__name__)
|
||||
):
|
||||
return self.storage.search(
|
||||
query=query, limit=limit, score_threshold=score_threshold
|
||||
) # type: ignore # BUG? The reference is to the parent class, but the parent class does not have this parameters
|
||||
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
Reset the short-term memory.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error resetting the memory.
|
||||
"""
|
||||
try:
|
||||
self.storage.reset()
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error resetting", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "reset", self.__class__.__name__)
|
||||
raise Exception(
|
||||
f"An error occurred while resetting the short-term memory: {e}"
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from crewai.memory.memory import Memory, MemoryOperationError
|
||||
from crewai.memory.memory import Memory
|
||||
|
||||
|
||||
class UserMemory(Memory):
|
||||
@@ -9,23 +9,9 @@ class UserMemory(Memory):
|
||||
Inherits from the Memory class and utilizes an instance of a class that
|
||||
adheres to the Storage for data storage, specifically working with
|
||||
MemoryItem instances.
|
||||
|
||||
Attributes:
|
||||
storage: The storage backend for the memory.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
"""
|
||||
|
||||
def __init__(self, crew=None, memory_verbose=False):
|
||||
"""
|
||||
Initialize a UserMemory instance.
|
||||
|
||||
Args:
|
||||
crew: The crew to associate with this memory.
|
||||
memory_verbose: Whether to log memory operations.
|
||||
|
||||
Raises:
|
||||
ImportError: If Mem0 is not installed.
|
||||
"""
|
||||
def __init__(self, crew=None):
|
||||
try:
|
||||
from crewai.memory.storage.mem0_storage import Mem0Storage
|
||||
except ImportError:
|
||||
@@ -33,72 +19,27 @@ class UserMemory(Memory):
|
||||
"Mem0 is not installed. Please install it with `pip install mem0ai`."
|
||||
)
|
||||
storage = Mem0Storage(type="user", crew=crew)
|
||||
super().__init__(storage, memory_verbose=memory_verbose)
|
||||
super().__init__(storage)
|
||||
|
||||
def save(
|
||||
self,
|
||||
value: Any,
|
||||
value,
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
agent: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Save user memory.
|
||||
|
||||
Args:
|
||||
value: The value to save.
|
||||
metadata: Additional metadata to store with the value.
|
||||
agent: The agent saving the value, if any.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error saving to memory.
|
||||
"""
|
||||
try:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Saving user memory", str(value))
|
||||
|
||||
# TODO: Change this function since we want to take care of the case where we save memories for the usr
|
||||
data = f"Remember the details about the user: {value}"
|
||||
super().save(data, metadata)
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error saving user memory", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "save", self.__class__.__name__)
|
||||
# TODO: Change this function since we want to take care of the case where we save memories for the usr
|
||||
data = f"Remember the details about the user: {value}"
|
||||
super().save(data, metadata)
|
||||
|
||||
def search(
|
||||
self,
|
||||
query: str,
|
||||
limit: int = 3,
|
||||
score_threshold: float = 0.35,
|
||||
) -> List[Any]:
|
||||
"""
|
||||
Search for user memories.
|
||||
|
||||
Args:
|
||||
query: The search query.
|
||||
limit: Maximum number of results to return.
|
||||
score_threshold: Minimum similarity score for results.
|
||||
|
||||
Returns:
|
||||
A list of matching user memories.
|
||||
|
||||
Raises:
|
||||
MemoryOperationError: If there's an error searching memory.
|
||||
"""
|
||||
try:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Searching user memory", query)
|
||||
|
||||
results = self.storage.search(
|
||||
query=query,
|
||||
limit=limit,
|
||||
score_threshold=score_threshold,
|
||||
)
|
||||
|
||||
if self.memory_verbose and results:
|
||||
self._log_operation("Found", f"{len(results)} results")
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
if self.memory_verbose:
|
||||
self._log_operation("Error searching user memory", str(e), level="error", color="red")
|
||||
raise MemoryOperationError(str(e), "search", self.__class__.__name__)
|
||||
):
|
||||
results = self.storage.search(
|
||||
query=query,
|
||||
limit=limit,
|
||||
score_threshold=score_threshold,
|
||||
)
|
||||
return results
|
||||
|
||||
@@ -584,3 +584,28 @@ 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()
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from crewai.agent import Agent
|
||||
from crewai.crew import Crew
|
||||
from crewai.memory.memory import Memory, MemoryOperationError
|
||||
from crewai.memory.short_term.short_term_memory import ShortTermMemory
|
||||
from crewai.memory.short_term.short_term_memory_item import ShortTermMemoryItem
|
||||
from crewai.task import Task
|
||||
from crewai.utilities.logger import Logger
|
||||
|
||||
|
||||
def test_memory_verbose_flag_in_crew():
|
||||
"""Test that memory_verbose flag is correctly set in Crew"""
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Research goal",
|
||||
backstory="Researcher backstory",
|
||||
)
|
||||
task = Task(
|
||||
description="Test task",
|
||||
expected_output="Test output",
|
||||
agent=agent,
|
||||
)
|
||||
crew = Crew(agents=[agent], tasks=[task], memory=True, memory_verbose=True)
|
||||
assert crew.memory_verbose is True
|
||||
|
||||
|
||||
def test_memory_verbose_logging_in_memory():
|
||||
"""Test that memory operations are logged when memory_verbose is enabled"""
|
||||
storage = MagicMock()
|
||||
|
||||
mock_logger = MagicMock(spec=Logger)
|
||||
|
||||
memory = Memory(storage=storage, memory_verbose=True)
|
||||
|
||||
memory._logger = mock_logger
|
||||
|
||||
memory.save("test value", {"test": "metadata"}, "test_agent")
|
||||
mock_logger.log.assert_called_once()
|
||||
args = mock_logger.log.call_args[0]
|
||||
assert args[0] == "info"
|
||||
assert "Saving" in args[1]
|
||||
|
||||
mock_logger.log.reset_mock()
|
||||
memory.search("test query")
|
||||
assert mock_logger.log.call_count == 2
|
||||
first_call_args = mock_logger.log.call_args_list[0][0]
|
||||
assert first_call_args[0] == "info"
|
||||
assert "Searching" in first_call_args[1]
|
||||
second_call_args = mock_logger.log.call_args_list[1][0]
|
||||
assert "Found" in second_call_args[1]
|
||||
|
||||
|
||||
def test_no_logging_when_memory_verbose_disabled():
|
||||
"""Test that no logging occurs when memory_verbose is disabled"""
|
||||
storage = MagicMock()
|
||||
|
||||
mock_logger = MagicMock(spec=Logger)
|
||||
|
||||
memory = Memory(storage=storage, memory_verbose=False)
|
||||
|
||||
memory._logger = mock_logger
|
||||
|
||||
memory.save("test value", {"test": "metadata"}, "test_agent")
|
||||
mock_logger.log.assert_not_called()
|
||||
|
||||
memory.search("test query")
|
||||
mock_logger.log.assert_not_called()
|
||||
|
||||
|
||||
def test_memory_verbose_in_short_term_memory():
|
||||
"""Test that memory_verbose flag is correctly passed to ShortTermMemory"""
|
||||
with patch('crewai.memory.short_term.short_term_memory.RAGStorage') as mock_storage_class:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
memory = ShortTermMemory(memory_verbose=True)
|
||||
assert memory.memory_verbose is True
|
||||
|
||||
mock_logger = MagicMock()
|
||||
memory._logger = mock_logger
|
||||
|
||||
memory.save("test value", {"test": "metadata"}, "test_agent")
|
||||
assert mock_logger.log.call_count >= 1
|
||||
|
||||
|
||||
def test_memory_verbose_passed_from_crew_to_memory():
|
||||
"""Test that memory_verbose flag is correctly passed from Crew to memory instances"""
|
||||
with patch('crewai.crew.LongTermMemory') as mock_ltm, \
|
||||
patch('crewai.crew.ShortTermMemory') as mock_stm, \
|
||||
patch('crewai.crew.EntityMemory') as mock_em, \
|
||||
patch('crewai.crew.UserMemory') as mock_um:
|
||||
|
||||
mock_ltm_instance = MagicMock()
|
||||
mock_stm_instance = MagicMock()
|
||||
mock_em_instance = MagicMock()
|
||||
mock_um_instance = MagicMock()
|
||||
|
||||
mock_ltm.return_value = mock_ltm_instance
|
||||
mock_stm.return_value = mock_stm_instance
|
||||
mock_em.return_value = mock_em_instance
|
||||
mock_um.return_value = mock_um_instance
|
||||
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Research goal",
|
||||
backstory="Researcher backstory",
|
||||
)
|
||||
task = Task(
|
||||
description="Test task",
|
||||
expected_output="Test output",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task], memory=True, memory_verbose=True, memory_config={})
|
||||
|
||||
mock_ltm.assert_called_once_with(memory_verbose=True)
|
||||
mock_stm.assert_called_with(crew=crew, embedder_config=None, memory_verbose=True)
|
||||
mock_em.assert_called_with(crew=crew, embedder_config=None, memory_verbose=True)
|
||||
mock_um.assert_called_with(crew=crew, memory_verbose=True)
|
||||
|
||||
|
||||
def test_memory_verbose_error_handling():
|
||||
"""Test that memory operations errors are properly handled when memory_verbose is enabled"""
|
||||
storage = MagicMock()
|
||||
storage.save.side_effect = Exception("Test error")
|
||||
storage.search.side_effect = Exception("Test error")
|
||||
|
||||
mock_logger = MagicMock()
|
||||
|
||||
with patch('crewai.memory.memory.Logger', return_value=mock_logger):
|
||||
memory = Memory(storage=storage, memory_verbose=True)
|
||||
|
||||
with pytest.raises(MemoryOperationError) as exc_info:
|
||||
memory.save("test value", {"test": "metadata"}, "test_agent")
|
||||
|
||||
assert "save" in str(exc_info.value)
|
||||
assert "Test error" in str(exc_info.value)
|
||||
assert "Memory" in str(exc_info.value)
|
||||
|
||||
with pytest.raises(MemoryOperationError) as exc_info:
|
||||
memory.search("test query")
|
||||
|
||||
assert "search" in str(exc_info.value)
|
||||
assert "Test error" in str(exc_info.value)
|
||||
Reference in New Issue
Block a user