Sub topic 9
Adding Slash Commands
This chapter assumes you have the chat loop, the message history list, and the JSON save and load helpers from earlier chapters. You should be comfortable with Python functions, dictionaries, and exceptions.
Why commands belong in the loop
So far the only way to leave the bot is /quit, and it is an if statement inside main(). Adding /reset and /save the same way would turn the loop into a long chain of conditions. A slash command is an input line that starts with / and controls the program instead of going to the model. Handling these lines in one place keeps the loop short and keeps command text out of the history.
The rule is simple. If a line starts with /, the program handles it locally. Otherwise it is a normal message and goes to the model.
The command flow
A command handler
The handler takes the history and the raw line. It returns True when the loop should stop. Keeping the system message is the important detail in /reset. If you clear the whole list, the bot loses its instructions.
import json
from pathlib import Path
SAVE_PATH = Path("history.json")
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 handle_command(line, history):
"""Run a slash command. Return True if the program should exit."""
parts = line.split(maxsplit=1)
name = parts[0].lower()
if name == "/quit":
return True
if name == "/reset":
history[:] = [m for m in history if m["role"] == "system"]
print("(conversation cleared)")
elif name == "/save":
path = Path(parts[1]) if len(parts) > 1 else SAVE_PATH
save_history(history, path)
print(f"(saved {len(history)} messages to {path})")
else:
print(f"Unknown command {name}. Try /reset, /save [file], /quit.")
return FalseTwo details matter here:
history[:] = ...replaces the contents of the existing list. Writinghistory = ...would only rebind a local name, and the loop would keep using the old list./saveaccepts an optional file name, so/save work.jsonand/saveboth work. It reuses the atomic write from the persistence chapter, so an interruption cannot leave a half-written file.
Wiring it into the loop
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.startswith("/"):
if handle_command(user_text, history):
break
continue
reply = run_turn(history, user_text, complete)
print(f"bot> {reply}")This uses run_turn and complete from the earlier chapters. The continue after a command matters. Without it, the command text would fall through and be sent to the model as a message.
Common mistakes
- Sending commands to the model. A typo such as
/restshould print a help message, not become a user turn. Thestartswith("/")check catches every slash line, including unknown ones. - Clearing the system message.
/resetmust filter by role, not callhistory.clear(). - Matching case-sensitively. Lowercasing the command name lets
/QUITwork. Leave the arguments alone, since file names are case-sensitive on some systems. - Treating a file path as a command. A user message that begins with a path like
/home/me/file.txtis routed to the handler. This is acceptable for a small tool. If it matters, require commands to be a single known word and send anything else to the model.
Exercise
Add a /history command that prints how many messages are in the history, without counting the system message. Where in handle_command does it go, and what does it return?
Show answer
Add an elif name == "/history": branch before the final else. It should print len([m for m in history if m["role"] != "system"]) and fall through to return False, since the program should keep running. It does not change the history, so it needs no list assignment.