Skip to main content

Fit to context

Long agent sessions and chat histories eventually outgrow a model's input window. Fit to context checks every request against the input window of the deployment the router picked, and when the request is too long it drops the oldest turns from the middle of the conversation before the call goes out. The system prompt, the first user turn and the newest turns are always kept, so the model still sees its instructions, the original task and the current exchange.

It is off by default. You turn it on per request, per key or team, per deployment or for the whole gateway, and it works on /v1/chat/completions, /v1/responses and /v1/messages.

A real-world scenario​

A support team runs a long-lived assistant whose conversations grow over a whole shift. After a few hours the history no longer fits the model's input window, and the provider starts answering with context window errors. The platform admin gives the assistant a key with fit to context turned on. From then on the gateway quietly drops the oldest middle turns of an oversized conversation, the assistant keeps its instructions, the customer's first message and the latest exchange, and the errors stop without any change to the assistant's code.

Step by step​

  1. Decide where to turn it on. For one team or key, use its metadata. For every key on the gateway, use Router Settings.

  2. For the whole gateway, open Router Settings under Settings in the Admin UI (/ui/router-settings), switch on Fit To Context and click Save Changes.

  3. For one key, create the assistant's key with the setting in its metadata:

    curl -X POST http://localhost:4000/key/generate \
    -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{"key_alias": "support-assistant", "metadata": {"context_fit": {"strategy": "middle_out"}}}'

    The answer's key field holds the new key, called sk-support-key below.

  4. Send a long conversation with that key and read the response headers:

    curl -s -D - -o /dev/null http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer sk-support-key" -H "Content-Type: application/json" \
    -d @long_conversation.json | grep -i x-spanway-context-fit

Expected result​

A request that fits is sent unchanged and carries no fit to context header. A request that is too long is trimmed before it reaches the provider, the call succeeds, and the response carries x-spanway-context-fit: middle_out and x-spanway-context-fit-dropped-messages with the number of messages removed. The trimmed request shows up on the Logs page like any other.

Strategies​

StrategyWhat it doesNeeds a model
middle_outDrops whole middle turns, oldest first, until the request fits. This is the default.No
summarizeReplaces older history with a summary written by a compactor model that supports native compaction.Yes, set model

middle_out drops whole turns only. A turn starts at a user message and runs until the next user message, so an assistant tool call and its tool result always stay together or go together. A turn that has a tool call without a matching result, or that contains a system or developer message, is never dropped. The gateway drops the fewest turns that make the request fit.

summarize can only be set by an admin, in router_settings or on a deployment, because it calls another model group. When it has no model, the gateway falls back to middle_out.

When trimming happens​

The budget is the deployment's max_input_tokens multiplied by trigger_ratio (0.9 unless you set it), minus the output allowance. The output allowance is the request's max_tokens, max_completion_tokens or max_output_tokens, or the deployment's max_output_tokens when the request sets none. Requests under the budget are sent unchanged.

Nothing is trimmed when the deployment has no known input window, when the request is a single string, or when the history is managed by the provider (previous_response_id, conversation, reasoning items or encrypted content). With middle_out, a request that still does not fit after every droppable turn is gone is sent unchanged, so the provider's context window error and your context_window_fallbacks still apply. With summarize, the gateway refuses such a request itself with a ContextWindowExceededError that starts with Context compaction:, see Errors.

Turn it on​

The first setting found wins, in this order. An explicit false at any level switches it off for that request.

  1. The request body field context_fit, or a transforms field in the style some hosted routers use.
  2. metadata.context_fit on the virtual key.
  3. metadata.context_fit on the team.
  4. context_fit in the deployment's spanway_params or model_info.
  5. router_settings.context_fit.

Each level accepts true, false, "middle_out" or an object such as {"strategy": "middle_out", "trigger_ratio": 0.8}. Requests, keys and teams can only choose middle_out.

Per request​

curl http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.6",
"context_fit": true,
"messages": [{"role": "user", "content": "..."}]
}'

