When I send another message to an agent, what am I continuing?

I can still see the conversation. The application has saved some state. The model receives another request. Somewhere on the provider’s infrastructure, there may also be cached work from the previous one.

Those are different things, and they have different lifetimes.

I work on Pal at PayPal. That work is part of why I want to understand this path more deeply. For this project, I’m building a small independent runtime using personal code and synthetic data, so I can inspect what was saved, what was sent, and eventually what the provider reports reusing.

But first, what is a session? And what happens after we press send?

What is a session?

A session is the application’s container for an ongoing interaction. It gives the conversation an identity and lets the application associate messages, tool calls, results and other events with it.

A turn starts when we ask the agent to do something. Finishing that turn may require several model requests: the model asks for a tool, the harness executes it, and the result goes back to the model. The harness is the software running this loop and managing the surrounding state.

Consider a simple session:

text
User: Read notes.txt and remember the codeword.Assistant: [requests the file-reading tool]Tool: codeword=amberAssistant: The codeword is amber.User: What was the codeword?

The application can save all of this. Before the next model call, it still has to decide which parts to send.

The session ID does not identify a reserved GPU or guarantee that the next request reaches the same worker. It identifies our interaction in the application.

What are system and user messages?

A model request contains more than the latest sentence we typed.

The application supplies instructions about how the assistant should behave. These are often called a system prompt; some APIs also distinguish developer instructions. A user message contains the task or follow-up. Assistant messages contain earlier model responses. Tool results contain information returned by programs the harness ran.

For our example, the application might supply:

text
Application instructions: Use the file-reading tool for workspace files.Tool definition: read_file(path) returns the file’s text.User: Read notes.txt and remember the codeword.

On a later request, it may include the tool call, its result, the assistant’s response and the new user question.

These roles tell the model how to interpret different parts of the request. Their exact representation depends on the API. They do not replace runtime permissions: the program executing the tool still has to enforce which files and credentials it can access.

I’ll call the input available for this model invocation its context. Saved history and current context can overlap without containing exactly the same information.

How does that context reach a GPU?

The harness sends a structured API request. The serving system formats its messages and tool definitions into the model’s expected representation and converts text into token IDs. A token can be a word, part of a word, punctuation or another unit; it is not necessarily one word.

The server schedules the request on inference workers. In a conventional GPU deployment, those workers already hold the model’s weights—the numerical parameters learned during training—in accelerator memory, possibly spread across several GPUs.

The token IDs become numerical tensors. An embedding lookup gives each position an initial representation, which is transformed as it passes through the model’s layers.

The GPU therefore works with numerical representations of the request. It does not load a PostgreSQL session object or read our conversation as a text editor would. Sending a new system prompt changes the input for this invocation; it does not retrain the weights.

A compatible cached prefix can let the serving system reuse previously computed state along this path. Otherwise, the needed state has to be computed again.

What does a Transformer do with those numbers?

This article follows a common generative design: a decoder-only Transformer. It repeatedly computes a distribution over the next token and chooses a token from it.

Each layer updates the numerical representation at each position. Attention lets a position use information from positions it is allowed to see. In ordinary left-to-right generation, it cannot look ahead at future positions. Other parts of the layer transform the representation further; attention is one component of the model.

Attention derives three learned signals:

  • A query represents what the current position is matching against.
  • A key represents a signal that another position offers for that match.
  • A value contains the information to combine after the matches are weighted.

These are arrays of numbers, not literal questions and answers. For a simplified attention head:

text
Q = H × Wq     K = H × Wk     V = H × Wvattention = softmax(Q × Kᵀ / √d + causal_mask) × V

H holds the positions’ current representations. The W matrices are learned weights. Comparing queries and keys produces scores; softmax turns them into weights for combining the values. The mask blocks future positions.

After the layer stack, the last position’s representation produces vocabulary scores. The generation rule selects the next token. The Transformer paper and Hugging Face’s overview provide the deeper background.

What does a query actually do?

Choose a position and change its query. Keys are [1,0], [0,1], [1,1]; values are [1,0], [0,2], [2,1].

PositionQ·K / √2Causal maskWeight
p10.707allowed0.248
p20.707allowed0.248
p31.414allowed0.503
p124.8%
p224.8%
p350.3%
Attention output vector: [1.255, 1]. This is not a vocabulary probability or a generated word.
Supplied two-dimensional vectors, one attention head. This calculates real scaled dot-product attention arithmetic on synthetic inputs; it does not run a trained Transformer.

What are prefill and decode?

The prompt tokens are already known. The server can process many of their positions together through each layer. This is prefill. The last prompt position produces the distribution used to select the first output token.

To predict the following token, the model processes that selected token’s position. This begins ordinary decode: process the new position, predict the next token, and repeat.

text
Prefill: process p₁ p₂ p₃ → select a₁Decode:  process a₁       → select a₂Decode:  process a₂       → select a₃

The token just selected is processed on the next pass if generation continues.

The server can retain the keys and values computed for earlier positions at each layer. A new query can attend to them without rebuilding those earlier representations. That retained state is the KV cache. Earlier queries are not needed for the next position’s attention. How KV caching works

Why do these steps stress the hardware differently?

During a substantial prefill, a loaded tile of weights can contribute to calculations for many prompt positions. Large matrix operations provide considerable arithmetic for the amount of data moved. This often makes uncached long-prompt prefill compute-bound: arithmetic throughput limits progress.

