Context Window
A context window is the maximum number of tokens (roughly 0.75 words per token) that an AI model can process in a single inference, encompassing everything simultaneously visible to the model: system prompts, conversation history, retrieved documents, user instructions, and generated responses. Acting as the model's working memory, the context window defines the absolute information boundary of any single AI interaction—content outside the window is invisible, context inside shapes every word of the output.
Business Context
Understanding context windows is the difference between AI implementations that work reliably and those that mysteriously fail at scale. As conversations grow or documents expand, organizations hit context limits in ways that produce invisible, dangerous failures: the AI simply ignores earlier content rather than signaling it can't process it, potentially producing outputs that contradict instructions given 10,000 tokens earlier. Conversely, organizations that master context window management unlock capabilities unavailable to competitors: analyzing 200-page contracts in a single pass, maintaining month-long conversation threads with full coherence, or grounding AI responses in vast proprietary knowledge bases. Context window engineering is not a technical detail—it is a strategic capability that determines how much intelligence your AI system can actually apply to any given decision.
Oregon Market Application
Business Type: Portland-based insurance brokerage (commercial lines, $45M in annual premiums placed)
Problem: Implemented AI assistant to help brokers analyze commercial insurance applications and match policies. System worked well for simple accounts. For complex commercial accounts with extensive history, the AI started producing dangerous errors:
- Ignoring coverage requirements mentioned early in long application documents
- Forgetting policy conditions noted in conversation history
- Missing material facts that appeared in page 40 of 80-page applications
A $2.3M commercial real estate account nearly bound with incorrect flood coverage because the AI didn't "see" the flood zone notation buried on page 47 of the property schedule—it had exceeded the context window.
Problem Diagnosis:
Context Window Audit:
Available: 128,000 tokens (~96,000 words)
Typical complex account:
- System prompt: 3,000 tokens
- Application document: 85,000 tokens (for large accounts)
- Policy comparison documents: 60,000 tokens
- Conversation history: 25,000 tokens
TOTAL: 173,000 tokens → EXCEEDS LIMIT
Result: Documents truncated silently
Material information dropped without warning
AI outputs confident answers based on incomplete data
Solution: Implemented tiered context management strategy:
Tier 1: Small Accounts (Under 50K tokens)
Direct processing:
All documents fit within context window
No special handling needed
90% of accounts
Tier 2: Medium Accounts (50K-100K tokens)
Intelligent chunking:
1. Extract high-priority sections (coverage requirements, exclusions,
special conditions) → Always in context
2. Summarize lower-priority sections (general conditions, standard terms)
3. Load summaries into context; original available via RAG
80% information density with 60% token usage
Tier 3: Large Accounts (100K+ tokens)
RAG + Hierarchical Context:
1. Index all documents in vector database
2. AI requests specific sections as needed
3. Core requirements document always loaded
4. Supporting documents retrieved on demand
Effectively unlimited document processing
Technical Implementation:
def manage_context_window(documents, conversation_history, max_tokens=120000):
"""
Intelligently manage context window allocation
"""
# Reserve space for system prompt and response
SYSTEM_PROMPT_TOKENS = 3000
RESPONSE_RESERVE = 8000
AVAILABLE_TOKENS = max_tokens - SYSTEM_PROMPT_TOKENS - RESPONSE_RESERVE
# = 109,000 tokens available for content
# Priority allocation
budget = {
'critical_requirements': int(AVAILABLE_TOKENS * 0.30), # 32,700 tokens
'recent_conversation': int(AVAILABLE_TOKENS * 0.20), # 21,800 tokens
'policy_documents': int(AVAILABLE_TOKENS * 0.30), # 32,700 tokens
'supporting_docs': int(AVAILABLE_TOKENS * 0.20), # 21,800 tokens
}
# Extract and prioritize content
critical = extract_critical_requirements(documents) # Coverage limits, exclusions
recent_conv = truncate_to_tokens(conversation_history, budget['recent_conversation'])
policies = select_relevant_policies(documents, budget['policy_documents'])
supporting = retrieve_supporting(documents, budget['supporting_docs'])
return assemble_context(critical, recent_conv, policies, supporting)
def extract_critical_requirements(documents):
"""Extract high-priority content using pattern matching + AI classification"""
critical_patterns = [
r'REQUIRED COVERAGE',
r'MINIMUM LIMITS',
r'COVERAGE EXCLUSIONS',
r'SPECIAL CONDITIONS',
r'ENDORSEMENTS REQUIRED',
r'FLOOD ZONE', # Added after the flood coverage incident
r'SEISMIC ZONE',
r'PROFESSIONAL LIABILITY',
]
# Pattern match first, then AI classify remaining
return prioritized_extraction(documents, critical_patterns)
Results:
- Coverage errors from truncation: 3/month → 0 in 11 months
- Large account processing capability: Impossible → 100+ pages reliably
- Broker productivity on complex accounts: +38%
- E&O insurance savings (error reduction): Estimated $40K/year avoided claims
- System now processes 200-page property schedules without data loss
Kenya Market Application
Context: Nairobi-based supply chain management company coordinating procurement for 120 SME clients across East Africa
Challenge: AI procurement assistant was failing on long-running supplier negotiations. After 4-5 email exchanges totaling 8,000+ words, the AI began forgetting agreed terms from earlier in the conversation:
- Forgot price cap agreements from negotiation round 2 when reviewing round 5 proposals
- Lost track of quality specifications agreed in week 1 when drafting week 3 orders
- Generated contracts missing clauses discussed earlier in the thread
Lost approximately KES 2.1M in a single procurement error when AI failed to include an agreed 90-day payment term—context had been exceeded and the AI defaulted to standard 30-day terms.
Implementation: Built sliding window context management:
Context Strategy for Long Negotiations:
SLIDING WINDOW APPROACH:
Round 1-3 (Early negotiation):
Full conversation history loaded
All parties' positions tracked
No truncation needed
Round 4-6 (Middle negotiation):
COMPRESS: Summarize rounds 1-2 into "Agreed Terms Summary"
KEEP: Full rounds 3-6 (recent + most relevant)
INJECT: "Running Agreements" document at top of context
Round 7+ (Late negotiation):
COMPRESS: Summarize all prior rounds
EXTRACT: All agreed terms → Structured format
HIGHLIGHT: Unresolved issues
CONTEXT = Agreed Terms Summary + Unresolved Issues + Last 2 Rounds
Running Agreements Document (auto-generated):
PROCUREMENT NEGOTIATION: [SUPPLIER] - [PRODUCT]
Status: Round {N}
Last Updated: {DATE}
═══════════════════════════════
CONFIRMED AGREED TERMS
═══════════════════════════════
Price: KES {AMOUNT} per unit (agreed Round 2)
Payment: 90-day from delivery (agreed Round 3) ← CRITICAL - never drop this
Quantity: Minimum 500 units/month (agreed Round 2)
Quality: ISO 9001 certification required (agreed Round 1)
Delivery: Nairobi warehouse, within 21 days (agreed Round 2)
═══════════════════════════════
STILL UNDER NEGOTIATION
═══════════════════════════════
- Warranty terms: Supplier wants 6 months; we need 12 months
- Penalty clauses: % for late delivery (not yet agreed)
- Price escalation: Annual review clause (not yet agreed)
═══════════════════════════════
LATEST SUPPLIER POSITION
═══════════════════════════════
{LAST_EMAIL_CONTENT}
═══════════════════════════════
YOUR TASK
═══════════════════════════════
[Current specific request]
Results:
- Negotiation errors from context loss: 4/quarter → 0 in 12 months
- Large procurement deal capability: Lost coherence after round 3 → Full negotiation support
- Contract accuracy review time: 3 hours/contract → 45 minutes
- KES 2.1M incident: Not repeated; system now flags payment terms in every round
- Procurement cycle time: 28 days average → 16 days (faster because AI maintains continuity)
Technical Details
Context Window by Model (February 2026):
| Model | Context Window | Token Equivalents | Best For |
|---|---|---|---|
| GPT-4 Turbo | 128K tokens | ~96,000 words | General business use |
| Claude 3.5 Sonnet | 200K tokens | ~150,000 words | Long documents, complex analysis |
| Gemini 1.5 Pro | 1M tokens | ~750,000 words | Massive document processing |
| Llama 3.1 70B | 128K tokens | ~96,000 words | Self-hosted deployments |
| Mistral Large | 128K tokens | ~96,000 words | European data residency |
Token Counting:
- 1 token ≈ 0.75 words in English
- Code is more token-dense than prose
- Non-English languages vary significantly
- Whitespace and formatting consume tokens
# Estimate tokens before API call
import tiktoken
encoder = tiktoken.encoding_for_model("gpt-4")
token_count = len(encoder.encode(your_text))
Context Window Management Strategies:
STRATEGY 1: COMPRESSION
- Summarize old conversation turns
- Replace verbose context with condensed summaries
- Preserve key facts, compress surrounding narrative
STRATEGY 2: RETRIEVAL
- Store documents in vector database
- Retrieve only relevant sections per query
- Never load full documents when sections suffice
STRATEGY 3: PRIORITIZATION
- Rank content by relevance to current query
- Always-in-context: System prompt, critical constraints
- On-demand: Supporting details, background information
STRATEGY 4: CHUNKING
- Split large documents into smaller units
- Process each chunk, store results
- Combine chunk results into final output
STRATEGY 5: SUMMARIZATION CHAINS
- Process document in sections
- Generate running summary
- Use summary as context for next section
Red Flags That Indicate Context Window Problems:
- AI "forgets" instructions given earlier in conversation
- AI gives answers contradicting previous context
- Quality degrades in long sessions but works in new sessions
- AI claims it "doesn't have information" about something you clearly provided
- Outputs become generic as conversation grows