Mastering Tools in LangChain.js
Aug 25,2026

Introduction

Until now, we've mostly used LLMs to generate text.

For example:

User
 ↓
Prompt
 ↓
OpenAI / Gemini
 ↓
Text Response

Suppose we ask:

What is Node.js?

The model can generate an answer.

But now consider a different question:

What is the current weather in Hyderabad?

The model cannot reliably know the current weather simply by generating text.

We need an external capability:

Weather API

The workflow becomes:

User
 ↓
LLM
 ↓
Weather Tool
 ↓
Weather API
 ↓
Tool Result
 ↓
LLM
 ↓
Final Response

This is where Tools become extremely important.

A tool allows an LLM application to interact with functionality outside the model itself.

Examples include:

  • Weather APIs

  • Database queries

  • Search APIs

  • Payment systems

  • File systems

  • Calculators

  • Internal business APIs

  • Order management systems

  • Email services

  • CRM systems

In this article, we'll learn:

  • What tools are

  • Why tools are needed

  • Tool calling

  • Function calling

  • Creating custom tools

  • Tool schemas

  • Zod validation

  • tool()

  • Tool descriptions

  • Tool arguments

  • Binding tools to OpenAI

  • Binding tools to Gemini

  • Calling tools manually

  • Understanding AI tool calls

  • Executing tool calls

  • Returning ToolMessage

  • Tool workflows

  • Multiple tools

  • Practical examples

  • Common mistakes

  • Security considerations

  • Tools vs Runnables

  • Tools vs Agents

Let's get started.


What Is a Tool?

A tool is a callable function that an AI model can request your application to execute.

For example:

function getWeather(city) {
  // call weather API
}

The model doesn't directly execute the JavaScript function.

Instead, it decides:

"I need weather information."

and produces a structured tool call:

Tool:
getWeather

Arguments:
{
  city: "Hyderabad"
}

Your application executes the function:

getWeather("Hyderabad")

and sends the result back to the model.


The Basic Tool Calling Flow

The complete process looks like:

                 User
                  ↓
               LLM
                  ↓
          Need a tool?
             /       \
           No         Yes
           ↓           ↓
       Response     Tool Call
                       ↓
                 Application
                       ↓
                  Tool Function
                       ↓
                  Tool Result
                       ↓
                      LLM
                       ↓
                 Final Response

This is one of the most important patterns in modern LLM applications.


Why Do We Need Tools?

LLMs are very good at:

  • Understanding language

  • Generating text

  • Reasoning about provided information

  • Transforming information

  • Producing structured output

But an LLM doesn't automatically have access to:

Your Database
Your APIs
Your Application
Current External Data
Private Systems

Tools provide that connection.


Example Without a Tool

User:

What is 25 × 40?

The model can calculate or reason about the answer.

1000

Example With a Tool

Suppose we create:

calculate

The model could request:

{
  "a": 25,
  "b": 40,
  "operation": "multiply"
}

The application executes the function:

calculate(25, 40, "multiply");

and returns:

1000

Another Example: Database Tool

Suppose we have:

getUser

The model could request:

{
  "userId": 101
}

Your application executes:

getUser(101);

and returns:

{
  "id": 101,
  "name": "Sundar",
  "role": "Developer"
}

The LLM can then convert that result into a natural-language response.


Tool Calling vs Function Calling

You may hear both terms:

Function Calling
Tool Calling

The concepts are closely related.

Historically, providers often described this capability as function calling.

Modern LangChain terminology generally uses tools and tool calling.

The important idea is:

LLM
 ↓
Structured request
 ↓
Application function
 ↓
Result

LangChain Tool

LangChain provides utilities for defining tools.

A common approach is:

import { tool } from "@langchain/core/tools";

We can then define a tool with:

  • A name

  • A description

  • An input schema

  • A function


Project Setup

Let's create a project.

mkdir langchain-tools
cd langchain-tools
npm init -y

Install the required packages:

npm install @langchain/core @langchain/openai @langchain/google-genai dotenv zod

Project Structure

langchain-tools/
│
├── index.js
├── .env
├── .gitignore
└── package.json

Environment Variables

Create .env:

OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key

Create .gitignore:

node_modules/
.env

Never commit API keys.


Step 1 — Import tool

import { tool } from "@langchain/core/tools";

We also need Zod:

