← Portfolio
GitHub ↗

NoorTrade Agent Core — AI Agent Built from Scratch

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.

PythonSQLiteAnthropic APITool useNo framework
Show:
Lines of agent code
~250
loop, tool dispatch, guards
Agent frameworks
0
no LangChain, every line debuggable
Safety layers
4
database opened read-only
Max turns
8
hard stop built into the loop
Orders in the dataset
8,020
synthetic Saudi retail, 2022–2024
Typical run
~12 s
2 turns · 1 query

Architecture

Local application

agent.pythe loop, language routing, turn and token guards
db_tools.pytool definitions, business rules, four safety layers
noortrade.dbSQLite, opened read-only
⇄HTTPS, text only. Sends the question, tool schema and query results. Receives text or a tool-call request.

Language model (Anthropic API)

Stateless. No data access and no code execution. The model never touches the database: it proposes SQL, and the application decides whether to run it.

The agent loop

1
AskThe question goes to the model together with the tool schema.
2
ProposeThe model replies with an answer or a request to run SQL, with a one-line purpose.
3
Guard and runThe application checks the SQL against the safety layers and runs it read-only.
4
Feed backResults or the error text return to the model. An error becomes a signal to fix the query.
5
StopThe loop ends on a final answer, or at 8 turns at most.
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})

Defense in depth: four layers

1Reject INSERT / UPDATE / DELETE / DROP / ALTER / PRAGMA
2Require the statement to start with SELECT or WITH
3Reject an embedded ; (one statement per call)
4Read-only connection enforced by SQLite itself (mode=ro)
Layers 1–3 are text filters and could in principle be worked around. Layer 4 makes the dangerous operation impossible, not merely disallowed.

Design decisions

1
Tools never raiseThey return the error as text, so the model can read it and retry inside the same loop.
2
A purpose field on every queryForces the model to state intent before acting and makes the trace readable.
3
Language belongs to the outputLogs, SQL and prompts stay in English; only the final answer is translated.

Case study: the failure that mattered

"Top 3 cities by profit in 2024?"
First run: the query the agent wrote
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
Arithmetically correct, analytically misleading. Gross profit ignores returns: 152 returned orders in 2024 carried SAR 86,380 of profit that never materialised.
The fix: two rules added to the tool description
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)
No model upgrade and no cleverer prompt. Cost of the fix: 865 extra input tokens, 583 output tokens, 3 seconds.
Second run: same question, same model
The agent surfaced Jeddah's return problem unprompted and recommended an action. Lesson: when an answer is arithmetically right but analytically incomplete, the defect is in the tool description, not the model.

Data, testing and roadmap

Dataset

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.

Data-quality catch: trailing spaces in City and Channel made SQL treat 'Riyadh ' and 'Riyadh' as different values. Uncleaned, the agent reported Riyadh revenue short by SAR 195,637. The build script strips all text columns.

Testing without spending tokens

Self-correctionBad column → SQL error → corrected query → answer
Turn guardA model that loops forever stops at exactly 8 turns
Unknown toolReturns an error string and does not crash
The API client is replaced by a scripted fake, so the loop mechanics are verified at zero cost.

Known limitations and what comes next

This is Unit 1 of a six-unit Agentic AI Engineering series: a foundation, not a production system.

Unit 3No conversational memory
Units 2 and 4SQL only, no documents
Unit 5No accuracy measurement
Unit 5No cost or latency ceiling
Unit 6CLI only, no auth or audit log
Unit 6Tool results are a prompt-injection surface
The most important gap is the missing evaluation harness. The agent answers with the same confidence whether it is right or wrong.