Sub topic 9
Adding slash commands
This chapter assumes you have the chat loop, the message history list, and the save_history and load_history helpers from earlier chapters. You should be comfortable with dictionaries of functions and with raising and catching exceptions.
Why the chat needs a control channel
So far the only thing a user can do is type a message, and every message goes to the model. That leaves some actions with no way to happen. The user cannot clear the history, save it on demand, or leave without pressing Ctrl+C.
Slash commands solve this. A line that starts with / is an instruction to your program and never reaches the model. This works well in a terminal because a single input stream carries both chat text and control input, and the first character tells you which one you got.
Commands run in your program, not the model, so they cost nothing, respond instantly, and behave the same every time. Asking the model to "please forget everything" does not clear the history list. Only code can do that.
Routing input
Each line from the user takes one of three paths. The // branch is an escape hatch, covered below.
The check for // comes before the check for /. Without it, a user could never send a message like /etc/hosts is a file, what does it do?, because the loop would treat it as an unknown command.
A command registry
The simplest design that scales is a dictionary that maps command names to handler functions. Adding a command then means writing one function and adding one entry. You never edit an if/elif chain.
Every handler has the same signature: it receives the history and the argument string, and it returns a message to print. A handler that needs to end the program raises a dedicated exception, so the loop does not need a special case for each command.
| Command | Argument | Effect |
|---|---|---|
| `/reset` | none | Replaces the history with a fresh one that holds only the system message |
| `/save` | optional file path | Writes the history to JSON, using `chat.json` by default |
| `/help` | none | Lists the available commands |
| `/quit` | none | Ends the program |
The full program
The complete function below is an echo stub so the program runs without an API key. Replace its body with your real model call, as in the earlier chapter.
import json
from pathlib import Path
SYSTEM_PROMPT = "You are a concise, helpful assistant."
DEFAULT_SAVE_PATH = "chat.json"
class QuitChat(Exception):
"""Raised by a command handler to end the chat loop."""
def complete(messages):
"""Echo stub. Replace with a call to your provider's SDK."""
return f"(echo) {messages[-1]['content']}"
def new_history():
return [{"role": "system", "content": SYSTEM_PROMPT}]
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 cmd_reset(history, arg):
history[:] = new_history()
return "History cleared."
def cmd_save(history, arg):
path = arg or DEFAULT_SAVE_PATH
try:
save_history(history, path)
except OSError as exc:
return f"Could not save to {path}: {exc}"
return f"Saved {len(history)} messages to {path}."
def cmd_help(history, arg):
lines = [f" {name}" for name in sorted(COMMANDS)]
return "Commands:\n" + "\n".join(lines)
def cmd_quit(history, arg):
raise QuitChat
COMMANDS = {
"/reset": cmd_reset,
"/save": cmd_save,
"/help": cmd_help,
"/quit": cmd_quit,
}
def dispatch(line, history):
"""Run one slash command and return the text to show the user."""
name, _, arg = line.strip().partition(" ")
handler = COMMANDS.get(name.lower())
if handler is None:
return f"Unknown command {name}. Type /help for a list."
return handler(history, arg.strip())
def main():
history = new_history()
print("Type /help for commands.")
while True:
try:
line = input("you> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not line:
continue
if line.startswith("//"):
line = line[1:]
elif line.startswith("/"):
try:
print(dispatch(line, history))
except QuitChat:
break
continue
history.append({"role": "user", "content": line})
reply = complete(history)
history.append({"role": "assistant", "content": reply})
print(f"bot> {reply}")
if __name__ == "__main__":
main()Design points worth knowing
Mutate the history in place
cmd_reset writes history[:] = new_history() instead of history = new_history(). Plain assignment would only rebind the handler's local variable, and the loop in main would keep using the old list. Slice assignment changes the contents of the one list that every part of the program shares.
Reset keeps the system message
The new history is built from new_history(), so the system prompt survives. A reset that left the list empty would silently remove the bot's instructions. This is the same rule the trimming function follows: system messages are never dropped.
Commands never touch the history
The user's /save line is not appended to the history, and neither is the handler's output. If it were, the saved file would contain text like "Saved 7 messages", the model would see it on the next turn, and the count would be wrong the moment it was written. Commands are control input, so keep them out of the conversation record.
Unknown commands stay local
A typo such as /rest prints a hint and stops there. Sending it to the model would cost a request and produce a confusing answer. This is the reason for the // escape: it is the only way for a user to send a leading slash to the model on purpose.
Parsing arguments
line.partition(" ") splits at the first space only, so /save my notes.json gives the argument my notes.json with the space intact. If you later need several arguments per command, switch to shlex.split, which handles quoted strings. Until then the simpler form has fewer edge cases.
Failure handling inside handlers
Handlers run outside the model call, so the failure modes differ from the ones in the error-handling chapter. The one realistic failure is file input and output. cmd_save catches OSError, which covers a missing directory, a permission problem, and a full disk, and it returns the error as text. The chat keeps running, and the in-memory history is unaffected.
Do not catch Exception broadly in dispatch. A bug in your own handler should fail loudly while you develop, not appear as a vague message. QuitChat is deliberately not an OSError, so it passes through the handlers and reaches the loop.
Testing the dispatcher
Because dispatch takes the history as an argument and returns a string, you can test it with no input mocking.
def test_reset_keeps_only_the_system_message():
history = new_history()
history.append({"role": "user", "content": "hi"})
dispatch("/reset", history)
assert history == new_history()
def test_unknown_command_does_not_change_history():
history = new_history()
message = dispatch("/nope", history)
assert "Unknown command" in message
assert history == new_history()
def test_quit_raises():
try:
dispatch("/quit", new_history())
except QuitChat:
return
raise AssertionError("expected QuitChat")Extending the set
Two commands that fit this design easily:
/load [path]reads a JSON file withload_historyand replaces the contents withhistory[:] = loaded. Validate that the result is a list of dictionaries that haveroleandcontentkeys before you replace anything, since a hand-edited file may be wrong./historyprints the number of messages, or the last few of them, so the user can see what the model will receive.
Both follow the same pattern: write a handler with the standard signature and add one dictionary entry.
Exercise
A user types /reset and the loop prints "History cleared.", but the bot still remembers the earlier conversation. The handler contains history = new_history(). What is wrong, and how do you fix it?
Show answer
The assignment rebinds the local name history inside the handler, so the list that main holds is never changed. Use slice assignment, history[:] = new_history(), which replaces the contents of the shared list in place.
Exercise
Why does the loop check for the // prefix before the / prefix, and what does a user type to send the message /etc/hosts is a file to the model?
Show answer
Checking // first lets a user escape a leading slash. If the single-slash check ran first, every message starting with / would be treated as a command. The user types //etc/hosts is a file, and the loop strips one slash and sends /etc/hosts is a file to the model.