컨텍스트 압축과 캐싱
기준일: 2026-07-26
난이도: 중급
공식 기준: Context Compression and Caching
개요
긴 대화의 이중 압축(게이트웨이 hygiene + 에이전트 ContextCompressor)과 프롬프트 캐시 안정성을 정리합니다.
핵심 개념
| 구성 | 역할 |
|---|---|
| Gateway hygiene | 세션 비대화 방지 (고임계) |
| ContextCompressor | 턴 예산 관리 (중임계) |
| Structured summary | Goal/Progress/Decisions |
| Pluggable engine | context.engine 교체 |
상세
교체 가능한 Context Engine
원문 절: Pluggable Context Engine
- Check
plugins/context_engine/<name>/directory - Check general plugin system (
register_context_engine()) - Fall back to built-in
ContextCompressor
context:
engine: "compressor" # default — built-in lossy summarization
engine: "lcm" # example — plugin providing lossless context
이중 압축 시스템
원문 절: Dual Compression System
- 1. Gateway Session Hygiene (85% threshold) — 공식 하위 절. 구현·설정 세부 원문 참조.
- 2. Agent ContextCompressor (50% threshold, configurable) — 공식 하위 절. 구현·설정 세부 원문 참조.
- safety net
- Threshold
- Token source
- Fires
┌──────────────────────────┐
Incoming message │ Gateway Session Hygiene │ Fires at 85% of context
─────────────────► │ (pre-agent, rough est.) │ Safety net for large sessions
└─────────────┬────────────┘
│
▼
┌──────────────────────────┐
│ Agent ContextCompressor │ Fires at 50% of context (default)
│ (in-loop, real tokens) │ Normal context management
└──────────────────────────┘
설정
원문 절: Configuration
- Parameter Details — 공식 하위 절. 구현·설정 세부 원문 참조.
- Per-model threshold overrides — 공식 하위 절. 구현·설정 세부 원문 참조.
- Codex gpt-5.5 threshold autoraise — 공식 하위 절. 구현·설정 세부 원문 참조.
- Codex app-server thread compaction — 공식 하위 절. 구현·설정 세부 원문 참조.
- Computed Values (for a 200K context model at defaults) — 공식 하위 절. 구현·설정 세부 원문 참조.
| Parameter | Default | Range | Description |
|---|---|---|---|
threshold |
0.50 |
0.0-1.0 | Compression triggers when prompt tokens ≥ threshold × context_length |
model_thresholds |
{} |
map | Per-model overrides of threshold. Keys are substring-matched against the model name (longest match wins). The small-context floor still applies on top (see below) |
target_ratio |
0.20 |
0.10-0.80 | Controls tail protection token budget: threshold_tokens × target_ratio |
protect_last_n |
20 |
≥1 | Minimum number of recent messages always preserved |
min_tail_user_messages |
1 |
≥1 | Minimum number of REAL (actionable) user messages guaranteed to survive in the uncompressed tail. 1 = the existing single last-user anchor (behavior-preserving default). Raise to e.g. 3 to keep the last 3 real user turns verbatim even when bulky tool outputs fill the tail token budget. Blank platform echoes, compaction handoffs, and synthetic continuation rows never count toward N. The guarantee wins over the tail token budget — the tail may exceed the budget when the anchor pulls the cut back |
protect_first_n |
3 |
(hardcoded) | System prompt + first exchange always preserved |
idle_compact_after_seconds |
0 |
≥0 seconds | Opt-in: compact up front when a session resumes after this many seconds idle (0 = disabled). Skips when context ≤ threshold × target_ratio; honors cooldown/anti-thrash/lock guards |
codex_gpt55_autoraise |
true |
bool | Raise the trigger to 85% for gpt-5.5 on the ChatGPT Codex OAuth route (see below). Set false to keep the global threshold |
codex_gpt55_autoraise_notice |
true |
bool | Show the one-time Codex gpt-5.5 autoraise notice. Set false to keep the 85% autoraise but suppress the banner |
codex_app_server_auto |
native |
native, hermes, off |
Thread-compaction mode for Codex app-server sessions (see below) |
compression:
threshold: 0.50
model_thresholds:
"glm-5.2": 0.40
"glm-5.2-1M": 0.25
"claude-sonnet": 0.35
압축 알고리즘
원문 절: Compression Algorithm
- Phase 1: Prune Old Tool Results (cheap, no LLM call) — 공식 하위 절. 구현·설정 세부 원문 참조.
- Phase 2: Determine Boundaries — 공식 하위 절. 구현·설정 세부 원문 참조.
- Phase 3: Generate Structured Summary — 공식 하위 절. 구현·설정 세부 원문 참조.
[Old tool output cleared to save context space]
Goal
- 이 절의 절차·표·코드는 공식 원문을 기준으로 적용한다.
Constraints & Preferences
- 이 절의 절차·표·코드는 공식 원문을 기준으로 적용한다.
Progress
- Done — 공식 하위 절. 구현·설정 세부 원문 참조.
- In Progress — 공식 하위 절. 구현·설정 세부 원문 참조.
- Blocked — 공식 하위 절. 구현·설정 세부 원문 참조.
Key Decisions
- 이 절의 절차·표·코드는 공식 원문을 기준으로 적용한다.
Relevant Files
- 이 절의 절차·표·코드는 공식 원문을 기준으로 적용한다.
Next Steps
- 이 절의 절차·표·코드는 공식 원문을 기준으로 적용한다.
Critical Context
- Phase 4: Assemble Compressed Messages — 공식 하위 절. 구현·설정 세부 원문 참조.
- Iterative Re-compression — 공식 하위 절. 구현·설정 세부 원문 참조.
- Head messages (with a note appended to system prompt on first compression)
- Summary message (role chosen to avoid consecutive same-role violations)
- Tail messages (unmodified)
Before/After Example
- Before Compression (45 messages, ~95K tokens) — 공식 하위 절. 구현·설정 세부 원문 참조.
- After Compression (25 messages, ~45K tokens) — 공식 하위 절. 구현·설정 세부 원문 참조.
[0] system: "You are a helpful assistant..." (system prompt)
[1] user: "Help me set up a FastAPI project"
[2] assistant: <tool_call> terminal: mkdir project </tool_call>
[3] tool: "directory created"
[4] assistant: <tool_call> write_file: main.py </tool_call>
[5] tool: "file written (2.3KB)"
... 30 more turns of file editing, testing, debugging ...
[38] assistant: <tool_call> terminal: pytest </tool_call>
[39] tool: "8 passed, 2 failed\n..." (5KB output)
[40] user: "Fix the failing tests"
[41] assistant: <tool_call> read_file: tests/test_api.py </tool_call>
[42] tool: "import pytest\n..." (3KB)
[43] assistant: "I see the issue with the test fixtures..."
[44] user: "Great, also add error handling"
Prompt Caching (Anthropic)
- Strategy: system_and_3 — 공식 하위 절. 구현·설정 세부 원문 참조.
- How It Works — 공식 하위 절. 구현·설정 세부 원문 참조.
- Cache-Aware Design Patterns — 공식 하위 절. 구현·설정 세부 원문 참조.
- Enabling Prompt Caching — 공식 하위 절. 구현·설정 세부 원문 참조.
- Stable system prompt
- Message ordering matters
| Content Type | Where Marker Goes |
|---|---|
| String content | Converted to [{"type": "text", "text": ..., "cache_control": ...}] |
| List content | Added to the last element's dict |
| None/empty | Added as msg["cache_control"] |
| Tool messages | Added as msg["cache_control"] (native Anthropic only) |
Breakpoint 1: System prompt (stable across all turns)
Breakpoint 2: 3rd-to-last non-system message ─┐
Breakpoint 3: 2nd-to-last non-system message ├─ Rolling window
Breakpoint 4: Last non-system message ─┘
Context Pressure Warnings
- 이 절의 절차·표·코드는 공식 원문을 기준으로 적용한다.
체크리스트
- 공식 원문 Context Compression and Caching과 대조했다
- 관련 코드·설정·권한을 로컬에서 확인했다
- 보안·opt-in·allowlist 정책을 지켰다
- 스모크 테스트 또는 단계 검증을 수행했다
다음 단계
기준일: 2026-07-26 — 공식 문서 동기화 코퍼스