Skip to main content
← Back to Blog
2026-02-22 · 8 min readAI AgentsPythonUpdated Oct 30, 2026

Beyond Built-ins: Architecting Custom Tools in LangChain

A code-first guide to custom LangChain tools. You build a small DevOps assistant with a decorator tool, a BaseTool subclass with a strict Pydantic schema and a tool that reports errors with ToolException, wire them into create_agent, and test the whole agent against a fake model without an API key.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
37 views
Beyond Built-ins: Architecting Custom Tools in LangChain

This guide is for developers who want an LLM agent to work with their own systems, not just web search and a calculator. You will build custom LangChain tools two ways: a quick decorator and a class with a strict Pydantic schema. Then you'll handle tool errors so the agent can correct itself, wire the tools into an agent and test it for free with a fake model.

Key takeaways

  • Use the @tool decorator for simple functions, and a BaseTool subclass when you need a strict schema, shared setup or custom error handling.
  • The tool's name, description and argument schema are the prompt the model reads. Write them for the model, and enforce formats with Pydantic.
  • Return errors to the model instead of crashing. A ToolException with handle_tool_error=True turns a failure into a message the agent can act on.

A LangChain tool is a function the model can call, packaged with a name, a description and an input schema so the model knows when to use it and what to pass. LangChain's tools docs describe the docstring as the description "that helps the model understand when to use it."

This post is part 11 of the LLM & LangChain Fundamentals series. In part 10 you gave a chatbot state with LangChain memory. Here you give an agent hands.

The limits of general-purpose tools

LangChain ships with ready-made tools such as search and HTTP requests. They're fine for demos. But if you're building an automation for a business or a micro-SaaS, you soon hit a wall.

The real value comes when the model can work with your systems: query your Postgres database, restart a service through your deploy API, or fetch one user's analytics from your dashboard.

For that you need more than a script. You need an interface the model can understand. This post builds one for a small DevOps assistant that checks server health, toggles feature flags and reads user analytics.

Two ways to define a tool

Approach What it gives you Trade-off Use it when
@tool decorator A tool from a plain function; the docstring becomes the description Less control over errors and setup Simple inputs such as a string or a number
BaseTool subclass Explicit name, description, schema and error handling in one class More code Strict validation, shared clients or custom error handling

The @tool decorator can also take a Pydantic schema through args_schema, so the line between the two is about how much structure you want, not what's possible.

Install the packages first (Python 3.10 or newer):

pip install -U langchain langchain-openai pydantic

The decorator: quick and simple

If you just need to expose a Python function to an agent, the @tool decorator is the fastest route. Create devops_tools.py:

# devops_tools.py
import os
import random
from typing import Literal

from langchain.agents import create_agent
from langchain.tools import BaseTool, ToolException, tool
from pydantic import BaseModel, Field

@tool
def check_server_health(server_id: str) -> str:
    """Check the health status of one server by its id, such as web-1.
    Use it when the user asks if a server is down or running slowly.
    """
    status = random.choice(["Healthy", "Degraded", "Down"])  # stand-in for your monitoring API
    return f"Server {server_id} is currently: {status}"

Checked against langchain@1.4.7, langchain-core@1.7.3, langchain-openai@1.7.3 and pydantic@2.14.2, 2026-10-30.

The most important part isn't the code. It's the docstring. The model reads it to decide when to call the tool and what to pass. If you leave it out, the model has to guess from the function name.

BaseTool and Pydantic for strict inputs

The decorator is fine for simple inputs. But when an agent changes something, such as a database record or a feature flag, you need strict validation. You don't want a string where a boolean belongs, or an environment name that doesn't exist.

You get that by defining an args_schema with Pydantic. An args_schema is a Pydantic model that describes the tool's inputs. LangChain turns the schema into a JSON schema for the model, and validates the model's arguments against it before your code runs.

Here is a tool that lets an agent toggle a feature flag.

Step A: define the schema

class FeatureFlagInput(BaseModel):
    feature_name: str = Field(description="Key of the flag to toggle, for example 'dark_mode' or 'beta_access'")
    enable: bool = Field(description="True to enable the feature, False to disable it")
    environment: Literal["dev", "staging", "production"] = Field(
        description="Where to change the flag: 'dev', 'staging' or 'production'"
    )

