Introduction
Long documents are the silent killer of RAG performance. A 200-page M&A agreement, a 500-page technical manual, or a 1,000-page regulatory filing cannot be processed with naive chunking—semantic units span multiple chunks, cross-references connect distant sections, and critical context gets fragmented across retrieval boundaries. Meanwhile, simply stuffing the entire document into a long-context LLM window (Gemini 1M, Claude 200K) is expensive, slow, and often produces worse results due to "lost-in-the-middle" attention degradation.
The enterprise answer is adaptive strategy selection: different documents and different queries demand different approaches. A factual lookup in a 500-page manual needs precise chunked retrieval. A thematic question about a 200-page contract needs hierarchical summarization. A cross-reference query needs multi-section assembly. This article presents an enterprise-grade multi-agent LangGraph system that profiles each document, selects the optimal long-context strategy, executes it with persistent memory of past decisions, and delivers answers that respect document structure.
Why Naive Approaches Fail
Approach | Failure Mode |
|---|---|
Fixed-size chunking | Splits semantic units mid-sentence; loses cross-section references |
Large chunks (2000+ tokens) | Retrieval becomes imprecise; irrelevant content drowns signal |
Stuff entire document | Expensive ($0.10+ per query); lost-in-the-middle effect; slow |
Single-level summarization | Loses detail; cannot answer specific factual questions |
Pure vector search | Misses structural hierarchy (chapters → sections → clauses) |
Five Core Strategies for Long-Context Handling
1. Hierarchical Summarization (Map-Reduce): Summarize chunks → summarize summaries → answer from global summary. Best for thematic, high-level questions.
2. Parent-Child (Small-to-Big): Retrieve small precise chunks but return their larger parent context. Best for factual QA over long docs.
3. Recursive Section-Aware Chunking: Respect document hierarchy (chapter → section → subsection). Best for structured technical docs.
4. Native Long-Context Stuffing: Pass entire document to 128K+ context model. Best for short docs (<50 pages) or when cost is not a constraint.
5. Iterative Cross-Section Assembly: Identify relevant sections, retrieve each, assemble coherent context. Best for cross-reference queries.
The Adaptive Answer
The key insight: no single strategy dominates. The optimal choice depends on:
- Document length (pages, tokens)
- Document structure (headings, sections, hierarchy depth)
- Query type (factual, thematic, cross-reference, comparative)
- Latency and cost constraints
Step-by-Step Implementation
1. Long-Context State Schema with Memory
from typing import List, Dict, Any, TypedDict, Optional, Literal
from langgraph.graph import StateGraph, END
from langchain_core.messages import HumanMessage
import redis
import json
from datetime import datetime
LongContextStrategy = Literal[
"hierarchical_summary", "parent_child", "section_aware",
"native_long_context", "cross_section_assembly"
]
class DocumentSection(TypedDict):
id: str
title: str
level: int # 1=chapter, 2=section, 3=subsection
content: str
parent_id: Optional[str]
children_ids: List[str]
summary: Optional[str]
class LongContextState(TypedDict):
messages: List
conversation_id: str
document_id: str
# Document profile
document_text: str
token_count: int
page_count: int
section_count: int
hierarchy_depth: int
has_structure: bool
sections: List[DocumentSection]
# Query analysis
query: str
query_type: Literal["factual", "thematic", "cross_reference", "comparative"]
relevant_section_ids: List[str]
# Strategy selection
selected_strategy: LongContextStrategy
strategy_reasoning: str
# Execution results
assembled_context: str
final_answer: str
citations: List[Dict]
# Metrics
context_tokens_used: int
estimated_cost_usd: float
latency_ms: float
# Memory
past_strategies: List[Dict]
document_type_history: Dict[str, List[str]]
2. Document Profiler Agent
from langchain_openai import ChatOpenAI
import re
class DocumentProfilerAgent:
"""Analyzes document structure, length, and hierarchy"""
def __init__(self):
self.llm = ChatOpenAI(model="gpt-4", temperature=0.0)
def profile(self, state: LongContextState) -> LongContextState:
text = state["document_text"]
# Basic metrics
state["token_count"] = int(len(text.split()) * 1.3)
state["page_count"] = max(1, state["token_count"] // 500)
# Detect structure via headings
heading_pattern = r'^(#{1,6}\s.+|Chapter\s+\d+[:\.]?\s*.+|Section\s+\d+[:\.]?\s*.+|Article\s+\d+[:\.]?\s*.+|[A-Z][^.!?\n]{3,80}\n)$'
headings = re.findall(heading_pattern, text, re.MULTILINE)
state["section_count"] = len(headings)
state["has_structure"] = len(headings) >= 3
# Parse sections hierarchically
sections = []
current_section = None
lines = text.split('\n')
for i, line in enumerate(lines):
heading_match = re.match(r'^(#{1,6})\s+(.+)', line)
if heading_match:
level = len(heading_match.group(1))
if current_section:
sections.append(current_section)
current_section = {
"id": f"sec_{len(sections)}",
"title": heading_match.group(2).strip(),
"level": level,
"content": "",
"parent_id": None,
"children_ids": [],
"summary": None
}
elif current_section:
current_section["content"] += line + "\n"
if current_section:
sections.append(current_section)
# Build parent-child relationships
section_stack = []
for sec in sections:
while section_stack and section_stack[-1]["level"] >= sec["level"]:
section_stack.pop()
if section_stack:
sec["parent_id"] = section_stack[-1]["id"]
section_stack[-1]["children_ids"].append(sec["id"])
section_stack.append(sec)
state["sections"] = sections
state["hierarchy_depth"] = max((s["level"] for s in sections), default=0)
return state
3. Strategy Router Agent
class StrategyRouterAgent:
"""Selects optimal long-context strategy based on document + query profile"""
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
self.llm = ChatOpenAI(model="gpt-4", temperature=0.0)
def _classify_query(self, query: str) -> str:
prompt = f"""Classify this query type for long-document retrieval:
Query: "{query}"
Types:
- factual: specific fact, number, name, date lookup
- thematic: high-level theme, summary, overall understanding
- cross_reference: connects multiple sections, compares parts
- comparative: compares entities or concepts across document
Respond with ONE word: factual|thematic|cross_reference|comparative"""
resp = self.llm.invoke(prompt)
return resp.content.strip().lower()
def _identify_relevant_sections(self, state: LongContextState) -> List[str]:
"""Use LLM to identify which sections likely contain the answer"""
section_summaries = "\n".join([
f"[{s['id']}] (L{s['level']}) {s['title']}: {s['content'][:150]}..."
for s in state["sections"][:30]
])
prompt = f"""Given this document structure, which section IDs are most relevant to answering the query?
Query: "{state['query']}"
Sections:
{section_summaries}
Respond with comma-separated section IDs (max 5):"""
resp = self.llm.invoke(prompt)
ids = [s.strip() for s in resp.content.split(",") if s.strip().startswith("sec_")]
return ids[:5]
def route(self, state: LongContextState) -> LongContextState:
state["query_type"] = self._classify_query(state["query"])
state["relevant_section_ids"] = self._identify_relevant_sections(state)
# Decision logic
token_count = state["token_count"]
has_structure = state["has_structure"]
query_type = state["query_type"]
relevant_count = len(state["relevant_section_ids"])
# Check historical preferences for this document type
history_key = f"long_context_history:{state['document_id']}"
history = json.loads(self.redis.get(history_key) or "[]")
# Strategy selection
if token_count < 30000:
# Short enough for native long-context
state["selected_strategy"] = "native_long_context"
state["strategy_reasoning"] = "Document fits within native context window; direct processing is most accurate"
elif query_type == "thematic":
state["selected_strategy"] = "hierarchical_summary"
state["strategy_reasoning"] = "Thematic query benefits from hierarchical summarization to capture global themes"
elif query_type in ("cross_reference", "comparative") and relevant_count > 1:
state["selected_strategy"] = "cross_section_assembly"
state["strategy_reasoning"] = f"Query spans {relevant_count} sections; assembling cross-section context is optimal"
elif has_structure and state["hierarchy_depth"] >= 2:
state["selected_strategy"] = "section_aware"
state["strategy_reasoning"] = "Document has clear hierarchy; section-aware retrieval preserves structure"
else:
state["selected_strategy"] = "parent_child"
state["strategy_reasoning"] = "Parent-child retrieval balances precision with context richness"
# Record in memory
history.append({
"query_type": query_type,
"strategy": state["selected_strategy"],
"timestamp": datetime.now().isoformat()
})
self.redis.set(history_key, json.dumps(history[-20:]))
state["past_strategies"] = history
return state
4. Hierarchical Summarizer Agent
class HierarchicalSummarizerAgent:
"""Map-reduce summarization for thematic queries"""
def __init__(self):
self.llm = ChatOpenAI(model="gpt-4", temperature=0.1)
def summarize(self, state: LongContextState) -> LongContextState:
sections = state["sections"]
# Map phase: summarize each section
section_summaries = []
for sec in sections[:20]: # Limit for cost
prompt = f"""Summarize this section in 2-3 sentences, preserving key facts:
Title: {sec['title']}
Content: {sec['content'][:1500]}
Summary:"""
resp = self.llm.invoke(prompt)
summary = resp.content.strip()
sec["summary"] = summary
section_summaries.append(f"[{sec['title']}]: {summary}")
# Reduce phase: synthesize global summary relevant to query
combined = "\n".join(section_summaries)
prompt = f"""Given these section summaries, answer the query comprehensively.
Query: {state['query']}
Section Summaries:
{combined}
Provide a detailed answer citing relevant sections:"""
resp = self.llm.invoke(prompt)
state["assembled_context"] = combined
state["final_answer"] = resp.content
state["context_tokens_used"] = int(len(combined.split()) * 1.3)
state["citations"] = [{"section": s["title"], "id": s["id"]} for s in sections[:10]]
return state
5. Parent-Child Retriever Agent
from langchain_huggingface import HuggingFaceEmbeddings
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
class ParentChildRetrieverAgent:
"""Retrieves small chunks but returns parent context"""
def __init__(self):
self.embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
def retrieve(self, state: LongContextState) -> LongContextState:
# Build child chunks (paragraphs) with parent references
children = []
for sec in state["sections"]:
paragraphs = [p.strip() for p in sec["content"].split("\n\n") if len(p.strip()) > 50]
for para in paragraphs:
children.append({
"content": para,
"parent_section_id": sec["id"],
"parent_title": sec["title"]
})
if not children:
state["final_answer"] = "No content available for retrieval."
return state
# Embed children
child_texts = [c["content"] for c in children]
child_embeddings = np.array(self.embeddings.embed_documents(child_texts))
query_embedding = np.array(self.embeddings.embed_query(state["query"]))
# Retrieve top children
similarities = cosine_similarity(query_embedding.reshape(1, -1), child_embeddings)[0]
top_indices = np.argsort(similarities)[::-1][:8]
# Expand to parents
parent_ids = set()
retrieved_parents = []
for idx in top_indices:
parent_id = children[idx]["parent_section_id"]
if parent_id not in parent_ids:
parent_ids.add(parent_id)
parent_sec = next((s for s in state["sections"] if s["id"] == parent_id), None)
if parent_sec:
retrieved_parents.append(parent_sec)
# Assemble context from parents
context_parts = []
for p in retrieved_parents[:5]:
context_parts.append(f"## {p['title']}\n{p['content'][:1500]}")
assembled = "\n\n---\n\n".join(context_parts)
state["assembled_context"] = assembled
state["context_tokens_used"] = int(len(assembled.split()) * 1.3)
state["citations"] = [{"section": p["title"], "id": p["id"]} for p in retrieved_parents[:5]]
return state

Join the conversation! Your thoughts help the community grow.