Defining tools as functions

As agents grow more capable, they need ways to do things in the world, not just decide. In classical agents, those capabilities are expressed as tools. This lesson exists to show how ordinary Python functions become those tools, giving an agent concrete actions it can execute while keeping its decision logic clean and predictable.

What a tool is in the context of an agent

In an agent, a tool represents an action the agent can take. It is something that causes work to happen, such as writing a file, generating output, or updating external state.

From a programming perspective, a tool is not mysterious. It is simply a named capability that the agent can invoke when needed.

Representing tools as Python functions

The most natural way to represent a tool in Python is as a function. Functions already package behavior behind a name, which makes them easy to reference and reuse.

A function used as a tool does not need special syntax. It is defined using def, just like any other function.

def generate_planet_page(name):
    return f"<html><h1>{name}</h1></html>"

Defining clear inputs and outputs for a tool

Tools work best when their inputs and outputs are explicit. Inputs are passed in as function parameters, and outputs are returned as values.

Clear inputs and outputs make a tool predictable. They also make it easier for an agent to reason about what the tool does without inspecting its internals.

def generate_planet_page(name):
    html = f"<html><h1>{name}</h1></html>"
    return html

Using functions to encapsulate side effects

Many tools exist to produce side effects, such as writing files or modifying state. Encapsulating those side effects inside a function keeps them contained.

This separation helps ensure that side effects occur only when the agent explicitly chooses to invoke the tool.

def save_page(filename, content):
    with open(filename, "w") as file:
        file.write(content)

Treating tools as reusable units of behavior

Once defined, a tool is just a function. That means it can be reused, tested, and combined with other code like any normal Python function.

For an agent, this reuse is essential. The same tool may be invoked many times in different situations, always producing the same kind of result from the same kind of input.

Conclusion

At this point, we know what a tool represents and how to define one using plain Python functions. By giving tools clear inputs, outputs, and well-contained side effects, we create reusable units of behavior that an agent can reliably execute when it decides to act.