LangChain JS agent with a custom tool

Authors
  • avatar
    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 zod

Set 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

References