Long-Context LLM Implementation Guide: Token Budgeting, Approach Selection, and Contract Field Extraction

    A practical guide to deploying long-context LLMs: how to measure tokens and compute input budgets, how to choose among direct long-context reading, RAG, and chunked summarization, and how to build a contract field extraction pipeline with clause-based chunking, retry logic, data masking, evaluation metrics, and production monitoring.

    Long-Context LLM Implementation Guide: Token Budgeting, Approach Selection, and Contract Field Extraction

    1. Measure Tokens First, Then Compute the Window Budget

    Context length is measured in tokens, and there is no fixed conversion ratio between tokens and Chinese characters. Different models use different tokenizers, so the same Chinese text can produce very different token counts across models. Do not rely on rules of thumb. Use the target model’s own tokenizer or its official token-counting API, and measure on your real samples.

    The context window must hold the prompt, the input document, and the model output. The input budget is:

    Available input tokens = window limit − reserved output tokens − safety margin

    The safety margin absorbs counting errors and minor prompt variations. Start with 5% of the window limit and adjust based on measured deviation. The output reservation should be estimated per task. JSON output for contract extraction is usually much shorter than the source text, but it should still be sized for the maximum number of records, not the average.

    The following code checks whether a single document fits in the window. count_tokens is provided by the caller and should call the target model’s counting method internally.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Budget:
    4. window: int # Model context window limit, in tokens
    5. reserved_output: int # Tokens reserved for model output
    6. safety_ratio: float = 0.05
    7. def max_input(self) -> int:
    8. margin = int(self.window * self.safety_ratio)
    9. return self.window - self.reserved_output - margin
    10. def fits_window(doc_text: str, prompt_text: str, count_tokens, budget: Budget) -> bool:
    11. used = count_tokens(doc_text) + count_tokens(prompt_text)
    12. return used <= budget.max_input()

    A “million-token” figure in marketing material only states the window limit. A document fitting in the window does not guarantee stable reasoning quality over long inputs. Whether to adopt the approach depends on test results on your own samples.

    2. Trade-offs Among Three Approaches

    There are three common routes for handling very long documents: direct long-context reading, RAG retrieval, and chunked summarization with aggregation. They differ in cost and risk structure.

    Approach How it works When to use Cost and latency Main risk
    Direct long-context reading Feed the entire document at once Total volume fits the window; cross-section judgment needed High cost per call; latency grows with input length Information in the middle of long inputs is easily overlooked
    RAG retrieval Chunk and index, retrieve before generating Large document base; specific questions Small input per call; fast retrieval Missed recall leads to missing answers
    Chunked summarization + aggregation Summarize segment by segment, then aggregate Full coverage of all documents needed, e.g., overview reports Many calls, but parallelizable Summaries lose detail; cross-segment contradictions are hard to spot

    Selection Checklist

    Answer these three questions in order.

    1. Does the total document volume fit within the available input budget? If not, go to step 3. If yes, go to step 2.
    2. Does the question require global judgment, such as comparing responsibility allocation across chapters? If yes, choose direct reading. If not, both direct reading and retrieval work; compare per-call cost before deciding.
    3. Is the question a local lookup, such as the price in a specific contract? If yes, use RAG retrieval. If not—meaning every document must be covered—use chunked summarization with aggregation.

    Real projects often combine approaches. Use retrieval to narrow down to relevant chapters, then read the entire matched chapter directly. For massive document sets, build a directory via chunked summarization first, then run retrieval for specific questions.

    The Lost-in-the-Middle Risk

    In the 2023 paper “Lost in the Middle,” Liu et al. found that when key information sits in the middle of a long input, model accuracy in using that information drops noticeably; content at the beginning and end is used more effectively. Therefore, when reading long documents directly, do not assume the model attends uniformly to the full text. Common countermeasures fall into three categories:

    • Front-load key clauses: place the most relevant content near the start of the prompt and repeat the question at the end.
    • Chunked summarization: extract key points segment by segment first, then hand the points to the model for aggregation, reducing interference from long inputs.
    • Retrieve then read: retrieve relevant fragments first, then read only the matched portions, shortening the effective input length.

    Common Pitfalls

    • Choosing direct reading based only on the advertised window limit.
    • Failing to reserve output space, causing request errors or truncated output.
    • Hard-splitting by fixed character counts, breaking a complete provision across two chunks.
    • Launching RAG without monitoring recall, so missed recall goes unnoticed.
    • Not checking the tail content after truncation—the critical clause may be exactly what was cut.

    3. Contract Field Extraction: Code and Pipeline

    Consider a contract compilation of about 80,000 characters. The goal is to extract, for each contract, the parties, subject matter, price, breach clause numbers, and dispute resolution method, outputting structured JSON. Missing fields are filled with null; the model must not guess.

    3.1 Split by Clause

    Split preferentially by “Article X” headings. Adjacent chunks carry the previous clause as context to reduce information loss at boundaries. A single clause exceeding the limit is kept whole—no hard splitting.

    1. import re
    2. CLAUSE_PATTERN = re.compile(r"^第[一二三四五六七八九十百千0-9]+条", re.MULTILINE)
    3. def split_by_clause(text: str, max_chars: int = 3000) -> list[str]:
    4. starts = [m.start() for m in CLAUSE_PATTERN.finditer(text)] or [0]
    5. starts.append(len(text))
    6. pieces = [text[starts[i]:starts[i + 1]] for i in range(len(starts) - 1)]
    7. chunks, buf, last = [], "", ""
    8. for piece in pieces:
    9. if buf and len(buf) + len(piece) > max_chars:
    10. chunks.append(buf)
    11. buf = last # Carry over the previous clause as boundary context
    12. buf += piece
    13. last = piece
    14. if buf:
    15. chunks.append(buf)
    16. return chunks

    Because context is carried over, the same clause may appear in two chunks. Deduplicate by clause number when merging results.

    3.2 Timeout Retry and Parse Validation

    The call function must accept a timeout parameter. In practice, replace TimeoutError with the retryable exception type in the SDK you use. Retry only errors that are safe to repeat. JSON parse failures should be handled separately rather than blindly resending the same request.

    1. import json
    2. import random
    3. import time
    4. FIELDS = ["parties", "subject_matter", "price", "breach_clause_numbers", "dispute_resolution"]
    5. def call_with_retry(call, prompt: str, max_retries: int = 3, timeout_s: float = 60.0) -> str:
    6. for attempt in range(max_retries + 1):
    7. try:
    8. return call(prompt, timeout=timeout_s)
    9. except TimeoutError:
    10. if attempt == max_retries:
    11. raise
    12. # Exponential backoff with jitter to avoid synchronized retries in bulk jobs
    13. time.sleep(2 ** attempt + random.uniform(0, 0.5))
    14. def parse_record(raw: str) -> dict | None:
    15. try:
    16. data = json.loads(raw)
    17. except json.JSONDecodeError:
    18. return None
    19. if not isinstance(data, dict) or any(f not in data for f in FIELDS):
    20. return None
    21. return data

    3.3 Data Masking

    Masking happens before text is sent to the model. Regular expressions only cover identifiers with fixed formats; personal names, addresses, and internal company IDs need separate rules or manual handling.

    1. import re
    2. MASKS = [
    3. ("ID_CARD", re.compile(r"(?<!\d)\d{17}[\dXx](?!\d)")),
    4. ("PHONE", re.compile(r"(?<!\d)1[3-9]\d{9}(?!\d)")),
    5. ("BANK_CARD", re.compile(r"(?<!\d)\d{16,19}(?!\d)")),
    6. ("EMAIL", re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")),
    7. ]
    8. def mask(text: str) -> str:
    9. for label, pattern in MASKS:
    10. text = pattern.sub(f"<{label}>", text)
    11. return text

    The ID card rule is placed before the bank card rule so that an 18-digit ID number is not misclassified as a bank card number.

    3.4 Main Extraction Pipeline

    The main pipeline masks first, then calls the model. On parse failure, retry at most once. Chunks that still fail are logged for manual handling.

    1. def build_prompt(text: str) -> str:
    2. return (
    3. "Extract fields from the contract clauses below based only on the original text, "
    4. "and output JSON. Fields: " + ", ".join(FIELDS) + ". "
    5. "Fill null for any field not found in the text; do not guess. "
    6. "For breach_clause_numbers, list the clause numbers as they appear in the text.\n\n"
    7. + text
    8. )
    9. def extract(chunks: list[str], call) -> list[dict]:
    10. records = []
    11. for chunk in chunks:
    12. prompt = build_prompt(mask(chunk))
    13. for _ in range(2): # Retry at most once on parse failure
    14. raw = call_with_retry(call, prompt)
    15. record = parse_record(raw)
    16. if record is not None:
    17. records.append(record)
    18. break
    19. else:
    20. records.append({"_error": "parse_failed", "chunk_head": chunk[:50]})
    21. return records

    4. Evaluation Metrics, Sample Size, and Regression Set

    Metric Definitions

    All four metrics below are computed on manually annotated samples.

    1. Field extraction accuracy = fields matching the annotation / total annotated fields. Trim leading and trailing whitespace before comparison; compare lists after sorting.
    2. Citation traceability rate = citations whose clause numbers can be found in the unmasked source / total citations in the output. Source verification must use the pre-masking text.
    3. Truncation rate = documents truncated due to window overflow or output cutoff / total documents submitted. The denominator must include all submitted documents, not just successful ones.
    4. Failure boundary coverage = number of failure types included in the regression set. Failure types include OCR errors in scanned files, tables broken across pages, and identically named clauses across multiple files.
    1. def norm(value):
    2. if value is None:
    3. return None
    4. if isinstance(value, list):
    5. return sorted(str(v).strip() for v in value)
    6. return str(value).strip()
    7. def field_accuracy(preds: list[dict], golds: list[dict]) -> float:
    8. total = correct = 0
    9. for pred, gold in zip(preds, golds):
    10. for field in FIELDS:
    11. total += 1
    12. correct += norm(pred.get(field)) == norm(gold.get(field))
    13. return correct / total if total else 0.0
    14. def traceable_rate(pairs: list[tuple[dict, str]]) -> float:
    15. # Each item in pairs is (extraction result, unmasked source text)
    16. total = ok = 0
    17. for pred, source in pairs:
    18. for clause_no in pred.get("breach_clause_numbers") or []:
    19. total += 1
    20. ok += str(clause_no) in source
    21. return ok / total if total else 1.0
    22. def truncation_rate(total_docs: int, truncated_docs: int) -> float:
    23. return truncated_docs / total_docs if total_docs else 0.0

    Sample Size

    Sample size determines the confidence range of results. For a proportion metric at 95% confidence, the margin of error is approximately:

    n = z² × p(1 − p) / e²

    With z = 1.96, p = 0.5 (the most conservative value), and e = 0.05, n ≈ 385. With only 100 annotated contracts, the margin of error is about ±9.8%. One hundred samples are fine for initial screening, but not for drawing external conclusions. Key metrics should be validated on progressively larger samples.

    Thresholds and Regression Set

    Thresholds are set by the team based on business risk and fixed after the pilot phase. The citation traceability rate should be close to 100%. Any untraceable clause number must go to manual review.

    Maintain the regression set as follows:

    • Record annotation date, annotator, model version, and prompt version for each version.
    • Every failure observed in production is added to the regression set.
    • After changing the model, prompt, or chunking parameters, rerun the regression set and compare against the previous baseline.
    • When annotations are revised, keep the historical version rather than overwriting the old labels.

    5. Production Monitoring

    After launch, record at least the following: per-call latency, retry counts, JSON parse failure rate, truncation rate, and the finish reason returned by the model. A sudden rise in parse failure rate usually means a model version or prompt change—roll back first, then investigate.

    Sample a fixed portion of outputs daily and compare them against manual results. Sampling results must be written into the evaluation record, not left in chat threads or verbal communication.

    6. Risk and Compliance Boundaries

    • The output is only auxiliary material organization and does not constitute legal advice. Key conclusions must be reviewed by a qualified lawyer.
    • Mask data before sending text to the model. Masking rules cannot guarantee removal of all personal information; names, addresses, and similar data need additional rules or manual review.
    • Before sending, confirm the model service’s data retention and training policies, and check them against contract confidentiality clauses and internal policies.
    • Audit logs record call time, model version, prompt version, input document hash, and output validation results. Unless policy permits, do not store contract plaintext in logs.
    • Assign access permissions on a least-privilege basis. Keep API keys in environment variables or a key management service—never in code or logs.