Clients that already send "transforms": ["middle-out"] can keep doing so. For deployments on a provider that understands the field it is passed through and the gateway does not trim as well. For every other provider the gateway does the trimming and removes transforms before the call, so providers that reject unknown fields still accept the request. "transforms": [] switches it off.

Per key or team​

curl http://localhost:4000/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{"metadata": {"context_fit": {"strategy": "middle_out"}}}'

Teams take the same metadata.context_fit through /team/new and /team/update. The gateway checks the value when the key or team is saved and answers 400 with Context compaction: metadata.context_fit must be true, false, "middle_out" or an object with a strategy or Context compaction: metadata.context_fit only accepts the middle_out strategy, so a typo never reaches live traffic.

Per deployment​

model_list:
- model_name: gpt-5.6
spanway_params:
model: openai/gpt-5.6
api_key: os.environ/OPENAI_API_KEY
model_info:
context_fit:
strategy: middle_out
trigger_ratio: 0.85

The setting is read for the deployment the router actually picked, so deployments in one group can have different windows and different settings. A context_fit set in spanway_params is moved to model_info when the deployment loads, so it is never sent to the provider on any endpoint. An invalid value fails the deployment when it loads instead of failing requests later.

For the whole gateway​

router_settings:
context_fit: middle_out

An admin can also switch this on in the Admin UI under Router Settings with the Fit To Context switch.

To summarize instead of dropping turns, point model at a model group whose provider supports native compaction.

router_settings:
context_fit:
strategy: summarize
model: claude-compactor
max_tokens: 4096

How you can tell it ran​

When the gateway trims a request, the response carries two headers.

HeaderValue
x-spanway-context-fitThe strategy that ran, middle_out or summarize.
x-spanway-context-fit-dropped-messagesHow many messages were removed or folded into the summary.

Neither header is present when the request went out unchanged.

Auto router​

The auto router has its own context_compaction block, which summarizes by default. Set strategy: middle_out inside it to drop middle turns there instead.

Errors​

What you seeWhat it meansFix
ContextWindowExceededError (400) even with fit to context onThe kept turns alone, the system prompt, the first user turn and the newest turns, are longer than the window.Shorten the system prompt, or route to a model with a larger window.
400 Context compaction: context_fit must be true, false, "middle_out" or an object with a strategyThe request's context_fit, or a key or team value saved before the gateway checked it, cannot be read. The message names context_fit, key metadata.context_fit or team metadata.context_fit.Send true, false, "middle_out" or {"strategy": "middle_out"}.
400 Context compaction: context_fit only accepts the middle_out strategyA request, key or team asked for summarize, which only an admin may set in router_settings or on a deployment.Use middle_out, or ask an admin to set summarize on the deployment.
400 Context compaction: The output allowance must be a positive integermax_tokens, max_completion_tokens or max_output_tokens is 0 or negative.Send a positive number, or leave it out.
ContextWindowExceededError (400) Context compaction: Retained instructions, tools and the latest turn leave no room for a summaryWith summarize, the parts that are always kept already fill the window.Shorten the instructions or tools, or route to a larger model.
ContextWindowExceededError (400) Context compaction: The summary and retained conversation still exceed the selected deployment's budgetWith summarize, the summary did not make the request small enough.Lower max_tokens on the compactor, or route to a larger model.
No x-spanway-context-fit header on a long requestFit to context is not on for that key, team or request, or the request already fitted.Turn it on as in Turn it on.
The answer ignores an early detailThe detail was in a middle turn that was dropped.Use summarize, which folds those turns into a summary, or keep the detail in the system prompt.

To see trimmed requests in the Admin UI, open Logs, open a request and read its response headers. Settings that apply to every key live on the Router Settings page under Settings.

Logs​

Fit to context writes no operator log line of its own. A trimmed request shows on the Logs page with the x-spanway-context-fit and x-spanway-context-fit-dropped-messages response headers, and a summarize run adds one spend row for the compactor model call. A change to the gateway default under router_settings writes an audit row, see audit logs.