Tutorials

Hands-on, step-by-step builds: you finish each one with working code and know why every step is there

Part1
Tutorial

How to See What apply_chat_template Sends Your Model

Render a real conversation through Qwen3's own chat template, make every newline visible, and find the exact character where a hand-built prompt goes wrong.

Part2
Tutorial

How to Validate Chat Messages Before apply_chat_template

Watch Qwen3's chat template silently drop a turn whose role is "User", then build a validator and a safe_render that refuse a malformed conversation before it reaches the model.

Part3
Tutorial

How to Render a Chat Template with Jinja Like Transformers

Rebuild the Jinja environment apply_chat_template uses, watch one missing dash add a token to every assistant turn, and prove your local render matches Qwen3 byte for byte.

Part4
Tutorial

How to Check if a Chat Template Supports a System Prompt

Build a Python probe that inspects a Hugging Face chat template without reading its Jinja: the generation prompt, and whether a system or developer message gets its own turn, on Qwen3, Llama 3 and Gemma 3.

Part5
Tutorial

How to Pass Tools to apply_chat_template and Parse the Calls

Build a Python module that sends tools and tool calls through apply_chat_template, then reads the model's calls back out: with the model's own response template when it ships one, and with a parser you choose when it does not.

Part6
Tutorial

How to Pass reasoning_content Back Through a Chat Template

Build a Python module that turns thinking on and off per model, splits a reply into reasoning and answer, stores the reasoning where the template reads it, and proves with token IDs that the next request repeats what the model saw.

Part7
Tutorial

How to Pass Images to apply_chat_template with a Processor

Build a Python module that renders image-and-text conversations through a Hugging Face processor, validates every content part, rewrites OpenAI image_url parts without touching your data, and checks that placeholders and images pair up before the model sees them.

Part8
Tutorial

How to Write a Chat Template for a Fine-Tuned Model and Test It

Write a chat template from the exact text your model was fine-tuned on, then prove it with string, token, mask, label and stop-token checks against a real TRL SFTTrainer batch.

Part9
Tutorial

How to Test a Chat Template Across Jinja Engines

Render one conversation with CPython Jinja2 and with @huggingface/jinja, find the first character where they differ, and lint a template for the constructs that do not port.

Part10
Tutorial

How to Check the Token IDs llama-server Sends the Model

Ask llama-server for the token IDs it builds from your conversation, compare them with apply_chat_template, and catch a doubled BOS token and a broken prefix cache before your users do.

Part11
Tutorial

How to Catch Chat Template Regressions with Golden-Token Tests

Record what a chat template renders and the token IDs your engine sends for a fixed set of conversations, then fail CI on any change: a whitespace edit, a misspelled switch, or a doubled BOS.

Part12
Tutorial

How to Detect Chat Template Backdoors and Forged Tokens

Pin a model's chat template by fingerprint, scan its syntax tree for backdoor shapes, and stop control tokens in user and tool content from becoming a fake turn.

Part13
Tutorial

How to Gate Chat Template Changes in CI with One Audit

Compose golden tokens, a fingerprint pin, a backdoor scan and Jinja parity into one audit and one CI exit code, so adding a model is a config entry, not a new rendering path.

All Tutorials

Tutorial

Run a PyTorch Anomaly Detector in Rust with ONNX and tract

Train a 1D convolutional autoencoder on pump sensor data, export it to ONNX, score it from a pure-Rust binary, and gate threshold changes on matured verdicts.

Tutorial

How to Cut AI Agent Cost: Prompt Caching and Model Routing

Build a Python support-ticket triage agent on the Claude API, and measure caching, structured outputs, and a Haiku-to-Sonnet cascade at about a third of Sonnet-only cost.

Tutorial

Claude Code Stop Hook with Hypothesis Property Tests

Give Claude Code a verifier: Hypothesis property tests for a RAG chunker, wired into hooks so the agent cannot stop while a property fails, or edit the properties to make them pass.

Tutorial

How to Reduce Claude Code Token Usage: A Measured Setup

Shrink what Claude Code re-reads on every turn, stop tool output from flooding the context, and prove the saving with real numbers.

Tutorial

Building ChatGPT-Style Streaming in React: FastAPI + Next.js Production Guide

Cancel-on-disconnect misses the drops that cost money, and resumable streams bill every closed tab. Bind the generation to a presence lease instead.

Tutorial

Contract Tests for a LangGraph Agent: Test the Property, Not the Setting

