signature.py•988 B
from __future__ import annotations
import inspect
from typing import Any, Dict
__all__ = ["signature_to_schema"]
PYTHON_TO_JSON = {
int: "integer",
float: "number",
bool: "boolean",
str: "string",
list: "array",
dict: "object",
}
def _type_to_json(t: Any) -> str:
try:
return PYTHON_TO_JSON[t]
except KeyError:
return "string"
def signature_to_schema(fn) -> Dict[str, Any]:
sig = inspect.signature(fn)
props: dict[str, Any] = {}
required: list[str] = []
for name, param in sig.parameters.items():
if name == "self" or name.startswith("_"):
continue
annotation = param.annotation if param.annotation is not inspect.Parameter.empty else str
props[name] = {"type": _type_to_json(annotation)}
if param.default is inspect.Parameter.empty:
required.append(name)
return {
"type": "object",
"properties": props,
"required": required,
}