Sam Austinon December 4, 202614 min read

AI Agent Memory Explained: Trimming vs. Summarization With the OpenAI API

AI Agent Memory Explained: Trimming vs. Summarization With the OpenAI API
Contents

Figure 1: AI Agent Memory Explained: Trimming vs. Summarization With the OpenAI API — a library of shelves, because an agent's memory is a stack of messages somebody has to decide what to keep

Your agent greeted Maria by name on turn three and then asked for her name again on turn twenty. Nothing broke. The application simply stopped sending the earlier messages, and the model had no way to know they ever existed.

That confusion costs teams weeks, because the fix is not a better model. It is a data-structure decision that most tutorials skip: what goes into the request.

I have shipped this twice, once badly. The first version resent the whole transcript and quietly burned through budget on a 4,000-message support thread. The second version trimmed aggressively and forgot a customer's refund promise. This post is the version that finally worked.

Why Your Agent Forgets

A chat API is stateless. Every request is a fresh conversation as far as the model is concerned, because the model keeps nothing between calls.

You can prove it in ten lines:

from openai import OpenAI

client = OpenAI()
MODEL = "gpt-4.1-mini"

client.responses.create(model=MODEL, input="Hi! My name is Maria and I live in Athens.")

r = client.responses.create(model=MODEL, input="What is my name and where do I live?")
print(r.output_text)

The second call knows nothing about the first. Ask it to recall Maria and you get either a polite "you haven't told me" or a confident hallucination, which is worse.

Agent memory is a property of your system, not of the model. Your code decides what is retained, where it lives, and when it is put back in front of the model.

The OpenAI API does offer shortcuts. Passing previous_response_id links a new request to an earlier response, and the Conversations API stores turns server-side. Both are conveniences over the same mechanics. If you understand the message list, you understand what those features are doing for you, and you can reason about their cost.

Short-Term Memory Is Just a List

The simplest memory implementation is a Python list of messages.

  1. Start with a system or developer instruction.
  2. Append each user message.
  3. Send the whole list as input.
  4. Append the assistant reply to the same list.
messages = [{"role": "system", "content": "You are a helpful assistant."}]

def chat(user_message):
    messages.append({"role": "user", "content": user_message})

    response = client.responses.create(model=MODEL, input=messages)
    reply = response.output_text

    messages.append({"role": "assistant", "content": reply})
    return reply

That is the entire memory loop: user message → store → model → reply → store → next request.

The "memory" you observe is controlled reuse of text, nothing more.

This is also why memory bugs are so easy to reproduce. If the agent forgets something, print the list. The answer is always visible.

What a Growing History Actually Costs

Keeping everything sounds safe, and for a short chat it is. The problem is arithmetic.

Symptom What is happening Where you feel it
Rising input tokens Every turn resends everything before it Monthly bill, per-request cost
Rising latency More tokens to prefill before the first token Streaming feels slow, timeouts appear
Diffuse answers Key facts buried in thousands of tokens Quality drops without any error
Context ceiling History approaches the window limit Hard failures, truncated requests

The growth is quadratic in a subtle way: turn n sends roughly n messages, so a 200-turn conversation pays for the transcript 200 times. You are not paying for memory; you are paying for re-reading it.

Context windows are large now, and that makes the problem sneakier. A 400k-token window does not make a 400k-token prompt cheap, fast, or focused.

Two Strategies: Trim or Summarize

Once history outgrows its budget, you have two honest options:

  • Trimming: drop older messages and keep the most recent ones.
  • Summarization: replace older messages with a compressed summary and keep recent messages verbatim.

Both reduce what you send. Both lose information. The difference is who decides what gets lost: you, or a model.

Trimming: Delete the Oldest

Trimming sets a retention limit and discards everything before it.

def trim_messages(messages, max_messages=6):
    system = messages[:1]
    recent = messages[1:][-max_messages:]
    return system + recent

Always preserve the instruction message. Losing the system prompt is the fastest way to turn a careful agent into a generic one.

Trimming has four real advantages:

  1. Free. No extra model call, no extra latency.
  2. Deterministic. Same history and limit, same result, every time.
  3. Simple. A slice and a len() check.
  4. Testable. You can assert exactly which messages survive.

Its weakness is just as simple. Trimming forgets by design, and it cannot tell a throwaway greeting from a stated allergy.

