Browse documentation
Concepts
View Markdown
On this page

Context management

What you will learn: why the size of a model conversation matters, who in gvn owns which part of the answer, how an agent or a conversation measures its conversation and makes it smaller, what happens when it cannot, and what reducing on gvn's side does compared with the vendor's own reduction.

Read first: The reference agent, The Governor, Workflows and Conversations. Time: about 25 minutes.

Where this sits

Every call to a model sends the whole conversation so far: the instructions, every message, every tool result. A model can read only so much in one call. That limit, counted in tokens (the pieces of text a model reads and writes; a word is one or a few), is the model's context window. A run that reads large tool results, or a conversation with a person that goes on for many turns, grows towards it. Long before it reaches it, each call costs more and takes longer, and once it passes it, the vendor refuses the call.

Three parts of gvn share the work, and each owns one thing:

  • The model owns its context window. It is a fact about the model, so it is a method of the Model port: Model.context_window(), an int of tokens, or None when unknown. A vendor adapter returns the number you give its constructor (context_window=); gvn keeps no table of model sizes.
  • The actor owns a context budget. How much of that window an agent or a conversation may use, when it should make its conversation smaller, and how, is a setting you choose when you build the actor: context_budget=, a ContextBudget.
  • The model reports token usage. The actor measures its conversation using that report. The size arrives the way time does (Time): in journaled events. Each model reply reports the tokens the call used, and the ModelFulfiller puts them in the model_replied event as "usage", beside the model's "context_window". The actor reads both into its context gauge, its own record of how full the window was at the last reply.

This page is about the context window and the context budget only. The run context (context=) is a different thing, never sent to the model; the reference agent sets the two apart. A memory, which keeps text beyond the conversation and the run, is a third thing, explained on the next page; this page shows only where a budget hands it what a reduction drops.

Before each model call, the actor asks one question of its gauge and its transcript: does the conversation fit, or must it be made smaller first? That question is a Decision, check_context, with five answers, and the machine routes each one:

flowchart LR
    model(["Model<br/>(owns context_window)"])
    fulfiller["ModelFulfiller"]
    event["event: model_replied<br/>message · usage · context_window<br/>(journaled)"]
    gauge["the actor's context gauge<br/>tokens at the last reply"]
    check{"check_context<br/>gauge + transcript<br/>against the context budget"}
    fits["context_fits<br/>ask the model"]
    trim["trim_due<br/>reduce without a model,<br/>then check again"]
    summary["summary_due<br/>ask a model for a summary,<br/>then check again"]
    remember["remember_due<br/>hand what the step will drop<br/>to a memory, then check again"]
    exhausted["context_exhausted<br/>end in overflowed"]
    model -- "Reply with token counts" --> fulfiller
    fulfiller --> event
    event --> gauge
    gauge --> check
    check --> fits
    check --> trim
    check --> summary
    check --> remember
    check --> exhausted

A reduction is anything that makes the transcript smaller: clearing old tool results, dropping old messages, or replacing old messages with a summary. The budget lists the reduction steps to try, in order. trim_due means the first step that applies needs no model; summary_due means it does. context_exhausted means the conversation is too big for the budget and nothing left can reduce it: the actor ends in a final state of its own, overflowed. remember_due is answered only by a budget built with remember_dropped=True: before a step drops anything, the actor hands the text it will drop to a memory, then checks again and the step runs.

What the measurement cannot see, the vendor catches. A conversation can outgrow the window between two measurements (a large tool result arrives after the last reply). The vendor then refuses the call; the adapter reports that as a ModelFailure with exceeded_context=True, and the model_failed event carries the flag. The actor records the refusal in its gauge and goes round to the same check, which now asks for a reduction, or answers context_exhausted when none applies.

The rest of the page goes from this picture to the states that carry it out, then to a run you can execute, and leaves the reduction steps, the thresholds and the costs to the end.

The states that do it

The reference agent and the conversation manage their window the same way, with the same four states and the same final state in their own machines. Here is the part of the agent's machine that changes; the conversation's is identical, with check_steps and within_steps in place of check_budget and within_budget:

