Generate a Tool Schema from a Python Function

medium
Unit 18 · Agents0/3 to milestone

LLM tool calling needs a JSON Schema for each function. Frameworks generate it automatically from type hints. Do the same with inspect.

Implement tool_schema(fn) returning:

{"name": fn.__name__, "description": <first line of the docstring, or "">,
 "parameters": {"type": "object", "properties": {...}, "required": [...]}}
  • Map annotations: str → "string", int → "integer", float → "number", bool → "boolean", list[X] → {"type": "array", "items": <schema of X>}, dict → "object". A missing annotation gives {} (any type).
  • Literal["a", "b"] → {"type": "string", "enum": ["a", "b"]}.
  • Optional[X] (or X | None) → the schema of X, and the parameter is not required.
  • Parameters without defaults are required (in signature order). Parameters with a default include "default" in their schema. Skip self, *args and **kwargs.
#agents#tool-use#introspection2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Generate a Tool Schema from a Python Function · TechGradify