Creating custom tools

Topic 1 of 4 in Tool calling & ReAct agents28 min readIntermediateFree course

Overview

A language model can interpret instructions, generate text, and reason about information. However, text generation alone cannot reliably retrieve a customer’s latest order, calculate an invoice, check inventory, or update an application record.

These operations require executable capabilities called tools.

A tool is a callable operation that an AI application exposes to a language model through a well-defined interface. It describes what the operation does, what arguments it accepts, and how application code executes it.

For example, an e-commerce assistant might have access to the following tools:

  • search_products: Find products matching customer requirements.
  • calculate_discount: Calculate a discounted price.
  • get_order_status: Retrieve an existing order.
  • check_inventory: Determine whether a product is available.

Rather than inventing an order status, the model can request execution of get_order_status with an appropriate order identifier. The application executes the function and returns the actual result.

This separation between reasoning and execution is fundamental to agentic AI engineering.

In the previous lesson, you learned how LangGraph coordinates computation through the Pregel execution model. Nodes execute, produce updates, and communicate through graph state. Tools introduce specialized operations that can be executed within those nodes.

A tool is not automatically a graph node. It is an executable component that a node, agent, or tool execution system can invoke.

The following diagram illustrates the conceptual relationship between a model, a tool, and application resources.

Overview diagram: User Request to Language Model; Language Model to Tool Call; Tool Call to Input Validation; Input Validation to Tool Execution; Tool Execution to Application Data; Application Data to Tool Execution; Tool Execution to Tool Result; Tool Result to Language Model; Language Model to Final Response.

In this lesson, we concentrate on designing the tools themselves. Model binding, automatic routing, and repeated tool execution will be covered in the following lessons.

Environment setup

Install the required packages in your Python virtual environment.

Terminal
pip install -U "langchain>=1,<2" "langgraph>=1,<2" "pydantic>=2,<3" httpx pytest

The examples use LangChain 1.x and LangGraph 1.x interfaces. Each Python example is standalone unless a filename is explicitly specified.

No language model credentials are required because we will execute tools directly or supply predetermined tool calls.

The examples have been checked against the current public LangChain tool documentation and LangGraph API reference. Expected outputs are illustrative; the examples have not been executed against the installed frameworks in this authoring environment.

Anatomy of a good tool

Creating your first tool with @tool

The simplest way to define a custom tool is to decorate a Python function with @tool, imported from langchain.tools.

Consider a calculator operation that determines the total cost of several products.

The following example demonstrates tool creation, metadata inspection, and direct execution.

Python
from langchain.tools import tool

@tool
def calculate_total(unit_price: float, quantity: int) -> float:
    """Calculate the total price before taxes or discounts."""
    return round(unit_price * quantity, 2)

print(calculate_total.name)
print(calculate_total.description)
print(calculate_total.args)

result = calculate_total.invoke({
    "unit_price": 19.99,
    "quantity": 3,
})

print(result)

Expected output:

Text
calculate_total
Calculate the total price before taxes or discounts.
{'unit_price': {'title': 'Unit Price', 'type': 'number'}, ...}
59.97

The complete argument schema also contains the integer definition for quantity.

The decorator constructs a tool object around the original function. For a normal typed function like this one, the resulting object is a structured tool.

It provides a standardized execution interface instead of requiring every caller to understand the original function signature.

The components of a tool

A well-designed tool has several distinct components.

Component Purpose Example
Name Uniquely identifies the operation calculate_total
Description Explains when the operation is useful Calculate a total before taxes
Input schema Defines acceptable arguments Price and quantity
Implementation Performs the actual operation Multiply two numbers
Return value Communicates the outcome 59.97
Validation Rejects unacceptable input Quantity must be positive

The name and description help a model choose an operation. The schema helps it construct arguments. The implementation determines the actual outcome.

These components should agree with one another. A tool described as calculating tax-inclusive prices should not return a value that excludes tax.

Writing effective tool descriptions

Tool descriptions are part of the interface presented to the language model. They should be treated as carefully as an API contract.

Consider these two descriptions:

Text
Processes order information.
Text
Retrieve the shipping status of an existing order using its
order ID. Does not create, modify, or cancel orders.

The second description establishes the tool’s purpose and operational boundaries.

