Build Your First Factory AI Agent: A Read-Only Shift Report Tutorial (With Code)

November 17, 2026
Build Your First Factory AI Agent: A Read-Only Shift Report Tutorial (With Code)

At the end of every shift, someone has to turn hundreds of readings into a few useful sentences: which machine is drifting, which one is fine, what happened that the next shift should know. It is a perfect first job for an AI agent. It is repetitive, the data already exists, and a wrong answer is cheap because a supervisor reads the report before anyone acts on it.

This tutorial builds that agent for a small precision grinding line. It is about 120 lines of Python. It can read measurements and events, work out drift, and draft a report. It cannot change anything on the floor, by design.

If you have not built an agent before, our general getting-started guide for AI agents covers the concepts. Here we go straight to a factory example.

Honest scope. The data in this tutorial is synthetic, generated by a script included below. The agent loop is tested offline with a scripted stand-in for the model. We have not shown real model output, because it varies between runs and models. Treat this as a working skeleton to adapt, not a finished product.

What we are building

flowchart TD
    A["Measurement and event data"] --> B["Read-only tools"]
    B --> C["Agent loop with step limit"]
    C --> D["Model drafts shift report"]
    C --> E["Audit log of every tool call"]
    D --> F["Supervisor reviews and decides"]

Four pieces:

  1. Data. A CSV of diameter readings for two grinding machines (G1 and G2) over a 06:00 to 14:00 shift, plus a short log of alarms and downtime. The part is a shaft, 25.000 mm with a tolerance of plus or minus 0.005 mm.
  2. Tools. Four small functions the model may call. All are read-only.
  3. Loop. Ask the model, run the tools it requests, return results, repeat until it writes the report or hits the step limit.
  4. Audit log. Every tool call is written to a file the agent cannot edit through its tools.

Why read-only, and where it sits in your network

In a real plant, an agent that can write to a controller is a safety question, not a software feature. So the first agent should never be connected to PLCs, machine controllers or anything on the control network.

A safer pattern is to let the agent read from a copy of the data: an export file, a replica database or a historian view in the IT zone. If the agent is wrong, confused or manipulated by text inside a data field, the worst outcome is a bad report. Our OT remote access checklist covers the network side of this in more detail.

Step 1: Project setup

mkdir factory-agent && cd factory-agent
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic
export ANTHROPIC_API_KEY=your-key   # never hard-code keys or commit them

We use Anthropic’s Python SDK and its tool-use feature here, but the structure (tools, loop, step limit, log) is the same in any SDK. Check your own organisation’s approved model and update the AGENT_MODEL setting accordingly.

Step 2: Generate demo data

Save as make_data.py and run python make_data.py. It writes data/measurements.csv (480 readings) and data/events.csv (3 events). Machine G1 is stable. Machine G2 has a worn wheel and its diameter creeps upward by 0.02 micrometres per part.

"""Generate synthetic shift data for a two-machine grinding line (demo only)."""
import csv, random
from datetime import datetime, timedelta

random.seed(7)
NOMINAL, TOL = 25.000, 0.005          # shaft diameter 25.000 +/- 0.005 mm
START = datetime(2026, 11, 17, 6, 0)  # 06:00 to 14:00 shift

rows = []
for machine, drift_per_part in (("G1", 0.0), ("G2", 0.00002)):
    for i in range(240):              # one part every 2 minutes
        t = START + timedelta(minutes=2 * i)
        d = NOMINAL + drift_per_part * i + random.gauss(0, 0.0012)
        rows.append([t.isoformat(), machine, "LOT-A17" if i < 120 else "LOT-A18",
                     f"{machine}-{i:04d}", f"{d:.4f}", "W-12" if machine == "G1" else "W-07"])
