Converts a Python function into a JSON-serializable dictionary that describes the function's signature, including its name, description, and parameters. Args: func: The function to be converted. Returns: A dictionary representing the function's signature in JSO
(func)
| 279 | |
| 280 | |
| 281 | def function_to_json(func) -> dict: |
| 282 | """ |
| 283 | Converts a Python function into a JSON-serializable dictionary |
| 284 | that describes the function's signature, including its name, |
| 285 | description, and parameters. |
| 286 | |
| 287 | Args: |
| 288 | func: The function to be converted. |
| 289 | |
| 290 | Returns: |
| 291 | A dictionary representing the function's signature in JSON format. |
| 292 | """ |
| 293 | type_map = { |
| 294 | str: "string", |
| 295 | int: "integer", |
| 296 | float: "number", |
| 297 | bool: "boolean", |
| 298 | # list: "array", |
| 299 | # dict: "object", |
| 300 | type(None): "null", |
| 301 | } |
| 302 | # def get_type_info(annotation): |
| 303 | # if hasattr(annotation, "__origin__"): # 处理typing类型 |
| 304 | # origin = annotation.__origin__ |
| 305 | # if origin is list: # 处理List类型 |
| 306 | # item_type = annotation.__args__[0] |
| 307 | # return { |
| 308 | # "type": "array", |
| 309 | # "items": { |
| 310 | # "type": type_map.get(item_type, "string") |
| 311 | # } |
| 312 | # } |
| 313 | # elif origin is dict: # 处理Dict类型 |
| 314 | # return {"type": "object"} |
| 315 | # return {"type": type_map.get(annotation, "string")} |
| 316 | |
| 317 | try: |
| 318 | signature = inspect.signature(func) |
| 319 | except ValueError as e: |
| 320 | raise ValueError( |
| 321 | f"Failed to get signature for function {func.__name__}: {str(e)}" |
| 322 | ) |
| 323 | |
| 324 | parameters = {} |
| 325 | # for param in signature.parameters.values(): |
| 326 | # try: |
| 327 | # param_type = type_map.get(param.annotation, "string") |
| 328 | # except KeyError as e: |
| 329 | # raise KeyError( |
| 330 | # f"Unknown type annotation {param.annotation} for parameter {param.name}: {str(e)}" |
| 331 | # ) |
| 332 | # parameters[param.name] = {"type": param_type} |
| 333 | for param in signature.parameters.values(): |
| 334 | if param.name == "context_variables": |
| 335 | continue |
| 336 | try: |
| 337 | param_info = get_type_info(param.annotation, type_map) |
| 338 | if isinstance(param_info, dict) and "additionalProperties" in param_info: |
no test coverage detected