Sub topic 2
A Minimal Terminal Chat Loop
What this chapter assumes
You should be comfortable with Python functions, lists, dictionaries, and try/except. You should also know that a chat API takes a list of messages and returns a reply. The previous chapter explained why the model forgets between requests. This chapter builds the program that works around that. It is a loop of about twenty lines that reads a line, sends the conversation, and prints the answer.
The shape of the loop
A terminal chatbot repeats the same five steps. It reads a line of text and decides whether to act on it. It adds the text to a list of messages. It sends the whole list to the model. It adds the reply to the same list. Finally it prints the reply.
The list is what makes the bot remember. The model keeps nothing between calls, so the program must hold the conversation and resend it every time.
A runnable first version
The code below runs as written. The complete function is a stub that reports how many messages it received. Replace its body with a call to your chosen provider's SDK when you are ready. Keeping the model behind one function means nothing else in the loop changes when you switch providers. A later chapter develops that idea.
def complete(messages):
"""Send the full message list to a model and return the reply text.
This stub echoes the last message. Replace the body with a real SDK call."""
last = messages[-1]["content"]
return f"(stub) I received {len(messages)} messages. You said: {last}"
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
history.append({"role": "user", "content": user_text})
reply = complete(history)
history.append({"role": "assistant", "content": reply})
print(f"bot> {reply}")
if __name__ == "__main__":
main()Save it as chat.py and run python chat.py. A session looks like this:
you> hello
bot> (stub) I received 2 messages. You said: hello
you> what did I just say?
bot> (stub) I received 4 messages. You said: what did I just say?
you> /quitThe stub cannot answer the second question. The message count still shows the mechanism. The first call carried two messages: the system message and hello. The second call carried four: the system message, hello, the first reply, and the new question. A real model would use those earlier messages to answer.
Walking through the loop
Reading input safely
input("you> ") prints a prompt and blocks until the user presses Enter. The .strip() call removes leading and trailing whitespace, including the newline. This also means a line containing only spaces counts as empty.
Two things can interrupt input():
EOFErroris raised when standard input is closed. Pressing Ctrl-D on Linux and macOS does this, as does Ctrl-Z followed by Enter on Windows. It also happens when input is piped in and runs out.KeyboardInterruptis raised when the user presses Ctrl-C.
Without the try, either one prints a traceback and exits. With it, the loop prints a blank line so the shell prompt starts on a fresh line, then breaks out and ends the program normally.
Ending the session
There are three ways out. The user can type /quit, press Ctrl-D, or press Ctrl-C at the prompt. All three reach the break statement and leave the loop, and main() then returns. A fixed word like /quit is also useful when the program is being driven by a script. The slash prefix makes an accidental match with normal conversation unlikely, though not impossible. The commands chapter returns to this.
Skipping empty input
if not user_text: continue ignores blank lines. This matters because an empty user message wastes a request. Some providers reject empty content with an error. Checking before the append keeps the history valid.
The two appends
The order is deliberate:
- Append the user message.
- Call
complete(history). - Append the assistant reply.
The call happens after the first append because the model must see the new question. The second append happens after the call because the reply does not exist until the call returns. The next request then includes both sides of this exchange.
Each entry is a plain dictionary with a role and a content key. The roles alternate user, assistant, user, assistant, after the leading system entry. Many providers expect exactly this pattern, and some refuse a request that breaks it.
Printing the reply
print(f"bot> {reply}") shows the full reply at once. The user sees nothing until the model has finished. For long answers that wait can be several seconds. A later chapter replaces this line with a streaming version that prints text as it arrives.
Edge cases at the prompt
| Input or event | What happens | Why | Column |
|---|---|---|---|
| Blank line or only spaces | Ignored, prompt shown again | `strip()` leaves an empty string, and `continue` skips it | |
| `/quit` | Loop ends | Exact match after stripping | |
| `/QUIT` or `/quit now` | Sent to the model as ordinary text | The comparison is exact and case-sensitive | |
| Ctrl-C at the prompt | Clean exit | `KeyboardInterrupt` is caught around `input()` | |
| Ctrl-D at the prompt | Clean exit | `EOFError` is caught around `input()` | |
| Piped input such as `printf 'hi\n' \ | python chat.py` | Answers each line, then exits when input ends | `EOFError` is raised at end of input |
| Ctrl-C while waiting for the model | Traceback, and a dangling user message in `history` | The `try` only covers `input()` |
The last row is a real weakness of this version. If complete() raises an exception, whether from a network error or an interrupt, the user message has already been appended. The history then ends with a user message that has no reply. The next turn adds another user message, and the list contains two in a row. The error-handling chapter fixes this by removing the pending message on failure.
Common mistakes
- Creating the history inside the loop. If
history = [...]sits insidewhile True, the list is rebuilt every turn and the bot forgets everything. The list must be created once, before the loop. - Sending only the latest message. Calling
complete([{"role": "user", "content": user_text}])works but gives a bot with no memory. This is the stateless behavior from the previous chapter. - Appending the reply before checking it. If
completecan returnNoneor an empty string, a bad value gets stored and sent back on every later turn. Validate before you append. - Comparing commands without stripping. Without
.strip(), a stray trailing space makes/quitfail to match. - Mutating a list the model function keeps.
completereceives the same list object the loop owns. If your wrapper stores it or edits it, you will corrupt the conversation. Treat the argument as read-only.
What this version does not do
The cost of growth is the main reason the next chapters exist. Turn 10 sends about twice as many messages as turn 5. Cost and latency both rise with that size, and eventually the request no longer fits in the model's context window.
Try it yourself
Before moving on, run the stub version and make three small changes. Change the prompt strings, add a print(len(history)) after each reply to watch the list grow, and move the history = [...] line inside the while loop to see the memory disappear. These changes make the role of the list concrete before it gets more complicated.
Exercise
In the loop, why is the user message appended to history before complete(history) is called, but the assistant reply is appended after? What goes wrong with the stub if you swap the two appends so that the user message is appended after the call?
Show answer
The model must see the new question, so the user message has to be in the list when complete runs. The reply does not exist until complete returns, so it can only be appended afterward. If the user message were appended after the call, the model would be sent a list that does not contain the current question. With the stub, the "You said" part would echo the previous reply or the system message instead of the new input, and the history would end up in the wrong order.
Exercise
A user pipes a file into the program with python chat.py < questions.txt, and the file has no /quit line. What happens at the end of the file, and which line of code handles it?
Show answer
input() raises EOFError when the input is exhausted. The except (EOFError, KeyboardInterrupt) clause catches it, prints a blank line, and breaks out of the loop, so the program ends normally without a traceback.