Sub topic 2
Saving Checkpoints
Assume you know basic Python, JSON, file-system operations, and how an agent calls tools in a loop. A checkpoint is saved task state that lets a later process continue without repeating finished work.
Saving checkpoints
A useful checkpoint records facts such as:
- Completed step names
- Outputs created by each step
- Decisions and their reasons
- Errors or unresolved problems
- The next step to run
Save after each meaningful step, not only at the end. If the process stops after step three, the next run can start at step four.
Writing checkpoints atomically
A process can crash while writing a file. The checkpoint might then contain incomplete JSON. An atomic write makes the update appear all at once:
- Write the new content to a temporary file in the same directory.
- Flush it to disk.
- Replace the old checkpoint with
os.replace.
import json
import os
import tempfile
def save_checkpoint(path, state):
directory = os.path.dirname(os.path.abspath(path))
fd, temporary = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as file:
json.dump(state, file, indent=2)
file.flush()
os.fsync(file.fileno())
os.replace(temporary, path)
except BaseException:
if os.path.exists(temporary):
os.unlink(temporary)
raise
def load_checkpoint(path):
try:
with open(path, encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError:
return NoneKeeping a progress file
Machine-readable JSON is useful to the program, but a Markdown progress file helps people and agents. Record the goal, current status, decisions, next action, and open problems. Keep it updated when the plan changes.
Resuming from saved state
A resume routine should skip completed steps and verify important outputs before trusting the checkpoint.
STEPS = ["fetch", "transform", "validate", "publish"]
def run(path, functions):
state = load_checkpoint(path) or {"completed": []}
for name in STEPS:
if name in state["completed"]:
continue
functions[name](state)
state["completed"].append(name)
save_checkpoint(path, state)
return stateIf a checkpoint says publish finished, check that the expected published artifact exists. Otherwise, mark the step incomplete and handle it deliberately.
Exercise
Why should the temporary checkpoint file be created in the same directory as the final file?
Show answer
Replacement is then usually an atomic operation on the same file system, so readers see either the old complete file or the new complete file.