Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
A half-finished terminal chat forgets your name, sends /reset to the model and crashes on a 429. Fix it in four tasks (memory, commands, errors, a history cap) against a stand-in model that counts the messages, until pytest says 5 passed.
What you will learn
- Give a chat tool memory by sending the earlier turns with every Messages API request
- Handle /reset, /exit and blank lines without calling the model
- Catch rate limit, server and connection errors so one busy signal never crashes the tool
- Cap the history to the last N exchanges and prove it all with five pytest checks
Before you start
- The Claude Messages API: Your First Call, Field by Field
- Streaming and Error Handling for LLM Calls
This one is a practice exercise. You build a small chat tool that runs on the command line. You start from a half-finished version and turn it into a tool a support team can actually rely on, with four things to add: memory, commands, error handling and a limit on the history.
The scenario
The support team wants to try out prompts on the command line before anything goes into the help-desk app. A colleague started the tool but didn't finish it. Here's the starter today, run against a stand-in test model:
you> My name is Priya.
bot> [test model reply] I can see 1 message(s) in this conversation. Your last message was: "My name is Priya."
you> What is my name?
bot> [test model reply] I can see 1 message(s) in this conversation. Your last message was: "What is my name?"
you> /reset
bot> [test model reply] I can see 1 message(s) in this conversation. Your last message was: "/reset"
The stand-in has a nice trick: it tells you how many messages it received. Look at the second question. It still says one message, so the tool forgot the first turn completely. And /reset was sent to the model as if it were a question.
Then the model answers with a 429, which means it is busy:
you> Where is order 1002?
Traceback ... anthropic.RateLimitError
The whole tool crashes. So in short: it forgets, it sends /reset to the model, and one busy signal crashes it.
What you start with
S04L07_ChatCli/
starter/chat.py you work here
starter/llm_client.py
solution/ open only after you finish
tests/test_chat.py the done-check
worksheet.md
starter/chat.pyhas aChatSessionclass with two methods:send(text)sends a message,handle(line)handles a line the user typed. Plus amain()loop. It runs, but has four TODOs.llm_client.py:make_client()gives the real Anthropic client whenANTHROPIC_API_KEYis set, otherwise a stand-in test model. No key needed, and nothing is spent.- Your own key, if you have one, goes in
.env(ANTHROPIC_API_KEY=your-key-here), and the same tool talks toclaude-sonnet-5-5.
Here's the starter's send and handle:
SYSTEM = "You are a concise assistant for a customer-support team. Answer in at most three sentences."
MAX_TURNS = 10 # user+assistant pairs kept in the history
class ChatSession:
def __init__(self, client: anthropic.Anthropic, model: str = MODEL, system: str = SYSTEM, max_turns: int = MAX_TURNS):
self.client = client
self.model = model
self.system = system
self.max_turns = max_turns
self.history: list[dict] = []
def send(self, text: str) -> str:
# TODO 1: send the earlier turns too (self.history), then store the user message and the reply.
# TODO 3: a 429, a lost connection or a 500 must not crash the tool; print a short message instead,
# and do not keep the failed turn in the history.
# TODO 4: keep at most self.max_turns user+assistant pairs in self.history.
response = self.client.messages.create(
model=self.model,
max_tokens=1024,
system=self.system,
messages=[{"role": "user", "content": text}],
)
return "".join(block.text for block in response.content if block.type == "text")
def handle(self, line: str) -> str | None:
"""One line from the user. Returns what to print, or None to quit."""
# TODO 2: "/reset" clears the history and returns "(conversation cleared)";
# "/exit" and "/quit" return None; an empty line returns "" without calling the model.
return self.send(line.strip())
See the bug in messages=? Only the newest message goes out. The API keeps nothing between calls, so a chat tool has to send the conversation itself, every time. That's the idea from The Claude Messages API: Your First Call, and this exercise is where you feel it.
Your four tasks
- Memory. Send the earlier turns with every request (
self.historyplus the new user message), and keep the user message and the reply after a successful call. The stand-in should say 3 messages on your second question. - Commands.
/resetclears the history and prints(conversation cleared);/exitand/quitstop the tool; a blank line never calls the model. - Errors. A 429, a 500 or a lost connection prints a short message in brackets, like
(the model is busy right now, try again in a moment), and the tool keeps running. The failed turn is not kept in the history. Ifstop_reasonis"refusal", print a short note instead of an empty reply. - History cap. Keep at most
max_turnsuser+assistant pairs (default 10), dropping the oldest, so a long session doesn't keep growing, and your bill doesn't either.
Try them yourself before you read on. Work one task at a time and run the tests after each one.
What done looks like
One command, one honest answer. From S04L07_ChatCli/:
pytest -q
On the starter, all five checks fail:
FAILED test_task1_remembers_earlier_turns
FAILED test_task2_reset_and_exit_and_blank
FAILED test_task3_errors_do_not_crash[429]
FAILED test_task3_errors_do_not_crash[500]
FAILED test_task4_history_is_capped
5 failed
Your goal is 5 passed. After that, try it by hand: cd starter, python chat.py, tell it your name, ask for it back, /reset, and ask again.
What the tests check
The tests use their own stand-in, a Recorder, that replies like the real API, remembers every request it was sent and can fail on purpose with a status code. Then they check what your ChatSession did:
| Test | What it does | What must be true |
|---|---|---|
test_task1_remembers_earlier_turns | "My name is Priya.", then "What is my name?" | the second request's roles are user, assistant, user, and the first content is "My name is Priya." |
test_task2_reset_and_exit_and_blank | "Hello", then /reset, a blank line, /exit | (conversation cleared), empty history, "", None, and only 1 request ever reached the model |
test_task3_errors_do_not_crash[429] and [500] | the first call fails with that status, then the same question again | the reply starts with (, the history stays empty, and after the retry it holds 2 messages |
test_task4_history_is_capped | max_turns=3, six questions | 6 messages in the history, the first is "Question 3", and the last request sent 7 messages |
The solution, explained
Only open solution/chat.py after your tests pass, then compare. Here are its send and handle:
def send(self, text: str) -> str:
"""Send one user message with the whole (trimmed) history; keep the history only on success."""
messages = self.history + [{"role": "user", "content": text}]
try:
response = self.client.messages.create(
model=self.model, max_tokens=1024, system=self.system, messages=messages,
)
except anthropic.RateLimitError:
return "(the model is busy right now, try again in a moment)"
except anthropic.APIConnectionError:
return "(could not reach the model, check your connection)"
except anthropic.APIStatusError as error:
return f"(the API returned an error: {error.status_code})"
if response.stop_reason == "refusal":
return "(the model declined this request)"
reply = "".join(block.text for block in response.content if block.type == "text")
self.history = (messages + [{"role": "assistant", "content": reply}])[-2 * self.max_turns:]
return reply
def handle(self, line: str) -> str | None:
"""One line from the user. Returns what to print, or None to quit."""
line = line.strip()
if line in ("/exit", "/quit"):
return None
if line == "/reset":
self.history = []
return "(conversation cleared)"
if not line:
return ""
return self.send(line)
Task 1: memory
messages = self.history + [new user message] builds the full conversation for this request. self.history is only updated at the end, after a successful reply, with both the user message and the assistant reply. So on the second question the model sees three messages: the first question, its answer, and the new question.
max_turns pairs, so a long session stays small.Task 2: commands
handle checks the line before anything reaches the model. /exit and /quit return None, which tells main() to break the loop. /reset empties the list. A blank line returns "", and main() prints nothing for it. Only real text goes to send.
Task 3: errors
The call sits inside try, and each error gets its own short message in brackets. The order of the except lines matters: RateLimitError is a more specific kind of APIStatusError, so it has to come first, or the 429 would get the general message. A lost connection has no status code, so APIConnectionError is caught on its own.
Notice what does not happen on an error: the function returns before the line that updates self.history. The failed turn is simply not kept. Here's the solution against a model that answers 429 first:
you> Where is order 1002?
bot> (the model is busy right now, try again in a moment)
you> Where is order 1002?
bot> [test model reply] I can see 1 message(s) in this conversation. Your last message was: "Where is order 1002?"
The second try sees 1 message, not 2: the failed question never went into the history. This tool shows a message and lets the person try again. Retrying automatically with a growing wait, and the trap of two retry layers, is covered in Streaming and Error Handling for LLM Calls.
Task 4: the history cap
One slice does it: [-2 * self.max_turns:]. Each turn is two messages, user and assistant, so with the default max_turns=10 the tool keeps the last 20 messages and drops the oldest. The history always starts with a user message, because it is cut on whole pairs.
The run
The same scripted conversation as the starter, now with the solution:
you> My name is Priya.
bot> [test model reply] I can see 1 message(s) in this conversation. Your last message was: "My name is Priya."
you> What is my name?
bot> [test model reply] I can see 3 message(s) in this conversation. Your last message was: "What is my name?"
you> /reset
bot> (conversation cleared)
you> What is my name?
bot> [test model reply] I can see 1 message(s) in this conversation. Your last message was: "What is my name?"
Three messages on the second question: the memory works. /reset never reached the model, and after it the count is back to one. Run the tests on the solution (CHAT_DIR=solution pytest -q, or python demo.py tests) and you get:
..... [100%]
5 passed
Common mistakes
- Saving the user message before the call. Then a 429 leaves a question with no answer in the history, and test 3 fails.
- Catching
APIStatusErrorbeforeRateLimitError. The 429 never reaches its own friendly message. - Sending commands to
sendand checking them afterwards. Test 2 counts the requests: only one may reach the model. - Capping by messages instead of pairs, for example
[-self.max_turns:]. You keep half the turns you meant to, and the history can start with an assistant message. - Opening the solution first. The point is the five red lines turning green, one task at a time.
Quick recap
| Task | The fix | Proof |
|---|---|---|
| Memory | self.history + [user message], saved after success | 3 messages on the second question |
| Commands | check /exit, /quit, /reset, blank in handle | only 1 request reaches the model |
| Errors | try/except per error type, history untouched | a short message in brackets, no traceback |
| History cap | [-2 * self.max_turns:] | first message is "Question 3" with max_turns=3 |
| Done | pytest -q | 5 passed |
Stretch tasks
- Stream the reply word by word with
client.messages.stream(...). - Add
/saveto write the conversation tochat-YYYYMMDD-HHMM.json, and/load <file>to restore it. - Add a
--modelcommand-line flag, and/system <text>to change the system prompt mid-session. - With a real key, print the
usageinput and output tokens after each reply.
The starter, the solution, the tests and the worksheet are in the StudyEasy AI Community, free to join.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.