Sub topic 1
Why the Model Forgets: Stateless APIs
Prerequisites
This chapter assumes basic Python, including functions, lists, dictionaries, and exceptions. You should also be comfortable running a program in a terminal and understand that a chat API accepts messages and returns a reply.
Why the Model Forgets: Stateless APIs
A model API is usually stateless. Stateless means that each request is independent unless your program sends earlier information again. The model does not automatically retain your previous request after it returns a response.
For example, these requests do not share memory:
Request 1: "My name is Ana."
Request 2: "What is my name?"The second request contains no evidence about Ana. To support a conversation, the client program must store earlier messages and include them in every new request.
The model receives a message list such as:
system: You are a concise assistant.
user: My name is Ana.
assistant: Nice to meet you, Ana.
user: What is my name?The model can answer because the client resends the relevant history.
A Minimal Terminal Chat Loop
A terminal chat loop repeatedly reads input, sends it to a model, prints the reply, and continues until the user quits.
The complete function represents your provider's SDK call. The loop itself does not need to know how the provider works.
def complete(messages):
"""Replace this with your model provider's API call."""
raise NotImplementedError
def main():
history = [
{"role": "system", "content": "You are a concise, helpful assistant."}
]
while True:
try:
text = input("you> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if text == "/quit":
break
if not text:
continue
history.append({"role": "user", "content": text})
reply = complete(history)
history.append({"role": "assistant", "content": reply})
print(f"bot> {reply}")
if __name__ == "__main__":
main()Keeping the Conversation as a List of Messages
Each message is a dictionary with a role and content. The roles identify who produced the text:
systemsets application behavior.usercontains the person's input.assistantcontains the model's replies.
Appending both sides of a successful turn is important. If you store only user messages, the model cannot see what it previously said. If a request fails, add the user message only after a successful call, or remove it in the error handler.
Setting Behavior with a System Message
A system message gives the model persistent instructions for this conversation. Keep it at the beginning of the history. For example, it can specify the tone, response format, or domain focus. It does not create memory by itself. The client still must resend the complete history.
Exercise
Why must a chatbot resend earlier messages to a stateless model API?
Show answer
Because each request is independent; the client must provide the earlier context in the new message list.