import { z } from "zod";

Step 2 — Create a Simple Tool

Let's create a calculator tool.

const calculatorTool = tool(
  async ({ a, b }) => {
    return a + b;
  },
  {
    name: "add_numbers",

    description:
      "Add two numbers together.",

    schema: z.object({
      a: z.number(),
      b: z.number(),
    }),
  }
);

We have created our first LangChain tool.


Understanding the Tool

Let's break it down.

Function

async ({ a, b }) => {
  return a + b;
}

This is the actual code executed by your application.


Name

name: "add_numbers"

This identifies the tool.

The model can request:

add_numbers

Description

description:
  "Add two numbers together."

This is extremely important.

The model uses the tool description to understand when the tool should be used.


Schema

schema: z.object({
  a: z.number(),
  b: z.number(),
})

The schema defines the expected arguments.

The tool expects:

{
  "a": 10,
  "b": 20
}

Why Is the Schema Important?

Without a schema, the model doesn't have a clear contract for the tool arguments.

With:

z.object({
  a: z.number(),
  b: z.number(),
})

the tool expects:

a → number
b → number

This helps both the model and your application.


Tool Schema as a Contract

Think of a tool schema as an API contract.

Tool
 ↓
Input Schema
 ↓
Validated Arguments
 ↓
Function

For example:

{
  a: 10,
  b: 20
}

is valid.

But:

{
  a: "ten",
  b: 20
}

doesn't satisfy:

z.number()

Step 3 — Inspect the Tool

We can inspect:

console.log(
  calculatorTool.name
);

and:

console.log(
  calculatorTool.description
);

The tool contains the metadata necessary for the model to understand its capability.


Step 4 — Initialize OpenAI

import {
  ChatOpenAI,
} from "@langchain/openai";

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

Step 5 — Bind the Tool

Now we tell the model that the tool is available.

const modelWithTools =
  model.bindTools([
    calculatorTool,
  ]);

This is an important concept.

The model now knows:

Available Tool:
add_numbers

What Does bindTools() Do?

bindTools() doesn't mean the model has executed the tool.

It means:

Make these tools available to the model during generation.

The model can now decide whether it needs to call one.

Think:

Model
 ↓
Available Tools
 ├── add_numbers
 ├── get_weather
 └── get_user

Step 6 — Invoke the Model

const response =
  await modelWithTools.invoke(
    "What is 25 + 40?"
  );

console.log(response);

The model may return an AIMessage containing a tool call.

Instead of immediately getting:

65

you may see structured information representing:

Tool Call:
add_numbers

Arguments:
{
  a: 25,
  b: 40
}

AIMessage and Tool Calls

The model response can contain:

response.tool_calls

For example:

console.log(
  response.tool_calls
);

Conceptually:

[
  {
    name: "add_numbers",
    args: {
      a: 25,
      b: 40
    }
  }
]

This is a critical concept.

The LLM is requesting that the tool be executed.

It hasn't necessarily executed your JavaScript function itself.


Important: The LLM Doesn't Directly Execute Your Function

This is one of the most important concepts.

The model produces:

Tool Call

Your application executes:

calculatorTool

The architecture is:

LLM
 ↓
Tool Call
 ↓
Your Application
 ↓
Tool Function
 ↓
Tool Result

The application remains in control.


Executing the Tool

We can inspect the tool call:

const toolCall =
  response.tool_calls[0];

Then execute the tool.

Depending on the LangChain.js version, tools can be invoked directly with their arguments.

For example:

const result =
  await calculatorTool.invoke(
    toolCall.args
  );

console.log(result);

Output:

65

But We Still Need to Send the Result Back to the Model

We're not finished yet.

The model initially said:

Call add_numbers(25, 40)

Our application executes:

65

Now we need to send:

65

back to the model.

The complete conversation becomes:

Human:
What is 25 + 40?

AI:
Tool Call → add_numbers

Tool:
65

AI:
25 + 40 = 65

This allows the model to produce the final natural-language response.


ToolMessage

LangChain represents tool results using:

ToolMessage

Import:

import {
  ToolMessage,
} from "@langchain/core/messages";

A tool message associates the result with the tool call.

Conceptually:

new ToolMessage({
  content: "65",
  tool_call_id: toolCall.id,
});

The tool_call_id is important because it connects the result to the original tool request.


