Introduction
In the previous article, we learned about Tools in LangChain.js.
We learned how to create a tool:
const weatherTool = tool(
async ({ city }) => {
// perform operation
},
{
name: "get_weather",
description:
"Get the current weather for a city.",
schema: z.object({
city: z.string(),
}),
}
);
We also learned that tools allow an AI model to interact with external functionality such as:
-
APIs
-
Databases
-
Search systems
-
Calculators
-
Internal services
-
Business applications
But there was an important part we didn't explore deeply:
How does the model actually call the tool?
Consider:
User
↓
"What is the weather in Hyderabad?"
↓
LLM
↓
???
How does the LLM tell our application:
Call get_weather
with city = Hyderabad
And after our application executes the tool, how do we send the result back to the model?
The complete workflow is:
User
↓
LLM
↓
Tool Call
↓
Application
↓
Tool
↓
Tool Result
↓
LLM
↓
Final Answer
This is called tool calling.
In this article, we'll go deep into the complete tool-calling workflow.
We'll learn:
-
What tool calling is
-
bindTools() -
AIMessage -
AIMessage.tool_calls -
Tool call structure
-
ToolMessage -
tool_call_id -
Executing tools
-
Returning tool results
-
Calling the model again
-
Building a complete tool-calling loop
-
Multiple tools
-
Multiple tool calls
-
OpenAI tool calling
-
Gemini tool calling
-
Tool calling with prompts
-
Tool calling with
RunnableSequence -
Tool calling with message history
-
Tool calling errors
-
Tool validation
-
Security
-
Common mistakes
-
Production architecture
Let's start from the basics.
What Is Tool Calling?
Tool calling is the mechanism where an AI model generates a structured request asking your application to execute a specific tool.
For example, the user asks:
What's the weather in Hyderabad?
The model may generate:
{
"name": "get_weather",
"args": {
"city": "Hyderabad"
}
}
Your application receives this request and executes:
await weatherTool.invoke({
city: "Hyderabad"
});
The tool returns:
{
"city": "Hyderabad",
"temperature": 30,
"condition": "Sunny"
}
Then the application sends the result back to the model.
The model finally responds:
The weather in Hyderabad is currently 30°C and sunny.
The Complete Tool Calling Architecture
Keep this diagram in mind throughout this article:
User
↓
┌─────────────┐
│ LLM │
└──────┬──────┘
↓
Tool Call
↓
┌─────────────────┐
│ Application │
└────────┬────────┘
↓
Execute Tool
↓
Tool Result
↓
ToolMessage
↓
┌─────────────┐
│ LLM │
└──────┬──────┘
↓
Final Answer
The most important point is:
The LLM requests the tool. Your application executes the tool.
Tool Calling vs Normal LLM Invocation
A normal LLM request looks like:
User
↓
LLM
↓
AI Response
Example:
const response =
await model.invoke(
"What is React?"
);
The model returns:
React is a JavaScript library...
Tool Calling
With tools:
User
↓
LLM
↓
Tool Call
↓
Tool
↓
Tool Result
↓
LLM
↓
Final Response
There are now multiple model/tool interactions.
Project Setup
Let's create a project.
mkdir langchain-tool-calling
cd langchain-tool-calling
npm init -y
Install the packages:
npm install @langchain/core @langchain/openai @langchain/google-genai dotenv zod
Project Structure
langchain-tool-calling/
│
├── 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
Step 1 — Import Dependencies
import "dotenv/config";
import {
ChatOpenAI,
} from "@langchain/openai";
import {
ChatGoogleGenerativeAI,
} from "@langchain/google-genai";
import {
tool,
} from "@langchain/core/tools";
import {
ToolMessage,
} from "@langchain/core/messages";
import {
z,
} from "zod";
Step 2 — Create a Tool
Let's start with a simple calculator.
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(),
}),
}
);
The tool accepts:
{
"a": 10,
"b": 20
}
and returns:
30
Step 3 — Create the OpenAI Model
const model =
new ChatOpenAI({
model: "gpt-4.1-mini",
});
Step 4 — Bind the Tool
Now we use:
bindTools()
const modelWithTools =
model.bindTools([
calculatorTool,
]);
This is a critical step.
It tells the model:
You are allowed to request this tool.
What Does bindTools() Do?
bindTools() makes the tool definitions available to the chat model.
The model receives information similar to:
Tool Name:
add_numbers
Description:
Add two numbers together.
Arguments:
a → number
b → number
The model can then decide whether to request that tool.
Step 5 — Invoke the Model
Let's ask:
const response =
await modelWithTools.invoke(
"What is 25 + 40?"
);
Now inspect:
console.log(response);
Instead of necessarily receiving only normal text, the AIMessage may contain a tool call.
Let's inspect:
console.log(
response.tool_calls
);
Understanding AIMessage
The model response is generally an AIMessage.
Conceptually:
AIMessage {
content: "",
tool_calls: [...]
}
If the model decides it needs a tool, tool_calls contains the requested calls.
Understanding tool_calls
Let's inspect:
console.log(
response.tool_calls
);
You may see a structure similar to:
[
{
name: "add_numbers",
args: {
a: 25,
b: 40
},
id: "call_123"
}
]
The exact metadata can vary by provider and LangChain version, but the important properties are:
name
args
id
Understanding Each Property
name
name: "add_numbers"
This tells us which tool the model wants to call.
args
args: {
a: 25,
b: 40
}
These are the arguments for the tool.
id
id: "call_123"
This uniquely identifies the tool call.
The ID becomes important when returning the tool result.
The Model Has Not Executed the Tool Yet
This is extremely important.
When we receive:
response.tool_calls
the tool has not necessarily been executed.
The model has only requested:
Please execute:
add_numbers(25, 40)
Your application is responsible for executing it.
Step 6 — Get the Tool Call
We can retrieve the first tool call:
const toolCall =
response.tool_calls[0];
Now:
console.log(
toolCall.name
);
Output:
add_numbers
And:
console.log(
toolCall.args
);
Output:
{
a: 25,
b: 40
}
Step 7 — Execute the Tool
Now execute:
const result =
await calculatorTool.invoke(
toolCall.args
);
The result is:
65
Now our application has the tool result.
Step 8 — Create a ToolMessage
We need to send the tool result back to the model.
Import:
import {
ToolMessage,
} from "@langchain/core/messages";
Create:
const toolMessage =
new ToolMessage({
content: String(result),
tool_call_id:
toolCall.id,
});
Now we have:
ToolMessage
↓
65
Why tool_call_id Is Important
Suppose the model requests multiple tools:
call_1 → get_weather
call_2 → calculator
When the results come back:
call_1 → weather result
call_2 → calculator result
The model needs to know which result belongs to which tool call.
That's why we use:
tool_call_id
It connects:
AI Tool Call
↓
Tool Result
The Complete Message Sequence
The conversation now looks like:
HumanMessage
"What is 25 + 40?"
AIMessage
Tool Call:
add_numbers(25, 40)
ToolMessage
65
AIMessage
"25 + 40 is 65."
This sequence is important.
Step 9 — Call the Model Again
Now we need to send the conversation back to the model.
Conceptually:
const finalResponse =
await modelWithTools.invoke([
{
role: "user",
content:
"What is 25 + 40?"
},
response,
toolMessage,
]);
In production code, it's better to work with LangChain message objects rather than manually constructing provider-specific message formats.
Using HumanMessage
Import:
import {
HumanMessage,
} from "@langchain/core/messages";
Then:
const messages = [
new HumanMessage(
"What is 25 + 40?"
),
response,
toolMessage,
];
Now:
const finalResponse =
await modelWithTools.invoke(
messages
);
The model sees:
Human:
What is 25 + 40?
AI:
Call add_numbers
Tool:
65
and can produce:
25 + 40 is 65.
Complete Manual Tool Calling Example
Let's put the steps together.
import "dotenv/config";
import {
ChatOpenAI,
} from "@langchain/openai";
import {
tool,
} from "@langchain/core/tools";
import {
HumanMessage,
ToolMessage,
} from "@langchain/core/messages";
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 userMessage =
new HumanMessage(
"What is 25 + 40?"
);
const response =
await modelWithTools.invoke([
userMessage,
]);
console.log(
"Tool Calls:",
response.tool_calls
);
const toolCall =
response.tool_calls[0];
const result =
await calculatorTool.invoke(
toolCall.args
);
const toolMessage =
new ToolMessage({
content:
String(result),
tool_call_id:
toolCall.id,
});
const finalResponse =
await modelWithTools.invoke([
userMessage,
response,
toolMessage,
]);
console.log(
"Final Answer:",
finalResponse.content
);
The workflow is:
User Message
↓
OpenAI
↓
AIMessage
↓
tool_calls
↓
Execute Tool
↓
ToolMessage
↓
OpenAI
↓
Final Answer
Why Do We Need Two Model Calls?
This is a common beginner question.
Why not:
User
↓
LLM
↓
Tool
↓
Final Answer
Because the LLM needs to participate on both sides of the tool execution.
First:
LLM
↓
Decide what tool to use
Then:
Tool Result
↓
LLM
↓
Understand result
↓
Generate final answer
So:
LLM → Tool → LLM
is the core pattern.
Building a Weather Tool
Let's create a realistic example.
const weatherTool = tool(
async ({ city }) => {
// In production, call
// an actual weather API.
return {
city,
temperature: 30,
condition: "Sunny",
};
},
{
name:
"get_weather",
description:
`
Get the current weather
for a specified city.
`,
schema:
z.object({
city:
z.string()
.describe(
"The city to get weather for"
),
}),
}
);
Bind the Weather Tool
const modelWithTools =
model.bindTools([
weatherTool,
]);
Now ask:
const response =
await modelWithTools.invoke(
"What is the weather in Hyderabad?"
);
The model may return:
[
{
name: "get_weather",
args: {
city: "Hyderabad"
},
id: "call_weather_1"
}
]
Execute the Weather Tool
const toolCall =
response.tool_calls[0];
const result =
await weatherTool.invoke(
toolCall.args
);
The result could be:
{
city: "Hyderabad",
temperature: 30,
condition: "Sunny"
}
Create ToolMessage
const toolMessage =
new ToolMessage({
content:
JSON.stringify(result),
tool_call_id:
toolCall.id,
});
Then call the model again:
const finalResponse =
await modelWithTools.invoke([
new HumanMessage(
"What is the weather in Hyderabad?"
),
response,
toolMessage,
]);
The final response might be:
The weather in Hyderabad is currently
30°C and sunny.
Why Use JSON.stringify()?
Tool results can be:
{
city: "Hyderabad",
temperature: 30,
condition: "Sunny"
}
But ToolMessage.content is commonly represented as message content.
Therefore:
JSON.stringify(result)
converts:
{
city: "Hyderabad"
}
into:
{"city":"Hyderabad"}
This allows the model to receive structured information as message content.
Multiple Tools
Let's create:
calculator
weather
const modelWithTools =
model.bindTools([
calculatorTool,
weatherTool,
]);
Now the model has two capabilities.
Example 1 — Calculator
User:
What is 50 + 100?
Possible tool call:
{
name: "add_numbers",
args: {
a: 50,
b: 100
}
}
Example 2 — Weather
User:
What's the weather in Hyderabad?
Possible tool call:
{
name: "get_weather",
args: {
city: "Hyderabad"
}
}
The model chooses based on the tool descriptions and the user's request.
Multiple Tool Calls in One Response
Now consider:
What is the weather in Hyderabad
and what is 50 + 100?
The model may request multiple tools:
[
{
name: "get_weather",
args: {
city: "Hyderabad"
},
id: "call_1"
},
{
name: "add_numbers",
args: {
a: 50,
b: 100
},
id: "call_2"
}
]
This is important.
Don't assume:
response.tool_calls[0]
is always the only tool call.
You should consider:
response.tool_calls
as an array.
Executing Multiple Tool Calls
We can loop through them.
const toolMessages =
[];
for (
const toolCall
of response.tool_calls
) {
let result;
if (
toolCall.name ===
"get_weather"
) {
result =
await weatherTool.invoke(
toolCall.args
);
}
if (
toolCall.name ===
"add_numbers"
) {
result =
await calculatorTool.invoke(
toolCall.args
);
}
toolMessages.push(
new ToolMessage({
content:
JSON.stringify(result),
tool_call_id:
toolCall.id,
})
);
}
Now:
Tool Call 1
↓
Tool Result 1
Tool Call 2
↓
Tool Result 2
Sending Multiple Tool Results Back
Now invoke:
const finalResponse =
await modelWithTools.invoke([
userMessage,
response,
...toolMessages,
]);
The model receives all results.
Then it can produce:
The weather in Hyderabad is 30°C and sunny.
Also, 50 + 100 equals 150.
Avoid Hardcoding Tool Selection
You might write:
if (
toolCall.name ===
"get_weather"
) {
...
}
This is fine for a small demonstration.
But as the number of tools increases:
20 tools
50 tools
100 tools
a large if/else chain becomes difficult to maintain.
Instead, create a tool registry.
Creating a Tool Registry
const tools = [
calculatorTool,
weatherTool,
];
Then:
const toolMap =
Object.fromEntries(
tools.map(
(tool) => [
tool.name,
tool,
]
)
);
Now:
console.log(
toolMap["get_weather"]
);
returns the weather tool.
Dynamic Tool Execution
Now we can execute:
for (
const toolCall
of response.tool_calls
) {
const selectedTool =
toolMap[
toolCall.name
];
if (!selectedTool) {
throw new Error(
`Unknown tool: ${toolCall.name}`
);
}
const result =
await selectedTool.invoke(
toolCall.args
);
toolMessages.push(
new ToolMessage({
content:
JSON.stringify(result),
tool_call_id:
toolCall.id,
})
);
}
This is much more scalable.
Complete Multi-Tool Example
import "dotenv/config";
import {
ChatOpenAI,
} from "@langchain/openai";
import {
tool,
} from "@langchain/core/tools";
import {
HumanMessage,
ToolMessage,
} from "@langchain/core/messages";
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 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(),
}),
}
);
const tools = [
calculatorTool,
weatherTool,
];
const toolMap =
Object.fromEntries(
tools.map(
(tool) => [
tool.name,
tool,
]
)
);
const model =
new ChatOpenAI({
model:
"gpt-4.1-mini",
});
const modelWithTools =
model.bindTools(
tools
);
const userMessage =
new HumanMessage(
`
What is 50 + 100?
Also tell me the weather
in Hyderabad.
`
);
const response =
await modelWithTools.invoke([
userMessage,
]);
const toolMessages =
[];
for (
const toolCall
of response.tool_calls
) {
const selectedTool =
toolMap[
toolCall.name
];
if (!selectedTool) {
throw new Error(
`Unknown tool:
${toolCall.name}`
);
}
const result =
await selectedTool.invoke(
toolCall.args
);
toolMessages.push(
new ToolMessage({
content:
JSON.stringify(result),
tool_call_id:
toolCall.id,
})
);
}
const finalResponse =
await modelWithTools.invoke([
userMessage,
response,
...toolMessages,
]);
console.log(
finalResponse.content
);
The Tool Registry Pattern
The architecture is:
Tools
↓
Tool Registry
↓
Tool Name
↓
Find Tool
↓
Execute
This is a very useful pattern when an application has many tools.
Tool Calling Loop
Now let's generalize the process.
User Message
↓
LLM
↓
Does it contain tool_calls?
│
┌─┴─┐
No Yes
↓ ↓
Answer Execute Tools
↓
ToolMessage
↓
LLM
↓
Does it contain
tool_calls?
Notice something important:
The model might request another tool after receiving the first tool result.
Why Do We Need a Loop?
Consider:
User:
Find the weather in Hyderabad
and calculate the temperature
in Fahrenheit.
The model might do:
Step 1:
get_weather
Result:
30°C
Then the model might decide:
Step 2:
convert_temperature
Result:
86°F
Then:
Final Answer
So the workflow becomes:
LLM
↓
Tool
↓
LLM
↓
Tool
↓
LLM
↓
Final
This is why tool calling can become an iterative loop.
Generic Tool Calling Loop
Conceptually:
let messages = [
userMessage,
];
while (true) {
const response =
await modelWithTools.invoke(
messages
);
messages.push(
response
);
if (
!response.tool_calls ||
response.tool_calls.length === 0
) {
break;
}
for (
const toolCall
of response.tool_calls
) {
const selectedTool =
toolMap[
toolCall.name
];
const result =
await selectedTool.invoke(
toolCall.args
);
messages.push(
new ToolMessage({
content:
JSON.stringify(result),
tool_call_id:
toolCall.id,
})
);
}
}
console.log(
messages.at(-1).content
);
This is a simplified manual tool-calling loop.
Why This Loop Matters
The loop gives the model the ability to:
Think
↓
Call Tool
↓
Observe Result
↓
Decide Next Step
↓
Call Another Tool
↓
Observe Result
↓
Final Answer
This is the foundation of more advanced agentic workflows.
Tool Calling with Gemini
Now let's implement the same architecture with Gemini.
Initialize:
import {
ChatGoogleGenerativeAI,
} from "@langchain/google-genai";
const model =
new ChatGoogleGenerativeAI({
model:
"gemini-2.5-flash",
});
Bind tools:
const modelWithTools =
model.bindTools([
calculatorTool,
weatherTool,
]);
Invoke:
const response =
await modelWithTools.invoke([
new HumanMessage(
"What is 25 + 40?"
),
]);
Inspect:
console.log(
response.tool_calls
);
If the model requests a tool, execute it using the same application-side tool execution logic.
Why LangChain Makes This Easier
Without LangChain, you'd have to manage provider-specific tool schemas and response formats.
With LangChain:
Your Tool
↓
LangChain Tool Abstraction
↓
OpenAI
or:
Your Tool
↓
LangChain Tool Abstraction
↓
Gemini
Your application can use a common tool representation.
OpenAI and Gemini Comparison
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 application-side tool remains:
weatherTool
Tool Calling with ChatPromptTemplate
Tools can also be combined with the prompt concepts we learned earlier.
Import:
import {
ChatPromptTemplate,
} from "@langchain/core/prompts";
Create:
const prompt =
ChatPromptTemplate.fromMessages([
[
"system",
`
You are a helpful assistant.
Use tools whenever current
or external information is required.
`,
],
[
"human",
"{input}",
],
]);
Then:
const chain =
prompt.pipe(
modelWithTools
);
Now:
Prompt
↓
Model
↓
Tool Call
Tool Calling + Message History
From Blog 16, we learned:
RunnableWithMessageHistory
We can combine that with tools.
The architecture becomes:
Session
↓
Message History
↓
Prompt
↓
LLM
↓
Tool Call
↓
Tool
↓
ToolMessage
↓
LLM
↓
Final Response
↓
Updated History
This is the architecture of a conversational tool-using assistant.
Example: Customer Support Assistant
Imagine a customer asks:
Where is my order 1001?
The model may call:
get_order_status
with:
{
"orderId": 1001
}
The application queries the database:
Order 1001
Status: Shipped
Expected Delivery: Tomorrow
Then returns:
ToolMessage
The model responds:
Your order 1001 has shipped
and is expected to arrive tomorrow.
Tool Calling + RunnableWithFallbacks
Suppose our weather API fails.
We could use:
LLM
↓
Weather Tool
↓
Primary API
↓
Failure
↓
Backup API
↓
Tool Result
↓
LLM
This combines:
Tool Calling
+
Fallbacks
Tool Calling + Configurable Runnables
Suppose users can choose:
OpenAI
Gemini
The architecture becomes:
User
↓
Configurable Model
↓
OpenAI / Gemini
↓
Tool Calling
↓
Tool
↓
Result
↓
Model
This connects directly with Blog 17.
Tool Calling + RunnableBranch
Suppose we have:
mode = "support"
Then:
Support Chain
↓
Support Tools
Or:
mode = "sales"
Then:
Sales Chain
↓
Sales Tools
This can be implemented with branching logic.
Tool Errors
Tools can fail.
For example:
Weather API
↓
Timeout
or:
Database
↓
Connection Error
or:
Tool Input
↓
Validation Error
You need to decide how the application should respond.
Handling Tool Errors
A simple approach:
try {
const result =
await selectedTool.invoke(
toolCall.args
);
} catch (error) {
console.error(
"Tool failed:",
error
);
}
But we usually want to return an error message to the model.
For example:
const toolMessage =
new ToolMessage({
content:
`Tool failed:
${error.message}`,
tool_call_id:
toolCall.id,
});
The model can then decide what to do next.
Important Security Consideration
Don't expose raw internal errors to the model unnecessarily.
Avoid returning:
Database connection string...
Internal stack trace...
API credentials...
Instead:
The weather service is currently unavailable.
Keep sensitive operational information inside your application logs.
Tool Validation
Zod provides validation:
schema: z.object({
userId:
z.number()
.int()
.positive(),
})
This protects your tool from invalid arguments.
For example:
userId = -10
should fail validation.
Authorization
Schema validation isn't enough.
Suppose:
userId = 100
is valid.
But is the current user allowed to access user 100?
Your application must check:
Authentication
↓
Authorization
↓
Tool Execution
The model should never be treated as the security boundary.
Tool Calling Is Not Authorization
This is a critical production principle:
An LLM deciding to call a tool does not mean the user is authorized to perform that action.
For example:
LLM:
delete_user(100)
Your application must still check:
Is this user allowed to delete user 100?
Only then:
Execute
Tool Calling vs Structured Output
These concepts are related but different.
Structured Output
The model returns data matching a schema:
{
"name": "John",
"age": 30
}
The goal is:
Reliable structured response
Tool Calling
The model returns:
{
"name": "get_weather",
"args": {
"city": "Hyderabad"
}
}
The goal is:
Request an external action/capability
Remember:
Structured Output
↓
Give me structured data
Tool Calling
↓
Tell me what action/capability to execute
Tool Calling vs withStructuredOutput()
We previously learned:
withStructuredOutput()
For example:
const structuredModel =
model.withStructuredOutput(
schema
);
This is useful when you want:
LLM
↓
Structured Result
Tool calling is:
LLM
↓
Tool Call
↓
Execute
↓
Tool Result
↓
LLM
They solve different problems.
Tool Calling vs RunnableWithFallbacks
Remember:
RunnableWithFallbacks
↓
Recover from failure
while:
Tool Calling
↓
Interact with external capabilities
They can be combined.
Tool Calling vs RunnableBranch
Remember:
RunnableBranch
↓
Choose based on condition
while:
Tool Calling
↓
Model decides which capability it needs
Again, they can be combined.
Common Beginner Mistakes
Mistake 1 — Calling bindTools() and expecting the tool to execute
This:
model.bindTools([
weatherTool,
]);
only makes the tool available to the model.
You still need to execute the requested tool.
Mistake 2 — Ignoring tool_calls
Don't assume:
response.content
contains the final answer.
Check:
response.tool_calls
when using tools.
Mistake 3 — Ignoring tool_call_id
When creating ToolMessage, use:
tool_call_id:
toolCall.id
so the result can be associated with the correct tool call.
Mistake 4 — Assuming Only One Tool Call
Don't always write:
response.tool_calls[0]
without considering that the model can request multiple tools.
Use:
for (
const toolCall
of response.tool_calls
) {
...
}
when appropriate.
Mistake 5 — Not Handling Unknown Tools
Always validate:
const selectedTool =
toolMap[
toolCall.name
];
If it doesn't exist:
if (!selectedTool) {
throw new Error(
"Unknown tool"
);
}
Mistake 6 — Trusting the Model for Security
Never assume:
LLM requested it
=
User is authorized
Always perform application-level authorization.
Mistake 7 — Sending Huge Tool Results
If your database returns:
10,000 records
don't send all of them back to the model.
Instead:
Filter
↓
Summarize
↓
Return relevant information
Best Practices
1. Use clear tool names
Good:
get_weather
get_order_status
search_products
2. Write detailed descriptions
Tell the model exactly when the tool should be used.
3. Use Zod schemas
Define precise arguments.
4. Validate every tool call
Don't blindly trust generated arguments.
5. Authorize sensitive operations
Especially:
-
Payments
-
Deletions
-
Account changes
-
Data access
-
Emails
-
External side effects
6. Keep tool results focused
Return only the information required for the next reasoning step.
7. Add error handling
Tools depend on external systems that can fail.
8. Log tool execution
For production applications, record:
Tool name
Arguments
Execution time
Success/failure
Error category
Be careful not to log secrets or sensitive personal data.
Production Tool Architecture
A production-ready architecture might look like:
User
↓
Authentication
↓
Authorization
↓
Conversation
History
↓
LLM
↓
Tool Call
↓
Validate Arguments
↓
Authorize Action
↓
Execute Tool
↓
Handle Tool Error
↓
ToolMessage
↓
LLM
↓
Final Response
This is much closer to how real AI systems should be designed.
Complete Mental Model
Remember these five steps:
1. Bind Tools
↓
2. Invoke Model
↓
3. Read tool_calls
↓
4. Execute Tools
↓
5. Send ToolMessage back to Model
In code:
const modelWithTools =
model.bindTools(tools);
then:
const response =
await modelWithTools.invoke(
messages
);
then:
response.tool_calls
then:
await tool.invoke(
toolCall.args
);
then:
new ToolMessage({
content,
tool_call_id:
toolCall.id,
});
then invoke the model again.
A Reusable Tool Executor
Instead of writing tool execution logic everywhere, create a reusable function.
async function executeToolCalls(
response,
toolMap
) {
const messages = [];
for (
const toolCall
of response.tool_calls
) {
const tool =
toolMap[
toolCall.name
];
if (!tool) {
messages.push(
new ToolMessage({
content:
`Unknown tool:
${toolCall.name}`,
tool_call_id:
toolCall.id,
})
);
continue;
}
try {
const result =
await tool.invoke(
toolCall.args
);
messages.push(
new ToolMessage({
content:
JSON.stringify(
result
),
tool_call_id:
toolCall.id,
})
);
} catch (error) {
messages.push(
new ToolMessage({
content:
"Tool execution failed.",
tool_call_id:
toolCall.id,
})
);
}
}
return messages;
}
Now the main workflow becomes much cleaner.
Reusable Tool Calling Workflow
const response =
await modelWithTools.invoke(
messages
);
messages.push(
response
);
if (
response.tool_calls?.length
) {
const toolMessages =
await executeToolCalls(
response,
toolMap
);
messages.push(
...toolMessages
);
const finalResponse =
await modelWithTools.invoke(
messages
);
console.log(
finalResponse.content
);
}
This separation is useful when building larger applications.
Tool Calling Loop with Multiple Iterations
For more complex tasks:
let messages = [
userMessage,
];
while (true) {
const response =
await modelWithTools.invoke(
messages
);
messages.push(
response
);
if (
!response.tool_calls?.length
) {
break;
}
const toolMessages =
await executeToolCalls(
response,
toolMap
);
messages.push(
...toolMessages
);
}
const finalMessage =
messages[
messages.length - 1
];
console.log(
finalMessage.content
);
This is a simplified example of an iterative tool-calling workflow.
Why Tool Calling Is Important
Before tools:
LLM
↓
Generate information
After tools:
LLM
↓
Understand request
↓
Choose capability
↓
Execute capability
↓
Observe result
↓
Continue reasoning
↓
Final response
This changes what we can build.
Now we can create:
-
AI customer support
-
AI shopping assistants
-
AI database assistants
-
AI research assistants
-
AI coding assistants
-
AI travel assistants
-
AI workflow automation
Example: AI Shopping Assistant
User:
Find me a laptop under ₹70,000
with at least 16GB RAM.
The model could call:
search_products
with:
{
"query": "laptop 16GB RAM",
"maxPrice": 70000
}
The tool queries a product database.
Then:
Tool Result
↓
LLM
↓
Compare Products
↓
Final Recommendation
Example: AI Database Assistant
User:
How many orders did we receive today?
The model calls:
get_order_count
The database returns:
124
The model responds:
We received 124 orders today.
Example: AI Customer Support
User:
Where is my order?
The model calls:
get_order_status
The tool returns:
{
"status": "shipped",
"deliveryDate": "tomorrow"
}
The model responds:
Your order has shipped and is expected
to arrive tomorrow.
The Bigger Picture
At this point, our LangChain.js learning path has reached an important milestone.
We've gone from:
Simple Prompt
to:
Chat Model
then:
Runnable
then:
Runnable Composition
then:
Memory
then:
Configuration
and now:
Tools
The architecture is becoming:
┌─────────────┐
│ User │
└──────┬──────┘
↓
Conversation History
↓
Configurable LLM
↓
┌───────┴────────┐
↓ ↓
OpenAI Gemini
↓ ↓
└───────┬────────┘
↓
Tool Call
↓
┌───────┴────────┐
↓ ↓
Weather Database
↓ ↓
└───────┬────────┘
↓
ToolMessage
↓
LLM
↓
Final Response
This is the foundation for agentic AI systems.
Final Thoughts
Tool calling is one of the most important concepts in modern LLM application development.
The basic flow is:
User
↓
LLM
↓
Tool Call
↓
Execute Tool
↓
ToolMessage
↓
LLM
↓
Final Response
The most important LangChain concepts from this article are:
bindTools()
Makes tools available to the model.
const modelWithTools =
model.bindTools([
weatherTool,
]);
AIMessage.tool_calls
Contains the tool requests generated by the model.
response.tool_calls
ToolMessage
Represents the result returned from a tool.
new ToolMessage({
content,
tool_call_id:
toolCall.id,
});
tool_call_id
Connects a tool result with the original tool call.
The most important mental model is:
┌─────────────┐
│ User │
└──────┬──────┘
↓
┌─────────────┐
│ LLM │
└──────┬──────┘
↓
Tool Call
↓
┌─────────────┐
│ Tool │
└──────┬──────┘
↓
Tool Result
↓
┌─────────────┐
│ LLM │
└──────┬──────┘
↓
Final Answer
And for multiple steps:
LLM
↓
Tool A
↓
LLM
↓
Tool B
↓
LLM
↓
Final Answer
This iterative loop is the foundation of agentic workflows.
The critical security principle is:
The LLM can request an action, but your application must remain responsible for validation, authorization, and execution.
Once you understand this, you're ready to move from simple tool calling into Agents, where the model can dynamically decide which tools to use and how to combine them to solve a problem.
Happy Coding! 🚀