每个班次结束时,总要有人把几百个测量值整理成几句有用的话:哪台机床的尺寸在漂移,哪台正常,下一班需要知道什么。这正是 AI Agent 的理想第一份工作:重复性强,数据现成,而且出错的代价小,因为在任何人采取行动之前,主管都会先看报告。
本教程为一条小型精密磨削线做出这样的 Agent,约 120 行 Python。它可以读取测量值和事件,计算漂移,并起草报告;但它不能改动车间里的任何东西,这是刻意的设计。
如果你还没做过 Agent,我们有一篇通用的 AI Agent 入门指南讲解了基本概念。本文直接进入工厂案例。
范围说明 本文使用的数据是下面脚本生成的合成数据。Agent 循环是用一个按脚本行事的模拟模型在离线状态下测试的。我们没有展示真实模型的输出,因为每次运行、每个模型都不一样。请把它当作可以改造的可运行骨架,而不是成品。
我们要做什么
flowchart TD
A["测量数据与事件"] --> B["只读工具"]
B --> C["带步数上限的 Agent 循环"]
C --> D["模型起草班次报告"]
C --> E["记录每次工具调用的审计日志"]
D --> F["主管审阅并决定"]
共四个部分:
- 数据。 两台磨床(G1 和 G2)在 06:00 到 14:00 班次中的直径测量值 CSV,外加一份简短的报警和停机记录。零件是轴,尺寸 25.000 mm,公差正负 0.005 mm。
- 工具。 模型可以调用的四个小函数,全部只读。
- 循环。 询问模型,执行它请求的工具,返回结果,重复直到写出报告或达到步数上限。
- 审计日志。 每次工具调用都写入文件。
为什么只读,以及它在网络中的位置
在真实工厂里,能向控制器写入的 Agent 是安全问题,而不是软件功能。因此第一个 Agent 绝不应连接 PLC、机床控制器,或控制网络上的任何设备。
更安全的做法是让 Agent 读取数据的副本:导出文件、副本数据库,或 IT 区里的 historian 视图。即使 Agent 出错、困惑,或被数据字段里的文字误导,最坏的结果也只是一份不好的报告。网络层面的做法,我们的 OT 远程访问检查清单有更详细的说明。
第 1 步:项目准备
mkdir factory-agent && cd factory-agent
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic
export ANTHROPIC_API_KEY=your-key # 不要把密钥写进代码或提交到仓库
这里使用 Anthropic 的 Python SDK 及其工具调用功能,但结构(工具、循环、步数上限、日志)在任何 SDK 中都一样。请确认你所在组织批准的模型,并相应修改 AGENT_MODEL 设置。
第 2 步:生成演示数据
保存为 make_data.py 并运行 python make_data.py,会生成 data/measurements.csv(480 条读数)和 data/events.csv(3 个事件)。G1 很稳定;G2 的砂轮已磨损,直径每个零件上升 0.02 微米。
"""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")
第 3 步:编写工具
保存为 tools.py。有三个设计选择比数学更重要:
- 机床白名单。 模型无法请求
MACHINES之外的任何内容。 - 参数设上限。 漂移计算窗口被限制在 10 到 200 个零件,模型无法请求不合理的数据量。
- 清晰的描述。 模型靠阅读每个工具的描述来决定何时使用它。
"""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"}}}},
]
第 4 步:编写 Agent 循环
保存为 agent.py。注意工具列表里没有什么:没有任何工具会写入、删除、发送或访问网络。
"""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."))
这个短文件里内置了三个安全习惯:
MAX_STEPS会让卡住的循环停下来。- 工具错误以消息形式返回给模型,而不是让程序崩溃,所以错误请求(比如未知的机床)会被平稳处理。
- 每次调用,无论成功与否,都会追加到
audit.jsonl。
第 5 步:无需 API key 的离线测试
模型调用要花钱,而且每次输出都不同,所以先测试自己能控制的部分。这个测试用一个按脚本行事的假模型来驱动真实的循环。保存为 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")
运行 python test_agent.py。测试会检查:工具算出的数字是否合理,未知机床是否被拒绝,错误的工具调用是否被记录且程序继续运行,以及一个永不停止的模型是否在步数上限处被切断。
第 6 步:真正运行
python agent.py
在阅读模型的报告之前,先看看工具在我们的合成数据上返回了什么,因为报告应该与这些数字一致:
| 机床 | 零件数 | 平均值(mm) | 超差数 | Cpk | 趋势(µm/件) | 距上限的零件数 |
|---|---|---|---|---|---|---|
| G1 | 240 | 25.0001 | 0 | 1.36 | 约 0 | 超过 7,000 |
| G2 | 240 | 25.0024 | 14 | 0.47 | +0.016 | 约 50 |
一份好报告会先指出 G2:14 个零件超差,趋势上升,距离上限大约还有 50 个零件(按每两分钟一件算,约 100 分钟),并且应当提到班次开始时记录的砂轮修整事件。对 G1,它应说明状态良好,并把冷却液报警和 12 分钟停机作为背景提及。
然后,请你亲自把报告和工具结果逐项核对。 如果报告里出现了工具没有返回的数字,那就是第一个要修的 bug。
需要小心的地方
- 只有稳定的工艺,Cpk 才有意义。 G2 正在漂移,所以它的 Cpk 只是粗略指标,不是能力声明。要确保提示词和主管们都理解这一点。
- 漂移估计取决于窗口大小。 在我们的测试中,60 个零件的窗口给出的斜率波动较大,120 个零件的窗口更稳定。窗口要和质量工程师一起选定,并用真实历史数据测试。
- 不要让模型做算术。 这正是由工具计算统计量、模型只负责描述的原因。
- 数据字段是不可信的文本。 如果真实系统的备注字段里写着指令,模型可能把它当成命令。保持工具范围狭窄,并让写入权限远离 Agent,这样即使模型被骗,也无法行动。
从演示到工厂:检查清单
- 替换 CSV。 改为对副本、导出或 historian 视图的只读连接。保持工具名称不变,这样 Agent 代码就不必修改。
- 给 Agent 独立账号, 仅对所需数据拥有只读权限。
- 与人工报告对比。 用几周时间做影子模式,衡量主管修改草稿的频率。
- 保存审计日志, 放在 Agent 无法修改的地方,并设定保留期限。
- 决定模型运行在哪里。 如果测量数据涉密,可以考虑部署在自己网络内的模型。详见我们的本地 LLM 就绪度评估。
- 最后再加入动作,而且一次一个。 例如"创建维修工单"可以做成一个需要有记录的人工批准后才执行的工具。
- 指定生产侧负责人, 由他判断报告是否足够好。
延伸方向
- 增加
get_wheel_history工具,让 Agent 能说出砂轮自上次修整以来加工了多少零件。 - 增加批次级工具,列出某一批次的读数,有助于回答追溯类问题。
- 只有当确有独立任务时才增加第二个 Agent,比如专门准备客户检验报告的 Agent。
Simplico 能帮什么
本教程展示的是思路的雏形。在真实工厂里,大部分工作在上游:从不同年代的量具和机床上取出测量值,把每个读数关联到批次、刀具和操作员,并把数据放在你能控制的网络区域内。这正是我们的 MES、测量集成和设备接口工作为精密制造企业所做的事,其中包括为日资工厂长期交付的项目。如果你想在自己的产线数据之上尝试只读 Agent,请发邮件到 hello@simplico.net,主题写 "Factory agent",并简述你目前测量哪些内容。我们会告诉你建议先连接什么。本文仅供教育参考,不对任何结果作出承诺。
常见问题
需要很大的模型吗?
不一定。计算由工具完成,模型主要负责决定调用哪些工具并写出摘要。在断定需要最大的模型之前,先用你自己的样例数据试试较小的或自行托管的模型。
发现漂移时,Agent 可以自己调整机床吗?
如果给它相应的工具,技术上可以,但我们不建议第一个 Agent 这样做。调整机床是关乎安全和质量的决定。先从通知人的报告开始,再与工程师、安全人员和设备厂商讨论是否执行动作。
为什么不直接写个脚本打印摘要?
对固定的统计量,脚本就是正确答案。当有用的报告取决于调查发现的内容时,Agent 才物有所值,比如把漂移与日志中的事件关联起来,或决定还需要查哪些额外数据。
必须用 Python 吗?
不必。这个模式适用于 SDK 支持的任何语言。这里用 Python 是因为它在工厂数据工作中很常见。
怎么知道报告是否正确?
把它与同一班次的人工报告对比,逐项核对每个数字与工具输出,并保留人工审阅,直到数据表明几乎不再需要修改。
参考资料
本文所有数字均来自上面 make_data.py 生成的合成数据,工具输出和离线测试也都是在该数据上运行的。未使用任何外部统计数据。
最新文章
- 联网的工厂,敞开的大门:制造、物流与 OT 的六个安全难题与应对 November 16, 2026
- AI 在医学研究中到底能做什么?写给泰国与日本的现实检验 November 15, 2026
- 后台一旦宕机,充电桩会不会全部熄火?充电桩业主说的“OCPP 备用接入点”到底是什么 November 13, 2026
- 冷冻柜黑客事件蔓延全球:各国政府最新建议,以及联网控制器场所的远程访问自查清单 November 11, 2026
- 在泰国如何选直流快充桩:以阳光电源(Sungrow)5 款产品为例,以及硬件装好之后的软件工作 November 4, 2026
- 您的公司准备好迎接AI智能体了吗?关于审批、权限与审计留痕的20问自查清单 November 4, 2026