LangChain Explained: The Framework Behind Production GenAI Applications
LangChain is an open-source framework for building applications on top of large language models. It gives you a standard interface to models, tools, retrieval and memory, so you can swap providers without rewriting your application, plus a configurable agent harness called create_agent that runs a model in a tool-calling loop until a task is done. It is used most often for RAG systems, tool-using agents, document processing pipelines and chatbots that need to reach real data. As of August 2026 the current version is LangChain 1.3.x, which requires Python 3.10 or higher and deprecates most patterns taught in pre-2026 tutorials.
That last sentence is the reason this article exists. LangChain is the most widely used and most badly documented framework in the GenAI stack, because the open web is full of tutorials teaching APIs that no longer exist.
Your roadmap to becoming a Generative AI Engineer
See what you already know, what to learn next and how long the switch to a GenAI engineering role takes. Tap any step for what to study and build.
What's inside8 stages · 30 steps to job-ready
- Python & engineering foundations
- ML & deep learning essentials
- How LLMs work
- Prompting & building LLM apps
- RAG & model customisation
- Agents & tool use
- Production, evaluation & safety
- Portfolio & job readiness
Python & engineering foundations
What to study
- Core Python: data types, functions, classes, modules
- Virtual environments and package management (pip, uv)
- Writing clean, testable scripts
What to build
A command-line script that reads a CSV, cleans it and writes a summary report.
What to study
- SQL joins, aggregations and window functions
- pandas for cleaning and reshaping data
- Working with text data at scale
What to build
A notebook that cleans a messy text dataset and prepares it for a model.
What to study
- Git branching and pull requests
- How REST APIs work: HTTP methods, status codes, auth headers
- Reading and writing JSON
What to build
Call a public API from Python, handle errors and save the results as JSON.
What to study
- Vectors, matrices and dot products
- Probability and distributions
- Gradients and optimisation, intuitively
What to build
Implement cosine similarity and gradient descent from scratch in NumPy.
ML & deep learning essentials
What to study
- Supervised vs unsupervised learning
- Train/test splits, overfitting and evaluation metrics
- scikit-learn workflows
What to build
Train and evaluate a text classifier with scikit-learn.
What to study
- Tokenisation and text preprocessing
- Word embeddings and semantic similarity
- Sequence models (RNN, LSTM) and why transformers replaced them
What to build
Build a semantic search over 500 short texts using sentence embeddings.
What to study
- Layers, activations, loss functions and backpropagation
- Training loops, batching and GPUs
- PyTorch tensors and autograd
What to build
Train a fully connected network on a small dataset and plot its learning curve.
How LLMs work
What to study
- Self-attention and multi-head attention
- Encoder, decoder and encoder-decoder models
- Positional encoding and why scale matters
What to build
Walk through a minimal transformer implementation and explain each block in a short write-up.
What to study
- The Transformers library, model hub and datasets
- Running open-weights models locally
- Fine-tuning a pre-trained model for a task
What to build
Fine-tune a small pre-trained transformer for sentiment or topic classification.
What to study
- Closed vs open-weights model families
- Tokens, context windows, temperature and sampling
- Comparing models on cost, latency and quality
What to build
A comparison table of three models answering the same 20 prompts, with cost and latency.
What to study
- Quantisation, pruning and distillation
- When a small model beats a large one
- On-device and low-cost inference
What to build
Quantise an open model and compare its speed and quality against the original.
Prompting & building LLM apps
What to study
- System prompts, few-shot examples and chain-of-thought
- Prompt test sets and versioning
- Reducing hallucinations through prompt design
What to build
A prompt library with a 30-example test set and before/after scores.
What to study
- Calling LLM APIs: streaming, rate limits, keys
- Serving with FastAPI and simple UIs with Streamlit
- Caching and cost control
What to build
A small chat app with streaming responses, deployed for others to try.
What to study
- JSON schema outputs and validation
- Function / tool calling
- Retries and graceful failure
What to build
An invoice or resume parser that returns validated JSON.
What to study
- Chains, prompts and output parsers
- Document loaders and retrievers
- When a framework helps and when it gets in the way
What to build
Rebuild your chat app with LangChain and compare the code with your plain-API version.
RAG & model customisation
What to study
- Embedding models and similarity search
- Vector databases (e.g. pgvector, Pinecone, Weaviate)
- Chunking strategies and metadata filters
What to build
Index a document set in a vector database and query it with filters.
What to study
- Supervised fine-tuning vs prompting vs RAG
- LoRA and other parameter-efficient methods
- Preparing instruction datasets
What to build
LoRA fine-tune an open-weights model on a narrow task and compare it with prompting alone.
What to study
- Vision transformers and CLIP-style models
- Image captioning and visual question answering
- Combining text and image retrieval
What to build
An image search app that finds photos from a text description.
What to study
- The RAG pipeline end to end
- Re-ranking, hybrid search and citations
- Measuring retrieval quality
What to build
A document Q&A assistant that cites its sources, with a retrieval-quality report.
What to study
- Instruction tuning and reward models
- RLHF and DPO, conceptually and with TRL
- Where alignment fits in real products
What to build
Train a small reward model and run a preference-tuning loop on a toy task.
Agents & tool use
What to study
- ReAct, planning and reflection patterns
- Single-agent vs multi-agent setups
- Memory: short-term, long-term and retrieval
What to build
A research agent that searches, reads and summarises sources on a topic.
What to study
- Model Context Protocol (MCP) servers and clients
- Connecting agents to databases, CRMs and internal APIs
- Permissions and audit trails for tool calls
What to build
An MCP server that exposes two tools from a real API, used by your agent.
What to study
- Graphs, state and checkpoints
- Human-in-the-loop approvals
- Error handling in multi-step workflows
What to build
Rebuild your research agent as a LangGraph workflow with an approval step.
Production, evaluation & safety
What to study
- Docker images for AI apps
- CI/CD basics
- Secrets and environment configuration
What to build
Containerise your RAG assistant and deploy it with a CI pipeline.
What to study
- Building evaluation datasets
- LLM-as-judge and its limits
- Regression testing prompts and models
What to build
An eval harness that scores your assistant on 50 cases and runs on every change.
What to study
- Tracing LLM calls
- Tracking token cost and latency
- Dashboards and alerting
What to build
Add tracing and a cost dashboard to your deployed app.
What to study
- Managed model platforms on AWS, GCP and Azure
- Serverless deployment and autoscaling
- Data privacy and region choices
What to build
Deploy your app on one cloud using a managed model endpoint.
What to study
- Hallucination, bias and privacy risks
- Prompt injection and defences
- PII handling and content filtering
What to build
Add input and output guardrails to your assistant and document the risks you tested.
Portfolio & job readiness
What to study
- GenAI system design questions
- Explaining trade-offs: RAG vs fine-tuning, cost vs quality
- Coding rounds in Python
What to build
Mock-interview notes for three GenAI system design questions.
What to study
- Choosing a domain problem (healthcare, fintech, edtech)
- Writing clear READMEs and architecture notes
- Recording a short demo
What to build
A client-ready AI agent for one domain, with a public demo and write-up.
Fine-tuned text classifier
Adapting a pre-trained transformer to a real task.
Fine-tune a small pre-trained transformer on a labelled dataset, evaluate it properly and compare it with a classic ML baseline.
Structured data extractor
Turning messy documents into clean JSON.
Use an LLM API with schema-validated outputs to extract fields from invoices or resumes, with a prompt test set to track accuracy.
Document Q&A assistant
Retrieval-augmented answers with citations.
Index a document collection in a vector database and build an assistant that answers questions with cited sources and a retrieval-quality report.
LoRA fine-tune of an open model
Customising a model when prompting isn't enough.
Fine-tune an open-weights model with LoRA on a narrow task and document when it beats prompting and RAG, and when it doesn't.
Reward model & preference tuning
Teaching a model what good looks like.
Train a small reward model on preference data and run a preference-tuning loop, with a write-up of what changed.
Multimodal image search
Finding images from plain-language descriptions.
Embed images and text in a shared space and build a search app that retrieves photos from a description.
Tool-using research agent
An agent that plans, acts and asks for approval.
Build a LangGraph agent that searches, reads and summarises sources, calls tools through an MCP server and pauses for human approval.
Deployed GenAI service
From notebook to a monitored production API.
Containerise an LLM app, deploy it on a cloud platform with CI/CD, and add tracing plus a cost and latency dashboard.
Eval harness with guardrails
Proving your AI app works, and stays safe.
Create a 50-case evaluation set, automate scoring on every change, and add input and output guardrails against prompt injection and PII leaks.
Domain AI agent capstone
A client-ready agent for a real industry problem.
Pick a domain such as healthcare, fintech or edtech and ship an agent that combines retrieval, tools, evals and guardrails, with a public demo and write-up.
GenAI glossary 17 terms
Tap a term to see what it means. You will hear these in every GenAI interview.
- LLM
- Large language model: a neural network trained on huge amounts of text to predict and generate language.
- Transformer
- The neural network architecture behind modern LLMs, built around the attention mechanism.
- Token
- A chunk of text (often part of a word) that a model reads and writes. Pricing and limits are counted in tokens.
- Context window
- The maximum number of tokens a model can consider at once, including your prompt and its answer.
- Prompt engineering
- Designing instructions and examples so a model reliably produces the output you need.
- Embeddings
- Numeric vectors that capture meaning, so similar texts end up close together.
- Vector database
- A database built to store embeddings and find the most similar ones quickly.
- RAG
- Retrieval-augmented generation: fetching relevant documents and giving them to the model so answers are grounded.
- Fine-tuning
- Further training a pre-trained model on your own data to specialise it.
- LoRA
- Low-rank adaptation: a parameter-efficient fine-tuning method that trains small add-on weights instead of the whole model.
- Agent
- An LLM system that plans steps, calls tools and acts towards a goal, often over several turns.
- Tool calling
- Letting a model call functions or APIs, such as search or a database query, with structured arguments.
- MCP
- Model Context Protocol: an open standard for connecting AI applications to tools and data sources.
- Evals
- Systematic tests that measure how well an AI system performs on representative cases.
- Guardrails
- Checks on inputs and outputs that keep an AI system safe, on-topic and compliant.
- Hallucination
- When a model states something false or unsupported with confidence.
- Prompt injection
- An attack where malicious text tricks a model into ignoring its instructions.
Close your gaps with a structured programme
The Certificate Programme in Generative AI from CEP, IIT Delhi covers transformers, fine-tuning, RAG, agents and responsible AI through live weekend classes and hands-on projects.
Key Takeaways
- LangChain is a standard interface plus an agent harness, not a magic layer that makes LLMs smarter.
- Current version is 1.3.x and requires Python 3.10+. Pre-v1 tutorials teach deprecated APIs.
- create_agent is the one agent abstraction now. Everything else you read about is legacy.
- Middleware is how you customise agent behaviour in v1: retries, summarisation, PII redaction, human approval.
- The framework’s biggest risk is using it when a direct API call would do.
What LangChain Actually Is
Strip away the marketing and LangChain does three things.
- It standardises model access. You write model=”openai:gpt-5.5″ or model=”anthropic:claude-sonnet-4-6″ and the rest of your code does not change. This sounds minor until you have to switch providers under cost pressure or an outage.
- It supplies the components LLM apps repeatedly need. Tools, retrievers, document loaders, text splitters, vector store integrations, output parsers, message types. None of these are conceptually difficult. All of them are tedious to write and maintain across providers.
- It provides an agent harness. This is the part that matters most now. LangChain’s own framing is “Agent = Model + Harness”, where the harness is everything around the model loop: the prompt, the tools, and the middleware that shapes behaviour.
- What LangChain is not: a model, a hosting platform, or something that improves output quality on its own. A badly specified prompt inside LangChain produces the same bad output it would produce anywhere else.
The three-layer picture
LangChain now ships as three layers, and knowing which one you are in prevents most confusion:
| Layer | What it is | Reach for it when |
| Deep Agents | Batteries-included harness with planning, virtual filesystem, subagents and memory pre-assembled | You want a capable agent fast and the defaults suit you |
| LangChain (create_agent) | Configurable harness you assemble yourself | You want control over the loop without writing graph code |
| LangGraph | Low-level orchestration runtime with explicit state graphs | Your flow needs custom topology, durability or human checkpoints |
The relationship in one line: create_agent compiles down to a LangGraph graph, and Deep Agents is built on create_agent. You are always using LangGraph underneath. For the full argument about when to drop down a layer, the LangChain vs LangGraph comparison covers the decision in depth, and this article stays at the LangChain layer.
What Is LangChain Used For?
The honest answer to “what is langchain used for” is narrower than the marketing suggests, and the narrowness is useful.
Retrieval-augmented generation. The dominant use case by a wide margin. You have documents the model was never trained on, and you need answers grounded in them. LangChain supplies loaders, splitters, embeddings interfaces and vector store integrations, which is most of a RAG pipeline’s plumbing. This guide to RAG covers the retrieval architecture itself.
Tool-using agents. The model needs to check inventory, query a database, call an internal API, or search the web. LangChain turns Python functions into tools the model can call and runs the loop that decides when to call them.
Document processing pipelines. Extracting structured data from unstructured input at volume: invoices, contracts, resumes, support tickets. This is where structured output and validation matter more than conversational ability.
Assistants over live systems. Internal support bots, sales assistants, ops copilots. The distinguishing requirement is reaching real data rather than answering from training.
Where LangChain is the wrong choice, stated plainly because most articles will not:
- You are making one or two LLM calls behind a function. Use the provider SDK. Adding a framework here is pure overhead and experienced reviewers notice.
- Your flow is a fixed sequence with no model-driven decisions. That is a script, not an agent.
- Retrieval quality is the entire product and you need deep control over indexing strategy. Specialised retrieval libraries fit better.
- You need something with a tiny dependency footprint. LangChain is not small.
How LangChain Agents Work
This section covers the langchain agents keyword and it is the part most worth your attention, because the agent abstraction is where v1 changed most.
An agent is a model calling tools in a loop until the task is complete. That is the whole concept. The model receives a task and a list of available tools, decides whether to call one, receives the result, and decides again. The loop ends when the model stops calling tools and returns an answer.
The minimal agent
From the current official documentation:
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="openai:gpt-5.5",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks) Three things deserve attention here.
The tool is a plain Python function. The docstring is not decoration: it becomes the tool description the model reads when deciding whether to call it. Vague docstrings produce agents that call the wrong tool, and this is one of the most common causes of bad agent behaviour.
The model is a string identifier. Swap “openai:gpt-5.5” for “anthropic:claude-sonnet-4-6” and nothing else changes.
Underneath those three arguments is a compiled graph with a model node, a tool node, and a conditional edge that loops until the model stops requesting tools.
Tools with the decorator
For anything beyond a trivial function, use the @tool decorator:
from langchain.agents import create_agent
from langchain.tools import tool
@tool
def search(query: str) -> str:
"""Search for information."""
return f"Results for: {query}"
agent = create_agent(model="anthropic:claude-sonnet-4-6", tools=[search] Middleware: the part that makes agents production-ready
Middleware is the defining feature of v1 agents and the thing most tutorials have not caught up with. It gives you hooks around each step of the loop, so you can change behaviour without rewriting the agent.
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware, HumanInTheLoopMiddleware
agent = create_agent(
model="gpt-5.5",
tools=[...],
middleware=[
SummarizationMiddleware(...),
HumanInTheLoopMiddleware(...)
], What official middleware covers, per the docs: logging and analytics, prompt and tool-selection transformation, retries, model fallbacks, early termination, rate limiting, guardrails, and PII detection.
That list is essentially a checklist of the things that separate a demo from a system. An agent with no retry logic, no call limit and no PII handling is a prototype regardless of how well it performs.
One important detail: middleware is not a separate runtime. The hooks run inside the compiled LangGraph that create_agent returns, which means you can drop an entire agent, middleware included, into a larger StateGraph as a single node and every hook still runs.
Deep Agents, the newest layer
If you want the capable-agent defaults without assembling them, deepagents is a separate package built on create_agent:
from deepagents import create_deep_agent
agent = create_deep_agent(
model="anthropic:claude-sonnet-4-6",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
It ships with a virtual filesystem for context management, subagent spawning with isolated context windows, long-term memory, context summarisation and offloading, and human-in-the-loop approval. The tradeoff is the usual one: less configuration, less control.
A LangChain Tutorial: Your First Working Agent
This covers the langchain tutorial intent. It is deliberately short, because the fastest way to understand LangChain is to build the smallest useful thing rather than read about it.
Prerequisites: Python 3.10 or higher. Version 1.x dropped 3.9 support. Comfort with Python functions and virtual environments is assumed.
- Step 1: Install. The provider comes as an extra.
- pip install -qU langchain “langchain[openai]”
- Step 2: Set your API key as an environment variable. Never hardcode it, and never commit it.
- Step 3: Write a tool that does something real. The weather example in the docs returns a hardcoded string, which is fine for checking your install and useless for learning. Replace it with a function that hits an actual API or reads an actual file. The interesting behaviour only appears when the tool can fail or return something unexpected.
- Step 4: Build the agent using the create_agent pattern above.
- Step 5: Break it deliberately. This is the step tutorials skip and it teaches more than the other four combined. Ask the agent something your tool cannot answer. Ask it something ambiguous enough that it should call two tools. Make the tool raise an exception. Watch what the loop does. You are learning the failure modes now, cheaply, instead of in production.
- Step 6: Add one piece of middleware. A call limit is the right first choice, because a runaway agent loop is the most expensive mistake in this space.
What to build next, in order: a RAG pipeline over your own documents, then an agent with three tools where choosing correctly between them matters, then the same agent with structured output validated against a schema. Those three cover most of what production work asks of you. The GenAI project ideas has fuller specifications if you want something scoped.
Why Most LangChain Tutorials Are Wrong
Worth its own section, because this is the single biggest obstacle to learning LangChain and almost nobody says it directly.
LangChain 1.0 shipped in October 2025 and consolidated years of API sprawl. The older chain and agent constructs moved to a langchain-classic package, leaving the core namespace focused on agents, models, messages and tools. The current release is 1.3.15, published 11 August 2026.
The practical filter. If a tutorial contains any of these, it predates the reset:
| Deprecated pattern | What replaced it |
| initialize_agent(…) | create_agent(…) |
| AgentExecutor | create_agent, which returns a runnable graph |
| LLMChain | Direct model invocation, or an agent |
| ConversationBufferMemory | Runtime state and checkpointers, or summarisation middleware |
| Bare from langchain.chains import … | Mostly moved to langchain-classic |
Check the publication date on anything you read. Before November 2025, assume it needs verification against the official migration guide. This applies to video content too, and video is worse, because the date is less visible and the code is harder to search.
This matters for interviews as much as for building. A candidate who writes AgentExecutor on a whiteboard in 2026 has signalled that their knowledge is second-hand and stale.
What LangChain Does Not Solve
A framework that is oversold gets a backlash it does not deserve. Here is the honest boundary.
- It does not make a weak model strong. Retrieval and tools extend what a model can reach. Neither improves its reasoning.
- It does not give you evaluation. You still need a test set and a measurement harness. LangSmith provides tracing and evaluation tooling, but the judgment about what “correct” means for your task is yours. Teams that skip this ship agents they cannot tell are degrading.
- It does not control cost. An agent loop can call a model many times per user request. Without call limits, cost per request is unbounded by default. This is the most common source of bill shock in agent projects and middleware is where you fix it.
- It does not remove the need to understand the underlying model. Context windows, tokenisation, temperature and tool-calling reliability all still apply. Understanding how large language models work is what lets you debug an agent that is behaving strangely, because the answer is usually in the model’s behaviour rather than the framework’s.
- It does not survive being used as a substitute for design. The failure mode is reaching for an agent when a deterministic function would be correct, faster, cheaper and testable.
Where LangChain Fits in Your Skill Stack
For an engineer with a few years of experience deciding how much to invest here, the useful framing is that LangChain is a week, and the things around it are the career.
Learning the framework itself is genuinely fast. create_agent, tools, middleware, retrieval, structured output. If you build the three projects listed earlier you will be productive within a couple of weeks. Professionals looking to master these practical development skills can enroll in the IIT Delhi generative AI programme.
What takes longer and matters more: knowing when an agent is the wrong architecture, being able to evaluate whether your system works, understanding cost and latency behaviour under load, and designing the retrieval layer well. Those transfer to every framework, including the ones that will replace this one.
The sequencing that works is fundamentals first, framework second. You want to understand what agents are conceptually before learning one library’s way of expressing them, because the concepts persist while the APIs churn. LangChain’s own v1 reset is the proof: everyone who learned the concepts adapted in an afternoon, and everyone who learned the API had to relearn it. The AI engineer roadmap puts this in order against the rest of the stack.
Build one thing end to end, including the unglamorous parts: evaluation, cost tracking, a failure path when the model returns nonsense. One complete system teaches more than five demos and is far more convincing in an interview, where the follow-up question is always about what broke.
Conclusion
LangChain is a standard interface to models plus a configurable agent harness. That is a smaller claim than the ecosystem around it makes, and it is also genuinely useful, which is why the framework remains the default starting point for production GenAI work.
The main thing standing between you and using it well is not difficulty. It is that most of the material you will find is teaching a version that no longer exists. Read the official docs, check the date on everything else, and build something small that breaks in interesting ways.
Then spend your remaining effort on the parts LangChain does not do for you: knowing whether your system actually works, and knowing when not to build an agent at all.
Frequently Asked Questions
Predominantly RAG over internal documents, tool-calling agents connected to internal APIs, document extraction pipelines, and customer support assistants. The unifying requirement is connecting a model to data or systems it cannot reach on its own.
The framework is open source and free. LangSmith, the observability and evaluation platform, is a separate commercial product with a free tier. Model API costs are separate and are usually the dominant expense.
There are separate Python and JavaScript/TypeScript implementations. Python is the more mature and more widely used of the two, and this article’s examples are Python.
No. For simple applications the provider SDK is often the better choice. LangChain earns its place when you need provider portability, an agent loop, retrieval plumbing, or the production concerns that middleware handles.
Good at tasks with a clear goal and a small set of well-described tools. Bad at tasks with ambiguous success criteria, and unreliable when given too many similar tools, because tool selection degrades as the options multiply.
The current 1.x line. As of August 2026 that is 1.3.15, requiring Python 3.10 or higher. Do not learn v0 patterns, and treat any pre-November-2025 material as suspect.
? A working agent in an afternoon. Practical competence in two to three weeks of building. Understanding when not to use it takes considerably longer and is the more valuable skill.