The Field descriptions are prompt text inside the data structure. The Literal type limits environment to three values, so environment="test_server" fails validation.

The schema also has no default environment. The earlier version of this post defaulted to production, which means a model that forgets the argument changes live settings. Make risky arguments required, so the model has to choose.

Step B: subclass BaseTool

class ToggleFeatureTool(BaseTool):
    name: str = "toggle_feature_flag"
    description: str = "Enable or disable one feature flag in one environment."
    args_schema: type[BaseModel] = FeatureFlagInput

    def _run(self, feature_name: str, enable: bool, environment: str) -> str:
        action = "ENABLED" if enable else "DISABLED"
        # Stand-in: write to your flag store (Redis, Postgres or a flag service) here.
        return f"SUCCESS: Feature '{feature_name}' has been {action} in {environment}."

BaseTool is a Pydantic model, so name, description and args_schema need type annotations. Without them, Pydantic refuses the class. Import BaseModel from pydantic directly; older examples import it from langchain.pydantic_v1, which current LangChain no longer has.

You don't have to write _arun for async agents. In the langchain-core source, the default _arun runs your _run in a thread pool. Write your own async def _arun only when you have an async client to call.

Why Pydantic matters here

When the model calls toggle_feature_flag, LangChain checks its arguments against FeatureFlagInput. If the model passes environment="test_server", validation fails before _run runs. In the agent below, that error goes back to the model as a tool message, so it can try again with a valid value. The test at the end shows this.

That way, a hallucinated argument never reaches your internal systems.

Handle tool errors gracefully

A crash loop is a common agent failure. The model calls a tool, the tool hits an error (say, an unknown id), and the whole run stops.

You want the agent to see the error and correct itself. LangChain's reference says a ToolException "allows tools to signal errors without stopping the agent." Raise it from the tool, and set handle_tool_error=True. The langchain-core source says that with True, the exception message is returned as the tool's output:

ANALYTICS = {"usr_1": {"logins_7d": 12, "plan": "pro"}}  # stand-in for your analytics store

class UserAnalyticsTool(BaseTool):
    name: str = "get_user_analytics"
    description: str = "Get the last 7 days of analytics for one user id, such as usr_1."
    handle_tool_error: bool = True

    def _run(self, user_id: str) -> str:
        if user_id not in ANALYTICS:
            raise ToolException(f"No user with id {user_id}. Ids look like usr_1.")
        return str(ANALYTICS[user_id])

The model reads the message as an observation. It can then reason: "I used the wrong id format. I'll retry with usr_1." Write error messages that say what to do next, not just what failed.

Don't hand an agent raw SQL

A tool that runs any SQL the model writes can read or delete anything its database user can. Give the agent narrow tools, such as "get one user's analytics," and run them with a database user that has the least access it needs.

Add the tools to an agent

Once the tools exist, wiring them into an agent is short. create_agent takes a model, a list of tools and a system prompt. Add this to devops_tools.py:

SYSTEM_PROMPT = "You are a DevOps assistant. Use the tools; if a tool returns an error, fix the arguments."

def build_agent(model):
    return create_agent(
        model,
        tools=[check_server_health, ToggleFeatureTool(), UserAnalyticsTool()],
        system_prompt=SYSTEM_PROMPT,
    )

if __name__ == "__main__":
    from langchain.chat_models import init_chat_model

    # Needs OPENAI_API_KEY. Check the provider's models page for current ids.
    agent = build_agent(init_chat_model(os.getenv("AGENT_MODEL", "openai:gpt-6-luna")))
    result = agent.invoke({"messages": [
        {"role": "user", "content": "Turn on the 'beta_dashboard' feature in staging."}
    ]})
    print(result["messages"][-1].text)

This replaces the older AgentExecutor, create_openai_tools_agent and hub.pull setup. On the date above, OpenAI's models page calls gpt-6-luna its most efficient model for focused, high-volume tasks. Model ids change often, so check the provider's page and set AGENT_MODEL to switch. For Claude, install langchain-anthropic and use an id such as anthropic:claude-sonnet-5-5.

Test the tools without an API key

