LangChain Agent Example: Empower Your Applications with Intelligent Tools
In the world of AI and large language models, agents are a core concept that make applications more dynamic and adaptable. Simply put, an agent in LangChain is an intelligent component that uses a language model to perform tasks by interacting with various tools and external systems. Unlike static workflows, agents can decide which tools to use and in what sequence, based on the context of a query or a task.
Agents are not just passive responders—they are capable of reasoning, planning, and taking actions autonomously. By leveraging LangChain's framework, agents can interact with APIs, databases, vector stores, and more to provide intelligent, multi-step solutions to complex problems.
Use Cases for Agents
Knowledge-Driven Customer Support
Building an AI-powered agent that helps resolve customer queries by fetching relevant information from various data sources.
- The agent uses a vector database to retrieve relevant FAQ or documentation snippets.
- It queries a CRM API to pull customer details or order history.
- It combines these inputs to provide a context-aware, personalized response to the user.
Example: A customer asks, "Can you help me with my order status and explain the return policy?" The agent retrieves the order details from the API and fetches the policy from a document store, presenting a cohesive response.
Financial Assistant for Investment Recommendations
Assisting users in making informed investment decisions by fetching and analyzing financial data.
- The agent queries real-time stock price APIs or financial news APIs.
- It uses a calculator tool to assess portfolio performance or risk analysis.
- Based on the user’s preferences (e.g., "low-risk investments"), it recommends potential options.
Example: A user asks, "What are some low-risk stocks to invest in this month?" The agent retrieves market data, filters based on volatility, and explains its recommendations.
Automated Travel Planner
Planning trips by integrating multiple data sources, like flight search engines, weather APIs, and hotel booking services.
- The agent queries a flight search API to find the best deals for a destination.
- It retrieves weather data to check suitable travel dates.
- It interacts with a hotel booking API to recommend accommodations within the user’s budget.
Example: A user asks, "Plan a trip to Paris next month with flights under $500 and a hotel close to the Eiffel Tower." The agent provides a complete itinerary with flights, weather forecasts, and hotel suggestions.
Why These Use Cases Shine
These use cases highlight the agent’s ability to:
- Integrate Multiple Tools: Interact with APIs, databases, and external tools.
- Provide Personalized Responses: Tailor outputs based on user inputs and retrieved data.
- Handle Complex, Multi-Step Tasks: Break down user requests into actionable steps and deliver a unified result.
Agents empower applications to go beyond static, single-step workflows, making them suitable for real-world challenges across industries.
Zero Shot React Description
// Calculator Tool Claculator.ts
import { Tool } from "langchain/tools";
class Calculator extends Tool {
name = "calculator";
description = "Perform basic arithmetic operations.";
async _call(input: string): Promise<string> {
try {
const result = eval(input); // Use eval safely for arithmetic
return `The result of ${input} is ${result}`;
} catch (error) {
return "Invalid mathematical expression.";
}
}
}
export default Calculator;
================================================================================
// main.ts
import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { ChatOpenAI } from "@langchain/openai";
import Calculator from "./Calculator";
import * as dotenv from "dotenv";
dotenv.config();
async function main() {
const model = new ChatOpenAI({
modelName: "gpt-3.5-turbo",
temperature: 0,
openAIApiKey: process.env.OPENAI_API_KEY!,
});
const tools = [new Calculator()];
const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: "zero-shot-react-description",
verbose: true,
});
const result = await executor.call({ input: "What is 42 times 7?" });
console.log("Agent Response:", result.output);
}
main().catch(console.error);
This code demonstrates the implementation of a LangChain agent that integrates a custom calculator tool to perform arithmetic operations dynamically. The Calculator tool, defined as a class extending LangChain's Tool, evaluates mathematical expressions provided by the user. The main script initializes the LangChain agent using the initializeAgentExecutorWithOptions function, incorporating the Calculator tool and an OpenAI GPT-3.5 model (ChatOpenAI). The agent uses the "zero-shot-react-description" approach, enabling it to interpret the input, decide on actions, and utilize the tool to calculate results. With verbosity enabled, the agent logs its reasoning process, including intermediate thoughts and tool interactions. The setup showcases how to extend LangChain with custom tools to create intelligent, interactive systems that combine LLM reasoning with external functionality.
Conversational React Description agent
// Calculator Tool Claculator.ts
import { Tool } from "langchain/tools";
class Calculator extends Tool {
name = "calculator";
description = "Perform basic arithmetic operations.";
async _call(input: string): Promise<string> {
try {
const result = eval(input); // Use eval safely for arithmetic
return `The result of ${input} is ${result}`;
} catch (error) {
return "Invalid mathematical expression.";
}
}
}
export default Calculator;
================================================================================
// main.ts
import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { ChatOpenAI } from "@langchain/openai";
import Calculator from "./Calculator";
import * as dotenv from "dotenv";
dotenv.config();
async function main() {
const model = new ChatOpenAI({
modelName: "gpt-3.5-turbo",
temperature: 0,
openAIApiKey: process.env.OPENAI_API_KEY!,
});
const tools = [new Calculator()];
const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: "zero-shot-react-description",
verbose: true,
});
const result = await executor.call({ input: "What is 42 times 7?" });
console.log("Agent Response:", result.output);
}
main().catch(console.error);
This example demonstrates how to implement a Conversational React Description agent in LangChain, which excels at managing multi-turn interactions by retaining conversational context. The agent integrates a custom Calculator tool for arithmetic operations and uses OpenAI's GPT-3.5 model (ChatOpenAI) for reasoning. Unlike zero-shot agents, this agent type remembers previous queries, enabling dynamic, context-aware responses. With the "conversational-react-description" agent type, you can build AI systems for use cases like conversational assistants, chatbots, or tools requiring sequential reasoning. The provided example highlights how the agent answers an initial arithmetic query and then performs further calculations based on prior results, showcasing its adaptability and intelligence in managing conversations.
Function Calling Agent
// Weather Tool WeatherTool.ts
import { Tool } from "langchain/tools";
class WeatherTool extends Tool {
name = "weather-tool";
description = "Fetch the current weather for a given city.";
async _call(city: string): Promise<string> {
try {
const response = await fetch(
`https://wttr.in/${encodeURIComponent(city)}?format=%C+%t`
);
if (!response.ok) {
throw new Error(`Failed to fetch weather data for ${city}.`);
}
const weatherData = await response.text();
if (!weatherData || weatherData.includes("Unknown location")) {
return `Sorry, I couldn't find weather data for ${city}.`;
}
return `The current weather in ${city} is ${weatherData.trim()}.`;
} catch (error) {
if (error instanceof Error) {
console.error("Error fetching weather data:", error.message);
return "I'm sorry, I couldn't fetch the weather data. Please try again later.";
} else {
return "An unknown error occurred while fetching weather data.";
}
}
}
}
export default WeatherTool;
================================================================================
// main.ts
import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { ChatOpenAI } from "@langchain/openai";
import WeatherTool from "./WeatherTool";
import * as dotenv from "dotenv";
dotenv.config();
async function main() {
const model = new ChatOpenAI({
modelName: "gpt-4",
temperature: 0,
openAIApiKey: process.env.OPENAI_API_KEY!,
});
const tools = [new WeatherTool()];
const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: "openai-functions",
verbose: true,
});
console.log("Agent Initialized. You can ask for weather updates!");
const userQuery = "What's the weather in Berlin?";
const response = await executor.call({ input: userQuery });
console.log("Agent Response:", response.output);
}
main().catch(console.error);
This code demonstrates a Function Calling Agent built with LangChain and OpenAI's GPT-4 model, integrated with the public wttr.in API for real-time weather updates. The WeatherTool fetches weather information by sending a query to the wttr.in API with the city name dynamically encoded in the URL. If the API responds with valid data, the tool parses the weather condition and temperature into a human-readable format. The main script initializes the LangChain agent with the WeatherTool, allowing it to respond to user queries like "What's the weather in Berlin?" using OpenAI's function-calling capabilities. With robust error handling for unknown locations or API issues, this implementation highlights how to combine LangChain's tooling framework with external APIs to create practical, intelligent agents.
Ohter LangChain Agents
- MRKL (Modular Reasoning, Knowledge, and Language) System: A more advanced agent type that combines reasoning, knowledge retrieval, and language capabilities. It selects appropriate tools or APIs based on modular reasoning. Complex, multi-step tasks that require combining reasoning with external knowledge retrieval.
- Self-Ask with Search: This agent type uses a search tool to retrieve information as needed before answering the user's query. It iteratively searches until sufficient information is gathered. Open-domain question answering where the agent needs to retrieve external information.
- Multi-Action Agent: An agent that can take multiple actions in a single turn. It is useful when a query requires invoking several tools simultaneously or in sequence. Complex workflows involving multiple APIs or tools, such as planning a trip with flight, hotel, and activity booking.
- Tool-Only Agent: This agent does not use the LLM for reasoning and instead directly invokes a predefined tool based on the user’s query. Simplified scenarios where the user input directly maps to a single tool action.
- And Others
Conclusion
LangChain agents revolutionize how applications interact with large language models by enabling dynamic, context-aware, and intelligent behavior. Through the examples explored — Zero Shot React Description, Conversational React Description, and Function Calling Agent — we see how agents can leverage tools to solve real-world problems, from performing arithmetic operations to fetching weather data and maintaining multi-turn conversational context. These agents highlight the flexibility of LangChain in combining LLM reasoning with external integrations, making it a powerful framework for building next-generation AI-powered applications. By incorporating robust error handling, dynamic queries, and tool-based actions, LangChain empowers developers to create scalable, task-oriented systems that deliver seamless user experiences across industries. Whether you're building chatbots, financial assistants, or travel planners, LangChain's agent framework opens up a world of possibilities for intelligent, interactive solutions.