Lesson 10 / 31

Defining Tools

Turn a function into a tool with a name, description and schema.

A function the model can ask for

A tool is a function with a name, a description and an argument schema that the model can request. The @tool decorator builds all three from the function: the name from the function name, the description from the docstring and the schema from the type hints. Good docstrings matter because the model reads them to decide when to call the tool. With a tool-calling chat model, model.bind_tools([...]) lets the model reply with a structured request ("call add with a=2, b=40"); your code (or an agent loop) executes it and returns the result. Validate arguments and limit what each tool can do.

Act, decide, recover

Tools let models act, routing picks a path, and retries and fallbacks keep chains running.

Four tools: tools, branch, retry, trace.
Figure 3.1 — Tools, branch, retry and trace.

A tool from a function, run

I ran this offline in a Python virtual environment with langchain-core 1.6.6, langchain-text-splitters 1.1.2 and llama-index-core 0.14.25. No API key or network call is needed because a fake model or a toy embedding stands in for the real one. The decorator derived the tool name add, its description from the docstring, and an argument schema from the type hints. Invoking it with a dict returns 42.

from langchain_core.tools import tool

@tool
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b

print(add.name, "|", add.description)
print(add.args)
print(add.invoke({"a": 2, "b": 40}))

Output:

add | Add two integers.
{'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}
42

Write the docstring for the model

Say what the tool does, when to use it and what each argument means. Vague descriptions cause wrong or missing tool calls.

Quick check: Where does the @tool decorator get the tool description from?

  • The function's docstring
  • The file name
  • A random string
  • The GPU
Answer

The function's docstring — The docstring becomes the description the model reads.