All Agent Engineering

Defining a legible custom tool contract in smolagents

Wrap a function as a Tool with name, description, inputs, output_type and forward, then verify each part of the contract.

AINavWritten / Updated
On this page

At a glance

The smolagents docs put tool definition plainly: a tool is mostly a function an LLM can use, but to use it the model must be given an API — name, tool description, input types and descriptions, output type. So it cannot be only a function; it should be a class wrapping that metadata. This task treats that metadata as a contract to write and to check: can the model tell when to call it, how to fill the arguments, what shape comes back, and what it sees when the call fails.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • smolagents Defining a legible custom tool contract in smolagents

Execution locations and responsibilities

  • smolagents Python runtime Use the workflow below to distinguish responsibilities of the caller, runtime, and external actions.
Engineering workflow order
Engineering workflow order1. Step 4: Pick decorator or subclass deliberately → 2. Step 1: Derive name and description from the call situation → 3. Step 2: Fill type and description for every input → 4. Step 3: Hold output_type to the actual return → 5. Step 5: Design the text a failure produces → 6. Step 6: Size the toolbox → 7. Step 7: Add portability rules if the Hub is planned. Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.1. Step 4: Pick decorator or subclass deliberately2. Step 1: Derive name and description from the callsituation3. Step 2: Fill type and description for every input4. Step 3: Hold output_type to the actual return5. Step 5: Design the text a failure produces6. Step 6: Size the toolbox7. Step 7: Add portability rules if the Hub is planned

Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.

When to use

  • A Tool subclass defines name, description, inputs, output_type and forward. inputs maps parameter names to dictionaries containing type and description: inputs[task][type] is string and inputs[task][description] describes that parameter. output_type follows the documented string, boolean, integer, number, image, audio, array, object, any and null values. type and description are not two top-level tool parameters in the complete inputs map.

When not to use

  • Does not cover type names outside the documented vocabulary: the allowed set is fixed at ten entries, and going beyond it is outside what this workflow can settle.
  • The decorator-versus-subclass choice covers only the documented criteria of method count and extra class attributes; the docs say nothing about performance or concurrency, so neither is addressed.
  • The Hub rules apply only when publishing a tool; a purely local tool need not trade structure for them, but the record should note which rules were left unmet.

Prerequisites and input

  • One real callable Python function with its actual arguments and return structure.
  • A description of the task situations in which the tool will be called, to judge whether the description is specific enough.
  • The confirmed type vocabulary for inputs and output: string, boolean, integer, number, image, audio, array, object, any, null.

Engineering checks

Layer 1: The five members of a Tool class — A Tool subclass defines name, description, inputs, output_type and forward. inputs maps parameter names to dictionaries containing type and description: inputs[task][type] is string and inputs[task][description] describes that parameter. output_type follows the documented string, boolean, integer, number, image, audio, array, object, any and null values. type and description are not two top-level tool parameters in the complete inputs map.

Layer 2: Decorator versus subclass — Use @tool for a simple callable and consider a Tool subclass for multiple methods or extra class attributes. A decorated function checks its clear name, input/output type hints and a docstring with Args: describing every argument without repeating type indications; types come from hints. A subclass checks class metadata and forward. These are distinct contracts.

Layer 3: Error text and toolbox size — Readable failure messages are a design recommendation. Check how actual exceptions enter model context in the running version rather than inferring a universal propagation guarantee from metadata. The docs warn that too many tools can overwhelm models, so record the toolbox and distinguishable descriptions. Subclasses intended for sharing also check self-contained methods, imports inside functions and __init__ with only self; these sharing conditions do not automatically constrain local-only tools.

1. Step 4: Pick decorator or subclass deliberately

Where: tool definition and the decision record. Input: callable complexity, method count and class-attribute needs. Choose @tool for a simple function or a Tool subclass for multiple methods or attributes, then follow that branch’s signature/docstring or metadata checks. Check initialization portability when sharing is planned rather than imposing Hub conditions on local-only usage. Completion: the chosen branch agrees with subsequent checks. Stop to correct mixed function and forward contracts.

