Context & Streaming

The gateway formats text in two directions. It orders the prompt so 90% of it comes from the cache. It cuts the model's token drip into 3 clean chat messages instead of 150 fragments.

Choose a prompt order and a way to send the reply, then press Run a turn. Watch how much of the prompt the cache reuses and how many messages reach the chat. Then we build both pipes piece by piece: the budget, the renderer, the caps, the cache line, the chunker and the pacing.

You need Lessons 1 to 4 of this series, or the idea that a model reads a prompt and writes tokens. A little Python helps for the labs. We build the rest from zero.

Lesson 5 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw, a self-hosted gateway between chat apps and an AI agent. We checked every OpenClaw detail here against its documentation.

Run one turn

Illustrative toy. Section sizes, the 600-character reply and the 4 characters per token are made up. The two rules are OpenClaw's: stable sections sit above the cache boundary, and replies go out as blocks.

Chapter 0

Two Pipes Through One Gateway

Follow one turn in, through the model, and back out to the chat

Someone types "is the oven off?" into WhatsApp. Before the model can answer, the gateway must write the exact text the model reads. It holds who the agent is, its tools, its workspace and the question. That is the first pipe, context in.

The model answers one token at a time. A token is a piece of a word, about 4 characters of English. WhatsApp knows nothing about tokens. It shows finished messages. So the gateway must regroup the token drip into messages a person can read. That is the second pipe, tokens out.

Step through one turn

The top row builds the prompt. The bottom row sends the reply. Press Step to move one stage, or Play to run the turn.

The stages follow OpenClaw's docs on the system prompt and on streaming. Stage names are ours.

Each pipe works under one hard limit:

PipeThe limitThe job
context inthe model's context window, and the price of each tokenchoose what goes in, cap it, and order it so the cache can reuse it
tokens outa chat app shows whole messages and dislikes floodscut the stream at clean breaks, merge small pieces, pace them

The site's tokenization lesson covers what a token is, and long-context LLMs covers why the window is finite. Here we take both as given and look at what the gateway does about them.

The road

  1. Fit the window: the one sum every request must pass.
  2. Three layers build the prompt: gather facts, apply settings, render text with no side effects.
  3. Prompt modes: full, minimal for sub-agents, and none.
  4. Workspace files, capped: why a cut file is not a lost file.
  5. The skills list: a menu in the prompt, the full text on demand.
  6. The cache boundary: stable text on top, changing text below.
  7. The block chunker: two bounds and a ladder of break points.
  8. Previews, merging and pacing: make the stream calm, and say nothing when there is nothing to say.
  9. The stream inspector: the chunker on a reply with code, live.
  10. Field guide: terms, numbers, a checklist and the core code.
Why does the gateway need its own "tokens out" pipe?

Chapter 1

Fit the Window

Add up everything the model reads, and keep room for its answer

A model reads at most a fixed number of tokens per request. This limit is its context window. OpenClaw's docs say that everything the model receives counts: the system prompt, the conversation so far, tool calls and their results, and attachments.

The answer also lives in the window, so the gateway must leave room for it. Call the system prompt's size P, the conversation history H, the room kept for the reply R, and the window W. All four are in tokens.

Say it aloud

P plus H plus R is at most W.

P
P the system prompt, in tokens: identity, rules, tools, workspace files.
H
H the history, in tokens: earlier messages, tool calls and tool results.
R
R the reply room, in tokens: space kept free for the model's answer.
≤
is at most the left side may equal W but never pass it.
W
W the context window of this model, in tokens.
In plain words

Add the prompt P, the history H and the reply room R. If the total is bigger than the window W, the request does not fit and something must shrink.

With numbers

With made-up numbers: a 6,000-character prompt is about P = 1,500 tokens. Twenty turns of 300 tokens give H = 6,000. Keep R = 2,000. The total is 9,500, so an 8,192-token window is 1,308 tokens short.

Fill the window

Pick a window size and drag the history. The bar turns red past the window line.

20

Illustrative: 300 tokens per turn, a 1,500-token prompt and 2,000 tokens of reply room. Real windows depend on the model.

History grows every turn, so a long chat always reaches the line. OpenClaw's answer is compaction: it writes a summary of old turns into the transcript and keeps recent messages whole. It can also prune old tool results from the prompt without touching the transcript on disk.

The prompt P is the part the gateway controls on every turn. Chapters 2 to 6 are about keeping it small, fixed in size, and cheap.