Good descriptions explain:

  • What the tool accomplishes.
  • When the model should use it.
  • Important assumptions and limitations.
  • Units, identifiers, or domain-specific terminology.
  • Whether the operation reads data or changes it.

Avoid extremely broad tools with names such as process_data or handle_request. Their responsibilities are ambiguous, making reliable selection and testing difficult.

Customizing tool names and descriptions

The decorator allows a public tool name and description to differ from the Python function name.

This example shows how to expose an existing calculation under a clearer interface.

Python
from langchain.tools import tool

@tool(
    "celsius_to_fahrenheit",
    description="Convert a temperature from Celsius to Fahrenheit.",
)
def convert_temperature(celsius: float) -> float:
    """Perform temperature conversion."""
    return round(celsius * 9 / 5 + 32, 2)

print(convert_temperature.name)
print(convert_temperature.invoke({"celsius": 25}))

Expected output:

Text
celsius_to_fahrenheit
77.0

The registered tool name is celsius_to_fahrenheit, while the Python variable remains convert_temperature.

This distinction is useful when refactoring implementation code without changing a public interface relied upon by an existing agent.

Designing predictable outputs

Tools can return strings, numbers, dictionaries, lists, or other supported values.

For business operations, structured dictionaries are often preferable to natural-language sentences.

Instead of returning:

Text
The order has shipped and should arrive in three days.

A tool could return:

JSON
{
  "order_id": "ORD-101",
  "status": "shipped",
  "estimated_delivery_days": 3
}

Structured output makes individual fields easier to interpret, validate, log, and test.

When invoked directly with an argument dictionary, a tool normally returns its underlying result. When invoked through a complete tool call containing an identifier, ordinary results are packaged into a ToolMessage suitable for the conversation.

Keep responses concise. Returning thousands of records can increase model context consumption, latency, and cost.

Tools that change application data should communicate whether the operation succeeded, failed, or was already completed. Avoid reporting success before the underlying operation has actually finished.

Tool schemas and validation

Why schemas matter

A language model generates tool arguments probabilistically. It might supply a negative quantity, an unsupported currency, a missing identifier, or an incorrectly formatted value.

An ordinary Python type annotation is not sufficient runtime validation by itself.

LangChain uses schemas to describe and validate structured tool inputs. By default, it derives a schema from the decorated function’s signature.

For example:

  • str becomes a string field.
  • int becomes an integer field.
  • float becomes a numeric field.
  • bool becomes a Boolean field.
  • list[str] describes an array of strings.
  • Literal["USD", "EUR"] describes a restricted set of values.

Parameters without defaults are generally required. Parameters with defaults can generally be omitted.

Schema inference is convenient, but production tools frequently need additional constraints.

Inferred schemas versus explicit schemas

Feature Inferred schema Explicit Pydantic schema
Definition Function signature Dedicated model class
Type validation Supported Supported
Numeric boundaries Possible with annotations Explicit and convenient
Field descriptions Annotations or parsed docstrings Field(description=...)
Custom validators Less convenient Fully supported
Reusability Usually function-specific Easily reusable
Best use Small, straightforward tools Complex business operations

For simple utilities, inference may be sufficient. For tools involving customer data, financial calculations, external services, or application writes, explicit schemas make the contract easier to maintain.

Creating an explicit Pydantic schema

Pydantic provides runtime data validation through model classes.

The following example implements a validated invoice calculator with restricted currencies, bounded numeric inputs, and decimal arithmetic.

Python
from decimal import Decimal, ROUND_HALF_UP
from typing import Literal

from langchain.tools import tool
from pydantic import BaseModel, ConfigDict, Field, ValidationError

class InvoiceInput(BaseModel):
    model_config = ConfigDict(extra="forbid")

    unit_price: float = Field(
        gt=0,
        le=100000,
        allow_inf_nan=False,
        description="Price of one item before tax.",
    )

    quantity: int = Field(
        ge=1,
        le=1000,
        strict=True,
        description="Number of items being purchased.",
    )

    tax_percent: float = Field(
        default=0,
        ge=0,
        le=100,
        allow_inf_nan=False,
        description="Tax percentage, such as 18 for 18 percent.",
    )

    currency: Literal["USD", "EUR", "INR"] = Field(
        default="USD",
        description="Three-letter invoice currency.",
    )

