LangChain JS agent with a custom tool
- Authors
- Name
- Hamza Rahman
- Published on
- -2 mins read
Use a LangChain agent when you want a model loop that can choose tools and respond with the result.
This example creates an agent with one custom weather tool.
Install
npm install langchain @langchain/openai zodSet your API key:
export OPENAI_API_KEY="your_api_key_here"Code
import { createAgent, tool } from 'langchain'import { z } from 'zod'
const getWeather = tool( async ({ city }) => { return `It is always sunny in ${city}.` }, { name: 'get_weather', description: 'Get the weather for a given city.', schema: z.object({ city: z.string().describe('The city to get weather for.'), }), })
const agent = createAgent({ model: 'gpt-5.5', tools: [getWeather],})
const result = await agent.invoke({ messages: [ { role: 'user', content: 'What is the weather in San Francisco?', }, ],})
console.log(result)What this gives you
The agent receives the user message, decides whether to call get_weather, runs the tool, and returns the model's final response.
Use this pattern when you want:
- A small agent with one or two tools
- A portable model/tool setup
- A path toward middleware, tracing, or LangGraph later
Common mistakes
- Leaving the tool description vague. The agent decides whether to call a tool from its name and description, so a clear description is what makes it fire at the right time.
- Skipping the Zod schema. Without it the model has no contract for the arguments, and you end up validating messy input by hand.
- Reaching for an agent too early. If the model only needs to return data, structured outputs or a single tool call is simpler and cheaper than an agent loop.
Related
- Vercel AI SDK tool calling example: a lighter agent loop without a full framework.
- OpenAI function calling in JavaScript: the raw function-calling loop the frameworks wrap.
References
Related articles
OpenAI function calling JavaScript example
A minimal OpenAI function calling example in JavaScript using the Responses API and a local tool, including the two-step call-the-tool then answer loop.
Vercel AI SDK tool calling example
A minimal Vercel AI SDK tool calling example using generateText, tool, stepCountIs, and a Zod inputSchema, with the tool loop handled for you.
Force an LLM to return JSON in JavaScript
Reliably get JSON from an LLM in JavaScript with OpenAI structured outputs and a Zod schema, instead of prompting for JSON and parsing fragile model text yourself.

