Lesson 7 of 9 · Composition
Tools in LangChain
Give LangChain models tools: the @tool decorator and its schema, bind_tools, reading tool calls, returning ToolMessages and letting create_agent run the loop.
- 8 min read
- Intermediate
- Reviewed
- Define a tool with the @tool decorator, including a good docstring and type hints
- Explain how a function becomes the schema a model sees
- Bind tools to a model and read the tool calls it makes
- Run tool calls and send results back as ToolMessages
- Build a tool-using agent with create_agent
Models that can ask for help
A tool is a function the model can ask your program to run, such as looking up stock, checking the weather or searching documents. The model never runs it itself; it returns a tool call saying which tool to use with which arguments, and your code runs it. (The Tool Calling course covers the full mechanics across providers.)
Defining a tool
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
@tool
def get_bike_stock(model_name: str, city: str) -> int:
"""Return how many units of a bike model are in stock at the shop in a city."""
stock = {("volta city 3", "lisbon"): 4, ("volta city 3", "porto"): 0}
return stock.get((model_name.lower(), city.lower()), 0)
print(get_bike_stock.name)
print(get_bike_stock.description)
print(get_bike_stock.args)
model = init_chat_model("anthropic:MODEL_NAME")
model_with_tools = model.bind_tools([get_bike_stock]) # the model now sees the tool's schema
reply = model_with_tools.invoke("Is the Volta City 3 in stock in Porto?")
print(reply.tool_calls) # the model asks for a call; it doesn't run itget_bike_stock
Return how many units of a bike model are in stock at the shop in a city.
{'model_name': {'title': 'Model Name', 'type': 'string'}, 'city': {'title': 'City', 'type': 'string'}}
[{'name': 'get_bike_stock', 'args': {'model_name': 'Volta City 3', 'city': 'Porto'}, 'id': 'call_1', 'type': 'tool_call'}]The @tool decorator reads three things from your function: its name, its docstring (the description) and its type hints (the argument schema). bind_tools sends that schema to the model with every request. When the model decides a tool is needed, its reply has an empty or short content and a list of tool_calls.
How a function becomes a schema
Here's what @tool does, in plain Python, using the inspect module:
import inspect
# What @tool does, in plain Python: read a function's name, docstring and type hints,
# and turn them into the schema a model sees.
JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean", list: "array"}
def to_tool_schema(fn):
sig = inspect.signature(fn)
properties, required = {}, []
for name, p in sig.parameters.items():
properties[name] = {"type": JSON_TYPES.get(p.annotation, "string")}
if p.default is inspect.Parameter.empty:
required.append(name) # no default value -> the model must provide it
else:
properties[name]["default"] = p.default
return {"name": fn.__name__, "description": inspect.getdoc(fn),
"parameters": {"type": "object", "properties": properties, "required": required}}
def get_bike_stock(model_name: str, city: str, include_used: bool = False) -> int:
"""Return how many units of a bike model are in stock at the shop in a city."""
return 4
schema = to_tool_schema(get_bike_stock)
print(schema["name"], "-", schema["description"])
for name, spec in schema["parameters"]["properties"].items():
print(f" {name}: {spec}")
print(" required:", schema["parameters"]["required"])Parameters without a default are required; type hints become JSON types; the docstring becomes the description. That's why docstrings and type hints matter so much: they are the only documentation the model gets.
Running tool calls yourself
The model asked for a call. Your code runs it and sends the result back as a ToolMessage, linked to the call by its ID:
from langchain_core.messages import HumanMessage
messages = [HumanMessage("Is the Volta City 3 in stock in Porto?")]
reply = model_with_tools.invoke(messages)
messages.append(reply)
for call in reply.tool_calls: # run each requested tool
tool_message = get_bike_stock.invoke(call) # given a tool call, a tool returns a ToolMessage
print(repr(tool_message.content), tool_message.tool_call_id)
messages.append(tool_message)
print(model_with_tools.invoke(messages).content) # the model answers using the result'0' call_1 Sorry, the Volta City 3 is out of stock in Porto right now.
Invoking a LangChain tool with a tool call (rather than plain arguments) returns a ready-made ToolMessage with the right tool_call_id. The model then sees its own request, the result, and answers the customer.
Let create_agent run the loop
Writing that loop by hand for every request gets repetitive, and real tasks may need several rounds of tool calls. create_agent builds an agent that loops for you: call the model, run any tool calls, send the results back, and repeat until the model answers without calling a tool:
from langchain.agents import create_agent
agent = create_agent(
model, # the chat model from above
tools=[get_bike_stock],
system_prompt="You help customers of Velamuvi Bikes. Always check stock before answering.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "Can I buy a Volta City 3 in Porto or Lisbon?"}]})
for m in result["messages"]:
print(f"{m.type:>5}: {m.content or [c['args'] for c in m.tool_calls]}")human: Can I buy a Volta City 3 in Porto or Lisbon?
ai: [{'model_name': 'Volta City 3', 'city': 'Porto'}, {'model_name': 'Volta City 3', 'city': 'Lisbon'}]
tool: 0
tool: 4
ai: The Volta City 3 is out of stock in Porto, but our Lisbon shop has 4. Would you like to reserve one there?The model asked for two tool calls at once (Porto and Lisbon), the agent ran both, and the model combined the results into one answer. The result's messages list is the full record of the run, which is exactly what you'd inspect when something goes wrong.
Common mistakes
Work out which tool arguments the model must always provide, the way @tool builds the required list of a tool's schema.
import inspect
def send_reminder(to: str, subject: str, cc: str = "", urgent: bool = False):
"""Send a reminder email."""
# Using inspect.signature(send_reminder).parameters, print two lists:
# required: [...] (parameters without a default value)
# optional: [...] (parameters with a default value)
What does a model do when it decides to use a tool bound with bind_tools?
Summary
@toolturns a function's name, docstring and type hints into a tool schema.bind_toolsshows the schema to the model; replies containtool_calls.- Run each call and send back a ToolMessage with the matching
tool_call_id. create_agentruns the model-tool loop for you, with middleware for approvals, limits and more.- Write tool docstrings for the model, and validate arguments inside tools.
Next: tracing with LangSmith.
Finished reading? Tick it off to track your progress.