15. RAG Inventory Planning Agent#
A fast, conceptual revision guide for 15-rag-inventory-agent. Traces how a production-style Inventory Planning Agent is built incrementally across 8 progressive steps — from SQLite relational storage, local embeddings, and ChromaDB retrieval to LCEL chains, RAG, tool-calling agent loops, deterministic pipelines, and a Gradio chat app.
Inventory Planning Domain & Core Formulas#
Revision Notes#
Reference files: 1_GIVE_FIRST_Exercise_Questions.html, 2_SHARE_AFTER_Solution_Explainer.html
Concept#
Think of a quick-commerce dark store (the warehouse behind a 10-minute delivery app). Running out of fast-selling items loses sales immediately, while overstocking ties up cash, shelf space, and risks expiry or obsolescence. Every step in this module exists to answer one core business question reliably: "Should I reorder this SKU right now, and how many units?"
Key Mental Models#
- One sentence to remember: Order enough to cover the days you wait for delivery, plus a buffer for unpredictable demand spikes, minus what you already have on the shelf.
- Core domain terms:
- SKU (Stock Keeping Unit): Unique identifier for one product (e.g.,
SKU-005, Laptop 15-inch). - Current stock: Units physically on the shelf right now.
- Lead time: Days between placing a supplier order and receiving the delivery.
- Average daily demand & demand std dev: Mean units sold per day and how wildly daily sales fluctuate around that mean.
- Service level & Z-score: Target probability of not stocking out during lead time, mapped to a standard normal Z-score (
90% -> 1.28,95% -> 1.65,97% -> 1.88,98% -> 2.05,99% -> 2.33).
- SKU (Stock Keeping Unit): Unique identifier for one product (e.g.,
- The three exact formulas:
- Safety Stock (buffer for demand spikes):
Z × demand_std_dev × √lead_time_days. - Desired Stock / Reorder Point (ROP):
(avg_daily_demand × lead_time_days) + safety_stock. - Reorder Quantity:
max(0, ceil(desired_stock - current_stock))— rounded up withmath.ceilbecause you cannot order fractional units and rounding down leaves you short of your service level.
- Safety Stock (buffer for demand spikes):
- Why domain rules matter alongside formulas: Raising service level from 95% to 99% increases safety stock by roughly 40% (
Zjumps from1.65to2.33). Categories also have distinct operational rules — Pharma demands 99%+ service levels, strict FIFO, and expiry tracking; Electronics carry high obsolescence risk and 14–30 day lead times; FMCG has short 3–7 day lead times and steady demand.
Structured Data Storage with SQLite#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/01_sqlite_basics.py, 2_SHARE_AFTER_Solution_Code/01_sqlite_basics.py (runs offline)
Concept#
Operational facts — exact stock counts, supplier names, lead times, and demand statistics — belong in a relational SQL database, not in an LLM prompt or a vector store. SQLite ships built into Python and lets you model normalized tables linked by keys (FOREIGN KEY (sku_id)) and retrieve exact records with JOIN queries.
Key Mental Models#
- Normalized tables +
JOIN: Keepingproductsandsuppliers(and laterinventory,lead_time, anddemandin Steps 07–08) in separate tables avoids duplicating supplier metadata whileJOIN ... ON s.sku_id = p.sku_idreassembles a complete SKU view on demand. - In-memory prototyping (
:memory:): Creating a RAM-only SQLite database lets exercises run cleanly and reproducibly with zero file cleanup, while using the exact same SQL as a disk-backed database. - Ergonomic & safe query patterns:
conn.row_factory = sqlite3.Rowallows accessing columns by name (row["sku_name"]) and converting results directly into Python dictionaries (dict(row)).- Parameterized queries (
?placeholders) prevent SQL injection and handle quoting safely. - Case-insensitive matching (
WHERE UPPER(p.sku_id) = UPPER(?)) ensures user inputs like"sku-002"resolve cleanly, while missing SKUs returnNoneinstead of crashing.
Trade-Offs & Pitfalls#
- SQL vs. Vector Search: SQL gives 100% deterministic, exact lookups on structured numeric fields; vector search is for unstructured text and fuzzy meaning. Mixing them up (e.g., putting live stock counts into embeddings) leads to stale, imprecise answers.
- Common SQL errors: Mismatched column names or table aliases (
p.vs.s.) raisesqlite3.OperationalError: no such column.
Code Reference#
import sqlite3
# ":memory:" = a temporary database that lives in RAM and disappears when the script ends
# Great for reproducible exercises and unit tests without leaving .db files on disk.
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row # lets us read columns by name: row["sku_name"] instead of positional index
cur = conn.cursor() # the "pen" we use to run SQL
# 1) Create two normalized tables linked by sku_id (a FOREIGN KEY).
# Separating product inventory from supplier lead times mirrors real ERP schemas.
cur.executescript("""
CREATE TABLE products (
sku_id TEXT PRIMARY KEY,
sku_name TEXT NOT NULL,
stock INTEGER NOT NULL
);
CREATE TABLE suppliers (
sku_id TEXT PRIMARY KEY,
supplier_name TEXT NOT NULL,
lead_time_days INTEGER NOT NULL, -- days between placing an order and receiving it
FOREIGN KEY (sku_id) REFERENCES products(sku_id)
);
""")
# 2) Insert rows. executemany runs the same INSERT once per tuple.
# Using "?" placeholders (parameterized queries) prevents SQL injection and handles quoting safely.
cur.executemany("INSERT INTO products VALUES (?, ?, ?)", [
("SKU-001", "Wireless Headphones", 150),
("SKU-002", "Paracetamol 500mg", 800),
("SKU-003", "Instant Noodles", 300),
])
cur.executemany("INSERT INTO suppliers VALUES (?, ?, ?)", [
("SKU-001", "TechImports Ltd", 21),
("SKU-002", "MedSupply Co", 7),
("SKU-003", "FoodDist Pvt", 4),
])
conn.commit()
# 3) Read both tables together with a JOIN
# ----- TODO 1: Write a JOIN query that returns sku_id, sku_name, stock, lead_time_days, supplier_name for every product -----
# Hint: SELECT p.sku_id, p.sku_name, p.stock, s.lead_time_days, s.supplier_name
# Hint: FROM products p JOIN suppliers s ON s.sku_id = p.sku_id ORDER BY p.sku_id
# Hint: cur.execute(sql).fetchall() returns all rows
rows = [] # replace with your code
print(f"{'SKU':<10} {'Name':<22} {'Stock':>6} {'Lead (days)':>12} Supplier")
print("-" * 70)
for r in rows:
print(f"{r['sku_id']:<10} {r['sku_name']:<22} {r['stock']:>6} {r['lead_time_days']:>12} {r['supplier_name']}")
# 4) A reusable lookup function: one SKU in, one dict out (or None).
# Returning plain Python dicts makes the data directly JSON-serializable for LLM tool responses.
def fetch_product(sku_id: str) -> dict | None:
# ----- TODO 2: Fetch ONE product (joined with its supplier) by sku_id; return it as a dict, or None if not found -----
# Hint: Same JOIN as above + WHERE UPPER(p.sku_id) = UPPER(?) (so "sku-002" also works)
# Hint: cur.execute(sql, (sku_id,)).fetchone() returns one row or None
# Hint: dict(row) turns a Row into a normal dict
return None # replace with your code
# ... (see full file: 01_sqlite_basics.py)
$ python 1_GIVE_FIRST_Starter_Code/01_sqlite_basics.py
# Before completing TODOs 1-2:
SKU Name Stock Lead (days) Supplier
----------------------------------------------------------------------
(no rows — fill in TODO 1)
fetch_product('sku-002') -> None
fetch_product('SKU-999') -> None
import sqlite3
# ":memory:" = a temporary database that lives in RAM and disappears when the script ends.
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row # lets us read columns by name: row["sku_name"] and convert via dict(row)
cur = conn.cursor() # the "pen" we use to run SQL
# 1) Create two normalized tables linked by sku_id (a FOREIGN KEY).
cur.executescript("""
CREATE TABLE products (
sku_id TEXT PRIMARY KEY,
sku_name TEXT NOT NULL,
stock INTEGER NOT NULL
);
CREATE TABLE suppliers (
sku_id TEXT PRIMARY KEY,
supplier_name TEXT NOT NULL,
lead_time_days INTEGER NOT NULL, -- days between placing an order and receiving it
FOREIGN KEY (sku_id) REFERENCES products(sku_id)
);
""")
# 2) Insert rows. executemany runs the same INSERT once per tuple. "?" = safe parameterized placeholder.
cur.executemany("INSERT INTO products VALUES (?, ?, ?)", [
("SKU-001", "Wireless Headphones", 150),
("SKU-002", "Paracetamol 500mg", 800),
("SKU-003", "Instant Noodles", 300),
])
cur.executemany("INSERT INTO suppliers VALUES (?, ?, ?)", [
("SKU-001", "TechImports Ltd", 21),
("SKU-002", "MedSupply Co", 7),
("SKU-003", "FoodDist Pvt", 4),
])
conn.commit()
# 3) Read both tables together with an INNER JOIN on sku_id.
# ----- TODO 1 (solved): Write a JOIN query that returns sku_id, sku_name, stock, lead_time_days, supplier_name for every product -----
rows = cur.execute("""
SELECT p.sku_id, p.sku_name, p.stock,
s.lead_time_days, s.supplier_name
FROM products p
JOIN suppliers s ON s.sku_id = p.sku_id
ORDER BY p.sku_id
""").fetchall()
# -> [
# {'sku_id': 'SKU-001', 'sku_name': 'Wireless Headphones', 'stock': 150,
# 'lead_time_days': 21, 'supplier_name': 'TechImports Ltd'},
# {'sku_id': 'SKU-002', 'sku_name': 'Paracetamol 500mg', 'stock': 800,
# 'lead_time_days': 7, 'supplier_name': 'MedSupply Co'},
# {'sku_id': 'SKU-003', 'sku_name': 'Instant Noodles', 'stock': 300,
# 'lead_time_days': 4, 'supplier_name': 'FoodDist Pvt'},
# ] (sqlite3.Row objects accessible by column name)
print(f"{'SKU':<10} {'Name':<22} {'Stock':>6} {'Lead (days)':>12} Supplier")
print("-" * 70)
for r in rows:
print(f"{r['sku_id']:<10} {r['sku_name']:<22} {r['stock']:>6} {r['lead_time_days']:>12} {r['supplier_name']}")
# 4) A reusable lookup function: one SKU in, one dict out (or None).
# Case-insensitive matching via UPPER() ensures agent calls like "sku-002" still match.
def fetch_product(sku_id: str) -> dict | None:
# ----- TODO 2 (solved): Fetch ONE product (joined with its supplier) by sku_id; return it as a dict, or None if not found -----
row = cur.execute(
"SELECT p.*, s.lead_time_days, s.supplier_name "
"FROM products p JOIN suppliers s ON s.sku_id = p.sku_id "
# ... (see full file: 01_sqlite_basics.py)
$ python 2_SHARE_AFTER_Solution_Code/01_sqlite_basics.py
SKU Name Stock Lead (days) Supplier
----------------------------------------------------------------------
SKU-001 Wireless Headphones 150 21 TechImports Ltd
SKU-002 Paracetamol 500mg 800 7 MedSupply Co
SKU-003 Instant Noodles 300 4 FoodDist Pvt
fetch_product('sku-002') -> {'sku_id': 'SKU-002', 'sku_name': 'Paracetamol 500mg', 'stock': 800, 'lead_time_days': 7, 'supplier_name': 'MedSupply Co'}
fetch_product('SKU-999') -> None
Semantic Search from Scratch with Embeddings#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/02_embeddings_basics.py, 2_SHARE_AFTER_Solution_Code/02_embeddings_basics.py (runs offline)
Concept#
Keyword search fails when a user asks about "consumer goods" and your note says "FMCG". Embeddings convert text into dense numeric vectors where semantically similar sentences land close together in vector space. Before introducing any vector database, this step shows that semantic retrieval is fundamentally just an embedding model + a dot product + sorting.
How It Works#
Key Mental Models#
- Local, zero-cost embeddings:
SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")maps every passage and query to a 384-dimensional vector completely offline on CPU. - Unit normalization turns cosine similarity into a dot product: Passing
normalize_embeddings=Truescales every vector to length 1. Once normalized, cosine similarity equals the dot product (passage_vectors @ qv), allowing NumPy to score all passages in a single matrix-vector multiplication and rank them withnp.argsort(scores)[::-1][:k].
Trade-Offs & Pitfalls#
- Why NumPy alone doesn't scale: Brute-force matrix multiplication over 6 passages is instant, but real knowledge bases need persistence, incremental inserts, approximate nearest-neighbor indexing (HNSW), and metadata filtering — which motivates moving to ChromaDB in Step 03.
Code Reference#
"""
Step 02 — Embeddings basics: find the most relevant passage for a question
Created by Shivank Agarwal
Goal: turn short inventory notes into vectors and find the best ones for a question.
No database and no LLM yet: just an embedding model + numpy.
Run it:
python 02_embeddings_basics.py
"""
import numpy as np
from sentence_transformers import SentenceTransformer
# Our tiny "knowledge base": six domain-specific facts about inventory planning
PASSAGES = [
"Safety Stock = Z-score * demand_std_dev * sqrt(lead_time_days)",
"Reorder Point = (avg_daily_demand * lead_time_days) + safety_stock",
"Electronics: lead times 14-30 days, high obsolescence risk.",
"Pharma: strict FIFO, 99%+ service level, expiry management.",
"FMCG: short lead times 3-7 days, high steady demand.",
"ABC Analysis: A-items need tight control, C-items tolerate bulk orders.",
]
# Free local bi-encoder: maps any text into a 384-dimensional semantic vector
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
print("Embedding passages...")
# normalize_embeddings=True scales every vector to unit L2 norm (|v| = 1),
# so cosine similarity simplifies to a fast matrix-vector dot product (passage_vectors @ qv).
passage_vectors = model.encode(PASSAGES, normalize_embeddings=True)
print(f"Passage matrix shape: {passage_vectors.shape} (6 passages x 384 numbers)\n")
def top_k(query: str, k: int = 3) -> list[tuple[float, str]]:
"""Return the k passages most similar to the query as (score, passage), best first."""
# ----- TODO 1: Embed the query, score it against every passage, and return the top k -----
# Hint: qv = model.encode(query, normalize_embeddings=True)
# Hint: scores = passage_vectors @ qv (the @ operator = dot product for every row at once)
# Hint: np.argsort(scores)[::-1][:k] = indexes of the k highest scores
return [] # replace with your code
queries = [
"How do I calculate safety stock?",
"What should I know about electronics inventory?",
"Tell me about demand patterns for consumer goods.",
]
for query in queries:
print(f"Query: {query!r}")
for score, passage in top_k(query):
print(f" {score:.3f} {passage}")
print()
$ python 1_GIVE_FIRST_Starter_Code/02_embeddings_basics.py
Embedding passages...
Passage matrix shape: (6, 384) (6 passages x 384 numbers)
Query: 'How do I calculate safety stock?'
Query: 'What should I know about electronics inventory?'
Query: 'Tell me about demand patterns for consumer goods.'
# (top_k returns [] until TODO 1 is implemented)
"""
Step 02 — Embeddings basics: find the most relevant passage for a question
Created by Shivank Agarwal
Goal: turn short inventory notes into vectors and find the best ones for a question.
No database and no LLM yet: just an embedding model + numpy.
Run it:
python 02_embeddings_basics.py
"""
import numpy as np
from sentence_transformers import SentenceTransformer
# Our tiny "knowledge base": six domain-specific facts about inventory planning
PASSAGES = [
"Safety Stock = Z-score * demand_std_dev * sqrt(lead_time_days)",
"Reorder Point = (avg_daily_demand * lead_time_days) + safety_stock",
"Electronics: lead times 14-30 days, high obsolescence risk.",
"Pharma: strict FIFO, 99%+ service level, expiry management.",
"FMCG: short lead times 3-7 days, high steady demand.",
"ABC Analysis: A-items need tight control, C-items tolerate bulk orders.",
]
# Free local bi-encoder: every text -> 384 numbers
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
print("Embedding passages...")
# normalize_embeddings=True scales every vector to unit length (L2 norm = 1),
# so cosine similarity equals the dot product without needing to divide by norms.
passage_vectors = model.encode(PASSAGES, normalize_embeddings=True)
# -> ndarray shape (6, 384), float32, each row unit-normalized (L2 norm = 1.0)
print(f"Passage matrix shape: {passage_vectors.shape} (6 passages x 384 numbers)\n")
def top_k(query: str, k: int = 3) -> list[tuple[float, str]]:
"""Return the k passages most similar to the query as (score, passage), best first."""
# ----- TODO 1 (solved): Embed the query, score it against every passage, and return the top k -----
qv = model.encode(query, normalize_embeddings=True)
# Vectorized matrix-vector multiplication scores all passages in one BLAS call
scores = passage_vectors @ qv # one score per passage
# -> array([0.718, 0.542, 0.141, 0.128, 0.109, 0.264]) (for 'How do I calculate safety stock?')
# np.argsort sorts ascending; [::-1] reverses to descending and [:k] takes the top-k indices
ranked = np.argsort(scores)[::-1][:k] # biggest first
# -> array([0, 1, 5]) (top-3 passage indices in descending score order)
return [(float(scores[i]), PASSAGES[i]) for i in ranked]
# -> [(0.718, 'Safety Stock = Z-score * demand_std_dev * sqrt(lead_time_days)'),
# (0.542, 'Reorder Point = (avg_daily_demand * lead_time_days) + safety_stock'),
# (0.264, 'ABC Analysis: A-items need tight control, C-items tolerate bulk orders.')]
queries = [
"How do I calculate safety stock?",
"What should I know about electronics inventory?",
"Tell me about demand patterns for consumer goods.",
]
for query in queries:
print(f"Query: {query!r}")
for score, passage in top_k(query):
print(f" {score:.3f} {passage}")
print()
$ python 2_SHARE_AFTER_Solution_Code/02_embeddings_basics.py
Embedding passages...
Passage matrix shape: (6, 384) (6 passages x 384 numbers)
Query: 'How do I calculate safety stock?'
0.718 Safety Stock = Z-score * demand_std_dev * sqrt(lead_time_days)
0.542 Reorder Point = (avg_daily_demand * lead_time_days) + safety_stock
0.264 ABC Analysis: A-items need tight control, C-items tolerate bulk orders.
Query: 'What should I know about electronics inventory?'
0.631 Electronics: lead times 14-30 days, high obsolescence risk.
0.419 ABC Analysis: A-items need tight control, C-items tolerate bulk orders.
0.352 Reorder Point = (avg_daily_demand * lead_time_days) + safety_stock
Query: 'Tell me about demand patterns for consumer goods.'
0.487 FMCG: short lead times 3-7 days, high steady demand.
0.341 Safety Stock = Z-score * demand_std_dev * sqrt(lead_time_days)
0.312 Reorder Point = (avg_daily_demand * lead_time_days) + safety_stock
Vector Databases & Metadata Filtering with ChromaDB#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/03_chromadb_retrieval.py, 2_SHARE_AFTER_Solution_Code/03_chromadb_retrieval.py (runs offline)
Concept#
ChromaDB replaces the raw NumPy array with a purpose-built vector database that stores four aligned fields per entry: ids, embeddings, documents (original text), and metadatas (structured tags). It also wraps the same local MiniLM model via LangChain's HuggingFaceEmbeddings interface.
Key Mental Models#
- Collection space configuration: Creating a collection with
metadata={"hnsw:space": "cosine"}configures ChromaDB's HNSW index to rank results by cosine distance. - Hybrid precision via metadata filtering (
where): Tagging each note with atopic(formula,category, orbest_practice) lets you narrow semantic search to a specific slice of the knowledge base (e.g.,where={"topic": "formula"}). This prevents category guidelines from crowding out formula definitions when you only want formulas. - Document vs. query embedding methods: LangChain's
HuggingFaceEmbeddingsexposesembed_documents(...)for batch-indexing passages andembed_query(...)for embedding a single search query at retrieval time.
Trade-Offs & Pitfalls#
- Duplicate collection error: Calling
client.create_collection("inventory_kb")twice in the same Python session (such as re-running a notebook cell) raises an already-exists error; useclient.get_or_create_collection(...)when re-running interactively. - Optional filter handling: Only pass
wheretocollection.query(...)when a filter dictionary is actually provided — passingwhere=Nonecan cause unexpected behavior in ChromaDB.
Code Reference#
import chromadb
from langchain_huggingface import HuggingFaceEmbeddings
# Same local model as Step 02, wrapped by LangChain for a standard embed_documents/embed_query API.
# Keeping normalize_embeddings=True ensures unit-length vectors aligned with cosine distance.
embed = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2",
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True},
)
client = chromadb.Client() # in-memory ChromaDB (nothing saved to disk)
# Configure the HNSW approximate nearest-neighbor index to use cosine space (default is L2).
collection = client.create_collection("inventory_kb", metadata={"hnsw:space": "cosine"})
# Each document carries structured metadata ("topic") so retrieval can combine
# semantic vector search with exact metadata filtering (hybrid pre-filtering).
docs = [
{"id": "ss-formula", "text": "Safety Stock = Z * demand_std_dev * sqrt(lead_time). Z=1.65 for 95%, Z=2.33 for 99%.", "meta": {"topic": "formula"}},
{"id": "rop-formula", "text": "Reorder Point (ROP) = (avg_daily_demand * lead_time) + safety_stock.", "meta": {"topic": "formula"}},
{"id": "electronics", "text": "Electronics: lead times 14-30 days, service level 95-99%, high obsolescence risk.", "meta": {"topic": "category"}},
{"id": "pharma", "text": "Pharma: lead times 7-21 days, service level 99%+, strict FIFO and expiry management.", "meta": {"topic": "category"}},
{"id": "fmcg", "text": "FMCG: lead times 3-7 days, high steady demand, service level 95-98%.", "meta": {"topic": "category"}},
{"id": "raw-mat", "text": "Raw materials: lead times 10-45 days, service level 90-95%.", "meta": {"topic": "category"}},
{"id": "abc", "text": "ABC Analysis: A-items need tight control and high service levels.", "meta": {"topic": "best_practice"}},
{"id": "variability", "text": "High demand variability requires more safety stock to maintain service level.", "meta": {"topic": "best_practice"}},
]
print("Embedding and storing documents...")
# ----- TODO 1: Embed every text and add ids, vectors, texts and metadata to the collection -----
# Hint: vectors = embed.embed_documents([d["text"] for d in docs])
# Hint: collection.add(ids=[...], embeddings=vectors, documents=[...], metadatas=[...])
pass # replace with your code
print(f"Collection has {collection.count()} documents\n")
def retrieve(query: str, n: int = 3, where: dict | None = None) -> list[str]:
"""Return the n most similar texts. `where` is an optional metadata filter, e.g. {"topic": "formula"}."""
# ----- TODO 2: Embed the query and search the collection (apply the filter only if one is given) -----
# Hint: qv = embed.embed_query(query)
# Hint: collection.query(query_embeddings=[qv], n_results=n, where=where)
# Hint: Only add the where filter when one is given (it is None by default)
# Hint: The texts are in results["documents"][0]
return [] # replace with your code
print("=== Query: 'pharma reorder safety stock' ===")
for chunk in retrieve("pharma reorder safety stock"):
print(" •", chunk)
print("\n=== Query: 'how to calculate stock' (formulas only) ===")
for chunk in retrieve("how to calculate stock", where={"topic": "formula"}):
print(" •", chunk)
print("\n=== Query: 'electronics inventory management' (categories only) ===")
for chunk in retrieve("electronics inventory management", where={"topic": "category"}):
print(" •", chunk)
$ python 1_GIVE_FIRST_Starter_Code/03_chromadb_retrieval.py
Embedding and storing documents...
Collection has 0 documents
=== Query: 'pharma reorder safety stock' ===
=== Query: 'how to calculate stock' (formulas only) ===
=== Query: 'electronics inventory management' (categories only) ===
# (Complete TODO 1 and TODO 2 to index the 8 documents and run filtered vector queries)
import chromadb
from langchain_huggingface import HuggingFaceEmbeddings
# Same local model as Step 02, wrapped by LangChain for a consistent embedding interface.
embed = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2",
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True},
)
client = chromadb.Client() # in-memory ChromaDB (nothing saved to disk)
# Set HNSW distance metric to cosine so vector ranking matches cosine similarity.
collection = client.create_collection("inventory_kb", metadata={"hnsw:space": "cosine"})
docs = [
{"id": "ss-formula", "text": "Safety Stock = Z * demand_std_dev * sqrt(lead_time). Z=1.65 for 95%, Z=2.33 for 99%.", "meta": {"topic": "formula"}},
{"id": "rop-formula", "text": "Reorder Point (ROP) = (avg_daily_demand * lead_time) + safety_stock.", "meta": {"topic": "formula"}},
{"id": "electronics", "text": "Electronics: lead times 14-30 days, service level 95-99%, high obsolescence risk.", "meta": {"topic": "category"}},
{"id": "pharma", "text": "Pharma: lead times 7-21 days, service level 99%+, strict FIFO and expiry management.", "meta": {"topic": "category"}},
{"id": "fmcg", "text": "FMCG: lead times 3-7 days, high steady demand, service level 95-98%.", "meta": {"topic": "category"}},
{"id": "raw-mat", "text": "Raw materials: lead times 10-45 days, service level 90-95%.", "meta": {"topic": "category"}},
{"id": "abc", "text": "ABC Analysis: A-items need tight control and high service levels.", "meta": {"topic": "best_practice"}},
{"id": "variability", "text": "High demand variability requires more safety stock to maintain service level.", "meta": {"topic": "best_practice"}},
]
print("Embedding and storing documents...")
# ----- TODO 1 (solved): Embed every text and add ids, vectors, texts and metadata to the collection -----
# Pre-computing embeddings explicitly lets us control the exact model and normalization settings.
vectors = embed.embed_documents([d["text"] for d in docs])
# -> list of 8 float lists, each length 384 (unit-normalized)
collection.add(
ids=[d["id"] for d in docs],
embeddings=vectors,
documents=[d["text"] for d in docs],
metadatas=[d["meta"] for d in docs],
)
print(f"Collection has {collection.count()} documents\n")
def retrieve(query: str, n: int = 3, where: dict | None = None) -> list[str]:
"""Return the n most similar texts. `where` is an optional metadata filter, e.g. {"topic": "formula"}."""
# ----- TODO 2 (solved): Embed the query and search the collection (apply the filter only if one is given) -----
qv = embed.embed_query(query)
kwargs = {"query_embeddings": [qv], "n_results": n}
# Only pass `where` when non-empty; Chroma raises an error if an empty dict is passed.
if where:
kwargs["where"] = where
results = collection.query(**kwargs)
# -> {'ids': [['ss-formula', 'rop-formula']],
# 'documents': [['Safety Stock = Z * ...', 'Reorder Point (ROP) = ...']],
# 'distances': [[0.28, 0.35]], ...} (for where={'topic': 'formula'})
# Chroma accepts batched queries, so results["documents"] is a list-of-lists; [0] unpacks our single query.
return results["documents"][0]
print("=== Query: 'pharma reorder safety stock' ===")
for chunk in retrieve("pharma reorder safety stock"):
print(" •", chunk)
print("\n=== Query: 'how to calculate stock' (formulas only) ===")
for chunk in retrieve("how to calculate stock", where={"topic": "formula"}):
print(" •", chunk)
print("\n=== Query: 'electronics inventory management' (categories only) ===")
for chunk in retrieve("electronics inventory management", where={"topic": "category"}):
print(" •", chunk)
$ python 2_SHARE_AFTER_Solution_Code/03_chromadb_retrieval.py
Embedding and storing documents...
Collection has 8 documents
=== Query: 'pharma reorder safety stock' ===
• Pharma: lead times 7-21 days, service level 99%+, strict FIFO and expiry management.
• Reorder Point (ROP) = (avg_daily_demand * lead_time) + safety_stock.
• Safety Stock = Z * demand_std_dev * sqrt(lead_time). Z=1.65 for 95%, Z=2.33 for 99%.
=== Query: 'how to calculate stock' (formulas only) ===
• Safety Stock = Z * demand_std_dev * sqrt(lead_time). Z=1.65 for 95%, Z=2.33 for 99%.
• Reorder Point (ROP) = (avg_daily_demand * lead_time) + safety_stock.
=== Query: 'electronics inventory management' (categories only) ===
• Electronics: lead times 14-30 days, service level 95-99%, high obsolescence risk.
• Pharma: lead times 7-21 days, service level 99%+, strict FIFO and expiry management.
• FMCG: lead times 3-7 days, high steady demand, service level 95-98%.
Composable LLM Chains & Why LLMs Shouldn't Do Math#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/04_llm_chain.py, 2_SHARE_AFTER_Solution_Code/04_llm_chain.py (requires OPENAI_API_KEY)
Concept#
Step 04 introduces LangChain Expression Language (LCEL) by wiring a reusable prompt template, a chat model (ChatOpenAI), and an output parser into a single runnable pipeline: prompt | llm | StrOutputParser(). Deliberately asking the LLM to compute safety stock and desired stock itself — then checking its output against exact Python math — exposes a critical limitation of LLMs.
How It Works#
Key Mental Models#
- Prompt templates separate instructions from data:
ChatPromptTemplate.from_messages(...)defines a stablesystemrole (persona, formulas, output format) and ahumanmessage with{variable}slots filled dynamically on each.invoke(params)call. - The pipe (
|) operator: Chainingprompt | llm | StrOutputParser()passes the formatted messages into the LLM and extracts the raw string from the returnedAIMessage, making the whole chain callable with a single.invoke(...). - LLMs predict tokens, they do not calculate: Even when given the exact formulas and Z-table in the system prompt, an LLM approximates arithmetic (especially square roots like
√21). It may be close, slightly off in decimals, or outright wrong. Multiplied across hundreds of SKUs, small rounding or arithmetic errors translate directly into stockouts or excess capital locked in inventory.
Trade-Offs & Pitfalls#
- Missing template variables: Every
{name}placeholder inChatPromptTemplatemust exist as a key in the dictionary passed to.invoke(...), otherwise LangChain raises aKeyError. - Design takeaway: Use LLMs for reasoning, explanation, and communication — never for exact business arithmetic. That sets up tool calling in Step 06.
Code Reference#
import math
from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# A prompt template = a message with blanks ({...}) that we fill in on every call.
# Separating the static system instructions (formulas + output format) from the dynamic
# human SKU payload keeps prompts reusable and easy to audit.
prompt = ChatPromptTemplate.from_messages([
("system", """You are an inventory planning expert.
Given these parameters, compute the desired stock level step by step.
Formulas:
Safety Stock = Z * demand_std_dev * sqrt(lead_time_days)
Desired Stock = (avg_daily_demand * lead_time_days) + Safety Stock
Z-scores: 90% -> 1.28 | 95% -> 1.65 | 97% -> 1.88 | 98% -> 2.05 | 99% -> 2.33
End your response with exactly:
DESIRED_STOCK: <number>"""),
("human",
"SKU: {sku_id} ({sku_name})\n"
"Lead Time : {lead_time_days} days\n"
"Daily Demand : {avg_daily_demand} units/day\n"
"Demand Std Dev : {demand_std_dev} units/day\n"
"Service Level : {service_level}%"),
])
# ----- TODO 1: Build the chain: prompt -> llm -> StrOutputParser -----
# LCEL (LangChain Expression Language) composes Runnables with `|`, streaming the output
# of each stage directly into the next.
# Hint: LangChain joins steps with the pipe operator |
# Hint: StrOutputParser() turns the LLM's message object into a plain string
chain = None # replace with your code
Z_TABLE = {90: 1.28, 95: 1.65, 97: 1.88, 98: 2.05, 99: 2.33}
test_cases = [
{"sku_id": "SKU-001", "sku_name": "Wireless Headphones", "lead_time_days": 21, "avg_daily_demand": 8, "demand_std_dev": 2.0, "service_level": 98},
{"sku_id": "SKU-003", "sku_name": "Instant Noodles", "lead_time_days": 4, "avg_daily_demand": 80, "demand_std_dev": 10.0, "service_level": 95},
]
for params in test_cases:
print(f"\n{'=' * 60}\nSKU: {params['sku_id']} — {params['sku_name']}\n{'=' * 60}")
# ----- TODO 2: Run the chain with this SKU's parameters and print the result -----
# Hint: chain.invoke(params) fills every {variable} in the prompt from the dict
result = "TODO" # replace with your code
print(result)
# Ground-truth Python check: highlights why we later move arithmetic from the LLM into a tool
z = Z_TABLE[params["service_level"]]
safety = z * params["demand_std_dev"] * math.sqrt(params["lead_time_days"])
desired = params["avg_daily_demand"] * params["lead_time_days"] + safety
print(f"\n[Python check] safety stock = {safety:.2f}, desired stock = {desired:.2f}")
$ python 1_GIVE_FIRST_Starter_Code/04_llm_chain.py
============================================================
SKU: SKU-001 — Wireless Headphones
============================================================
TODO
[Python check] safety stock = 18.79, desired stock = 186.79
============================================================
SKU: SKU-003 — Instant Noodles
============================================================
TODO
[Python check] safety stock = 33.00, desired stock = 353.00
import math
from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# A prompt template = a message with blanks ({...}) that we fill in on every call.
# Requiring a fixed trailing marker (`DESIRED_STOCK: <number>`) makes downstream parsing predictable.
prompt = ChatPromptTemplate.from_messages([
("system", """You are an inventory planning expert.
Given these parameters, compute the desired stock level step by step.
Formulas:
Safety Stock = Z * demand_std_dev * sqrt(lead_time_days)
Desired Stock = (avg_daily_demand * lead_time_days) + Safety Stock
Z-scores: 90% -> 1.28 | 95% -> 1.65 | 97% -> 1.88 | 98% -> 2.05 | 99% -> 2.33
End your response with exactly:
DESIRED_STOCK: <number>"""),
("human",
"SKU: {sku_id} ({sku_name})\n"
"Lead Time : {lead_time_days} days\n"
"Daily Demand : {avg_daily_demand} units/day\n"
"Demand Std Dev : {demand_std_dev} units/day\n"
"Service Level : {service_level}%"),
])
# ----- TODO 1 (solved): Build the chain: prompt -> llm -> StrOutputParser -----
# LCEL pipe: dict -> formatted messages -> AIMessage -> plain str.
chain = prompt | llm | StrOutputParser()
Z_TABLE = {90: 1.28, 95: 1.65, 97: 1.88, 98: 2.05, 99: 2.33}
test_cases = [
{"sku_id": "SKU-001", "sku_name": "Wireless Headphones", "lead_time_days": 21, "avg_daily_demand": 8, "demand_std_dev": 2.0, "service_level": 98},
{"sku_id": "SKU-003", "sku_name": "Instant Noodles", "lead_time_days": 4, "avg_daily_demand": 80, "demand_std_dev": 10.0, "service_level": 95},
]
for params in test_cases:
print(f"\n{'=' * 60}\nSKU: {params['sku_id']} — {params['sku_name']}\n{'=' * 60}")
# ----- TODO 2 (solved): Run the chain with this SKU's parameters and print the result -----
result = chain.invoke(params)
# -> "1. Service level 98% -> Z = 2.05\n...\nDESIRED_STOCK: 186.79" (for SKU-001)
print(result)
# Compare the LLM's step-by-step arithmetic against exact Python math (especially for non-integer sqrt)
z = Z_TABLE[params["service_level"]]
safety = z * params["demand_std_dev"] * math.sqrt(params["lead_time_days"])
# -> 18.788... (SKU-001: 2.05 * 2.0 * sqrt(21))
desired = params["avg_daily_demand"] * params["lead_time_days"] + safety
# -> 186.788... (SKU-001: 8 * 21 + 18.79)
print(f"\n[Python check] safety stock = {safety:.2f}, desired stock = {desired:.2f}")
$ python 2_SHARE_AFTER_Solution_Code/04_llm_chain.py
============================================================
SKU: SKU-001 — Wireless Headphones
============================================================
1. Service level 98% -> Z = 2.05
2. Safety Stock = 2.05 * 2.0 * sqrt(21) = 4.10 * 4.5826 = 18.79
3. Lead Time Demand = 8 * 21 = 168
4. Desired Stock = 168 + 18.79 = 186.79
DESIRED_STOCK: 186.79
[Python check] safety stock = 18.79, desired stock = 186.79
============================================================
SKU: SKU-003 — Instant Noodles
============================================================
1. Service level 95% -> Z = 1.65
2. Safety Stock = 1.65 * 10.0 * sqrt(4) = 16.5 * 2 = 33.00
3. Lead Time Demand = 80 * 4 = 320
4. Desired Stock = 320 + 33.00 = 353.00
DESIRED_STOCK: 353.00
[Python check] safety stock = 33.00, desired stock = 353.00
Retrieval-Augmented Generation (RAG) Chains#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/05_rag_chain.py, 2_SHARE_AFTER_Solution_Code/05_rag_chain.py (requires OPENAI_API_KEY)
Concept#
A general-purpose LLM does not know your organization's internal policies, category rules, or standard Z-score conventions. RAG (Retrieve → Augment → Generate) bridges this gap by querying ChromaDB for the top relevant knowledge notes at runtime and injecting them into the system prompt's {rag_context} slot before the LLM generates its answer.
How It Works#
Injecting only the top-3 semantically matched ChromaDB policy notes into {rag_context} upgrades generic inventory advice into organization-specific guidance—citing Pharma FIFO rules, expiry tracking, and the 40% safety-stock jump at 99% service level.
Key Mental Models#
- A/B verification (
bare_chainvs.rag_chain): Running the exact same Pharma SKU (Paracetamol 500mg, 99% service level) through a prompt without context and a prompt with retrieved notes makes the value of RAG immediately visible: only the RAG-augmented response cites company-specific rules such as strict FIFO, expiry management, and the 40% safety-stock jump from 95% to 99%. - Why retrieve top 3 instead of stuffing the entire KB:
- Cost and latency: Fewer input tokens mean faster, cheaper calls.
- Signal-to-noise ratio: Irrelevant notes distract the model and degrade answer quality.
- Scalability habit: While 6–13 notes could fit in a prompt, real enterprise knowledge bases hold thousands of documents where selective retrieval is mandatory.
Trade-Offs & Pitfalls#
- Context merging: When invoking
rag_chain, you must merge both the SKU dictionary and"rag_context"into one input dict ({**sku, "rag_context": context}). - Retrieval quality caps generation quality: If the query string fails to surface the right policy note, the LLM falls back to generic training knowledge.
Code Reference#
import chromadb
from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_openai import ChatOpenAI
load_dotenv()
# ----------------------------------------------------------------------------
# 1) Build the knowledge base (same idea as Step 03)
# Indexes domain policies and formulas into Chroma so they can be retrieved on demand.
# ----------------------------------------------------------------------------
embed = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2",
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True},
)
client = chromadb.Client()
col = client.create_collection("inv_kb", metadata={"hnsw:space": "cosine"})
KB = [
("ss", "Safety Stock = Z * demand_std_dev * sqrt(lead_time). Z=1.65 for 95%, Z=2.33 for 99%."),
("rop", "Reorder Point (ROP) = (avg_daily_demand * lead_time) + Safety Stock."),
("elec", "Electronics: lead times 14-30 days, high obsolescence risk."),
("ph", "Pharma: 99%+ service level, strict FIFO, expiry dates matter."),
("slv", "Raising service level from 95% to 99% increases safety stock by about 40% (Z goes from 1.65 to 2.33)."),
("var", "High demand variability requires more safety stock for the same service level."),
]
vecs = embed.embed_documents([text for _, text in KB])
col.add(ids=[doc_id for doc_id, _ in KB], embeddings=vecs, documents=[text for _, text in KB])
def retrieve_context(query: str, n: int = 3) -> str:
"""RETRIEVE: return the n most relevant KB passages as one bullet-list string."""
# ----- TODO 1: Search the collection and return the passages as a bullet list ("- passage" per line) -----
# Formatting retrieved chunks as concise bullets keeps the augmented system prompt clean and readable.
# Hint: qv = embed.embed_query(query); res = col.query(query_embeddings=[qv], n_results=n)
# Hint: The passages are in res["documents"][0]
# Hint: "\n".join(f"- {c}" for c in passages)
return "" # replace with your code
# ----------------------------------------------------------------------------
# 2) Two prompts: one WITHOUT extra knowledge, one WITH a {rag_context} slot
# Running both side-by-side on the same SKU demonstrates how RAG grounds advice
# in company-specific rules (e.g. strict FIFO, obsolescence risk, exact Z-scores).
# ----------------------------------------------------------------------------
human_msg = (
"SKU: {sku_name} | Category: {category}\n"
"Current Stock: {current_stock} | Lead Time: {lead_time_days} days\n"
"Daily Demand: {avg_daily_demand} (std dev {demand_std_dev}) | Service Level: {service_level}%"
)
bare_prompt = ChatPromptTemplate.from_messages([
("system", "You are an inventory planning expert. Advise on reorder strategy in under 150 words."),
("human", human_msg),
])
rag_prompt = ChatPromptTemplate.from_messages([
("system",
# ... (see full file: 05_rag_chain.py)
$ python 1_GIVE_FIRST_Starter_Code/05_rag_chain.py
# Before completing TODO 1 (retrieve_context returns ""):
--- Retrieved context ---
(empty — fill in TODO 1 to inject ChromaDB passages)
--- Bare LLM vs. RAG LLM ---
Both prompts produce generic advice because {rag_context} is empty until TODO 1 is solved.
import chromadb
from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_openai import ChatOpenAI
load_dotenv()
# ----------------------------------------------------------------------------
# 1) Build the knowledge base (same idea as Step 03)
# Stores company-specific inventory rules and formulas in an in-memory cosine index.
# ----------------------------------------------------------------------------
embed = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2",
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True},
)
client = chromadb.Client()
col = client.create_collection("inv_kb", metadata={"hnsw:space": "cosine"})
KB = [
("ss", "Safety Stock = Z * demand_std_dev * sqrt(lead_time). Z=1.65 for 95%, Z=2.33 for 99%."),
("rop", "Reorder Point (ROP) = (avg_daily_demand * lead_time) + Safety Stock."),
("elec", "Electronics: lead times 14-30 days, high obsolescence risk."),
("ph", "Pharma: 99%+ service level, strict FIFO, expiry dates matter."),
("slv", "Raising service level from 95% to 99% increases safety stock by about 40% (Z goes from 1.65 to 2.33)."),
("var", "High demand variability requires more safety stock for the same service level."),
]
vecs = embed.embed_documents([text for _, text in KB])
col.add(ids=[doc_id for doc_id, _ in KB], embeddings=vecs, documents=[text for _, text in KB])
def retrieve_context(query: str, n: int = 3) -> str:
"""RETRIEVE: return the n most relevant KB passages as one bullet-list string."""
# ----- TODO 1 (solved): Search the collection and return the passages as a bullet list ("- passage" per line) -----
# Embeds the query in the same normalized space, fetches top-n chunks, and formats them for prompt injection.
qv = embed.embed_query(query)
res = col.query(query_embeddings=[qv], n_results=n)
# -> {'ids': [['ph', 'rop', 'ss']],
# 'documents': [['Pharma: 99%+ service level, strict FIFO, expiry dates matter.',
# 'Reorder Point (ROP) = (avg_daily_demand * lead_time) + Safety Stock.',
# 'Safety Stock = Z * demand_std_dev * sqrt(lead_time). ...']]}
return "\n".join(f"- {c}" for c in res["documents"][0])
# -> "- Pharma: 99%+ service level, strict FIFO, expiry dates matter.\n"
# "- Reorder Point (ROP) = (avg_daily_demand * lead_time) + Safety Stock.\n"
# "- Safety Stock = Z * demand_std_dev * sqrt(lead_time). ..."
# ----------------------------------------------------------------------------
# 2) Two prompts: one WITHOUT extra knowledge, one WITH a {rag_context} slot
# Comparing bare_prompt vs. rag_prompt isolates the value of grounded retrieval.
# ----------------------------------------------------------------------------
human_msg = (
"SKU: {sku_name} | Category: {category}\n"
"Current Stock: {current_stock} | Lead Time: {lead_time_days} days\n"
"Daily Demand: {avg_daily_demand} (std dev {demand_std_dev}) | Service Level: {service_level}%"
)
bare_prompt = ChatPromptTemplate.from_messages([
("system", "You are an inventory planning expert. Advise on reorder strategy in under 150 words."),
("human", human_msg),
])
rag_prompt = ChatPromptTemplate.from_messages([
("system",
"You are an inventory planning expert. Advise on reorder strategy in under 150 words.\n\n"
# ... (see full file: 05_rag_chain.py)
$ python 2_SHARE_AFTER_Solution_Code/05_rag_chain.py
=== Retrieved Context ===
- Pharma: 99%+ service level, strict FIFO, expiry dates matter.
- Reorder Point (ROP) = (avg_daily_demand * lead_time) + Safety Stock.
- Safety Stock = Z * demand_std_dev * sqrt(lead_time). Z=1.65 for 95%, Z=2.33 for 99%.
=== BARE LLM (no RAG) ===
With 800 units on hand and 40/day demand over a 7-day lead time, you have plenty of buffer above expected lead-time demand (280 units). Monitor stock weekly and reorder before dropping near 310 units.
=== RAG LLM (grounded in KB) ===
Paracetamol 500mg (Pharma) requires a 99%+ service level (Z=2.33). Safety Stock = 2.33 * 5 * sqrt(7) ≈ 30.8 units, giving ROP = 280 + 30.8 ≈ 311 units. Current stock (800) is well above ROP, so do not reorder yet—enforce strict FIFO rotation and track batch expiry dates.
Tool Calling & the Manual Agent Loop#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/06_tool_calling_agent.py, 2_SHARE_AFTER_Solution_Code/06_tool_calling_agent.py (requires OPENAI_API_KEY)
Concept#
To fix the arithmetic unreliability exposed in Step 04, Step 06 separates decision-making from execution: exact math (calculate_safety_stock, calculate_reorder_point) and data lookups (lookup_sku_stock) live in @tool-decorated Python functions, while the LLM decides which tools to call, in what order, and when it has enough information to answer.
How It Works#
Key Mental Models#
- Binding tools (
llm.bind_tools(tools)): Sends each tool's function name, typed parameter schema, and docstring to the LLM so it knows what capabilities exist and when to invoke them. - Why a loop is required: Multi-step questions like "Does SKU-005 need to be reordered?" cannot be solved in one shot. The model must first call
lookup_sku_stock, read the returned parameters, then callcalculate_safety_stock, then pass that result intocalculate_reorder_point, and finally synthesize an answer. ToolMessagecorrelation: Every tool execution result is serialized (json.dumps(result)) and appended tomessageswithtool_call_id=tc["id"]so the LLM knows exactly which request produced which output.MAX_STEPSsafety net: Bounding thefor _ in range(MAX_STEPS)loop (MAX_STEPS = 8here) prevents infinite loops and runaway API costs if a tool keeps failing and the LLM retries endlessly.
Trade-Offs & Pitfalls#
- LLM skipping tools: If the model tries to do mental math instead of calling a tool, sharpen the tool docstrings and reinforce an explicit system rule ("never do the maths yourself").
- Missing tool error handling: Returning structured error dicts (e.g.,
{"error": "SKU-999 not found"}) lets the LLM recover gracefully and explain the problem to the user rather than crashing the loop.
Code Reference#
import json
import math
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# Z-score lookup table for standard normal service levels (used by the exact-math tool)
Z_TABLE = {90: 1.28, 91: 1.34, 92: 1.41, 93: 1.48, 94: 1.55, 95: 1.65, 96: 1.75, 97: 1.88, 98: 2.05, 99: 2.33}
# ── Tools ─────────────────────────────────────────────────────────────────────
# Splitting lookup, safety stock, and ROP into three composable tools lets the agent
# chain them dynamically across multiple turns (lookup -> safety stock -> ROP -> answer).
@tool
def calculate_safety_stock(demand_std_dev: float, lead_time_days: float, service_level_pct: float) -> float:
"""
Calculate safety stock (extra buffer units).
safety_stock = Z * demand_std_dev * sqrt(lead_time_days)
Z-scores: 90%->1.28, 95%->1.65, 97%->1.88, 98%->2.05, 99%->2.33
"""
z = Z_TABLE.get(round(service_level_pct), 1.65)
return round(z * demand_std_dev * math.sqrt(lead_time_days), 2)
@tool
def calculate_reorder_point(avg_daily_demand: float, lead_time_days: float, safety_stock: float) -> float:
"""
Calculate the reorder point (ROP): reorder when stock falls to this level.
ROP = (avg_daily_demand * lead_time_days) + safety_stock
"""
return round(avg_daily_demand * lead_time_days + safety_stock, 2)
@tool
def lookup_sku_stock(sku_id: str) -> dict:
"""
Look up current stock and demand parameters for a SKU from the inventory database.
Returns: sku_id, sku_name, current_stock, avg_daily_demand, demand_std_dev, lead_time_days, service_level
"""
db = { # a small pretend database
"SKU-001": {"sku_name": "Wireless Headphones", "current_stock": 150, "avg_daily_demand": 8, "demand_std_dev": 2.0, "lead_time_days": 21, "service_level": 98},
"SKU-002": {"sku_name": "Paracetamol 500mg", "current_stock": 800, "avg_daily_demand": 40, "demand_std_dev": 5.0, "lead_time_days": 7, "service_level": 99},
"SKU-005": {"sku_name": "Laptop 15-inch", "current_stock": 50, "avg_daily_demand": 3, "demand_std_dev": 1.0, "lead_time_days": 30, "service_level": 99},
}
record = db.get(sku_id.upper())
if not record:
return {"error": f"{sku_id} not found"}
return {"sku_id": sku_id.upper(), **record}
# ── LLM with tools bound ──────────────────────────────────────────────────────
tools = [calculate_safety_stock, calculate_reorder_point, lookup_sku_stock]
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none").bind_tools(tools)
TOOL_MAP = {t.name: t for t in tools}
# Guard rail: every ReAct / tool-calling loop needs a step cap to prevent runaway API spend.
MAX_STEPS = 8 # safety net: never loop forever
# ... (see full file: 06_tool_calling_agent.py)
$ python 1_GIVE_FIRST_Starter_Code/06_tool_calling_agent.py
# Expected multi-step agent trace once the starter's while-loop TODO is implemented:
Question: Should we reorder SKU-001?
Step 1 -> lookup_sku_stock({'sku_id': 'SKU-001'}) -> {'sku_id': 'SKU-001', 'sku_name': 'Wireless Headphones', 'current_stock': 150, ...}
Step 2 -> calculate_safety_stock({'demand_std_dev': 2.0, 'lead_time_days': 21, 'service_level_pct': 98}) -> 18.79
Step 3 -> calculate_reorder_point({'avg_daily_demand': 8, 'lead_time_days': 21, 'safety_stock': 18.79}) -> 186.79
Answer: Yes — SKU-001 (Wireless Headphones) has 150 units on hand, which is below its reorder point of 186.79 units (shortfall: 36.79 units).
import json
import math
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# Z-score for each service level (standard normal table)
Z_TABLE = {90: 1.28, 91: 1.34, 92: 1.41, 93: 1.48, 94: 1.55, 95: 1.65, 96: 1.75, 97: 1.88, 98: 2.05, 99: 2.33}
# ── Tools ─────────────────────────────────────────────────────────────────────
# Each tool encapsulates one deterministic responsibility so the LLM orchestrates the
# workflow (lookup -> safety stock -> reorder point) without doing mental arithmetic.
@tool
def calculate_safety_stock(demand_std_dev: float, lead_time_days: float, service_level_pct: float) -> float:
"""
Calculate safety stock (extra buffer units).
safety_stock = Z * demand_std_dev * sqrt(lead_time_days)
Z-scores: 90%->1.28, 95%->1.65, 97%->1.88, 98%->2.05, 99%->2.33
"""
z = Z_TABLE.get(round(service_level_pct), 1.65)
return round(z * demand_std_dev * math.sqrt(lead_time_days), 2)
# -> 18.79 (for SKU-001: Z=2.05, std=2.0, lead_time=21)
@tool
def calculate_reorder_point(avg_daily_demand: float, lead_time_days: float, safety_stock: float) -> float:
"""
Calculate the reorder point (ROP): reorder when stock falls to this level.
ROP = (avg_daily_demand * lead_time_days) + safety_stock
"""
return round(avg_daily_demand * lead_time_days + safety_stock, 2)
# -> 186.79 (for SKU-001: 8 * 21 + 18.79)
@tool
def lookup_sku_stock(sku_id: str) -> dict:
"""
Look up current stock and demand parameters for a SKU from the inventory database.
Returns: sku_id, sku_name, current_stock, avg_daily_demand, demand_std_dev, lead_time_days, service_level
"""
db = { # a small pretend database
"SKU-001": {"sku_name": "Wireless Headphones", "current_stock": 150, "avg_daily_demand": 8, "demand_std_dev": 2.0, "lead_time_days": 21, "service_level": 98},
"SKU-002": {"sku_name": "Paracetamol 500mg", "current_stock": 800, "avg_daily_demand": 40, "demand_std_dev": 5.0, "lead_time_days": 7, "service_level": 99},
"SKU-005": {"sku_name": "Laptop 15-inch", "current_stock": 50, "avg_daily_demand": 3, "demand_std_dev": 1.0, "lead_time_days": 30, "service_level": 99},
}
record = db.get(sku_id.upper())
if not record:
return {"error": f"{sku_id} not found"}
return {"sku_id": sku_id.upper(), **record}
# -> {'sku_id': 'SKU-001', 'sku_name': 'Wireless Headphones', 'current_stock': 150,
# 'avg_daily_demand': 8, 'demand_std_dev': 2.0, 'lead_time_days': 21,
# 'service_level': 98}
# ── LLM with tools bound ──────────────────────────────────────────────────────
tools = [calculate_safety_stock, calculate_reorder_point, lookup_sku_stock]
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none").bind_tools(tools)
TOOL_MAP = {t.name: t for t in tools}
# Hard upper bound on reasoning/tool iterations to guard against infinite loops.
MAX_STEPS = 8 # safety net: never loop forever
# ... (see full file: 06_tool_calling_agent.py)
$ python 2_SHARE_AFTER_Solution_Code/06_tool_calling_agent.py
Question: Should we reorder SKU-001?
[step 1] lookup_sku_stock({'sku_id': 'SKU-001'}) -> {'sku_id': 'SKU-001', 'sku_name': 'Wireless Headphones', 'current_stock': 150, 'avg_daily_demand': 8, 'demand_std_dev': 2.0, 'lead_time_days': 21, 'service_level': 98}
[step 2] calculate_safety_stock({'demand_std_dev': 2.0, 'lead_time_days': 21, 'service_level_pct': 98}) -> 18.79
[step 3] calculate_reorder_point({'avg_daily_demand': 8, 'lead_time_days': 21, 'safety_stock': 18.79}) -> 186.79
Answer: Yes, reorder SKU-001 (Wireless Headphones). Current stock (150) is below the reorder point (186.79; safety stock = 18.79), leaving a shortfall of 36.79 units.
Question: Should we reorder SKU-002?
[step 1] lookup_sku_stock({'sku_id': 'SKU-002'}) -> {'sku_id': 'SKU-002', 'sku_name': 'Paracetamol 500mg', 'current_stock': 800, 'avg_daily_demand': 40, 'demand_std_dev': 5.0, 'lead_time_days': 7, 'service_level': 99}
[step 2] calculate_safety_stock({'demand_std_dev': 5.0, 'lead_time_days': 7, 'service_level_pct': 99}) -> 30.82
[step 3] calculate_reorder_point({'avg_daily_demand': 40, 'lead_time_days': 7, 'safety_stock': 30.82}) -> 310.82
Answer: No reorder needed for SKU-002 (Paracetamol 500mg). Current stock (800) exceeds the reorder point (310.82) by 489.18 units.
Multi-Chain Pipelines vs. Dynamic Agents#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/07_multi_chain_pipeline.py, 2_SHARE_AFTER_Solution_Code/07_multi_chain_pipeline.py (requires OPENAI_API_KEY)
Concept#
Not every AI workflow should be an autonomous agent. Step 07 builds a deterministic multi-chain pipeline where your Python code controls the exact sequence of steps: query a 3-table SQLite database (inventory, lead_time, demand), call safety_stock_tool directly in Python, pass the verified numbers to Chain 1 (compute_chain) for explanation, and feed Chain 1's text output as {computation} into Chain 2 (reorder_chain) for a final reorder recommendation.
How It Works#
Use a code-driven multi-chain pipeline for repeatable batch workflows (like nightly reorder audits) where fixed cost and testability matter, and a dynamic tool-calling agent for interactive chat where user questions vary unpredictably.
Key Mental Models#
- Chaining LLM outputs: Splitting one large task into focused chains (
compute_chain->reorder_chain) keeps each prompt short, single-purpose, and easier to evaluate or swap independently. - Pipeline (Step 07) vs. Agent (Steps 06 & 08):
- Who decides the steps? Pipeline: you, in code. Agent: the LLM, at runtime.
- Predictability: Pipeline executes the exact same steps every time (easy to test). Agent may choose different tool paths per run.
- Flexibility for open questions: Pipeline only handles the exact flow you coded. Agent handles unanticipated questions ("list SKUs", "compare two SKUs", "which SKUs are most at risk?").
- Cost & latency: Pipeline has a fixed number of LLM calls. Agent cost varies with question complexity.
- When to use each: Use a pipeline for repeatable batch workflows (e.g., nightly reorder reports); use an agent for open-ended interactive chat assistants. Many production systems use a pipeline for the core flow and an agent at the edges.
Code Reference#
import math
import sqlite3
from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# ── 1) Database: 3 normalized tables (inventory, lead_time, demand) ──────────
# Separating stock, supplier lead times, and demand statistics models a realistic
# multi-table ERP database queried via SQL JOINs.
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.executescript("""
CREATE TABLE inventory (sku_id TEXT PRIMARY KEY, sku_name TEXT, category TEXT, current_stock REAL, service_level REAL);
CREATE TABLE lead_time (sku_id TEXT PRIMARY KEY, lead_time_days REAL, supplier_name TEXT);
CREATE TABLE demand (sku_id TEXT PRIMARY KEY, avg_daily_demand REAL, demand_std_dev REAL);
""")
cur.executemany("INSERT INTO inventory VALUES (?,?,?,?,?)", [
("SKU-001", "Wireless Headphones", "Electronics", 150, 98),
("SKU-002", "Paracetamol 500mg", "Pharma", 800, 99),
("SKU-005", "Laptop 15-inch", "Electronics", 50, 99),
])
cur.executemany("INSERT INTO lead_time VALUES (?,?,?)", [
("SKU-001", 21, "TechImports Ltd"),
("SKU-002", 7, "MedSupply Co"),
("SKU-005", 30, "GlobalTech"),
])
cur.executemany("INSERT INTO demand VALUES (?,?,?)", [
("SKU-001", 8, 2.0), ("SKU-002", 40, 5.0), ("SKU-005", 3, 1.0),
])
conn.commit()
def fetch_sku(sku_id: str) -> dict | None:
# 3-way JOIN consolidates all parameters needed by the downstream calculation and LLM chains.
row = cur.execute("""
SELECT i.*, l.lead_time_days, l.supplier_name, d.avg_daily_demand, d.demand_std_dev
FROM inventory i
JOIN lead_time l ON l.sku_id = i.sku_id
JOIN demand d ON d.sku_id = i.sku_id
WHERE UPPER(i.sku_id) = UPPER(?)
""", (sku_id,)).fetchone()
return dict(row) if row else None
# ── 2) Tool: exact maths ──────────────────────────────────────────────────────
# Returning a structured dict (z_score, safety_stock, desired_stock) gives subsequent
# pipeline stages deterministic numbers to compare against current_stock.
Z_TABLE = {90: 1.28, 91: 1.34, 92: 1.41, 93: 1.48, 94: 1.55, 95: 1.65, 96: 1.75, 97: 1.88, 98: 2.05, 99: 2.33}
@tool
def safety_stock_tool(avg_daily_demand: float, demand_std_dev: float, lead_time_days: float, service_level_pct: float) -> dict:
"""Compute safety stock and desired stock level with exact arithmetic."""
z = Z_TABLE.get(round(service_level_pct), 1.65)
ss = round(z * demand_std_dev * math.sqrt(lead_time_days), 2)
desired = round(avg_daily_demand * lead_time_days + ss, 2)
return {"z_score": z, "safety_stock": ss, "desired_stock": desired}
# ... (see full file: 07_multi_chain_pipeline.py)
$ python 1_GIVE_FIRST_Starter_Code/07_multi_chain_pipeline.py
# Expected pipeline output once the starter's multi-chain orchestration TODOs are wired:
SKU-001 (Wireless Headphones) | stock=150.0 | desired=186.79 (SS=18.79) -> REORDER (shortfall 36.79)
SKU-002 (Paracetamol 500mg) | stock=800.0 | desired=310.82 (SS=30.82) -> OK (surplus 489.18)
SKU-005 (Laptop 15-inch) | stock=50.0 | desired=102.76 (SS=12.76) -> REORDER (shortfall 52.76)
import math
import sqlite3
from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# ── 1) Database: 3 normalized tables ──────────────────────────────────────────
# Mirrors a multi-table ERP store; deterministic SQL lookups feed exact numbers into the pipeline.
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.executescript("""
CREATE TABLE inventory (sku_id TEXT PRIMARY KEY, sku_name TEXT, category TEXT, current_stock REAL, service_level REAL);
CREATE TABLE lead_time (sku_id TEXT PRIMARY KEY, lead_time_days REAL, supplier_name TEXT);
CREATE TABLE demand (sku_id TEXT PRIMARY KEY, avg_daily_demand REAL, demand_std_dev REAL);
""")
cur.executemany("INSERT INTO inventory VALUES (?,?,?,?,?)", [
("SKU-001", "Wireless Headphones", "Electronics", 150, 98),
("SKU-002", "Paracetamol 500mg", "Pharma", 800, 99),
("SKU-005", "Laptop 15-inch", "Electronics", 50, 99),
])
cur.executemany("INSERT INTO lead_time VALUES (?,?,?)", [
("SKU-001", 21, "TechImports Ltd"),
("SKU-002", 7, "MedSupply Co"),
("SKU-005", 30, "GlobalTech"),
])
cur.executemany("INSERT INTO demand VALUES (?,?,?)", [
("SKU-001", 8, 2.0), ("SKU-002", 40, 5.0), ("SKU-005", 3, 1.0),
])
conn.commit()
def fetch_sku(sku_id: str) -> dict | None:
# Parameterized 3-way JOIN returns one unified SKU record (or None if unknown).
row = cur.execute("""
SELECT i.*, l.lead_time_days, l.supplier_name, d.avg_daily_demand, d.demand_std_dev
FROM inventory i
JOIN lead_time l ON l.sku_id = i.sku_id
JOIN demand d ON d.sku_id = i.sku_id
WHERE UPPER(i.sku_id) = UPPER(?)
""", (sku_id,)).fetchone()
return dict(row) if row else None
# -> {'sku_id': 'SKU-001', 'sku_name': 'Wireless Headphones', 'category': 'Electronics',
# 'current_stock': 150.0, 'service_level': 98.0, 'lead_time_days': 21.0,
# 'supplier_name': 'TechImports Ltd', 'avg_daily_demand': 8.0, 'demand_std_dev': 2.0}
# ── 2) Tool: exact maths ──────────────────────────────────────────────────────
# Decoupling arithmetic from the LLM chain guarantees reproducible safety-stock & ROP values
# before the final LLM chain synthesizes the executive recommendation.
Z_TABLE = {90: 1.28, 91: 1.34, 92: 1.41, 93: 1.48, 94: 1.55, 95: 1.65, 96: 1.75, 97: 1.88, 98: 2.05, 99: 2.33}
@tool
def safety_stock_tool(avg_daily_demand: float, demand_std_dev: float, lead_time_days: float, service_level_pct: float) -> dict:
"""Compute safety stock and desired stock level with exact arithmetic."""
z = Z_TABLE.get(round(service_level_pct), 1.65)
ss = round(z * demand_std_dev * math.sqrt(lead_time_days), 2)
desired = round(avg_daily_demand * lead_time_days + ss, 2)
return {"z_score": z, "safety_stock": ss, "desired_stock": desired}
# -> {'z_score': 2.05, 'safety_stock': 18.79, 'desired_stock': 186.79} (for SKU-001)
# ... (see full file: 07_multi_chain_pipeline.py)
$ python 2_SHARE_AFTER_Solution_Code/07_multi_chain_pipeline.py
============================================================
Pipeline Run: SKU-001 (Wireless Headphones)
============================================================
[Stage 1: SQL] stock=150, lead_time=21d (TechImports Ltd), demand=8/day (std=2.0), SL=98%
[Stage 2: Math] {'z_score': 2.05, 'safety_stock': 18.79, 'desired_stock': 186.79}
[Stage 3: LLM] ACTION: REORDER 37+ units from TechImports Ltd immediately. Current stock (150)
is 36.79 units below the desired level (186.79) for a 21-day Electronics lead time.
============================================================
Pipeline Run: SKU-005 (Laptop 15-inch)
============================================================
[Stage 1: SQL] stock=50, lead_time=30d (GlobalTech), demand=3/day (std=1.0), SL=99%
[Stage 2: Math] {'z_score': 2.33, 'safety_stock': 12.76, 'desired_stock': 102.76}
[Stage 3: LLM] ACTION: REORDER 53+ units from GlobalTech. Stock (50) is less than half of the
102.76 target, creating high stockout risk over the 30-day lead time.
End-to-End Inventory Planning Agent & Gradio UI#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/08_full_agent_app.py, 2_SHARE_AFTER_Solution_Code/08_full_agent_app.py (requires OPENAI_API_KEY)
Concept#
Step 08 unifies every previous building block into a browser-based Inventory Planning Agent powered by Gradio (gr.ChatInterface). For each user question, the app retrieves relevant policy notes from ChromaDB (RAG), injects them into the agent's system prompt, runs the multi-step tool-calling loop against a 10-SKU SQLite database and an exact metrics calculator, and returns a plain-English recommendation in a web chat window.
How It Works#
The Step 08 Gradio capstone unifies structured SQLite operational tables, unstructured ChromaDB policy RAG, and atomic Python safety-stock/ceil(reorder_qty) calculators inside a 15-step guarded ReAct loop.
Key Mental Models#
- Consolidated metrics tool (
compute_stock_metrics): Instead of forcing the agent to make separate calls for safety stock and reorder point, one tool returnsz_score,safety_stock,desired_stock,reorder_quantity(rounded up viamath.ceil), andreorder_neededin a single atomic call — reducing loop turns and latency. - Higher step budget (
MAX_STEPS = 15): Open-ended queries like "Which SKUs are most at risk of stockout?" require listing all 10 SKUs and inspecting multiple items, so the step cap is raised from 8 to 15. - Production-minded web app details:
check_same_thread=Falseonsqlite3.connect(":memory:", ...)is required because Gradio handles incoming chat requests on worker threads different from the main thread that created the DB.chat_handlerwrapsrun_agent(message)in atry/exceptblock so runtime errors display a helpful recovery message instead of crashing the UI.- Stateless per turn:
chat_handler(message, history)ignoreshistory, meaning every question is answered independently (adding multi-turn conversation memory is a natural next extension).
- Human judgment still matters: Even with exact math, edge cases like
SKU-009(current stock120vs. desired stock119.14— less than 1 unit of margin) show why tools provide exact numbers while human managers still weigh upcoming festival seasons, supplier reliability, minimum order quantities, and in-transit shipments.
Code Reference#
import json
import math
import sqlite3
import chromadb
import gradio as gr
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
from langchain_core.tools import tool
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_openai import ChatOpenAI
load_dotenv()
# =============================================================================
# 1. Database (3 tables, 10 SKUs)
# Capstone architecture combines SQLite (structured live data), ChromaDB
# (unstructured policy RAG), exact-math tools, and a Gradio chat UI.
# =============================================================================
# check_same_thread=False is required because Gradio handles each UI request on a
# worker thread different from the main thread that initialized the SQLite connection.
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.executescript("""
CREATE TABLE inventory (
sku_id TEXT PRIMARY KEY, sku_name TEXT NOT NULL, category TEXT,
current_stock REAL NOT NULL, service_level REAL NOT NULL
);
CREATE TABLE lead_time (
sku_id TEXT PRIMARY KEY, lead_time_days REAL NOT NULL, supplier_name TEXT,
FOREIGN KEY (sku_id) REFERENCES inventory(sku_id)
);
CREATE TABLE demand (
sku_id TEXT PRIMARY KEY, avg_daily_demand REAL NOT NULL, demand_std_dev REAL NOT NULL,
FOREIGN KEY (sku_id) REFERENCES inventory(sku_id)
);
""")
# Seed 10 SKUs across 4 categories (Electronics, Pharma, FMCG, Raw Materials)
# so the agent must combine SQL numbers with category-specific RAG policies.
cur.executemany("INSERT INTO inventory VALUES (?,?,?,?,?)", [
("SKU-001", "Wireless Headphones", "Electronics", 150, 98),
("SKU-002", "Paracetamol 500mg", "Pharma", 800, 99),
("SKU-003", "Instant Noodles 12-pack", "FMCG", 300, 95),
("SKU-004", "Steel Rod 10mm", "Raw Materials", 300, 92),
("SKU-005", "Laptop 15-inch", "Electronics", 50, 99),
("SKU-006", "Vitamin C Tablets", "Pharma", 600, 97),
("SKU-007", "Shampoo 400ml", "FMCG", 900, 95),
("SKU-008", "Copper Wire 2.5mm", "Raw Materials", 150, 90),
("SKU-009", "Bluetooth Speaker", "Electronics", 120, 96),
("SKU-010", "Flour 5kg", "FMCG", 2000, 95),
])
cur.executemany("INSERT INTO lead_time VALUES (?,?,?)", [
("SKU-001", 21, "TechImports Ltd"), ("SKU-002", 7, "MedSupply Co"),
("SKU-003", 4, "FoodDist Pvt"), ("SKU-004", 14, "SteelWorks Inc"),
("SKU-005", 30, "GlobalTech"), ("SKU-006", 10, "PharmaPlus"),
("SKU-007", 5, "FMCG Direct"), ("SKU-008", 21, "CopperMine Co"),
("SKU-009", 18, "AudioWorld"), ("SKU-010", 3, "LocalMills"),
])
cur.executemany("INSERT INTO demand VALUES (?,?,?)", [
("SKU-001", 8, 2.0), ("SKU-002", 40, 5.0), ("SKU-003", 80, 10.0),
# ... (see full file: 08_full_agent_app.py)
$ python 1_GIVE_FIRST_Starter_Code/08_full_agent_app.py
* Running on local URL: http://127.0.0.1:7860
# Once the starter's RAG tool, SQL tool, math tool, and agent loop TODOs are completed,
# the Gradio UI accepts natural-language queries like "Audit SKU-005 and recommend a reorder"
# and displays both the tool-call trace and the grounded final recommendation.
import json
import math
import sqlite3
import chromadb
import gradio as gr
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
from langchain_core.tools import tool
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_openai import ChatOpenAI
load_dotenv()
# =============================================================================
# 1. Database (3 tables, 10 SKUs)
# Full capstone: unifies SQLite inventory data, ChromaDB policy RAG, exact
# safety-stock/ROP tools, and a multi-step LangChain agent behind Gradio.
# =============================================================================
# check_same_thread=False allows Gradio's worker threads to query the shared in-memory DB.
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.executescript("""
CREATE TABLE inventory (
sku_id TEXT PRIMARY KEY, sku_name TEXT NOT NULL, category TEXT,
current_stock REAL NOT NULL, service_level REAL NOT NULL
);
CREATE TABLE lead_time (
sku_id TEXT PRIMARY KEY, lead_time_days REAL NOT NULL, supplier_name TEXT,
FOREIGN KEY (sku_id) REFERENCES inventory(sku_id)
);
CREATE TABLE demand (
sku_id TEXT PRIMARY KEY, avg_daily_demand REAL NOT NULL, demand_std_dev REAL NOT NULL,
FOREIGN KEY (sku_id) REFERENCES inventory(sku_id)
);
""")
# Seed 10 realistic SKUs spanning Electronics, Pharma, FMCG, and Raw Materials
# so queries exercise SQL joins, Z-score math, and category-aware RAG policies together.
cur.executemany("INSERT INTO inventory VALUES (?,?,?,?,?)", [
("SKU-001", "Wireless Headphones", "Electronics", 150, 98),
("SKU-002", "Paracetamol 500mg", "Pharma", 800, 99),
("SKU-003", "Instant Noodles 12-pack", "FMCG", 300, 95),
("SKU-004", "Steel Rod 10mm", "Raw Materials", 300, 92),
("SKU-005", "Laptop 15-inch", "Electronics", 50, 99),
("SKU-006", "Vitamin C Tablets", "Pharma", 600, 97),
("SKU-007", "Shampoo 400ml", "FMCG", 900, 95),
("SKU-008", "Copper Wire 2.5mm", "Raw Materials", 150, 90),
("SKU-009", "Bluetooth Speaker", "Electronics", 120, 96),
("SKU-010", "Flour 5kg", "FMCG", 2000, 95),
])
cur.executemany("INSERT INTO lead_time VALUES (?,?,?)", [
("SKU-001", 21, "TechImports Ltd"), ("SKU-002", 7, "MedSupply Co"),
("SKU-003", 4, "FoodDist Pvt"), ("SKU-004", 14, "SteelWorks Inc"),
("SKU-005", 30, "GlobalTech"), ("SKU-006", 10, "PharmaPlus"),
("SKU-007", 5, "FMCG Direct"), ("SKU-008", 21, "CopperMine Co"),
("SKU-009", 18, "AudioWorld"), ("SKU-010", 3, "LocalMills"),
])
cur.executemany("INSERT INTO demand VALUES (?,?,?)", [
("SKU-001", 8, 2.0), ("SKU-002", 40, 5.0), ("SKU-003", 80, 10.0),
# ... (see full file: 08_full_agent_app.py)
$ python 2_SHARE_AFTER_Solution_Code/08_full_agent_app.py
* Running on local URL: http://127.0.0.1:7860
--- Gradio Chat Interaction ---
User: Check SKU-005 and advise on reordering.
[Tool Trace]
1. fetch_sku_data({'sku_id': 'SKU-005'}) -> Laptop 15-inch | Electronics | stock=50 | lead_time=30d (GlobalTech) | demand=3/day (std=1.0) | SL=99%
2. calculate_stock_levels({'avg_daily_demand': 3, 'demand_std_dev': 1.0, 'lead_time_days': 30, 'service_level_pct': 99}) -> safety_stock=12.76, desired_stock=102.76
3. search_inventory_kb({'query': 'Electronics lead time obsolescence policy'}) -> "Electronics: lead times 14-30 days, service level 95-99%, high obsolescence risk."
Assistant: SKU-005 (Laptop 15-inch) is critically below target: current stock is 50 units vs. a desired level of 102.76 units (12.76 safety stock + 90 lead-time demand). Place a reorder of ~53 units with GlobalTech now, avoiding excess over-ordering due to Electronics obsolescence risk.
How All Building Blocks Connect#
Revision Notes#
Every file in 15-rag-inventory-agent adds exactly one architectural layer to the final assistant:
- Steps 01–03 run completely offline and establish the two distinct memory systems an AI app needs: SQL for exact structured numbers and ChromaDB for unstructured domain knowledge.
- Steps 04–05 introduce the LLM and show how to ground it in company policies via RAG — while exposing why arithmetic cannot be trusted to token prediction.
- Steps 06–07 contrast the two core orchestration patterns: dynamic tool-calling agents (flexible, LLM-driven) versus fixed multi-chain pipelines (predictable, code-driven).
- Step 08 brings it all together into an interactive Gradio application where SQL holds the facts, Python tools compute the math, RAG supplies the business judgment rules, and the LLM acts as the planner and communicator.
Quick Self-Check Questions#
Self-Check Questions#
Why shouldn't you rely on an LLM to calculate safety stock and desired stock directly, even when you put the exact formulas in the system prompt?
LLMs predict likely tokens rather than executing arithmetic. They frequently drift on decimals or square roots (√lead_time), and small errors across hundreds of SKUs cause costly stockouts or overstocking. Exact math belongs in deterministic Python tools.
Why do Steps 02 and 03 set normalize_embeddings=True when encoding text with all-MiniLM-L6-v2?
Normalizing scales every embedding vector to unit length (length 1). For unit vectors, cosine similarity is mathematically identical to the dot product (passage_vectors @ qv), making similarity scoring fast and simple.
What is the advantage of tagging documents with metadata ({"topic": "formula"}, {"topic": "category"}, etc.) in ChromaDB?
Metadata allows pre-filtering with where={...} before ranking by vector similarity, so you can restrict retrieval to only formulas or only category rules when needed.
In Step 05, why retrieve only the top 3 notes instead of injecting all 13 knowledge-base notes into the system prompt?
Sending fewer notes lowers token cost and latency, prevents irrelevant notes from distracting the LLM, and builds the retrieval habit required when a real knowledge base has thousands of documents.
Why is MAX_STEPS essential in the manual agent loop (Steps 06 and 08)?
If a tool repeatedly errors out or the LLM gets stuck re-requesting tools, an unbounded while loop would run forever, burning time and API spend. MAX_STEPS caps execution as a simple circuit breaker.
When should you choose a multi-chain pipeline (Step 07) over a tool-calling agent (Steps 06 & 08)?
Choose a pipeline when the workflow is fixed, repeatable, and needs predictable cost and testability (e.g., a nightly reorder report). Choose an agent when users ask open-ended, unpredictable questions (e.g., an interactive chat assistant).
Why does Step 08 pass check_same_thread=False to sqlite3.connect(":memory:", ...) and use math.ceil for reorder quantity?
Gradio handles chat requests in worker threads different from the main thread that created the SQLite connection, so SQLite would otherwise raise a thread-safety error. math.ceil rounds fractional reorder quantities up to whole units so you never order fewer units than required to meet the target service level.