P = 1,500, H = 6,000, R = 2,000 and W = 8,192. What is true?

Chapter 2

Three Layers Build the Prompt

Gather live facts, apply settings, and render the text in a function with no side effects

The system prompt is the text the model reads before the conversation: who it is, how to behave, which tools exist. One way to build it is a big template that reads files and settings as it goes. Then nobody can say why a prompt came out the way it did. The answer depends on the disk and the clock at that moment.

OpenClaw splits the job into three layers:

  1. Runtime adapters gather live facts: the tools that exist now, the sandbox state, channel features, the workspace files.
  2. buildConfiguredAgentSystemPrompt applies the agent's settings: the owner's display name, voice hints, model aliases, how memory is cited, how sub-agents are used.
  3. buildAgentSystemPrompt renders the text from explicit inputs. It reads no global settings. It is a pure function: the same inputs always give the same output, byte for byte.

Render it twice

Each button changes one input, or none. Watch which layer lights up, which named section changes, and the prompt's fingerprint.

The fingerprint is a 32-bit FNV-1a hash of the toy prompt text. The three layer names and the three swappable sections are OpenClaw's; the section texts are ours.

Why insist on purity? Because a prompt you can reproduce is a prompt you can debug. Give the renderer the inputs from a bad turn and you get that exact prompt back. Purity also helps the cache in Chapter 6: same inputs, same bytes, so the cache can reuse them.

The renderer writes the prompt as named sections. A provider plugin may replace one of three: interaction_style, tool_call_style and execution_bias. A model that prefers terse tool calls gets a different tool_call_style, and every other byte stays the same.

Why is buildAgentSystemPrompt a pure renderer that reads no files and no global settings?

Chapter 3

Prompt Modes

Give a sub-agent a smaller prompt by leaving out sections it never uses

A sub-agent is a helper run that the main agent starts for one narrow job, such as "summarise this file". It does not chat with the owner, so it does not need the messaging rules or the owner's profile. Sending them anyway costs tokens on every call.

So the renderer takes a prompt mode:

ModeUsed forWhat it renders
fullthe main agent (default)every section
minimalsub-agentsleaves out Memory Recall, Model Aliases, User Identity, Assistant Output Directives, Messaging, Collapsible Details and Silent Replies
nonea near-raw modelonly the base identity line

Switch the mode

Each row is one section, its bar is its size. Pick a mode and watch rows drop out.

Section names and the minimal list are from OpenClaw's system-prompt docs. The sizes are made up for the toy.

What stays in minimal mode is what a helper needs to work: tooling, safety, skills, the workspace, the sandbox and runtime facts. The workspace files of Chapter 4 also shrink for a sub-agent: it gets only AGENTS.md.

The lab below builds an assembler with three rules: drop sections by mode, cap each section, and stop before the total passes the budget. The sizes are scaled down so the caps bite on short strings.

A sub-agent runs in minimal mode. Compared with full, its system prompt:

Chapter 4

Workspace Files, Capped

Inject each file up to a limit, cap the total, and keep the full file one tool call away

The agent also needs to know its world. That lives in plain files in its workspace, injected when a session starts. OpenClaw calls them bootstrap files:

FileWhat it holds
AGENTS.mdoperating instructions, including a Tools section with local notes
SOUL.mdpersona, tone and boundaries
IDENTITY.mdthe agent's name, vibe and emoji
USER.mdthe owner's stable preferences
BOOTSTRAP.mda first-run ritual, for brand-new workspaces only
MEMORY.mdcurated long-term facts; main private session only

A busy MEMORY.md grows without limit, so two caps apply. Call the size of file i in characters ci, the per-file cap b, and the total cap B. The injected total is T.

Say it aloud

T equals the sum over i of the minimum of c-i and b, and T is at most B.

T
T the characters of workspace files that go into the prompt.
Σi
the sum over i add one term for each bootstrap file.
min
the minimum of the smaller of the two numbers, so a short file goes in whole and a long one is cut.
ci
c-i the size of file i on disk, in characters.
b
b the per-file cap, bootstrapMaxChars: 20,000 by default.
B
B the total cap, bootstrapTotalMaxChars: 60,000 by default.
In plain words

For each file, take its size c-i or the cap b, whichever is smaller. Add them up to get T. T must stay under the total cap B.

With numbers

With made-up file sizes: AGENTS 12,000, SOUL 3,000, IDENTITY 800, USER 2,500 and MEMORY 45,000. MEMORY is cut to 20,000. T = 12,000 + 3,000 + 800 + 2,500 + 20,000 = 38,300, under B = 60,000.

