Solution explainer · Share after the exercise

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

Step-by-step solutions for all 8 steps, the inventory maths with real numbers, and answers to the discussion questions.

For learners, after the exerciseSteps 01 – 08
On this page
  1. The finished system in one picture
  2. The maths with one real example
  3. Step 01 · 02 · 03 · 04 · 05 · 06 · 07 · 08
  4. Pipeline vs agent
  5. Answers to "Think about it"
  6. Common errors

The finished system in one picture

Data side

SQLite: 3 tables (inventory, lead_time, demand), 10 products. Exact facts.

ChromaDB: 13 short notes (formulas, category rules, best practices), embedded with all-MiniLM-L6-v2. Advice and context.

Brain side

LLM (gpt-6-luna): understands the question, decides which tool to call, writes the answer.

Tools: db_lookup, list_available_skus, compute_stock_metrics. Facts and maths, never guessed.

Usertypes in Gradio chat
→
RAG3 relevant notes → system prompt
→
Agent loopLLM ↔ tools until done
→
Answerquantity, urgency, why

Golden rule of this design: facts come from the database, maths comes from Python, knowledge comes from retrieval, and the LLM only does the reasoning and the talking.

The maths with one real example

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

Results of compute_stock_metrics for all 10 products in Step 08 (real run):

SKUProductStockZSafety stockDesired stockOrder now
SKU-001Wireless Headphones1502.0518.79186.7937
SKU-002Paracetamol 500mg8002.3330.82310.820
SKU-003Instant Noodles 12-pack3001.6533.00353.0053
SKU-004Steel Rod 10mm3001.4115.83225.830
SKU-005Laptop 15-inch502.3312.76102.7653
SKU-006Vitamin C Tablets6001.8823.78273.780
SKU-007Shampoo 400ml9001.6529.52329.520
SKU-008Copper Wire 2.5mm1501.2814.66224.6675
SKU-009Bluetooth Speaker1201.7511.14119.140 (just barely)
SKU-010Flour 5kg20001.6557.16507.160

Step 01 — SQLite basics

Why a SQL database? Stock numbers are exact facts that change every day. They belong in a table, not in a prompt and not in a vector store.

TODO 1 — Write a JOIN query that returns sku_id, sku_name, stock, lead_time_days, supplier_name for every product

Solution for TODO 1
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()

JOIN ... ON s.sku_id = p.sku_id glues each product row to the supplier row with the same sku_id. p and s are short nicknames for the tables.

TODO 2 — Fetch ONE product (joined with its supplier) by sku_id; return it as a dict, or None if not found

Solution for TODO 2
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 "
    "WHERE UPPER(p.sku_id) = UPPER(?)",
    (sku_id,),
).fetchone()
return dict(row) if row else None

The ? placeholder lets SQLite insert the value safely (never build SQL with f-strings: that opens the door to SQL injection). UPPER(...) on both sides makes the lookup case-insensitive.

Output (real run)
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

Lookup sku-002: {'sku_id': 'SKU-002', 'sku_name': 'Paracetamol 500mg', 'stock': 800, 'lead_time_days': 7, 'supplier_name': 'MedSupply Co'}
Lookup SKU-999: None

Step 02 — Embeddings basics

TODO 1 — Embed the query, score it against every passage, and return the top k

Solution for TODO 1
qv = model.encode(query, normalize_embeddings=True)
scores = passage_vectors @ qv              # one score per passage
ranked = np.argsort(scores)[::-1][:k]      # biggest first
return [(float(scores[i]), PASSAGES[i]) for i in ranked]

normalize_embeddings=True makes every vector length 1. Then cosine similarity is just the dot product, and passage_vectors @ qv scores all six passages in one line (a 6×384 matrix times a 384 vector = 6 scores). np.argsort gives positions sorted from smallest to largest, so [::-1] flips it to largest first.

QuestionExpected #1 passage
How do I calculate safety stock?Safety Stock = Z-score * demand_std_dev * sqrt(lead_time_days)
What should I know about electronics inventory?Electronics: lead times 14-30 days, high obsolescence risk.
Tell me about demand patterns for consumer goods.FMCG: short lead times 3-7 days, high steady demand.

The third one is the interesting one: the question says consumer goods, the passage says FMCG, and no words overlap. The embedding model still knows they mean the same thing. (Exact scores vary slightly between machines.)

