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

LangChain Chains, Agents and Tools

A side-by-side view of chains, agents and tools, with an LLMChain, a RetrievalQA chain and an agent with a search tool, plus the popular built-in tools.

17.1

What are Chains?

  • Chains in LangChain are sequences of components that work together to perform a task.
  • They allow you to combine LLMs, prompts, retrievers and other components in a pipeline.
  • Chains make it easy to build complex workflows like RAG, summarization and question answering.
  • LangChain provides built-in chains like LLMChain, RetrievalQA, ConversationalChain, etc.
17.2

What are Agents?

  • Agents use an LLM to decide which tool to use, when to use it and how to use it.
  • They can interact with external systems (APIs, databases, calculators, search, etc.) to complete tasks.
  • Agents can plan, take actions, observe results and iterate until they get the final answer.
  • Useful for dynamic tasks where the LLM needs to choose the right tool based on the user query.
17.3

Chains vs Agents vs Tools

AspectChainsAgentsTools
PurposeExecute a fixed sequence of stepsDynamically decide and use toolsExternal functions or APIs used by agents
Control FlowPredefinedDynamic (LLM decides)Executed when called by an agent
Use CaseRAG, summarization, Q&A pipelinesComplex tasks, multi-step reasoningSearch, database query, calculator, API calls, etc.
FlexibilityLess flexibleMore flexible and autonomousExtensible (custom tools)
ExamplesLLMChain, RetrievalQAZeroShotAgent, OpenAIAgentSearchTool, PythonREPLTool, Custom Tools
17.4

Simple Chain Example (LLMChain)

python
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain

# 1. Define LLM
llm = OpenAI(model="gpt-3.5-turbo", temperature=0.7)

# 2. Define prompt template
prompt = PromptTemplate(
    input_variables=["topic"],
    template="Explain {topic} in simple words."
)

# 3. Create chain
chain = LLMChain(llm=llm, prompt=prompt)

# 4. Run chain
result = chain.invoke({"topic": "Microservices"})
print(result["text"])
17.5

Retrieval QA Chain Example

python
from langchain.chains import RetrievalQA
from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.llms import OpenAI

# Load and split document
loader = PyPDFLoader("data/tech_document.pdf")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=1000,
    chunk_overlap=200)
chunks = splitter.split_documents(docs)

# Create vector store
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(chunks, embeddings)
retriever = vectorstore.as_retriever()

# Create RetrievalQA chain
qa_chain = RetrievalQA.from_chain_type(llm=OpenAI(),
    chain_type="stuff", retriever=retriever)

result = qa_chain.invoke({"query": "What is the main topic of this document?"})
print(result["result"])
17.6

Agents Architecture

User QueryFind latest news and summarize
AgentLLM decides which tool to use
ToolsWeb search, database, custom tool
ObservationTool result
Final OutputLLM generates answer
17.7

Agent Example (Using Tools)

python
from langchain.agents import initialize_agent, Tool
from langchain.tools import DuckDuckGoSearchRun
from langchain.llms import OpenAI

# Define tools
search = DuckDuckGoSearchRun()
tools = [
    Tool(
        name="Search",
        func=search.run,
        description="Useful for searching information on the internet"
    )
]

# Create agent
llm = OpenAI(model="gpt-3.5-turbo", temperature=0.7)
agent = initialize_agent(tools, llm, agent="zero-shot-react-description",
                         verbose=True)

# Run agent
response = agent.invoke({"input": "Find latest news about AU Small Finance Bank"})
print(response["output"])
17.8

Popular Built-in Tools

ToolDescription
DuckDuckGoSearchRunSearch information from the internet
SerpAPIWrapperSearch using Google SerpAPI
WikipediaQueryRunSearch from Wikipedia
PythonREPLToolExecute Python code
SQLDatabaseToolkitQuery a database using natural language
RequestsToolMake HTTP API requests
Custom ToolCreate your own tool (e.g., call internal API)
17.9

Key Takeaways

  • Chains execute a fixed sequence of steps.
  • Agents dynamically decide which tool to use.
  • Tools extend agent capabilities with external APIs and functions.
  • Use built-in tools or create custom tools.
  • Agents are useful for complex, multi-step real-world tasks.
  • Combine Chains + Agents + Tools for powerful LLM applications.