LangChain Tutorial 120 lessons · 2:16:24+ of video
LangChain Home Getting Started
What Is LangChain How LLM Apps Work Setting Up Models and Messages
Your First Model Call Messages Conversations Settings, Streaming, Batches
Model Settings Streaming Batch Calls Tokens and Providers
Tokens and Usage Switching Providers Basics Quiz Prompt Templates
Prompt Templates Chat Prompt Templates MessagesPlaceholder Examples, Chains, Parsers
Few-Shot Prompts Chains with the Pipe Output Parsers Runnables
Runnables RunnableLambda RunnableParallel Passthrough, Routing, Fallbacks
RunnablePassthrough Routing Fallbacks and Retries Inside Chains and Practice
Seeing Inside a Chain Practice: Review Summariser Chains Quiz Structured Output
Why Structured Output Pydantic Models with_structured_output Shapes, Labels, Extraction
Lists and Nested Data Classification Extraction Structured Output in Practice
Batch Extraction When Output Goes Wrong Structured Output Quiz Tools
What Are Tools The tool Decorator Tool Schemas Tool Calls by Hand
Binding Tools Reading Tool Calls Running Tools Yourself Agents
The Agent Loop create_agent Several Tools Prompts, Streaming, Memory
Agent System Prompts Streaming Agent Steps Agent Memory Structured Answers and Middleware
Structured Agent Answers Middleware Built-in Middleware Context and Errors
Dynamic Prompts Tool Errors Runtime Context Agent Practice and Approval
Practice: Bookshop Agent Human Approval Agents Quiz RAG Foundations
What Is RAG Documents Loading Files Chunks and Embeddings
Splitting Text Chunk Size and Overlap Embeddings Similarity and Vector Stores
Similarity Vector Stores Search with Scores Retrievers
Retrievers Metadata Filters MMR Search Your First RAG Chain
Your First RAG Chain The RAG Prompt Saying I Don't Know Better RAG
Citing Sources Conversational RAG RAG as a Tool RAG in Practice
Saving a Vector Store Checking RAG Quality RAG Pitfalls FAQ Bot and Async
Practice: Bookshop FAQ Bot RAG Quiz Async Calls Cache, Limits and Timeouts
Caching Model Calls Rate Limiting Timeouts Cost, Logging and Tracing
Tracking Cost Callbacks for Logging Tracing with LangSmith Evaluation
Evaluating Answers Test Sets Comparing Prompts Safety
Prompt Injection Guardrails PII Redaction Reliability
Model Fallbacks Limiting Agent Calls Production Quiz Serving and the Project Plan
Serving with FastAPI Streaming over HTTP Project: Support Bot Plan Project: Building the Bot
Project: Knowledge Base Project: Tools Project: The Agent Project: Memory, Guardrails, Tests
Project: Memory Project: Guardrails Project: Testing Project Review and Good Habits
Project: Review Choosing Models Prompt Habits Images and Long Documents
Multimodal Input Long Documents Map-Reduce Summaries Rewriting and Extraction
Translation and Rewriting Data from Tables Applied Quiz The Bigger Picture
LangChain vs LangGraph The Ecosystem Cheat Sheet: Core Wrapping Up
Cheat Sheet: Agents and RAG Common Mistakes What to Learn Next LangChain · Lesson 50 of 120
Middleware Hooks around the model.
⏱ 2 min read ▶ Video at 55:20 🎓 Free
▶ starts at 55:20 Sometimes you want to change what happens inside the agent loop. Log every model call. Trim long histories. Block certain requests. Middleware lets you hook into the loop, at well defined points.
From the video: Middleware Change the inside of the loop Log, trim, block Hooks at fixed points Middleware can run at several points. Before the agent starts. Before each model call. Around the model call itself, which lets you change the request or the response. After each model call. And around each tool call. You pick only the hooks you need.
before_agent
before_model
wrap_model_call
after_model
wrap_tool_call
From the video: Where middleware runs Here we write two small hooks, using decorators. Before model prints how many messages are about to be sent. Wrap tool call prints the tool and its arguments, then runs it. We pass both in the middleware list. Run it. We can now see inside the loop, every model call, and every tool call.
middleware.py python Copy
from langchain.agents import create_agent
from langchain.agents.middleware import before_model, wrap_tool_call
from shop_tools import check_stock
@before_model
def log_model (state, runtime):
print ( f "model call with { len (state[ 'messages' ]) } messages" )
@wrap_tool_call
def log_tool (request, handler):
print ( "tool:" , request.tool_call[ "name" ], request.tool_call[ "args" ])
return handler(request)
agent = create_agent( "google_genai:gemini-flash-lite-latest" , tools = [check_stock],
middleware = [log_model, log_tool])
out = agent.invoke({ "messages" : [{ "role" : "user" , "content" : "Is Dune in stock?" }]})
print ( "answer:" , out[ "messages" ][ - 1 ].text) Output
model call with 1 messages
tool: check_stock {'title': 'Dune'}
model call with 3 messages
answer: Yes, there are 3 copies of *Dune* in stock. Also uses shop_tools.py from langchain.tools import tool
BOOKS = {
"The Hobbit" : { "stock" : 7 , "price" : 8.99 , "author" : "J.R.R. Tolkien" },
"Dune" : { "stock" : 3 , "price" : 9.99 , "author" : "Frank Herbert" },
"Circe" : { "stock" : 0 , "price" : 10.99 , "author" : "Madeline Miller" },
}
@tool
def check_stock (title: str ) -> int :
"""Copies of a book in stock at Riverside Books."""
return BOOKS .get(title, {}).get( "stock" , 0 )
@tool
def get_price (title: str ) -> float :
"""Price of a book in pounds."""
return BOOKS .get(title, {}).get( "price" , 0.0 )
@tool
def get_author (title: str ) -> str :
"""Author of a book."""
return BOOKS .get(title, {}).get( "author" , "unknown" ) Prefer to watch? The full LangChain course is free All lessons in one video with animations, real code and chapters.
Watch free Middleware hooks into the agent loop, before and after model calls, and around tool calls. Decorators make simple hooks easy. Next, the ready made middleware LangChain provides.
Key takeaways @before_model @wrap_tool_call middleware=[...]