Sign up for my FREE incoming seminar at Soft Uni:
LangChain in Action: How to Build Intelligent AI Applications Easily and Efficiently ?
LangChain in Action: How to Build Intelligent AI Applications Easily and Efficiently ?
// index.ts
import { Tool } from "@langchain/core/tools";
import { ChatOpenAI } from "@langchain/openai";
import { MemorySaver } from "@langchain/langgraph";
import { HumanMessage } from "@langchain/core/messages";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import * as dotenv from "dotenv";
dotenv.config();
// ----------------------
// Custom Weather Tool
// ----------------------
class WeatherTool extends Tool {
name = "get_weather";
description =
"Fetches current weather data for a given city. Use this when asked about weather.";
async _call(city: string): Promise<string> {
try {
const url = `${process.env.WEATHER_API_URL}?q=${encodeURIComponent(
city,
)}&appid=${process.env.WEATHER_API_KEY}&units=metric`;
const res = await fetch(url);
if (!res.ok) return `Weather API error: ${res.statusText}`;
const data = await res.json();
const weather = data.weather?.[0]?.description ?? "No description";
const temp = data.main?.temp ?? "N/A";
const feels_like = data.main?.feels_like ?? "N/A";
return `Weather in ${city}: ${weather}, Temp: ${temp}°C, Feels like: ${feels_like}°C`;
} catch (err) {
return `Error: ${(err as Error).message}`;
}
}
}
// ----------------------
// Setup LLM Agent
// ----------------------
const weatherTool = new WeatherTool();
const agentModel = new ChatOpenAI({ temperature: 0 });
const memory = new MemorySaver();
const agent = createReactAgent({
llm: agentModel,
tools: [weatherTool],
checkpointSaver: memory,
});
// ----------------------
// Use the Agent
// ----------------------
const run = async () => {
const first = await agent.invoke(
{ messages: [new HumanMessage("What is the weather in San Francisco?")] },
{ configurable: { thread_id: "42" } },
);
console.log(
"
[SF]",
first.messages[first.messages.length - 1].content,
);
const second = await agent.invoke(
{ messages: [new HumanMessage("what about New York?")] },
{ configurable: { thread_id: "42" } },
);
console.log(
"
[NY]",
second.messages[second.messages.length - 1].content,
);
};
run();