Sign up for my FREE incoming seminar at Soft Uni:
LangChain in Action: How to Build Intelligent AI Applications Easily and Efficiently ?

Harnessing LangChain Agents: Building Smarter AI Interactions

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 leveragingLangChain's framework, agents can interact with APIs, databases, vector stores, and more to provide intelligent, multi-step solutions to complex problems.

LangChain Agents
LangChain Agents

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.

Understanding Zero Shot React Description in AI Agents

Zero Shot React Description is a technique used in AI agents to make decisions dynamically without requiring prior training examples or fine-tuning. It enables the agent to reason about a problem, decide on an appropriate tool, and generate an action—all in real-time.

Why Use Zero Shot React Agents?

  • No Training Required: Unlike supervised learning, this method allows AI to solve tasks without pre-labeled examples.
  • Dynamic Decision Making: The agent can decide on the best tool to use based on the input question.
  • Explainable AI: The ReAct (Reason + Act) framework provides a step-by-step explanation of how the AI reaches a decision.
  • Efficient Use of Tools: The agent selects only relevant tools for the given task, making it adaptable to various scenarios.

Where Should You Use It?

  • AI-powered Assistants: When building AI agents that can dynamically call APIs, search databases, or use tools.
  • Automated Data Processing: When working with calculators, data parsers, or document analyzers.
  • Chatbots and Helpdesk Agents: Where the bot needs to determine whether to use an external tool or answer directly.
  • Scientific and Engineering Applications: To dynamically calculate formulas, process text data, or retrieve structured knowledge.

╔════════════════════════════════════════════════════════════════════════════╗
║                         🌟 EDUCATIONAL EXAMPLE 🌟                         ║
║                                                                            ║
║  📌 This is a minimal and short working example for educational purposes.  
║  ⚠️ Not optimized for production!║                                                                            ║
║  📦 Versions Used:- "@langchain/core": "^0.3.38"- "@langchain/openai": "^0.4.2"║                                                                            ║
║  🔄 Note: LangChain is transitioning from a monolithic structure to a      ║
║      modular package structure. Ensure compatibility with future updates.  
╚════════════════════════════════════════════════════════════════════════════╝

import { Tool } from "@langchain/core/tools"; // used to define custom tools that an agent can use to perform specific tasks
import { AgentExecutor, createOpenAIFunctionsAgent } from "langchain/agents"; // used to create an agent that can execute tasks
import { ChatOpenAI } from "@langchain/openai"; // used to create an OpenAI language model
import { ChatPromptTemplate } from "@langchain/core/prompts"; // used to create a prompt template for the agent
import dotenv from "dotenv"; // used to load environment variables from the .env file

dotenv.config(); // load environment variables from the .env file

const model = new ChatOpenAI({ // create an instance of the ChatOpenAI class
    modelName: "gpt-3.5-turbo",
    temperature: 0,
    openAIApiKey: process.env.OPENAI_API_KEY!,
})

class Calculator extends Tool { // define a custom tool that can perform basic arithmetic operations
    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.";
        }
    }
}

async function run() { // define an async function to run the agent
    const tools = [new Calculator()]; // create an array of tools

    const prompt = ChatPromptTemplate.fromMessages([ // create a prompt template for the agent
        ["system", "You are an AI assistant that can answer user questions using a calculator."],
        ["human", "{input}"],
        ["ai", "{agent_scratchpad}"], // Include agent_scratchpad
    ]);

    const agent = await createOpenAIFunctionsAgent({ // create an agent that can execute tasks
        llm: model,
        tools,
        prompt,
    });

    const executor = new AgentExecutor({ // create an executor that can execute tasks
        agent,
        tools,
        verbose: false, //  LangChain's verbose debug logs, which show detailed information about the agent's execution process.
    })

    const result = await executor.invoke({ input: "What is 42 times 7?" }); // execute the agent with the given input

    console.log("Agent Response:", result.output); // print the agent's response
}

run().catch(console.error); // run the function and catch any potential errors