stateDiagram-v2
    admitting --> measuring : within_budget
    measuring --> thinking : context_fits
    measuring --> remembering : remember_due
    measuring --> measuring : trim_due
    measuring --> summarising : summary_due
    measuring --> overflowed : context_exhausted
    remembering --> measuring : remembered
    remembering --> measuring : remember_failed
    remembering --> suspended : interrupted
    summarising --> measuring : model_replied
    summarising --> measuring : model_failed
    summarising --> suspended : interrupted
    thinking --> interpreting : model_replied
    thinking --> diagnosing : model_failed
    diagnosing --> failed : failure_final
    diagnosing --> admitting : context_exceeded
    overflowed --> [*]
State Output Kind of output What it is for
measuring check_context internal decision Judge the transcript and the gauge against the budget, before every model call. A trim happens here, and the check is made again.
remembering remember request Only with remember_dropped=True: hand a memory the text the step now due would drop, then go back to measuring whether the memory kept it or failed.
summarising invoke_model request Ask the model for a summary of the older messages, with no tools.
diagnosing classify_failure internal decision Tell a failed model call that did not fit the window (context_exceeded) from any other failure (failure_final).
overflowed (final) overflowed names no work The conversation no longer fits the budget and no reduction step applies.

A few things to notice:

  • measuring routes each model call. context_fits leads to the regular reply in thinking, and summary_due leads to a summary call in summarising.
  • Reductions happen between completed tool batches. admitting first enters measuring after every tool call from the last reply has been answered. A trim or summary can then reduce the transcript without separating a call from its result.
  • A refused call is retried through the budget. context_exceeded goes back to admitting, so each retry spends a turn (a step, in a conversation). A vendor that keeps refusing cannot loop the actor for ever.
  • A summary call is not a turn. summarising spends no turn and no step; the budget's own rules end repeated reductions (see the steps).
  • A memory that fails does not stop the run. remember_failed leads back to measuring like remembered, and the step runs; Memory has the details.
  • interrupted is declared in remembering and summarising, as in every state that waits for a request.

What a host must now route

overflowed is one more way an agent or a conversation can end, so whatever runs one must handle it:

  • A workflow Host that routes by routes= must name overflowed for an Agent or a Conversation; leaving it out is a ValueError when the Host is built, as for any final state.
  • Closing(closings=...), the Decision a host uses to route on a conversation's ending, includes overflowed among its outcomes, beside exhausted, left and failed.
  • An overflowed outcome carries "reason" (whether the vendor refused the conversation or its measured size reached the limit), "attempts" and "reductions".

Step 1: a model that reports its size

To run this offline you need a model that reports token counts and knows its window. The ScriptedModel fake (from gvn.testing.fakes, see Testing your harness) takes context_window=, and each scripted Reply takes input_tokens and output_tokens, exactly what a vendor adapter would report. This one plays an investigator that reads two days of logs and then answers. The second log read reports a conversation of 9,050 tokens in a window of 20,000:

import asyncio
import typing

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.context_window import ClearToolResults, ContextBudget, Summarise
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.harness.tools import Invocation, Tool, Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel


