Published

Context Window Management: Strategies for Long Documents and Long Conversations

Million-token context windows still cost time and money. Chunking, compression, sliding windows and map-reduce strategies for long documents and chat histories.

Written by
Ali ÖzdurmuşFounder, Veni AI
Updated
Reading time
6 min read

The context window is the maximum number of tokens a model can read in one request. Current frontier models accept around a million tokens, but filling that window is slow, expensive and not always accurate: models can still miss details buried in the middle of very long inputs. Managing context well remains one of the biggest levers on quality and cost.

Code samples are illustrative Python. client is an initialized SDK client and MODEL is a placeholder for the model ID you choose.

Context Window Limits

Model Comparison

Input limits from our model catalog (October 2026). Output limits are much smaller, so check both in your provider's documentation.

ModelContext length
GPT-6 Astra, GPT-6.1 Sol1.05M
Claude Opus 5.5, Sonnet 5.5, Haiku 5.51M
Gemini 4 Argon1M
DeepSeek V4 Pro (open weights)1M
Grok 4.7500K

As a rough guide, one million tokens is about 750,000 English words.

Token Calculation

python
import tiktoken

def count_tokens(text: str, encoding_name: str = "o200k_base") -> int:
    encoding = tiktoken.get_encoding(encoding_name)
    return len(encoding.encode(text))

def estimate_tokens(text: str) -> int:
    # Quick estimate: ~4 chars = 1 token (English)
    return len(text) // 4

Tokens and Turkish Text

Models split text into subword tokens using methods such as BPE or SentencePiece. Tokenizers are trained mostly on English, and Turkish is agglutinative (one word can carry several suffixes), so the same content often needs more tokens in Turkish than in English. Measure token counts on your own documents when you estimate context usage and cost.

Chunking Strategies

Fixed-Size Chunking

python
def fixed_size_chunk(text: str, chunk_size: int = 1000, overlap: int = 200) -> list:
    chunks = []
    start = 0
    
    while start < len(text):
        end = start + chunk_size
        chunk = text[start:end]
        chunks.append(chunk)
        start = end - overlap
    
    return chunks

Semantic Chunking

python
from langchain_text_splitters import RecursiveCharacterTextSplitter

def semantic_chunk(text: str, chunk_size: int = 1000) -> list:
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=200,
        separators=["\n\n", "\n", ". ", " ", ""],
        length_function=len
    )
    
    return splitter.split_text(text)

Document Structure Aware

python
def structure_aware_chunk(document: str) -> list:
    chunks = []
    current_section = ""
    current_header = ""
    
    for line in document.split("\n"):
        # Header detection
        if line.startswith("#"):
            if current_section:
                chunks.append({
                    "header": current_header,
                    "content": current_section.strip()
                })
            current_header = line
            current_section = ""
        else:
            current_section += line + "\n"
    
    if current_section:
        chunks.append({
            "header": current_header,
            "content": current_section.strip()
        })
    
    return chunks

Context Compression

Summarization

python
def compress_context(text: str, max_tokens: int = 2000) -> str:
    current_tokens = count_tokens(text)
    
    if current_tokens <= max_tokens:
        return text
    
    # Summarize with LLM
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {
                "role": "system",
                "content": f"Summarize the following text under {max_tokens} tokens. "
                          "Preserve important information."
            },
            {"role": "user", "content": text}
        ]
    )
    
    return response.choices[0].message.content

Extractive Compression

python
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

def extractive_compress(text: str, ratio: float = 0.3) -> str:
    sentences = text.split(". ")
    
    # Find important sentences with TF-IDF
    vectorizer = TfidfVectorizer()
    tfidf_matrix = vectorizer.fit_transform(sentences)
    
    # Importance score of each sentence
    scores = np.array(tfidf_matrix.sum(axis=1)).flatten()
    
    # Select most important sentences
    num_sentences = max(1, int(len(sentences) * ratio))
    top_indices = np.argsort(scores)[-num_sentences:]
    top_indices = sorted(top_indices)  # Preserve order
    
    return ". ".join([sentences[i] for i in top_indices])

Sliding Window

Conversation History Management

python
class SlidingWindowMemory:
    def __init__(self, max_tokens: int = 4000):
        self.max_tokens = max_tokens
        self.messages = []
    
    def add_message(self, role: str, content: str):
        self.messages.append({"role": role, "content": content})
        self._trim()
    
    def _trim(self):
        while self._total_tokens() > self.max_tokens and len(self.messages) > 2:
            # Preserve System message, delete oldest user/assistant
            if self.messages[0]["role"] == "system":
                self.messages.pop(1)
            else:
                self.messages.pop(0)
    
    def _total_tokens(self) -> int:
        return sum(count_tokens(m["content"]) for m in self.messages)
    
    def get_messages(self) -> list:
        return self.messages.copy()

Document Processing Window

