mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-05-01 07:13:00 +00:00
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.
This commit is contained in:
@@ -18,6 +18,7 @@ from pydantic import (
|
|||||||
BaseModel as PydanticBaseModel,
|
BaseModel as PydanticBaseModel,
|
||||||
ConfigDict,
|
ConfigDict,
|
||||||
Field,
|
Field,
|
||||||
|
ValidationError,
|
||||||
create_model,
|
create_model,
|
||||||
field_validator,
|
field_validator,
|
||||||
)
|
)
|
||||||
@@ -150,19 +151,23 @@ class BaseTool(BaseModel, ABC):
|
|||||||
|
|
||||||
super().model_post_init(__context)
|
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(
|
def run(
|
||||||
self,
|
self,
|
||||||
*args: Any,
|
*args: Any,
|
||||||
**kwargs: Any,
|
**kwargs: Any,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
if kwargs and self.args_schema is not None and self.args_schema.model_fields:
|
kwargs = self._validate_kwargs(kwargs)
|
||||||
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
|
|
||||||
|
|
||||||
result = self._run(*args, **kwargs)
|
result = self._run(*args, **kwargs)
|
||||||
|
|
||||||
@@ -339,14 +344,7 @@ class Tool(BaseTool, Generic[P, R]):
|
|||||||
Returns:
|
Returns:
|
||||||
The result of the tool execution.
|
The result of the tool execution.
|
||||||
"""
|
"""
|
||||||
if kwargs and self.args_schema is not None and self.args_schema.model_fields:
|
kwargs = self._validate_kwargs(kwargs)
|
||||||
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
|
|
||||||
|
|
||||||
result = self.func(*args, **kwargs)
|
result = self.func(*args, **kwargs)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user