Hands-on exercises · Give to learners

Module 4 — Build an Inventory Planning Agent, Step by Step: Exercises

Hands-on exercise sheet. Try every TODO yourself before you see the solution.

For learnersAbout 2 hoursOpenAI API key needed (Steps 04–08)

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.

01 SQLdatabase
→
02 Embeddingsmeaning as numbers
→
03 ChromaDBvector store
→
04 LLM chainprompt | llm
→
05 RAGadd knowledge
→
06 Tools + loopexact maths
→
07 Pipelinechain of chains
→
08 Agent appall together

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:

WordPlain meaningExample (SKU-005, Laptop 15-inch)
SKUStock Keeping Unit: the ID of one productSKU-005
Current stockUnits on the shelf right now50 laptops
Lead timeDays between placing an order and receiving it30 days
Average daily demandUnits sold per day on average3 per day
Demand std devHow much daily sales jump around the average (standard deviation)1 per day (some days 2, some days 4)
Service levelHow sure you want to be that you will not run out before the delivery arrives99%
Z-scoreThe service level turned into a number from the statistics table. Higher = more caution99% → 2.33 (95% → 1.65)
Safety stockExtra buffer for bad days: Z × demand_std_dev × √lead_time2.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_stock3 × 30 + 12.76 = 102.76
Reorder quantityHow many to order now: max(0, desired − current), rounded up102.76 − 50 → 53 laptops
One sentence to remember

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.

TODO 1Write a JOIN query that returns sku_id, sku_name, stock, lead_time_days, supplier_name for every product
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_id ORDER BY p.sku_id
  • cur.execute(sql).fetchall() returns all rows
TODO 2Fetch ONE product (joined with its supplier) by sku_id; return it as a dict, or None if not found
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 or None
  • dict(row) turns a Row into a normal dict
You are done when the table prints 3 rows with the supplier names, 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.

TODO 1Embed the query, score it against every passage, and return the top k
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
You are done when each of the 3 questions prints 3 notes with scores, and How do I calculate safety stock? puts the Safety Stock formula first.

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.

TODO 1Embed every text and add ids, vectors, texts and metadata to the collection
Need a hint?
  • vectors = embed.embed_documents([d["text"] for d in docs])
  • collection.add(ids=[...], embeddings=vectors, documents=[...], metadatas=[...])
TODO 2Embed the query and search the collection (apply the filter only if one is given)
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]
You are done when the collection has 8 documents, and the "formulas only" search returns only the 2 formula notes.

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.

TODO 1Build the chain: prompt -> llm -> StrOutputParser
Need a hint?
  • LangChain joins steps with the pipe operator |
  • StrOutputParser() turns the LLM's message object into a plain string
TODO 2Run the chain with this SKU's parameters and print the result
Need a hint?
  • chain.invoke(params) fills every {variable} in the prompt from the dict
You are done when each SKU prints the LLM's step-by-step working ending with 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.

TODO 1Search the collection and return the passages as a bullet list ("- passage" per line)
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)
TODO 2Run the RAG chain: pass all SKU fields AND the retrieved context
Need a hint?
  • rag_chain.invoke({**sku, "rag_context": context}) ({**sku} copies every key of the dict)
You are done when you see the retrieved notes, then two answers. Write down one concrete difference between them.

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.

TODO 1One turn of the agent loop

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_calls is 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"])
You are done when question 2 (SKU-005) prints three [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.

TODO 1Build reorder_chain: a prompt that receives chain 1's explanation as {computation}, then llm, then a parser
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()
TODO 2Step 3 — run reorder_chain, feeding it chain 1's output, and print the recommendation
Need a hint?
  • reorder_chain.invoke({"sku_id": ..., "sku_name": ..., "current_stock": ..., "supplier_name": ..., "computation": computation})
  • The first four values come from `record`
You are done when both SKUs print the tool result, a Chain 1 explanation and a Chain 2 recommendation. SKU-001 should need about 37 units and SKU-005 about 53.

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.

TODO 1Write the compute_stock_metrics tool (exact maths for one SKU)
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_stock
  • reorder_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
TODO 2One turn of the agent loop (same as Step 06)
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"])
You are done when the browser chat answers list, What is the reorder quantity for SKU-001? (37 units) and Give me a full analysis for SKU-005. (53 units), and the terminal shows the [tool] calls.

Think about it

  1. Step 04: did the LLM's DESIRED_STOCK exactly match the Python check? Why is "close enough" not good enough here?
  2. Step 05: which parts of the RAG answer could only come from the retrieved notes?
  3. 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.
  4. Why does Step 06 have MAX_STEPS? What could happen without it?
  5. In Step 08, the agent only gets the 3 most relevant notes, not all 13. Why not send all of them every time?
  6. 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