python
def process_long_document(document: str, query: str, window_size: int = 8000):
    chunks = semantic_chunk(document, chunk_size=window_size)
    results = []
    
    for i, chunk in enumerate(chunks):
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {
                    "role": "system",
                    "content": "Analyze the given text chunk."
                },
                {
                    "role": "user",
                    "content": f"Text:\n{chunk}\n\nQuestion: {query}"
                }
            ]
        )
        
        results.append({
            "chunk_index": i,
            "response": response.choices[0].message.content
        })
    
    # Combine results
    return synthesize_results(results, query)

Map-Reduce Pattern

Long Document QA

python
def map_reduce_qa(document: str, question: str):
    chunks = semantic_chunk(document, chunk_size=4000)
    
    # Map: Analyze each chunk separately
    partial_answers = []
    for chunk in chunks:
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {
                    "role": "user",
                    "content": f"Text:\n{chunk}\n\nQuestion: {question}\n\n"
                              "Answer based on this text chunk. "
                              "If no information, say 'No information in this chunk'."
                }
            ]
        )
        partial_answers.append(response.choices[0].message.content)
    
    # Reduce: Combine answers
    combined = "\n\n".join([
        f"Source {i+1}: {ans}" 
        for i, ans in enumerate(partial_answers)
    ])
    
    final_response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {
                "role": "user",
                "content": f"Information from different sources:\n{combined}\n\n"
                          f"Question: {question}\n\n"
                          "Provide a comprehensive answer by synthesizing all information."
            }
        ]
    )
    
    return final_response.choices[0].message.content

Retrieval Augmented Context

Smart Context Selection

python
def select_relevant_context(query: str, documents: list, max_tokens: int = 4000):
    # Embedding-based relevance
    query_embedding = get_embedding(query)
    
    scored_docs = []
    for doc in documents:
        doc_embedding = get_embedding(doc["content"])
        score = cosine_similarity(query_embedding, doc_embedding)
        scored_docs.append({"doc": doc, "score": score})
    
    # Sort by relevance
    scored_docs.sort(key=lambda x: x["score"], reverse=True)
    
    # Add until Token limit
    selected = []
    current_tokens = 0
    
    for item in scored_docs:
        doc_tokens = count_tokens(item["doc"]["content"])
        if current_tokens + doc_tokens <= max_tokens:
            selected.append(item["doc"])
            current_tokens += doc_tokens
        else:
            break
    
    return selected

Long Context Best Practices

1. Prompt Positioning

python
def optimize_prompt_position(context: str, query: str) -> str:
    """Put important information at start and end (Lost in the Middle)"""
    
    chunks = semantic_chunk(context)
    
    # Preserve first and last chunks
    if len(chunks) > 2:
        middle = chunks[1:-1]
        compressed_middle = compress_context(" ".join(middle))
        context = f"{chunks[0]}\n\n{compressed_middle}\n\n{chunks[-1]}"
    
    return f"Context:\n{context}\n\n---\n\nQuestion: {query}"

2. Hierarchical Processing

python
def hierarchical_summarize(document: str, levels: int = 2):
    """Hierarchical summarization"""
    
    current_text = document
    
    for level in range(levels):
        chunks = semantic_chunk(current_text, chunk_size=4000)
        
        summaries = []
        for chunk in chunks:
            summary = compress_context(chunk, max_tokens=500)
            summaries.append(summary)
        
        current_text = "\n\n".join(summaries)
    
    return current_text

3. Anchoring Key Instructions

python
def add_attention_anchors(prompt: str) -> str:
    """Add attention anchors"""
    
    return f"""
[IMPORTANT START]
{prompt[:500]}
[/IMPORTANT]

{prompt[500:-500]}

[IMPORTANT END]
{prompt[-500:]}
[/IMPORTANT]
"""

Monitoring and Debugging

python
class ContextMonitor:
    def __init__(self):
        self.logs = []
    
    def log_request(self, messages: list, model: str):
        total_tokens = sum(count_tokens(m["content"]) for m in messages)
        
        self.logs.append({
            "timestamp": datetime.now(),
            "model": model,
            "input_tokens": total_tokens,
            "message_count": len(messages)
        })
        
        # Alerts
        if total_tokens > 100000:
            print(f"⚠️ High token count: {total_tokens}")
    
    def get_stats(self):
        return {
            "avg_tokens": np.mean([l["input_tokens"] for l in self.logs]),
            "max_tokens": max(l["input_tokens"] for l in self.logs),
            "total_requests": len(self.logs)
        }

Conclusion

A bigger context window is not a strategy on its own. Send the model what it needs: relevant chunks instead of whole archives, summaries instead of full histories, and key instructions where they will not get lost. Your applications will be faster, cheaper and more accurate.

Veni AI builds applications that work with long contracts, reports and document archives, combining retrieval, summarization and careful context design. See our services or talk to us about your documents.

Keep reading

Have a process that should run on AI?

Describe one process as it runs today, and we'll show you which repetitive steps an AI application or agent could handle.