AI Agents, Evergreen

How AI Agents Maintain State and Context Across Multi-Turn Interactions

Overwhelmed cartoon agent buried under chat bubbles and notes under the headline MORE CONTEXT, LESS RECALL

When an AI agent answers your third question as if it remembers the first two, agent state and context are doing the work behind the scenes. The language model itself remembers nothing between calls. Everything that looks like memory is machinery around the model: the history sent again on each turn, the summaries that replace older turns, and the stores that hold facts and progress outside any single conversation.

What agent state and context mean in a multi-turn interaction

Three different things hide inside the phrase agent memory. Conversation history is the record of the turns exchanged so far: what the user said, what the agent replied, and what tools returned. Task state is the progress of the work: the goal, the steps done, the items still pending, and the tool results the agent still needs. Durable user facts outlive one conversation: a preference, an account detail, or a fact stated last week that still applies today.

Context is narrower than all three. Anthropic defines context as the set of tokens included when sampling from a large language model, and context engineering as the strategies for curating and maintaining the optimal set of those tokens during inference. In a multi-turn agent, that context state includes the system instructions, the tools, any Model Context Protocol connections, external data, and the message history. On every turn, the builder decides which pieces of history, state, and stored fact earn a place in that limited set.

How one turn is processed: the stateless model and the resent history

Each text-generation request is independent and stateless. That is OpenAI’s own description of its API: a multi-turn conversation is implemented by providing additional messages as parameters to each request. The client appends each new turn to the history and sends the growing history again. The model sees only what arrives in that request.

A turn has a simple shape. The user sends a message. Your code assembles the request: system instructions, the history so far, any retrieved material, and the tool definitions. The model replies with text, a tool call, or both. Your code runs any requested tool, appends the result, and sends the history back for the next step, repeating until the model gives a final answer or a stop condition fires.

The sketch below shows that loop in its simplest form. It is a simplified illustration, not a vendor SDK example: it uses a generic model call so the shape of the loop, rather than any one provider’s interface, is what you see.

messages = []

def run_turn(user_message):
    messages.append({"role": "user", "content": user_message})
    while True:
        reply = call_model(messages)
        messages.append(reply)
        if reply.is_final_answer:
            return reply.text
        tool_result = run_tool(reply.tool_call)
        messages.append(tool_result)

Two consequences follow. In an untrimmed implementation that resends the full history, growing input can increase processing cost and latency. And every turn boundary is a decision point: your code decides what to keep verbatim, what to compress, what to store outside the conversation, and what to drop. OpenAI’s Conversations API and its previous_response_id parameter move the storage job server-side, but the history still grows and still needs trimming or summarising before it outgrows the window.

Keeping context inside one conversation

Cartoon robot feeding a long scroll of chat bubbles into a funnel, with one summary card coming out

The simplest strategy is to keep the whole transcript and send it again each time. It works until the history grows long enough to cost more, respond more slowly, and recall less reliably. Builders use four techniques, often together. Trimming removes messages: a sliding window keeps only the most recent turns, which suits short interactions where early turns stop mattering, but anything dropped is gone, including a constraint stated early and not repeated. Deleting specific messages applies the same idea selectively, for example removing stale tool output while keeping the user’s instructions.

Summarisation keeps the gist and drops the verbatim detail. When a conversation approaches a limit, a model summarises the older turns and the summary replaces them. LlamaIndex provides this as ChatSummaryMemoryBuffer, which limits history to a token length and iteratively summarises the messages that do not fit, in contrast to its ChatMemoryBuffer, which simply truncates history after a token limit and can remove relevant information. Anthropic’s version is compaction: a conversation nearing the limit is summarised and a new context window starts with the summary. In the cookbook’s runner-driven form, the API summarises server-side and returns a single compaction block; the runner replaces the history with that block and continues. The cookbook describes server-side compaction as triggering at a developer-set threshold of 50,000 input tokens or more. The loss summarisation causes is specific: a decisive detail in an early turn can be the detail the summary drops.

Selective retrieval, the fourth technique, fetches only the earlier turns or passages relevant to the current turn instead of summarising everything. A related illustrative design option is deferred loading through identifiers: keep lightweight references, such as file paths or stored queries, and load the full material only when needed. Retrieval avoids paying for a full transcript on every turn, but it can miss the one earlier turn that mattered.

The reason to use any of these techniques is not only cost. Anthropic describes context rot: as the number of tokens in the context window increases, the model’s ability to accurately recall information from that context decreases. The cause is architectural: every token can attend to every other token, producing n squared pairwise relationships for n tokens, and capturing those relationships gets stretched thin as context grows. The result is a performance gradient rather than a hard cliff, with reduced precision for retrieval and long-range reasoning. Anthropic’s principle follows directly: find the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome.

A multi-turn walkthrough: what is kept, summarised, and dropped

Consider an illustrative troubleshooting conversation. A user reports that a device will not sync. The agent asks which device; the user names a tablet and adds that the problem started after an update. The agent checks a knowledge base and suggests a step. The user tries it, reports that it did not work, and corrects an earlier detail: the device is a phone, not a tablet. The agent revises its advice, the user confirms the fix, and the conversation ends with a summary of what resolved it.

In the first turns, the full transcript is resent: symptom, device, and update timing are all in context. As tool results accumulate, a sliding window would drop the earliest turns, exactly where the update timing lives. Summarisation would keep a compressed version, perhaps “user reports sync failure after an update,” and lose the exact wording of the symptom. The correction is where current-value tracking helps, as a recommended design choice: the agent keeps a structured current device value, updated to phone, while the transcript retains the earlier tablet statement as history. Keeping both is not automatically a conflict: the current value drives the next action, and the history preserves what was said and when. Problems arise when a summary or a retrieved fact presents the superseded value as current.

