mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-04-27 05:12:52 +00:00
Compare commits
1 Commits
devin/1740
...
devin/1745
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
155fe58ee7 |
@@ -134,19 +134,6 @@ class BaseAgent(ABC, BaseModel):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def process_model_config(cls, values):
|
||||
"""
|
||||
Process model configuration values.
|
||||
|
||||
Args:
|
||||
values: Configuration values or callable agent
|
||||
When using CrewBase decorator, this can be a callable that returns an agent
|
||||
|
||||
Returns:
|
||||
Processed configuration or callable agent
|
||||
"""
|
||||
# Handle case where values is a function (can happen with CrewBase decorator)
|
||||
if callable(values) and not isinstance(values, dict):
|
||||
return values
|
||||
return process_config(values, cls)
|
||||
|
||||
@field_validator("tools")
|
||||
|
||||
@@ -12,7 +12,7 @@ from crewai.utilities.task_output_storage_handler import TaskOutputStorageHandle
|
||||
def reset_memories_command(
|
||||
long,
|
||||
short,
|
||||
entity,
|
||||
entities, # Changed from entity to entities to match CLI parameter
|
||||
knowledge,
|
||||
kickoff_outputs,
|
||||
all,
|
||||
@@ -23,7 +23,7 @@ def reset_memories_command(
|
||||
Args:
|
||||
long (bool): Whether to reset the long-term memory.
|
||||
short (bool): Whether to reset the short-term memory.
|
||||
entity (bool): Whether to reset the entity memory.
|
||||
entities (bool): Whether to reset the entity memory.
|
||||
kickoff_outputs (bool): Whether to reset the latest kickoff task outputs.
|
||||
all (bool): Whether to reset all memories.
|
||||
knowledge (bool): Whether to reset the knowledge.
|
||||
@@ -45,7 +45,7 @@ def reset_memories_command(
|
||||
if short:
|
||||
ShortTermMemory().reset()
|
||||
click.echo("Short term memory has been reset.")
|
||||
if entity:
|
||||
if entities: # Changed from entity to entities
|
||||
EntityMemory().reset()
|
||||
click.echo("Entity memory has been reset.")
|
||||
if kickoff_outputs:
|
||||
|
||||
@@ -65,27 +65,6 @@ def cache_handler(func):
|
||||
return memoize(func)
|
||||
|
||||
|
||||
def _resolve_agent(task_instance):
|
||||
"""
|
||||
Resolve an agent from a task instance.
|
||||
|
||||
If the agent is a callable (e.g., a method from CrewBase), call it to get the agent instance.
|
||||
|
||||
Args:
|
||||
task_instance: The task instance containing the agent
|
||||
|
||||
Returns:
|
||||
The resolved agent instance or None if no agent is present
|
||||
"""
|
||||
if not hasattr(task_instance, 'agent') or not task_instance.agent:
|
||||
return None
|
||||
|
||||
if callable(task_instance.agent) and not isinstance(task_instance.agent, type):
|
||||
return task_instance.agent()
|
||||
|
||||
return task_instance.agent
|
||||
|
||||
|
||||
def crew(func) -> Callable[..., Crew]:
|
||||
|
||||
@wraps(func)
|
||||
@@ -100,14 +79,7 @@ def crew(func) -> Callable[..., Crew]:
|
||||
|
||||
# Instantiate tasks in order
|
||||
for task_name, task_method in tasks:
|
||||
# Get the task instance
|
||||
task_instance = task_method(self)
|
||||
|
||||
# Resolve the agent
|
||||
agent = _resolve_agent(task_instance)
|
||||
if agent:
|
||||
task_instance.agent = agent
|
||||
|
||||
instantiated_tasks.append(task_instance)
|
||||
agent_instance = getattr(task_instance, "agent", None)
|
||||
if agent_instance and agent_instance.role not in agent_roles:
|
||||
|
||||
@@ -61,25 +61,6 @@ class Task(BaseModel):
|
||||
output_pydantic: Pydantic model for task output.
|
||||
tools: List of tools/resources limited for task execution.
|
||||
"""
|
||||
|
||||
def __init__(self, **data):
|
||||
# Handle case where agent is a callable (can happen with CrewBase decorator)
|
||||
if 'agent' in data and callable(data['agent']) and not isinstance(data['agent'], type):
|
||||
try:
|
||||
# Call the agent method to get the agent instance
|
||||
agent = data['agent']()
|
||||
|
||||
# Verify that the agent is a valid instance
|
||||
from crewai.agents.agent_builder.base_agent import BaseAgent
|
||||
if agent is not None and not isinstance(agent, BaseAgent):
|
||||
raise ValueError(f"Expected BaseAgent instance, got {type(agent)}")
|
||||
|
||||
data['agent'] = agent
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to initialize agent from callable: {e}")
|
||||
|
||||
# Call the parent class __init__ method
|
||||
super().__init__(**data)
|
||||
|
||||
__hash__ = object.__hash__ # type: ignore
|
||||
logger: ClassVar[logging.Logger] = logging.getLogger(__name__)
|
||||
|
||||
62
tests/cli/test_reset_memories.py
Normal file
62
tests/cli/test_reset_memories.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import os
|
||||
import tempfile
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
from crewai.cli.cli import reset_memories
|
||||
from crewai.cli.reset_memories_command import reset_memories_command
|
||||
|
||||
|
||||
def test_reset_memories_command_parameters():
|
||||
"""Test that the CLI parameters match the function parameters."""
|
||||
# Create a mock for reset_memories_command
|
||||
with patch('crewai.cli.cli.reset_memories_command') as mock_reset:
|
||||
runner = CliRunner()
|
||||
|
||||
# Test with entities flag
|
||||
result = runner.invoke(reset_memories, ['--entities'])
|
||||
assert result.exit_code == 0
|
||||
|
||||
# Check that the function was called with the correct parameters
|
||||
# The third parameter should be True for entities
|
||||
mock_reset.assert_called_once_with(False, False, True, False, False, False)
|
||||
|
||||
|
||||
def test_reset_memories_all_flag():
|
||||
"""Test that the --all flag resets all memories."""
|
||||
with patch('crewai.cli.cli.reset_memories_command') as mock_reset:
|
||||
runner = CliRunner()
|
||||
|
||||
# Test with all flag
|
||||
result = runner.invoke(reset_memories, ['--all'])
|
||||
assert result.exit_code == 0
|
||||
|
||||
# Check that the function was called with the correct parameters
|
||||
# The last parameter should be True for all
|
||||
mock_reset.assert_called_once_with(False, False, False, False, False, True)
|
||||
|
||||
|
||||
def test_reset_memories_knowledge_flag():
|
||||
"""Test that the --knowledge flag resets knowledge storage."""
|
||||
with patch('crewai.cli.cli.reset_memories_command') as mock_reset:
|
||||
runner = CliRunner()
|
||||
|
||||
# Test with knowledge flag
|
||||
result = runner.invoke(reset_memories, ['--knowledge'])
|
||||
assert result.exit_code == 0
|
||||
|
||||
# Check that the function was called with the correct parameters
|
||||
# The fourth parameter should be True for knowledge
|
||||
mock_reset.assert_called_once_with(False, False, False, True, False, False)
|
||||
|
||||
|
||||
def test_reset_memories_no_flags():
|
||||
"""Test that an error message is shown when no flags are provided."""
|
||||
runner = CliRunner()
|
||||
|
||||
# Test with no flags
|
||||
result = runner.invoke(reset_memories, [])
|
||||
assert result.exit_code == 0
|
||||
assert "Please specify at least one memory type" in result.output
|
||||
@@ -1,51 +0,0 @@
|
||||
import unittest
|
||||
|
||||
from crewai import Agent, Task
|
||||
|
||||
|
||||
class TestTaskInitFix(unittest.TestCase):
|
||||
"""Test the fix for issue #2219 where agent methods are not handled correctly in tasks."""
|
||||
|
||||
def test_task_init_handles_callable_agent(self):
|
||||
"""Test that the Task.__init__ method correctly handles callable agents."""
|
||||
|
||||
# Create an agent instance
|
||||
agent_instance = Agent(
|
||||
role="Test Agent",
|
||||
goal="Test Goal",
|
||||
backstory="Test Backstory"
|
||||
)
|
||||
|
||||
# Create a callable that returns the agent instance
|
||||
def callable_agent():
|
||||
return agent_instance
|
||||
|
||||
# Create a task with the callable agent
|
||||
task = Task(
|
||||
description="Test Task",
|
||||
expected_output="Test Output",
|
||||
agent=callable_agent
|
||||
)
|
||||
|
||||
# Verify that the agent in the task is an instance, not a callable
|
||||
self.assertIsInstance(task.agent, Agent)
|
||||
self.assertEqual(task.agent.role, "Test Agent")
|
||||
self.assertIs(task.agent, agent_instance)
|
||||
|
||||
def test_task_init_handles_invalid_callable_agent(self):
|
||||
"""Test that the Task.__init__ method correctly handles invalid callable agents."""
|
||||
|
||||
# Create a callable that returns an invalid agent (not an Agent instance)
|
||||
def invalid_callable_agent():
|
||||
return "Not an agent"
|
||||
|
||||
# Create a task with the invalid callable agent
|
||||
with self.assertRaises(ValueError) as context:
|
||||
task = Task(
|
||||
description="Test Task",
|
||||
expected_output="Test Output",
|
||||
agent=invalid_callable_agent
|
||||
)
|
||||
|
||||
# Verify that the error message is correct
|
||||
self.assertIn("Expected BaseAgent instance", str(context.exception))
|
||||
Reference in New Issue
Block a user