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

推荐订阅源

L
LINUX DO - 热门话题
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security @ Cisco Blogs
W
WeLiveSecurity
N
News and Events Feed by Topic
Security Archives - TechRepublic
Security Archives - TechRepublic
V2EX - 技术
V2EX - 技术
TaoSecurity Blog
TaoSecurity Blog
L
LINUX DO - 最新话题
Cloudbric
Cloudbric
S
Secure Thoughts
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
CXSECURITY Database RSS Feed - CXSecurity.com
Forbes - Security
Forbes - Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Blog of Author Tim Ferriss
博客园 - 【当耐特】
NISL@THU
NISL@THU
F
Full Disclosure
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC
B
Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
B
Blog RSS Feed
Jina AI
Jina AI
N
News | PayPal Newsroom
G
Google Developers Blog
P
Proofpoint News Feed
雷峰网
雷峰网
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Proofpoint News Feed
PCI Perspectives
PCI Perspectives
H
Heimdal Security Blog
GbyAI
GbyAI
Project Zero
Project Zero
Hacker News - Newest:
Hacker News - Newest: "LLM"
Y
Y Combinator Blog
S
Schneier on Security
Hacker News: Ask HN
Hacker News: Ask HN
S
Security Affairs
P
Privacy & Cybersecurity Law Blog
Attack and Defense Labs
Attack and Defense Labs
美团技术团队
T
Threat Research - Cisco Blogs
T
Threatpost
The Hacker News
The Hacker News
C
Cisco Blogs
Last Week in AI
Last Week in AI
Google DeepMind News
Google DeepMind News

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
Two Patterns for Reducing LLM Costs in Data-Heavy RAG Apps
Lucas · 2026-06-24 · via DEV Community

How we cut token usage significantly in an F1 telemetry analyzer by rethinking what goes into the context window — and when.


When building RAG applications on top of structured data (databases, APIs, telemetry), the naive approach is to dump everything into the context and let the LLM figure it out. It works, but it's expensive and slow. After building F1 Analyst Pro — a chat interface for Formula 1 race analysis backed by FastF1 + Supabase + Claude — we refined two patterns that significantly reduced both token usage and API costs without sacrificing response quality.

This post covers both patterns with real code from the project.


The Problem: Context Bloat

A typical race weekend in F1 Analyst Pro has data across multiple sessions: FP1, FP2, FP3, Qualifying, and Race. Each session has lap-by-lap data for 22 drivers — compound, lap time, position, stint, sector times, tyre life. On top of that: qualifying results, race results, stint summaries, pit stop analysis, key moments, race incidents, and journalist notes.

If you send all of that to the LLM on every query, two things happen:

  1. Cost explodes. A full context dump for a race weekend easily reaches 8,000-12,000 tokens per query. At $3/MTok for Claude Sonnet input, that's $0.024-$0.036 per query — fine for one user, painful for many.

  2. Quality degrades. LLMs perform worse when the context contains irrelevant information. A question about qualifying doesn't need race stint summaries — and including them adds noise that can distract the model from what matters.

The solution is two complementary patterns: conditional context and pre-generation.


Pattern 1: Conditional Context via Intent Detection

Instead of always building the full context, detect what the user is actually asking about and fetch only the relevant data.

Intent Detection

import unicodedata

def _detect_intents(prompt: str) -> dict:
    # Normalize accents so "clasificación" matches "clasificacion"
    p = unicodedata.normalize("NFD", prompt.lower())
    p = "".join(c for c in p if unicodedata.category(c) != "Mn")

    wants_qualy = any(w in p for w in [
        "clasificacion", "qualifying", "q1", "q2", "q3", "pole", "sector"
    ])
    wants_race = any(w in p for w in [
        "carrera", "race", "resultado", "vuelta rapida", "stint", "degradacion"
    ])
    wants_telemetry = any(w in p for w in [
        "telemetria", "aceleracion", "frenada", "velocidad", "throttle", "brake"
    ])
    wants_undercut = any(w in p for w in [
        "undercut", "overcut", "parada", "pit stop", "estrategia de pit"
    ])
    wants_practice = any(w in p for w in [
        "entrenamiento", "practica", "fp1", "fp2", "fp3", "long run", "evolucion"
    ])
    wants_race_sim = any(w in p for w in [
        "race simulation", "simulacion de carrera", "ritmo de fp2"
    ])

    # load_all is the fallback: fires only when no specific intent is detected
    load_all = not any([
        wants_qualy, wants_race, wants_telemetry,
        wants_undercut, wants_practice, wants_race_sim
    ])

    return {
        "wants_qualy": wants_qualy,
        "wants_race": wants_race,
        "wants_telemetry": wants_telemetry,
        "wants_undercut": wants_undercut,
        "wants_practice": wants_practice,
        "wants_race_sim": wants_race_sim,
        "load_all": load_all,
    }

