Managing in-memory state
As programs run longer, they need a way to remember what has already happened. For classical agents, this memory lives inside the program itself and shapes every decision that follows. This lesson exists to orient us around program state and how Python programs keep track of it while they run.
What program state is
Program state is the collection of values a program is holding at a given moment. It includes things like counters, flags, accumulated results, and remembered inputs. In a long-running program, state is what allows the program to behave differently now than it did earlier.
State is not special syntax in Python. It is simply data that stays in memory while the program continues executing.
Representing state with Python data structures
In Python, state is usually represented with familiar structures. Simple values can live in variables. Groups of related values often live in dictionaries or lists.
A dictionary is a common choice when state has named parts.
state = {
"pages_generated": 0,
"errors": [],
"last_planet": None
}
Lists are useful when state grows over time or preserves order.
generated_pages = []
These structures sit in memory and remain available as long as the program keeps running.
Updating state in response to events or input
State changes when something happens. An event might be user input, a completed task, or a step in a loop.
Updating state is usually straightforward assignment or mutation.
state["pages_generated"] += 1
state["last_planet"] = "Mars"
generated_pages.append("mars.html")
Each update captures the outcome of the most recent action so the program can respond differently next time.
Using state to influence future behavior
State becomes useful when it affects what the program does next. Decisions often read from state before choosing an action.
if state["pages_generated"] == 0:
title = "Welcome to the Solar System"
else:
title = "Planet Pages"
Here, earlier behavior directly influences later output. This is the foundation of deterministic agent behavior.
Keeping state consistent during execution
Because state is shared across the program, it must stay coherent. Related values should be updated together, and state should reflect what has actually happened.
A common pattern is to update state immediately after an action completes successfully.
html = "<h1>Mars</h1>"
generated_pages.append(html)
state["pages_generated"] += 1
state["last_planet"] = "Mars"
Consistency makes later decisions predictable and easier to reason about.
Conclusion
We now have a clear picture of what in-memory state is and how Python programs represent and update it. By storing information in variables, lists, and dictionaries, a long-running program can remember the past and let it shape future behavior. That orientation is enough to begin building agents that act with continuity instead of starting fresh each time.