|
13 | 13 | # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= |
14 | 14 | import functools |
15 | 15 | import inspect |
16 | | -from typing import Any, Callable, Optional |
| 16 | +import warnings |
| 17 | +from typing import ( |
| 18 | + Any, |
| 19 | + Callable, |
| 20 | + List, |
| 21 | + Optional, |
| 22 | + Tuple, |
| 23 | + Union, |
| 24 | + get_args, |
| 25 | + get_origin, |
| 26 | + get_type_hints, |
| 27 | +) |
| 28 | + |
| 29 | +from pydantic import create_model |
| 30 | +from pydantic.errors import PydanticSchemaGenerationError |
| 31 | + |
| 32 | +from camel.logger import get_logger |
| 33 | + |
| 34 | +logger = get_logger(__name__) |
| 35 | + |
| 36 | + |
| 37 | +def _is_pydantic_serializable(type_annotation: Any) -> Tuple[bool, str]: |
| 38 | + r"""Check if a type annotation is Pydantic serializable. |
| 39 | +
|
| 40 | + Args: |
| 41 | + type_annotation: The type annotation to check |
| 42 | +
|
| 43 | + Returns: |
| 44 | + Tuple[bool, str]: (is_serializable, error_message) |
| 45 | + """ |
| 46 | + # Handle None type |
| 47 | + if type_annotation is type(None) or type_annotation is None: |
| 48 | + return True, "" |
| 49 | + |
| 50 | + # Handle generic types (List, Dict, Optional, etc.) |
| 51 | + origin = get_origin(type_annotation) |
| 52 | + if origin is not None: |
| 53 | + args = get_args(type_annotation) |
| 54 | + |
| 55 | + # For Union types (including Optional), check all args |
| 56 | + if origin is Union: |
| 57 | + for arg in args: |
| 58 | + is_serializable, error_msg = _is_pydantic_serializable(arg) |
| 59 | + if not is_serializable: |
| 60 | + return False, error_msg |
| 61 | + return True, "" |
| 62 | + |
| 63 | + # For List, Set, Tuple, etc., check the contained types |
| 64 | + if origin in (list, set, tuple, frozenset): |
| 65 | + for arg in args: |
| 66 | + is_serializable, error_msg = _is_pydantic_serializable(arg) |
| 67 | + if not is_serializable: |
| 68 | + return False, error_msg |
| 69 | + return True, "" |
| 70 | + |
| 71 | + # For Dict, check both key and value types |
| 72 | + if origin is dict: |
| 73 | + for arg in args: |
| 74 | + is_serializable, error_msg = _is_pydantic_serializable(arg) |
| 75 | + if not is_serializable: |
| 76 | + return False, error_msg |
| 77 | + return True, "" |
| 78 | + |
| 79 | + # Try to create a simple pydantic model with this type |
| 80 | + try: |
| 81 | + create_model("TestModel", test_field=(type_annotation, ...)) |
| 82 | + # If model creation succeeds, the type is serializable |
| 83 | + return True, "" |
| 84 | + except (PydanticSchemaGenerationError, TypeError, ValueError) as e: |
| 85 | + error_msg = ( |
| 86 | + f"Type '{type_annotation}' is not Pydantic serializable. " |
| 87 | + f"Consider using a custom serializable type or converting " |
| 88 | + f"to bytes/base64. Error: {e!s}" |
| 89 | + ) |
| 90 | + return False, error_msg |
| 91 | + |
| 92 | + |
| 93 | +def _validate_function_types(func: Callable[..., Any]) -> List[str]: |
| 94 | + r"""Validate function parameter and return types are Pydantic serializable. |
| 95 | +
|
| 96 | + Args: |
| 97 | + func (Callable[..., Any]): The function to validate. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + List[str]: List of error messages for incompatible types. |
| 101 | + """ |
| 102 | + errors = [] |
| 103 | + |
| 104 | + try: |
| 105 | + type_hints = get_type_hints(func) |
| 106 | + except (NameError, AttributeError) as e: |
| 107 | + # If we can't get type hints, skip validation |
| 108 | + logger.warning(f"Could not get type hints for {func.__name__}: {e}") |
| 109 | + return [] |
| 110 | + |
| 111 | + # Check return type |
| 112 | + return_type = type_hints.get('return', Any) |
| 113 | + if return_type != Any: |
| 114 | + is_serializable, error_msg = _is_pydantic_serializable(return_type) |
| 115 | + if not is_serializable: |
| 116 | + errors.append(f"Return type: {error_msg}") |
| 117 | + |
| 118 | + # Check parameter types |
| 119 | + sig = inspect.signature(func) |
| 120 | + for param_name, _param in sig.parameters.items(): |
| 121 | + if param_name == 'self': |
| 122 | + continue |
| 123 | + |
| 124 | + param_type = type_hints.get(param_name, Any) |
| 125 | + if param_type != Any: |
| 126 | + is_serializable, error_msg = _is_pydantic_serializable(param_type) |
| 127 | + if not is_serializable: |
| 128 | + errors.append(f"Parameter '{param_name}': {error_msg}") |
| 129 | + |
| 130 | + return errors |
17 | 131 |
|
18 | 132 |
|
19 | 133 | class MCPServer: |
@@ -55,7 +169,7 @@ class MyToolkit(BaseToolkit): |
55 | 169 |
|
56 | 170 | def __init__( |
57 | 171 | self, |
58 | | - function_names: Optional[list[str]] = None, |
| 172 | + function_names: Optional[List[str]] = None, |
59 | 173 | server_name: Optional[str] = None, |
60 | 174 | ): |
61 | 175 | self.function_names = function_names |
@@ -135,6 +249,26 @@ def new_init(instance, *args, **kwargs): |
135 | 249 | f"Method {name} not found in class {cls.__name__} or " |
136 | 250 | "cannot be called." |
137 | 251 | ) |
| 252 | + |
| 253 | + # Validate function types for Pydantic compatibility |
| 254 | + type_errors = _validate_function_types(func) |
| 255 | + if type_errors: |
| 256 | + error_message = ( |
| 257 | + f"Method '{name}' in class '{cls.__name__}' has " |
| 258 | + f"non-Pydantic-serializable types:\n" |
| 259 | + + "\n".join(f" - {error}" for error in type_errors) |
| 260 | + + "\n\nSuggestions:" |
| 261 | + + "\n - Use standard Python types (str, int, float, bool, bytes)" # noqa: E501 |
| 262 | + + "\n - Convert complex objects to JSON strings or bytes" # noqa: E501 |
| 263 | + + "\n - Create custom Pydantic models for complex data" # noqa: E501 |
| 264 | + + "\n - Use base64 encoding for binary data like images" # noqa: E501 |
| 265 | + ) |
| 266 | + |
| 267 | + # For now, issue a warning instead of raising an error |
| 268 | + # This allows gradual migration while alerting developers |
| 269 | + warnings.warn(error_message, UserWarning, stacklevel=3) |
| 270 | + logger.warning(error_message) |
| 271 | + |
138 | 272 | wrapper = self.make_wrapper(func) |
139 | 273 | instance.mcp.tool(name=name)(wrapper) |
140 | 274 |
|
|
0 commit comments