Turn a Function Into a Tool Spec
Implement tool_spec(fn), which builds the spec a model reads for a Python function. It returns {"name": ..., "description": ..., "input_schema": {"type": "object", "properties": {...}, "required": [...]}}. Specs written by hand drift from their functions, so SDKs generate them, and this is how.
nameis the function's name.descriptionis the docstring's first paragraph, on one line: its line breaks become single spaces. A function with no docstring raisesTypeError.propertieshas one entry per parameter, in signature order, built from its type hint:str,int,floatandboolbecome{"type": "string"},"integer","number"and"boolean".list[X]becomes{"type": "array", "items": <the schema for X>}.Literal["a", "b"]becomes{"type": "string", "enum": ["a", "b"]}.Literal[1, 2]has type"integer".Optional[X], also writtenX | None, becomes the schema for X.
- A parameter's
descriptioncomes from the docstring'sArgs:block, where a line readsname: what it is. With no such line there is nodescriptionkey. requiredlists the parameters with no default, in signature order.Optionaldoes not make a parameter optional; only a default does.- Refuse what you cannot describe. No hint, a hint outside rule 3,
*argsor**kwargsraisesTypeError, and the message names the parameter.
The catch. A file that starts with from __future__ import annotations keeps its hints as strings, so inspect.signature gives you 'int', not int. typing.get_type_hints(fn) resolves them. Also, bool is a subclass of int in Python, and it must not come out as "integer".