class ReadLog(Tool):
    def name(self) -> str:
        return "read_log"

    def description(self) -> str:
        return "Read one day's build log."

    def arguments(self) -> Record:
        return Record({"day": Text()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        return "a very long log of " + arguments["day"] + " ..."


read_log = ReadLog()


class AllowAll(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("cleared")


def reads_log(day: str, call_id: str, input_tokens: int) -> Reply:
    call = ToolCall(call_id=call_id, name="read_log", arguments={"day": day})
    return Reply(
        message=Message.assistant(text="", calls=[call]),
        input_tokens=input_tokens,
        output_tokens=50,
    )


model = ScriptedModel(
    [
        reads_log("monday", "c1", input_tokens=1_000),
        reads_log("tuesday", "c2", input_tokens=9_000),
        Reply(
            message=Message.assistant(text="Tuesday's deploy broke the build."),
            input_tokens=900,
            output_tokens=40,
        ),
    ],
    context_window=20_000,
)

Step 2: an agent with a context budget

The budget says: start reducing once the conversation reaches 40% of the model's window (reduce_at=0.4, here 8,000 tokens); first try clearing old tool results, keeping the newest one; if that is not enough, summarise all but the last four messages.

investigator = Agent(
    name="investigator",
    instructions="Find what broke the build.",
    tools=[read_log],
    context_budget=ContextBudget(
        reduce_at=0.4,
        steps=[ClearToolResults(keep=1), Summarise(keep=4)],
    ),
)

limit is left at its default, the whole window: past reduce_at the agent reduces, and only a conversation that still reaches the whole window with nothing left to reduce ends overflowed.

Step 3: run it and see the trim

toolbox = Toolbox([read_log])
journal = MemoryJournal()
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=AllowAll()),
    },
    journal=journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)
result = asyncio.run(
    governor.deliver(
        actor=investigator, event=Event("started", {"prompt": "Why did the build break?"})
    )
)
print(result.outcome().state(), result.outcome().payload()["reductions"])
for message in model.exchanges()[-1].messages():
    print(message.role(), [each.content() for each in message.results()])
State('completed') {'trimmed': 1, 'summarised': 0, 'fell_back': 0, 'remembered': 0, 'unremembered': 0}
user []
assistant []
tool ['[tool result cleared to save context; call the tool again if you need it]']
assistant []
tool ['a very long log of tuesday ...']

After the second reply the gauge read 9,050 tokens, past the 8,000 of reduce_at. The tool then returned, and in measuring, before the third model call, the check answered trim_due: ClearToolResults(keep=1) applied, so Monday's result was replaced by a short note and Tuesday's, the newest, was kept. The model's last call (the transcript printed above) saw the call to read Monday's log and the note in place of its result. The outcome's "reductions" counts what happened: one trim. Its last two counts are for a budget that hands its losses to a memory (Memory); this one does not.

A trim leaves the gauge not knowing the size any more: the old measurement described the longer transcript. The check that follows answers context_fits (nothing is known to be too big), and the next reply measures again.

Step 4: what the journal holds

The journal holds the size as it holds every other fact, in the events:

async def show_sizes() -> None:
    for record in await journal.read("investigator"):
        event = record["event"]
        payload = event["payload"] or {}
        print(event["name"], payload.get("usage", {}).get("input_tokens"), payload.get("context_window"))


asyncio.run(show_sizes())
started None None
model_replied 1000 20000
cleared None None
tools_returned None None
model_replied 9000 20000
cleared None None
tools_returned None None
model_replied 900 20000

The decisions (trim_due, context_fits) are not in the journal. They are made by the agent from what the journal holds, so a replay of the same events, offline, makes the same reductions at the same points.

Step 5: when it cannot fit

ContextBudget(), the default when you pass no context_budget, reduces nothing. An agent built without one never trims, and a conversation the vendor refuses as too large ends overflowed rather than failed. Here a model that always refuses stands in for a vendor that says the conversation does not fit, inside a small workflow that sends an overflowed answer to a person:

from gvn.harness.ports import Exchange, ModelFailure
from gvn.harness.workflow import Host, Memo, Plan, Report, Workflow
from gvn.kernel.blueprint import MooreBlueprint
from gvn.kernel.symbols import Alphabet
from gvn.testing.fakes import FunctionModel

TRIAGE_MACHINE = (
    MooreBlueprint(name="triage")
    .inputs("started", "answered", "answer_failed", "too_long")
    .outputs("idle", "answer", "done", "failed", "to_person")
    .state(name="idle", output="idle")
    .state(name="answering", output="answer")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .state(name="to_person", output="to_person", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="answering")
    .branch(
        source="answering",
        outcomes=Alphabet.of("answered", "answer_failed", "too_long"),
        routes={"answered": "done", "answer_failed": "failed", "too_long": "to_person"},
    )
    .otherwise_stay()
    .build()
)


