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.
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
| 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 |
Results of compute_stock_metrics for all 10 products in Step 08 (real run):
| SKU | Product | Stock | Z | Safety stock | Desired stock | Order now |
|---|---|---|---|---|---|---|
| SKU-001 | Wireless Headphones | 150 | 2.05 | 18.79 | 186.79 | 37 |
| SKU-002 | Paracetamol 500mg | 800 | 2.33 | 30.82 | 310.82 | 0 |
| SKU-003 | Instant Noodles 12-pack | 300 | 1.65 | 33.00 | 353.00 | 53 |
| SKU-004 | Steel Rod 10mm | 300 | 1.41 | 15.83 | 225.83 | 0 |
| SKU-005 | Laptop 15-inch | 50 | 2.33 | 12.76 | 102.76 | 53 |
| SKU-006 | Vitamin C Tablets | 600 | 1.88 | 23.78 | 273.78 | 0 |
| SKU-007 | Shampoo 400ml | 900 | 1.65 | 29.52 | 329.52 | 0 |
| SKU-008 | Copper Wire 2.5mm | 150 | 1.28 | 14.66 | 224.66 | 75 |
| SKU-009 | Bluetooth Speaker | 120 | 1.75 | 11.14 | 119.14 | 0 (just barely) |
| SKU-010 | Flour 5kg | 2000 | 1.65 | 57.16 | 507.16 | 0 |
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
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
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.
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: NoneStep 02 — Embeddings basics
TODO 1 — Embed the query, score it against every passage, and return the top k
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.
| Question | Expected #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
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)
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.
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
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
result = chain.invoke(params)
invoke(params) fills {sku_id}, {lead_time_days} and the other blanks from the dict keys with the same names.
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 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
TODO 1 — Search the collection and return the passages as a bullet list ("- passage" per line)
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
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
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.
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
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
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.
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)
@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)
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.
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})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.
check_same_thread=False: Gradio answers each chat message in a worker thread, and SQLite would otherwise refuse to be used from a different thread.chat_handlercatches errors and shows a friendly message instead of crashing the app.- Every question is answered on its own (the chat
historyis not sent to the LLM). Making it remember is a stretch challenge.
Pipeline (Step 07) vs Agent (Steps 06 and 08)
| Pipeline | Agent | |
|---|---|---|
| Who decides the steps? | You, in code | The LLM, at run time |
| Predictable? | Yes, same steps every time | Less, it may take different paths |
| Handles new kinds of questions? | No, only the flow you wrote | Yes: "list", "compare", "most at risk"... |
| Cost and speed | Fixed number of LLM calls | Varies with the question |
| Use it when | The task is always the same (nightly reorder report) | Users ask open questions (chat assistant) |
Answers to "Think about it"
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.
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.
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.
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.
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.
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 see | Fix |
|---|---|
sqlite3.OperationalError: no such column | Check the column names and the table nicknames (p. / s.) in your SQL. |
chromadb ... Collection inventory_kb already exists | Only 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 {...} variable | Every {name} in a prompt must be a key in the dict you pass to invoke. |
| The agent answers without calling tools | Make 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 thread | Keep 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. |