Complete Manual Tool Calling Flow

Let's build the flow ourselves.

const response =
  await modelWithTools.invoke(
    "What is 25 + 40?"
  );

console.log(
  response.tool_calls
);

Then:

const toolCall =
  response.tool_calls[0];

Execute:

const result =
  await calculatorTool.invoke(
    toolCall.args
  );

Create a tool message:

const toolMessage =
  new ToolMessage({
    content: String(result),
    tool_call_id:
      toolCall.id,
  });

Then send the conversation back to the model.


Why Does the Model Need the Tool Result?

Because the model needs to incorporate the result into its final answer.

For example:

Tool:
65

The model can then respond:

25 + 40 equals 65.

The model is responsible for generating the final natural-language response.


The Complete Tool Loop

The complete process is:

                 User
                  ↓
                 LLM
                  ↓
              Tool Call
                  ↓
           Execute Function
                  ↓
             Tool Result
                  ↓
                 LLM
                  ↓
            Final Response

This is the fundamental tool-calling loop.


Creating a Weather Tool

Let's build a more realistic example.

We'll create a simple weather tool.

For now, instead of calling a real API, we'll return mock data.

const weatherTool = tool(
  async ({ city }) => {
    return {
      city,
      temperature: 30,
      condition: "Sunny",
    };
  },
  {
    name: "get_weather",

    description:
      "Get the current weather for a city.",

    schema: z.object({
      city: z
        .string()
        .describe(
          "The city to get weather for"
        ),
    }),
  }
);

Why Use .describe()?

Look at:

city: z
  .string()
  .describe(
    "The city to get weather for"
  )

This gives additional information about the field.

The model sees that:

city

represents:

The city to get weather for

Good descriptions improve tool selection and argument generation.


Tool Description Is Extremely Important

Consider:

description:
  "Get data."

This is too vague.

Better:

description:
  "Get the current weather for a specified city."

Even better:

description:
  `
Get the current weather for a city.

Use this tool when the user asks
about current weather conditions.
`

The description acts as guidance for the model.


Creating a Database Tool

Suppose we have:

const getUserTool = tool(
  async ({ userId }) => {
    return {
      id: userId,
      name: "Sundar",
      role: "Frontend Developer",
    };
  },
  {
    name: "get_user",

    description:
      "Retrieve a user's profile by user ID.",

    schema: z.object({
      userId: z
        .number()
        .describe(
          "The unique user ID"
        ),
    }),
  }
);

The model can request:

get_user

with:

{
  "userId": 101
}

Multiple Tools

We don't have to provide only one tool.

We can provide several:

const modelWithTools =
  model.bindTools([
    calculatorTool,
    weatherTool,
    getUserTool,
  ]);

Now the model has:

Available Tools

1. add_numbers
2. get_weather
3. get_user

How Does the Model Choose a Tool?

The model looks at:

  • User request

  • Tool names

  • Tool descriptions

  • Input schemas

For example:

User:
What's the weather in Hyderabad?

The model may choose:

get_weather

For:

What is 20 + 50?

it may choose:

add_numbers

For:

Get user 101

it may choose:

get_user

Tool Selection

Conceptually:

User Request
      ↓
     LLM
      ↓
Understand Intent
      ↓
Choose Tool
      ↓
Generate Arguments

The model doesn't necessarily need you to write:

if (question.includes("weather")) {
  getWeather();
}

The model can select the appropriate tool based on the tool metadata.


Tool Calling With Gemini

The same architecture can be used with Gemini.

Initialize:

import {
  ChatGoogleGenerativeAI,
} from "@langchain/google-genai";

const gemini =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

Bind the tool:

const geminiWithTools =
  gemini.bindTools([
    calculatorTool,
    weatherTool,
  ]);

Then:

const response =
  await geminiWithTools.invoke(
    "What is the weather in Hyderabad?"
  );

Gemini can return a structured tool call.

The overall architecture remains the same:

Gemini
 ↓
Tool Call
 ↓
Your Application
 ↓
Tool
 ↓
Tool Result
 ↓
Gemini
 ↓
Final Response

OpenAI vs Gemini Tool Calling

The application architecture is nearly identical.

OpenAI

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

const modelWithTools =
  model.bindTools([
    weatherTool,
  ]);

Gemini

const model =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

const modelWithTools =
  model.bindTools([
    weatherTool,
  ]);