def make_answerer(name: str, memo: Memo) -> Agent:
    return Agent(name=name, instructions="Answer the customer.")


def start_answerer(memo: Memo) -> Event:
    return Event("started", {"prompt": memo.input()["question"]})


class Triage(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(
            definition=TRIAGE_MACHINE,
            stages={
                "answering": Host(
                    actor_class=Agent,
                    make=make_answerer,
                    start=start_answerer,
                    routes={
                        "completed": "answered",
                        "failed": "answer_failed",
                        "overflowed": "too_long",
                    },
                )
            },
        )


def refuses(exchange: Exchange) -> typing.NoReturn:
    raise ModelFailure("the conversation does not fit", exceeded_context=True)


refusing = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=FunctionModel(respond=refuses), toolbox=Toolbox())
    },
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
result = asyncio.run(
    refusing.deliver(
        actor=Triage(name="ticket-4"), event=Event("started", {"question": "Where is A-17?"})
    )
)
answering = Report(outcome=result.outcome()).results("answering")[0]
print(result.outcome().state())
print(answering.state(), answering.payload()["reason"])
State('to_person')
State('overflowed') the context budget was exhausted: the vendor refused the conversation as too large for the model's context window, and no reduction step applies

The model call failed with exceeded_context, diagnosing answered context_exceeded, and the agent went back through admitting to measuring. The gauge now held a refusal and the budget had no step to try, so the check answered context_exhausted. The Host routes overflowed like any other ending; the workflow chose to hand the ticket to a person.

That is the 80% you need. The rest of the page is the detail: each reduction step, the thresholds, and what reducing does to thinking and caching.

Deeper: the reduction steps

Three steps are built in, all in gvn.harness.context_window. Each is an immutable value, equal by content, saved with the budget.

Step What it does Needs a model
ClearToolResults(keep) Replaces the content of every tool result older than the last keep tool messages with a short note saying it was cleared (the constant CLEARED), and drops its attachments. The calls stay, each result keeps its call id and whether it failed, and no message is removed. no
KeepRecent(messages) Keeps only the last messages messages. When those would not start with a user message, it puts a short user message before them saying that the earlier conversation was dropped (the constant OMITTED); that note is not counted in messages. no
Summarise(keep, brief="", model_role=None) Asks a model to summarise all but the last keep messages, and keeps that summary in their place, followed by the kept messages. brief is the summariser's instructions; a default (DEFAULT_BRIEF) is used when it is empty. model_role says which model writes it (below). yes

The order. When a reduction is due, the actor takes the first step in the list that applies: one that would change the transcript. A step that would change nothing (no old tool result left to clear, a transcript already as short as KeepRecent would make it, only an earlier summary or the note of an earlier drop left to summarise) is passed over. So cheap steps go first: clearing tool results loses the least, keeping recent messages loses more, and a summary costs a model call. After a trim the check is made again at once, so several steps can apply one after the other before the next model call. With reduce_over (below), for example, a budget of [ClearToolResults(keep=1), KeepRecent(messages=4)] first clears old results and, if the transcript is still too long, then cuts it. Because a step applies only when it changes something, and every change either makes the transcript shorter or puts a summary or the note of a drop where earlier messages were, repeated reductions end.

Cuts never break a pair. A cut never separates a tool call from its result, nor an instruction message from the user message it follows: where a cut would fall between them, it moves back, so KeepRecent(n) may keep a few more than n messages. What is cut can include the run's first message (an agent's prompt); the actor's instructions are not part of the transcript and are sent with every call.

The note of a drop. Every vendor expects a conversation to start with a user message, and what KeepRecent keeps often starts with the model's reply or tool call instead. In that case it puts one user message first, saying [the earlier conversation was dropped to save context] (the constant OMITTED), so the model is told that something came before and the vendor accepts the request. The note is an ordinary user message, not an instruction message, and it is not counted in messages: KeepRecent(4) can leave five messages, the note and the four it kept. The note does count toward reduce_over, like any message. A transcript that is already the note followed by what KeepRecent would keep is left as it is, and Summarise does not apply when all it could summarise is the note, so neither step runs again only to replace the note. When what is kept starts with a user message, no note is added, and an earlier note is dropped like any other message.

