An analytical agent that answers business questions about Saudi retail sales in Arabic or English. It writes its own SQL, reads its own errors, corrects itself, and does not state a number it did not measure.
agent.pythe loop, language routing, turn and token guardsdb_tools.pytool definitions, business rules, four safety layersnoortrade.dbSQLite, opened read-onlyStateless. No data access and no code execution. The model never touches the database: it proposes SQL, and the application decides whether to run it.
for turn in range(1, MAX_TURNS + 1):
response = client.messages.create(..., tools=TOOLS, messages=messages)
if response.stop_reason != "tool_use":
return final_text # (a) done
messages.append({"role": "assistant", "content": response.content})
tool_results = [ # (b) run tools, feed results back
{"type": "tool_result", "tool_use_id": b.id,
"content": execute_tool(b.name, b.input)}
for b in response.content if b.type == "tool_use"
]
messages.append({"role": "user", "content": tool_results})| 1 | Reject INSERT / UPDATE / DELETE / DROP / ALTER / PRAGMA |
| 2 | Require the statement to start with SELECT or WITH |
| 3 | Reject an embedded ; (one statement per call) |
| 4 | Read-only connection enforced by SQLite itself (mode=ro) |
SELECT City, ROUND(SUM(Gross_Profit_SAR),2) AS total_profit FROM v_sales WHERE substr(Order_Date,1,4)='2024' GROUP BY City ORDER BY total_profit DESC LIMIT 3
10. Gross_Profit_SAR ignores returns. For any profit question, compute BOTH
gross and net = SUM(Gross_Profit_SAR) - SUM(COALESCE(Refund_Amount,0)).
11. Report profit erosion: 100.0 * SUM(COALESCE(Refund_Amount,0))
/ SUM(Gross_Profit_SAR)Synthetic Saudi retail dataset: 8,020 orders, 2,000 customers, 34 products, 400 returns, 8 cities and 3 channels (App, Online, Store), 2022–2024. A build script loads it into SQLite, adds six indexes and creates one joined view, so the model has fewer joins to get wrong.
'Riyadh ' and 'Riyadh' as different values. Uncleaned, the agent reported Riyadh revenue short by SAR 195,637. The build script strips all text columns.| Self-correction | Bad column → SQL error → corrected query → answer |
| Turn guard | A model that loops forever stops at exactly 8 turns |
| Unknown tool | Returns an error string and does not crash |
This is Unit 1 of a six-unit Agentic AI Engineering series: a foundation, not a production system.