Modern LLMs boast context windows of 128K–200K tokens, but enterprise RAG applications still routinely hit context limits when integrating with external APIs like Salesforce. Naive truncation (e.g., string slicing, dropping trailing records) destroys relational context, breaks retrieval quality, and introduces hallucination risks.
This article presents a production-grade, LangGraph-orchestrated pattern for adaptive payload truncation, combining semantic filtering, dynamic chunking, contextual compression, and fallback routing. We’ll walk through a real-time enterprise use case: a Sales Intelligence Assistant that queries Salesforce Accounts, Opportunities, and Case histories while guaranteeing context window compliance, auditability, and RAG fidelity.
The Context Window Trap in Enterprise RAG
External APIs return unpredictable, deeply nested payloads:
Salesforce SOQL queries can return thousands of records with related objects (
Opportunity → Cases → Activities → Attachments)A single API response can easily exceed 50K–150K tokens after JSON serialization
LLM context budgets must be split across: system prompt, user query, retrieved chunks, tool outputs, and output generation
Blind truncation loses critical business context (e.g., dropping a pricing objection case because it appeared late in the payload)
Enterprise Requirement: Truncation must be semantic, bounded, auditable, and retry-aware.
Real-World Use Case: Enterprise Sales Intelligence Assistant
Query: "Summarize the top risks for ACME Corp's Q3 renewal opportunity and pull recent case notes mentioning pricing objections or SLA breaches."
Expected Salesforce Payload:
1 Account record (50 fields)
12 Opportunity records with line items
84 Case records with comments & activity history
Custom object metadata (
Contract__c,Pricing_History__c)

Problem: Raw JSON payload ≈ 110K tokens. LLM context budget for tools: 60K tokens. Naive truncation drops 70% of cases, losing the exact pricing objections the query targets.
Solution: LangGraph orchestrates an adaptive truncation pipeline that:
Prunes non-essential fields
Filters records by semantic relevance to the query
Chunks payloads into budget-aligned segments
Routes chunks through a RAG retriever for contextual compression
Falls back to lightweight summarization if budget is still exceeded
Architecture: LangGraph State Machine for Adaptive Payload Handling

LangGraph’s state machine enables:
Deterministic budget tracking across nodes
Conditional routing for fallback strategies
Parallel chunk processing via
SendFull audit trails for compliance
Step-by-Step Implementation
1. State Definition
from langgraph.graph import StateGraph, START, END
from typing import TypedDict, List, Dict, Any, Optional
import tiktoken
class SalesAgentState(TypedDict):
query: str
sf_account_id: str
raw_payload: List[Dict[str, Any]]
token_budget: int
processed_chunks: List[List[Dict[str, Any]]]
compressed_context: List[str]
response: str
truncation_metadata: Dict[str, Any]
retry_count: int
error: Optional[str]2. Salesforce Data Fetcher (Paginated)
from simple_salesforce import Salesforce
import os
def fetch_salesforce_data(state: SalesAgentState) -> SalesAgentState:
sf = Salesforce(username=os.getenv("SF_USER"),
password=os.getenv("SF_PASS"),
security_token=os.getenv("SF_TOKEN"),
domain="login")
# SOQL with related objects & pagination
soql = f"""
SELECT Id, Name, StageName, Amount, CloseDate, Description,
(SELECT Id, Subject, Description, Status FROM Cases),
(SELECT Id, ActivityDate, Description FROM ActivityHistories)
FROM Opportunity
WHERE AccountId = '{state['sf_account_id']}'
ORDER BY CloseDate DESC
"""
records = sf.query_all(soql)['records']
# Remove SF metadata
clean = [{k: v for k, v in r.items() if not k.startswith("attributes")} for r in records]
state["raw_payload"] = clean
return state3. Adaptive Truncation & Semantic Chunking
This node enforces token budgets while preserving semantic relevance.
import json
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
def adaptive_truncate(state: SalesAgentState) -> SalesAgentState:
enc = tiktoken.get_encoding("cl100k_base")
budget = state["token_budget"]
raw = state["raw_payload"]
# 1. Field Pruning: Keep only query-relevant fields
essential_fields = {"Id", "Name", "StageName", "Amount", "CloseDate", "Description", "Cases", "ActivityHistories"}
filtered = [{k: v for k, v in r.items() if k in essential_fields} for r in raw]
# 2. Token Estimation & Chunking
chunks = []
current_chunk = []
current_tokens = 0
for rec in filtered:
rec_str = json.dumps(rec, default=str)
rec_tokens = len(enc.encode(rec_str))
if current_tokens + rec_tokens > budget * 0.8: # 80% buffer for system/retrieval overhead
chunks.append(current_chunk)
current_chunk = [rec]
current_tokens = rec_tokens
else:
current_chunk.append(rec)
current_tokens += rec_tokens
if current_chunk:
chunks.append(current_chunk)
state["processed_chunks"] = chunks
state["truncation_metadata"] = {
"total_records": len(raw),
"kept_records": sum(len(c) for c in chunks),
"chunks_generated": len(chunks),
"estimated_tokens": current_tokens
}
return state
Join the conversation! Your thoughts help the community grow.