In the support example, Maria mentions her plan tier in turn two. Twenty turns later, the limit has pushed it out, and the agent starts quoting the wrong refund policy with total confidence.

Summarization: Compress the Oldest

Summarization keeps recent messages intact and replaces the older block with a model-written digest.

def summarize_history(messages, keep_last=6):
    system, rest = messages[:1], messages[1:]
    if len(rest) <= keep_last:
        return messages

    old, recent = rest[:-keep_last], rest[-keep_last:]

    transcript = "\n".join(f"{m['role']}: {m['content']}" for m in old)

    summary = client.responses.create(
        model=MODEL,
        input=(
            "Summarize this conversation in a few sentences. "
            "Preserve the user's name, location, preferences, "
            "constraints, and any decision already made.\n\n" + transcript
        ),
    ).output_text

    digest = {
        "role": "system",
        "content": f"Summary of earlier conversation: {summary}",
    }
    return system + [digest] + recent

The prompt is the important part. A summary is only as good as the instruction that produced it, so name the categories of fact you cannot afford to lose.

That is why summarization preserves more context than trimming. Maria's name survives because you told the summarizer to keep it.

The Risk You Are Buying

Summaries are generated, so they can:

  • Drop a detail nobody flagged as important.
  • Compress two decisions into one that was never made.
  • Drift in tone or certainty across repeated re-summarization.
  • Smuggle in an inference the user never stated.

Trimming loses information predictably. Summarization loses it plausibly, which is harder to catch in review.

One more trap: re-summarizing a summary every few turns compounds distortion. Keep the original transcript for the summary window and regenerate from source, or refresh the digest on a schedule rather than on every message.

Trimming vs. Summarization

Feature Trimming Summarization
Approach Delete older messages Compress older messages
Extra model call No Yes, one per refresh
Cost Lowest Higher
Behavior Deterministic Model-dependent
Information kept Low Higher, if prompted well
Implementation Very simple Moderate
Failure mode Facts vanish Facts get distorted
Recent messages Kept verbatim Kept verbatim
Cross-session memory None None

Neither strategy is better in the abstract. The right choice depends on what forgetting costs you.

When Trimming Wins

Trim when the recent exchange carries almost all the value:

  • Short support or FAQ interactions.
  • Stateless command-style tools.
  • High-volume, low-stakes traffic where cost dominates.
  • Systems where you need reproducible, auditable behavior.

A deterministic window is also easier to test. If you can write "given these twelve messages, these six survive," you can unit-test your memory policy like any other function.

When Summarization Wins

Summarize when early context keeps paying rent:

  • Long research or debugging sessions.
  • Planning workflows with commitments made early.
  • Assistants that accumulate user preferences.
  • Multi-step tasks where a decision in step 2 constrains step 20.

The extra call is cheap compared with the cost of a wrong answer, especially if you regenerate the summary only every 10 to 20 turns rather than on every request.

Neither One Is Long-Term Memory

Here is the distinction that gets blurred constantly.

A summary lives in the same Python list as everything else. End the process, and the summary dies with the transcript.

Short-term memory covers the current session: what was asked, what was decided, which facts came up. Long-term memory covers a different session, days later, and requires storage outside the conversation plus retrieval logic to bring the right pieces back.

Trimming and summarization are context management. They are not persistence. If you need an agent to greet Maria next Tuesday, you need a store and a retrieval policy, which is the subject of my agent memory architecture guide.

Memory Is a System Around the Model

The useful mental model: memory surrounds the model rather than living inside it.

That surrounding system answers five questions:

  1. What is worth retaining?
  2. Where is it stored?
  3. When is it retrieved?
  4. Which pieces enter the context window now?
  5. How much history goes in this particular request?

Reframed that way, agent memory becomes an ordinary engineering problem with budgets, interfaces, and tests.

Building the Loop in Python

A complete minimal agent needs four steps:

  1. Initialize with the instruction message.
  2. Append the user turn.
  3. Fit the history to budget, by trimming or summarizing.
  4. Send, then store the reply.
def respond(user_message, max_messages=8):
    messages.append({"role": "user", "content": user_message})

    trimmed = trim_messages(messages, max_messages=max_messages)
    response = client.responses.create(model=MODEL, input=trimmed)

    messages.append({"role": "assistant", "content": response.output_text})
    return response.output_text

