|
| 1 | +import enum |
| 2 | +import typing |
| 3 | +import inspect |
| 4 | + |
| 5 | +def get_function_schema( |
| 6 | + func: typing.Annotated[typing.Callable, "The function to get the schema for"] |
| 7 | +) -> typing.Annotated[dict[str, typing.Any], "The JSON schema for the given function"]: |
| 8 | + """ |
| 9 | + Returns a JSON schema for the given function. |
| 10 | +
|
| 11 | + You can annotate your function parameters with the special Annotated type. |
| 12 | + Then get the schema for the function without writing the schema by hand. |
| 13 | +
|
| 14 | + Especially useful for OpenAI API function-call. |
| 15 | +
|
| 16 | + Example: |
| 17 | + >>> from typing import Annotated, Optional |
| 18 | + >>> import enum |
| 19 | + >>> def get_weather( |
| 20 | + ... city: Annotated[str, "The city to get the weather for"], |
| 21 | + ... unit: Annotated[ |
| 22 | + ... Optional[str], |
| 23 | + ... "The unit to return the temperature in", |
| 24 | + ... enum.Enum("Unit", "celcius fahrenheit") |
| 25 | + ... ] = "celcius", |
| 26 | + ... ) -> str: |
| 27 | + ... \"\"\"Returns the weather for the given city.\"\"\" |
| 28 | + ... return f"Hello {name}, you are {age} years old." |
| 29 | + >>> get_function_schema(get_weather) |
| 30 | + { |
| 31 | + "name": "get_weather", |
| 32 | + "description": "Returns the weather for the given city.", |
| 33 | + "parameters": { |
| 34 | + "type": "object", |
| 35 | + "properties": { |
| 36 | + "city": { |
| 37 | + "type": "string", |
| 38 | + "description": "The city to get the weather for" |
| 39 | + }, |
| 40 | + "unit": { |
| 41 | + "type": "string", |
| 42 | + "description": "The unit to return the temperature in", |
| 43 | + "enum": ["celcius", "fahrenheit"], |
| 44 | + "default": "celcius" |
| 45 | + } |
| 46 | + }, |
| 47 | + "required": ["city"] |
| 48 | + } |
| 49 | + } |
| 50 | + """ |
| 51 | + sig = inspect.signature(func) |
| 52 | + params = sig.parameters |
| 53 | + schema = { |
| 54 | + "type": "object", |
| 55 | + "properties": {}, |
| 56 | + "required": [], |
| 57 | + } |
| 58 | + for name, param in params.items(): |
| 59 | + param_args = typing.get_args(param.annotation) |
| 60 | + is_annotated = len(param_args) > 1 |
| 61 | + |
| 62 | + enum_ = None |
| 63 | + default_value = inspect._empty |
| 64 | + |
| 65 | + if is_annotated: |
| 66 | + # first arg is type |
| 67 | + (T, _) = param_args |
| 68 | + |
| 69 | + # find description in param_args tuple |
| 70 | + description = next( |
| 71 | + (arg for arg in param_args if isinstance(arg, str)), |
| 72 | + f"The {name} parameter", |
| 73 | + ) |
| 74 | + |
| 75 | + # find enum in param_args tuple |
| 76 | + enum_ = next( |
| 77 | + (arg for arg in param_args if isinstance(arg, enum.Enum)), None |
| 78 | + ) |
| 79 | + else: |
| 80 | + T = param.annotation |
| 81 | + description = f"The {name} parameter" |
| 82 | + |
| 83 | + # find default value for param |
| 84 | + if param.default is not inspect._empty: |
| 85 | + default_value = param.default |
| 86 | + |
| 87 | + schema["properties"][name] = { |
| 88 | + "type": guess_type(T), |
| 89 | + "description": description, # type: ignore |
| 90 | + } |
| 91 | + |
| 92 | + if enum_ is not None: |
| 93 | + schema["properties"][name]["enum"] = enum_.values |
| 94 | + |
| 95 | + if default_value is not inspect._empty: |
| 96 | + schema["properties"][name]["default"] = default_value |
| 97 | + |
| 98 | + if not isinstance(None, T): |
| 99 | + schema["required"].append(name) |
| 100 | + return { |
| 101 | + "name": func.__qualname__, |
| 102 | + "description": inspect.getdoc(func), |
| 103 | + "parameters": schema, |
| 104 | + } |
| 105 | + |
| 106 | + |
| 107 | +def guess_type( |
| 108 | + T: typing.Annotated[type, "The type to guess the JSON schema type for"] |
| 109 | +) -> typing.Annotated[ |
| 110 | + typing.Union[str, list[str]], "str | list of str that representing JSON schema type" |
| 111 | +]: |
| 112 | + """Guesses the JSON schema type for the given python type.""" |
| 113 | + _types = [] |
| 114 | + |
| 115 | + # hacking around typing modules, `typing.Union` and `types.UnitonType` |
| 116 | + if isinstance(1, T): |
| 117 | + _types.append("integer") |
| 118 | + elif isinstance(1.1, T): |
| 119 | + _types.append("number") |
| 120 | + |
| 121 | + if isinstance("", T): |
| 122 | + _types.append("string") |
| 123 | + if not isinstance(1, T) and isinstance(True, T): |
| 124 | + _types.append("boolean") |
| 125 | + if isinstance([], T): |
| 126 | + _types.append("array") |
| 127 | + if isinstance({}, T): |
| 128 | + return "object" |
| 129 | + |
| 130 | + if len(_types) == 0: |
| 131 | + return "object" |
| 132 | + |
| 133 | + if len(_types) == 1: |
| 134 | + return _types[0] |
| 135 | + |
| 136 | + return _types |
0 commit comments