Your First LangChain Agent
🎯 Introduction
In the previous article, we implemented the agent loop manually, handling model requests, tool name matching, message history, and stopping conditions ourselves. Reimplementing this logic for every agent adds development and maintenance work. Here, we will use LangChain.js and createAgent() to build a product agent, see how the framework manages the tool-calling loop, and identify the developer’s remaining responsibilities.
🧱 Why Use LangChain?
LangChain is a framework for building LLM applications and agents. It provides model integrations, tool wrappers, agent execution, and extension mechanisms. This course uses its JavaScript version.
It is not a new model service, nor does it require migrating your business system to LangChain. Existing functions such as findProduct() and getStock() remain usable.
| Manual implementation | With LangChain |
|---|---|
| Call the model API | Use a common model interface |
| Define tools and map them to functions | Associate definitions and functions with tool() |
| Manage tool requests, results, and the loop | Let createAgent() manage them |
| Implement execution controls yourself | Extend execution with middleware and other mechanisms |
LangChain agents run on LangGraph’s execution infrastructure. This article uses the high-level agent API, so you do not need to understand StateGraph, nodes, or edges yet.
🛠 Set Up LangChain
Continue in agent-demo with Node.js 24 LTS. Install these exact dependency versions:
npm install --save-exact langchain@1.6.8 @langchain/core@1.5.0 @langchain/openai@1.8.5 @langchain/langgraph@1.7.5 zod@4.2.1
langchain provides agent and tool APIs, @langchain/core supplies base interfaces, and @langchain/openai integrates the model. Zod defines and validates data structures, including tool arguments. We will also use LangGraph in later articles. Keep the existing .env and shop.mjs.
Create agent.mjs and initialize a LangChain model object:
import { ChatOpenAI } from '@langchain/openai';
export const model = new ChatOpenAI({
apiKey: process.env.AI_API_KEY,
model: process.env.AI_MODEL,
configuration: { baseURL: process.env.AI_BASE_URL },
// Keep using the Chat Completions API from the previous article
useResponsesApi: false,
});
ChatOpenAI is LangChain’s OpenAI integration. It wraps the API in a common model interface. Here, it reuses the existing model configuration.
Create run.mjs to test the model connection temporarily:
import { model } from './agent.mjs';
const result = await model.invoke('Please reply with OK');
console.log(result.content);
Run:
node --env-file=.env run.mjs
The expected output is OK or equivalent text, confirming that the model connection works. This is still an ordinary model call, with no tools or agent.
🧱 Register Business Functions as Tools
Reuse findProduct() and getStock() from the previous article. Add these imports at the top of agent.mjs:
import { createAgent, tool } from 'langchain';
import { z } from 'zod';
import { findProduct, getStock } from './shop.mjs';
Define the first tool at the end of the file:
export const findProductTool = tool(
// The business function executed by the tool
({ name }) => JSON.stringify(findProduct(name)),
{
// Tool name and purpose provided to the model
name: 'find_product',
description: 'Look up a product ID by name, without returning stock',
// Define and validate tool inputs
schema: z.object({
name: z.string().describe('Product name'),
}),
}
);
tool() associates the definition with its execution function, removing the need for a manual name-to-function mapping. The schema serves a similar purpose to function calling parameter definitions, with Zod validating the input.
Add the stock lookup tool in the same way:
export const stockTool = tool(({ id }) => JSON.stringify(getStock(id)), {
name: 'get_stock',
description: 'Look up stock using a known product ID; product names are not accepted',
schema: z.object({
id: z.string().describe('Product ID, such as P100'),
}),
});
Both tools reuse the existing business functions and return JSON text as their results. Only the integration changes; the business logic stays the same.
🧱 Create and Run the Agent
Append to agent.mjs:
export const shopOptions = {
model,
// Tools available to the agent
tools: [findProductTool, stockTool],
systemPrompt:
'You are a product assistant. Always use tools for product data. Never guess IDs or stock levels. Report failed lookups accurately.',
};
export const agent = createAgent(shopOptions);
shopOptions holds the model, tools, and prompt configuration for reuse in later articles.
createAgent() combines the model, tools, and system prompt into an agent. The framework handles tool execution, history updates, and the loop. Creating the instance does not execute a user task yet.
Replace the temporary model test in run.mjs with:
import { agent } from './agent.mjs';
// Give the task to the agent and wait for the loop to finish
const result = await agent.invoke(
{
messages: [{ role: 'user', content: 'Are there enough mechanical keyboards to buy 15 units?' }],
},
{ recursionLimit: 20 }
);
// Get the last answer from the returned message history
const lastMessage = result.messages.at(-1);
console.log(lastMessage?.content);
Run:
node --env-file=.env run.mjs
One possible answer:
There are 12 units in stock, so you need 3 more.
We no longer need to write askModel(), executeTool(), or the for loop ourselves. After executing the task, agent.invoke() returns the agent state, whose messages contain the messages produced during execution.
recursionLimit limits underlying execution steps, not model calls. Exceeding it throws an error.Inspect the Execution
The final answer alone cannot confirm that tools were used. Replace the two lines that retrieve and print lastMessage, along with their comment, with:
for (const message of result.messages) {
console.log('Message type:', message.type);
console.log('Message content:', message.content);
// Inspect tool requests made by the model
if (message.tool_calls?.length) {
console.log('Tool calls:', message.tool_calls);
}
}
Run again. One possible output follows (the tool call IDs are examples):
Message type: human
Message content: Are there enough mechanical keyboards to buy 15 units?
Message type: ai
Message content:
Tool calls: [
{
name: 'find_product',
args: { name: 'mechanical keyboard' },
id: 'call_1',
type: 'tool_call'
}
]
Message type: tool
Message content: {"id":"P100","name":"mechanical keyboard"}
Message type: ai
Message content:
Tool calls: [
{
name: 'get_stock',
args: { id: 'P100' },
id: 'call_2',
type: 'tool_call'
}
]
Message type: tool
Message content: {"id":"P100","stock":12}
Message type: ai
Message content: There are 12 units in stock, so you need 3 more.
human represents a user message, ai a model message, and tool a tool result. The framework performed two lookups and returned their results to the model automatically. Tool arguments in args are already objects, so no manual parsing of function.arguments is needed.
The framework manages the loop, but developers remain responsible for correct tool definitions, business logic, and permission checks. Tool order and answers may vary by model; verify answers against tool results.
❓ Questions and Answers
Q1: How does calling stockTool.invoke({ id: 'P100' }) differ from calling agent.invoke()?
The former executes a specific tool directly, without model selection. The latter gives a task to the agent, letting the model decide whether to use tools and whether to continue or answer based on results. Direct tool calls are useful for debugging business functions.
🧪 Exercises
Change the question in run.mjs to “How many units of P200 are in stock?” Check whether the agent calls get_stock directly and correctly reports 0 units from the result. Keep agent.mjs and run.mjs for the next article.
🎉 Congratulations! You have created and run your first LangChain agent.
