公開日

コンテキストウィンドウの管理:長文書と長い会話のための戦略

100万トークンのコンテキストでも、時間とコストはかかります。長い文書やチャット履歴に使える、チャンク分割、圧縮、スライディングウィンドウ、マップリデュースの各戦略を解説します。

執筆者
Ali ÖzdurmuşVeni AI 創業者
更新日
読了時間
読了時間 約5分

コンテキストウィンドウとは、モデルが1回のリクエストで読み取れるトークンの最大数です。現在の最先端モデルは100万トークン前後を受け付けますが、そのウィンドウを埋めると処理は遅く、費用がかさみ、精度も常に保てるとは限りません。非常に長い入力では、途中に埋もれた細部をモデルが見落とすことがあるためです。コンテキストを適切に管理することは、品質とコストを左右する最大のレバーの1つであり続けています。

コードサンプルは説明用のPythonです。clientは初期化済みのSDKクライアント、MODELは選択したモデルIDのプレースホルダーです。

コンテキストウィンドウの上限

モデル比較

当社のモデルカタログ(2026年10月)に基づく入力上限です。出力上限ははるかに小さいため、両方をプロバイダーのドキュメントで確認してください。

モデルコンテキスト長
GPT-6 Astra, GPT-6.1 Sol1.05M
Claude Opus 5.5, Sonnet 5.5, Haiku 5.51M
Gemini 4 Argon1M
DeepSeek V4 Pro(オープンウェイト)1M
Grok 4.7500K

おおよその目安として、100万トークンは英単語で約75万語に相当します。

トークンの計算

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

トークンとトルコ語テキスト

モデルは、BPEやSentencePieceなどの手法でテキストをサブワードのトークンに分割します。トークナイザーは主に英語で学習されており、トルコ語は膠着語(1つの単語に複数の接尾辞が付く)であるため、同じ内容でもトルコ語のほうが英語より多くのトークンを要することがよくあります。コンテキストの使用量とコストを見積もるときは、自社の文書でトークン数を実測してください。

チャンク分割の戦略

固定サイズのチャンク分割

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

セマンティックチャンク分割

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)

文書構造を考慮した分割

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

コンテキストの圧縮

要約

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

抽出型の圧縮

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])

スライディングウィンドウ

会話履歴の管理

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()

文書処理ウィンドウ

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)

マップリデュースパターン

長文書の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

検索拡張コンテキスト

コンテキストのスマートな選択

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

ロングコンテキストのベストプラクティス

1. プロンプト内での配置

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. 階層的な処理

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. 重要な指示のアンカー化

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]
"""

モニタリングとデバッグ

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)
        }

まとめ

コンテキストウィンドウが大きいことは、それだけでは戦略になりません。モデルには必要なものだけを渡します。アーカイブ全体ではなく関連するチャンク、履歴全体ではなく要約、そして重要な指示は埋もれない位置に置きます。そうすれば、アプリケーションはより速く、より安く、より正確になります。

Veni AIは、検索、要約、慎重なコンテキスト設計を組み合わせて、長い契約書、レポート、文書アーカイブを扱うアプリケーションを構築しています。サービスを見る、またはお手元の文書についてご相談ください。

続けて読む

AIで動かしたい業務はありますか?

現在の動き方のまま、1つの業務プロセスをご説明ください。AIアプリケーションやエージェントが担える繰り返しのステップをお示しします。