A summary round. In summarising the actor asks one invoke_model with the step's brief as the instructions, the older messages followed by a request to summarise them as the messages, and no tools. The summariser is never sent sealed content (below), nor the bytes of an attachment: each attachment is described instead (kind, media type and size, or its URL). When the reply has text, the older messages are replaced by one user message that starts by saying it is a model-written summary of the earlier conversation and not instructions (SUMMARY_PREFIX), and the kept messages follow. When the reply is blank, or the call fails, the round falls back to KeepRecent(keep), including its note when the kept messages need one, and the outcome counts it under "fell_back". The summary call's token counts are not a measurement of the conversation and are ignored.

Which model summarises. By default the summary is written by the actor's own model. A summary is a simpler task than the work itself, so a smaller, cheaper model can often write it. Summarise(keep, model_role="summariser") asks for the model your wiring gives the role "summariser": a role is a name, not a vendor's model id, and the ModelFulfiller maps each role to a model (ModelFulfiller(model, toolbox, roles={"summariser": small_model})). With no role on the step, the summary uses the actor's own role, if it has one (model_role= on the agent or the conversation), else the default model. The summary's request carries the role as "model_role"; its token counts are still ignored, so the summariser's smaller window never becomes the actor's measurement. A model per role shows the wiring with a runnable example.

Handing the loss to a memory. Every step loses text for good: a cleared result, dropped messages, or the messages a summary replaced. With ContextBudget(..., remember_dropped=True) the actor first issues one remember request with the transcript of exactly what the step that is due would drop (budget.dropping(messages)), in the state remembering, and then the step runs. A summary round is one loss, handed over once. The outcome counts the answers in "reductions" as "remembered" and "unremembered" (the memory failed and the step ran anyway). Memory runs it.

What the actor keeps besides the transcript. A reduced transcript no longer holds every tool call, so both actors keep their attempts (what became of each tool call) beside it. An agent's "attempts" still lists every call the model made in the run; a conversation's "tally" still counts every call over the whole conversation.

Deeper: thresholds in tokens or as shares

ContextBudget(limit=1.0, reduce_at=None, reduce_over=None, steps=(), remember_dropped=False) takes five settings:

Setting Meaning
limit The most the conversation may hold. An int is tokens (at least 1); a float is a share of the model's window (above 0, at most 1). The default, 1.0, is the whole window.
reduce_at When a reduction is due, in the same two forms. None means at limit.
reduce_over None, or an int: a reduction is also due once the transcript holds more messages than this, whatever their size. It bounds what is stored, which tokens alone do not.
steps The reduction steps, in the order they are tried.
remember_dropped A bool: whether what a step is about to drop is first handed to a memory. False by default.

An int and a float are different settings: limit=1 is one token, limit=1.0 the whole window. A reduce_at above a limit given in the same form is a ValueError.

The check, made in measuring before every model call, is:

  1. A reduction is due when the vendor refused the last call, or the gauge reached reduce_at, or the transcript has more than reduce_over messages. If one is due and a step applies, the answer is remember_due when the budget remembers what is dropped and this step's loss has not been handed over yet; else trim_due or summary_due, for the first step that applies.
  2. Otherwise, if the vendor refused the last call or the gauge reached limit, the answer is context_exhausted.
  3. Otherwise, context_fits.