Explanation of the Code

  • Imports Required Libraries: Loads LangChain, dotenv (for API keys), and OpenAI API.
  • Defines a Calculator Tool: Creates a custom tool for performing arithmetic calculations.
  • Creates an OpenAI GPT Model: Initializes gpt-3.5-turbo to process responses.
  • Defines a Zero Shot ReAct Prompt: Ensures AI follows the structured ReAct framework (Reason + Act).
  • Creates a ReAct Agent: Uses createOpenAIFunctionsAgent() to build an AI assistant.
  • Executes the Agent Using an Executor: Runs the agent and retrieves the response dynamically.
  • Handles Errors Gracefully: Prevents crashes by catching errors at runtime.

Conversational Re-Act Description agent

A Conversational ReAct Description Agent is a special type of AI agent that:

  • Remembers past interactions – It maintains memory of the conversation.
  • Uses reasoning before acting – It analyzes the query before deciding what action to take.
  • Utilizes tools dynamically – If needed, it calls external tools (e.g., a calculator) to solve queries.
  • Provides structured responses – The agent follows a predefined format when responding.

This type of agent is based on the ReAct (Reason + Act) Framework, where the model:
✅ Thinks → Chooses an Action → Executes the Action → Observes the Result → Responds

You can use it for: AI Chatbots, Customer Support Bots, Virtual Assistants, Automation Agents


import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createOpenAIFunctionsAgent } from "langchain/agents";
import { Tool } from "langchain/tools";
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";
import dotenv from "dotenv";

dotenv.config();

// Define the CalculatorTool without zod
class CalculatorTool extends Tool {
  name = "Calculator";
  description = "Performs arithmetic calculations. Provide an 'expression' as input. Example: {"expression": "15 * 3"}";

  async _call(expression: string) {
    console.log(`CalculatorTool called with expression: ${expression}`); // Debugging log
    try {
      return eval(expression).toString();
    } catch (error) {
      return "Error: Invalid calculation input.";
    }
  }
}

// Define the TimeTool without zod
class TimeTool extends Tool {
  name = "TimeFetcher";
  description = "Returns the current date and time in ISO format. No input is required.";

  async _call() {
    return new Date().toISOString();
  }
}

async function main() {
  const model = new ChatOpenAI({
    model: "gpt-4",
    temperature: 0.7,
  });

  const tools = [new CalculatorTool(), new TimeTool()];

  // Define a system prompt template
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are an AI assistant with access to tools. Use them wisely to assist users."],
    new MessagesPlaceholder("chat_history"), // Ensure history is handled properly
    ["human", "{input}"],
    new MessagesPlaceholder("agent_scratchpad"), // Ensure agent's scratchpad is included
  ]);

  // Create the agent
  const agent = await createOpenAIFunctionsAgent({
    llm: model,
    tools,
    prompt,
  });

  // Create the executor
  const executor = new AgentExecutor({
    agent,
    tools,
    verbose: false,
  });

  console.log("Agent initialized. Ready for conversation.");

  const input = "What is 15 * 3? Also, what is the current time?";

  console.log(`User: ${input}`);
  const result = await executor.invoke({
    input,
    chat_history: [], // Ensure chat history is always provided
    agent_scratchpad: [], // Ensure agent_scratchpad is provided
  });

  console.log("Agent Response:", result.output);
}

main().catch(console.error);
  • Imports Required Libraries Loads necessary modules from LangChain, OpenAI, and memory management.
  • Defines Calculator Tool Creates a custom calculator tool that can perform basic arithmetic.
  • Creates a Chat Model (ChatOpenAI) Initializes the GPT-3.5-turbo model with temperature = 0 for consistent responses.
  • Enables BufferMemory Allows the agent to remember past interactions.
  • Defines the Prompt Template (ChatPromptTemplate) Ensures the AI follows structured ReAct reasoning.
  • Creates the ReAct Agent Uses createReactAgent() to enable reasoning before action.
  • Sets Up the AgentExecutorExecutes queries while managing memory.
  • Processes User Input Handles questions, including memory recall.
  • Handles Errors Ensures the agent doesn't crash on invalid queries.

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.