Conditional Context Building

Each intent triggers specific SQL queries. Critically, expensive analyses (undercut/overcut, key moments, race incidents) are only fetched when they're actually relevant:

def build_context(self, prompt: str, gp_name: str, year: int) -> str:
    intents = _detect_intents(prompt)
    context = ""

    # --- QUALIFYING ---
    if intents["wants_qualy"] or intents["load_all"]:
        q_id = self.db.get_session_id(year, gp_name, "Q")
        if q_id:
            q_results = self.db.get_qualifying_results(q_id)
            context += "--- QUALIFYING (Q) ---\n" + q_results.to_string(index=False) + "\n\n"

    # --- RACE ---
    if intents["wants_race"] or intents["wants_undercut"] or intents["load_all"]:
        r_id = self.db.get_session_id(year, gp_name, "R")
        if r_id:
            # Always include stint summary for race queries
            stints = self.db.get_stint_summary(r_id)
            context += "--- RACE STINT SUMMARY ---\n" + stints.to_string(index=False) + "\n\n"

            # Undercut analysis: only when explicitly asked OR general race query
            if intents["wants_undercut"] or intents["wants_race"] or intents["load_all"]:
                pit_df = self.db.get_pit_stop_analysis(r_id)
                if not pit_df.empty:
                    context += "--- UNDERCUT/OVERCUT ANALYSIS ---\n" + pit_df.to_string(index=False) + "\n\n"

            # Key moments: only for race/general queries, not undercut-specific ones
            if intents["wants_race"] or intents["load_all"]:
                km_df = self.db.get_key_moments(r_id)
                if not km_df.empty:
                    context += "--- KEY MOMENTS ---\n" + km_df.to_string(index=False) + "\n\n"

            # Race incidents: always when race data is present
            inc_df = self.db.get_race_incidents(r_id)
            if not inc_df.empty:
                context += "--- RACE INCIDENTS ---\n" + inc_df.to_string(index=False) + "\n\n"

    # --- PRACTICE (FP1/FP2/FP3) ---
    if intents["wants_practice"] or intents["load_all"]:
        for fp_code, fp_label in [("FP1", "PRÁCTICA 1"), ("FP2", "PRÁCTICA 2"), ("FP3", "PRÁCTICA 3")]:
            fp_id = self.db.get_session_id(year, gp_name, fp_code)
            if fp_id:
                best = self.db.get_best_lap_per_driver(fp_id)
                if not best.empty:
                    context += f"--- {fp_label} ({fp_code}) ---\n" + best.to_string(index=False) + "\n\n"

    return context

The Impact

A query like "¿Cuál fue la pole?" used to pull in race stints, pit stop analysis, key moments, and FP laps — all irrelevant. With intent detection, it only fetches qualifying results: ~400 tokens vs ~6,000 tokens for the same question. That's a 15x reduction in input tokens for qualifying-specific queries.

For general race queries (load_all=False, wants_race=True), the context is still substantial but focused — stints, undercut analysis, key moments, incidents — all directly relevant to any race question.


Pattern 2: Pre-Generation for Charts

The standard approach when a user asks for a chart is to let the LLM generate the plotting code, return it to the client, execute it, and display the result. This sounds reasonable but has three problems in practice:

  1. It costs tokens. A matplotlib or Plotly snippet is 50-150 lines of code — all in the output window.
  2. It's unreliable. The LLM may hallucinate API calls, use deprecated methods, or generate code that fails silently.
  3. It's slow. The user waits for the full code generation before seeing anything.

