Sub topic 2
Isolating the Model Call Behind One Function
Assume you know Python functions, lists, dictionaries, exceptions, and how a chat API accepts role-tagged messages. A model API is usually stateless: it does not remember an earlier request unless your program sends the earlier messages again.
One function owns the model call
Keep provider-specific code in one function. The rest of the chatbot should only know that it passes a message list and receives reply text.
| Component | Responsibility |
|---|---|
| `complete` | Sends messages to the model and returns text |
| Chat loop | Reads input and updates history |
| `trim_history` | Keeps requests within the context limit |
import json
from pathlib import Path
HISTORY_FILE = Path("chat-history.json")
def complete(messages):
"""Replace this body with your provider SDK call."""
return f"(model saw {len(messages)} messages)"
def trim_history(history, max_messages=6):
system = [m for m in history if m["role"] == "system"]
other = [m for m in history if m["role"] != "system"][-max_messages:]
# Do not begin with an assistant message after trimming.
while other and other[0]["role"] != "user":
other.pop(0)
return system + other
def save_history(history):
temporary = Path(str(HISTORY_FILE) + ".tmp")
temporary.write_text(json.dumps(history, indent=2), encoding="utf-8")
temporary.replace(HISTORY_FILE)
def load_history():
if not HISTORY_FILE.exists():
return [{"role": "system", "content": "Be concise and helpful."}]
return json.loads(HISTORY_FILE.read_text(encoding="utf-8"))
def main():
history = load_history()
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})
request = trim_history(history)
reply = complete(request)
history.append({"role": "assistant", "content": reply})
save_history(history)
print(f"bot> {reply}")
if __name__ == "__main__":
main()Why history cannot grow forever
A model has a context window, the maximum amount of text it can process in one request. The limit includes the system message, previous conversation, new input, and sometimes the requested reply. A long history can make requests fail or leave too little space for an answer.
Keeping recent turns with a sliding window
A sliding window keeps the newest messages and drops older ones. The system message remains because it defines the bot's behavior. Removing only complete user-and-assistant turns avoids broken conversation structure.
Remembering across runs with JSON
JSON is a text format that represents Python dictionaries and lists. The example saves after every successful reply. Writing a temporary file first, then replacing the old file, reduces the chance of leaving a partly written history after an interruption.
Exercise
Why does complete receive request instead of the full history?
Show answer
request is the trimmed history, so the model receives the system message and recent turns without exceeding its context window.