Language Model Session Management: Context, Cloning, Compaction, and Memory
How to create, persist, branch, and compact LLM chat sessions on the web and in agents, without losing context or exhausting token limits.
This page summarizes how to manage ongoing conversations with a language model in two places: Chrome’s built-in Prompt API (LanguageModel sessions in the browser) and Cloudflare Agents (the experimental Session API for server-side agents). Both solve the same problem—keeping useful context across turns while staying inside finite token and memory limits—but they use different primitives.
What a language model session is: context across turns
Section titled “What a language model session is: context across turns”A session is an ongoing conversation with the model where prior user prompts and assistant replies inform the next response. Chrome’s Prompt API states that each session keeps conversation context until the context window fills; you can monitor progress with contextUsage and contextWindow.
One key feature of the Prompt API is sessions. They let you have one or multiple ongoing conversations with the AI model, without the model losing track of the context of what was said.
— Chrome, Best practices for session management with the Prompt API
On Cloudflare, the Session API is the memory layer: tree-structured message history, optional context blocks in the system prompt, compaction, and tools the model can use to read or write memory. Conversation state and memory separates conversation history (messages and tool results) from context memory (persistent blocks such as identity, scratchpad facts, or searchable knowledge).
| Concern | Prompt API (LanguageModel) |
Cloudflare Session API |
|---|---|---|
| Where state lives | In-memory session object; optional localStorage for restore |
Durable Object SQLite by default; optional Postgres |
| System / persona | initialPrompts at create() only |
Context blocks (soul, memory, etc.) in system prompt |
| Parallel chats | clone() from a base session |
Branches via parent_id; SessionManager.fork() |
| Long chats | Browser eviction or proactive compaction | Non-destructive compaction overlays + pruneMessages() for the model |
| Cleanup | destroy() |
destroy() on clones; session delete via manager |
Prompt API sessions: create, warm up, and set instructions early
Section titled “Prompt API sessions: create, warm up, and set instructions early”initialPrompts and when to call LanguageModel.create()
Section titled “initialPrompts and when to call LanguageModel.create()”System instructions belong in session creation, not in the first prompt() call. Built-in AI APIs: Do and don’t warns that initialPrompts can only be set during create(), and that waiting until the user clicks “Generate” causes cold-start latency.
Do: Provide system instructions during session initialization to improve the speed of the first prompt.
— Chrome, Built-in AI APIs: Do and don’t
Caution: For the Prompt API, wait until you have the initialPrompts ready before calling create(), because these can only be set during creation.
— Chrome, Built-in AI APIs: Do and don’t
Pre-warm the model when the user’s intent is clear (navigating to an AI surface, hovering the workspace, etc.), as described in the same guide and the Language Model guide.
Clone sessions for parallel or repeated tasks
Section titled “Clone sessions for parallel or repeated tasks”clone() forks a session: clones inherit initial/system prompts and history up to the clone point. The recommended pattern is a base session with only system instructions, then clone() per task—avoid reusing one session for unrelated tasks or calling create() repeatedly with identical system prompts.
Create a base session: To handle unrelated tasks efficiently, create a base session that contains only your system instructions and no previous conversational context. Clone the baseline: Use clone() on that base session for new tasks to save the overhead of re-parsing system instructions.
— Chrome, Built-in AI APIs: Do and don’t
Session management best practices show independent clones for parallel chats (e.g. support agents handling multiple customers).
Restore a past session without a native restore API
Section titled “Restore a past session without a native restore API”There is no dedicated “restore session” API yet; you recreate context by passing stored turns as initialPrompts (roles user, assistant, system). Best practices for session management store JSON in localStorage after each turn. The Language Model guide adds a privacy warning: localStorage is unencrypted and may hold PII.
You can combine restore with clone—for example, restore once, then let the user clone for “what if” branches—as noted in session management.
Context window limits on the web: overflow, abort, and compaction
Section titled “Context window limits on the web: overflow, abort, and compaction”Monitor usage and listen for contextoverflow
Section titled “Monitor usage and listen for contextoverflow”When a new prompt does not fit, the browser drops oldest prompt/response pairs (not the system portion set via initialPrompts at runtime). The contextoverflow event fires when eviction starts. If even full eviction cannot fit the prompt, prompt() / promptStreaming() throw QuotaExceededError.
Session compacting with the Prompt API recommends surfacing contextUsage / contextWindow (e.g. a <progress> bar) and using contextoverflow to warn users or trigger compaction before silent loss of history.
When this context window is exceeded, it causes the session to lose track of the oldest messages. This may lead to worse results if the context was important.
— Chrome, Best practices for session management with the Prompt API
Proactive compaction with the Summarizer API
Section titled “Proactive compaction with the Summarizer API”Automatic eviction is reactive; session compacting summarizes history with the Summarizer API, destroy()s the old session, and create()s a new one with compacted messages as initialPrompts. Summaries in initialPrompts are not evicted at runtime the same way as ordinary turns—though if the compacted initialPrompts alone exceed the window, create() rejects with QuotaExceededError.
Keep a separate fullHistory array for recovery if compaction fails after the old session is destroyed. Optional: split messages by code fences and summarize prose only, preserving code verbatim (session compacting).
Built-in AI links session compacting to detecting overflow and extending conversations via summarization.
Stop generations and free memory
Section titled “Stop generations and free memory”Pass AbortController.signal to prompt() or promptStreaming()—not to create()—so users can stop useless generations and preserve quota (session management, Prompt API). Call destroy() on sessions you no longer need; Built-in AI APIs: Do and don’t notes garbage collection is slower than explicit destroy(). The Language Model guide recommends destroy() when finished and never assigning model output to innerHTML.
Cloudflare agent sessions: storage, context blocks, and compaction
Section titled “Cloudflare agent sessions: storage, context blocks, and compaction”Do not confuse SQLite storage with LLM context
Section titled “Do not confuse SQLite storage with LLM context”For chat agents, maxPersistedMessages caps stored messages only—it does not change what the model receives. Use the AI SDK’s pruneMessages() to control the active context. Calling LLMs shows building prompts from agent-owned SQL history so the client need not resend the full thread each time.
| Control | Mechanism | Affects |
|---|---|---|
| Persistence cap | maxPersistedMessages |
SQLite storage |
| Model input | pruneMessages() |
Tokens sent to the LLM |
| Huge tool output | Automatic compaction (~1.8 MB row limit) | Stored message shape |
Context blocks, tools, and prompt caching
Section titled “Context blocks, tools, and prompt caching”Configure sessions with Session.create(agent) and .withContext() for read-only persona (soul), writable memory, searchable knowledge, or loadable skills—see Sessions and conversation state and memory. The Session generates tools such as set_context, search_context, and load_context based on provider types.
freezeSystemPrompt() caches the rendered system prompt; with .withCachedPrompt(), it survives Durable Object hibernation. Writable block updates via set_context do not invalidate the frozen prompt mid-turn; call refreshSystemPrompt() between turns when the model should see its own memory writes (conversation state and memory).
Think wires this via configureSession()—context blocks, compaction, and search (configuration, getting started).
Compaction without deleting history
Section titled “Compaction without deleting history”Macro-compaction stores summaries as overlays; getHistory() applies them at read time while originals remain in SQLite (conversation state and memory, Sessions). Register .onCompaction() and .compactAfter(tokenThreshold) on the session builder. Long-running agents lists sliding window, summarization, and selective retention as strategies when history grows over months.
SessionManager supports multiple named sessions, fork() at a message, compactAndSplit() for a continuation session, and cross-session search (Sessions).
Shared design choices: what both stacks agree on
Section titled “Shared design choices: what both stacks agree on”Separate “what we store” from “what the model sees.” Chrome eventually evicts oldest turns from the live session; Cloudflare keeps full history in SQLite but prunes or compacts what you send to the model.
Branching conversations. Chrome uses clone() after a prepared baseline; Cloudflare uses message-tree parent_id and getHistory(leafId) for regeneration and forks.
Summarization beats unbounded growth. Chrome’s Summarizer-driven session restart and Cloudflare’s compaction overlays both compress old turns while trying to preserve thread continuity.
Resource hygiene. Explicit session teardown (destroy() on the web; destroy clones and delete managed sessions on the server) and stopping in-flight generation with AbortSignal reduce wasted tokens and memory.
For input size before calling a model, Evaluate product reviews with AI recommends countTokens() and shortening prompts that exceed limits—a useful check for one-shot prompts as well as long restored histories.
Common mistakes
Section titled “Common mistakes”- Sending system instructions as the first
prompt()instead ofinitialPromptsatcreate()(higher latency; see Built-in AI APIs: Do and don’t). - Reusing one Prompt API session for unrelated tasks or cloning a session that already carries irrelevant history (Built-in AI APIs: Do and don’t).
- Assuming
maxPersistedMessagestrims LLM context on Cloudflare (chat agents). - Compacting or destroying the only session without
fullHistorybackup on the web (session compacting). - Keeping many large Prompt API sessions alive without
destroy()(Built-in AI APIs: Do and don’t). - Breaking provider prefix cache by re-rendering the system prompt every tool step instead of using
freezeSystemPrompt()/ refreshing between turns (conversation state and memory).
Further UX guidance for built-in AI (streaming, undo, caching) is in Built-in AI APIs: Do and don’t and the Language Model guide.
How to check this on your site
Section titled “How to check this on your site”- For a web app using the Prompt API, log
session.contextUsageandsession.contextWindowafter each turn and confirm acontextoverflowhandler runs; compare with The Prompt API and session compacting. - Run through Best practices for session management with the Prompt API: clone two branches from a base session and verify each branch keeps its own follow-up context.
- After implementing
localStoragerestore, reload the browser and confirmLanguageModel.create({ initialPrompts: … })continues the thread; review privacy notes in the Language Model guide. - For a Cloudflare agent, verify
getHistory()still returns full storage whilepruneMessages()limits model input, following chat agents and Sessions. - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact wording you are asking about.