Agentic AI Masterclass: LangChain, LangGraph, RAG & LLM Gateways

A comprehensive 10.5-hour course covering generative AI and agentic AI fundamentals, LangChain v1 updates, LangGraph for agent building, RAG implementations (traditional, agentic, vectorless), deep research agents, LLM evaluation techniques, guardrails, and LLM gateways for production deployment.

Course Overview & Setup

Complete Course Roadmap

The course covers six major topics: generative AI and agentic AI with LangChain, LangGraph crash course for building agentic applications, traditional RAG implementation, agentic RAG, vectorless RAG with comparisons, deep research agents with practical implementation, AI security (guardrails and LLM evaluation), and LLM gateways with 30-40 minutes of implementation.

Environment Setup with UV Package Manager

UV is a fast Python package manager written in Rust. Initialize a project with 'uv init', create a virtual environment with 'uv venv', activate it, then install dependencies from requirements.txt using 'uv add -r requirements.txt'. This replaces traditional pip workflows with faster, more efficient dependency management.

Key Libraries & API Keys Required

Install langchain, langchain-community, langchain-openai, langchain-groq, python-dotenv, and langchain-google-genai. Create .env file with three API keys: OpenAI API key, Google API key, and Groq API key. These enable integration with multiple LLM providers for comparison and fallback capabilities.

Agents & Agent Architecture

What is an Agent

An agent is an autonomous system that makes decisions about which tools to use based on input. Unlike simple LLMs that only generate text, agents can reason about whether they need external information, call appropriate tools to fetch context, and generate informed responses. This enables handling of real-time data and tasks beyond the LLM's training cutoff.

Creating Agents with LangChain v1

Use 'from langchain.agents import create_agent' to instantiate agents. Provide the model name (e.g., 'gpt-4-mini'), a list of tools, and optional system prompts. Tools are functions decorated with @tool that the agent can invoke. The agent automatically determines when and which tools to call based on the input and tool descriptions.

Tool Definition & Integration

Tools are created by decorating functions with @tool from langchain.tools. Each tool requires a docstring describing its functionality—this docstring is critical as the LLM uses it to understand when to invoke the tool. Tools can be simple functions returning strings or complex functions making API calls. Bind tools to models using model.bind_tools() or pass them to create_agent().

Model Integration & Streaming

Multi-Provider Model Integration

LangChain supports seamless integration with OpenAI, Google Gemini, Groq, and other providers. Use init_chat_model() for a unified interface, or provider-specific classes like ChatOpenAI, ChatGoogleGenerativeAI, ChatGroq. Simply change the model name string to switch providers without code changes. All models support the same invoke() interface.

Streaming vs Batch Processing

Streaming outputs tokens as they are generated using model.stream(), improving user experience for long responses by showing progressive output. Batch processing sends multiple independent requests in parallel using model.batch(), improving throughput and reducing cost. Use max_concurrency parameter to control parallel request limits.

Cost Tracking & Token Usage

Models return usage metadata including input_tokens, output_tokens, and total_tokens. This allows tracking API costs per request. For batch operations, sum token counts across all requests. Understanding token usage is critical for budgeting and optimizing prompt design.

Message Types & Conversation Structure

Four Message Types in LangChain

SystemMessage provides instructions on how the LLM should behave. HumanMessage represents user input. AIMessage is the LLM's response. ToolMessage contains output from tool execution. These can be combined in a list to maintain conversation history and context, enabling multi-turn interactions.

Detailed System Prompts Improve Output Quality

Generic system messages like 'you are a helpful assistant' produce generic responses. Detailed system prompts specifying domain expertise, output format, constraints, and reasoning style significantly improve response quality. For example, 'You are a senior Python developer with expertise in web frameworks. Always provide code examples and explain your reasoning' produces more targeted, practical responses.

Structured Output & Pydantic

Structured Output with Pydantic Models