@tool(args_schema=InvoiceInput)
def calculate_invoice(
    unit_price: float,
    quantity: int,
    tax_percent: float = 0,
    currency: str = "USD",
) -> dict:
    """Calculate invoice subtotal, tax, and final payable amount."""
    cents = Decimal("0.01")
    subtotal = (Decimal(str(unit_price)) * quantity).quantize(
        cents,
        rounding=ROUND_HALF_UP,
    )

    tax = (
        subtotal * Decimal(str(tax_percent)) / Decimal("100")
    ).quantize(cents, rounding=ROUND_HALF_UP)

    return {
        "subtotal": str(subtotal),
        "tax": str(tax),
        "total": str(subtotal + tax),
        "currency": currency,
    }

print(calculate_invoice.invoke({
    "unit_price": 100,
    "quantity": 3,
    "tax_percent": 18,
    "currency": "INR",
}))

try:
    calculate_invoice.invoke({
        "unit_price": 100,
        "quantity": -3,
    })
except ValidationError as error:
    print(error.errors()[0]["loc"])
    print(error.errors()[0]["type"])

Expected output:

Text
{'subtotal': '300.00', 'tax': '54.00', 'total': '354.00', 'currency': 'INR'}
('quantity',)
greater_than_equal

The example uses decimal arithmetic after parsing the input and returns monetary amounts as strings to preserve their displayed precision.

For systems requiring exact monetary input, consider accepting integer minor units or decimal strings rather than floating-point prices.

Understanding the validation process

When the calculator receives arguments, its Pydantic schema validates them before the underlying implementation runs.

The Field configuration introduces several constraints:

  • gt: Greater than.
  • ge: Greater than or equal to.
  • lt: Less than.
  • le: Less than or equal to.
  • min_length: Minimum string or collection length.
  • max_length: Maximum string or collection length.
  • pattern: Required string pattern.
  • strict: Restricts automatic type conversion.

ConfigDict(extra="forbid") rejects unexpected fields rather than silently ignoring them.

Without strict validation, Pydantic may perform useful conversions, such as converting the string "3" to the integer 3. Use strict validation where such conversions would violate the intended contract.

Inspecting the model-facing schema

Pydantic models generate JSON Schema representations. These describe fields, required arguments, supported values, and many validation constraints.

The following example shows how to inspect the public tool schema.

Python
import json
from typing import Literal

from langchain.tools import tool
from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(min_length=1, max_length=100)
    category: Literal["books", "electronics", "all"] = "all"
    limit: int = Field(default=5, ge=1, le=20)

@tool(args_schema=SearchInput)
def search_catalog(
    query: str,
    category: str = "all",
    limit: int = 5,
) -> dict:
    """Search the catalog using a keyword and optional category."""
    return {
        "query": query,
        "category": category,
        "limit": limit,
        "results": [],
    }

schema = search_catalog.tool_call_schema.model_json_schema()

print(json.dumps(schema, indent=2))

The generated schema contains an object with three properties: query, category, and limit.

The query field is required. The category contains an enumeration of allowed values, while the limit contains minimum and maximum constraints.

A provider integration can translate this schema into its own tool-calling representation. However, provider-side argument generation does not replace local validation.

Custom field and cross-field validation

Some business rules cannot be represented through simple numeric boundaries.

For instance, a date range requires its ending date to occur on or after its starting date.

The following example uses a Pydantic model validator to enforce a relationship between fields.

Python
from datetime import date

from langchain.tools import tool
from pydantic import BaseModel, ValidationError, model_validator

class DateRangeInput(BaseModel):
    start_date: date
    end_date: date

    @model_validator(mode="after")
    def validate_range(self):
        if self.end_date < self.start_date:
            raise ValueError("end_date must not precede start_date")
        return self

@tool(args_schema=DateRangeInput)
def calculate_days(start_date: date, end_date: date) -> int:
    """Calculate elapsed calendar days between two ISO dates."""
    return (end_date - start_date).days

print(calculate_days.invoke({
    "start_date": "2026-12-01",
    "end_date": "2026-12-10",
}))

try:
    calculate_days.invoke({
        "start_date": "2026-12-10",
        "end_date": "2026-12-01",
    })
except ValidationError:
    print("Invalid date range")

Expected output:

Text
9
Invalid date range

Use field_validator to normalize or validate individual fields and model_validator to enforce relationships between fields.

Note: Schema validation establishes whether input satisfies a contract. It does not establish whether the caller is authorized to perform an operation. Authorization and business invariants must also be enforced by application code.

Accessing state and context from a tool

A tool may require information that the language model should not generate.

Examples include authenticated user identifiers, tenant identifiers, application settings, conversation state, and persistent preferences.

LangChain provides ToolRuntime to make this information available during execution.

Understanding ToolRuntime

Import the runtime interface alongside the decorator:

Python
from langchain.tools import tool, ToolRuntime

A parameter declared as runtime: ToolRuntime is automatically supplied by the tool execution system when running in an appropriate graph or agent environment.

It is excluded from the model-facing tool schema.

The following properties are particularly important:

Property Purpose
runtime.state Current graph state
runtime.context Invocation-scoped application context
runtime.store Configured persistent store
runtime.tool_call_id Identifier of the current tool call
runtime.config Execution configuration
runtime.stream_writer Writer for custom streaming events
runtime.tools Tools available to the execution system

State and context serve different purposes.

State contains workflow data that can evolve during execution. Context carries dependencies and application information supplied for the current invocation and should be treated as read-only.

For example, a selected order identifier might belong in state, while an authenticated customer identifier belongs in context.

The following diagram illustrates how public arguments and internal runtime information reach a tool.

Accessing state and context from a tool diagram: Language Model to Public Arguments; Public Arguments to Custom Tool; Graph State to Tool Runtime; Invocation Context to Tool Runtime; Persistent Store to Tool Runtime; Tool Runtime to Custom Tool; Custom Tool to Tool Result.

Reading graph state and invocation context

The following example implements a customer-specific order lookup.

A minimal graph executes one predetermined tool call using ToolNode. This allows us to demonstrate runtime injection without involving a language model. Automatic tool selection and routing are covered in the next lesson.

Python
from dataclasses import dataclass

from langchain.messages import AIMessage
from langchain.tools import tool, ToolRuntime
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode

ORDERS = {
    "ORD-101": {"customer_id": "C-1", "status": "shipped"},
    "ORD-102": {"customer_id": "C-2", "status": "processing"},
}

class State(MessagesState):
    selected_order: str

@dataclass(frozen=True)
class Context:
    customer_id: str

@tool
def get_order_status(
    runtime: ToolRuntime[Context, State],
) -> dict:
    """Retrieve the shipping status of the currently selected order."""
    order_id = runtime.state["selected_order"]
    customer_id = runtime.context.customer_id

    order = ORDERS.get(order_id)

    if not order or order["customer_id"] != customer_id:
        return {"found": False, "message": "Order not available"}

    return {
        "found": True,
        "order_id": order_id,
        "status": order["status"],
    }

graph = (
    StateGraph(State, context_schema=Context)
    .add_node("tools", ToolNode([get_order_status]))
    .add_edge(START, "tools")
    .add_edge("tools", END)
    .compile()
)

def run_lookup(customer_id: str):
    return graph.invoke(
        {
            "selected_order": "ORD-101",
            "messages": [
                AIMessage(
                    content="",
                    tool_calls=[
                        {
                            "name": "get_order_status",
                            "args": {},
                            "id": "call_order_1",
                            "type": "tool_call",
                        }
                    ],
                )
            ],
        },
        context=Context(customer_id=customer_id),
    )

print(run_lookup("C-1")["messages"][-1].content)
print(run_lookup("C-2")["messages"][-1].content)

print(
    get_order_status.tool_call_schema
    .model_json_schema()["properties"]
)

Expected output, ignoring JSON whitespace:

Text
{"found": true, "order_id": "ORD-101", "status": "shipped"}
{"found": false, "message": "Order not available"}
{}

The public argument schema is empty because the tool obtains everything it needs from the runtime.

The customer identifier must originate from trusted authentication logic in a real application. Merely passing a value through context does not make that value trustworthy.

Use context_schema and the context invocation argument for application-specific runtime information rather than storing user data in config["configurable"].

Updating graph state from a tool

Returning a dictionary from a tool does not automatically update arbitrary graph state fields.

To explicitly request a state update, return a Command from langgraph.types.