Build a pytest suite that checks fan-out width, merge order, spend across resumes, and spend after a crash - and watch a setting-shaped fix fail each one.

Tutorial

How to Build a Claude Code Agent Loop That Cannot Run Away

Build a loop that reruns every failing test before it touches code, fixes only the failures that reproduce, and is stopped by a hook its own instructions cannot override.

Tutorial

MCP with LangGraph: A Practical 2026 Walkthrough

Your checkpoint is durable. The handle inside it is not. Nothing in either system compares the two.

Tutorial

Build a Kill Switch for a LangGraph Agent

Four independent mechanisms - a tool-call interceptor, a watchdog, an anomaly detector, and a manual override - that stop it even when it will not stop itself.

Tutorial

How SynthID Works: Build a Watermark in Python

Build the green-list watermark on GPT-2 and detect it from text alone at p = 3.07e-56. Then find out how few tokens it needs and how much editing it survives.

Tutorial

Superpowers Plugin for Claude Code: Install and Verify

Install it, prove which skills actually fire, and measure what it costs you - then switch it off where it does not belong.

Tutorial

BM25 vs Dense Retrieval: Measure It on Your Own Corpus

Build a bake-off harness that runs BM25, dense, hybrid, and reranked retrieval over a labelled query set - and tells you with Recall@k, nDCG, and cost per query which one your RAG system actually needs.

Tutorial

How to Rerank Retrieval Results with a Cross-Encoder

Build a two-stage search pipeline and measure the reranking gain yourself, in NDCG@10, on your own machine.

Tutorial

Building a Production MCP Server: Architecture, Pitfalls, and Best Practices

The four-layer architecture that survives an adversarial LLM client, rewritten for the stateless spec.

Tutorial

Claude Code Guide: Build Agentic Workflows with Commands, MCP, and Subagents

*A practical guide to using Claude Code as a programmable agent with commands, skills, memory, hooks, and MCP.* Most developers try Claude Code once, get med...

Tutorial

Building an MCP Server for Non-LLM Clients (CLIs, IDEs, Pipelines)

## The Problem: Context Access Is Locked Behind LLM Abstractions You've built an MCP server that provides rich context from your organization's systems—code ...

Tutorial

How to Build a Hybrid Search Service with BM25 and Docker

Fuse BM25 with dense retrieval, tune the fusion weight on real relevance judgments, and ship the whole thing as a container that shows you every stage's score.

Tutorial

Building Privacy-Preserving Machine Learning Applications in Python with Homomorphic Encryption

Data privacy is one of the biggest challenges in deploying AI systems. From healthcare to finance, sensitive datasets are often required to train or run machine...

Tutorial

Provenance in AI: Building a Provenance Graph with Neo4j – Part 3

In [Part 2](https://ranjankumar.in/provenance-in-ai-tracking-ai-lineage-with-signed-provenance-logs-in-python-part-2/), we built a `ProvenanceTracker` that gene...

Tutorial

Prompt Engineering Tutorial 2026: Prove Which Prompts Work

Build promptlab, a local Python harness that measures whether a prompt change helped, then use it to reproduce the prompting effects that still hold and the four that stopped.

Tutorial

LLM Text Clustering and Topic Modeling: HDBSCAN and BERTopic Tutorial

Cluster documents by meaning with sentence-transformer embeddings, UMAP and HDBSCAN, then turn clusters into labelled topics with BERTopic and an LLM. Updated for BERTopic's client-based OpenAI API and current model IDs.

Tutorial

Hands-on Tutorial on Making an Audio Bot using LLM, and RAG

Build an offline audio bot that answers questions from your own PDFs: Llama 3.2 via Ollama, a Qdrant + FastEmbed RAG pipeline, faster-whisper speech-to-text and pyttsx3 text-to-speech. Updated for qdrant-client 1.19 and LangChain 1.x.

Tutorial

How to Fine-Tune a Cross-Encoder for Semantic Similarity

Train a distilroberta cross-encoder on STS-B with the Sentence Transformers trainer, on a plain CPU, and use it to score sentence pairs and rerank search results.

Tutorial

Install Ollama and Run Llama 3.2 Locally: Python, LangChain

Install Ollama, run Llama 3.2 on your own machine, and call it from the terminal, a browser sidebar, plain HTTP, the official Python client and LangChain - then reach it from another machine without exposing it to the internet.

Tutorial

How to Record, Save and Play Audio in Python

Build a working voice recorder in about twenty minutes, on a stack that still installs on current Python.