Use Pydantic BaseModel to define output schemas with field validation. Decorate fields with Field() to add descriptions and constraints. Bind schema to model using model.with_structured_output(). The LLM then generates responses matching the schema exactly, enabling reliable downstream processing. Pydantic validates types automatically.

Field Validation & Type Safety

Pydantic enforces type validation—if a field expects int but receives string, validation fails. Field descriptions guide the LLM on what to generate. This ensures output is always in the expected format, eliminating parsing errors and enabling reliable automation.

RAG: Retrieval-Augmented Generation

RAG Architecture & Components

RAG combines retrieval and generation: documents are loaded, split into chunks, embedded into vectors, stored in a vector database, and retrieved based on query similarity. Retrieved documents are passed as context to the LLM, which generates answers grounded in the documents. This solves the problem of LLMs having outdated training data.

Traditional RAG vs Agentic RAG vs Vectorless RAG

Traditional RAG retrieves documents once and passes them to the LLM. Agentic RAG uses agents to iteratively refine queries and retrieve multiple times. Vectorless RAG uses keyword matching or other non-embedding methods. Each has tradeoffs in accuracy, cost, and latency.

Creating Test Datasets for RAG Evaluation

Create question-answer pairs representing expected behavior. Store in LangSmith as datasets. These serve as ground truth for evaluating RAG performance. Each example should have a question and reference answer.

LLM Evaluation & Metrics

LLM as Judge for Evaluation

Use a powerful LLM to evaluate outputs from another LLM by comparing against reference answers or criteria. Define evaluation metrics as functions that take input, output, and reference output, then return a score. This is more scalable than manual evaluation and captures nuanced quality aspects.

Four Key RAG Evaluation Metrics

Correctness: does answer match ground truth? Relevance: does answer address the question? Groundedness: is answer supported by retrieved documents? Retrieval Relevance: are retrieved documents relevant to query? These four metrics comprehensively assess RAG quality.

Running Evaluations in LangSmith

Use client.evaluate() to run metrics against a dataset. Specify target function, dataset, and evaluators. LangSmith runs all evaluations and displays results with per-example scores and aggregated metrics. This enables comparing different models or configurations.

LLM Gateways & Production Patterns

What is an LLM Gateway

An LLM gateway is a smart middleware between applications and LLM providers. It provides unified API for multiple providers, automatic fallbacks if one provider fails, intelligent routing based on task type, caching for repeated queries, cost tracking, rate limiting, and security guardrails. This eliminates direct API integration complexity.

Core LLM Gateway Capabilities

Unified API: one function call across 100+ providers. Automatic fallbacks: switch providers if one fails. Smart routing: send different tasks to optimal providers. Load balancing: distribute requests across multiple API keys. Caching: reuse responses for identical queries. Observability: log all calls with cost and latency. Guardrails: block sensitive data before reaching LLM. Evals: integrate evaluation frameworks.

Caching Dramatically Reduces Costs

When identical queries are cached, subsequent requests return cached responses instantly without calling the LLM. This reduces latency from ~1.5 seconds to ~0.002 seconds (700x faster) and eliminates API costs entirely for cached queries. Caching can reduce overall costs by 40-60% for typical applications.

Smart Routing by Task Type

Define routing rules mapping task types to optimal models. For coding tasks, route to GPT-4. For summarization, route to GPT-4-mini (cheaper). For speed, route to Groq Llama. The gateway classifies incoming queries and automatically routes to the best model, optimizing cost and performance.

Guardrails: Blocking Sensitive Data

Define regex patterns for sensitive data (emails, phone numbers, SSNs, credit cards, PII). Before sending prompts to LLM, scan for patterns and redact matching data. This prevents sensitive information from reaching external LLM providers, maintaining privacy and compliance.

Automatic Fallbacks Prevent Outages

Configure primary and backup LLM providers. If primary fails, gateway automatically tries backup. This prevents application outages when a provider has issues. For example, if OpenAI is down, automatically use Groq or Claude. No code changes needed.

Real-World Outage: November 2023 OpenAI Incident

