Mastering LangChain Tools: Define, Build, and Optimize Agent Functions
This guide explains what LangChain tools are, why clear descriptions matter, and walks through three ways to create them—using the @tool decorator, StructuredTool with Pydantic models, and custom BaseTool subclasses—plus examples of built‑in tools and reference links.
What Is a Tool in LangChain?
A tool is essentially a Python function that an LLM‑based agent can call to interact with the external world, such as searching the web, running code, querying a database, or invoking an API. Each tool consists of three parts:
Name : a unique identifier used by the agent.
Description : a natural‑language explanation that tells the agent when and how to use the tool; the clearer the description, the more reliably the agent will select the correct tool.
Arguments : the input schema for the function, typically defined with a Pydantic model to enforce types and provide helpful metadata.
How to Define a Tool
1. Using the @tool Decorator (Recommended)
This is the simplest way to turn a plain Python function into a LangChain tool. The function name becomes the tool’s name, the docstring becomes the description, and the type hints are converted into an args_schema.
from langchain_core.tools import tool
@tool
def get_current_time(timezone: str) -> str:
"""Get the current time for a given timezone."""
# ... implementation ...
return "Current time is ..."The function name get_current_time is automatically the tool name.
The docstring supplies the description.
The type hint timezone: str generates the argument schema.
2. Using StructuredTool for Complex Arguments
When a tool requires structured input, define a Pydantic model and pass it as args_schema to StructuredTool.from_function.
from langchain_core.tools import StructuredTool
from pydantic import BaseModel, Field
class CalculatorInput(BaseModel):
expression: str = Field(description="Mathematical expression to evaluate")
def calculate_expression(expression: str) -> str:
"""Calculate a mathematical expression."""
return str(eval(expression)) # Warning: eval is unsafe in production
calculator_tool = StructuredTool.from_function(
func=calculate_expression,
name="calculator",
description="Tool for evaluating mathematical expressions.",
args_schema=CalculatorInput,
)The Pydantic model defines each argument’s type and description, enabling the agent to generate correct JSON payloads.
3. Subclassing BaseTool (Most Flexible)
For full control—e.g., asynchronous execution or custom error handling—inherit from langchain_core.tools.BaseTool and implement the required methods.
from langchain_core.tools import BaseTool
class MyAsyncTool(BaseTool):
name = "my_async"
description = "Performs an async operation."
args_schema = MyArgsModel
async def _run(self, **kwargs):
# custom async logic
...Why a Clear Description Is Crucial
The agent’s reasoning heavily relies on the tool description. It reads the description to decide:
When to invoke the tool (does the user query match the tool’s capability?).
How to invoke it (which arguments are required and what they mean?).
A vague or inaccurate description can cause the agent to miss the tool entirely or hallucinate incorrect calls.
Common Built‑In Tools
LangChain ships with several ready‑made tools that illustrate typical use cases: TavilySearchResults: Internet search. PythonREPLTool: Execute Python code. LLMMathChain: Perform math calculations. WikipediaQueryRun: Query Wikipedia.
Putting It All Together
The article demonstrates creating a custom tool with @tool, defining a structured tool with StructuredTool, and integrating both into an agent workflow. It also references the official LangChain “how‑to” pages for deeper exploration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
BirdNest Tech Talk
Author of the rpcx microservice framework, original book author, and chair of Baidu's Go CMC committee.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
