惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 聂微东
C
CXSECURITY Database RSS Feed - CXSecurity.com
H
Help Net Security
P
Proofpoint News Feed
V
Visual Studio Blog
WordPress大学
WordPress大学
Recent Announcements
Recent Announcements
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
Recorded Future
Recorded Future
Blog — PlanetScale
Blog — PlanetScale
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
I
InfoQ
Microsoft Security Blog
Microsoft Security Blog
The Register - Security
The Register - Security
Y
Y Combinator Blog
Last Week in AI
Last Week in AI
F
Full Disclosure
Jina AI
Jina AI
博客园 - 司徒正美
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
SegmentFault 最新的问题
量子位
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
Vercel News
Vercel News
L
LangChain Blog
云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
有赞技术团队
有赞技术团队
腾讯CDC
Martin Fowler
Martin Fowler
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
DataBreaches.Net
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Context Compression Before the LLM: Cutting Tokens Without Cutting Recall
Gabriel Anhaia · 2026-06-14 · via DEV Community

You retrieve the top 10 chunks, paste them into the prompt, and send it to the model. Each chunk is 400 tokens. That is 4,000 tokens of context for a question whose answer lives in two sentences buried in chunk 6. You pay for all 4,000 on input. You also pay a quieter tax: the model has to find the answer inside a wall of near-miss text, and longer contexts degrade answer quality even when the right fact is present.

Stanford's "Lost in the Middle" work showed it clearly. As input context grows, models reliably use information at the start and end and lose track of facts stuck in the middle (Liu et al., 2023). So the chunk that ranked sixth, sitting in the middle of your prompt, is exactly where the model is weakest.

Context compression is the layer that sits between retrieval and generation. You retrieve generously, then squeeze the retrieved set down to the part that earns its place in the prompt. Two families do this: extractive and abstractive. They make different trade-offs, and most teams pick the wrong one for their data.

Extractive: keep the original sentences, drop the rest

Extractive compression scores each unit of retrieved text against the query and keeps only the units that clear a bar. The text you keep is verbatim from the source. Nothing is rewritten, so nothing is hallucinated into the context.

The simplest version works at the sentence level. Split each chunk into sentences, embed each sentence and the query, keep the sentences whose similarity beats a threshold.

import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("BAAI/bge-small-en-v1.5")

def split_sentences(text: str) -> list[str]:
    # Cheap splitter; swap for spaCy on messy text.
    parts = text.replace("\n", " ").split(". ")
    return [p.strip() for p in parts if p.strip()]

def compress_extractive(
    query: str,
    chunks: list[str],
    keep: float = 0.5,
) -> str:
    sents = []
    for c in chunks:
        sents.extend(split_sentences(c))
    q_vec = model.encode(query, normalize_embeddings=True)
    s_vecs = model.encode(sents, normalize_embeddings=True)
    scores = s_vecs @ q_vec
    n = max(1, int(len(sents) * keep))
    top = np.argsort(scores)[::-1][:n]
    # Restore reading order so prose stays coherent.
    top_sorted = sorted(top.tolist())
    return " ".join(sents[i] for i in top_sorted)

The keep ratio is your dial. At keep=0.5 you drop half the sentences and roughly halve token cost on the context. The sentences you keep are the originals, so a citation that points back to the source still lines up word for word.

The risk with sentence-level filtering is reference breakage. A sentence like "It expires after 30 days" scores low against the query "what is the refund policy" because it shares no keywords, even though it carries the actual answer. You cut it, and the model loses the qualifier. The fix is to keep a small window around every retained sentence so dangling pronouns and follow-on clauses survive.

def with_neighbors(
    sents: list[str],
    kept_idx: list[int],
    radius: int = 1,
) -> list[int]:
    keep = set()
    for i in kept_idx:
        for j in range(i - radius, i + radius + 1):
            if 0 <= j < len(sents):
                keep.add(j)
    return sorted(keep)

A trained extractor does better than cosine similarity. Models like bge-reranker score query-sentence relevance as a cross-encoder, reading both together instead of comparing two separate embeddings. That catches the "it expires after 30 days" case more often, because the reranker sees the query and the sentence in one forward pass. It costs more per sentence, so run it on the candidate set after a cheap embedding filter, not on every sentence in the corpus.

Abstractive: rewrite the chunks into a tighter summary

Abstractive compression sends the retrieved chunks to a small, fast model and asks it to write a query-focused summary. The output is new text. That is the appeal and the danger.

