原则:不要直连 MES 数据库
直连数据库耦合度高,MES 表结构一变 AI 就崩。正确做法是中间层解耦:MES 通过 API/消息队列暴露数据,智能体只与中间层交互。
Step 1:数据层——封装只读 API
让 MES 侧提供只读接口(或由集成团队封装):
# 中间层:封装 MES 只读接口(示例)
GET /api/v1/work-orders?status=IN_PROGRESS
GET /api/v1/work-orders/{id}
GET /api/v1/defects?date=today
POST /api/v1/audit-logs # 智能体动作留痕Step 2:事件驱动——用消息队列替代轮询
智能体每 10 秒轮询查待办是反面教材。改用消息队列订阅事件:
# 用 MQTT 订阅 MES 事件(Python 示例)
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
event = json.loads(msg.payload)
# {"type":"WORK_ORDER_CHANGED","order_id":"WO-1037","action":"APPROVE_REQUIRED"}
dispatch_to_agent(event)
client = mqtt.Client()
client.on_message = on_message
client.connect("mqtt.internal", 1883)
client.subscribe("mes/events/#")
client.loop_forever()Step 3:智能体编排——拆任务 + 人工确认
复杂任务用"拆解-执行-确认"模式,高风险动作必须人工确认:
# 智能体任务编排(伪代码)
def handle_work_order_changed(evt):
steps = agent.plan([
"读取工单详情",
"检查异常标记",
"生成处置建议",
"通知班组长确认" # 关键步骤:人工确认
])
for s in steps:
if s.need_confirm:
send_confirm(evt["order_id"], s.proposal) # 等待人工
else:
s.execute()
# 人工确认接口
POST /api/v1/confirmations/{id} # 批准/驳回异常处理:三道防线
① 关键操作(付款、删数据、改工艺)必须人工确认;
② API 失败自动重试 + 指数退避,连续失败转人工;
③ 所有智能体动作写审计日志,30 天内可回滚。
# 重试 + 退避示例
import time, requests
for attempt in range(3):
try:
r = requests.post(MES_API, json=payload, timeout=10)
r.raise_for_status()
break
except Exception as e:
if attempt == 2:
notify_human(f"MES 调用失败: {e}") # 转人工
time.sleep(2 ** attempt)集成前务必与 MES 厂商确认 API 能力与授权范围;敏感操作以人工确认兜底。