What "unknown" means. The gauge knows nothing before the first reply, nothing again after each reduction until the next reply, and no window until a reply carries one. A share of an unknown window is an unknown threshold, and an unknown threshold is never crossed. So with a model whose context_window() is None, a budget written in shares does nothing until the vendor refuses a call; give such a model token numbers, reduce_over, or the window itself (each adapter's context_window=). Reaching limit always makes a reduction due, even when reduce_at is a share of a window not yet known.

Deeper: what reducing on gvn's side costs

Some models write their reasoning as signed blocks, which gvn keeps as sealed content on the assistant message and sends back to the same vendor (thinking between tool rounds). The vendor binds that content to the unchanged history before it. Every reduction step changes that history, so every message a step returns carries no sealed content. Two costs follow:

  • The model loses its carried thinking. After a reduction, the model does not get its earlier reasoning back; the text and tool calls stay.
  • The vendor's cache of the conversation restarts. Prompt caching matches the start of the request byte for byte. A reduction changes the start of the conversation, so the next call is billed as new input after the instructions and tools.

Both are why the order of the steps, and a reduce_at well below the limit, matter: a budget that reduces rarely, by a lot, pays these costs rarely.

The vendor's own reduction

Both vendors can reduce a conversation on their own side, and that keeps the thinking and the cache consistent for that vendor. gvn does not wrap it in a step: it is an adapter setting, passed through as the vendor defines it, as server tools are:

  • AnthropicModel(..., context_edits=[...]): Anthropic's context edits (for example its compaction edit), sent as context_management.edits.
  • OpenAIModel(..., context_management=[...]): OpenAI's context_management entries (for example its compaction entry).

What gvn does with them: the adapter enables what the vendor needs for the setting, and keeps what the vendor returns to be sent back (a compaction block or item) as sealed content, in its place, so later calls continue from the vendor's summary. The actor's measurement then simply sees a smaller conversation in the next reply's usage, and its own budget applies as usual. gvn passes the setting through as the vendor defines it. The vendor's reduction is not journaled as a reduction (the outcome's "reductions" does not count it) and replay sees the usage the vendor reported, not what the vendor did. gvn's own transcript is unchanged: it still keeps, journals and sends every message. On Anthropic, the adapter reports the call's top-level token counts, so the compaction pass is not in the recorded usage. The two kinds of reduction can be combined; a budget with no steps and a vendor-side setting leaves all reducing to the vendor and still ends in overflowed when the vendor refuses.

What to trust and what to put where

  • A summary is model-written content made from untrusted text (the person's words, tool results). It is kept as a user message that says so, and it never enters a run context or a route.
  • The size is reported, not computed. It is what the vendor said the last call used. A fake or an adapter that reports no usage leaves the gauge unknown, and only reduce_over and the vendor's refusal apply.
  • exceeded_context is set by the adapter, from the vendor's own error, never by a model's text.
  • Put what must hold for the whole run in the instructions. They are never reduced; a summary is model-written and can drop or distort detail.
  • Tool results and answers appended since the last reply are counted at the next reply. A very large tool result can reach the window before the check sees it; the vendor's refusal then arrives as exceeded_context and the diagnosis handles it.
  • A context budget belongs to one actor. Each agent or conversation, in a workflow too, measures and reduces its own conversation, with its own gauge and budget; a workflow has none. What one run learned reaches another through a memory (a model's recall, or what a budget with remember_dropped=True handed over) or a conversation's thread=. The actor recalls by itself when built with recall=True.

Recap

  • The model owns its context window (Model.context_window()); the actor owns a ContextBudget for it (context_budget=), unrelated to the run context (context=).
  • The size arrives in journaled model_replied events (usage, context_window); no machine counts tokens. A vendor's refusal arrives as exceeded_context.
  • Before every model call, measuring answers context_fits, remember_due, trim_due, summary_due or context_exhausted; remembering hands a loss to a memory first; diagnosing sorts a failed call; overflowed is a final state every host must route.
  • Steps run first-that-applies: ClearToolResults, KeepRecent, Summarise (which can use a smaller model through a role). The outcome counts them, and what a memory took, in "reductions".
  • Reducing on gvn's side drops carried thinking and restarts the vendor's cache; the vendor's own reduction is an adapter setting that gvn passes through and does not record.

Next: Memory, what outlives the conversation and the run.