The following example creates a tool that changes the active search category in graph state.

Python
from typing import Literal

from langchain.messages import AIMessage, ToolMessage
from langchain.tools import tool, ToolRuntime
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode
from langgraph.types import Command

class State(MessagesState):
    category: str

@tool
def set_category(
    category: Literal["books", "electronics"],
    runtime: ToolRuntime,
) -> Command:
    """Change the active product search category."""
    return Command(
        update={
            "category": category,
            "messages": [
                ToolMessage(
                    content=f"Active category changed to {category}",
                    tool_call_id=runtime.tool_call_id,
                )
            ],
        }
    )

graph = (
    StateGraph(State)
    .add_node("tools", ToolNode([set_category]))
    .add_edge(START, "tools")
    .add_edge("tools", END)
    .compile()
)

result = graph.invoke({
    "category": "books",
    "messages": [
        AIMessage(
            content="",
            tool_calls=[{
                "name": "set_category",
                "args": {"category": "electronics"},
                "id": "call_category_1",
                "type": "tool_call",
            }],
        )
    ],
})

print(result["category"])
print(result["messages"][-1].content)

Expected output:

Text
electronics
Active category changed to electronics

The Command communicates the intended update to LangGraph. The ToolMessage associates the result with the originating tool call.

This connects directly to the Pregel model: state changes should flow through the graph’s update mechanism rather than through uncontrolled in-place mutations.

Concurrent tools that update the same state field may require an appropriate reducer or serialized execution.

Accessing persistent storage

When a graph is compiled with a store, tools can access it through runtime.store.

For example, a preference-reading tool could retrieve a record using:

Python
runtime.store.get(("users", user_id), "preferences")

Stores support information that may need to survive across conversations, unlike ordinary invocation context.

Always account for the possibility that no store is configured, and namespace user records appropriately to prevent cross-tenant access.

Async tools

Many useful tools spend most of their execution time waiting for external services.

Typical examples include HTTP requests, database queries, file operations, and search services.

Asynchronous Python allows other work to proceed while an operation awaits I/O.

Synchronous versus asynchronous execution

Characteristic Synchronous tool Asynchronous tool
Function definition def async def
Direct invocation .invoke() await .ainvoke()
I/O waiting Occupies the executing thread Can yield to the event loop
Typical workload Calculations and simple operations Network and database requests
Concurrent I/O Requires additional coordination Supported through asyncio

A synchronous tool can also support asynchronous invocation through framework execution facilities. However, native asynchronous implementations are generally preferable for high-concurrency network operations.

Creating an asynchronous tool

The following example simulates a network-based inventory service. It uses asyncio.sleep() instead of a real external dependency.

Python
import asyncio

from langchain.tools import tool

INVENTORY = {
    "SKU-100": 12,
    "SKU-200": 0,
    "SKU-300": 7,
}

@tool
async def check_inventory(product_id: str) -> dict:
    """Retrieve available inventory for a product SKU."""
    await asyncio.sleep(0.2)

    if product_id not in INVENTORY:
        return {"found": False, "product_id": product_id}

    return {
        "found": True,
        "product_id": product_id,
        "available": INVENTORY[product_id],
    }

async def main():
    results = await asyncio.gather(
        check_inventory.ainvoke({"product_id": "SKU-100"}),
        check_inventory.ainvoke({"product_id": "SKU-200"}),
        check_inventory.ainvoke({"product_id": "SKU-300"}),
    )

    for result in results:
        print(result)

if __name__ == "__main__":
    asyncio.run(main())

Expected output:

Text
{'found': True, 'product_id': 'SKU-100', 'available': 12}
{'found': True, 'product_id': 'SKU-200', 'available': 0}
{'found': True, 'product_id': 'SKU-300', 'available': 7}

The three simulated I/O operations can overlap because each coroutine yields control while waiting.

An async-only tool should be executed using ainvoke(). When such a tool is executed inside a graph, use the graph’s asynchronous execution interface.

Making asynchronous HTTP requests

A realistic asynchronous tool can use httpx.AsyncClient to communicate with a REST API.

The following example retrieves a sample record from the public JSONPlaceholder testing service.

Python
import asyncio

import httpx
from langchain.tools import tool
from pydantic import BaseModel, Field

class PostInput(BaseModel):
    post_id: int = Field(ge=1, le=100)