OpenAI experienced a 4-hour outage on November 8, 2023. Applications hardcoded to use OpenAI (like Cursor, Notion AI) went completely offline. With an LLM gateway and fallbacks, these applications would have automatically switched to alternative providers and remained operational.

LightLLM Implementation

LightLLM: Open-Source LLM Gateway

LightLLM is an open-source Python library providing unified API for 100+ LLM providers. Use 'from litellm import completion' to call any model by changing the model name string. Supports automatic fallbacks, caching, cost tracking, and guardrails with minimal code.

Unified Completion API Across Providers

Single completion() function works with all providers. Change model name from 'gpt-4-mini' to 'groq/llama-3.3-70b-versatile' to 'claude-opus' without changing code. Each provider uses its own API key from environment variables.

Cost Tracking with LightLLM

Use completion_cost() to get cost of each API call. Returns input tokens, output tokens, and total cost in dollars. Aggregate across requests to track total spending by model, user, or project.

Router for Task-Based Model Selection

Define routing rules mapping task types to model lists with fallbacks. Router automatically classifies queries and selects appropriate model. Supports strategies like 'simple_shuffle' (round-robin), 'least_busy' (load balancing), and 'latency_based' (fastest provider).

Notable quotes

Agents autonomously make decisions about which tools to call based on input. — Krish Naik
LLM gateways eliminate direct API integration complexity with unified middleware. — Krish Naik
Caching reduces latency 700x and eliminates costs for repeated queries. — Krish Naik

Action items

  • Install UV package manager and set up virtual environment with 'uv init' and 'uv venv'
  • Create .env file with OpenAI, Google, and Groq API keys
  • Build your first agent using create_agent() with at least one custom tool
  • Implement streaming with model.stream() to show progressive token output
  • Create a Pydantic model for structured output and bind it to an LLM
  • Build a RAG pipeline: load documents, create embeddings, set up retriever
  • Create evaluation metrics using LLM-as-judge and run in LangSmith
  • Implement an LLM gateway with LightLLM including fallbacks and caching
  • Add PII guardrails to block sensitive data before reaching LLM
  • Set up smart routing to send different task types to optimal models