Step 03 — ChromaDB retrieval

Step 02 kept vectors in a numpy array. A vector database stores the text, the vector and tags together, searches fast even with millions of rows, and can filter by tag.

TODO 1 — Embed every text and add ids, vectors, texts and metadata to the collection

Solution for TODO 1
vectors = embed.embed_documents([d["text"] for d in docs])
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],
)

Four parallel lists, matched by position: the 1st id goes with the 1st vector, the 1st text and the 1st tag.

TODO 2 — Embed the query and search the collection (apply the filter only if one is given)

Solution for TODO 2
qv = embed.embed_query(query)
kwargs = {"query_embeddings": [qv], "n_results": n}
if where:
    kwargs["where"] = where
results = collection.query(**kwargs)
return results["documents"][0]

where={"topic": "formula"} works like SQL WHERE topic = 'formula': Chroma searches by meaning, but only inside matching rows. The results come back as a list per query, so ["documents"][0] takes the first (and only) query's list.

Output (real run; the order of the two lines may differ)
Collection has 8 documents

=== Query: 'how to calculate stock' (formulas only) ===
 • 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%.

The filtered search returns only 2 notes even though we asked for 3, because only 2 notes have the formula tag.

Step 04 — Your first LLM chain

TODO 1 — Build the chain: prompt -> llm -> StrOutputParser

Solution for TODO 1
chain = prompt | llm | StrOutputParser()

Read the pipe | as "then": fill the prompt, then send it to the LLM, then turn the reply into a plain string. This is LangChain's LCEL (LangChain Expression Language).

TODO 2 — Run the chain with this SKU's parameters and print the result

Solution for TODO 2
result = chain.invoke(params)

invoke(params) fills {sku_id}, {lead_time_days} and the other blanks from the dict keys with the same names.