The same LangChain tool can be used.

This is one of the major benefits of using LangChain.


Tool Schema With Multiple Fields

Let's create a search tool.

const searchTool = tool(
  async ({
    query,
    limit,
  }) => {

    return {
      query,
      limit,
      results: [],
    };
  },

  {
    name: "search_products",

    description:
      "Search products using a search query and result limit.",

    schema: z.object({
      query: z
        .string()
        .describe(
          "Product search query"
        ),

      limit: z
        .number()
        .min(1)
        .max(20)
        .describe(
          "Maximum number of results"
        ),
    }),
  }
);

The schema becomes:

search_products(
    query: string,
    limit: number
)

Optional Fields

Zod also allows optional values.

schema: z.object({
  query: z.string(),

  limit:
    z.number()
      .optional(),
})

The model may provide:

{
  "query": "React books"
}

without specifying limit.


Default Values

You can also define defaults.

schema: z.object({
  query: z.string(),

  limit:
    z.number()
      .default(10),
})

This means if the value isn't provided, your schema can use:

10

as the default.


Enum Values

Suppose we create an order tool.

const orderTool = tool(
  async ({
    orderId,
    action,
  }) => {

    return {
      orderId,
      action,
      status: "success",
    };
  },

  {
    name: "manage_order",

    description:
      "Perform an action on an order.",

    schema: z.object({
      orderId:
        z.string(),

      action:
        z.enum([
          "track",
          "cancel",
        ]),
    }),
  }
);

Now the model knows that:

action

can only be:

track
cancel

This is much safer than accepting arbitrary strings.


Nested Tool Schemas

Zod can also define nested objects.

const createUserTool = tool(
  async ({
    user,
  }) => {

    return {
      message:
        `Created ${user.name}`,
    };
  },

  {
    name: "create_user",

    description:
      "Create a new user.",

    schema: z.object({
      user: z.object({
        name:
          z.string(),

        email:
          z.string().email(),

        age:
          z.number(),
      }),
    }),
  }
);

The expected input becomes:

{
  "user": {
    "name": "John",
    "email": "john@example.com",
    "age": 30
  }
}

Tools Can Call External APIs

A real tool isn't limited to local JavaScript.

For example:

const weatherTool = tool(
  async ({ city }) => {

    const response =
      await fetch(
        `https://api.example.com/weather?city=${city}`
      );

    return response.json();
  },

  {
    name: "get_weather",

    description:
      "Get current weather information.",

    schema: z.object({
      city: z.string(),
    }),
  }
);

Now:

LLM
 ↓
get_weather
 ↓
External API
 ↓
Weather Data
 ↓
LLM

This is where tools become extremely powerful.


Tools Can Access Databases

For example:

const getOrdersTool = tool(
  async ({ userId }) => {

    const orders =
      await database.orders.findMany({
        userId,
      });

    return orders;
  },

  {
    name: "get_user_orders",

    description:
      "Get all orders for a user.",

    schema: z.object({
      userId: z.number(),
    }),
  }
);

Now the AI can request:

get_user_orders

and your backend performs the database query.


Tools Can Perform Actions

Tools don't have to be read-only.

They can perform actions such as:

Create order
Cancel order
Send email
Create ticket
Update profile
Schedule appointment

For example:

const createTicketTool =
  tool(
    async ({
      title,
      description,
    }) => {

      // Create ticket
      return {
        ticketId: "T-1001",
        status: "created",
      };
    },

    {
      name:
        "create_support_ticket",

      description:
        "Create a support ticket.",

      schema:
        z.object({
          title:
            z.string(),

          description:
            z.string(),
        }),
    }
  );

Read Tools vs Action Tools

This distinction is important.

Read Tool

Retrieves information:

get_weather
get_user
search_products
get_orders

Action Tool

Changes something:

create_order
cancel_order
send_email
delete_user

Action tools require additional security considerations.


Tool Calling and Human Approval

For sensitive actions, you may want:

User
 ↓
LLM
 ↓
Tool Call
 ↓
Approval Required
 ↓
Human
 ↓
Approve
 ↓
Tool Execution

For example:

Send email?
[Approve] [Cancel]

This prevents an AI model from automatically performing high-impact operations.


Tool Execution Should Be Controlled by Your Application

This is a critical security principle.

