Sub topic 2
A minimal terminal chat loop
This chapter builds the smallest working version of the chatbot: a loop that reads a line, sends the conversation to a model, and prints the reply. It assumes you can write Python functions, lists, dictionaries, and try/except blocks, and that you can run a script from a terminal. It also assumes you know that a chat API takes messages in and returns a reply.
What the loop does
A terminal chatbot repeats the same four steps on every turn:
- Read a line from the user.
- Add it to the conversation as a message.
- Send the whole conversation to the model and get a reply.
- Add the reply to the conversation and print it.
Step 3 sends the whole conversation because the model API is stateless. The previous chapter explained that the model remembers nothing between requests. The list you keep in your program is the only memory the bot has.
The code
The model call lives in a function named complete. It is a stub here, so you can plug in any provider's SDK later without touching the loop.
def complete(messages):
"""Send the full message list to a model and return the reply text.
Replace this body with a call to your chosen provider's SDK."""
raise NotImplementedError
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()As written, the first real message raises NotImplementedError. You must fill in complete before the bot answers. A quick way to see the loop work is to temporarily make it return f"you said: {messages[-1]['content']}".
Walking through the code
The history list. history starts with one system message that sets the bot's behavior. Each later message is a dictionary with a role (user or assistant) and content. The next chapters cover roles in detail. For now, note that the list grows by two entries per turn.
Reading input. input("you> ") blocks until the user presses Enter. .strip() removes surrounding whitespace, so a line of only spaces counts as empty.
Ending cleanly. input raises EOFError when input ends, for example when the user presses Ctrl+D on Linux or macOS, or when input is piped in and runs out. It raises KeyboardInterrupt on Ctrl+C. Catching both and breaking out of the loop lets the program exit without a traceback. The bare print() moves the cursor to a fresh line so the shell prompt does not appear on the same line as you>.
Skipping empty lines. An empty message would waste a request and add a blank entry to the history, so the loop uses continue to prompt again.
A first command. Checking for /quit before appending anything means the quit text never enters the history. Later chapters add more slash commands in the same place.
Order of appends. The user message is appended before complete is called, because the model needs to see it. The reply is appended after, because it does not exist until then.
Common errors
- Sending only the latest message. If you call
complete([{"role": "user", "content": user_text}]), the bot answers each line as if it were the first. Always pass the full list. - Forgetting to append the reply. The bot will remember what you said but not what it said, and its answers will stop making sense.
- A failed call leaves a dangling user message. In this version, if
completeraises, the program crashes. If you catch the error and keep looping, the history ends with an unanswered user message. The error-handling chapter shows how to fix this.
Exercise
In the loop above, why is the /quit check placed before history.append(...) for the user message?
Show answer
So the command is handled by the program and never becomes part of the conversation. If it were appended first, the text "/quit" would be sent to the model and stored in the history.
Exercise
A user reports that the bot forgets their name right after being told. Looking at the loop, which two mistakes could cause this?
Show answer
Either complete is called with only the newest user message instead of the full history, or the loop never appends the user message (or the reply) to history, so later requests do not contain the earlier turns.