Skip to content

< CollectionsBuilding effective agents · 16 of 16 ·101 · Level 04, Tool Calling

Turn a Function Into a Tool Spec

medium · implement · Tool Calling

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.

  1. name is the function's name.
  2. description is the docstring's first paragraph, on one line: its line breaks become single spaces. A function with no docstring raises TypeError.
  3. properties has one entry per parameter, in signature order, built from its type hint:
    • str, int, float and bool become {"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 written X | None, becomes the schema for X.
  4. A parameter's description comes from the docstring's Args: block, where a line reads name: what it is. With no such line there is no description key.
  5. required lists the parameters with no default, in signature order. Optional does not make a parameter optional; only a default does.
  6. Refuse what you cannot describe. No hint, a hint outside rule 3, *args or **kwargs raises TypeError, 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".