Don't think:

LLM
 ↓
Directly execute anything

Instead:

LLM
 ↓
Tool Request
 ↓
Application Validation
 ↓
Authorization
 ↓
Tool Execution

Your application remains in control.


Tool Arguments Must Be Validated

Suppose a tool expects:

userId: z.number()

Don't blindly trust the model's arguments.

Zod provides validation.

For example:

schema: z.object({
  userId:
    z.number().int().positive(),
})

This rejects invalid values such as:

-1

or:

"hello"

Tool Security

Tools can potentially access sensitive systems.

For example:

Database
Payment API
Email Service
File System
Admin API

Therefore, never assume:

"The model asked for it, so execute it."

Instead, validate:

Who is the user?
 ↓
Are they authorized?
 ↓
Is the operation allowed?
 ↓
Are arguments valid?
 ↓
Execute tool

Example: Dangerous Tool

Imagine:

const deleteUserTool = tool(
  async ({ userId }) => {
    await database.deleteUser(
      userId
    );

    return "Deleted";
  },
  {
    name: "delete_user",
    description:
      "Delete a user account.",
    schema: z.object({
      userId: z.number(),
    }),
  }
);

You should not blindly allow the model to execute this.

A safer architecture is:

LLM
 ↓
delete_user request
 ↓
Authorization
 ↓
Human confirmation
 ↓
Delete User

Tool Names Should Be Clear

Prefer:

get_weather
get_user_orders
search_products
create_support_ticket

Avoid:

tool1
tool2
execute
process

Clear names help the model understand what each tool does.


Tool Descriptions Should Be Specific

Bad:

description:
  "Get information."

Good:

description:
  "Get the current weather for a specified city."

Better:

description:
  `
Get the current weather for a city.

Use this tool when the user asks
about current temperature or weather
conditions.
`

Tools and Runnables

Tools and Runnables are related but not identical.

A Runnable represents a unit of executable LangChain logic.

For example:

RunnableSequence
RunnableParallel
RunnableLambda

A Tool represents a capability that can be exposed to an AI model for tool calling.

Conceptually:

Runnable
 ↓
Application Workflow

while:

Tool
 ↓
AI-callable Capability

A tool can participate in Runnable workflows, but its main purpose is to provide an interface that models can call.


Tools vs RunnableLambda

You might ask:

Why not just use RunnableLambda?

For example:

const add =
  RunnableLambda.from(
    ({ a, b }) => a + b
  );

This is a Runnable.

But the model doesn't automatically know that it can call:

add

A tool has metadata designed for model tool calling:

Name
Description
Schema
Function

So:

RunnableLambda
 ↓
Application logic

while:

Tool
 ↓
Model-callable capability

Tools vs Agents

Another important distinction.

A tool is a capability:

get_weather

An agent is a system that can decide:

Which tool should I use?
In what order?
Should I call another tool?
When should I stop?

Conceptually:

Agent
 ├── Tool A
 ├── Tool B
 └── Tool C

We'll explore agents later in this series.


Multiple Tool Calls

A model may request multiple tools.

For example:

User:
Compare the weather in Hyderabad and Bangalore.

The model might request:

get_weather("Hyderabad")
get_weather("Bangalore")

The application can execute both.

Conceptually:

             ┌──→ Hyderabad Weather
LLM ─────────┤
             └──→ Bangalore Weather

Then the results are returned to the model.


Tool Calling Loop with Multiple Tools

The workflow becomes:

User
 ↓
LLM
 ↓
Tool Call 1
Tool Call 2
 ↓
Execute Tools
 ↓
Results
 ↓
LLM
 ↓
Final Response

Depending on the model and workflow, tool calls may be handled sequentially or in parallel.


Tool Calling with a Prompt

Tools can also be used with our existing prompt architecture.

const prompt =
  ChatPromptTemplate.fromMessages([
    [
      "system",
      "You are a helpful assistant.",
    ],

    [
      "human",
      "{input}",
    ],
  ]);

Then:

const chain =
  prompt.pipe(
    modelWithTools
  );

Now:

Prompt
 ↓
Model with Tools
 ↓
Tool Call

Tool Calling with Message History

We learned RunnableWithMessageHistory in Blog 16.

Tools can also be combined with conversation history.

The architecture becomes:

User
 ↓
Message History
 ↓
