Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. LLM Fundamentals

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.

Chaand Sheikh

·27 November 2026LLM Fundamentals

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.py has a ChatSession class with two methods: send(text) sends a message, handle(line) handles a line the user typed. Plus a main() loop. It runs, but has four TODOs.
  • llm_client.py: make_client() gives the real Anthropic client when ANTHROPIC_API_KEY is 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 to claude-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

  1. Memory. Send the earlier turns with every request (self.history plus 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.
  2. Commands. /reset clears the history and prints (conversation cleared); /exit and /quit stop the tool; a blank line never calls the model.
  3. 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. If stop_reason is "refusal", print a short note instead of an empty reply.
  4. History cap. Keep at most max_turns user+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:

TestWhat it doesWhat 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 againthe reply starts with (, the history stays empty, and after the retry it holds 2 messages
test_task4_history_is_cappedmax_turns=3, six questions6 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.

The history sent with every request, and the cap Memory: the tool resends the conversation request 1 user 1 message request 2 user assistant user 3 messages History cap: max_turns=3, after six questions Q0, Q1, Q2 pairs dropped Q3 + reply Q4 + reply Q5 + reply history: 6 messages, first is "Question 3" The next request sends these 6 plus the new question: 7 messages.
Every request carries the history. The cap keeps the last 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 APIStatusError before RateLimitError. The 429 never reaches its own friendly message.
  • Sending commands to send and 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

TaskThe fixProof
Memoryself.history + [user message], saved after success3 messages on the second question
Commandscheck /exit, /quit, /reset, blank in handleonly 1 request reaches the model
Errorstry/except per error type, history untoucheda short message in brackets, no traceback
History cap[-2 * self.max_turns:]first message is "Question 3" with max_turns=3
Donepytest -q5 passed

Stretch tasks

  • Stream the reply word by word with client.messages.stream(...).
  • Add /save to write the conversation to chat-YYYYMMDD-HHMM.json, and /load <file> to restore it.
  • Add a --model command-line flag, and /system <text> to change the system prompt mid-session.
  • With a real key, print the usage input and output tokens after each reply.

The starter, the solution, the tests and the worksheet are in the StudyEasy AI Community, free to join.

Keep going in AI Engineering · 9 of 66

Previous
Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
Next post
Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • The scenario
  • What you start with
  • Your four tasks
  • What done looks like
  • What the tests check
  • The solution, explained
  • Task 1: memory
  • Task 2: commands
  • Task 3: errors
  • Task 4: the history cap
  • The run
  • Common mistakes
  • Quick recap
  • Stretch tasks
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.