Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
AI & Machine Learning

Implementing Long-Context Reranking with Sliding Window Attention: Scoring Retrieved Chunks Against Full Query Context for Precision-Critical RAG Applications

Standard embedding retrieval and cross-encoder reranking fail when queries contain negations, exclusions, and conditional logic. This lesson teaches you to build a production-grade long-context reranking pipeline that scores each retrieved chunk against the complete query context using LLM-based scoring rubrics — with async parallel execution, cost optimization, and graceful error handling.

⚡ Practitioner29 min readNov 26, 2026Updated Nov 26, 2026
Implementing Long-Context Reranking with Sliding Window Attention: Scoring Retrieved Chunks Against Full Query Context for Precision-Critical RAG Applications
On this page
  • Introduction
  • Prerequisites
  • Why Standard Reranking Falls Short for Complex Queries
  • The Architecture: Sliding Window Scoring
  • Building the Scoring Rubric
  • The Async Scoring Engine
  • Composing the Full Query Context
  • Integrating with an Existing RAG Pipeline
  • Cost and Latency Optimization
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • When to Use This Pattern (and When Not To)
  • Summary & Next Steps

Implementing Long-Context Reranking with Sliding Window Attention: Scoring Retrieved Chunks Against Full Query Context for Precision-Critical RAG Applications

Introduction

Imagine you're building a RAG system for a legal research firm. A paralegal asks: "What are the indemnification obligations for the acquiring party in the event of a material breach that occurred prior to closing, excluding breaches that were disclosed in Schedule 3.4?" That's not a simple semantic lookup — it's a multi-clause query with explicit carve-outs, referencing a specific exhibit, and requiring precise understanding of temporal sequence. Your vector search retrieves 20 candidate chunks from a 400-page acquisition agreement. Some are genuinely relevant; many are plausible-sounding distractors about indemnification in different contexts. If you send the wrong chunks to your generation model, the answer will be confidently, catastrophically wrong.

This is exactly where standard RAG pipelines break down. Embedding-based retrieval scores each chunk independently against a compressed query representation. It's fast and scales well, but it fundamentally cannot reason about query complexity, negations, qualifiers, or contextual dependencies between clauses. Reranking with cross-encoders (covered in depth in Building a Reranking Layer for RAG: Improving Retrieval Precision with Cross-Encoders and LLM-Based Scoring) improves precision significantly — but even cross-encoders have context window limits that can truncate complex queries. The technique we're tackling here — long-context reranking with sliding window attention — combines the full expressive power of a large language model's context window with a structured scoring protocol to evaluate each candidate chunk against the complete query context.

By the end of this lesson, you'll have a production-ready implementation that handles precision-critical use cases where retrieval errors are unacceptable. We'll build from first principles to a full async pipeline you can drop into an existing RAG system.

What you'll learn:

  • Why standard embedding retrieval and cross-encoder reranking fail for complex, multi-clause queries
  • How sliding window attention scoring works as a reranking strategy and when to use it
  • How to implement chunk-by-chunk LLM scoring with structured relevance output
  • How to design an async batched pipeline that keeps latency manageable
  • How to tune scoring rubrics for domain-specific precision requirements

Prerequisites