Prompt
 ↓
LLM
 ↓
Tool Call
 ↓
Tool
 ↓
Tool Result
 ↓
LLM
 ↓
Response
 ↓
Save History

This is a very common architecture for conversational AI assistants.


Tool Calling with Configurable Runnables

We also learned configurable Runnables in Blog 17.

Now we can combine:

Configurable Model
       ↓
OpenAI / Gemini
       ↓
Tools

For example:

provider = openai
       ↓
OpenAI + Tools

or:

provider = gemini
       ↓
Gemini + Tools

This creates a flexible tool-enabled AI workflow.


Example Architecture

We can now build:

                    ┌──→ Weather Tool
                    │
User → History → LLM ├──→ Database Tool
                    │
                    └──→ Search Tool
                         ↓
                     Tool Result
                         ↓
                         LLM
                         ↓
                    Final Response

This is the foundation for AI assistants that can actually interact with external systems.


Complete Simple Tool Example

Let's create a complete calculator example.

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

import {
  tool,
} from "@langchain/core/tools";

import {
  z,
} from "zod";

const calculatorTool =
  tool(
    async ({ a, b }) => {
      return a + b;
    },

    {
      name:
        "add_numbers",

      description:
        "Add two numbers together.",

      schema:
        z.object({
          a:
            z.number(),

          b:
            z.number(),
        }),
    }
  );

const model =
  new ChatOpenAI({
    model:
      "gpt-4.1-mini",
  });

const modelWithTools =
  model.bindTools([
    calculatorTool,
  ]);

const response =
  await modelWithTools.invoke(
    "What is 100 + 250?"
  );

console.log(
  response.tool_calls
);

The model may produce a tool call similar to:

[
  {
    name: "add_numbers",
    args: {
      a: 100,
      b: 250
    }
  }
]

The important thing is that the model has identified the appropriate tool and generated structured arguments.


Building a Weather Tool

Let's create another complete example.

const weatherTool =
  tool(
    async ({ city }) => {

      // In a real application,
      // call a weather API here.

      return {
        city,
        temperature: 30,
        condition:
          "Sunny",
      };
    },

    {
      name:
        "get_weather",

      description:
        "Get the current weather for a city.",

      schema:
        z.object({
          city:
            z.string()
              .describe(
                "City name"
              ),
        }),
    }
  );

Bind it:

const modelWithTools =
  model.bindTools([
    weatherTool,
  ]);

Invoke:

const response =
  await modelWithTools.invoke(
    "What is the weather in Hyderabad?"
  );

The model may request:

get_weather
{
  city: "Hyderabad"
}

Your application executes the tool.


Tool Result

The tool returns:

{
  city: "Hyderabad",
  temperature: 30,
  condition: "Sunny"
}

The model receives the result and can generate:

The current weather in Hyderabad is
30°C and sunny.

The Complete Mental Model

Remember this:

                 ┌──────────────┐
                 │     User     │
                 └──────┬───────┘
                        ↓
                 ┌──────────────┐
                 │     LLM      │
                 └──────┬───────┘
                        ↓
                 ┌──────────────┐
                 │  Tool Call   │
                 └──────┬───────┘
                        ↓
                 ┌──────────────┐
                 │ Application   │
                 └──────┬───────┘
                        ↓
                 ┌──────────────┐
                 │    Tool      │
                 └──────┬───────┘
                        ↓
                 ┌──────────────┐
                 │ Tool Result  │
                 └──────┬───────┘
                        ↓
                 ┌──────────────┐
                 │     LLM      │
                 └──────┬───────┘
                        ↓
                 Final Response

This is the core architecture you should remember.


Common Beginner Mistakes

Mistake 1 — Thinking the LLM Executes the Tool

The LLM doesn't directly execute your JavaScript function.

It requests:

Tool Call

Your application executes the function.


Mistake 2 — Poor Tool Descriptions

The model depends heavily on tool metadata.

Avoid:

"Do stuff"

Use:

"Get the current weather for a specified city."

Mistake 3 — Missing Schema

Don't create tools without clearly defining expected arguments.

Use Zod:

schema: z.object({
  city: z.string(),
})

Mistake 4 — Trusting Tool Arguments

Validate arguments before performing sensitive operations.


Mistake 5 — Exposing Dangerous Tools Without Authorization

Don't allow an LLM to automatically:

Delete accounts
Transfer money
Cancel orders
Send sensitive emails

without appropriate controls.


Mistake 6 — Forgetting Tool Results

The model needs the tool result to generate the final response.

The complete flow is:

Tool Call
 ↓
Execute
 ↓
Tool Result
 ↓
LLM
 ↓
Final Response

Best Practices

1. Keep tools focused

A tool should generally have one clear responsibility.

Good:

get_weather

Instead of:

do_everything

2. Use strong schemas

Use Zod to define exactly what the tool expects.


3. Write detailed descriptions

Tell the model:

  • What the tool does

  • When to use it

  • What the arguments mean

  • Any important restrictions


4. Validate sensitive operations

For destructive or financial operations:

Validate
 ↓
Authorize
 ↓
Confirm
 ↓
Execute

5. Keep tool results concise

Don't return unnecessary data.

Instead of returning:

Entire database record

return only the information required by the model.


6. Handle tool errors

Tools can fail.

For example:

API unavailable
Database error
Invalid input
Timeout

Your application should handle these failures gracefully.


What Happens When a Tool Fails?

Suppose:

LLM
 ↓
get_weather
 ↓
Weather API
 ↓
❌ Error

You need an error strategy.

Possible approaches:

Tool Error
 ↓
Retry

or:

Tool Error
 ↓
Fallback API

or:

Tool Error
 ↓
Return error to LLM
 ↓
LLM explains failure

This connects directly with our previous topic:

RunnableWithFallbacks


Tools + Fallbacks

Imagine:

get_weather
     ↓
Weather API
     ↓
Failure
     ↓
Backup Weather API

This can make tools more resilient.

The architecture becomes:

LLM
 ↓
Weather Tool
 ↓
Primary API
 ↓
Fallback API
 ↓
Result
 ↓
LLM

Tools + Message History + Configuration

We can now combine several concepts from this series:

                   ┌──→ OpenAI
                   │
User → History → Configurable Model
                   │
                   └──→ Gemini
                         ↓
                       Tools
                         ↓
                    Tool Results
                         ↓
                        LLM
                         ↓
                    Final Answer

This is becoming a complete AI application architecture.


The Bigger Picture

Let's review what we've learned throughout the series.

PromptTemplate
      ↓
ChatPromptTemplate
      ↓
Output Parsers
      ↓
Runnable Interface
      ↓
RunnableSequence
      ↓
RunnableParallel
      ↓
RunnableLambda
      ↓
RunnablePassthrough
      ↓
RunnableAssign
      ↓
RunnableBranch
      ↓
RunnableWithFallbacks
      ↓
RunnableWithMessageHistory
      ↓
Configurable Runnables
      ↓
Tools

Tools are an important transition point.

Previously:

LLM → Response

Now:

LLM → Tool → External System → LLM → Response

This is where AI applications become capable of taking actions.


Final Thoughts

Tools are one of the most important concepts in modern AI application development.

An LLM by itself mainly generates or transforms information:

User
 ↓
LLM
 ↓
Text

Tools extend the model's capabilities:

User
 ↓
LLM
 ↓
Tool
 ↓
External System
 ↓
Tool Result
 ↓
LLM
 ↓
Final Response

A LangChain tool generally contains four important pieces:

Tool
 ├── Name
 ├── Description
 ├── Schema
 └── Function

For example:

const weatherTool =
  tool(
    async ({ city }) => {
      // API call
    },

    {
      name:
        "get_weather",

      description:
        "Get the current weather for a city.",

      schema:
        z.object({
          city:
            z.string(),
        }),
    }
  );

Then expose it to a model:

const modelWithTools =
  model.bindTools([
    weatherTool,
  ]);

The model can request:

get_weather

Your application executes the tool and returns the result.

The most important mental model is:

The model decides what it needs; your application decides whether and how to execute it.

That distinction is critical for security and production AI development.

Once you understand tools, you can start building AI applications that interact with:

  • APIs

  • Databases

  • Search systems

  • Internal services

  • Business workflows

  • External applications

And when tools are combined with:

RunnableWithMessageHistory
RunnableWithFallbacks
Configurable Runnables
RunnableBranch
RunnableParallel

you can build sophisticated AI workflows that are conversational, configurable, resilient, and capable of interacting with real-world systems.

Happy Coding! 🚀