Sub topic 3
Adding Commands and Reliability to a Terminal Chatbot
Assume you know Python functions, lists, dictionaries, exceptions, and the earlier loop that sends a complete message history to a model. This chapter adds operational features without changing the history model.
Adding slash commands
Handle commands before sending text to the model. A command is input beginning with /, such as /reset, /save, or /quit.
def handle_input(text, history, path):
if text == "/quit":
return "quit"
if text == "/reset":
system = history[0]
history[:] = [system]
print("conversation reset")
return "handled"
if text == "/save":
save_history(history, path)
print(f"saved to {path}")
return "handled"
return "message"
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 replyThe slice assignment in /reset changes the existing list instead of replacing it. Code that holds a reference to history therefore still sees the reset list.
Handling failures without corrupting history
Append the user message before the request because the model needs it. Append the assistant message only after a successful response. If the request fails, remove the user message or mark the turn as failed. Removing it keeps the next request structurally valid.
Catch expected errors, such as network timeouts, in the outer loop. Print a short message and let the user retry. Handle EOFError and KeyboardInterrupt so leaving the terminal does not write a partial assistant message.
Printing replies as they stream
A streaming model returns chunks instead of one final string. Print each chunk immediately, but collect the same chunks in memory. Add the joined text to history only when the stream finishes successfully.
Testing with a fake model
Pass the model function into the conversation code. Tests can then use a fake that returns predictable text or raises an error. Test successful growth by two messages and failure rollback by unchanged history.
Compressing old turns into a summary
A context window is the maximum input a model can process in one request. When history approaches that limit, summarize older user and assistant turns into one assistant or system-style record. Keep recent turns verbatim because they contain the most immediate context.
Going further: long-term memory and retrieval
Long-term memory stores selected facts outside the current conversation, often in a database or search index. Before a request, retrieve only relevant facts and add them as context. Store stable, useful information rather than every message. Retrieval improves scale, but it can return irrelevant or outdated facts, so label and review inserted memory.
Exercise
Why should a failed model call remove the newly appended user message?
Show answer
It prevents an incomplete turn from being saved and sent again as if it had a matching assistant reply.