Ask the Factory’s Data a Question, and See the Query That Answered It
A production manager at a large multi-site manufacturer, like the Volvo Penta, Scania and ABB plants in
AI-COMPETE and SMART, wants to know why energy per engine rose last month on line 2 and whether the sister plant
sees the same. The data team’s backlog is weeks long. This agent turns the question into
SQL or Python and validates the code before running it. It executes the code in a sandbox against a read-only
copy of the data, then returns a chart, a short finding and the full query trail that produced them.
ContextUniversity of Skövde · AI-COMPETE (Vinnova) & SMART (KK-stiftelsen) · 2026 · system design
ResultSystem design — architecture, security layers and an execution-accuracy evaluation plan. No usage figures are claimed yet.
What this page is. A system design for a use case from the industrial partners of AI-COMPETE and SMART. It is
not a report of a deployment at any partner. Figures marked target are release gates. They are not
measured results.
Stakeholder engagement · problem formulation
The data exists. The queue to query it is the problem.
Large manufacturers have data teams and data platforms. Their analysts are the bottleneck.
An established manufacturer collects everything: MES records of orders and stops, energy metering per line,
scrap and quality logs, and ERP costs, across several plants. The data platform and the analysts exist, but every
ad-hoc question joins their queue. “Which product variant drove the energy increase, and is it the same in
the other plant?” waits weeks, or it never gets asked.
Scale adds two problems that a single-site tool never meets. Plants define the same metric differently, so two
OEE figures may not be comparable. And thousands of potential users with different rights mean governance has
to sit in the architecture, not in a policy document.
Three requirements came before any feature:
Cannot damage anything. No query or script the model writes can change, delete or copy out
production data, whatever the user types.
Can be checked. Every number links to the exact query, the row count and the time of the
data it came from.
One definition per metric. “OEE”, “energy per unit” and
“line 2” mean the governed company definition, the same in every plant, not what a model
guesses.
Architecture · tool-calling agent
Generate, validate, execute in a sandbox, explain
The model writes code. Deterministic layers decide whether that code runs.
Two feedback loops let the agent repair its code. Neither of them can loosen a rule.
Ground the question. A semantic layer defines each metric once: OEE, energy per unit, scrap
rate, which tables they come from, and how lines and shifts are named in each plant. The agent gets the definitions that match
the question, not the whole schema.
Choose a tool. Lookups and aggregations go to SQL. Trends, decompositions and anything
statistical go to Python with pandas. The tools are typed function calls, and the choice is logged so it can be
evaluated like any other decision.
Validate the code. SQL is parsed with sqlglot and Python with the ast module.
Only single SELECT statements on allow-listed tables pass, and Python may import only an allow-listed set of
modules, with no file, network or subprocess access. A LIMIT is added when the query has none.
Execute in isolation. Each request gets a fresh sandbox (Azure Container Apps dynamic sessions,
or E2B), with no outbound network and with caps on CPU, memory and time. It connects through a pooled
connection to a read-only replica, or to a DuckDB snapshot for heavy analysis.
Explain. The result becomes a Vega-Lite chart, which is validated against its schema before it
is rendered, and a short written finding. The finding may cite only numbers that appear in the result set.
Guardrails · defence in depth
Assume the prompt is hostile, then make that not matter
Prompt instructions are not a security boundary. Each layer below holds even if the ones above it fail.
Layer
What it stops
Database role
The connection is read-only at the database level, so no write succeeds even if every other check misses it.
AST validation
DDL, DML, multiple statements, system catalogs and tables that are not allow-listed are rejected before execution.
Sandbox isolation
Python cannot reach the network, the host or another user’s session, and runaway code hits the time and memory caps.
Row-level scope
The user’s identity sets which sites and lines the replica returns, so the agent cannot query its way around permissions.
Data as data
Text inside the data, such as operator comments, is passed to the model as quoted values and never as instructions, which blocks indirect prompt injection.
Output limits
Row caps and aggregate-only exports stop the agent being used to copy tables out in bulk.
Context engineering
The schema is too big to send, and most of it is noise
Accuracy depends on which 2% of the schema the model sees.
Schema retrievalTable and column descriptions are embedded. Only the tables relevant to the
question are sent, with column types and a few sample values.
Metric definitionsIf the question mentions a defined metric, its canonical SQL is included
and the agent must build on it rather than reinvent it.
Verified examplesA few question–query pairs that analysts have approved, chosen by
similarity to the current question, act as worked examples.
Result summariesLarge results come back as shape, summary statistics and head rows. The
full result stays in the sandbox for the next step.
Evaluation
Graded by the answer the query returns, not by how the query looks
Two different queries can both be right. Only execution tells which ones are.
The benchmark is a set of real manager-style questions, each with a reference query written by an analyst. The
agent’s query is executed and its result set compared with the reference result. A red-team set of injection
and exfiltration prompts runs alongside it on every change.
Metric
How it is measured
Release gate (target)
Execution accuracy
Result set matches the reference result set
≥ 0.85
Unsafe execution
Red-team prompts that reach execution with a write, an off-list table or network access
0 (hard gate)
Finding faithfulness
Numbers in the written finding present in the result set, checked by code
1.00
Correct “can’t answer”
Questions the data cannot answer declined, with the missing data named
≥ 0.90
Latency, SQL path
p95, question to chart for lookups and aggregations
< 3 s
Latency, Python path
p95, question to chart for multi-step analyses
< 15 s
Full stack · production
Every answer comes with its receipts
A trail a sceptical controller can re-run.
Front endReact + TypeScript: the question, the chart and the finding, with a
“show your work” panel that holds the query, row count, data timestamp and a button to re-run it.
Back endFastAPI with streamed steps, a pooled connection manager (PgBouncer in front of
the replica), and caching of repeat queries keyed on the query text and the data version.
OperationsDocker, Entra ID sign-in and an audit log of every generated query and its
verdict. A good answer can be saved as a verified example, which improves the next one.
In the AI-COMPETE architecture this agent is the data tool for the others. The
planning copilot asks it for historical energy per batch, and the
robot-cell copilot for fault frequencies. Both get the same validation and
query trail.