Sub topic 10
Handling failures without corrupting history
This chapter assumes you know Python exceptions and have the chat loop, the message list, and a complete(messages) function from earlier chapters. It shows how to keep the history valid when a request fails or the user presses Ctrl+C.
Why a failed turn is dangerous
A turn changes the history twice. It appends the user message, calls the model, then appends the reply. If the call fails in between, the history ends with a user message that has no reply.
The next turn then adds a second user message in a row. Some APIs reject two consecutive messages with the same role. Others accept them and answer oddly. Trimming code that expects the conversation to alternate can also break.
Make each turn all-or-nothing
Move the two appends into one function. If the call fails, remove the user message and re-raise the error.
def run_turn(history, user_text, complete):
history.append({"role": "user", "content": user_text})
try:
reply = complete(history)
except BaseException:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return replyThe handler catches BaseException, not Exception. KeyboardInterrupt inherits from BaseException, so except Exception would let a Ctrl+C during the request leave the orphaned user message behind. Re-raising lets the caller decide what to show.
Handle errors in the loop
Ctrl+C means different things depending on where it arrives. At the prompt it should quit. During a request it should cancel that request and return to the prompt.
def complete(messages):
return f"echo: {messages[-1]['content']}" # stub; replace with a real call
def main():
history = [{"role": "system", "content": "You are a concise, helpful assistant."}]
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(cancelled)")
continue
except Exception as exc:
print(f"error: {exc}")
continue
print(f"bot> {reply}")
if __name__ == "__main__":
main()The user can retype the same message after an error. The history is unchanged, so nothing needs repairing.
Where each failure is handled
| Failure | Raised where | Handling |
|---|---|---|
| Network error, timeout, rate limit | Inside `complete()` | `run_turn` rolls back, the loop prints the error |
| Ctrl+C at the prompt | `input()` | Leave the loop and exit |
| Ctrl+C during the request | Inside `complete()` | `run_turn` rolls back, the loop prints "(cancelled)" |
| End of input (Ctrl+D) | `input()` | Same as quitting |
Protect the saved file
Failures also threaten the save file. Save only after a turn succeeds, never between the two appends. Write through a temporary file and replace the original, as in the persistence chapter, so a crash mid-write cannot leave half a JSON document. Saving the history after a rolled-back turn is safe, because the rollback has already restored it.
Retrying automatically is optional. If you add it, retry inside complete() so that run_turn still sees one call that either returns a reply or raises.
Exercise
Suppose run_turn used except Exception: instead of except BaseException:. What would be wrong with the history after the user presses Ctrl+C while a reply is being generated?
Show answer
KeyboardInterrupt is not a subclass of Exception, so the handler would not run and history.pop() would be skipped. The history would end with a user message that has no reply. The next turn would append a second user message in a row.