refactor: simplify nested conditions in tool usage check

Co-Authored-By: Joe Moura <joao@crewai.com>
This commit is contained in:
Devin AI
2025-02-24 13:22:13 +00:00
parent b44842d1de
commit a3b3b411df

View File

@@ -284,23 +284,35 @@ class ToolUsage:
def _check_tool_repeated_usage( def _check_tool_repeated_usage(
self, calling: Union[ToolCalling, InstructorToolCalling] self, calling: Union[ToolCalling, InstructorToolCalling]
) -> bool: ) -> bool:
if not self.tools_handler: """Check if a tool is being called with the same arguments as the last call.
This method prevents duplicate tool executions by comparing the current tool call
with the last one. For WebSocket tools, it specifically checks if the 'question'
argument is identical. For other tools, it compares all arguments.
Args:
calling: The tool calling to check for repetition, containing the tool name
and arguments.
Returns:
bool: True if the tool is being called with the same name and arguments as
the last call, False otherwise.
"""
if not self.tools_handler or not self.tools_handler.last_used_tool:
return False return False
if last_tool_usage := self.tools_handler.last_used_tool:
# For WebSocket tools, we need to check if the question is the same last_tool_usage = self.tools_handler.last_used_tool
if (calling.arguments is not None and last_tool_usage.arguments is not None and if calling.tool_name != last_tool_usage.tool_name:
"question" in calling.arguments and "question" in last_tool_usage.arguments): return False
return (
calling.tool_name == last_tool_usage.tool_name if not calling.arguments or not last_tool_usage.arguments:
and calling.arguments["question"] == last_tool_usage.arguments["question"] return False
)
# For other tools, check all arguments try:
return ( if "question" in calling.arguments and "question" in last_tool_usage.arguments:
calling.tool_name == last_tool_usage.tool_name return calling.arguments["question"] == last_tool_usage.arguments["question"]
and calling.arguments is not None return calling.arguments == last_tool_usage.arguments
and last_tool_usage.arguments is not None except (KeyError, TypeError):
and calling.arguments == last_tool_usage.arguments
)
return False return False
def _select_tool(self, tool_name: str) -> Any: def _select_tool(self, tool_name: str) -> Any: