Compare commits

..

1 Commits

Author SHA1 Message Date
Devin AI
155fe58ee7 Fix issue #2678: Fix parameter name mismatch in reset-memories command
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-23 21:58:46 +00:00
7 changed files with 66 additions and 221 deletions

View File

@@ -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:

View File

@@ -1,2 +1 @@
from .base_tool import BaseTool, tool
from .human_tool import HumanTool

View File

@@ -1,98 +0,0 @@
"""Tool for handling human input using LangGraph's interrupt mechanism."""
import logging
from typing import Any, Dict, Optional
from pydantic import BaseModel, Field
from crewai.tools import BaseTool
class HumanToolSchema(BaseModel):
"""Schema for HumanTool input validation."""
query: str = Field(
...,
description="The question to ask the user. Must be a non-empty string."
)
timeout: Optional[float] = Field(
default=None,
description="Optional timeout in seconds for waiting for user response"
)
class HumanTool(BaseTool):
"""Tool for getting human input using LangGraph's interrupt mechanism.
This tool allows agents to request input from users through LangGraph's
interrupt mechanism. It supports timeout configuration and input validation.
"""
name: str = "human"
description: str = "Useful to ask user to enter input."
args_schema: type[BaseModel] = HumanToolSchema
result_as_answer: bool = False # Don't use the response as final answer
def _run(self, query: str, timeout: Optional[float] = None) -> str:
"""Execute the human input tool.
Args:
query: The question to ask the user
timeout: Optional timeout in seconds
Returns:
The user's response
Raises:
ImportError: If LangGraph is not installed
TimeoutError: If response times out
ValueError: If query is invalid
"""
if not query or not isinstance(query, str):
raise ValueError("Query must be a non-empty string")
try:
from langgraph.prebuilt.state_graphs import interrupt
logging.info(f"Requesting human input: {query}")
human_response = interrupt({"query": query, "timeout": timeout})
return human_response["data"]
except ImportError:
logging.error("LangGraph not installed")
raise ImportError(
"LangGraph is required for HumanTool. "
"Install with `pip install langgraph`"
)
except Exception as e:
logging.error(f"Error during human input: {str(e)}")
raise
async def _arun(self, query: str, timeout: Optional[float] = None) -> str:
"""Execute the human input tool asynchronously.
Args:
query: The question to ask the user
timeout: Optional timeout in seconds
Returns:
The user's response
Raises:
ImportError: If LangGraph is not installed
TimeoutError: If response times out
ValueError: If query is invalid
"""
if not query or not isinstance(query, str):
raise ValueError("Query must be a non-empty string")
try:
from langgraph.prebuilt.state_graphs import interrupt
logging.info(f"Requesting async human input: {query}")
human_response = interrupt({"query": query, "timeout": timeout})
return human_response["data"]
except ImportError:
logging.error("LangGraph not installed")
raise ImportError(
"LangGraph is required for HumanTool. "
"Install with `pip install langgraph`"
)
except Exception as e:
logging.error(f"Error during async human input: {str(e)}")
raise

View File

@@ -182,10 +182,6 @@ class ToolUsage:
else:
result = tool.invoke(input={})
except Exception as e:
# Check if this is a LangGraph interrupt that should be propagated
if hasattr(e, '__class__') and e.__class__.__name__ == 'Interrupt':
raise e # Propagate interrupt up
self.on_tool_error(tool=tool, tool_calling=calling, e=e)
self._run_attempts += 1
if self._run_attempts > self._max_parsing_attempts:

View 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

View File

@@ -1,83 +0,0 @@
"""Test HumanTool functionality."""
from unittest.mock import patch
import pytest
from crewai.tools import HumanTool
def test_human_tool_basic():
"""Test basic HumanTool creation and attributes."""
tool = HumanTool()
assert tool.name == "human"
assert "ask user to enter input" in tool.description.lower()
assert not tool.result_as_answer
@pytest.mark.vcr(filter_headers=["authorization"])
def test_human_tool_with_langgraph_interrupt():
"""Test HumanTool with LangGraph interrupt handling."""
tool = HumanTool()
with patch('langgraph.prebuilt.state_graphs.interrupt') as mock_interrupt:
mock_interrupt.return_value = {"data": "test response"}
result = tool._run("test query")
assert result == "test response"
mock_interrupt.assert_called_with({"query": "test query", "timeout": None})
def test_human_tool_timeout():
"""Test HumanTool timeout handling."""
tool = HumanTool()
timeout = 30.0
with patch('langgraph.prebuilt.state_graphs.interrupt') as mock_interrupt:
mock_interrupt.return_value = {"data": "test response"}
result = tool._run("test query", timeout=timeout)
assert result == "test response"
mock_interrupt.assert_called_with({"query": "test query", "timeout": timeout})
def test_human_tool_invalid_input():
"""Test HumanTool input validation."""
tool = HumanTool()
with pytest.raises(ValueError, match="Query must be a non-empty string"):
tool._run("")
with pytest.raises(ValueError, match="Query must be a non-empty string"):
tool._run(None)
@pytest.mark.asyncio
async def test_human_tool_async():
"""Test async HumanTool functionality."""
tool = HumanTool()
with patch('langgraph.prebuilt.state_graphs.interrupt') as mock_interrupt:
mock_interrupt.return_value = {"data": "test response"}
result = await tool._arun("test query")
assert result == "test response"
mock_interrupt.assert_called_with({"query": "test query", "timeout": None})
@pytest.mark.asyncio
async def test_human_tool_async_timeout():
"""Test async HumanTool timeout handling."""
tool = HumanTool()
timeout = 30.0
with patch('langgraph.prebuilt.state_graphs.interrupt') as mock_interrupt:
mock_interrupt.return_value = {"data": "test response"}
result = await tool._arun("test query", timeout=timeout)
assert result == "test response"
mock_interrupt.assert_called_with({"query": "test query", "timeout": timeout})
def test_human_tool_without_langgraph():
"""Test HumanTool behavior when LangGraph is not installed."""
tool = HumanTool()
with patch.dict('sys.modules', {'langgraph': None}):
with pytest.raises(ImportError) as exc_info:
tool._run("test query")
assert "LangGraph is required" in str(exc_info.value)
assert "pip install langgraph" in str(exc_info.value)

View File

@@ -1,13 +1,12 @@
import json
import random
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
import pytest
from pydantic import BaseModel, Field
from crewai import Agent, Task
from crewai.tools import BaseTool
from crewai.tools.tool_calling import ToolCalling
from crewai.tools.tool_usage import ToolUsage
@@ -86,36 +85,6 @@ def test_random_number_tool_schema():
)
def test_tool_usage_interrupt_handling():
"""Test that tool usage properly propagates LangGraph interrupts."""
class InterruptingTool(BaseTool):
name: str = "interrupt_test"
description: str = "A tool that raises LangGraph interrupts"
def _run(self, query: str) -> str:
raise type('Interrupt', (Exception,), {})("test interrupt")
tool = InterruptingTool()
tool_usage = ToolUsage(
tools_handler=MagicMock(),
tools=[tool],
original_tools=[tool],
tools_description="Sample tool for testing",
tools_names="interrupt_test",
task=MagicMock(),
function_calling_llm=MagicMock(),
agent=MagicMock(),
action=MagicMock(),
)
# Test that interrupt is propagated
with pytest.raises(Exception) as exc_info:
tool_usage.use(
ToolCalling(tool_name="interrupt_test", arguments={"query": "test"}, log="test"),
"test"
)
assert "test interrupt" in str(exc_info.value)
def test_tool_usage_render():
tool = RandomNumberTool()