Sub topic 8
Remembering across runs: saving history to JSON
The history list lives in memory, so it disappears when the program exits. This chapter saves it to a JSON file and loads it at startup. It assumes you know Python functions, dictionaries, exceptions, and the message list from earlier chapters.
Why JSON fits
Each message is a plain dictionary with string values: a role and a content. Python's json module turns a list of such dictionaries into text and back with no custom code. The file is also easy to open in an editor, which helps when you debug.
Save and load functions
import json
from pathlib import Path
def save_history(history, path):
tmp = Path(str(path) + ".tmp")
tmp.write_text(json.dumps(history, indent=2), encoding="utf-8")
tmp.replace(path)
def load_history(path, default):
p = Path(path)
if not p.exists():
return default
return json.loads(p.read_text(encoding="utf-8"))save_history does not write to the target file directly. It writes to a temporary file next to it, then calls replace, which swaps the new file in as a single step. If the program crashes in the middle of the write, the old save file is still intact. A direct write could leave a half-written file that cannot be parsed.
load_history takes a default. When no save file exists, such as on the first run, it returns the default. Pass a fresh history that contains your system message.
Wiring it into the loop
Load once at startup, and save after every completed turn instead of only at exit. Saving only at exit loses the whole session if the process is killed.
HISTORY_PATH = "history.json"
def complete(messages):
"""Replace this body with a call to your chosen provider's SDK."""
raise NotImplementedError
def main():
default = [{"role": "system", "content": "You are a concise, helpful assistant."}]
history = load_history(HISTORY_PATH, default)
while True:
try:
user_text = input("you> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not user_text:
continue
if user_text == "/quit":
break
history.append({"role": "user", "content": user_text})
reply = complete(history)
history.append({"role": "assistant", "content": reply})
save_history(history, HISTORY_PATH)
print(f"bot> {reply}")
if __name__ == "__main__":
main()Saving happens after the assistant reply is appended. The file therefore always holds complete user and assistant pairs.
Common errors
- A corrupt or hand-edited file.
json.loadsraisesjson.JSONDecodeErroron invalid text. Decide what to do: stop with a clear message, or rename the bad file and start fresh. Do not silently overwrite it. - A stale system message. The loaded history contains the system message from the earlier run. If you change the prompt in your code, the old one still wins. Replace the first message after loading, or keep the system message out of the file and add it at startup.
- Unbounded growth. The file grows with the conversation. Apply
trim_historybefore sending, and decide whether to save the trimmed or the full list. Saving the full list keeps a complete record. Saving the trimmed list keeps the file small. - Sensitive content. The file holds everything the user typed in plain text. Keep it out of version control, and consider restrictive file permissions.
- Encoding. Pass
encoding="utf-8"explicitly. Otherwise Windows may use a different default and fail on non-ASCII text.
Exercise
Why does save_history write to a ".tmp" file and then call replace, instead of writing straight to the save file?
Show answer
If the program crashes or is killed during a direct write, the save file can be left half-written and unreadable. Writing to a temporary file first means the original stays intact until the complete new file is swapped in with one replace call.
Exercise
You changed the system prompt in your code, but the bot still behaves as before after restarting. What is the likely cause, and how can you fix it?
Show answer
The loaded JSON history still contains the old system message as its first entry. Either overwrite the first message with the new prompt after loading, or store only the non-system messages in the file and prepend the current system message at startup.