Sub topic 8
Remembering across runs: saving history to JSON
The chatbot now keeps a message list in memory, so it remembers within one run. When the program exits, the list is gone and the next run starts blank. This chapter writes the list to disk after each turn and reads it back at startup.
This chapter assumes you have the chat loop and the run_turn function from earlier chapters, and that you know Python's json module, pathlib.Path, and exception handling. You don't need any new libraries.
Why JSON fits
The history is a list of dictionaries. Each dictionary has a "role" string and a "content" string. That is exactly the structure JSON describes, so json.dumps and json.loads convert it with no custom code.
JSON also has practical advantages for a chat log:
- You can open the file in an editor and read or fix it by hand.
- Most providers accept the same message shape, so a loaded list goes straight to
complete(). - A single file holds a whole conversation, which is enough for one user at a terminal.
You would need a database only for many conversations, many users, or concurrent writers. Section "Edge cases" below covers the concurrent case.
Saving safely
The obvious way to save is path.write_text(json.dumps(history)). It has a flaw. If the process dies halfway through the write, for example from a power cut or a kill signal, the file is left truncated. The next load fails, and you lose the whole conversation, not only the last turn.
The fix is to write the full content to a temporary file and then replace the real file in one step:
import json
from pathlib import Path
def save_history(history, path):
path = Path(path)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(
json.dumps(history, indent=2, ensure_ascii=False),
encoding="utf-8",
)
tmp.replace(path)Path.replace renames the temporary file over the target. On the same filesystem, the rename either happens completely or not at all, so a reader sees the old file or the new one, never a partial one. The temporary file lives in the same directory as the target to guarantee the same filesystem.
Two details matter here:
encoding="utf-8"is explicit because the default encoding differs between systems, and a conversation can contain any character.ensure_ascii=Falsekeeps non-English text readable in the file. Without it,json.dumpswrites characters such aséas\u00e9escapes. Both forms load back identically.
Loading defensively
A file can be missing, empty, hand-edited into invalid JSON, or valid JSON with the wrong shape. A loader for a file you wrote yourself still has to handle these, because you or an older version of the program may have changed it.
import json
from pathlib import Path
VALID_ROLES = {"system", "user", "assistant"}
def is_valid_history(data):
if not isinstance(data, list):
return False
for message in data:
if not isinstance(message, dict):
return False
if message.get("role") not in VALID_ROLES:
return False
if not isinstance(message.get("content"), str):
return False
return True
def load_history(path, default):
path = Path(path)
if not path.exists():
return default
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
data = None
if not is_valid_history(data):
bad = path.with_name(path.name + ".bad")
path.replace(bad)
print(f"Could not read {path}; moved it to {bad} and starting fresh.")
return default
return dataValueError covers both json.JSONDecodeError and UnicodeDecodeError, because both are subclasses of it. When the file is unusable, the loader doesn't delete it. It renames the file to .bad and starts a new conversation, so you can still inspect or repair the old data. Silently overwriting a damaged file on the next save would destroy it.
The validation checks structure only. It doesn't check that roles alternate or that the first non-system message is from the user. If you trim history after loading, the trim_history function from the previous chapter repairs the start of the list.
Deciding what to load: the system prompt
Suppose you save the full history, including the system message, and later edit the system prompt in your code. If you load the file as-is, the bot keeps following the old instructions, because the saved system message wins.
The usual fix is to treat the system prompt as configuration, not as conversation data. At startup, discard any saved system messages and put the current prompt first:
SYSTEM_PROMPT = "You are a concise, helpful assistant."
def start_history(path, system_prompt=SYSTEM_PROMPT):
saved = load_history(path, default=[])
conversation = [m for m in saved if m["role"] != "system"]
return [{"role": "system", "content": system_prompt}] + conversationYou can still save the system message to the file, which keeps the file a faithful record of what was sent. The loader ignores it either way.
Choosing when to save
You can save at different moments. Each choice trades safety against simplicity.
| When to save | Advantage | Risk |
|---|---|---|
| After every successful turn | A crash loses at most the turn in progress | One small file write per turn |
| Only on `/quit` | Fewest writes | Ctrl+C, a crash, or a terminal closing loses the whole session |
| Only on a `/save` command | The user controls it | Users forget, and the result looks like lost memory |
Saving after each successful turn is the best default. The file is small, and writing it takes microseconds compared with the model request. Never save a turn that failed. The run_turn function from the earlier chapter already removes the user message when the model call fails, so saving after run_turn returns only ever writes valid history.
Putting it together
This version loads at startup and saves after every turn. It reuses run_turn from the earlier chapter.
import json
from pathlib import Path
HISTORY_PATH = Path("chat_history.json")
def complete(messages):
"""Send the full message list to a model and return the reply text.
Replace this body with a call to your chosen provider's SDK."""
raise NotImplementedError
def run_turn(history, user_text, complete):
history.append({"role": "user", "content": user_text})
try:
reply = complete(history)
except Exception:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return reply
def save_history(history, path):
path = Path(path)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(history, indent=2, ensure_ascii=False), encoding="utf-8")
tmp.replace(path)
def load_history(path, default):
path = Path(path)
if not path.exists():
return default
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return default
return data if isinstance(data, list) else default
def main():
system = {"role": "system", "content": "You are a concise, helpful assistant."}
saved = load_history(HISTORY_PATH, default=[])
history = [system] + [m for m in saved if m.get("role") != "system"]
if len(history) > 1:
print(f"Resumed {len(history) - 1} earlier messages.")
while True:
try:
user_text = input("you> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not user_text:
continue
if user_text == "/quit":
break
try:
reply = run_turn(history, user_text, complete)
except Exception as exc:
print(f"error: {exc}")
continue
save_history(history, HISTORY_PATH)
print(f"bot> {reply}")
if __name__ == "__main__":
main()This listing keeps a shorter loader than the validating one above so it stays self-contained. In a real project, put the validating load_history and start_history in one module and import them.
Edge cases
- Large files. The saved list grows with every turn. If you trim the in-memory list with a sliding window, you have a choice. Save the trimmed list and the old turns are gone for good, or keep a full copy for the file and send only the trimmed copy to the model. The second option keeps a complete record, but a full reload then sends more than fits, so trim again after loading.
- Two instances at once. Two terminals using the same file overwrite each other, and the last writer wins. Use a different file per session, for example by passing the path as a command-line argument.
- Changed format. If you later add fields to messages, old files won't have them. Store a wrapper such as
{"version": 1, "messages": [...]}if you expect the format to change. - Working directory. A relative path like
chat_history.jsonresolves against wherever you launched the program, so running from another folder starts a new conversation. Use an absolute path, such as one underPath.home(), if that is not what you want.
Exercise
A user reports that after the program was killed during a save, the chatbot printed an error and lost the whole conversation. Which line of the original save_history design causes this, and how does the version in this chapter avoid it?
Show answer
Writing directly to the real file with path.write_text(...) can leave a truncated file if the process dies mid-write, and that file then fails to parse. The chapter's version writes to a .tmp file first and calls tmp.replace(path), which swaps the files in one rename. The real file is always either the old complete version or the new complete version.
Exercise
You change SYSTEM_PROMPT to make the bot answer in French, but a resumed conversation still replies in English. What is the likely cause, and how do you fix it?
Show answer
The old system message was saved in the file and loaded back as the first message, so the bot still follows the old instructions. Fix it by dropping all saved messages with role "system" at startup and prepending the current system prompt, as start_history does.