A correction handled this way is one recommended approach. Other approaches, including prompting the model to prefer the latest statement, can also work in some designs; the evidence for this article does not settle which is best in general. History should be retained when the user, an auditor, or a later turn needs to see what was originally said; the current value should be overwritten when later actions must use the corrected fact. Turn by turn, the record for this conversation might look like this, with illustrative values: turn 1, the symptom and the tablet statement enter context in full; turn 2, the knowledge-base result is added and the update timing remains in context; turn 3, the correction updates the structured current device value to phone while the transcript keeps the earlier statement; turn 4, only the current value and a short summary travel forward, and the full tool output is dropped. The structured state after the correction could be recorded as:

{"current_device": "phone", "earlier_device_statement": "tablet", "symptom": "will not sync", "onset": "after an update"}

A debug record for the correction turn would note the history sent, any summary used, the current device value before and after the correction, and the stored facts retrieved.

Resuming after a pause: session state and checkpointing

When a conversation pauses, what survives until the user returns? Session state is the answer for a single thread: the history, the task state, and any pending tool work, held under a session identifier so the next request can pick up where the last one stopped.

Checkpointing makes resumption reliable. LangGraph’s persistence layer provides two complementary systems. Checkpointers persist a thread’s graph state as checkpoints: short-term, thread-scoped memory for conversation continuity, human-in-the-loop workflows, and fault tolerance, accessed by passing a thread_id in the graph configuration. Stores persist application-defined data outside the graph state: long-term, cross-thread memory such as user preferences and facts. LangGraph’s summary is that most applications can use both: a checkpointer tracks the current thread, and a store tracks durable information across threads.

A checkpoint is a snapshot, so resuming is only as good as the last one. How a framework handles a turn that ends mid-tool-call is a design concern to check in that framework’s documented semantics: whether a snapshot records an unanswered tool call, and what state is needed to resume reliably, depends on the framework. Checkpoint timing likewise follows the chosen framework’s documented semantics rather than a universal schedule. A resumed session is also not a remembered user: restoring a thread brings back that conversation’s progress, but not facts from other conversations. That is the next section’s job.

Remembering across conversations: long-term agent memory

Cartoon robot filing memory cards into drawers marked with clock, star and gear symbols

Long-term memory is everything that persists outside the context window and is selected back into it later. One taxonomy, presented by Mem0 from the CoALA framework and rooted in cognitive science, distinguishes working, episodic, semantic, and procedural memory. As Mem0’s presentation stresses, these are architectural categories, not built-in features of a language model. A model ships with none of them; each is designed and added.

Working memory is the current context window: the active conversation, retrieved material, and tool outputs, bounded and gone at the end of the request unless something writes it out. Episodic memory is what happened in past sessions: specific interactions and outcomes, tied to a time. Semantic memory is durable facts: preferences, account details, and learned entities, not tied to one event. Procedural memory is learned behaviour: which tool sequence worked last time, and which standing instructions shape how the agent should behave.

The reference design for retrieval comes from Park and colleagues’ Generative Agents paper (2023): a memory stream recording experiences in natural language, reflection synthesising those memories into higher-level inferences written back into the stream, and retrieval combining relevance, recency, and importance to surface the records needed for the agent’s next behaviour. That three-factor combination is the paper’s retrieval description. How a builder weights the three factors in their own store is a separate design choice, illustrated here only as an option to consider when implementing retrieval.

Stores vary in organisation, but share a write path and a read path designed separately. One possible write policy is to extract facts or events from a finished conversation rather than storing every message; other application-defined records and write timings are also possible, depending on the store. The read path scores stored items against the current turn and injects only the winners into context. What matters for recall is the material selected into context on each turn: retrieving generously into the window can recreate the crowding that trimming and summarising were meant to avoid, whatever the size of the external store.

Choosing a combination and avoiding common failures

These mechanisms can be layered. A useful default: full history inside the current conversation until it approaches a threshold, summarisation or compaction past that threshold, a checkpointer holding the thread’s state so the conversation can resume, and a long-term store holding facts and events under the store’s chosen write policy, retrieved selectively into new conversations.

Choose by answering three questions. How long do conversations run? Short ones may need nothing beyond resending history. How often do users pause and return? Frequent pauses make checkpointing the priority. Must any durable user-specific or application-level information — facts, past episodes, or procedures — be available across threads? A store earns its complexity, storage, and privacy obligations when the answer is yes for some such information, and the trade-off is between that availability and the cost and care of maintaining it. A store holding personal facts needs the same care as any user-data store: what is kept, for how long, who can see it, and how a user corrects or deletes it.

The failure modes follow the mechanisms. Summarisation drops verbatim detail, so keep exact values later turns depend on, such as identifiers and dates, in structured task state rather than prose history. Stored facts go stale or contradict each other, and there is no single standard answer: builders choose between overwriting, versioning, and flagging a contradiction, and should log the choice. Over-retrieval crowds the window with plausible but irrelevant memories; retrieval should be scored and capped. Audit an agent that forgets by replaying what the model saw on each turn: possible paths to investigate are a turn that was trimmed, a summary that dropped it, or a retrieval step that never fetched it.

Done well, agent state and context are invisible: a conversation that continues naturally, a task that resumes where it stopped, and an agent that remembers what matters. That is the result of deliberate decisions, made at every turn boundary, about what to keep, what to compress, what to store, and what to let go.