Persisting and restoring state

Long-running programs become more useful when they can survive being stopped and started again. In agent-style programs, this usually means remembering what has already happened. Persisting state lets a program pick up where it left off instead of starting from scratch each time it runs.

Why long-running programs need persistence

In-memory state disappears when a program stops. For short scripts, that does not matter. For long-running programs and agents, losing state means losing progress, history, or decisions already made.

Persistence gives state a life beyond a single run. It allows an agent to behave consistently over time, even if it is restarted.

Serializing program state to a file

To persist state, we need to convert in-memory data into a form that can be written to disk. This process is called serialization. In Python, simple state made of dictionaries and lists can be serialized easily.

A common approach is to store state in a JSON file.

import json

state = {
    "pages_generated": 12,
    "last_body": "Mars"
}

with open("state.json", "w") as file:
    json.dump(state, file)

Here, a small dictionary representing program state is written to a file as structured text.

Restoring program state from a file at startup

When the program starts, it can check for an existing state file and load it back into memory. This restores the state from the previous run.

import json

with open("state.json", "r") as file:
    state = json.load(file)

After loading, the program can continue using state as if it had never stopped.

Handling missing or incomplete state files

A program cannot assume that a state file always exists. On the first run, there may be nothing to load. Programs usually handle this by starting with default state when no file is present.

import json
import os

if os.path.exists("state.json"):
    with open("state.json", "r") as file:
        state = json.load(file)
else:
    state = {
        "pages_generated": 0,
        "last_body": None
    }

This keeps startup predictable while still allowing persistence when data is available.

Continuing execution using restored state

Once state is restored, it should immediately influence program behavior. The program should not treat restored state differently from newly created state.

For example, an agent that generates HTML pages can resume generation from the last recorded body instead of starting over.

if state["last_body"] == "Mars":
    next_body = "Jupiter"

Persistence only matters if restored state actively shapes what happens next.

Conclusion

At this point, we know why persistence matters for long-running programs and how state can be saved and restored using files. We have seen how serialized state allows a program to survive restarts and continue execution with continuity. This is a key step toward building agents that operate reliably over time.