You should be comfortable with:

  • Python async programming (asyncio, aiohttp)
  • The basics of RAG pipelines — if you're newer to this, start with Retrieval-Augmented Generation Explained: How RAG Works and When to Use It
  • Working with the OpenAI or Anthropic API (we'll use both; see Using the OpenAI API with Python if you need a refresher)
  • Familiarity with vector embeddings and chunking — Chunking Strategies for RAG: How to Split Documents by Size, Sentence, and Semantic Meaning is a solid prerequisite

You'll also want openai>=1.0, anthropic, asyncio, and pydantic installed.


Why Standard Reranking Falls Short for Complex Queries

Before writing any code, let's establish what problem we're actually solving, because "my RAG isn't precise enough" can mean many different things with different solutions.

Standard two-stage RAG pipelines work like this: embed the query, retrieve top-K chunks by cosine similarity, pass those chunks to an LLM for generation. The retrieval stage scores each chunk independently. This works well when queries are short and unambiguous — "What is the capital gains tax rate?" — because the semantic content of the query maps cleanly to the semantic content of the relevant chunks.

The failure mode appears when queries have:

  1. Negations and exclusions: "...excluding breaches disclosed in Schedule 3.4" — embedding models don't reliably distinguish "include X" from "exclude X" at the vector level
  2. Multi-hop dependencies: "What happens to the earnout if the revenue target is missed and the CEO departs voluntarily?" — the relevant chunks may not co-occur in the same section
  3. Conditional logic: "Only in jurisdictions where..." — semantically similar text exists for the unconditional case
  4. Specificity traps: "Section 7.2(c)(iii)" — embeddings smooth over structural references

Cross-encoders handle these better because they process query and chunk together, allowing the model to reason about their interaction. But standard cross-encoders (BERT-based, typically 512 token max) truncate long queries. For a legal query that runs 150 tokens plus a chunk of 300 tokens, you're right at the edge — and many real-world domain queries exceed this.

Long-context LLM-based reranking sidesteps truncation entirely. The full query — no matter how long — is placed in context alongside each candidate chunk, and the model is explicitly asked to score relevance on a structured rubric. The tradeoff is cost and latency. This is not a technique for high-volume, low-stakes retrieval. It's for precision-critical pipelines where a wrong retrieval is worse than a slow response.

Key insight

Think of your retrieval pipeline as a funnel. Embedding retrieval is a wide, fast filter — it gets you from millions of chunks to dozens of candidates. Reranking is a narrow, slow filter that gets you from dozens to the best 3-5. Long-context LLM reranking is the precision instrument at the end of that funnel. Using it at the top of the funnel would be financially and computationally absurd.


The Architecture: Sliding Window Scoring

The term "sliding window" here refers to how we process the candidate chunks, not to any specific model architecture. The concept is straightforward:

We have:

  • A full query context: the user's question, plus any relevant conversation history, plus any explicit constraints provided by the system (think: "this is a Delaware-law governed agreement")
  • A candidate pool: N chunks retrieved by embedding search (typically 15-30)
  • A scoring window: each chunk evaluated individually against the full query context

The "sliding" part means we process one chunk at a time through a fixed context template, rather than trying to stuff all candidates simultaneously into one context (which would be expensive, ordering-biased, and would risk attention dilution across too many candidates).

Here's the full flow:

User Query
    │
    ▼
[Embedding Retrieval] ──► Candidate Pool (top 20-30 chunks)
    │
    ▼
[Context Assembly] ──► Full Query Context Block
    │                   (query + constraints + conversation history)
    ▼
[Sliding Window Scorer]
    ├── Score(chunk_1 | full_query_context)
    ├── Score(chunk_2 | full_query_context)
    ├── ...
    └── Score(chunk_N | full_query_context)
    │
    ▼
[Ranked Results] ──► Top K chunks by score
    │
    ▼
[Generation] ──► Final Response

The key insight is that each scoring call gets the complete, untruncated query context, so the scorer can reason about all the qualifiers, exclusions, and dependencies in the query when evaluating each candidate.


Building the Scoring Rubric

The quality of your reranker lives or dies by the scoring rubric you give the LLM. Generic "is this relevant?" prompts produce noisy scores. You need a structured, domain-aware rubric that the model can apply consistently.

Let's build one for the legal document use case, then generalize it.

from pydantic import BaseModel, Field
from typing import Optional

class ChunkRelevanceScore(BaseModel):
    """Structured relevance score for a retrieved chunk."""
    
    relevance_score: float = Field(
        ge=0.0, le=1.0,
        description="Overall relevance score from 0.0 (completely irrelevant) to 1.0 (perfectly relevant)"
    )
    addresses_core_question: bool = Field(
        description="Does the chunk directly address the main question being asked?"
    )
    handles_qualifiers: bool = Field(
        description="Does the chunk address the specific qualifiers, exclusions, or conditions in the query?"
    )
    specificity_match: float = Field(
        ge=0.0, le=1.0,
        description="How well does the specificity of the chunk match what the query requires? (0=too general or too narrow, 1=exact match)"
    )
    reasoning: str = Field(
        description="Brief explanation of the score (2-3 sentences max)"
    )
    disqualifying_mismatch: Optional[str] = Field(
        default=None,
        description="If the chunk seems relevant but contains a critical mismatch (wrong party, wrong time period, etc.), describe it here"
    )

This model does several useful things. The addresses_core_question and handles_qualifiers flags let you hard-filter chunks that score well overall but miss specific requirements. The disqualifying_mismatch field catches the most dangerous failure mode: a chunk that looks right but is actually about the wrong scenario.

Tip

Pydantic models are your best friend for LLM scoring outputs. They force the model to produce structured data you can reason over programmatically, rather than free-text scores you'd have to parse. See Structured Output: Getting JSON, Tables, and Code from LLMs for techniques on ensuring reliable structured output from different model providers.

Now let's build the scoring prompt:

RERANKING_SYSTEM_PROMPT = """You are a precision relevance evaluator for a legal document retrieval system. 
Your task is to evaluate whether a retrieved document chunk is genuinely useful for answering a specific legal query.

You must be strict. A chunk that is *topically related* but does not specifically address the query's conditions, 
parties, timeframes, or exceptions should receive a low score. The downstream system relies on your evaluation 
to decide which chunks to pass to a generating model — false positives cause incorrect legal analysis.

Evaluate the chunk against ALL elements of the query, including:
- The core question being asked
- Any named parties (acquiring party, target, etc.)
- Any temporal qualifiers (prior to closing, after the effective date, etc.)
- Any explicit exclusions or carve-outs
- Any referenced exhibits, schedules, or sections

Return your evaluation as a JSON object matching the specified schema."""


def build_scoring_prompt(
    query: str,
    query_context: str,
    chunk_text: str,
    chunk_metadata: dict
) -> str:
    """
    Build the user-facing prompt for a single chunk scoring call.
    
    Args:
        query: The user's original question
        query_context: Additional context (conversation history, constraints, etc.)
        chunk_text: The retrieved chunk to evaluate
        chunk_metadata: Source information (document name, section, page, etc.)
    """
    
    source_info = (
        f"Document: {chunk_metadata.get('document_name', 'Unknown')}\n"
        f"Section: {chunk_metadata.get('section', 'Unknown')}\n"
        f"Page: {chunk_metadata.get('page', 'Unknown')}"
    )
    
    return f"""## Query to Answer

{query}

## Additional Query Context
{query_context if query_context else "No additional context provided."}

---

## Candidate Chunk to Evaluate

Source Information:
{source_info}

Chunk Content:
\"\"\"
{chunk_text}
\"\"\"

---

Evaluate this chunk's relevance to the query above. Be strict about whether the chunk addresses 
all specified conditions, parties, and qualifiers — not just the general topic."""

The Async Scoring Engine

Now we build the actual scoring engine. The key design decisions here:

  1. Async parallel scoring: We don't want to score chunks sequentially — that would take N × latency time. We score in parallel with controlled concurrency.
  2. Structured output via JSON mode: We use the model's JSON mode to enforce schema compliance.
  3. Graceful degradation: If a scoring call fails, we return a default low-confidence score rather than crashing.
import asyncio
import json
import time
from dataclasses import dataclass, field
from typing import Optional
import openai
from openai import AsyncOpenAI

@dataclass
class RetrievedChunk:
    chunk_id: str
    text: str
    metadata: dict
    embedding_score: float  # Original retrieval score
    rerank_score: Optional[float] = None
    rerank_details: Optional[ChunkRelevanceScore] = None
    scoring_error: Optional[str] = None


class LongContextReranker:
    """
    Reranks retrieved chunks using full-context LLM scoring.
    
    Uses sliding window approach: each chunk scored individually
    against the complete query context.
    """
    
    def __init__(
        self,
        model: str = "gpt-4o",
        max_concurrent_calls: int = 5,
        scoring_timeout_seconds: float = 30.0,
        min_score_threshold: float = 0.3
    ):
        self.client = AsyncOpenAI()
        self.model = model
        self.semaphore = asyncio.Semaphore(max_concurrent_calls)
        self.timeout = scoring_timeout_seconds
        self.min_score_threshold = min_score_threshold
    
    async def score_single_chunk(
        self,
        chunk: RetrievedChunk,
        query: str,
        query_context: str
    ) -> RetrievedChunk:
        """Score a single chunk against the full query context."""
        
        async with self.semaphore:
            try:
                prompt = build_scoring_prompt(
                    query=query,
                    query_context=query_context,
                    chunk_text=chunk.text,
                    chunk_metadata=chunk.metadata
                )
                
                response = await asyncio.wait_for(
                    self.client.chat.completions.create(
                        model=self.model,
                        messages=[
                            {"role": "system", "content": RERANKING_SYSTEM_PROMPT},
                            {"role": "user", "content": prompt}
                        ],
                        response_format={"type": "json_object"},
                        temperature=0.0,  # Deterministic scoring
                        max_tokens=400
                    ),
                    timeout=self.timeout
                )
                
                raw_json = response.choices[0].message.content
                score_data = json.loads(raw_json)
                
                # Validate with Pydantic
                chunk.rerank_details = ChunkRelevanceScore(**score_data)
                chunk.rerank_score = chunk.rerank_details.relevance_score
                
                # Apply hard filters
                if not chunk.rerank_details.addresses_core_question:
                    chunk.rerank_score *= 0.5  # Penalize chunks that miss the core question
                
                if chunk.rerank_details.disqualifying_mismatch:
                    chunk.rerank_score = min(chunk.rerank_score, 0.2)  # Hard cap on disqualified chunks
                    
            except asyncio.TimeoutError:
                chunk.scoring_error = "timeout"
                # Fall back to embedding score, heavily discounted
                chunk.rerank_score = chunk.embedding_score * 0.5
                
            except (json.JSONDecodeError, ValueError) as e:
                chunk.scoring_error = f"parse_error: {str(e)}"
                chunk.rerank_score = chunk.embedding_score * 0.5
                
            except openai.RateLimitError:
                # Let this propagate — the caller should handle rate limiting
                raise
                
        return chunk
    
    async def rerank(
        self,
        chunks: list[RetrievedChunk],
        query: str,
        query_context: str = "",
        top_k: int = 5
    ) -> list[RetrievedChunk]:
        """
        Rerank a list of retrieved chunks using LLM scoring.
        
        Returns the top_k chunks sorted by rerank score, 
        filtered by min_score_threshold.
        """
        
        start_time = time.monotonic()
        
        # Score all chunks in parallel (bounded by semaphore)
        scoring_tasks = [
            self.score_single_chunk(chunk, query, query_context)
            for chunk in chunks
        ]
        
        scored_chunks = await asyncio.gather(*scoring_tasks, return_exceptions=False)
        
        # Sort by rerank score, breaking ties with original embedding score
        scored_chunks.sort(
            key=lambda c: (c.rerank_score or 0.0, c.embedding_score),
            reverse=True
        )
        
        # Filter and take top_k
        qualified_chunks = [
            c for c in scored_chunks
            if (c.rerank_score or 0.0) >= self.min_score_threshold
        ]
        
        elapsed = time.monotonic() - start_time
        print(f"Reranked {len(chunks)} chunks in {elapsed:.2f}s, "
              f"{len(qualified_chunks)} passed threshold, "
              f"returning top {min(top_k, len(qualified_chunks))}")
        
        return qualified_chunks[:top_k]

Warning

Notice that temperature=0.0 is non-negotiable here. You want deterministic, consistent scoring behavior. Even slight temperature introduces variance that makes scores from different runs incomparable — which breaks any downstream logic that depends on consistent score thresholds. This is one place where creativity in LLM output is actively harmful.


Composing the Full Query Context

The power of long-context reranking comes from feeding the scorer the complete query context — not just the raw user question. What belongs in that context depends on your application, but here's a production-grade context assembler for a multi-turn document QA system:

from dataclasses import dataclass
from typing import Optional

@dataclass  
class QueryContext:
    """Assembled context for a reranking operation."""
    raw_query: str
    conversation_turns: list[dict] = field(default_factory=list)
    system_constraints: list[str] = field(default_factory=list)
    entity_context: dict = field(default_factory=dict)  # Named entities already established
    document_scope: Optional[str] = None  # e.g., "Delaware Merger Agreement, executed 2023-09-14"


def assemble_query_context(ctx: QueryContext) -> tuple[str, str]:
    """
    Returns (query, context_block) tuple for the reranker.
    
    Separates the raw query from supporting context so the scorer
    can weight them appropriately.
    """
    
    context_parts = []
    
    # Document scope
    if ctx.document_scope:
        context_parts.append(f"Document Being Analyzed: {ctx.document_scope}")
    
    # Established entities (things defined earlier in the conversation)
    if ctx.entity_context:
        entity_lines = [f"- {k}: {v}" for k, v in ctx.entity_context.items()]
        context_parts.append(
            "Previously Established Definitions:\n" + "\n".join(entity_lines)
        )
    
    # Relevant conversation history (last N turns to avoid context explosion)
    if ctx.conversation_turns:
        recent_turns = ctx.conversation_turns[-4:]  # Last 2 exchanges
        turn_lines = []
        for turn in recent_turns:
            role_label = "User" if turn["role"] == "user" else "Assistant"
            # Truncate long assistant responses to their first 200 chars
            content = turn["content"]
            if turn["role"] == "assistant" and len(content) > 200:
                content = content[:200] + "... [truncated]"
            turn_lines.append(f"{role_label}: {content}")
        context_parts.append(
            "Recent Conversation:\n" + "\n".join(turn_lines)
        )
    
    # System constraints
    if ctx.system_constraints:
        constraint_lines = [f"- {c}" for c in ctx.system_constraints]
        context_parts.append(
            "Applicable Constraints:\n" + "\n".join(constraint_lines)
        )
    
    context_block = "\n\n".join(context_parts)
    return ctx.raw_query, context_block

Here's how this looks in practice for a real query sequence:

# After several turns of conversation about a merger agreement...
ctx = QueryContext(
    raw_query=(
        "What are the indemnification obligations for the acquiring party "
        "in the event of a material breach that occurred prior to closing, "
        "excluding breaches that were disclosed in Schedule 3.4?"
    ),
    conversation_turns=[
        {"role": "user", "content": "Who is the acquiring party in this agreement?"},
        {"role": "assistant", "content": "The acquiring party is Meridian Capital Holdings LLC, defined in Section 1.1 as 'Buyer'."},
        {"role": "user", "content": "And when is the anticipated closing date?"},
        {"role": "assistant", "content": "The anticipated closing date is March 15, 2024, per Section 2.3(a)."},
    ],
    entity_context={
        "Acquiring Party / Buyer": "Meridian Capital Holdings LLC",
        "Target Company": "Vantage Systems Inc.",
        "Anticipated Closing Date": "March 15, 2024",
        "Agreement": "Agreement and Plan of Merger, dated September 14, 2023"
    },
    system_constraints=[
        "Analysis must be limited to the four corners of the provided agreement",
        "Delaware law governs interpretation disputes per Section 11.7"
    ],
    document_scope="Agreement and Plan of Merger between Meridian Capital Holdings LLC and Vantage Systems Inc., dated September 14, 2023"
)

query, context_block = assemble_query_context(ctx)

This context block gives the scorer everything it needs to distinguish a chunk about Meridian's indemnification obligations from a chunk about Vantage's indemnification obligations — a distinction that an embedding model would almost certainly miss.


Integrating with an Existing RAG Pipeline

Let's wire this into a complete, production-style pipeline that you can drop into an existing system built with Building AI Workflows with LangChain and LlamaIndex or any other orchestration framework:

import asyncio
from typing import Optional

class PrecisionRAGPipeline:
    """
    A precision-focused RAG pipeline with long-context reranking.
    
    Designed for applications where retrieval errors are unacceptable:
    legal, compliance, medical, financial document Q&A.
    """
    
    def __init__(
        self,
        vector_store,          # Any store with .similarity_search(query, k) -> list[Document]
        embedding_function,    # Callable: str -> list[float]
        generation_client,     # AsyncOpenAI or Anthropic client
        reranker: LongContextReranker,
        retrieval_k: int = 20,     # How many to retrieve initially
        rerank_top_k: int = 5,     # How many to pass to generation
        generation_model: str = "gpt-4o"
    ):
        self.vector_store = vector_store
        self.embedding_fn = embedding_function
        self.gen_client = generation_client
        self.reranker = reranker
        self.retrieval_k = retrieval_k
        self.rerank_top_k = rerank_top_k
        self.generation_model = generation_model
    
    def _docs_to_chunks(self, docs) -> list[RetrievedChunk]:
        """Convert vector store results to RetrievedChunk objects."""
        chunks = []
        for i, doc in enumerate(docs):
            chunks.append(RetrievedChunk(
                chunk_id=doc.metadata.get("chunk_id", f"chunk_{i}"),
                text=doc.page_content,
                metadata=doc.metadata,
                embedding_score=doc.metadata.get("score", 0.5)
            ))
        return chunks
    
    def _build_generation_prompt(
        self,
        query: str,
        reranked_chunks: list[RetrievedChunk],
        context_block: str
    ) -> str:
        """Build the final generation prompt using only reranked chunks."""
        
        sources_text = ""
        for i, chunk in enumerate(reranked_chunks, 1):
            source = chunk.metadata.get("document_name", "Unknown")
            section = chunk.metadata.get("section", "")
            confidence = f"{(chunk.rerank_score or 0)*100:.0f}%"
            sources_text += (
                f"\n[Source {i} | {source} | {section} | Relevance: {confidence}]\n"
                f"{chunk.text}\n"
            )
        
        return f"""Answer the following question using ONLY the provided source materials.
If the sources do not contain sufficient information to fully answer the question, 
state explicitly what information is missing.

## Question
{query}

## Context
{context_block}

## Source Materials
{sources_text}

## Instructions
- Cite specific source numbers when making claims
- If sources conflict, note the conflict explicitly
- Do not extrapolate beyond what the sources state
- If a qualifier or exclusion in the question is not addressed by the sources, say so"""
    
    async def query(
        self,
        query_ctx: QueryContext
    ) -> dict:
        """
        Execute a full precision RAG query.
        
        Returns dict with answer, sources, and scoring metadata.
        """
        
        query, context_block = assemble_query_context(query_ctx)
        
        # Stage 1: Broad retrieval
        raw_docs = self.vector_store.similarity_search(
            query, 
            k=self.retrieval_k
        )
        candidate_chunks = self._docs_to_chunks(raw_docs)
        
        print(f"Retrieved {len(candidate_chunks)} candidate chunks")
        
        # Stage 2: Long-context reranking
        reranked_chunks = await self.reranker.rerank(
            chunks=candidate_chunks,
            query=query,
            query_context=context_block,
            top_k=self.rerank_top_k
        )
        
        if not reranked_chunks:
            return {
                "answer": "No sufficiently relevant sources found for this query.",
                "sources": [],
                "reranking_metadata": {"chunks_retrieved": len(candidate_chunks), "chunks_qualified": 0}
            }
        
        print(f"Top reranked scores: {[f'{c.rerank_score:.2f}' for c in reranked_chunks]}")
        
        # Stage 3: Generation with precision-filtered sources
        generation_prompt = self._build_generation_prompt(query, reranked_chunks, context_block)
        
        response = await self.gen_client.chat.completions.create(
            model=self.generation_model,
            messages=[
                {
                    "role": "system", 
                    "content": "You are a precise legal document analyst. Answer questions accurately based solely on the provided source materials."
                },
                {"role": "user", "content": generation_prompt}
            ],
            temperature=0.1,
            max_tokens=1500
        )
        
        answer = response.choices[0].message.content
        
        # Build source attribution
        sources = []
        for chunk in reranked_chunks:
            sources.append({
                "chunk_id": chunk.chunk_id,
                "document": chunk.metadata.get("document_name"),
                "section": chunk.metadata.get("section"),
                "page": chunk.metadata.get("page"),
                "rerank_score": chunk.rerank_score,
                "reasoning": chunk.rerank_details.reasoning if chunk.rerank_details else None,
                "text_preview": chunk.text[:200] + "..."
            })
        
        return {
            "answer": answer,
            "sources": sources,
            "reranking_metadata": {
                "chunks_retrieved": len(candidate_chunks),
                "chunks_qualified": len(reranked_chunks),
                "model_used": self.reranker.model
            }
        }

Note

The source attribution dict returned here pairs naturally with a citation and source attribution system if you want to surface inline citations in your UI. The reasoning field from the reranker is especially useful — it gives you a human-readable explanation of why each source was considered relevant.


Cost and Latency Optimization

Long-context LLM reranking is expensive. Let's be honest about the numbers. If you're scoring 20 chunks, and each scoring call uses roughly 800 tokens (query context + chunk + system prompt), you're using 16,000 tokens per reranking operation. At GPT-4o rates, that's around $0.06 per query just for reranking. For high-volume applications, that adds up fast.

Here are the levers you can pull:

1. Use a smaller model for initial scoring passes

You don't need GPT-4o for every chunk. Use a tiered approach: score all candidates with a smaller model (like gpt-4o-mini), then re-score only the borderline cases (scores between 0.4 and 0.7) with the full model.

class TieredReranker:
    """Two-pass reranker: fast model for broad scoring, strong model for borderline cases."""
    
    def __init__(self):
        self.fast_reranker = LongContextReranker(
            model="gpt-4o-mini",
            max_concurrent_calls=10
        )
        self.precision_reranker = LongContextReranker(
            model="gpt-4o",
            max_concurrent_calls=3
        )
    
    async def rerank(
        self,
        chunks: list[RetrievedChunk],
        query: str,
        query_context: str,
        top_k: int = 5,
        borderline_low: float = 0.4,
        borderline_high: float = 0.7
    ) -> list[RetrievedChunk]:
        
        # First pass: score everything with fast model
        first_pass = await self.fast_reranker.rerank(
            chunks, query, query_context, top_k=len(chunks)
        )
        
        # Classify results
        clear_positives = [c for c in first_pass if (c.rerank_score or 0) > borderline_high]
        borderline = [c for c in first_pass if borderline_low <= (c.rerank_score or 0) <= borderline_high]
        
        print(f"First pass: {len(clear_positives)} clear positives, {len(borderline)} borderline")
        
        if borderline:
            # Second pass: re-score borderline chunks with stronger model
            borderline_rescored = await self.precision_reranker.rerank(
                borderline, query, query_context, top_k=len(borderline)
            )
            combined = clear_positives + borderline_rescored
        else:
            combined = clear_positives
        
        combined.sort(key=lambda c: c.rerank_score or 0, reverse=True)
        return combined[:top_k]

2. Cache reranking results for repeated or similar queries

If your users tend to ask similar questions (common in domain-specific applications), caching scored chunk-query pairs can dramatically reduce costs. See Implementing LLM Response Caching with Redis: Semantic Deduplication, TTL Strategies, and Cache Invalidation Patterns for production caching patterns that handle semantic similarity rather than exact match.

3. Pre-filter with a lightweight heuristic before scoring

Before spending LLM tokens, run cheap heuristic filters:

def pre_filter_chunks(
    chunks: list[RetrievedChunk],
    query: str,
    max_candidates: int = 15
) -> list[RetrievedChunk]:
    """
    Lightweight pre-filter to reduce LLM scoring calls.
    Uses keyword overlap and embedding score threshold.
    """
    
    # Extract key terms from query (naive implementation — use a proper NLP library in production)
    query_terms = set(query.lower().split())
    stop_words = {"the", "a", "an", "in", "of", "and", "or", "to", "for", "is", "are", "that"}
    query_terms -= stop_words
    
    def chunk_prefilter_score(chunk: RetrievedChunk) -> float:
        chunk_text_lower = chunk.text.lower()
        
        # Keyword overlap bonus
        matched_terms = sum(1 for term in query_terms if term in chunk_text_lower)
        keyword_score = matched_terms / max(len(query_terms), 1)
        
        # Combine with embedding score
        return 0.6 * chunk.embedding_score + 0.4 * keyword_score
    
    scored = [(chunk, chunk_prefilter_score(chunk)) for chunk in chunks]
    scored.sort(key=lambda x: x[1], reverse=True)
    
    return [chunk for chunk, _ in scored[:max_candidates]]

Tip

Even crude pre-filtering makes a material difference. In a typical legal document RAG system, reducing candidate pool from 25 to 15 before LLM scoring cuts reranking cost by 40% with minimal precision loss, because the bottom 10 candidates were almost certainly irrelevant anyway.


Hands-On Exercise

Let's build a complete working example you can run locally. This exercise uses a small corpus of synthetic contract clauses to demonstrate the precision difference between embedding-only retrieval and long-context reranking.

# exercise.py — Complete runnable example
import asyncio
import json
from dataclasses import dataclass, field
from typing import Optional

# --- Synthetic corpus: 8 contract clauses, some intentionally misleading ---
SYNTHETIC_CHUNKS = [
    RetrievedChunk(
        chunk_id="c001",
        text="""Section 8.2(a) — Buyer Indemnification. Subject to the limitations set forth in 
        Section 8.4, Buyer shall indemnify, defend, and hold harmless Seller and its affiliates 
        from and against any Losses arising from (i) any breach of any representation or warranty 
        made by Buyer in this Agreement, or (ii) any breach of any covenant of Buyer.""",
        metadata={"document_name": "Merger Agreement", "section": "8.2(a)", "page": 42},
        embedding_score=0.91
    ),
    RetrievedChunk(
        chunk_id="c002",
        text="""Section 8.3(a) — Seller Indemnification. Seller shall indemnify Buyer from and against 
        any Losses arising from any breach of Seller's representations or warranties, subject to 
        the survival periods set forth in Section 8.1 and excluding any breach that was disclosed 
        in the Disclosure Schedules delivered at signing.""",
        metadata={"document_name": "Merger Agreement", "section": "8.3(a)", "page": 43},
        embedding_score=0.89  # High embedding score, but wrong party!
    ),
    RetrievedChunk(
        chunk_id="c003",
        text="""Schedule 3.4 — Disclosed Breaches. The following matters, which may constitute 
        breaches of the representations and warranties of Seller, are hereby disclosed: 
        (1) The pending EPA notice dated August 3, 2023 regarding Site No. 7; 
        (2) The employment discrimination claim filed by former employee J. Martinez.""",
        metadata={"document_name": "Merger Agreement", "section": "Schedule 3.4", "page": 87},
        embedding_score=0.84
    ),
    RetrievedChunk(
        chunk_id="c004",
        text="""Section 8.4 — Limitations on Indemnification. No indemnification shall be required 
        under Section 8.2 or 8.3 unless the aggregate amount of Losses exceeds the Deductible of 
        $500,000, and in no event shall Buyer's aggregate indemnification liability exceed the 
        Cap Amount of $5,000,000.""",
        metadata={"document_name": "Merger Agreement", "section": "8.4", "page": 44},
        embedding_score=0.82
    ),
    RetrievedChunk(
        chunk_id="c005",
        text="""Section 8.5 — Pre-Closing Breach Procedures. With respect to any breach that 
        occurred prior to the Closing Date, Buyer shall provide written notice to Seller within 
        18 months of Closing. Notwithstanding the foregoing, Buyer shall have no indemnification 
        obligation with respect to breaches that were specifically identified in Schedule 3.4.""",
        metadata={"document_name": "Merger Agreement", "section": "8.5", "page": 45},
        embedding_score=0.78
    ),
    RetrievedChunk(
        chunk_id="c006",
        text="""Section 7.1 — Conditions to Closing. The obligations of Buyer to consummate the 
        Merger are subject to: (a) the accuracy of Seller's representations and warranties as of 
        the Closing Date; (b) performance by Seller of all covenants required to be performed 
        prior to Closing; (c) no Material Adverse Effect shall have occurred.""",
        metadata={"document_name": "Merger Agreement", "section": "7.1", "page": 36},
        embedding_score=0.71
    ),
    RetrievedChunk(
        chunk_id="c007",
        text="""Section 11.3 — Indemnification Procedure. A party seeking indemnification (the 
        'Indemnified Party') shall promptly notify the indemnifying party in writing upon becoming 
        aware of any claim. Failure to provide timely notice shall not relieve the indemnifying 
        party of its obligations except to the extent of actual prejudice.""",
        metadata={"document_name": "Merger Agreement", "section": "11.3", "page": 58},
        embedding_score=0.69
    ),
    RetrievedChunk(
        chunk_id="c008",
        text="""Section 8.2(b) — Buyer Post-Closing Obligations. Following the Closing, Buyer 
        shall be responsible for all Losses arising from the operation of the Business after 
        the Closing Date, regardless of whether such Losses relate to conditions existing 
        prior to Closing, except as set forth in Section 8.3.""",
        metadata={"document_name": "Merger Agreement", "section": "8.2(b)", "page": 42},
        embedding_score=0.74
    ),
]

async def run_exercise():
    """
    Demonstrate the precision difference between embedding retrieval 
    and long-context reranking on a complex legal query.
    """
    
    query = (
        "What are the indemnification obligations for the acquiring party "
        "in the event of a material breach that occurred prior to closing, "
        "excluding breaches that were disclosed in Schedule 3.4?"
    )
    
    entity_context = {
        "Acquiring Party / Buyer": "Meridian Capital Holdings LLC",
        "Target / Seller": "Vantage Systems Inc.",
        "Closing Date": "March 15, 2024"
    }
    
    ctx = QueryContext(
        raw_query=query,
        entity_context=entity_context,
        document_scope="Merger Agreement, Meridian / Vantage, September 14, 2023"
    )
    
    _, context_block = assemble_query_context(ctx)
    
    print("=" * 60)
    print("EMBEDDING RETRIEVAL ORDER (top 5 by embedding score):")
    print("=" * 60)
    top_by_embedding = sorted(SYNTHETIC_CHUNKS, key=lambda c: c.embedding_score, reverse=True)[:5]
    for i, chunk in enumerate(top_by_embedding, 1):
        print(f"{i}. [{chunk.metadata['section']}] score={chunk.embedding_score:.2f}")
        print(f"   Preview: {chunk.text[:100]}...")
        print()
    
    print("=" * 60)
    print("RUNNING LONG-CONTEXT RERANKER...")
    print("=" * 60)
    
    reranker = LongContextReranker(
        model="gpt-4o",
        max_concurrent_calls=4,
        min_score_threshold=0.35
    )
    
    reranked = await reranker.rerank(
        chunks=SYNTHETIC_CHUNKS,
        query=query,
        query_context=context_block,
        top_k=5
    )
    
    print("\nRERANKED ORDER:")
    for i, chunk in enumerate(reranked, 1):
        print(f"{i}. [{chunk.metadata['section']}] rerank={chunk.rerank_score:.2f} (was embed={chunk.embedding_score:.2f})")
        if chunk.rerank_details:
            print(f"   Core question: {chunk.rerank_details.addresses_core_question}")
            print(f"   Handles qualifiers: {chunk.rerank_details.handles_qualifiers}")
            if chunk.rerank_details.disqualifying_mismatch:
                print(f"   ⚠️  Disqualifying mismatch: {chunk.rerank_details.disqualifying_mismatch}")
            print(f"   Reasoning: {chunk.rerank_details.reasoning}")
        print()


if __name__ == "__main__":
    asyncio.run(run_exercise())

When you run this, you should see:

  • c002 (Seller indemnification — wrong party) fall dramatically in score despite high embedding score
  • c005 (Pre-Closing Breach Procedures with Schedule 3.4 carve-out) rise significantly — it directly addresses the exclusion in the query
  • c001 (Buyer indemnification) remain high, but the reranker should flag that it doesn't address the Schedule 3.4 exclusion
  • c006 (Conditions to Closing) fall to near-zero — topically related but doesn't address indemnification

This is the value proposition in a single test case. Embedding retrieval got the topic right; reranking got the answer right.


Common Mistakes & Troubleshooting

Mistake 1: Scoring too many chunks with the expensive model

If you're sending 30 chunks to GPT-4o for every query, your costs will be prohibitive and you won't see proportional precision gains (the bottom-ranked candidates from embedding retrieval are almost always genuinely irrelevant). Rule of thumb: retrieve 20-25 candidates, pre-filter to 12-15, then run LLM scoring.

Mistake 2: Not including enough query context

The most common failure mode after implementation is that the reranker doesn't have enough context to make the right call. If your users work in multi-turn sessions, you must include conversation history in the context block. A standalone query like "What about the exclusions?" is completely uninterpretable without prior context.

Mistake 3: Treating relevance_score as absolute

LLM-based scores are relative assessments, not calibrated probabilities. A score of 0.8 from one query does not mean the same thing as 0.8 from another. Use scores for ranking within a single query, not for cross-query comparisons. If you're comparing thresholds across different document types or query styles, you'll need to calibrate per domain.

Mistake 4: Temperature above 0 for scoring

We covered this in a warning above, but it bears repeating: any non-zero temperature introduces variance. Run the same chunk-query pair twice with temperature=0.1, and you may get 0.72 and 0.68. For a threshold of 0.70, that's the difference between including and excluding a critical source.

Mistake 5: Ignoring the disqualifying_mismatch field

A chunk can score 0.65 on overall relevance while containing a critical error — wrong party, wrong date, wrong jurisdiction. The disqualifying_mismatch field is specifically designed to catch this. If your rubric doesn't include it (or if you ignore it in post-processing), you'll occasionally pass confidently wrong information to the generation stage.

Warning

If you're building a system where errors have real-world consequences — legal, medical, financial — you should consider adding a human review gate for any response where disqualifying_mismatch was triggered on a chunk that was still included in the generation context. The LLM reranker catches most of these, but not all. See Testing and Evaluating LLM Applications: A Comprehensive Guide to Quality Assurance for how to build systematic evaluation that catches these edge cases.

Troubleshooting: Reranker scores feel random or inconsistent

If your scores feel noisy, check:

  1. Is your system prompt specific enough? Generic "evaluate relevance" prompts produce generic, inconsistent results.
  2. Is your chunk text clean? OCR artifacts, encoding issues, and broken sentence fragments all confuse the scorer.
  3. Are you including enough query context? If the scorer doesn't know who "the buyer" is, it can't evaluate party-specific clauses.
  4. Is your model being asked to score chunks that are genuinely ambiguous? If multiple chunks have similar content and legitimate overlap with the query, scores will naturally cluster. This is correct behavior, not noise.

Troubleshooting: High latency even with async

If reranking is taking 20+ seconds, check:

  1. max_concurrent_calls might be too low — increase from 5 to 8-10 if your rate limits allow
  2. max_tokens=400 for scoring responses — if you're not constraining output length, the model might generate lengthy explanations that increase latency
  3. Consider reducing retrieval_k — going from 25 candidates to 15 is a 40% speedup with minimal precision cost

When to Use This Pattern (and When Not To)

Long-context LLM reranking is the right choice when:

  • Precision is more critical than throughput: legal, compliance, medical, financial document QA
  • Queries are complex: multiple clauses, negations, conditional logic, explicit exclusions
  • False positives have real consequences: wrong information passed to generation is worse than a "not enough information" response
  • Document corpus is specialized: the domain-specific scoring rubric can be finely tuned

Skip this pattern when:

  • Volume is high, queries are simple: customer FAQ bots, product search, documentation lookup
  • Cost per query must be sub-cent: use a lightweight cross-encoder (BERT-based) instead
  • Latency < 2 seconds is a hard requirement: the async pipeline gets this under 5-8 seconds with the right model and concurrency, but that may still be too slow for some interfaces
  • Your retrieval quality is already high: if embedding search consistently returns 90%+ relevant results, the marginal improvement from LLM reranking may not justify the cost

A note on alternative approaches: if you're on the fence about cost, consider that implementing hybrid search (combining dense embedding retrieval with sparse BM25 retrieval) can significantly improve initial retrieval precision at near-zero marginal cost. Better retrieval reduces the pressure on reranking, and sometimes eliminates the need for expensive LLM scoring entirely.


Summary & Next Steps

You've built a production-grade long-context reranking system from the ground up. Here's what you've accomplished:

  • Understood the failure modes of embedding retrieval and standard cross-encoder reranking for complex, multi-clause queries
  • Designed a structured scoring rubric using Pydantic models that captures relevance, qualifier handling, and disqualifying mismatches
  • Built an async scoring engine with bounded concurrency, graceful error handling, and deterministic temperature settings
  • Assembled complete query context that includes conversation history, entity definitions, and system constraints — giving the scorer everything it needs
  • Implemented a tiered cost optimization strategy that uses cheaper models for clear cases and reserves the precision model for borderline ones
  • Built a full pipeline that integrates retrieval, reranking, and generation with structured source attribution

Where to go next:

The natural extension of this system is to instrument it properly. Every reranking decision — which chunks scored high, which were disqualified, what the final answer was, and whether the user was satisfied — is a training signal for a self-improving RAG pipeline. Once you've collected enough reranking judgments, you can fine-tune a smaller model on your scoring rubric, dramatically reducing the cost of each scoring call.

You should also look at how this pipeline behaves under load. The async patterns here work for single-request execution, but in a multi-tenant production system you'll need to think carefully about rate limit management and request queuing — the LLM observability and monitoring patterns lesson covers how to instrument this so you can see exactly where latency is going and which queries are hitting rate limits.

Finally, if your documents include tables, diagrams, or scanned pages, the text-based reranking here will miss information that only exists in non-text form. That's where multimodal LLM integration becomes relevant — the same sliding window scoring architecture applies, but you pass image content alongside text to a vision-capable model.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Building with LLMs

Previous

Webhook Integration for Real-Time LLM Triggers: Connecting External Events to AI Pipelines with Python

Related Insights

AI & Machine LearningPractitioner

Designing Fallback Prompts: How to Handle Low-Confidence, Ambiguous, and Out-of-Scope User Inputs Gracefully in Production AI Applications

24 min
AI & Machine LearningPractitioner

Implementing Agent Sandboxing and Capability Boundaries: Restricting Tool Access, Scoping Permissions, and Enforcing Execution Limits for Safe Autonomous LLM Agents in Production

22 min
AI & Machine LearningFoundation

Webhook Integration for Real-Time LLM Triggers: Connecting External Events to AI Pipelines with Python

16 min

On this page

  • Introduction
  • Prerequisites
  • Why Standard Reranking Falls Short for Complex Queries
  • The Architecture: Sliding Window Scoring
  • Building the Scoring Rubric
  • The Async Scoring Engine
  • Composing the Full Query Context
  • Integrating with an Existing RAG Pipeline
  • Cost and Latency Optimization
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • When to Use This Pattern (and When Not To)
  • Summary & Next Steps