Working through this module?
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.
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.
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.
Chains vs Agents vs Tools
| Aspect | Chains | Agents | Tools |
|---|---|---|---|
| Purpose | Execute a fixed sequence of steps | Dynamically decide and use tools | External functions or APIs used by agents |
| Control Flow | Predefined | Dynamic (LLM decides) | Executed when called by an agent |
| Use Case | RAG, summarization, Q&A pipelines | Complex tasks, multi-step reasoning | Search, database query, calculator, API calls, etc. |
| Flexibility | Less flexible | More flexible and autonomous | Extensible (custom tools) |
| Examples | LLMChain, RetrievalQA | ZeroShotAgent, OpenAIAgent | SearchTool, PythonREPLTool, Custom Tools |
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"])
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"])
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
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"])
Popular Built-in Tools
| Tool | Description |
|---|---|
| DuckDuckGoSearchRun | Search information from the internet |
| SerpAPIWrapper | Search using Google SerpAPI |
| WikipediaQueryRun | Search from Wikipedia |
| PythonREPLTool | Execute Python code |
| SQLDatabaseToolkit | Query a database using natural language |
| RequestsTool | Make HTTP API requests |
| Custom Tool | Create your own tool (e.g., call internal API) |
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.