Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 46/ 160
03. AI Agents

Short-term Memory

Conversation history and working state that fit inside the active context window.

BeginnerChat History · Working Memory3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The AI only "remembers" what's in the text it's given each time, so the app has to keep the recent conversation and shrink the old parts.

Think of it like…

A whiteboard in a meeting room: everyone can see what's written on it, but it has limited space. To keep writing you erase old items or replace them with a one-line summary, and you keep the important decisions near the top.

Where you’ve seen it

A tutoring assistant keeps the system prompt (800 tokens), a running summary of the session (300 tokens), the last 8 messages verbatim (about 2,000 tokens) and a small working-state block listing the topic and the student's open question (150 tokens). Older turns are summarised once the history passes 6,000 tokens. The prompt stays near 3,500 tokens however long the session runs, cutting average cost per message by about 60 percent compared with sending the full transcript.

Words you’ll hear

Message history
The ordered user, assistant and tool messages sent with each model call.
Working memory
State injected for the current task: plan, findings, current goal.
Sliding window
Keeping only the most recent N messages or tokens.
Rolling summary
A running condensed record of older turns that is updated as the conversation grows.

Visual diagram

Loading interactive diagram

Theory & deep dive

What short-term memory contains

Each request includes the system prompt, the conversation so far (user messages, assistant replies, tool calls and results) and any injected context. The model has no memory beyond this: if a fact isn't in the window, it doesn't know it. Tool results are often the largest items (a 20,000-token API response), so decide what to keep: store the full result outside the prompt and keep only a short extract or a reference.

Working memory is structured state you maintain for the task, separate from raw messages: the user's goal, constraints they stated ("budget ₹8,000, no night flights"), the current plan, facts discovered, and open questions. Rewriting this block each turn (or updating it with the model's help) keeps the important information near the end of the prompt, where models use it most reliably, and survives summarisation.

A working-state block

"TASK: book a Pune→Delhi flight. CONSTRAINTS: ≤ ₹8,000, depart Fri after 6 pm, no layovers. FOUND: 3 options (IndiGo 7,650 at 19:10 selected by user). OPEN: seat preference." Stating constraints once in state prevents them being lost when old turns are summarised.

Key takeaway: The window is the memory; keep a compact working state with goals and constraints.

Managing growth: windows, summaries and trimming

Strategies, from simple to sophisticated: sliding window (keep the last N turns: simple, but forgets early requirements); token-budget trimming (drop the oldest messages until the prompt fits, always keeping the system prompt and any pinned items); rolling summarisation (when history passes a threshold, have a model summarise the oldest part into a few sentences and replace it); selective retention (pin messages that contain decisions, constraints or identifiers); and offloading (store full tool outputs or documents externally and retrieve them on demand).

Pitfalls: summaries lose details and can introduce errors, so keep exact values (order ids, amounts, dates) in structured state rather than prose; summarising invalidates the prompt-cache prefix, so do it at coarse intervals; and trimming mid-conversation can orphan tool results from their tool calls, which many APIs reject. Test with long conversations: ask about something said early and check whether the assistant still knows it, and track tokens per turn and cost as sessions lengthen.

A trimming rule

Budget 6,000 tokens. Always keep: system prompt, pinned constraints, the latest user message. Then add messages from newest to oldest until the budget is reached; replace everything older with the rolling summary. Never cut between a tool call and its result.

Key takeaway: Window, summarise, pin and offload; keep exact facts structured and tool-call pairs intact.

How it works, step by step

Step 1 of 4
Design

1. Budget the context

Allocate tokens to system prompt, summary, recent turns, working state and the reply.

800 + 300 + 2,000 + 150 + reply
Key numbers at this step
Plan
for the maximum

When to use it & trade-offs

What it is

Short-term memory is whatever the model can see right now: the message history of the current conversation plus any working state you inject (a scratchpad of findings, the current plan, the user's active task). LLMs are stateless, so "memory" in a chat is just your application re-sending earlier messages on every call. Because the context window is finite and every token costs money, short-term memory needs management: keep recent turns verbatim, summarise or drop older ones, and trim bulky tool outputs.

Why it matters: Chat quality depends on remembering what was said three turns ago, and cost and latency depend on how much you re-send. A naive "append everything" approach works for ten turns and then fails with context errors, high bills and degraded answers (the model loses track in a long, noisy history). Understanding what lives in the window, and how to budget it, is the foundation for every longer-running agent.

When to reach for it

  • Chat assistants and tutors
  • Agents with multi-step tasks
  • Any session that may exceed a few thousand tokens

When to avoid or be careful

  • Appending raw history forever
  • Putting exact numbers only in prose summaries
  • Cutting between a tool call and its result

Managing conversation history

Send full history
Best for: Short conversations

Strengths: Perfect fidelity; simplest.

Watch out: Cost and latency grow; hits limits.

Sliding window
Best for: Casual chat with little long-range dependence

Strengths: Simple, bounded.

Watch out: Forgets early requirements.

Rolling summary + pinned state
Best for: Long tasks and sessions

Strengths: Bounded cost; keeps key facts.

Watch out: Summaries lose detail; extra calls.

Interview signals & numbers to know

When this topic comes up

  • “The assistant forgets what I said earlier”
  • “Costs grow with conversation length”
  • “Context length exceeded”
  • Rolling summaries
  • Working memory

Benchmarks & rules of thumb

≈ 3,500 -
prompt tokens in the budgeted example, constant over time
−60% -
cost per message vs full transcript in the example
N = 6 – 10 -
typical recent-turn window

Common mistakes & follow-ups

Common interview mistakes

  • Summarising away a stated constraint such as a budget, then recommending options that break it.
  • Trimming history until a tool result is left without its call, causing an API error.
  • Re-summarising every turn, which breaks prompt caching and adds cost.

Likely interviewer follow-ups

  • How would you handle a 200-turn conversation?
  • What belongs in working memory versus the transcript?
  • How do you test that early facts aren't lost?
Interview tip: Describe the prompt as a budget with named slots (system, summary, recent, state, reply). It shows you manage context deliberately.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Short-term Memory with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Reflection
Next topic
Long-term Memory