LangChain Tutorial 2026: Build AI Applications with Chains and Agents
โก Quick Answer
LangChain tutorial 2026 โ learn chains, agents, memory, and RAG with practical Python examples for building production AI applications from scratch.
Get more content like this on Telegram!
Daily AI tips, notes & resources โ free
Advertisement
LangChain Tutorial 2026: Build AI Applications with Chains and Agents
LangChain is an open-source Python and JavaScript framework for building applications on top of language models โ chains, memory, retrieval, and agents, instead of raw API calls. The complexity in an AI application was never the API call itself; it's everything around it: conversation history, vector databases, multi-step LLM calls, tools.
LangChain handles that scaffolding. By 2026 it's the most widely used framework for AI application development, with a cleaner architecture than earlier versions thanks to LangChain Expression Language (LCEL).
This tutorial covers the components used in real production systems, with working code for each.
Installation and Setup
# Core LangChain packages (modular in v0.2+)
pip install langchain langchain-openai langchain-anthropic langchain-community
pip install langchain-chroma # Vector store
pip install langgraph # For agents
pip install langsmith # Observability (optional)import os
os.environ["OPENAI_API_KEY"] = "your-key"
# Or use python-dotenv: from dotenv import load_dotenv; load_dotenv()Core Concept: LangChain Expression Language (LCEL)
LCEL composes chains with the pipe operator (|) โ prompt, model, and parser connect the way Unix commands pipe into each other, each stage's output feeding the next stage's input.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# Components
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)
output_parser = StrOutputParser()
# Simple chain: prompt | llm | parser
prompt = ChatPromptTemplate.from_messages([
("system", "You are an expert in {domain}."),
("human", "{question}")
])
chain = prompt | llm | output_parser
# Invoke
result = chain.invoke({
"domain": "Python",
"question": "What are the best practices for error handling?"
})
print(result)
# Stream
for chunk in chain.stream({"domain": "machine learning", "question": "Explain overfitting"}):
print(chunk, end="", flush=True)
# Batch (parallel execution)
results = chain.batch([
{"domain": "Python", "question": "What is a generator?"},
{"domain": "SQL", "question": "When should I use indexes?"},
{"domain": "Docker", "question": "What is a multi-stage build?"},
])Prompts and Templates
A prompt template is a reusable prompt with variable slots โ write the structure once, fill in the specifics per call. Few-shot templates go further, embedding examples directly so the model has a pattern to imitate.
from langchain_core.prompts import (
ChatPromptTemplate,
FewShotChatMessagePromptTemplate,
MessagesPlaceholder
)
# Few-shot prompting
examples = [
{"input": "happy", "output": "sad"},
{"input": "tall", "output": "short"},
{"input": "energetic", "output": "lethargic"},
]
example_prompt = ChatPromptTemplate.from_messages([
("human", "{input}"),
("ai", "{output}"),
])
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_prompt=example_prompt,
examples=examples,
)
final_prompt = ChatPromptTemplate.from_messages([
("system", "You are an antonyms generator."),
few_shot_prompt,
("human", "{input}"),
])
chain = final_prompt | llm | output_parser
print(chain.invoke({"input": "big"})) # "small"
# Dynamic prompts with message history
with_history_prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"), # Inject message history
("human", "{input}"),
])Conversation Memory with Message History
Conversation memory keeps prior turns available to the model across calls โ without it, every message would land in a fresh context with no idea a name was mentioned two messages ago.
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
# Session-based chat history
store = {}
def get_session_history(session_id: str) -> InMemoryChatMessageHistory:
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{input}"),
])
chain = prompt | llm | output_parser
# Wrap with message history
chain_with_history = RunnableWithMessageHistory(
chain,
get_session_history,
input_messages_key="input",
history_messages_key="history",
)
# Invoke with session tracking
config = {"configurable": {"session_id": "user-123"}}
print(chain_with_history.invoke({"input": "Hi, my name is Alice."}, config=config))
print(chain_with_history.invoke({"input": "What's my name?"}, config=config))
# Output: "Your name is Alice, as you told me!"RAG Chain
RAG (Retrieval-Augmented Generation) retrieves relevant documents before generating an answer, so the model responds from your data instead of only its training memory. This is what lets a chatbot answer questions about your own documentation instead of guessing.
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
from langchain_community.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.runnables import RunnablePassthrough
# 1. Load and index documents
loader = WebBaseLoader("https://example.com/docs")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = splitter.split_documents(docs)
vectorstore = Chroma.from_documents(splits, OpenAIEmbeddings())
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
# 2. RAG prompt
rag_prompt = ChatPromptTemplate.from_messages([
("system", """Answer the question using only the provided context.
If the answer isn't in the context, say "I don't have that information."
Context: {context}"""),
("human", "{question}")
])
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# 3. RAG chain with LCEL
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| rag_prompt
| llm
| output_parser
)
answer = rag_chain.invoke("What are the main features?")
print(answer)
# With sources
from langchain_core.runnables import RunnableParallel
rag_chain_with_sources = RunnableParallel(
{"context": retriever | format_docs, "question": RunnablePassthrough()}
).assign(answer=rag_prompt | llm | output_parser)
result = rag_chain_with_sources.invoke("What are the main features?")
print(f"Answer: {result['answer']}")Tool Use and Agents
An agent lets the model decide which tool to call and in what order, instead of following a fixed pipeline. Think of the difference between a fixed assembly line and a technician who chooses the right tool for each problem as it appears.
from langchain.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
# Define tools
@tool
def search_web(query: str) -> str:
"""Search the web for current information."""
# In practice: integrate with SerpAPI, Tavily, etc.
return f"Search results for: {query}"
@tool
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression."""
try:
result = eval(expression, {"__builtins__": {}}, {})
return str(result)
except Exception as e:
return f"Error: {e}"
@tool
def get_weather(city: str) -> str:
"""Get current weather for a city."""
# In practice: call a weather API
return f"Weather in {city}: 72ยฐF, partly cloudy"
tools = [search_web, calculate, get_weather]
# Create agent with LangGraph (modern approach)
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = create_react_agent(model, tools)
# Run the agent
response = agent.invoke({
"messages": [("human", "What is the square root of 144, and what's the weather like in Paris?")]
})
for message in response["messages"]:
print(f"{message.type}: {message.content}")Structured Output
Structured output forces the model's response into a defined schema โ a Pydantic model here โ instead of free-form text you'd otherwise have to parse and hope is well-formed.
from pydantic import BaseModel, Field
from typing import List
class MovieReview(BaseModel):
title: str = Field(description="Movie title")
rating: float = Field(description="Rating from 1-10")
pros: List[str] = Field(description="Positive aspects")
cons: List[str] = Field(description="Negative aspects")
summary: str = Field(description="One-sentence summary")
# Structured output with Pydantic
structured_llm = llm.with_structured_output(MovieReview)
review = structured_llm.invoke(
"Review the movie 'Inception' by Christopher Nolan"
)
print(f"Title: {review.title}")
print(f"Rating: {review.rating}/10")
print(f"Pros: {review.pros}")
print(f"Summary: {review.summary}")LangSmith Observability
LangSmith traces every LangChain call โ latency, token usage, inputs and outputs, errors โ into a dashboard, with no code changes beyond setting three environment variables.
import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-langsmith-key"
os.environ["LANGCHAIN_PROJECT"] = "my-chatbot"
# All LangChain calls are now traced to LangSmith dashboard
# View: latency, token usage, inputs/outputs, errors
# No code changes needed beyond setting environment variables
chain = prompt | llm | output_parser
result = chain.invoke({"question": "What is machine learning?"})
# This call appears in your LangSmith project dashboardThe Bottom Line
LCEL's pipe operator makes AI application composition genuinely elegant โ readable, composable pipelines instead of nested class configurations. The parts that pay off most in production are the retriever integrations, memory management, and LangSmith observability.
Start simple: reach for LCEL chains first, and add agents only when the task genuinely needs dynamic tool selection. Most AI applications don't need an agent โ they need a well-designed chain.
For the RAG component that makes chatbots know your data, see our RAG system tutorial. For deploying LangChain applications, see our production deployment guide.
Further Reading
- AI API Cost Management: How to Cut LLM Costs by 80% Without Losing Quality
- Build an AI Chatbot with Python: Complete Guide from Scratch to Deployment
- RAG System Tutorial: Build a Production Retrieval-Augmented Generation System
- Build a Personal AI Assistant: Complete Python Project with Memory and Tools
- Deploy AI Model to Production: FastAPI, Docker, and Cloud Deployment Guide
- Best Open Source LLMs in 2025: LLaMA, Mistral, Phi and More Compared
- OpenAI Assistants API Guide: Build Agents with Code Interpreter and File Search
- Recommendation Systems Explained: How Netflix and Amazon Know What You Want
Advertisement
๐ฌ DiscussionPowered by GitHub Discussions
Frequently Asked Questions

Software Testing Expert & Prompt Engineering
Ensures every release is bug-free through rigorous testing, and crafts high-precision prompts that power our AI-driven workflows. Abdullah Al Arman Emon leads QA and prompt engineering across AiTechWorlds.
Not sure yet? Ask AI about this article
Get an instant, unbiased AI summary of โLangChain Tutorial 2026: Build AI Applications with Chains and Agentsโ.
Advertisement
Related Articles
AI API Cost Management: How to Cut LLM Costs by 80% Without Losing Quality
AI API cost management โ practical strategies to reduce OpenAI, Claude, and Gemini API costs by 80% using model selection, caching, RAG, prompt optimization, and batch processing.
Build an AI Chatbot with Python: Complete Guide from Scratch to Deployment
Build an AI chatbot with Python โ complete tutorial from OpenAI API integration to conversation memory, streaming responses, and deploying a production-ready chatbot application.
Build a Personal AI Assistant: Complete Python Project with Memory and Tools
Build a personal AI assistant in Python with persistent memory, web search, file access, and calendar integration โ a complete project from architecture to working prototype.
CrewAI Tutorial: Build Multi-Agent AI Systems That Work Together
CrewAI tutorial โ build multi-agent AI systems where specialized agents collaborate to complete complex tasks, with practical Python examples for research, coding, and content workflows.