@tool(args_schema=PostInput)
async def fetch_post(post_id: int) -> dict:
    """Retrieve a sample article using its numeric post ID."""
    url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"

    async with httpx.AsyncClient(timeout=10.0) as client:
        response = await client.get(url)
        response.raise_for_status()
        data = response.json()

    return {
        "id": data["id"],
        "title": data["title"],
    }

async def main():
    result = await fetch_post.ainvoke({"post_id": 1})
    print(result)

if __name__ == "__main__":
    asyncio.run(main())

The tool returns a dictionary containing the post identifier and title. This example requires internet access and depends on the availability of the external testing service.

Production integrations should additionally validate response data, manage authentication, reuse connections where appropriate, and distinguish temporary failures from permanent errors.

Tip: Declaring a function with async def does not automatically make blocking operations asynchronous. Avoid time.sleep(), synchronous HTTP clients, and blocking database calls inside async tools. Use async-compatible libraries or deliberately offload blocking work.

Testing tools on their own

One of the most important engineering practices is testing tools independently of language models.

An agent can fail because it selected the wrong operation, generated incorrect arguments, or received an incorrect result. Independent tool tests eliminate one major source of uncertainty.

Direct invocation tests

Use .invoke() with argument dictionaries to verify synchronous tools. Use .ainvoke() for asynchronous tools.

Direct tests should exercise the decorated tool rather than exclusively calling its underlying Python function, because the wrapper performs input validation and other execution behavior.

Testing with pytest

The following complete example tests a calculator tool for successful execution, boundary values, and invalid input.

Save it as test_tools.py.

Python
from typing import Literal

import pytest
from langchain.tools import tool
from pydantic import BaseModel, Field, ValidationError

class CalculatorInput(BaseModel):
    operation: Literal["add", "subtract", "multiply"]
    a: int = Field(ge=-10000, le=10000)
    b: int = Field(ge=-10000, le=10000)

@tool(args_schema=CalculatorInput)
def calculator(operation: str, a: int, b: int) -> int:
    """Perform integer addition, subtraction, or multiplication."""
    if operation == "add":
        return a + b

    if operation == "subtract":
        return a - b

    if operation == "multiply":
        return a * b

    raise ValueError("Unsupported operation")

@pytest.mark.parametrize(
    "operation,a,b,expected",
    [
        ("add", 10, 5, 15),
        ("subtract", 10, 5, 5),
        ("multiply", 10, 5, 50),
        ("multiply", 0, 100, 0),
        ("add", -10000, 10000, 0),
    ],
)
def test_valid_operations(operation, a, b, expected):
    result = calculator.invoke({
        "operation": operation,
        "a": a,
        "b": b,
    })

    assert result == expected

@pytest.mark.parametrize(
    "arguments",
    [
        {"operation": "divide", "a": 10, "b": 2},
        {"operation": "add", "a": 10001, "b": 1},
        {"operation": "add", "a": 1},
        {"operation": "add", "a": "invalid", "b": 2},
    ],
)
def test_invalid_inputs(arguments):
    with pytest.raises(ValidationError):
        calculator.invoke(arguments)

def test_tool_message():
    message = calculator.invoke({
        "name": "calculator",
        "args": {"operation": "add", "a": 2, "b": 3},
        "id": "call_test_1",
        "type": "tool_call",
    })

    assert message.tool_call_id == "call_test_1"
    assert message.content == "5"

Run the tests:

Terminal
pytest -q test_tools.py

Expected output:

Text
10 passed

The final test verifies message packaging, not just the underlying calculation. This helps ensure that the tool behaves appropriately when integrated into an agent.

Testing tools that require ToolRuntime

A runtime-dependent tool cannot generally be tested by supplying only its public arguments through ordinary direct invocation.

Test it at two levels:

  1. Extract business logic into ordinary functions and test those functions independently.
  2. Execute the decorated tool inside a minimal graph with controlled state, context, and storage.

The order lookup example earlier in this lesson illustrates the second approach.

For asynchronous tools, use pytest-asyncio or run an asynchronous test coroutine through asyncio.run(). Mock external services so routine tests do not depend on network availability.

Common mistakes and production best practices

Tool quality directly affects the reliability of an agent. A sophisticated model cannot consistently compensate for ambiguous interfaces or incorrect implementations.