rows.sort()
with open("data/measurements.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["timestamp", "machine", "lot", "part_id", "diameter_mm", "wheel_id"])
    w.writerows(rows)

events = [
    ("2026-11-17T06:00:00", "G2", "wheel_dress", "Wheel W-07 dressed at shift start"),
    ("2026-11-17T09:12:00", "G1", "alarm", "Coolant level low, cleared by operator"),
    ("2026-11-17T10:30:00", "G1", "downtime", "Stopped 12 min for fixture change"),
]
with open("data/events.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["timestamp", "machine", "type", "note"])
    w.writerows(events)
print("wrote", len(rows), "measurements and", len(events), "events")

Step 3: Write the tools

Save as tools.py. Three design choices matter more than the maths:

  • An allowlist of machines. The model cannot ask for anything outside MACHINES.
  • Capped parameters. The drift window is clamped to 10 to 200 parts, so the model cannot request unreasonable amounts of data.
  • Clear descriptions. The model reads each description to decide when to use the tool.
"""Read-only tools for the shift-report agent. No tool here can change anything."""
import csv, math, statistics
from pathlib import Path

DATA = Path(__file__).parent / "data"
NOMINAL, TOL = 25.000, 0.005
MACHINES = {"G1", "G2"}                # allowlist: the agent can only see these

def _rows(machine):
    if machine not in MACHINES:
        raise ValueError(f"unknown machine {machine!r}; allowed: {sorted(MACHINES)}")
    with open(DATA / "measurements.csv", newline="") as f:
        return [r for r in csv.DictReader(f) if r["machine"] == machine]

def list_machines():
    return sorted(MACHINES)

def get_measurement_summary(machine):
    xs = [float(r["diameter_mm"]) for r in _rows(machine)]
    mean, sd = statistics.fmean(xs), statistics.stdev(xs)
    usl, lsl = NOMINAL + TOL, NOMINAL - TOL
    cpk = min(usl - mean, mean - lsl) / (3 * sd)
    out = sum(1 for x in xs if x > usl or x < lsl)
    return {"machine": machine, "parts": len(xs), "mean_mm": round(mean, 4),
            "stdev_mm": round(sd, 4), "min_mm": min(xs), "max_mm": max(xs),
            "out_of_tolerance": out, "cpk": round(cpk, 2)}

def get_drift(machine, window=120):
    window = max(10, min(int(window), 200))          # cap what the model can ask for
    xs = [float(r["diameter_mm"]) for r in _rows(machine)][-window:]
    n = len(xs)
    xbar, ybar = (n - 1) / 2, statistics.fmean(xs)
    slope = (sum((i - xbar) * (x - ybar) for i, x in enumerate(xs))
             / sum((i - xbar) ** 2 for i in range(n)))   # mm per part
    last = statistics.fmean(xs[-5:])
    limit = NOMINAL + TOL if slope > 0 else NOMINAL - TOL
    parts_left = None if abs(slope) < 1e-7 else max(0, math.floor((limit - last) / slope))
    return {"machine": machine, "window": n, "slope_um_per_part": round(slope * 1000, 3),
            "recent_mean_mm": round(last, 4), "parts_until_limit": parts_left}

def get_events(machine=None):
    if machine is not None and machine not in MACHINES:
        raise ValueError(f"unknown machine {machine!r}")
    with open(DATA / "events.csv", newline="") as f:
        return [r for r in csv.DictReader(f) if machine in (None, r["machine"])]

FUNCS = {"list_machines": list_machines,
         "get_measurement_summary": get_measurement_summary,
         "get_drift": get_drift, "get_events": get_events}

SCHEMAS = [
    {"name": "list_machines", "description": "List the machines you may inspect.",
     "input_schema": {"type": "object", "properties": {}}},
    {"name": "get_measurement_summary",
     "description": "Shift statistics for one machine's shaft diameter: count, mean, "
                    "stdev, min, max, out-of-tolerance count and Cpk. Tolerance is 25.000 +/- 0.005 mm.",
     "input_schema": {"type": "object", "properties": {"machine": {"type": "string"}},
                      "required": ["machine"]}},
    {"name": "get_drift",
     "description": "Trend of recent diameters for one machine: slope in micrometres per part "
                    "and estimated parts left before a tolerance limit is reached.",
     "input_schema": {"type": "object", "properties": {"machine": {"type": "string"},
                      "window": {"type": "integer", "description": "recent parts to fit, 10-200"}},
                      "required": ["machine"]}},
    {"name": "get_events",
     "description": "Alarms, downtime and wheel-dress events logged this shift. Machine optional.",
     "input_schema": {"type": "object", "properties": {"machine": {"type": "string"}}}},
]

Step 4: Write the agent loop

Save as agent.py. Notice what is not in the tool list: nothing writes, deletes, sends or reaches the network.

"""Shift-report agent: reads line data through read-only tools and drafts a report."""
import json, os, time
import anthropic
from tools import FUNCS, SCHEMAS

MODEL = os.environ.get("AGENT_MODEL", "claude-sonnet-5-5")   # check your approved model name
MAX_STEPS = 8
SYSTEM = (
    "You are a shift-report assistant for a precision grinding line. "
    "You can only read data through the tools provided. You cannot change machines, "
    "settings or records, and you must never claim that you did. "
    "Quote numbers exactly as the tools return them. If data is missing, say so. "
    "Write a short report: one summary line, one section per machine, then a list of "
    "items a human should check. Recommendations are suggestions for the supervisor."
)

def log(entry):                                   # append-only audit trail
    with open("audit.jsonl", "a") as f:
        f.write(json.dumps({"ts": time.time(), **entry}) + "\n")

def run(prompt, client=None):
    client = client or anthropic.Anthropic()      # reads ANTHROPIC_API_KEY from the environment
    messages = [{"role": "user", "content": prompt}]
    for step in range(MAX_STEPS):                 # hard step limit = loop breaker
        resp = client.messages.create(model=MODEL, max_tokens=1500, system=SYSTEM,
                                      tools=SCHEMAS, messages=messages)
        messages.append({"role": "assistant", "content": resp.content})
        if resp.stop_reason != "tool_use":
            return "".join(b.text for b in resp.content if b.type == "text")
        results = []
        for block in resp.content:
            if block.type != "tool_use":
                continue
            try:
                out = FUNCS[block.name](**block.input)   # only functions in the allowlist
                log({"step": step, "tool": block.name, "input": block.input, "ok": True})
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": json.dumps(out)})
            except Exception as e:                       # return errors to the model, never crash
                log({"step": step, "tool": block.name, "input": block.input, "error": str(e)})
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": f"error: {e}", "is_error": True})
        messages.append({"role": "user", "content": results})
    return "Stopped: step limit reached. A human should review audit.jsonl."

if __name__ == "__main__":
    print(run("Prepare the shift report for the 06:00-14:00 shift on 2026-11-17."))

Three safety habits are built into this short file:

  • MAX_STEPS stops a stuck loop.
  • Tool errors go back to the model as messages instead of crashing the program, so a bad request (for example an unknown machine) is handled calmly.
  • Every call, successful or not, is appended to audit.jsonl.

Step 5: Test it offline, with no API key

A model call costs money and gives different output each time, so test the parts you control first. This test drives the real loop with a scripted fake model. Save as test_agent.py:

"""Offline test: a scripted fake model drives the real loop, no API key needed."""
import json, os
from types import SimpleNamespace as NS
import agent, tools

# 1) tools behave as expected on the synthetic data
for m in ("G1", "G2"):
    print(tools.get_measurement_summary(m)); print(tools.get_drift(m))
assert tools.get_drift("G1")["parts_until_limit"] is None or tools.get_drift("G1")["parts_until_limit"] > 500
assert tools.get_drift("G2")["slope_um_per_part"] > 0.012
try: tools.get_drift("G9"); raise SystemExit("allowlist failed")
except ValueError: pass

# 2) loop: scripted model calls two tools, then answers; plus a bad call it must survive
script = iter([
    NS(stop_reason="tool_use", content=[NS(type="tool_use", id="1", name="get_drift", input={"machine": "G2"}),
                                         NS(type="tool_use", id="2", name="get_drift", input={"machine": "G9"})]),
    NS(stop_reason="end_turn", content=[NS(type="text", text="REPORT OK")]),
])
client = NS(messages=NS(create=lambda **kw: next(script)))
if os.path.exists("audit.jsonl"): os.remove("audit.jsonl")
assert agent.run("test", client) == "REPORT OK"
lines = [json.loads(l) for l in open("audit.jsonl")]
assert lines[0]["ok"] and "error" in lines[1]
print("audit:", len(lines), "entries; loop test passed")

# 3) step limit: a model that never stops must be cut off
loop = NS(messages=NS(create=lambda **kw: NS(stop_reason="tool_use",
        content=[NS(type="tool_use", id="x", name="list_machines", input={})])))
assert agent.run("test", loop).startswith("Stopped")
print("step limit passed")

Run python test_agent.py. The test checks that the tools compute sensible numbers, that an unknown machine is rejected, that a bad tool call is logged and survived, and that a model that never stops is cut off at the step limit.

Step 6: Run it for real

python agent.py

Before reading the model’s report, look at what the tools returned on our synthetic data, because the report should agree with these numbers:

Machine Parts Mean (mm) Out of tolerance Cpk Trend (µm per part) Parts until limit
G1 240 25.0001 0 1.36 about 0 more than 7,000
G2 240 25.0024 14 0.47 +0.016 about 50

A good report flags G2 first: 14 parts outside tolerance, a rising trend and roughly 50 parts (about 100 minutes at one part every two minutes) before the upper limit, and it should mention the wheel-dress event logged at the start of the shift. It should call G1 healthy and mention the coolant alarm and the 12-minute downtime as context.

Then check the report against the tool results yourself. If the report states a number the tools did not return, that is the first bug to fix.

What to be careful about

  • Cpk is only meaningful on a stable process. G2 is drifting, so its Cpk is a rough indicator, not a capability claim. Make sure your prompt and your supervisors understand that.
  • Drift estimates depend on the window. In our test, a 60-part window gave a noisy slope and a 120-part window was steadier. Choose the window with your quality engineer and test it on real history.
  • The model should not do arithmetic. That is why the tools compute the statistics and the model only describes them.
  • Data fields are untrusted text. If a note field in a real system contains instructions, the model may read them as commands. Keep tools narrow and keep write access out of reach, so even a fooled model cannot act.

From demo to plant: a checklist

  1. Replace the CSV with a read-only connection to a replica, export or historian view. Keep the same tool names, so the agent code does not change.
  2. Give the agent its own account with read-only rights on exactly the data it needs.
  3. Compare against the manual report for a few weeks in shadow mode. Measure how often the supervisor changes the draft.
  4. Keep the audit log somewhere the agent cannot change, and set a retention period.
  5. Decide where the model runs. If measurement data is confidential, consider a model hosted inside your own network. We cover that in our local LLM assessment.
  6. Add actions last, and one at a time. For example, "create a maintenance ticket" can be a tool that needs a recorded human approval before it runs.
  7. Name an owner on the production side who decides whether the report is good enough.

Extend it

  • Add a get_wheel_history tool so the agent can say how many parts a wheel has made since its last dress.
  • Add a lot-level tool that lists readings for one lot, which helps answer traceability questions.
  • Add a second agent only if a separate task really needs it, such as one that prepares customer inspection reports.

Where Simplico fits

This tutorial shows the shape of the idea. In a real plant, most of the work is upstream: getting measurements off gauges and machines of different ages, tying each reading to a lot, tool and operator, and keeping that data on a network zone you control. That is what our MES, measurement-integration and device-interface work does for precision manufacturers, including long-running delivery for Japanese-affiliated plants. If you would like to explore a read-only agent on top of your own line data, write to hello@simplico.net with the subject "Factory agent" and a short description of what you measure today. We will tell you what we would connect first. This post is educational and promises no particular result.

FAQ

Do I need a big model to do this?
Not necessarily. The tools do the calculation and the model mostly decides which tools to call and writes the summary. Test a smaller or locally hosted model on your example data before assuming you need the largest one.

Can the agent adjust the machine when it sees drift?
Technically it could be given a tool for that, but we advise against it for a first agent. Adjusting a machine is a safety and quality decision. Start with a report that tells a human, then discuss any action with your engineers, safety staff and the machine vendor.

Why not just write a script that prints the summary?
For fixed statistics, a script is the right answer. The agent earns its place when the useful report depends on what it finds, for example linking a drift to an event in a log, or deciding which extra data to look up.

Is Python required?
No. The pattern works in any language the SDK supports. Python is used here because it is common in factory data work.

How do I know the report is right?
Compare it with a human report on the same shift, check every number against the tool outputs, and keep a human reviewer until the data shows that review is rarely needed.

Sources

All numbers in this tutorial come from the synthetic data produced by make_data.py above, and the tool outputs and offline tests were run on that data. No external statistics are used.

Ready to talk about your project?

Share goals and constraints. We'll assemble architects and engineers to move fast with you.

Get in touch