Creates a tool instance from a config. This default implementation uses inspect to automatically map config values to constructor arguments based on their type hints. Subclasses should override this method for custom initialization logic. Args: config: The config for the tool
(
cls: Type[SelfTool], config: ToolArgsConfig, config_abs_path: str
)
| 160 | |
| 161 | @classmethod |
| 162 | def from_config( |
| 163 | cls: Type[SelfTool], config: ToolArgsConfig, config_abs_path: str |
| 164 | ) -> SelfTool: |
| 165 | """Creates a tool instance from a config. |
| 166 | |
| 167 | This default implementation uses inspect to automatically map config values |
| 168 | to constructor arguments based on their type hints. Subclasses should |
| 169 | override this method for custom initialization logic. |
| 170 | |
| 171 | Args: |
| 172 | config: The config for the tool. |
| 173 | config_abs_path: The absolute path to the config file that contains the |
| 174 | tool config. |
| 175 | |
| 176 | Returns: |
| 177 | The tool instance. |
| 178 | """ |
| 179 | from ..agents import config_agent_utils |
| 180 | |
| 181 | # Get the constructor signature and resolve type hints |
| 182 | sig = inspect.signature(cls.__init__) |
| 183 | type_hints = get_type_hints(cls.__init__) |
| 184 | config_dict = config.model_dump() |
| 185 | kwargs = {} |
| 186 | |
| 187 | # Iterate through constructor parameters (skip "self") |
| 188 | for param_name, _ in sig.parameters.items(): |
| 189 | if param_name == "self": |
| 190 | continue |
| 191 | param_type = type_hints.get(param_name) |
| 192 | |
| 193 | if param_name in config_dict: |
| 194 | value = config_dict[param_name] |
| 195 | |
| 196 | # Get the actual type T of the parameter if it's Optional[T] |
| 197 | if get_origin(param_type) is Union: |
| 198 | # This is Optional[T] which is Union[T, None] |
| 199 | args = get_args(param_type) |
| 200 | if len(args) == 2 and type(None) in args: |
| 201 | # Get the non-None type |
| 202 | actual_type = args[0] if args[1] is type(None) else args[1] |
| 203 | param_type = actual_type |
| 204 | |
| 205 | if param_type in (int, str, bool, float): |
| 206 | kwargs[param_name] = value |
| 207 | elif ( |
| 208 | inspect.isclass(param_type) |
| 209 | and issubclass(param_type, BaseModel) |
| 210 | and value is not None |
| 211 | ): |
| 212 | kwargs[param_name] = param_type.model_validate(value) |
| 213 | elif param_type is Callable or get_origin(param_type) is Callable: |
| 214 | kwargs[param_name] = config_agent_utils.resolve_fully_qualified_name( |
| 215 | value |
| 216 | ) |
| 217 | elif param_type in (list, set, dict): |
| 218 | kwargs[param_name] = param_type(value) |
| 219 | elif get_origin(param_type) is list: |