Cap the files

Outlined bars are the files on disk; filled bars are what the prompt gets. Grow MEMORY.md, or switch to a sub-agent.

45,000
12,000

Caps and the sub-agent rule are OpenClaw defaults. File sizes are made up. When the total passes B, the toy trims the last file; the docs do not say which file loses first.

Is a cut MEMORY.md lost? No. OpenClaw keeps the file on disk whole and cuts only the copy it injects. When cutting happens it adds a short notice to the prompt. The model can read the rest with memory_get, which reads a memory file or a range of its lines, or find it with memory_search.

MEMORY.md is 45,000 characters and the per-file cap is 20,000. Has the agent lost 25,000 characters of memory?

Chapter 5

The Skills List

Put a short menu entry in the prompt, and let the model read the full skill only when it uses it

A skill is a written procedure the agent can follow, kept in a SKILL.md file. A workspace can have hundreds. Pasting every full file into the prompt would fill the window before the owner speaks.

So OpenClaw injects a menu. Each eligible skill gets one entry in an <available_skills> block: its name, a description and its location, the path to the SKILL.md. When the model picks a skill, it reads the file at that path with the read tool.

How big is the menu? The docs give about 97 characters of fixed markup per entry. Call the number of skills N, and for skill i the lengths of its name, description and location ni, di and li. The menu size is S.

Say it aloud

S equals the sum over i from 1 to N of 97 plus n-i plus d-i plus l-i.

S
S the size of the skills menu in the prompt, in characters.
Σi=1..N
the sum over i from 1 to N one term per eligible skill; N is the number of skills.
97
ninety-seven the fixed markup of one entry, from OpenClaw's skills docs.
ni
n-i the length of skill i's name.
di
d-i the length of skill i's description.
li
l-i the length of skill i's location, the path to its SKILL.md.
In plain words

For each skill, add 97 to the lengths of its name n-i, description d-i and location l-i. Add the entries for all N skills to get S.

With numbers

With made-up lengths: N = 40 skills, each with a 20-character name, a 120-character description and a 45-character path. One entry is 97 + 20 + 120 + 45 = 282. S = 40 × 282 = 11,280 characters, about 2,820 tokens. Pasting 40 files of 6,000 characters would cost 240,000.

Fit the menu

Each tile is one skill entry. Add skills or shrink the budget and watch the descriptions shorten, then go.

40
15,000

The 97-character overhead and the order of the fallback are from OpenClaw's skills docs. The docs give no default budget; 15,000 is ours. We reuse 97 characters for every format.

The menu has its own budget, skills.limits.maxSkillsPromptChars, with a per-agent override. If the block would pass it, OpenClaw first keeps as many names and locations as fit. It gives what is left to shortened descriptions, and drops descriptions if nothing is left. The prompt then points to openclaw skills check. When the skills_search tool is on, the model can still find a skill that the budget cut.

The skills block would pass its budget. What does OpenClaw give up first?

Chapter 6

The Cache Boundary

Put stable text on top so the provider can reuse it, and push changing text below the line

Every turn the gateway sends nearly the same prompt as last turn. Model providers offer prefix caching: they keep the work done on the start of a prompt. If the next prompt begins with the same bytes, they reuse that work, and the reused tokens are cheaper and faster. The LLM inference lesson shows the cache inside the server.

The catch: reuse stops at the first byte that differs. One changing line near the top, such as the time, makes everything below it new.

Move the clock

The strip is the prompt, front on the left. Green is the cached prefix. Move the clock line and watch the green shrink and the cost bars grow.

Made-up prices: $3 per million input tokens, cached tokens at one tenth. Real prices differ by provider. Section sizes match the hero.

Call the prompt's size T and the cached prefix A, both in tokens. Call the price per token p, and the cached price as a fraction k of p. The cost of one turn's prompt is C.

Say it aloud

C equals p times, open bracket, k times A, plus T minus A, close bracket.

C
C the cost of sending this turn's prompt, in dollars.
p
p the normal price of one input token.
k
k the cached price as a fraction of p, between 0 and 1.
A
A the cached prefix: tokens from the start up to the first change.
T
T all tokens of the prompt; T minus A is the part paid in full.
In plain words

Pay the cheap rate k times p for the A cached tokens. Pay the full rate p for the other T minus A tokens. Their sum is C. A bigger A means a smaller C.

