Working through this module?0 of 17 done
Module 10 · Page 11 of 20 · 9 sections

Agents in LangChain (Advanced)

The ReAct loop in detail, the full list of agent types, the tools agents commonly use and examples of a ReAct agent, a multi-tool agent and a custom-tool agent.

10.1

What are Agents?

  • Agents are LLMs that can decide which tools to use, when to use them and in what order to achieve a goal.
  • They can break complex tasks into multiple steps, use tools and reason about the next action.
  • Agents follow a reasoning loop called "Plan → Action → Observation".
  • LangChain provides different agent types and an easy way to create custom agents.
10.2

Why Use Agents?

  • Handle complex, multi-step tasks.
  • Automatically choose the right tool based on the user query.
  • Work with real-time data (APIs, DB, search, etc.).
  • Useful for chatbots, research assistants, report generators and automation systems.
  • Reduce manual effort by letting the LLM decide the workflow.
10.3

How Agents Work (ReAct Pattern)

User QueryGoal
LLMReasoning
Choose ToolDecide action
Execute ToolAPI / DB / search / etc.
Observe ResultUse output
Final AnswerTo user

The LLM thinks, chooses a tool, performs an action, observes the result and repeats until the final answer is ready.

10.4

Types of Agents in LangChain

Agent TypeDescription
ZeroShotAgentDecides tool usage without examples.
ReActAgentUses reasoning (Thought → Action → Observation) to decide the next step.
StructuredChatAgentUses a structured chat format with tools.
OpenAIFunctionsAgentUses OpenAI function calling.
ConversationalAgentMaintains conversation history.
SelfAskWithSearchAgentBreaks complex questions into simple sub-questions.
Custom AgentCreate your own agent with custom logic and tools.
10.5

Common Tools Used with Agents

  • SerpAPI / search tools (Google Search)
  • Python REPL tool (run Python code)
  • Requests tool (HTTP API calls)
  • SQL Database tool (query database)
  • Wikipedia tool (general knowledge)
  • Custom tools (business logic, internal APIs)
10.6

Example 1: ReAct Agent with Search Tool

python
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import SerpAPIWrapper

# Initialize LLM
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)

# Create search tool
search = SerpAPIWrapper()
tools = [search]

# Create ReAct agent
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.REACT_DOCSTORE,
    verbose=True
)

response = agent.invoke({"input": "What is the latest news about electric vehicles in India?"})
print(response["output"])
10.7

Example 2: Agent with Multiple Tools

python
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import SerpAPIWrapper, PythonREPLTool

llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)

search = SerpAPIWrapper()
python_tool = PythonREPLTool()
tools = [
    Tool(name="Search", func=search.run,
         description="Search the internet for information"),
    Tool(name="PythonREPL", func=python_tool.run,
         description="Run Python code for calculation or analysis")
]
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)
response = agent.invoke({"input": "Search the population of Delhi and calculate 5% of that number using Python."})
print(response["output"])
10.8

Example 3: Custom Tool with Agent

python
from langchain.tools import tool

@tool
def get_employee_details(emp_id: str) -> str:
    """Get employee details from internal system."""
    # Your business logic here
    return f"Employee {emp_id} - Name: Rahul, Dept: IT"

# Use this tool with an agent
# tools = [get_employee_details]
# agent = initialize_agent(tools, llm, agent=..., verbose=True)
10.9

Key Takeaways

  • Agents can use multiple tools to solve complex tasks.
  • Choose the right agent type based on your use case.
  • Provide clear tool descriptions for better results.
  • Agents follow a reasoning loop (Plan → Action → Observation).
  • Combine search, database, code execution and custom tools.
  • Useful for building powerful AI assistants and automation workflows.