From dea796a7613eea87731efed12e071f20da142146 Mon Sep 17 00:00:00 2001 From: lorenzejay Date: Tue, 24 Feb 2026 09:21:42 -0800 Subject: [PATCH] refactor: improve argument validation in BaseTool - Introduced a new private method to handle argument validation for tools, enhancing code clarity and reusability. - Updated the method to utilize the new validation method, ensuring consistent error handling for invalid arguments. - Enhanced exception handling to specifically catch , providing clearer error messages for tool argument validation failures. --- lib/crewai/src/crewai/tools/base_tool.py | 30 +++++++++++------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/lib/crewai/src/crewai/tools/base_tool.py b/lib/crewai/src/crewai/tools/base_tool.py index e787c25c2..a55c56384 100644 --- a/lib/crewai/src/crewai/tools/base_tool.py +++ b/lib/crewai/src/crewai/tools/base_tool.py @@ -18,6 +18,7 @@ from pydantic import ( BaseModel as PydanticBaseModel, ConfigDict, Field, + ValidationError, create_model, field_validator, ) @@ -150,19 +151,23 @@ class BaseTool(BaseModel, ABC): super().model_post_init(__context) + def _validate_kwargs(self, kwargs: dict[str, Any]) -> dict[str, Any]: + if kwargs and self.args_schema is not None and self.args_schema.model_fields: + try: + validated = self.args_schema.model_validate(kwargs) + return {k: getattr(validated, k) for k in validated.model_fields} + except ValidationError as e: + raise ValueError( + f"Tool '{self.name}' arguments validation failed: {e}" + ) from e + return kwargs + def run( self, *args: Any, **kwargs: Any, ) -> Any: - if kwargs and self.args_schema is not None and self.args_schema.model_fields: - try: - validated = self.args_schema.model_validate(kwargs) - kwargs = validated.model_dump() - except Exception as e: - raise ValueError( - f"Tool '{self.name}' arguments validation failed: {e}" - ) from e + kwargs = self._validate_kwargs(kwargs) result = self._run(*args, **kwargs) @@ -339,14 +344,7 @@ class Tool(BaseTool, Generic[P, R]): Returns: The result of the tool execution. """ - if kwargs and self.args_schema is not None and self.args_schema.model_fields: - try: - validated = self.args_schema.model_validate(kwargs) - kwargs = validated.model_dump() - except Exception as e: - raise ValueError( - f"Tool '{self.name}' arguments validation failed: {e}" - ) from e + kwargs = self._validate_kwargs(kwargs) result = self.func(*args, **kwargs)