With numbers

With made-up prices: p = $3 per million, k = 0.1, T = 1,500. Stable first gives A = 1,350, so C = $0.000855 a turn. Clock second gives A = 100, so C = $0.00423. Over 1,000 turns: $0.86 against $4.23.

OpenClaw orders the prompt by how often each part changes. Large stable content stays above an internal cache boundary: the Project Context, workspace instructions, fixed policy and common runtime instructions. Below it go the parts that change with tools or channels: Tooling, Skills, Memory Recall, Model Aliases, Sandbox, and per-turn guidance.

Date, time zone and other per-turn facts go in a separate Runtime Context message, outside the system prompt. So the system prompt stays byte-identical even across midnight.

Why does OpenClaw keep the date and time out of the system prompt?

Chapter 7

The Block Chunker

Wait for enough text, never pass the maximum, and cut at the cleanest break in between

Now the other pipe. Most chat apps cannot grow one message a token at a time. A WhatsApp message goes out once, whole. So OpenClaw's block streaming sends the reply in coarse pieces, called blocks, as they become ready. It is off by default; blockStreamingDefault turns it on.

A component called EmbeddedBlockChunker decides where each block ends. It has two bounds:

Between the bounds the chunker looks for the cleanest break. It walks down a break ladder: a paragraph break, a newline, a sentence end, any space, and last a hard cut.

Cut the reply

Each shaded run is one block. The bar at its end is orange for a clean break and red for a cut through a word. Drag the bounds, or turn on blind cuts.

60
160

The bounds and the ladder are OpenClaw's. The reply and the slider ranges are made up; real bounds are larger.

A worked cut, with minChars 60 and maxChars 160. The chunker looks at characters 60 to 160 of the buffer. It finds no blank line, but finds a newline at 109, so the first block is 109 characters and ends on a whole line. The next window starts at 109.

blockStreamingBreak sets when blocks flush. With text_end blocks go out as soon as the chunker emits them. With message_end the gateway waits for the whole assistant message, then flushes.

The buffer is past minChars but below maxChars. Where does the chunker cut?

Chapter 8

Previews, Merging and Pacing

Edit one message in place, merge small blocks, space them like a person, and stay silent on purpose

Clean blocks fired the moment they are ready still feel wrong: five quick messages, then silence. OpenClaw has two ways to show a reply as it grows, plus two tools to calm block replies.

Preview streaming uses chat apps that can edit a sent message, such as Telegram, Discord and Slack. One message updates in place:

ModeWhat the person sees
offnothing until the final answer
partialone preview, replaced by the latest text
blockone preview that grows in appended steps
progressa status line during the work, such as "searching the web", then the final answer

Discord, Telegram and Slack default to progress. For block replies, coalescing waits for an idle gap, idleMs, and merges small blocks. Discord, Signal and Slack default to minChars 1,500 and idleMs 1,000. humanDelay adds a pause between block replies; its natural setting picks 800 to 2,500 ms at random.

Play one reply

The top lane is what the chunker emits. The bottom lane is what the chat gets. Pick a mode; for block replies, try merging and pacing.

Block sizes, arrival times and the pause values are made up. Mode names, the 1,500 and 1,000 defaults and the 800 to 2,500 ms range are OpenClaw's.

How much time does pacing add? Call the number of block replies n and the average pause d̄. The added time is D.

Say it aloud

D equals n minus one, times d-bar.

D
D the extra time pacing adds to a reply, in milliseconds.
n
n the number of block replies sent; there are n minus 1 gaps between them.
d̄
d-bar the average pause. For natural, the middle of 800 and 2,500: 1,650 ms.
In plain words

Count the gaps between messages: n minus 1. Multiply by the average pause d-bar. That is D.

With numbers

With made-up block counts: n = 4 block replies with natural pacing. D = 3 × 1,650 = 4,950 ms, about 5 seconds. Coalesce them into 2 messages and D = 1,650 ms.

Sometimes the right reply is none, for example in a group chat where the message was not for the agent. The model then answers with the silent token NO_REPLY. Only a final answer whose whole text is that token asks for silence:

Final textWhat the chat gets
NO_REPLY (any case, any spaces around)nothing; unsent text from this turn is dropped
NO_REPLY on the first line, then an answerthe answer; the first line is removed
an answer, then NO_REPLY on the last linethe answer; the last line is removed
NO_REPLY. or "NO_REPLY"that text, shown as a normal message
On Discord, Signal and Slack, coalescing defaults to minChars 1,500 and idleMs 1,000. What problem does that solve?

