🤖 AI/ML

Context Window

Context Window

The number of tokens an LLM can process at once. Claude 200K, GPT-4 128K, and so on.

📖 Detailed Explanation

Context Window refers to the maximum number of tokens that an LLM (Large Language Model) can process in a single inference. The total length of the input prompt and the output response combined must fall within this limit, and a token is the basic unit into which text is split, at the level of words, subwords, or characters.

Starting from 2K tokens in GPT-3 in 2020, context windows have expanded rapidly to 128K in GPT-4, 200K in Claude 3, and 1M in Gemini 1.5. This progress has been driven by optimization of the Attention mechanism (Flash Attention, Sparse Attention), memory-efficiency techniques (KV Cache compression), and improved positional encoding (RoPE, ALiBi).

A larger context window makes it possible to analyze an entire long document at once, maintain a long conversation history, or reference multiple files simultaneously. However, as the context grows longer, computational cost increases as O(n^2), and the "Lost in the Middle" phenomenon can degrade retrieval performance for information in the middle portion.

In practice, the context window directly affects RAG architecture design, chunking strategy, prompt engineering, and cost optimization. Rather than blindly using a large context, finding the optimal length for the task and selectively including only the necessary information is advantageous for both performance and cost.

💻 Code Example

import tiktoken
from anthropic import Anthropic

# 토큰 수 계산 (OpenAI 모델용 tiktoken 예시)
def count_tokens_openai(text: str, model: str = "gpt-4") -> int:
    encoding = tiktoken.encoding_for_model(model)
    return len(encoding.encode(text))

# Claude 토큰 수 계산 (Anthropic API 사용)
def count_tokens_claude(text: str) -> int:
    client = Anthropic()
    # count_tokens API는 Claude 모델의 정확한 토큰 수 반환
    result = client.count_tokens(text)
    return result.tokens

# 컨텍스트 윈도우 관리 예시
class ContextManager:
    def __init__(self, max_tokens: int = 128000, reserve_output: int = 4096):
        self.max_tokens = max_tokens
        self.reserve_output = reserve_output  # 출력용 토큰 예약
        self.available = max_tokens - reserve_output

    def fit_messages(self, messages: list[dict], system_prompt: str = "") -> list[dict]:
        """컨텍스트 윈도우에 맞게 메시지 자르기 (최근 메시지 우선)"""
        system_tokens = count_tokens_openai(system_prompt) if system_prompt else 0
        available = self.available - system_tokens

        fitted = []
        current_tokens = 0

        # 최신 메시지부터 역순으로 추가
        for msg in reversed(messages):
            msg_tokens = count_tokens_openai(msg["content"])
            if current_tokens + msg_tokens <= available:
                fitted.insert(0, msg)
                current_tokens += msg_tokens
            else:
                break

        print(f"사용 토큰: {current_tokens + system_tokens}/{self.max_tokens}")
        print(f"포함된 메시지: {len(fitted)}/{len(messages)}")
        return fitted

# 사용 예시
manager = ContextManager(max_tokens=128000)
chat_history = [{"role": "user", "content": "..." }] * 100  # 긴 대화

fitted_messages = manager.fit_messages(chat_history, system_prompt="You are helpful.")
# 결과: 컨텍스트에 맞게 오래된 메시지가 제거됨

🗣️ Examples of Practical Conversations

In an LLM service design meeting

"With Claude's 200K context, you could fit an entire book in one go. But if you actually do that, besides the cost, retrieval of the middle content can drop because of the Lost in the Middle phenomenon. It's more realistic to use RAG to pull out only the relevant chunks and work with about 20K."

In a technical interview

"As the context window grows, Attention computation increases as O(n^2), so cost and latency rise sharply. That's why optimization techniques like Flash Attention and Sliding Window Attention matter, and when choosing a model, you shouldn't just look at the maximum token count, but also consider the range that is actually usable."

In a prompt optimization discussion

"If you cut the prompt too much to save tokens, quality drops, and if it's too long, costs explode. We recommend keeping the system prompt within 500 tokens, limiting examples to 2-3, and adding only the context that's needed dynamically."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

📊 Context Window Comparison by Model (January 2025)

Model Context Approx. character count Features
Gemini 1.5 Pro 1M ~750,000 characters 🏆 Maximum (an entire book)
Claude 3.5 Sonnet 200K ~150,000 characters 📄 Best for long document analysis
GPT-4o / o1 128K ~100,000 characters ⚡ Fast response speed
Llama 3.1 405B 128K ~100,000 characters 🔓 Open source
BERT 512 ~400 characters ⚠️ Short (chunking required)

💡 Conversion basis: 1 English token ≈ 4 characters, 1 Korean token ≈ 1.5 characters. 128K tokens = approx. 300 pages of English documents = approx. 80,000 Korean characters.

⚠️ Cautions

1
Input + Output Combined

The context window is the sum of input and output. If you input 100K tokens into a 128K model, the output is limited to 28K. Keep this in mind when setting max_tokens.

2
Beware of Cost Surges

API cost increases in proportion to the number of tokens. A 100K-token prompt costs 100 times as much as a 1K-token prompt. Avoid wasting unnecessary context.

3
Performance Degradation with Long Contexts

According to the "Lost in the Middle" study, models remember information at the beginning and end well but tend to miss the middle portion. Place important information at the beginning and end.

🔗 Related Terms

📚 Learn More