Common mistake Better approach
Missing type hints Declare every public input explicitly
Vague tool descriptions Document purpose and operational boundaries
Unrestricted expression execution Expose a controlled set of operations
Unbounded search results Validate and enforce result limits
Model-generated user identity Inject authenticated identity through context
Direct state mutation Return explicit graph updates
Blocking I/O in async tools Use asynchronous clients
Testing only through an LLM Add deterministic tool-level tests
Returning raw exceptions or secrets Expose sanitized, appropriate error information

Designing for safe execution

Treat model-generated arguments and retrieved external content as untrusted data.

A calculator should not use unrestricted eval(). A database lookup should not concatenate model-generated strings into SQL statements. Tools should expose narrow operations, enforce resource limits, and use parameterized queries.

Read-only tools are usually easier to reason about than tools that perform irreversible writes.

For write operations, consider authorization, human approval where appropriate, and idempotency. A retry or resumed execution must not accidentally create duplicate orders or charge a customer twice.

Graph checkpointing does not automatically make external side effects transactional.

Keeping tools maintainable

Separate business logic from the tool interface whenever complexity increases.

A practical architecture might contain a Pydantic schema, a decorated wrapper, a business service, and a repository or external API client. This separation makes it easier to reuse logic outside an agent, replace dependencies, and test behavior independently.

For the chapter project, the search tool, calculator, and database lookup should each expose a narrow, independently testable contract. Their implementations may use different technologies, but their standardized tool interfaces allow the agent to interact with them consistently.

Connecting to the next lesson

You can now create tools with explicit contracts, validate their arguments, access internal graph information, execute asynchronous operations, and test behavior without a language model.

However, defining a tool does not automatically make it available to a model or determine when it should execute.

In the next lesson, Binding tools, ToolNode and tools_condition, you will connect these independently developed tools to a tool-capable chat model, inspect generated tool calls, execute them through LangGraph, and conditionally route the workflow based on the model’s response.

That integration will establish the foundation for building a complete ReAct agent from scratch.

Exercise

Build a validated product search tool

Build a custom tool that searches an in-memory product catalog by keyword, category, and maximum price. Use a Pydantic input schema to validate search arguments and limit the number of returned products. Return structured results and write assertions covering successful searches, empty results, and invalid inputs.

Python
from typing import Literal

from langchain.tools import tool
from pydantic import BaseModel, Field, ValidationError

PRODUCTS = [
    {"id": 1, "name": "Wireless Mouse", "category": "electronics", "price": 25},
    {"id": 2, "name": "Mechanical Keyboard", "category": "electronics", "price": 85},
    {"id": 3, "name": "Python Programming", "category": "books", "price": 40},
    {"id": 4, "name": "Python Cookbook", "category": "books", "price": 55},
    {"id": 5, "name": "Office Chair", "category": "furniture", "price": 150},
]

class ProductSearchInput(BaseModel):
    # TODO: Define query, category, max_price, and limit.
    pass

# TODO: Apply the tool decorator with the explicit input schema.
def search_products(
    query: str,
    category: str = "all",
    max_price: float = 1000,
    limit: int = 5,
) -> dict:
    """Search the product catalog using optional filters."""
    # TODO: Filter products using case-insensitive matching.
    # TODO: Apply category and price filters.
    # TODO: Sort results by price and apply the limit.
    # TODO: Return a dictionary containing count and products.
    raise NotImplementedError

# TODO: Test a successful search.
# TODO: Test a search with no matching products.
# TODO: Verify invalid arguments raise ValidationError.

Summary

  • The @tool decorator transforms a Python function into a tool with a name, description, input schema, and standardized execution interface.
  • Clear tool descriptions and meaningful parameter names help language models select tools and generate appropriate arguments.
  • Pydantic schemas provide runtime validation, input constraints, normalization, and explicit parameter documentation.
  • ToolRuntime gives tools access to graph state, invocation context, persistent storage, and execution metadata without exposing those parameters to the model.
  • Tools should return concise, structured results and use Command when explicitly updating graph state.
  • Asynchronous tools support efficient concurrent I/O without blocking the event loop.
  • Every custom tool should be tested independently for valid inputs, invalid inputs, boundary conditions, and expected business behavior.