Chapter 9

The Stream Inspector

Stream a reply with code through the chunker and see it close and reopen the fence

Chat apps render Markdown, and a code fence is a code block between two lines of three backticks. Cut a reply inside a fence and the first message has an opening fence with no close. The chat then shows the rest of that message, and maybe the next, as broken code.

OpenClaw's rule: never split inside a fence. Sometimes a fence is longer than maxChars and a cut inside it is forced. Then the chunker closes the fence at the end of the block and reopens it at the start of the next. Every block is valid Markdown alone.

Stream a reply with code

The top shows the reply and its blocks; the shaded run is the code fence. Below, each sent block is listed with how it ends. Press Stream, then turn the fence rule off and stream again.

60
150

The reply and the bounds are made up. The fence rule (never split inside, close and reopen when forced) is OpenClaw's.

With the rule on, every listed block has an even number of fence lines. With it off, some block opens a fence it never closes, and the list marks it red. Shrink maxChars below the length of the code to force the close-and-reopen case.

A code block is longer than maxChars, so a cut inside it is forced. What does OpenClaw's chunker do?

Chapter 10

Field Guide

Keep the terms, the numbers, a checklist and the core code in one place

Context in: three layers render a prompt by mode. Workspace files and the skills menu go in under caps. Stable text sits above the cache boundary, and the whole request must fit the window. Tokens out: the chunker cuts at clean breaks, never inside a fence. Previews, coalescing and pacing make the stream calm, and NO_REPLY makes it silent.

TermMeaningOpenClaw value
context windowtokens a model reads per requestmodel-specific; /context list shows the sizes
compactionsummarise old turns into the transcriptrecent messages stay whole
rendererpure function from inputs to promptbuildAgentSystemPrompt
prompt modehow much of the prompt to renderfull, minimal (sub-agents), none
per-file capmost characters per bootstrap filebootstrapMaxChars 20,000
total capmost characters of all bootstrap filesbootstrapTotalMaxChars 60,000
skills entryone menu line per skillname, description, location; about 97 characters of markup
cache boundarystable text above, changing text belowdate and time in a separate Runtime Context message
block chunkercuts the reply into blocksEmbeddedBlockChunker, {minChars, maxChars, breakPreference}
break ladderpreferred cut pointsparagraph, newline, sentence, space, hard cut
coalescingmerge blocks in short gapsDiscord, Signal, Slack: minChars 1,500, idleMs 1,000
humanDelaypause between block repliesnatural: 800 to 2,500 ms
preview modesone message edited in placeoff partial block progress
silent tokena final answer that asks for no messageNO_REPLY, the whole text only

Checklist for any agent gateway

The core, in code

A toy of both pipes. It is a sketch for reading, not OpenClaw's code.

pythondef inject(files, b=20000, B=60000):          # chapter 4: T = sum of min(c_i, b) <= B
    out, total = [], 0
    for name, text in files:
        part = text[:b]
        part = part[:max(0, B - total)]
        out.append((name, part, len(part) < len(text)))   # flag: add a truncation notice
        total += len(part)
    return out

def order(sections):                              # chapter 6: stable first, keep relative order
    return [s for s in sections if s.stable] + [s for s in sections if not s.stable]

LADDER = ["\n\n", "\n", ". ", " "]
def cut(buf, lo, hi, in_fence):                     # chapter 7: best break in (lo, hi]
    for mark in LADDER:
        p = buf.rfind(mark, lo, hi)
        while p != -1 and in_fence(p + len(mark)):    # chapter 9: never inside a fence
            p = buf.rfind(mark, lo, p)
        if p != -1:
            return p + len(mark), False
    return hi, in_fence(hi)                         # hard cut; True means close and reopen the fence

def is_silent(final):                             # chapter 8: the whole text only
    return final.strip().upper() == "NO_REPLY"

Where each thread continues

The takeaway. Fit the window, render purely, cap what you inject and point to the rest, put stable text first, cut the reply at clean breaks outside code fences, and pace it like a person.
In one sentence, what are the two pipes?

Now press Present or Teach and explain it from memory. Cover the window sum, the layers, the caps, the skills menu, the cache boundary, the chunker and the fence rule. Then go back to the hero and run a turn both ways again.

Anatomy of an Agent Gateway, Lesson 5: Context and Streaming
OpenClaw docs · Next: the command queue · Back to Gleams