Example output for SKU-001 (the LLM's working varies; the Python check line is exact)
Safety Stock = 2.05 × 2 × √21 ≈ 2.05 × 2 × 4.583 ≈ 18.79
Desired Stock = (8 × 21) + 18.79 = 168 + 18.79 = 186.79

DESIRED_STOCK: 186.79

[Python check] safety stock = 18.79, desired stock = 186.79
The lesson of this step

The LLM usually gets close, but square roots and decimals are where it slips (for example writing √21 ≈ 4.6 and ending at 186.86). For inventory, money or medicine, "usually close" is not acceptable. That is why Step 06 moves every calculation into Python tools.

Step 05 — RAG chain

Retrievefind 3 notes in ChromaDB
→
Augmentpaste them into {rag_context}
→
GenerateLLM answers using them

TODO 1 — Search the collection and return the passages as a bullet list ("- passage" per line)

Solution for TODO 1
qv = embed.embed_query(query)
res = col.query(query_embeddings=[qv], n_results=n)
return "\n".join(f"- {c}" for c in res["documents"][0])

We turn the notes into one bullet-list string because a prompt is just text.

TODO 2 — Run the RAG chain: pass all SKU fields AND the retrieved context

Solution for TODO 2
answer = rag_chain.invoke({**sku, "rag_context": context})

{**sku, "rag_context": context} makes a new dict with every SKU field plus one extra key, so the prompt can fill {rag_context} too.

Without RAG (typical)With RAG (typical)
General advice: "monitor demand, keep a buffer, review regularly". Uses the retrieved notes: names the 99%+ service level for pharma, FIFO and expiry dates, and the safety-stock formula with Z = 2.33.

The retrieved notes are usually the pharma rule, the safety-stock formula and the 95% → 99% service-level note (order can vary). Same LLM, same question, but the RAG answer is specific to our business rules, because we gave it our rules.

Step 06 — Tool calling with an agent loop

TODO 1 — One turn of the agent loop

Solution for TODO 1
response = llm.invoke(messages)
messages.append(response)

# No tool calls -> the LLM is ready to answer
if not response.tool_calls:
    return response.text  # .text = the answer as plain text

# Run every tool the LLM asked for, then go round the loop again
for tc in response.tool_calls:
    result = TOOL_MAP[tc["name"]].invoke(tc["args"])
    print(f"  [tool] {tc['name']}({tc['args']}) -> {result}")
    messages.append(ToolMessage(content=json.dumps(result), tool_call_id=tc["id"]))

Each trip round the loop is one "think → act → observe" cycle. The loop ends when the LLM replies with no tool calls (it has everything it needs). json.dumps turns the Python result (a dict or a number) into text, because messages carry text.

Example output (the [tool] lines and numbers are exact; the wording varies)
Q: Does SKU-005 need to be reordered? Show the reorder point.
  [tool] lookup_sku_stock({'sku_id': 'SKU-005'}) -> {'sku_id': '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}
  [tool] calculate_safety_stock({'demand_std_dev': 1.0, 'lead_time_days': 30, 'service_level_pct': 99}) -> 12.76
  [tool] calculate_reorder_point({'avg_daily_demand': 3, 'lead_time_days': 30, 'safety_stock': 12.76}) -> 102.76
A: Yes. SKU-005 (Laptop 15-inch) has 50 units, below its reorder point of 102.76 units
   (3/day × 30 days + 12.76 safety stock). Reorder now.

Notice the LLM chained the tools: it used the output of lookup_sku_stock as the input of calculate_safety_stock, then used that result in calculate_reorder_point. Three loop rounds, then the answer. Sometimes the LLM asks for two tools in the same round; the inner for loop handles that.

Step 07 — Multi-chain pipeline

TODO 1 — Build reorder_chain: a prompt that receives chain 1's explanation as {computation}, then llm, then a parser

Solution for TODO 1
reorder_prompt = ChatPromptTemplate.from_messages([
    ("system",
     "You are an inventory planning advisor.\n"
     "Reorder Quantity = max(0, Desired Stock - Current Stock), rounded up to whole units.\n"
     "State the quantity and whether an immediate reorder is needed, in under 80 words."),
    ("human",
     "SKU: {sku_id} | {sku_name}\n"
     "Current Stock: {current_stock}   Supplier: {supplier_name}\n\n"
     "Stock Computation:\n{computation}"),
])
reorder_chain = reorder_prompt | llm | StrOutputParser()

A second prompt with a {computation} slot. Whatever chain 1 writes is pasted there.

TODO 2 — Step 3 — run reorder_chain, feeding it chain 1's output, and print the recommendation

Solution for TODO 2
recommendation = reorder_chain.invoke({
    "sku_id": record["sku_id"],
    "sku_name": record["sku_name"],
    "current_stock": record["current_stock"],
    "supplier_name": record["supplier_name"],
    "computation": computation,   # <- chain 1's output becomes chain 2's input
})

This is the hand-off: chain 1's output becomes chain 2's input. Each chain has one small, focused job, which makes each prompt easier to write and test.

Example output, shortened (tool lines exact; chain text varies)
Processing SKU-001
[Tool] safety_stock_tool -> {'z_score': 2.05, 'safety_stock': 18.79, 'desired_stock': 186.79}
--- Chain 1: Stock Computation ---  (explanation ... ends with DESIRED_STOCK: 186.79)
--- Chain 2: Reorder Recommendation ---  Order 37 units of Wireless Headphones now (186.79 - 150 = 36.79, rounded up).

Processing SKU-005
[Tool] safety_stock_tool -> {'z_score': 2.33, 'safety_stock': 12.76, 'desired_stock': 102.76}
--- Chain 2: Reorder Recommendation ---  Order 53 units of Laptop 15-inch immediately (102.76 - 50 = 52.76, rounded up).

Step 08 — The full agent app

TODO 1 — Write the compute_stock_metrics tool (exact maths for one SKU)

Solution for TODO 1
@tool
def compute_stock_metrics(avg_daily_demand: float, demand_std_dev: float, lead_time_days: float,
                          service_level_pct: float, current_stock: float) -> dict:
    """
    Compute safety stock, desired stock level, and reorder quantity with exact arithmetic.
    Returns: z_score, safety_stock, desired_stock, reorder_quantity, reorder_needed.
    """
    z = Z_TABLE.get(round(service_level_pct), 1.65)
    safety_stock = round(z * demand_std_dev * math.sqrt(lead_time_days), 2)
    desired_stock = round(avg_daily_demand * lead_time_days + safety_stock, 2)
    reorder_quantity = max(0, math.ceil(desired_stock - current_stock))
    return {
        "z_score": z,
        "safety_stock": safety_stock,
        "desired_stock": desired_stock,
        "reorder_quantity": reorder_quantity,
        "reorder_needed": reorder_quantity > 0,
    }

One tool does all the maths for a SKU and returns everything as a dict. math.ceil rounds up, because you cannot order 36.79 headphones, and rounding down would leave you short.

TODO 2 — One turn of the agent loop (same as Step 06)

Solution for TODO 2
response = llm.invoke(messages)
messages.append(response)

if not response.tool_calls:
    return response.text  # .text = the answer as plain text

for tc in response.tool_calls:
    result = TOOL_MAP[tc["name"]].invoke(tc["args"])
    print(f"  [tool] {tc['name']}({tc['args']})")
    messages.append(ToolMessage(content=json.dumps(result, default=str), tool_call_id=tc["id"]))

The same loop as Step 06. The difference is in what goes into it: a system prompt with instructions plus the 3 most relevant knowledge notes (RAG), and MAX_STEPS = 15 because "Which SKUs are most at risk?" needs many lookups.

Terminal after asking: What is the reorder quantity for SKU-001? (real run)
Starting Inventory Planning Agent...
  10 SKUs in the database
  13 notes in the knowledge base
* Running on local URL:  http://127.0.0.1:7860

  [tool] db_lookup({'sku_id': 'SKU-001'})
  [tool] compute_stock_metrics({'avg_daily_demand': 8.0, 'demand_std_dev': 2.0, 'lead_time_days': 21.0, 'service_level_pct': 98.0, 'current_stock': 150.0})
Example chat answer (wording varies; the numbers come from the tools)
Reorder 37 units of SKU-001 (Wireless Headphones).
- Current stock: 150. Desired stock: 186.79 (168 for the 21-day lead time + 18.79 safety stock at 98% service level).
- Urgency: medium-high. With 21-day international lead times for electronics, order this week.
Things to notice in the code

Pipeline (Step 07) vs Agent (Steps 06 and 08)

PipelineAgent
Who decides the steps?You, in codeThe LLM, at run time
Predictable?Yes, same steps every timeLess, it may take different paths
Handles new kinds of questions?No, only the flow you wroteYes: "list", "compare", "most at risk"...
Cost and speedFixed number of LLM callsVaries with the question
Use it whenThe task is always the same (nightly reorder report)Users ask open questions (chat assistant)

Answers to "Think about it"

1. Did the LLM's number match the Python check?

Often close, sometimes off in the decimals, occasionally clearly wrong. LLMs predict likely text; they do not calculate. A small error times hundreds of SKUs means real money: lost sales or cash stuck in stock. Exact maths belongs in code.

2. What could only come from the retrieved notes?

Our business rules: "Pharma: 99%+ service level, strict FIFO, expiry dates" and the exact Z values. A general LLM may know similar ideas, but it cannot know your company's rules unless you give them.

3. Agent vs pipeline advantages?

Agent: flexible, handles questions you did not plan for. Pipeline: predictable, easy to test, fixed cost. Many real systems use a pipeline for the core flow and an agent only at the edges.

4. Why MAX_STEPS?

If the LLM keeps asking for tools (for example, a tool keeps returning an error and the LLM keeps retrying), the loop would never end, burning money and time. A step limit is a simple safety net.

5. Why only 3 notes, not all 13?

Fewer tokens = cheaper and faster. Irrelevant notes can also distract the LLM. With 13 notes you could send all of them, but a real knowledge base has thousands, so retrieval is the habit to build.

6. SKU-009 with 120 in stock and a desired stock of 119.14?

The formula says no reorder, but there is less than one unit of margin. A manager would want: upcoming sales or festival season, supplier reliability, minimum order size, and whether an order is already on its way. Tools give exact numbers; people still make the judgement call.

Common errors and fixes

You seeFix
sqlite3.OperationalError: no such columnCheck the column names and the table nicknames (p. / s.) in your SQL.
chromadb ... Collection inventory_kb already existsOnly happens if you run the creation twice in one session (for example in a notebook). Use client.get_or_create_collection(...), or restart.
KeyError: 'rag_context' or a missing {...} variableEvery {name} in a prompt must be a key in the dict you pass to invoke.
The agent answers without calling toolsMake the tool docstrings clearer and keep the system prompt rule "never do the maths yourself".
SQLite objects created in a thread can only be used in that same threadKeep check_same_thread=False in Step 08.
"Stopped: too many steps"The LLM kept calling tools. Print the [tool] lines to see which one keeps failing.