Note the split: messages is the durable session log, while trimmed is the disposable view sent to the model. Keeping the full log and sending a window lets you change policy later without losing data.

Designing Better Memory

Optimize for the right information at the right time, not for maximum storage.

Goal Lever
Relevance Retrieve by similarity or recency, not by dumping everything
Cost Window size, summary refresh rate, smaller model for summarization
Latency Fewer tokens, cached instruction prefix
Preservation Pinned facts, structured slots for name and preferences
Reliability Validate summaries, keep the raw transcript as the source of truth

A pattern that works well in production combines both strategies: pin a short "known facts" block, summarize the middle, keep the last six turns verbatim. You get determinism where it matters and compression where you need it.

Common Pitfalls

These cost me real debugging hours:

  • Dropping the system message. Trimming from index 0 silently deletes your instructions.
  • Separating tool calls from their results. A window boundary between an assistant tool call and its output produces API errors.
  • Assuming previous_response_id replaces your own bookkeeping. You still need to know what the conversation contains.
  • Summarizing on every turn. Cost and distortion both climb; refresh on an interval instead.
  • Counting messages instead of tokens. Six long messages can outweigh sixty short ones.
  • Testing only happy paths. Try a 50-turn conversation and check whether the key fact survives.
  • Calling a summary "long-term memory." It dies with the process.

Best Book to Read

CoverBookDescriptionGet it
Cover of “AI Engineering: Building Applications with Foundation Models” AI Engineering: Building Applications with Foundation Modelsby Chip Huyen context management, evaluation, cost trade-offs, and the system design around a model, which is exactly where agent memory lives [4]. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read the chapter on evaluation before you tune your window size. You cannot choose a retention policy without a task-level metric, and the book is unusually clear about building one.

Wrapping Up

Agent memory is a system you build, not a feature you enable. The model sees only the current request, so every "remembered" fact was placed there by your code.

Trimming is cheap, deterministic, and forgetful. Summarization preserves more but pays for it with a model call and the risk of plausible distortion. Neither one survives the end of a session.

Start by logging every request and counting tokens. Then set a window, add a pinned facts block, and summarize the middle only when the window overflows. That order keeps the cost visible and the regressions obvious.

Frequently Asked Questions

What is short-term memory in an AI agent?

Short-term memory is the conversation history an agent retains during an active session. It usually consists of previous user messages and assistant replies that the application resends as context on every request. Nothing is stored inside the model between calls.

What is the difference between trimming and summarization in agent memory?

Trimming deletes older messages and keeps a fixed number of recent ones, so it costs nothing extra and behaves deterministically. Summarization replaces older messages with a model-written summary, which preserves more context but adds a model call, latency, and the risk of omissions or distortions.

Does summarizing a conversation create long-term memory?

No. A summary lives in the same message list as the rest of the history, so it disappears when the session ends. Persistent memory needs storage outside the conversation, plus retrieval logic that decides what to reload later.

How many messages should I keep before trimming?

There is no universal number. Keep enough to cover the longest realistic dependency in your task, then measure. A support bot often works with 6 to 10 recent messages, while a coding assistant may need far more, and a summary anchored to the oldest decisions.

Does the OpenAI API remember previous requests automatically?

Not by default. Each request is stateless unless you resend the history or link it with something like previous_response_id. The model only sees what is inside the current request.

Sources

  • [1] OpenAI platform documentation, Conversation state and the Responses API - how previous_response_id and conversations carry turns forward, and what the API does and does not retain: platform.openai.com
  • [2] Anthropic, Effective Context Engineering for AI Agents (2025) - practical treatment of context budgets, compaction, and note-taking for long-running agents: anthropic.com
  • [3] Packer et al., MemGPT: Towards LLMs as Operating Systems (2023) - the tiered memory design that separates a small active context from larger external storage: arxiv.org
  • [4] Huyen, AI Engineering: Building Applications with Foundation Models (O'Reilly, 2025) - evaluation, cost, latency, and context management for production LLM systems: oreilly.com
  • [5] Park et al., Generative Agents: Interactive Simulacra of Human Behavior (2023) - the memory stream with retrieval, reflection, and summarization that most agent memory designs echo: arxiv.org

What are You Looking For?

esc