from openai import OpenAI

client = OpenAI()

COMPRESS_PROMPT = """You are a context compressor. Given a
question and source passages, write a concise summary that
keeps every fact relevant to the question. Copy numbers,
names, and dates verbatim. Do not add facts. If a passage is
irrelevant, omit it. If nothing is relevant, return exactly:
NO_RELEVANT_CONTEXT"""

def compress_abstractive(query: str, chunks: list[str]) -> str:
    joined = "\n\n---\n\n".join(chunks)
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": COMPRESS_PROMPT},
            {"role": "user",
             "content": f"Question: {query}\n\n{joined}"},
        ],
        temperature=0.0,
    )
    return resp.choices[0].message.content

The compression ratio here can be far higher than extractive. The model can fold five paragraphs that circle the same fact into one sentence. On verbose corpora (support transcripts, meeting notes, legal boilerplate) abstractive can land in the 50-75% range where extractive is bounded nearer 30-50% by how many sentences you keep. Treat both as rough, corpus-dependent rules of thumb, not guaranteed figures.

The cost is twofold. First, you add an LLM call before the answer call, which adds latency and spend. Second, the summarizer can drop a qualifier or smooth two facts into one wrong fact. "The discount is 10% for orders over $500" can come back as "there is a 10% discount" once the threshold gets summarized away. The mitigations: temperature 0, an explicit instruction to copy numbers and dates verbatim, and a NO_RELEVANT_CONTEXT escape hatch so the model is allowed to return nothing instead of inventing a connection.

The trade-off, stated plainly

Pick on three axes: faithfulness, ratio, and cost.

Extractive Abstractive
Faithful to source high (verbatim) medium (rewritten)
Typical token cut 30-50% 50-75%
Hallucination risk none real
Added latency low (no LLM) one extra LLM call
Citation alignment exact approximate

If your domain punishes wrong facts (legal, medical, finance, anything with a number that matters), start extractive. The verbatim guarantee is the point. If your corpus is verbose and repetitive and the cost of a near-miss summary is low, abstractive buys more headroom.

There is a hybrid that gets most of both. Run extractive first to throw away the obviously irrelevant sentences, then run abstractive on what survives. The summarizer sees a cleaner, shorter input, so it hallucinates less and costs less, and you still get the high compression ratio.

Measure recall, not just token count

A compressor that cuts 60% of tokens and 5% of correct answers is a bad trade you will not notice until users complain. The number that matters is whether the compressed context still contains the facts the model needs. That is context recall, and you can measure it directly.

Take your labeled eval set: question, retrieved chunks, and the gold answer. Run compression. Then check whether the gold facts survived.

def context_recall(
    compressed: str,
    gold_facts: list[str],
) -> float:
    if not gold_facts:
        return 1.0
    hits = sum(
        1 for f in gold_facts
        if f.lower() in compressed.lower()
    )
    return hits / len(gold_facts)

Exact substring matching is crude; for paraphrase-tolerant scoring, an LLM judge or an entailment model reads "does this context support this fact" per gold fact. Either way, the loop is the same: sweep the keep ratio (or compare extractive vs abstractive) and plot context recall against token cost. You are looking for the knee in the curve, the point where dropping more tokens starts costing real answers.

Run it against the same eval you use for retrieval, not a fresh cherry-picked set. The whole reason compression is worth doing is that it sits on the critical path between your retriever and your bill. Treat it like the rest of the pipeline: instrument it, sweep the dial, keep the setting that wins on your data instead of the one a blog post liked.

Where compression sits in the pipeline

The order is fixed. Retrieve more than you need, rerank, compress, generate.

Retrieve wide (top 20 instead of top 5) because compression lets you afford it. Rerank so the best chunks are densest at the top, which makes both compressors more effective. Compress to cut the prompt down to the part that earns its tokens. Then generate, with a shorter, sharper context that the model reads more reliably because the answer is no longer buried in the middle.

Skip compression when your retrieved context is already small and on-target, or when you have a long-context model and token cost is not your constraint. The layer earns its place when you are retrieving generously, paying per input token, and watching answer quality slip as context grows. That is most production RAG.

The RAG Pocket Guide covers this layer alongside retrieval, chunking, and reranking, with the eval methodology to pick a compression strategy on your own corpus instead of guessing. If your prompts are fat and your answers are slipping, compression is the cheapest lever you are probably not pulling yet.

RAG Pocket Guide