Topics / 🔗 LangChain & LangGraph / 🧠 Level 48: LangChain: Memory & Context

Python exercise · about 5 minutes · free

Trim the History Without Breaking It

Long chats cost more and eventually overflow the context window. Cutting old messages is easy. Cutting them without corrupting the conversation is the skill.

A model is stateless: you resend the whole conversation every time. Short-term memory in LangChain is that message list plus a checkpointer that saves it per thread_id. When the list grows, one simple fix is to trim it in a before_model middleware: keep the system instructions and only the most recent messages.

The trap: a tool message only makes sense after the assistant message that asked for it. If you cut the assistant message but keep the tool result, many providers reject the history. So after trimming, drop any leading tool messages.

Prices, versions and service names last checked 2026-11-19. They change, so confirm on the official pages before you rely on them.

Table. history: #, role, kept?; 1 | system | yes; 2 | user | no; 3 | assistant (call) | no; 4 | tool (result) | orphan: drop; 5 | assistant | yes; 6 | user | yes. Operation: keep system + last 3, drop orphan tool. Result after trimming: role; system; assistant; userhistory#rolekept?1systemyes2userno3assistant (call)no4tool (result)orphan: drop5assistantyes6useryesafter trimmingrolesystemassistantuserdrop orphan toolkeep system + last 3,
Your quest: Write trim_messages(messages, keep_last). Keep every system message (in order) and then the last keep_last non-system messages. If the kept tail now starts with tool messages, remove them. keep_last=0 keeps only the system messages.
Try it now Runs in your browser. No sign-in needed. Ctrl+Enter to run.
HintSplit into <code>system</code> and <code>rest</code>. Take <code>tail = rest[-keep_last:]</code> only when <code>keep_last &gt; 0</code> (<code>rest[-0:]</code> is the whole list!). Then <code>while tail and tail[0]['role'] == 'tool'</code> drop the first one.
Output appears here.

Open it in the full course → Free with Google: saves your progress and unlocks 627 lessons.

In this level you'll learn:
More in Level 48: LangChain: Memory & Context

Share on LinkedIn