2. Step 1: Derive name and description from the call situation

Where: the selected function or class definition. Input: the calling task and return object. For @tool write a clear function name and descriptive docstring; for a subclass write name and description explaining when to call it and what returns. Completion: the description alone conveys the purpose without private context. Stop to narrow the tool task if purpose or output cannot be stated.

3. Step 2: Fill type and description for every input

Where: function signature/docstring or subclass inputs. Input: actual parameters. For @tool supply input/output type hints and an Args: docstring entry for every argument, with types drawn from hints. For a subclass map each parameter name to {type,description} and align it with forward. Completion: no missing or extra arguments, and each branch has types and descriptions in its proper surface. Stop integration on missing hints, Args descriptions or nested parameter metadata.

4. Step 3: Hold output_type to the actual return

Where: the function return annotation or subclass output_type and actual result. Input: sample return values. For @tool inspect the return type hint; for a subclass inspect output_type and avoid declaring structured results arbitrarily as string. Completion: the selected branch declaration matches the actual shape. Stop to change the boundary when results vary or contradict it, without treating documentation as a passing runtime test.

5. Step 5: Design the text a failure produces

Where: the @tool-decorated function body or the chosen Tool subclass forward, following the actual branch for exception and return handling. Input: known failure modes (invalid argument, unavailable dependency, empty result). Action: decide the message each mode raises, ensuring it carries enough signal for the model to fix the next call instead of only surfacing an underlying exception. Completion check: every known failure mode has one readable message. Stop condition: if the cause cannot be stated without exposing sensitive configuration, use a generic description and mark that limit in the record.

6. Step 6: Size the toolbox

Where: the tools argument at agent initialization. Input: the full current tool list. Action: count tools and description lengths and judge against the documented warning about too many tools; when expansion is genuinely needed, consider splitting agents by task rather than stacking tools. Completion check: the tool list and each description's length are recorded along with a verdict on whether it is too many. Stop condition: if descriptions can no longer be told apart, merge or remove before continuing.

7. Step 7: Add portability rules if the Hub is planned

Where: the tool's source layout. Input: the tool's imports and initialization logic. Action: move all imports inside the functions so every method is self-contained and uses only variables from its arguments; if __init__ remains, confirm it takes only self, putting fixed values in class attributes. Completion check: all three documented Hub rules are ticked individually, with a note that push_to_hub requires a repository already created on the Hub and a token with read access. Stop condition: any unmet rule means staying local instead of publishing.

Task example

Unexecuted synthetic walkthrough: define a network-free simple demo_count(dataset:str)->int callable and choose @tool. Its docstring explains the demonstration count and describes allowed dataset names under Args: without repeating type indications; hints define input and output types. Inspect description, parameters and return annotation, then design a readable unknown-name error while leaving actual propagation unverified. A Tool subclass instead uses type/description inside inputs[dataset], output_type=integer and forward; do not impose those fields on the decorated function. Check Hub portability only when sharing is actually planned.

Completion checks

  • Subclass inputs names and nested type/description match forward; decorated-function hints and Args docstring cover every argument, without mixing branches.
  • Check the actual result against the chosen return hint or output_type; subclass type values follow the documented set.
  • The description, read on its own, settles both when to call and what returns.
  • Every known failure mode has a corresponding readable message.
  • If Hub sharing is declared, all three rules are satisfied: self-contained methods, imports inside functions, __init__ taking only self.

Verification scope

Official Tools and Guided tour documentation was read. smolagents was not installed, no tool was created or called and nothing was pushed to the Hub. Signatures, docstrings, metadata and failure text are design reviews; actual exception propagation and calling outcomes remain untested.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. smolagents · smolagents documentation: hf-tools
  2. smolagents · smolagents documentation: hf-guided-tour

Found an error? Tell us →