Skip to content

type_annotation_to_schema ยค

Functions:

Name Description
type_annotation_to_str_schema

This method accepts arbitrary types defined in the return annotation of a functions.

type_annotation_to_str_schema ยค

type_annotation_to_str_schema(type_) -> Optional[str]

This method accepts arbitrary types defined in the return annotation of a functions. Then creates a string representation of the annotation schema to be passed to the model.

Source code in src/declarai/python_parser/type_annotation_to_schema.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def type_annotation_to_str_schema(type_) -> Optional[str]:
    """
    This method accepts arbitrary types defined in the return annotation of a functions.
    Then creates a string representation of the annotation schema to be passed to the model.
    """
    if type_.__module__ == "builtins":
        if type_ in (str, int, float, bool):
            return type_.__name__

    if isinstance(type_, typing._GenericAlias):
        root_name = type_._name
        if not root_name:
            if type_.__origin__ == typing.Union:
                root_name = "Union"
        properties = []
        for sub_type in type_.__args__:
            resolved_schema = resolve_to_json_schema(sub_type)
            properties.append(resolve_pydantic_schema_recursive(resolved_schema))

        if len(properties) > 1:
            resolved_str_schema = f"{root_name}[{properties[0]}, {properties[1]}]"
        else:
            resolved_str_schema = f"{root_name}[{properties[0]}]"
        return schema_to_string_for_prompt(resolved_str_schema)

    resolved_schema = resolve_to_json_schema(type_)
    resolved_schema = resolve_pydantic_schema_recursive(resolved_schema)
    str_schema = json.dumps(resolved_schema, indent=4)
    return schema_to_string_for_prompt(str_schema)