A fake chat model replays a scripted run, so you can test schemas and error handling for free. Save this as test_devops_tools.py next to devops_tools.py:

# test_devops_tools.py
from langchain.messages import AIMessage, ToolCall
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel

from devops_tools import build_agent, check_server_health

class FakeToolModel(GenericFakeChatModel):
    def bind_tools(self, tools, **kwargs):
        return self

def call(name, args, id):
    return AIMessage(content="", tool_calls=[ToolCall(name=name, args=args, id=id)])

def test_decorator_tool_runs_on_its_own():
    assert check_server_health.invoke({"server_id": "web-1"}).startswith("Server web-1 is currently:")

def test_agent_recovers_from_bad_arguments():
    flag = {"feature_name": "beta_dashboard", "enable": True}
    model = FakeToolModel(messages=iter([
        call("toggle_feature_flag", {**flag, "environment": "test_server"}, "1"),  # not allowed
        call("toggle_feature_flag", {**flag, "environment": "staging"}, "2"),
        call("get_user_analytics", {"user_id": "1"}, "3"),                         # wrong id format
        call("get_user_analytics", {"user_id": "usr_1"}, "4"),
        AIMessage(content="Done. beta_dashboard is on in staging."),
    ]))
    result = build_agent(model).invoke({"messages": [{"role": "user", "content": "Turn it on."}]})
    tool_results = [m.text for m in result["messages"] if m.type == "tool"]
    assert "Input should be 'dev', 'staging' or 'production'" in tool_results[0]
    assert tool_results[1] == "SUCCESS: Feature 'beta_dashboard' has been ENABLED in staging."
    assert tool_results[2] == "No user with id 1. Ids look like usr_1."
    assert "logins_7d" in tool_results[3]

Run it with pip install -U pytest and then pytest test_devops_tools.py. Both tests passed with the versions above. The subclass of GenericFakeChatModel ignores bind_tools, because the fake model only replays the messages you give it.

The test shows both paths: the bad environment was caught by the schema before _run ran, and the unknown user came back as a readable error from ToolException.

Best practices for tool design

  1. Descriptions are prompts. Write the docstring or description for the model. State the input format and when to use the tool.
  2. Keep inputs flat. As a rule of thumb, models fill flat schemas more reliably than deeply nested JSON. If the input is complex, split it into several tools or simplify the schema.
  3. Make tools safe to repeat. An agent may call a tool twice. If a tool charges a card or sends an email, protect it against duplicates, for example with an idempotency key.
  4. Scope access. Never give an agent broad rights such as DROP TABLE. Give each tool the smallest API key or database role it needs.

What's next

Custom tools are the difference between a chatbot and a system that does work. With Pydantic schemas and clear error messages, your agent can work with your own stack and recover from its own mistakes.

When an agent misbehaves, you need to see each step it took. The next part shows how with LangChain callbacks for debugging.

Frequently asked questions

When should I use @tool instead of BaseTool?

Use @tool for simple functions where the docstring and type hints say enough. Use a BaseTool subclass when you want the name, description, schema and error handling together in one class, or when the tool holds a shared client. Both can use a Pydantic args_schema.

Why does my BaseTool subclass fail with a Pydantic error?

BaseTool is a Pydantic model, so class fields need type annotations. Write name: str = "my_tool" and description: str = "...", not name = "my_tool". Also import BaseModel from pydantic, not from langchain.pydantic_v1.

How does an agent recover from a tool error?

The error has to come back to the model as a message instead of crashing the run. Raise ToolException and set handle_tool_error=True, and the message becomes the tool's output. With create_agent, schema validation errors also come back to the model, so it can retry with fixed arguments.

Do I need to write _arun for async agents?

No. The default _arun in langchain-core runs your _run method in a thread pool. Write your own async def _arun when the tool calls an async client and you want to avoid the extra thread.

Sources

Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.

  1. LangChain docs: Tools
  2. LangChain docs: Agents
  3. LangChain reference: BaseTool
  4. LangChain reference: ToolException
  5. langchain-core source: tools/base.py
  6. LangChain docs: Unit testing (fake chat models)
  7. OpenAI API: Models
  8. Claude docs: Models overview
  9. langchain on PyPI
All 14 parts in this series
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.