Krish Naik
11 hr 13 min video
4 min read
Agentic AI Masterclass: LangChain, LangGraph, RAG & LLM Gateways
You just saved 11 hr 9 min.
The big takeaway
A comprehensive 10.5-hour course covering generative AI and agentic AI fundamentals, LangChain v1 updates, LangGraph for agent building, RAG implementations (traditional, agentic, vectorless), deep research agents, LLM evaluation techniques, guardrails, and LLM gateways for production deployment.
Course Overview & Setup
Complete Course Roadmap
The course covers six major topics: generative AI and agentic AI with LangChain, LangGraph crash course for building agentic applications, traditional RAG implementation, agentic RAG, vectorless RAG with comparisons, deep research agents with practical implementation, AI security (guardrails and LLM evaluation), and LLM gateways with 30-40 minutes of implementation.
0:00
Generative AI & Agentic AI with LangChain
~2h
LangGraph crash course
~4h
Traditional RAG implementation
~6h
Agentic RAG & vectorless RAG
~8h
Deep research agents
~9h
Guardrails & LLM evaluation
~10h
LLM gateways implementation
Course structure spanning 10.5 hours of content
Environment Setup with UV Package Manager
UV is a fast Python package manager written in Rust. Initialize a project with 'uv init', create a virtual environment with 'uv venv', activate it, then install dependencies from requirements.txt using 'uv add -r requirements.txt'. This replaces traditional pip workflows with faster, more efficient dependency management.
1
Run 'uv init' to initialize project
2
Run 'uv venv' to create virtual environment
3
Activate venv with provided script
4
Create requirements.txt with library names
5
Run 'uv add -r requirements.txt' to install all dependencies
6
Check pyproject.toml for installed versions
UV package manager setup workflow
Key Libraries & API Keys Required
Install langchain, langchain-community, langchain-openai, langchain-groq, python-dotenv, and langchain-google-genai. Create .env file with three API keys: OpenAI API key, Google API key, and Groq API key. These enable integration with multiple LLM providers for comparison and fallback capabilities.
1
langchain
v1.1.0
2
langchain-community
v0.4.1
3
langchain-openai
latest
4
langchain-groq
latest
5
python-dotenv
required
Core libraries for agentic AI development
Agents & Agent Architecture
What is an Agent
An agent is an autonomous system that makes decisions about which tools to use based on input. Unlike simple LLMs that only generate text, agents can reason about whether they need external information, call appropriate tools to fetch context, and generate informed responses. This enables handling of real-time data and tasks beyond the LLM's training cutoff.
1
User provides input query
2
Agent evaluates if it needs external information
3
Agent selects and calls appropriate tool
4
Tool returns context/data
5
Agent generates response using context
Agent decision-making workflow
Creating Agents with LangChain v1
Use 'from langchain.agents import create_agent' to instantiate agents. Provide the model name (e.g., 'gpt-4-mini'), a list of tools, and optional system prompts. Tools are functions decorated with @tool that the agent can invoke. The agent automatically determines when and which tools to call based on the input and tool descriptions.
Tool Definition & Integration
Tools are created by decorating functions with @tool from langchain.tools. Each tool requires a docstring describing its functionality—this docstring is critical as the LLM uses it to understand when to invoke the tool. Tools can be simple functions returning strings or complex functions making API calls. Bind tools to models using model.bind_tools() or pass them to create_agent().
1
Import @tool decorator from langchain.tools
2
Define function with clear docstring
3
Decorate function with @tool
4
Bind tool to model or pass to create_agent
5
Agent automatically selects tool when needed
Tool creation and integration process
Model Integration & Streaming
Multi-Provider Model Integration
LangChain supports seamless integration with OpenAI, Google Gemini, Groq, and other providers. Use init_chat_model() for a unified interface, or provider-specific classes like ChatOpenAI, ChatGoogleGenerativeAI, ChatGroq. Simply change the model name string to switch providers without code changes. All models support the same invoke() interface.
Streaming vs Batch Processing
Streaming outputs tokens as they are generated using model.stream(), improving user experience for long responses by showing progressive output. Batch processing sends multiple independent requests in parallel using model.batch(), improving throughput and reducing cost. Use max_concurrency parameter to control parallel request limits.
Invoke (blocking)
Wait for full response
Stream (progressive)
Show tokens as generated
Streaming improves perceived latency
Cost Tracking & Token Usage
Models return usage metadata including input_tokens, output_tokens, and total_tokens. This allows tracking API costs per request. For batch operations, sum token counts across all requests. Understanding token usage is critical for budgeting and optimizing prompt design.
Message Types & Conversation Structure
Four Message Types in LangChain
SystemMessage provides instructions on how the LLM should behave. HumanMessage represents user input. AIMessage is the LLM's response. ToolMessage contains output from tool execution. These can be combined in a list to maintain conversation history and context, enabling multi-turn interactions.
1
SystemMessage
Instructions for LLM behavior
2
HumanMessage
User input
3
AIMessage
LLM response
4
ToolMessage
Tool execution output
Message types in conversation flow
Detailed System Prompts Improve Output Quality
Generic system messages like 'you are a helpful assistant' produce generic responses. Detailed system prompts specifying domain expertise, output format, constraints, and reasoning style significantly improve response quality. For example, 'You are a senior Python developer with expertise in web frameworks. Always provide code examples and explain your reasoning' produces more targeted, practical responses.
Structured Output & Pydantic
Structured Output with Pydantic Models
Use Pydantic BaseModel to define output schemas with field validation. Decorate fields with Field() to add descriptions and constraints. Bind schema to model using model.with_structured_output(). The LLM then generates responses matching the schema exactly, enabling reliable downstream processing. Pydantic validates types automatically.
1
Define Pydantic BaseModel class with fields
2
Add Field() descriptions for each field
3
Use model.with_structured_output(schema)
4
LLM generates output matching schema
5
Pydantic validates types and constraints
Structured output workflow with Pydantic
Field Validation & Type Safety
Pydantic enforces type validation—if a field expects int but receives string, validation fails. Field descriptions guide the LLM on what to generate. This ensures output is always in the expected format, eliminating parsing errors and enabling reliable automation.
RAG: Retrieval-Augmented Generation
RAG Architecture & Components
RAG combines retrieval and generation: documents are loaded, split into chunks, embedded into vectors, stored in a vector database, and retrieved based on query similarity. Retrieved documents are passed as context to the LLM, which generates answers grounded in the documents. This solves the problem of LLMs having outdated training data.
1
Load documents from URLs or files
2
Split documents into chunks
3
Generate embeddings for chunks
4
Store embeddings in vector database
5
Retrieve relevant chunks for query
6
Pass chunks as context to LLM
7
LLM generates grounded response
Complete RAG pipeline
Traditional RAG vs Agentic RAG vs Vectorless RAG
Traditional RAG retrieves documents once and passes them to the LLM. Agentic RAG uses agents to iteratively refine queries and retrieve multiple times. Vectorless RAG uses keyword matching or other non-embedding methods. Each has tradeoffs in accuracy, cost, and latency.
Creating Test Datasets for RAG Evaluation
Create question-answer pairs representing expected behavior. Store in LangSmith as datasets. These serve as ground truth for evaluating RAG performance. Each example should have a question and reference answer.
LLM Evaluation & Metrics
LLM as Judge for Evaluation
Use a powerful LLM to evaluate outputs from another LLM by comparing against reference answers or criteria. Define evaluation metrics as functions that take input, output, and reference output, then return a score. This is more scalable than manual evaluation and captures nuanced quality aspects.
1
Define evaluation criteria
2
Create evaluation function using LLM
3
Pass input, output, reference to evaluator
4
LLM judges quality and returns score
5
Aggregate scores across test set
LLM-as-judge evaluation workflow
Four Key RAG Evaluation Metrics
Correctness: does answer match ground truth? Relevance: does answer address the question? Groundedness: is answer supported by retrieved documents? Retrieval Relevance: are retrieved documents relevant to query? These four metrics comprehensively assess RAG quality.
1
Correctness
Response vs reference answer
2
Relevance
Response addresses question
3
Groundedness
Response supported by documents
4
Retrieval Relevance
Documents match query
Four dimensions of RAG quality
Running Evaluations in LangSmith
Use client.evaluate() to run metrics against a dataset. Specify target function, dataset, and evaluators. LangSmith runs all evaluations and displays results with per-example scores and aggregated metrics. This enables comparing different models or configurations.
LLM Gateways & Production Patterns
What is an LLM Gateway
An LLM gateway is a smart middleware between applications and LLM providers. It provides unified API for multiple providers, automatic fallbacks if one provider fails, intelligent routing based on task type, caching for repeated queries, cost tracking, rate limiting, and security guardrails. This eliminates direct API integration complexity.
1
Application sends request to gateway
2
Gateway routes to appropriate provider
3
Gateway checks cache for similar queries
4
If cache miss, calls LLM provider
5
Gateway logs cost, latency, tokens
6
Gateway returns response to application
LLM gateway request flow
Core LLM Gateway Capabilities
Unified API: one function call across 100+ providers. Automatic fallbacks: switch providers if one fails. Smart routing: send different tasks to optimal providers. Load balancing: distribute requests across multiple API keys. Caching: reuse responses for identical queries. Observability: log all calls with cost and latency. Guardrails: block sensitive data before reaching LLM. Evals: integrate evaluation frameworks.
Caching Dramatically Reduces Costs
When identical queries are cached, subsequent requests return cached responses instantly without calling the LLM. This reduces latency from ~1.5 seconds to ~0.002 seconds (700x faster) and eliminates API costs entirely for cached queries. Caching can reduce overall costs by 40-60% for typical applications.
First request (no cache)
1.45 seconds, full cost
Cached request
0.002 seconds, zero cost
Caching impact on latency and cost
Smart Routing by Task Type
Define routing rules mapping task types to optimal models. For coding tasks, route to GPT-4. For summarization, route to GPT-4-mini (cheaper). For speed, route to Groq Llama. The gateway classifies incoming queries and automatically routes to the best model, optimizing cost and performance.
1
Coding
GPT-4 (best quality)
2
Summarization
GPT-4-mini (cheap)
3
Speed-critical
Groq Llama (fastest)
4
Complex reasoning
Claude Opus
Task-based routing strategy
Guardrails: Blocking Sensitive Data
Define regex patterns for sensitive data (emails, phone numbers, SSNs, credit cards, PII). Before sending prompts to LLM, scan for patterns and redact matching data. This prevents sensitive information from reaching external LLM providers, maintaining privacy and compliance.
1
Define PII patterns (email, phone, SSN, etc)
2
Scan user input for pattern matches
3
Redact matching data with placeholder
4
Send sanitized input to LLM
5
Log what was redacted for audit
PII guardrail workflow
Automatic Fallbacks Prevent Outages
Configure primary and backup LLM providers. If primary fails, gateway automatically tries backup. This prevents application outages when a provider has issues. For example, if OpenAI is down, automatically use Groq or Claude. No code changes needed.
1
Primary
GPT-4
2
Fallback 1
Claude Opus
3
Fallback 2
Groq Llama
Fallback provider hierarchy
Real-World Outage: November 2023 OpenAI Incident
OpenAI experienced a 4-hour outage on November 8, 2023. Applications hardcoded to use OpenAI (like Cursor, Notion AI) went completely offline. With an LLM gateway and fallbacks, these applications would have automatically switched to alternative providers and remained operational.
4 hours
OpenAI outage duration (Nov 8, 2023)
Real production incident demonstrating need for fallbacks
LightLLM Implementation
LightLLM: Open-Source LLM Gateway
LightLLM is an open-source Python library providing unified API for 100+ LLM providers. Use 'from litellm import completion' to call any model by changing the model name string. Supports automatic fallbacks, caching, cost tracking, and guardrails with minimal code.
Unified Completion API Across Providers
Single completion() function works with all providers. Change model name from 'gpt-4-mini' to 'groq/llama-3.3-70b-versatile' to 'claude-opus' without changing code. Each provider uses its own API key from environment variables.
Cost Tracking with LightLLM
Use completion_cost() to get cost of each API call. Returns input tokens, output tokens, and total cost in dollars. Aggregate across requests to track total spending by model, user, or project.
Router for Task-Based Model Selection
Define routing rules mapping task types to model lists with fallbacks. Router automatically classifies queries and selects appropriate model. Supports strategies like 'simple_shuffle' (round-robin), 'least_busy' (load balancing), and 'latency_based' (fastest provider).
Worth quoting
"Agents autonomously make decisions about which tools to call based on input."
— Krish Naik, at [26:54]
"LLM gateways eliminate direct API integration complexity with unified middleware."
— Krish Naik, at [630:29]
"Caching reduces latency 700x and eliminates costs for repeated queries."
— Krish Naik, at [655:33]
Try this
Install UV package manager and set up virtual environment with 'uv init' and 'uv venv'
Create .env file with OpenAI, Google, and Groq API keys
Build your first agent using create_agent() with at least one custom tool
Implement streaming with model.stream() to show progressive token output
Create a Pydantic model for structured output and bind it to an LLM
Build a RAG pipeline: load documents, create embeddings, set up retriever
Create evaluation metrics using LLM-as-judge and run in LangSmith
Implement an LLM gateway with LightLLM including fallbacks and caching
Add PII guardrails to block sensitive data before reaching LLM
Set up smart routing to send different task types to optimal models
Made with Glimpse by Wozart
glimpse.wozart.com/v/xf9sdoou
Share this infographic

More like this