Skip to main content
Connic
Back to BlogProduct Spotlight

LLM Context Compression for Long-Running AI Agents

Connic compresses older conversation history and oversized tool results, then retries the model call, so long-running agent sessions survive context limits.

July 20, 20268 min read

An agent that answers one prompt never worries about the context window. An agent that holds a support conversation for three weeks, processes a queue around the clock, or works through a forty-step task does. Conversation history only grows, every model has a hard token limit, and when a session crosses it the provider rejects the call and the run fails mid-task.

The hard limit is only half the problem. Model quality drops well before the window is full. Chroma's context-rot study (2025) evaluated 18 frontier models and found that output quality degrades as input length grows, even on simple tasks. Earlier, Lost in the Middle (Liu et al., 2023) showed that models retrieve information best from the start and end of a prompt, with accuracy dropping sharply when it sits in the middle. A bloated context does not only risk an error. It makes every answer worse.

Why Long-Running Agents Run Out of Context

Three things fill an agent's context window, and none of them shrink on their own:

Persistent Sessions
Session-backed agents carry conversation history across runs. A support agent keyed to a chat ID accumulates every user message and every reply, for as long as the session lives.
Tool Results
One verbose API response can outweigh fifty chat messages. A database query that returns a few hundred rows lands in the context as tens of kilobytes of JSON, and it stays there for every subsequent model call.
Multi-Step Reasoning
Agent loops add turns. Each tool call means another model request and another response appended to history, so a single complex task can generate dozens of messages before it produces a final answer.

Truncation, Sliding Windows, and Summarization

There are three common ways to keep an LLM context bounded, with very different failure modes:

Truncation
Drop the oldest messages when the context gets full. Free and instant, but the agent forgets the goals and constraints that were set at the start, which is exactly the information it needs to finish the task.
Sliding Window
Keep only the last N messages. Predictable size, same amnesia problem, plus a new one: a naive cutoff can separate a tool call from its result, which many providers reject as a malformed request.
LLM Summarization
Replace older history with a model-written summary that preserves goals, decisions, and IDs at a fraction of the tokens. Costs an extra model call or two when it runs, and keeps the agent able to continue the task.

Connic uses LLM summarization, with retention rules designed to avoid the failure modes of the other two.

Ship agents that survive long sessions

Context compression, persistent sessions, and full traces are built into every Connic agent runtime.

Get started free

How Connic Compresses Context

The default trigger is the moment things would otherwise break: a provider context-limit error.

Model CallContext Limit ErrorCompressRetryResponse

When a model call fails, the runner classifies the error. It recognizes context-window errors across providers and explicitly ignores rate-limit and quota errors, so compression only fires on a genuine overflow. It then compresses the request and retries the call once, inside the same run. The user never sees a failed run, and no work is lost. If the retried call still exceeds the window, the run fails with the original error.

What stays, what gets summarized

The most recent messages stay verbatim: keep_recent_messages, 8 by default. The boundary is then adjusted backwards so that a tool result is never separated from the call that produced it, the malformed-request trap that naive windowing falls into.

Everything older is summarized by an LLM with strict instructions: preserve user goals, constraints, decisions, tool names and arguments, tool results, IDs, numbers, errors, open questions, and next steps, and invent nothing. History too long for a single pass is split into 12,000-character chunks, each chunk summarized, and the chunk summaries merged into one continuation summary.

The result is inserted as a single message that tells the model exactly what happened: earlier history was compressed, and the retained recent messages are the source of truth for the current turn. The model continues the task instead of hallucinating a fresh start.

Oversized tool results

Compression also targets the single biggest space consumer directly. When compression runs, oversized tool responses within the retained messages are summarized in place and replaced with a compact record that includes the summary and the original size. A bulky JSON payload becomes a paragraph, and the agent keeps the facts it extracted from it.

Compress before the error: token budgets

Waiting for the provider to complain means one failed call per compression. Set max_prompt_tokens and the runner compresses proactively instead: it records the model-reported prompt token count after every call, and when the last call meets the budget it compresses before sending the next one. No error, no retry, no wasted call. Because Connic is bring-your-own-key, smaller prompts also show up directly as lower input cost on your provider bill.

A cheaper model for summaries

Summaries do not need your best model. Set context_compression.model to run them on a small, fast model while the agent itself stays on its configured one. If you omit it, summaries use the agent model. The retried agent call always uses the agent model either way.

Configuration in YAML

Context compression is part of the agent YAML for any LLM agent. A complete configuration for a session-backed chat agent:

agents/support-bot.yaml
version: "1.0"

