What you will build
A chat assistant for a store manager. Ask "Should I reorder SKU-002?" and it reads the database, does the exact maths with tools, uses inventory best practices from a small knowledge base (RAG), and replies in plain English, in a web chat window.
You build it in 8 small steps. Each step is its own file and adds one new idea.
Time: about 2 hours (about 15 minutes per step) · API key needed: Yes, from Step 04 on (Steps 01–03 run offline)
Inventory words in 2 minutes
Think of a quick-commerce dark store (the warehouse behind a 10-minute grocery app). It must never run out of fast-selling items, but it also cannot overstock because shelf space and cash are limited. These words describe that balance:
| Word | Plain meaning | Example (SKU-005, Laptop 15-inch) |
|---|---|---|
| SKU | Stock Keeping Unit: the ID of one product | SKU-005 |
| Current stock | Units on the shelf right now | 50 laptops |
| Lead time | Days between placing an order and receiving it | 30 days |
| Average daily demand | Units sold per day on average | 3 per day |
| Demand std dev | How much daily sales jump around the average (standard deviation) | 1 per day (some days 2, some days 4) |
| Service level | How sure you want to be that you will not run out before the delivery arrives | 99% |
| Z-score | The service level turned into a number from the statistics table. Higher = more caution | 99% → 2.33 (95% → 1.65) |
| Safety stock | Extra buffer for bad days: Z × demand_std_dev × √lead_time | 2.33 × 1 × √30 = 12.76 |
| Desired stock (= reorder point) | What you must have to survive until the delivery comes: avg_daily_demand × lead_time + safety_stock | 3 × 30 + 12.76 = 102.76 |
| Reorder quantity | How many to order now: max(0, desired − current), rounded up | 102.76 − 50 → 53 laptops |
Order enough to cover the days you wait for delivery, plus a buffer for bad days, minus what you already have.
Setup: 11-rag-setup/Setup_Guide_for_Learners.html. All files are in 1_GIVE_FIRST_Starter_Code. Run each one with python <file name>.
Step 01 — SQLite basics
File: 1_GIVE_FIRST_Starter_Code/01_sqlite_basics.py
Store products and suppliers in two tables linked by sku_id, and read them back together.
Need a hint?
- 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_idORDER BYp.sku_id cur.execute(sql).fetchall()returns all rows
Need a hint?
- Same JOIN as above
+ WHERE UPPER(p.sku_id) = UPPER(?)(so "sku-002" also works) cur.execute(sql, (sku_id,)).fetchone()returns one row orNonedict(row)turns a Row into a normal dict
Lookup sku-002 prints a dict (lower-case input still works) and Lookup SKU-999 prints None.Step 02 — Embeddings basics
File: 1_GIVE_FIRST_Starter_Code/02_embeddings_basics.py
Six short notes about inventory. For each question, find the 3 most relevant notes using embeddings and a dot product. No database, no LLM.
Need a hint?
qv = model.encode(query, normalize_embeddings=True)scores = passage_vectors @qv(the @ operator = dot product for every row at once)np.argsort(scores)[::-1][:k] =indexes of the k highest scores
Step 03 — ChromaDB retrieval
File: 1_GIVE_FIRST_Starter_Code/03_chromadb_retrieval.py
The same idea with a real vector database. Each note also gets a tag (formula, category, best_practice) so you can search inside one tag only.
Need a hint?
vectors = embed.embed_documents([d["text"] for d in docs])collection.add(ids=[...], embeddings=vectors, documents=[...], metadatas=[...])
Need a hint?
qv = embed.embed_query(query)collection.query(query_embeddings=[qv], n_results=n, where=where)- Only add the where filter when one is given
(it is None by default) - The texts are in
results["documents"][0]
Step 04 — Your first LLM chain
File: 1_GIVE_FIRST_Starter_Code/04_llm_chain.py
Put the formulas in a prompt and ask the LLM to calculate the desired stock. The script also computes the exact answer in Python so you can check the LLM's maths.
Need a hint?
- LangChain joins steps with the pipe operator
| StrOutputParser()turns theLLM'smessage object into a plain string
Need a hint?
chain.invoke(params)fills every{variable} inthe prompt from the dict
DESIRED_STOCK: ..., followed by the [Python check] line. Compare the two numbers.Step 05 — RAG chain
File: 1_GIVE_FIRST_Starter_Code/05_rag_chain.py
Ask the same question twice: once with a plain prompt, once with relevant notes retrieved from ChromaDB pasted into the prompt.
Need a hint?
qv = embed.embed_query(query); res = col.query(query_embeddings=[qv], n_results=n)- The passages are in
res["documents"][0] "\n".join(f"- {c}" for c in passages)
Need a hint?
rag_chain.invoke({**sku, "rag_context": context})({**sku} copies every key of the dict)
Step 06 — Tool calling with an agent loop
File: 1_GIVE_FIRST_Starter_Code/06_tool_calling_agent.py
The maths moves into Python tools. Some questions need several tools in a row (look up the SKU, then calculate safety stock, then the reorder point), so the LLM is called in a loop until it stops asking for tools.
This is the heart of every agent: think → act (tool) → observe (result) → repeat.
Need a hint?
response = llm.invoke(messages); messages.append(response)- If
response.tool_callsis empty-> return response.text (the final answer as plain text) - Otherwise run each tool:
TOOL_MAP[tc["name"]].invoke(tc["args"]) - and append
ToolMessage(content=json.dumps(result), tool_call_id=tc["id"])
[tool] lines in order: lookup_sku_stock, calculate_safety_stock (12.76), calculate_reorder_point (102.76).Step 07 — Multi-chain pipeline
File: 1_GIVE_FIRST_Starter_Code/07_multi_chain_pipeline.py
This time you fix the order of steps: database → maths tool → chain 1 explains → chain 2 recommends. Chain 2 reads chain 1's output.
Need a hint?
- System message:
"Reorder Quantity = max(0, Desired Stock - Current Stock). State the quantity and whether an immediate reorder is needed." - Human message must contain
{sku_id}, {sku_name}, {current_stock}, {supplier_name} and {computation} reorder_chain = reorder_prompt | llm | StrOutputParser()
Need a hint?
reorder_chain.invoke({"sku_id": ..., "sku_name": ..., "current_stock": ..., "supplier_name": ..., "computation": computation})- The first four values come from `record`
Step 08 — The full agent app
File: 1_GIVE_FIRST_Starter_Code/08_full_agent_app.py
Everything together: 3-table database with 10 products, a 13-note knowledge base, three tools, the agent loop and a Gradio chat window.
Need a hint?
- Inputs:
avg_daily_demand, demand_std_dev, lead_time_days, service_level_pct, current_stock (all float) z = Z_TABLE.get(round(service_level_pct), 1.65)safety_stock = Z * demand_std_dev * sqrt(lead_time_days);desired_stock = avg_daily_demand * lead_time_days + safety_stockreorder_quantity = max(0, math.ceil(desired_stock - current_stock))(whole units)- Return a dict with
z_score, safety_stock, desired_stock, reorder_quantity, reorder_needed
Need a hint?
response = llm.invoke(messages); messages.append(response)- No
tool_calls -> return response.text (the final answer as plain text) - Otherwise run each tool and append
ToolMessage(content=json.dumps(result, default=str), tool_call_id=tc["id"])
[tool] calls.Think about it
- Step 04: did the LLM's
DESIRED_STOCKexactly match the Python check? Why is "close enough" not good enough here? - Step 05: which parts of the RAG answer could only come from the retrieved notes?
- Step 06 vs Step 07: one lets the LLM choose the order of tools, the other has a fixed order. Give one advantage of each.
- Why does Step 06 have
MAX_STEPS? What could happen without it? - In Step 08, the agent only gets the 3 most relevant notes, not all 13. Why not send all of them every time?
- SKU-009 (Bluetooth Speaker) has 120 in stock and a desired stock of 119.14. The tool says "no reorder". Would you, as the store manager, still order? What extra information would you want?
Stretch challenges
- Step 03: Add a note about Diwali season demand with tag
best_practice, then search for "festival planning". - Step 06: Add a tool
days_until_stockout(sku_id)and ask "When will SKU-005 run out?" - Step 08: Ask "Which SKUs are most at risk of stockout?" and count the tool calls in the terminal. Then make the agent remember the chat by turning
historyinto messages.