r"""Generate a Python function code from a JSON schema. Args: json_obj (dict): The JSON schema object containing properties and required fields, and json format is follow openai tools schema Returns: str: The generated Python function code as a string.
(json_obj: Dict)
| 399 | |
| 400 | |
| 401 | def json_to_function_code(json_obj: Dict) -> str: |
| 402 | r"""Generate a Python function code from a JSON schema. |
| 403 | |
| 404 | Args: |
| 405 | json_obj (dict): The JSON schema object containing properties and |
| 406 | required fields, and json format is follow openai tools schema |
| 407 | |
| 408 | Returns: |
| 409 | str: The generated Python function code as a string. |
| 410 | """ |
| 411 | properties = json_obj.get('properties', {}) |
| 412 | required = json_obj.get('required', []) |
| 413 | |
| 414 | if not properties or not required: |
| 415 | raise ValueError( |
| 416 | "JSON schema must contain 'properties' and 'required' fields" |
| 417 | ) |
| 418 | |
| 419 | args = [] |
| 420 | docstring_args = [] |
| 421 | return_keys = [] |
| 422 | |
| 423 | prop_to_python = { |
| 424 | 'string': 'str', |
| 425 | 'number': 'float', |
| 426 | 'integer': 'int', |
| 427 | 'boolean': 'bool', |
| 428 | } |
| 429 | |
| 430 | for prop in required: |
| 431 | # if no description, return empty string |
| 432 | description = properties[prop].get('description', "") |
| 433 | prop_type = properties[prop]['type'] |
| 434 | python_type = prop_to_python.get(prop_type, prop_type) |
| 435 | args.append(f"{prop}: {python_type}") |
| 436 | docstring_args.append( |
| 437 | f" {prop} ({python_type}): {description}." |
| 438 | ) |
| 439 | return_keys.append(prop) |
| 440 | |
| 441 | # extract entity of schema |
| 442 | args_str = ", ".join(args) |
| 443 | docstring_args_str = "\n".join(docstring_args) |
| 444 | return_keys_str = ", ".join(return_keys) |
| 445 | |
| 446 | # function template |
| 447 | function_code = f''' |
| 448 | def {Constants.FUNC_NAME_FOR_STRUCTURED_OUTPUT}({args_str}): |
| 449 | r"""Return response with a specified json format. |
| 450 | Args: |
| 451 | {docstring_args_str} |
| 452 | Returns: |
| 453 | Dict: A dictionary containing {return_keys_str}. |
| 454 | """ |
| 455 | return {{{", ".join([f'"{prop}": {prop}' for prop in required])}}} |
| 456 | ''' |
| 457 | |
| 458 | return function_code |
no outgoing calls
no test coverage detected