name: support-bot
type: llm
model: gemini/gemini-2.5-pro
description: "A support chatbot that remembers conversation history"
system_prompt: |
  You are a helpful support agent. Use the conversation history
  to provide contextual responses.

# Persistent sessions keyed by chat ID
session:
  key: context.chat_id
  ttl: 86400

# Keep long conversations within the model context window
context_compression:
  enabled: true
  # Optional model for compression summaries; defaults to the agent model
  model: gemini/gemini-2.5-flash
  keep_recent_messages: 12
  # Optional early compression based on model-reported prompt usage
  max_prompt_tokens: 100000
  # Optional compaction for stored session history between runs
  session_history:
    interval: 4
    keep_recent_runs: 1

Only the block itself is required. Add context_compression with enabled: true and you get error-triggered compression with the defaults. Everything else is tuning.

Compacting Stored Session History

In-request compression shapes what a single model call sees. Session-backed agents have a second growth problem: the history stored between runs. The session_history block compacts it. Every interval runs, older stored history is replaced with a summary, keeping the most recent keep_recent_runs runs untouched. A session that has been alive for months starts each new run from a compact summary plus recent turns, not from its entire life story.

Every Compression Is a Trace Span

Compression rewrites what your agent sees, so it should never be invisible. Each compression is captured as an OpenTelemetry trace span in the run:

What Fired and Why
Spans record the trigger reason (provider error or token budget), message counts before and after, whether history was summarized, and how many tool responses were compressed with their character reduction.
What It Cost
The summary calls consume tokens too. Each span carries the token usage of the compression itself, so the overhead is visible per run instead of hiding inside your provider bill.

In-request compression appears as a context_compression span, stored-history compaction as history_compression. Both also write log lines into the run. See the observability documentation for how traces work, or read the agent observability guide for the bigger picture.

Tip: Start Reactive, Then Add a Budget
Error-triggered compression is the safe default: it costs nothing until a session actually overflows. Once traces show sessions regularly hitting the window, set max_prompt_tokens below the model's limit so compression runs before the failed call instead of after it.

Getting Started

Adding context compression to an existing LLM agent takes minutes:

  • 1.Add a context_compression block to the agent's YAML configuration
  • 2.Deploy. Compression activates on the next run, no code changes needed
  • 3.Watch the Traces tab for context_compression spans as long sessions hit the window
  • 4.Tune keep_recent_messages, add a token budget, or switch summaries to a cheaper model based on what you see

For the full option reference, including sessions and compaction, see the runtime controls documentation. New to Connic? Follow the quickstart guide to deploy your first agent, then give it a memory that does not run out.

More from the Blog

Announcement

Introducing the Connic Marketplace

The Connic Marketplace is the new home for agent templates, connectors, and retrieval sources. One catalog, one publisher model, one CLI install.

July 5, 20265 min read
Product Spotlight

Connic Tests: Catch Agent Regressions Before They Reach Production

A YAML-driven testing framework built for non-deterministic AI agents. Repeated-run pass thresholds, expression-based assertions, custom-code mocking, multimodal fixtures, and a deploy gate that blocks failed checks by default.

May 6, 20268 min read
Product Spotlight

Human-in-the-Loop AI Agents: How Approvals Work in Production

How to pause an AI agent before refunds, deletes, or external calls, route the decision to a human, and resume automatically, with a full audit trail.

April 5, 202610 min read
Product Spotlight

A/B Testing for AI Agents: Ship Better Prompts with Confidence

You changed the prompt. It feels better. But is it actually better? Learn how to run controlled experiments on your AI agents and let real traffic decide.

March 27, 20269 min read
Product Spotlight

Secure AI Agents: A Production Safety Checklist

Shipping AI agents without a security strategy is a liability. A practical checklist covering prompt injection, PII handling, output validation, and the guardrails you need before go-live.

March 21, 202612 min read
Product Spotlight

Agent Guardrails: Real-Time Safety for Your AI Agents

Connic Guardrails intercept agent inputs and outputs in real time to block prompt injection, redact PII, and enforce topic restrictions.

March 3, 20269 min read
Product Spotlight

Connic Bridge: AI Agents for Private Infrastructure

Connic Bridge creates a secure outbound tunnel so your AI agents can reach private Kafka, databases, and internal services without opening inbound ports.

February 19, 20267 min read
Product Spotlight

Agent Observability: Track Costs, Tokens & Runs

Deploying AI agents without visibility is flying blind. Build custom dashboards, track LLM costs per model, and catch failures before users do.

January 23, 20268 min read
Product Spotlight

Composer SDK: Better Agent Development Tooling

No more manual uploads or YAML guessing. The Composer SDK adds scaffolding, validation, cloud-backed hot-reload development, and CLI deployments.

December 27, 20255 min read