一.什么是Durable Execution?
如果你想做一款类似 马里奥 的 闯关小游戏,那么在整个游戏中肯定要有保存点(或者终点),下一次复活直接从保存点开始出发。
然后你呢觉得在跑agent的时候也可以加入这个保存点,如果遇到断网或者关闭页面的话,下一次可以从保存的节点开始。
恭喜你!发明了Durable Execution!
二.代码示例
可以直接复制代码,感受Durable Execution的核心思想
import json
import osSTATE_FILE = "agent_state.json"def save_state(step, context):with open(STATE_FILE, "w") as f:json.dump({"step": step, "context": context}, f)def load_state():if not os.path.exists(STATE_FILE):return 0, {}with open(STATE_FILE, "r") as f:data = json.load(f)return data["step"], data["context"]def step1(context):print("Step 1: 获取天气数据")context["weather"] = "晴天"return contextdef step2(context):print("Step 2: 根据天气决定活动")# 模拟随机断电(运行时你可以改为故意让它失败)if context.get("weather") == "晴天":context["activity"] = "去公园"else:context["activity"] = "看电影"return contextdef step3(context):print("Step 3: 发送通知")print(f"最终活动: {context['activity']}")return contextdef main():start_step, context = load_state()steps = [step1, step2, step3]for i in range(start_step, len(steps)):print(f"\n--- 执行第 {i+1} 步 ---")try:# 模拟可能崩溃:你可以在这行前面加一个# if i == 2: raise Exception("断网")context = steps[i](context)save_state(i+1, context) # 保存下一步索引except Exception as e:print(f"执行失败: {e},状态已保存,下次继续")return # 退出,假装程序崩溃# 全部完成,清除状态文件if os.path.exists(STATE_FILE):os.remove(STATE_FILE)print("\n全部完成!")if __name__ == "__main__":main()
