Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 32 ยท Agents and Tools

Defining Tools

Define LangChain tools with the @tool decorator, type hints and docstrings. See how a schema is built for the model and run a stand-in tool registry in Python.

A tool is a function the model is allowed to ask you to run. The model never executes anything; it only produces a request like {"name": "add", "args": {"a": 2, "b": 3}}. Your code runs the function and sends the result back. For the model to ask correctly, it needs a precise description of each tool: a name, a purpose and an argument schema. LangChain builds that description from your function, so the quality of your type hints and docstring directly decides how well the agent behaves.

The real langchain package is not available on this site, so real code is read-only. The runnable examples are a stand-in that builds the same kind of schema with Python's inspect module, so you can see exactly what the model receives.

The @tool decorator

The simplest way to define a tool in LangChain is the @tool decorator.

Python
# Real LangChain (read-only)
from langchain.tools import tool

@tool
def convert_celsius(celsius: float) -> float:
    """Convert a temperature from Celsius to Fahrenheit.

    Use this when the user gives a temperature in Celsius.
    """
    return celsius * 9 / 5 + 32

print(convert_celsius.name)         # convert_celsius
print(convert_celsius.description)  # the docstring
print(convert_celsius.args)         # {'celsius': {'title': 'Celsius', 'type': 'number'}}
print(convert_celsius.invoke({"celsius": 100}))  # 212.0

Four things are derived automatically:

  • name from the function name (override with @tool("new_name"));
  • description from the docstring (this is what the model reads);
  • argument schema from the type hints;
  • return value is sent back to the model as text.

A docstring is required. A tool without one raises an error, because a tool the model cannot understand is useless.

What the model sees

Behind the scenes the schema is turned into JSON that is sent with every request, roughly like this (the exact envelope depends on the provider):

JSON
{
  "name": "convert_celsius",
  "description": "Convert a temperature from Celsius to Fahrenheit. Use this when the user gives a temperature in Celsius.",
  "parameters": {
    "type": "object",
    "properties": { "celsius": { "type": "number" } },
    "required": ["celsius"]
  }
}

The model picks a tool by comparing the user's request with these descriptions, then fills parameters with values. Everything it knows about your function is in that JSON.

A stand-in tool decorator

This example builds the same pipeline in plain Python: a decorator that records the name, the docstring and a parameter schema from type hints, and a function that prints the JSON the model would be shown.

Python Stand-in: build a tool schema from a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that repeat marks only text as required because times has a default. Defaults tell the model which arguments it may leave out.

Writing descriptions that work

Models choose tools by reading, so write for a reader who has never seen your code.

  • Say what the tool does and when to use it ("Use this when ...").
  • Name arguments clearly: order_id beats id; start_date beats d.
  • State formats: "ISO date, like 2026-03-31".
  • Say what the tool returns, and what it does not do.
  • Keep tools small and separate. Two focused tools beat one with a mode argument.

You can add per-argument documentation with a pydantic model passed as args_schema:

Python
# Real LangChain (read-only)
from pydantic import BaseModel, Field
from langchain.tools import tool

class OrderLookup(BaseModel):
    order_id: str = Field(description="Order number such as 'A-1042'")
    include_items: bool = Field(default=False, description="Also return the line items")

@tool(args_schema=OrderLookup)
def lookup_order(order_id: str, include_items: bool = False) -> str:
    """Look up the status of a customer order."""
    return f"Order {order_id}: shipped"

Here each argument has its own description in the schema, which helps the model pick values correctly.

Validating calls before running them

The model's arguments are untrusted input. They may be missing, misnamed or of the wrong type. LangChain validates calls against the schema (via pydantic) and returns an error message to the model if validation fails, so it can try again. The stand-in below does a small version of that: it checks required arguments and types before calling the function, and returns a readable error instead of crashing.

Python Stand-in: validate a tool call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A returned error string goes back to the model as the tool result. A good model reads "missing argument 'celsius'" and repeats the call correctly.

Tools with side effects

Reading tools (search, lookup) are low risk. Tools that change something (send an email, delete a row, charge a card) need extra care: ask for human approval (human in the loop), limit scope, make them idempotent where you can, and log every call. Never give an agent a tool you would not allow an untrusted user to trigger, because prompt injection can make the model call it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does LangChain take a tool's description from when you use @tool?

    The docstring becomes the description the model reads, so write it carefully.
  2. 2. Who actually executes a tool?

    The model only emits a structured request; the agent runtime in your process runs the function.
  3. 3. Which is the best argument name for an order identifier?

    Descriptive names help the model fill the right value.
  4. 4. What should a tool return when the model passes a bad argument?

    An informative error lets the model retry with corrected arguments.

Summary

  • A tool is a function plus a name, a description and an argument schema.
  • @tool derives the schema from type hints and the description from the docstring; args_schema adds per-argument detail.
  • The model sees only the schema and chooses tools by reading descriptions.
  • Treat arguments as untrusted: validate, return readable errors, and guard side-effecting tools.

Next: The Tool-Calling Loop