The alternative: generate the chart from real database data before the API call, then tell the LLM the chart exists.

Implementation

def send_message(self, prompt: str, gp_name: str, year: int) -> dict:
    intents = _detect_intents(prompt)

    # Step 1: pre-generate chart if telemetry is requested
    pre_chart = None
    chart_notification = ""

    if intents["wants_telemetry"]:
        drivers = self._extract_drivers(prompt, gp_name, year)
        session_type = self._detect_session_type(prompt)
        qualifying_segment = self._detect_qualifying_segment(prompt)  # Q1/Q2/Q3

        if drivers:
            pre_chart = plot_telemetry_trace(
                laps_data=None,         # fetches directly from FastF1
                gp_name=gp_name,
                year=year,
                drivers=drivers,
                session_type=session_type,
                qualifying_segment=qualifying_segment,
            )
            if pre_chart is not None:
                chart_notification = (
                    f"\n\n[SYSTEM: A telemetry chart comparing "
                    f"{', '.join(drivers)} in {session_type} has been generated. "
                    f"Reference it in your analysis without generating any code.]"
                )

    # Step 2: build context (conditional, as shown above)
    context = self.build_context(prompt, gp_name, year)

    # Step 3: inject chart notification into the user message
    user_content = context + prompt + chart_notification

    # Step 4: call the LLM
    response = self.anthropic.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1000,
        system=self._system_prompt(),
        messages=[{"role": "user", "content": user_content}],
    )

    return {
        "text": response.content[0].text,
        "chart": pre_chart,   # passed to Streamlit for rendering
    }

The Qualifying Segment Detail

One refinement worth highlighting: qualifying telemetry in F1 has three segments (Q1, Q2, Q3). A driver eliminated in Q1 never ran in Q3 — comparing their "best lap in Q" against a Q3 driver's best lap is meaningless.

The pre-generation step handles this by detecting the segment from the prompt:

def _detect_qualifying_segment(self, prompt: str) -> str | None:
    match = re.search(r'\b(q[123])\b', prompt.lower())
    return match.group(1).upper() if match else None

And in plot_telemetry_trace:

if qualifying_segment:
    stint_map = {"Q1": 1, "Q2": 2, "Q3": 3}
    seg_laps = drv_laps[drv_laps["Stint"] == stint_map[qualifying_segment]]
    drv_laps = seg_laps if not seg_laps.empty else drv_laps  # fallback if driver wasn't in that segment

fastest = drv_laps.loc[drv_laps["LapTime"].idxmin()]

The Impact

The pre-generation pattern eliminates chart code from the LLM output entirely. A telemetry response that previously cost ~800 output tokens (code + explanation) now costs ~200 tokens (explanation only). For charts, that's a 75% reduction in output tokens.

More importantly, the chart is guaranteed to use real data — no hallucinated driver codes, no deprecated FastF1 API calls, no silent failures.


Combining Both Patterns

The two patterns compose naturally. Here's what happens for a query like "Show me the telemetry of COL vs GAS in Q2":

  1. Intent detectionwants_telemetry=True, wants_qualy=True
  2. Context building → fetches qualifying results only (~400 tokens)
  3. Pre-generation → generates Q2-filtered telemetry chart for COL and GAS from FastF1 directly
  4. API call → sends qualifying context + chart notification (~600 tokens total input)
  5. Response → LLM references the chart and analyzes the data (~200 tokens output)

Total: ~800 tokens. Without these patterns, the same query would use ~7,000 tokens (full context dump + chart code generation).


What This Doesn't Cover

These patterns work well for structured, database-backed RAG. For unstructured document RAG (PDFs, articles, knowledge bases), vector search with embedding-based retrieval is still the right tool. The key insight is matching the retrieval mechanism to the data structure — keyword/intent-based for tabular data, semantic for text.


The Full Project

F1 Analyst Pro is open source. The patterns described here are implemented in core/consultant_agent.py and core/chart_builder.py.

🏎️ f1-analyst.streamlit.app
📦 github.com/luc45hn/f1-analyst-pro