At a small decode batch, each sequence contributes one new position. The server still needs the weights used by that step, and attention reads its accumulated KV. Fewer operations share those reads, so memory bandwidth often limits progress.

Memory bandwidth means how quickly bytes move to the compute units. Memory capacity means how much state fits. A machine can have enough capacity for a request while taking too long to move its state.

Batching changes the balance by sharing weight reads across more requests. Long contexts add KV traffic; a heavily cached prefill can spend much of its time restoring state. These are workload-dependent regimes, not permanent labels for every kernel. NVIDIA’s matrix guide

Separating prefill and decode into serving pools is one way to tune them independently. It need not mean different GPU models. DeepSeek’s February 2025 V3/R1 account used H800s for both, with different parallelism. We’ll examine that architecture separately.

Who manages the cache?

There are two jobs here: the provider stores and retrieves KV state; the application constructs requests that can reuse it.

Anthropic exposes automatic caching and explicit cache_control breakpoints. These let developers choose reusable boundaries and retention. That is useful flexibility; the provider still manages the tensors. Claude caching

OpenAI historically emphasized implicit caching. Its current documentation also exposes explicit controls on supported newer models. Settings vary by model and endpoint. OpenAI caching

I care about having enough control to express which parts of an agent request will be reused, and enough visibility to tell whether it worked.

Why spend so much effort preserving the prefix?

An agent repeatedly sends earlier material back to the model. A short new question can follow a large body of instructions, tools and history. The amount of newly typed text is a poor guide to the work or bill for the next request.

Hunter Paulson’s article about output-token cache charges follows a subtle case: an assistant span is charged as output when generated, then can incur a cache-write input charge when it returns in a subsequent request. His argument is that retaining generated state could let the next use be a read instead.

Those are different charge categories, not two charges at the output rate. Provider contracts change, so the billing for a particular request has to be checked against its own usage and current prices.

For a synthetic example, suppose a provider charges 10 units per million output tokens, 2.5 per million cache-write tokens and 0.1 per million cache-read tokens. A 1,000-token assistant span costs 0.010 units to generate. A later write adds 0.0025; a read would add 0.0001. That excludes every other token and charge in the session.

There is also a denominator problem. If the next input contains 1,000 reused tokens and 100 new ones, the cached share of that input is 90.9%, while coverage of the 1,000-token old prefix is 100%. That arithmetic alone cannot explain a real provider result; we need the exact requests and usage fields.

What can the harness do about it?

First, preserve the information needed to understand each request.

An append-only event log records what happened without overwriting earlier events. The harness derives a model request from that record. That gives us two things to inspect: the history and the particular input selected from it.

Append-only storage does not automatically produce an append-only model prefix. A context policy can omit old turns, a summary can replace them, a tool definition can change, or a timestamp can be inserted near the beginning. Each can alter what follows it in the model input.

A cache-conscious harness therefore needs stable serialization as well as durable history. Keep shared instructions and tool definitions stable where practical. Put changing material after the reusable prefix. Preserve the required message boundaries and cache settings. When context must change, make that change deliberate and observable.

Pi is a useful reference for thinking about sessions, request construction and prefix identity; Earendil’s prompt-caching article connects those decisions. Our personal lab is currently a separate implementation, not Pi with a PostgreSQL backend already attached.

Its implemented path is:

text
HTTP request → append session event in PostgreSQL             → select history and build provider input             → save exact model.requested snapshot             → call provider / execute bounded tool             → append result events → next request

PostgreSQL stores events and request snapshots here, not the provider’s KV tensors. The local demos use a deterministic offline provider; their restarts, database operations and gVisor tools are real, but they do not measure provider cache hits. A Pi adapter is a possible later integration, not a result this prototype has demonstrated.

Can different sessions reuse the same beginning?

Yes, when their initial tokens and cache settings match within the provider’s allowed scope. Different user questions can follow the same instructions and tool definitions:

text
Session A: [shared tools + instructions][A’s conversation]Session B: [shared tools + instructions][B’s conversation]            reusable initial prefix    different suffixes

A matching session ID is not the criterion. Prefix identity, eligible boundaries, model/configuration, isolation scope, routing and retention matter. OpenAI documents organization and regional boundaries; Anthropic’s isolation also depends on platform and workspace. The stable prefix must be long enough to meet the chosen model’s cache threshold.

For Claude’s default five-minute policy, a request that reads the cached prefix refreshes its lifetime from request start. Unrelated traffic does not refresh it. A four-minute response leaves about one minute for the next request under that policy. Use scheduling margin, not an exact five-minute boundary. Longer retention is available. Lifetime and sharing

Claude also now documents max_tokens: 0 pre-warming, with restrictions. That is a separate charged operation to evaluate, not proof our runtime already keeps a cache warm.

This is why reuse across sessions is interesting: regular traffic can keep a common eligible prefix useful. It does not establish that every session’s private suffix remains cached, or guarantee physical GPU residency.

What I want this runtime to make visible

At Pal, we benefit from prompt-prefix reuse. That experience motivates these questions; this independent project will produce its own evidence.

I want to inspect three records together: the events the session saved, the exact requests the harness constructed, and the provider’s usage for those requests. Then I can ask whether a miss followed a changed prefix, an idle gap, a different configuration, or something the API does not expose.

The existing experiments establish the first two records. Real provider reuse, expiry and total-cost measurements come next. They should include retries and any warming requests, not just successful user-facing turns.

That is why I’m building this runtime. A session should be something I can examine, and a cache hit should be a claim I can account for.