Sub topic 10
Handling failures without corrupting history
This chapter assumes you have the chat loop, the message list, save_history and load_history from earlier chapters. It also assumes you know Python exceptions, including that KeyboardInterrupt is not a subclass of Exception. The goal is a program where a network error, a Ctrl+C or a damaged save file never leaves the history in a state that breaks the next request.
Why failures corrupt history
The history is the bot's only memory, and the API checks it on every request. Many providers reject a list that has two user messages in a row, or one that ends in the wrong role. So the main risk is a partial update: the program adds the user's message, the model call fails, and the list is left half-finished.
The naive loop does exactly this:
history.append({"role": "user", "content": user_text})
reply = complete(history) # raises here
history.append({"role": "assistant", "content": reply})If complete raises, the history ends with an orphan user message. The next turn appends another user message, and the request may now be rejected on every attempt until you restart. If you also save after each turn, the bad state can reach disk.
The rule for this chapter is that a turn is all or nothing. Either both messages (user and assistant) are added, or neither is.
Two ways to make a turn atomic
The spine's run_turn appends first and removes the user message if the call fails:
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 replyThis works for ordinary errors, but it has two weaknesses:
except Exceptiondoes not catchKeyboardInterrupt. If the user presses Ctrl+C while waiting for the reply, thepop()never runs and the orphan message stays.- It relies on
completenot changing the list. If a wrapper trims or editshistoryin place,pop()may remove the wrong message.
A more robust version builds the request from a copy and only commits after success:
class ModelError(Exception):
"""Raised for model failures. retryable marks transient ones."""
def __init__(self, message, retryable=False):
super().__init__(message)
self.retryable = retryable
def run_turn(history, user_text, complete):
user_message = {"role": "user", "content": user_text}
reply = complete(history + [user_message])
if not isinstance(reply, str) or not reply.strip():
raise ModelError("model returned an empty reply")
history.append(user_message)
history.append({"role": "assistant", "content": reply})
return replyhistory + [user_message] creates a new list, so history itself is untouched until the last two lines. Nothing needs undoing, so it makes no difference which exception arrives, including KeyboardInterrupt. The two append calls at the end cannot fail in practice, so the window for a partial update is as small as it can be.
The reply check matters too. Some providers return an empty string or None when a safety filter fires or the output limit is reached before any text. Storing that creates an assistant message with no content, which some APIs reject on the next call. Treating it as an error keeps the history clean.
The shape of one turn
Retrying transient failures
Not every failure should end the turn. Rate limits, timeouts and temporary server errors often succeed a few seconds later. Bad credentials and oversized requests never will. The model function is where you tell them apart. Your complete should convert the provider's exceptions into ModelError with retryable set accordingly. The retry logic then stays independent of any one SDK:
import time
def call_with_retry(complete, messages, attempts=3, base_delay=1.0, sleep=time.sleep):
for attempt in range(attempts):
try:
return complete(messages)
except ModelError as exc:
last_attempt = attempt == attempts - 1
if not exc.retryable or last_attempt:
raise
sleep(base_delay * 2 ** attempt)The delay doubles each time (1 s, 2 s, 4 s). That is exponential backoff, and it avoids hammering a service that is already overloaded. sleep is a parameter so that tests can pass a no-op instead of waiting.
| Failure | Retry? | What the user sees | History |
|---|---|---|---|
| Timeout, connection reset | Yes | Nothing, or a short "retrying" note | Unchanged |
| Rate limit (HTTP 429) | Yes, with backoff | Nothing until retries run out | Unchanged |
| Server error (HTTP 5xx) | Yes | Error after the last attempt | Unchanged |
| Invalid API key | No | Error message | Unchanged |
| Request too large | No | Error message, suggest `/reset` or a smaller window | Unchanged |
| Empty reply | No | Error message | Unchanged |
| Ctrl+C during the call | No | "turn cancelled" | Unchanged |
Every row ends in the same state, and that uniformity is what the all-or-nothing rule buys.
Handling errors in the loop
The loop decides what each failure means for the session. A Ctrl+C at the prompt means "I'm done". A Ctrl+C while waiting for a reply means "cancel this question". These need separate try blocks.
import json
from pathlib import Path
HISTORY_PATH = Path("chat_history.json")
SYSTEM = {"role": "system", "content": "You are a concise, helpful assistant."}
def model_complete(messages):
"""Placeholder model. Replace with a real provider call that raises ModelError."""
return "echo: " + messages[-1]["content"]
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 main():
history = load_history(HISTORY_PATH, [SYSTEM])
def complete(messages):
return call_with_retry(model_complete, 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 KeyboardInterrupt:
print("\n[turn cancelled]")
continue
except ModelError as exc:
print(f"[error] {exc}")
continue
except Exception as exc:
print(f"[unexpected error] {exc!r}")
continue
print(f"bot> {reply}")
save_history(history, HISTORY_PATH)
if __name__ == "__main__":
main()The save happens only after a successful turn, so the file on disk is always a state the program was willing to send to the model. The blocks in this chapter form one file in the order shown. The load_history function it calls is defined in the next section.
Surviving a damaged save file
A turn can also fail at startup, when the saved file is unreadable. The atomic write from the previous chapter makes truncated files unlikely, but you can still get a hand-edited file, a full disk during an older write, or a file from a different program. Crashing on json.loads would lock the user out until they delete the file by hand. A safer loader validates the data and moves a bad file aside instead of destroying it:
def load_history(path, default):
p = Path(path)
if not p.exists():
return default
try:
data = json.loads(p.read_text(encoding="utf-8"))
valid = isinstance(data, list) and all(
isinstance(m, dict)
and isinstance(m.get("role"), str)
and isinstance(m.get("content"), str)
for m in data
)
except (OSError, ValueError):
valid = False
if not valid:
backup = p.with_name(p.name + ".corrupt")
p.replace(backup)
print(f"[warning] could not read {p}; moved it to {backup}")
return default
return datajson.JSONDecodeError and UnicodeDecodeError are both subclasses of ValueError, so one clause covers bad JSON and bad bytes. Renaming rather than deleting means the user can still recover the text. Note that the check is structural only. It confirms that each entry has a string role and content, not that the roles alternate correctly.
Testing the failure paths
The fake-model approach from the testing chapter applies directly. Each failure mode becomes a short test that checks the history afterward:
def test_interrupt_leaves_history_unchanged():
history = [{"role": "system", "content": "s"}]
def interrupted(messages):
raise KeyboardInterrupt
try:
run_turn(history, "hi", interrupted)
except KeyboardInterrupt:
pass
assert history == [{"role": "system", "content": "s"}]
def test_empty_reply_is_rejected():
history = [{"role": "system", "content": "s"}]
try:
run_turn(history, "hi", lambda messages: " ")
except ModelError:
pass
assert len(history) == 1
def test_retry_succeeds_after_transient_errors():
calls = []
def flaky(messages):
calls.append(1)
if len(calls) < 3:
raise ModelError("busy", retryable=True)
return "ok"
delays = []
assert call_with_retry(flaky, [], sleep=delays.append) == "ok"
assert delays == [1.0, 2.0]
def test_non_retryable_error_is_not_retried():
calls = []
def bad_key(messages):
calls.append(1)
raise ModelError("bad key", retryable=False)
try:
call_with_retry(bad_key, [], sleep=lambda s: None)
except ModelError:
pass
assert len(calls) == 1The first test fails against the append-then-pop version of run_turn and passes against the copy-then-commit version. A test that fails on the old design and passes on the new one is a good check that you understood the difference.
Common mistakes
- Saving the history before the model call succeeds. A crash then persists the orphan message.
- Retrying every exception. A bad API key retried three times only delays the error message.
- Retrying without a limit or a delay. Always cap attempts and back off.
- Swallowing errors silently. Print something, or the user will think the bot ignored them.
- Mutating
historyinsidecomplete, for example by trimming it in place. Trim a copy and leave the stored list alone.
Exercise
A user types a question and presses Ctrl+C while the model is still replying. Using the first version of runturn (append, then except Exception with pop()), what is wrong with the history afterward, and which change to runturn fixes it without catching BaseException?
Show answer
KeyboardInterrupt is not a subclass of Exception, so the except Exception block never runs and pop() is skipped. The history ends with a user message that has no reply, and the next turn adds a second user message in a row. Build the request from a copy (history + [user_message]) and append the user and assistant messages only after complete() returns a valid reply. Then no exception type can leave a half-finished turn.
Exercise
Why is sleep a parameter of callwithretry, and what would a test of retry behavior look like without it?
Show answer
Passing sleep lets a test supply a function that records the delays (or does nothing) instead of waiting for real seconds. Without it, a test of three attempts with backoff would block for about three seconds or more, and it could not check the delay values. With sleep=delays.append, the test asserts that the delays are [1.0, 2.0] and runs instantly.