langchain-masterclass
A hands-on LangChain course with 100+ runnable labs — RAG, tools, agents, MCP, structured outputs, and multi-provider LLM support.
Install / Use
claude mcp add zainulabidin1 -- npx -y github:zainulabidin1/langchain-masterclassIf the server publishes to npm under a different name, use that package instead — check the repo README.
MCP Server
Model Context Protocol server
Quality Score
Category
AI & Machine LearningSupported Platforms
Skill content
View source on GitHubTable of Contents
- Introduction
- Features
- Course Roadmap
- Prerequisites
- Installation
- Configuration
- Running Labs
- Curriculum
- Skills Acquired
- Best Practices Demonstrated
- Troubleshooting / FAQ
- Contributing
- Acknowledgements
- License
🦜 Introduction
LangChain MasterClass is a structured, code-first curriculum that teaches you how to build sophisticated AI applications using the LangChain ecosystem. Every concept is grounded in a self-contained Python lab — no slides, no fluff, no theoretical hand-waving.
The repository spans 18 modules and 100+ individual labs, taking you from the absolute basics (invoking a chat model) all the way to building autonomous agents that call live APIs, query databases, discover tools over the Model Context Protocol, and reason across multi-step tool chains. Every lab is executable as a standalone script with a single command.
Target Audience
This course is designed for students, Python developers, backend engineers, and AI practitioners who want to build real LangChain applications — not just copy-paste demos. Whether you are transitioning into AI engineering, deepening an existing LangChain skill set, or building the knowledge base needed to build RAG and agent systems, this curriculum provides a clear, practical path.
| Audience | Why This Course Fits | |----------|---------------------| | Students | Bridging academic theory with industry-standard AI engineering | | Python Developers | Familiar with Python; want to add AI/LLM capabilities to their skill set | | Backend Engineers | Building APIs or services that incorporate LLM-powered features | | AI/ML Practitioners | Know the theory; want hands-on LangChain implementation experience | | Data Engineers | Interested in RAG pipelines, document processing, and semantic search |
What Makes It Different?
Unlike tutorial repositories that focus on a single feature or borrow examples directly from LangChain's documentation, this course builds every concept from the ground up using a consistent codebase, shared helper utilities, and progressively harder challenges. A multi-provider ModelFactory abstraction means you can run every lab against OpenAI, Anthropic Claude, Google Gemini, Ollama, or HuggingFace and more by changing two lines in a .env file.
✨ Features
- 📦 18 progressive modules — from your first model call to full autonomous agents
- 🧪 100+ runnable labs — every concept is a standalone, executable Python script
- 🔌 Multi-provider support — OpenAI, Anthropic, Google Gemini, Ollama, HuggingFace and more
- 🧬 Structured outputs — Pydantic, TypedDict, and JSON-schema-driven extraction
- 🗄️ Vector databases — InMemoryVectorStore, Chroma, and FAISS, each with full CRUD coverage
- 📚 Retrieval-Augmented Generation (RAG) — from basic pipelines to conversational chatbots and agentic RAG
- 🔗 Model Context Protocol (MCP) — local and remote tool discovery and aggregation
- 🤖 Agents — custom agentic loops, ReAct-style agents, SQL agents, and RAG agents
- ⚡ Async, Streaming — non-blocking pipelines with token-by-token delivery
- 📡 Callbacks — logging, cost tracking, and real-time event hooks
<p align="center"> 💡 If you find this repo useful, don't forget to <a href="https://github.com/zainulabidin1/langchain-masterclass/stargazers">star (🌟)</a> — it helps others discover it too! </p>
📚 Course Roadmap
| Module | Topic | Skills Learned |
|--------|-------|----------------|
| 01_models | Models & Embeddings | ChatModel, temperature, max_tokens, stop sequences, multimodal (image input), LLM caching, embedding vectors, embedding dimensions |
| 02_prompts | Prompt Engineering | Message types (System/Human/AI/Tool/Chat), PromptTemplate, ChatPromptTemplate, multi-variable prompts, few-shot prompting, length-based example selection |
| 03_chains | LCEL Chains | Simple LCEL chains, output parsers in chains, multi-step sequential chains, batch execution, sequential vs batch performance benchmarking |
| 04_runnables | LCEL Runnables | RunnableSequence, pipe operator \|, RunnableParallel, RunnableBranch, RunnableLambda (dynamic routing), RunnablePassthrough, .assign(), fallback chains, runtime ConfigurableField & ConfigurableAlternatives |
| 05_output_parsers | Output Parsers | StrOutputParser, CommaSeparatedListOutputParser, JsonOutputParser, XMLOutputParser, PydanticOutputParser, custom BaseOutputParser |
| 06_structured_output | Structured Output | JSON schema binding, TypedDict schema, Pydantic schema, nested Pydantic models, with_structured_output() |
| 07_async_streaming | Async & Streaming | ainvoke, astream (token-by-token), astream_events (v2 event filtering by run name) |
| 08_callbacks | Callbacks | StdOutCallbackHandler, OpenAI token & cost tracking, custom sync BaseCallbackHandler, custom async AsyncCallbackHandler |
| 09_memory | Memory & Persistence | Stateless chat (demonstrates forgetting), manual message list, RunnableWithMessageHistory, SQLite via SQLChatMessageHistory, JSON file custom history, trim_messages, interactive in-memory chatbot, interactive SQLite chatbot |
| 10_document_loaders | Document Loaders | TextLoader, CSVLoader, PyPDFLoader, WebBaseLoader, DirectoryLoader, SQLDatabaseLoader, WikipediaLoader |
| 11_text_splitters | Text Splitters | CharacterTextSplitter, RecursiveCharacterTextSplitter, TokenTextSplitter (tiktoken), MarkdownHeaderTextSplitter, language-aware code splitter, SemanticChunker |
| 12_document_transformers | Document Transformers | HTML cleaning & tag extraction with BeautifulSoupTransformer, semantic duplicate filtering with EmbeddingsRedundantFilter |
| 13_vector_stores | Vector Stores | InMemoryVectorStore (CRUD), Chroma (persistent, CRUD), FAISS (save/load, CRUD), similarity search types (standard, MMR, scored, threshold) |
| 14_retrievers | Retrievers | WikipediaRetriever, VectorStoreRetriever, BM25Retriever, EnsembleRetriever (hybrid), MultiQueryRetriever, ContextualCompressionRetriever (LLM extractor), ParentDocumentRetriever, MultiVectorRetriever (summary index), FlashRank reranking |
| 15_rag | RAG Pipelines | Basic RAG (PDF ingestion), Wikipedia RAG (LCEL), RAG + message history + query rewriting, RAG + Pydantic citations, conversational RAG chatbot (CLI), long-context reordering |
| 16_tools | Tools & Toolkits | DuckDuckGo/Wikipedia/PythonREPL/Requests built-in tools, @tool decorator, StructuredTool, BaseTool class, manual tool-call execution loop, FileManagementToolkit, custom BaseToolkit, retriever-as-tool |
| 17_mcp | Model Context Protocol (MCP) | FastMCP server, @mcp.tool(), STDIO transport, MultiServerMCPClient, local & remote (Streamable HTTP) tool discovery, multi-server aggregation |
| 18_agents | Agents | Custom agentic reasoning loop with tool dispatch, create_agent (built-in ReAct-style), create_sql_agent (natural language to SQL), MCP-powered agent via MultiServerMCPClient, retriever-as-tool RAG agent via create_retriever_tool |
📋 Prerequisites
- Python 3.10 or higher
- Basic Python proficiency (functions, classes, decorators,
async/await) - Familiarity with REST APIs and JSON (used in tool labs)
- At least one LLM API key (OpenAI, Anthropic, Google) — or Ollama install
- No prior LangChain experience required
🚀 Installation
1. Clone the repository
git clone https://github.com/zainulabidin1/langchain-masterclass.git
cd langchain-masterclass
2. Create and activate a virtual environment
python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate
3. Install all dependencies
pip install -r requirements.txt
4. Configure your environment
# macOS / Linux / Windows (PowerShell)
cp .env.example .env
# Windows (CMD)
copy .env.example .env
Then open .env and fill in your credentials (see Configuration below).
⚙️ Configuration
All configuration lives in the .env file at the project root. The two most important settings are LLM_MODEL_PROVIDER and LLM_MODEL_NAME.
# Choose your LLM provider: "openai", "google", "ollama", "anthropic", "huggingface"
LLM_MODEL_PROVIDER="ollama"
LLM_MODEL_NAME="gpt-oss:120b-cloud"
# Choose your embeddings provider: "openai", "google", "ollama", "huggingface"
EMBEDDINGS_MODEL_PROVIDER="ollama"
EMBEDDINGS_MODEL_NAME="nomic-embed-text"
# API Keys — fill in only the ones you plan to use
OPENAI_API_KEY=""
ANTHROPIC_API_KEY=""
GOOGLE_API_KEY=""
HUGGINGFACEHUB_API_TOKEN=""
# Set if not running Ollama on the default localhost. Otherwise leave blank
OLLAMA_BASE_URL=""
# Identifies your requests to external services (e.g. Wikipedia, WebBaseLoader)
# Some APIs reject or rate-limit requests with no User-Agent — safe to leave as default
USER_AGENT="LangChainMasterClass/1.0"
How model_factory.py Works
The _common/model_factory.py module is the backbone of the entire course. It reads LLM_MODEL_PROVIDER and LLM_MODEL_NAME from the environment at startup and exposes three factory functions:
| Function | Returns | Notes |
|----------|---------|-------|
| get_chat_model(**kwargs) | BaseChatModel | Supports OpenAI, Google, Ollama, Anthropic, HuggingFace |
| get_embedding_model(**kwargs) | Embeddings | Supports OpenAI, Google, Ollama, HuggingFace |
All **kwargs are forwarded directly to the underlying provider class, so you can pass temperature, max_tokens, streaming, or any provider-specific parameter without modifying the factory. This is why every lab can override the model behavior (e.g., get_chat_model(temperature=0.9)) without touching the provider configuration.
In practice, every lab starts the same way:
from _common.model_factory import get_chat_model
# The entire codebase adapts to your .env file automatically
model = get_chat_model(temperature=0)
response = model.invoke("Hello, LangChain!")
Switch LLM_MODEL_PROVIDER in .env from ollama to openai or anthropic and every lab — no code changes required — runs against a different provider.
▶️ Running Labs
Each lab is a self-contained Python script. To run any lab, activate your virtual environment and execute the file directly:
# Example: Run from module folder
cd 01_models
python lab_01_chat_model.py
# Exam
Truncated for display — read the full file on GitHub.
Related Skills
momen-cursurrules-prompt-file
40.6kCursor rules for building custom frontends with Momen.app as headless BaaS with GraphQL API, actionflows, AI agents, and Stripe integration.
pyspark-etl-best-practices-cursorrules-prompt-file
40.6kCursor rules for PySpark ETL development with code style, joins, window functions, map operations, and Iceberg patterns.
semiotic-react-dataviz-cursorrules-prompt-file
40.6kCursor rules for Semiotic data visualization library with 30+ chart types, MCP server, and AI-assisted chart generation.
claude-mem
91.6kPersistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
