AI Cost Optimization

Live & hands-on

Jeremy HintzEngineering Lead @Meta

What you'll learn

Understand your AI bill

  • Know what each token type costs and why
  • See how a short question turns into thousands of billed tokens
  • Do the napkin math on what a request costs

Track spend across your org

  • Put one gateway in front of all your AI calls
  • Break spend down by feature, team, and user
  • Find the one or two features driving most of the bill

Cut costs with caching

  • Arrange prompts so provider caches actually hit
  • Catch the small mistakes that quietly break caching
  • Answer repeat questions without calling the model

Keep agent context small

  • Learn why stale tool output is the first thing to cut
  • Summarize long histories without dropping key facts
  • Store agent memory outside the context window

Replace big prompts with small models

  • Understand how a small model can take over one high-volume job
  • Stop paying for the same long prompt on every call
  • Learn what breaks when the small model goes stale

Route requests to the right model

  • Send easy requests to cheap models and save the big ones
  • Build a router and its evals from scratch
  • Compare routers on cost and quality, not demos

Stop agents from burning money

  • Estimate multi-agent costs before you build
  • Catch loops early, before the retries pile up
  • Fix a broken research agent as your capstone

Course Outline

Week 1
Saturday, October 31, 20269-11 AM PT Live Session11 AM-12 PM PT Live Q&A

AI Cost Dynamics and Observability

AI cost foundations

  • Core meters (input, output, cached, batch, and reasoning tokens)
  • Secondary meters (tool use, images/audio/video, embeddings)
  • Purchasing models (pay-as-you-go, provisioned throughput, self-hosted)
  • Economics of LLM inference
  • Latency metrics like TTFT and inter-token latency
  • Tokenomics in agentic systems
  • Cost amplifiers: tool schemas, RAG documents, multi-agent fan-out, etc.

Cost observability

  • Context growth and failure modes like context rot
  • Traces and spans for LLM applications
  • OpenTelemetry GenAI semantic conventions
  • Content vs. metadata logging (privacy, PII, retention)
  • Sampling strategies
  • Attribution hierarchy
  • Unit economics such as cost per conversation or task

Gateways and where to optimize

  • LLM gateway / LLM mesh like routing and budgets
  • Gateway landscape (LiteLLM, Portkey, Kong, Cloudflare, OpenRouter) and trade-offs
  • Observability stacks (Langfuse, LangSmith, Helicone, Arize Phoenix, W&B Weave, Braintrust)
  • Build vs. buy
  • Baseline diagnostics (top drivers, cache hit rate, waste rate)
  • When not to optimize
  • Optimization stack overview, ranked by ROI

Assignments: Instrument an LLM Gateway

1. Build the mesh

  • Build a gateway for a multi-tenant workload
  • Emit telemetry for every call (tokens, latency, attribution)
  • Connect an observability stack (Langfuse)

2. Diagnose and optimize

  • Produce a cost-diagnosis report
  • Ship one optimization with a measured before/after
AI Cost Dynamics and Observability diagramWeek 1 assignment diagram
Week 2
Saturday, November 7, 20269-11 AM PT Live Session11 AM-12 PM PT Live Q&A

Token Efficiency Techniques

Caching

  • Exact-match response caching
  • Semantic caching (embed → ANN search → threshold → serve or miss)
  • Threshold tuning for cache hits
  • Failure taxonomy
  • Hardening like scoped keys and verifier models
  • Provider prompt caching
  • Stable-to-volatile ordering of input prompt
  • Cache-busting anti-patterns

Context compression

  • Compaction vs. caching
  • Agentic compaction (/compact-style)
  • Tool-result pruning
  • Attention sinks and window management
  • Hard compression and soft compression
  • KV-cache eviction and quantization
  • Context OS

Distillation

  • Prompt and context distillation
  • Model distillation (soft labels, sequence-level KD, SFT on teacher outputs)
  • Limitations and losses

Assignments: Practice Token Efficiency

1. Semantic cache

  • Build a semantic cache and sweep similarity thresholds
  • Harden with a policy gate and a verifier model
  • Build a prefix-cache simulator and detect cache-busting anti-patterns

2. Compaction

  • Compare compaction strategies with a needle-recall test
  • Measure cost vs. recall per strategy

3. Distillation

  • Distill a big-prompt router into a lightweight student
  • Test staleness after a policy change and retrain
Token Efficiency Techniques diagramWeek 2 assignment diagram
Week 3
Saturday, November 14, 20269-11 AM PT Live Session11 AM-12 PM PT Live Q&A

Intelligent Routing and Model Cascades

Model and reasoning effort economics

  • Reasoning effort as a cost lever
  • Capability overlap and difficulty prediction
  • Model complementarity (RouterBench, RouterArena)
  • Cost–quality–latency trade-offs

Model routing

  • Model cascades (FrugalGPT)
  • Expected-cost formulation
  • Routing frameworks (WHEN × SIGNAL × COMPUTE)
  • Predictive vs. non-predictive routing, hybrid systems
  • Ecosystem (RouteLLM, LiteLLM, OpenRouter, Azure Model Router, Bedrock, etc)
  • RouteLLM deep dive (router architectures, data augmentation, calibration, serving)
  • Deterministic and vector-based routing
  • Agent-step routing

Routing evals

  • Metrics (PGR, APGR)
  • Offline certification (golden sets, replay matrix)
  • Programmatic checks and LLM-as-judge labeling
  • Online monitoring (routing distribution, shadow scoring, canary, interleaving)

Assignment: Build a Router

  • Build a model router from scratch
  • Run it against a simulated model pool
  • Build evals and certify the router
Intelligent Routing and Model Cascades diagramWeek 3 assignment diagram
Week 4
Saturday, November 21, 20269-11 AM PT Live Session11 AM-12 PM PT Live Q&A

Agentic Workflow Optimization

Multi-agent loops

  • Decomposition (context isolation, parallelism, specialization)
  • Loop topologies (orchestrator, evaluator, peer debate, blackboard)
  • Cost models for multi-agent systems

Runaway loops and state hygiene

  • Runaway taxonomy (retry spirals, ping-pong delegation, oscillation, goal drift, amplification)
  • Detection (counters, state hashing, semantic repetition, progress metrics, watchdog agents)
  • Context rot (attention dilution, behavioral contamination)
  • State cleansing (truncation, retention policies, compaction, external memory, fresh restarts)
  • Error hygiene (digests, deduplication, failures → constraints)

Planning, speed, and systems thinking

  • Semantic convergence (embedding similarity, edit distance, evaluator score)
  • Convergence vs. stagnation
  • Planning (ReAct vs. plan-then-execute, tree search, pruning, replanning)
  • Speculative decoding (draft–verify, acceptance math, agent-level speculation)
  • Co-design (tool, model, prompt, eval, infra)

Capstone: Rescue a Research Agent

  • Redesign a failing deep research agent
  • Apply the full optimization toolkit end to end
Agentic Workflow Optimization diagramWeek 4 assignment diagram
Optional Office Hours

Drop in with questions about the material or your project. Entirely optional.

Tue, Nov 3 · 7–8 PM PTTue, Nov 10 · 7–8 PM PTTue, Nov 17 · 7–8 PM PTTue, Nov 24 · 7–8 PM PT
Drop in with questions about the material or your project. Entirely optional. diagram

Meet Your Instructor

Jeremy Hintz

Jeremy Hintz

Jeremy Hintz is an engineering leader at Meta. He works at the intersection of AI infrastructure and ML research, leading teams of engineers and researchers seeking to make AI inference more efficient and affordable at scale. His work is driven by the belief that AI that is more affordable and accessible will benefit everyone. It will maximize the utility and ROI that organizations can realize from their AI investments, while allowing more time, freedom, and flexibility in the lives of individuals.

This course focuses first on the fundamentals of this rapidly evolving space that apply across new model releases, tools, and hardware generations. Jeremy then dives deep into the AI optimizations that have the most impact on affordability. Students who take this course will learn to assess, triage, and tune the workflows they rely on to run critical workflows. Most importantly, they will also learn to build optimizations that help maximize their ROI.

Meta and Uber

Prerequisites

  • You don’t need extensive AI knowledge, but some experience using AI tools will help you apply the techniques covered in this course.
  • An API key for Claude, OpenAI, Gemini, or another LLM provider. Expect approximately $10–$20 in API usage costs.

What You’ll Get

Live & Interactive Sessions

Learn directly from the instructor in real time. Ask questions, receive feedback, and stay engaged.

Peer Community

Stay motivated and accountable with a group of peers who are learning alongside you.

Certificate of Completion

Showcase your achievement on LinkedIn. Proof that you’ve leveled up with real-world skills.

The ByteByteGo Guarantee

If the membership isn’t the right fit, you can request a full refund within 7 days of purchase, as long as you haven’t completed a course.

FAQs

Every session is recorded, so you can catch up anytime that works for you.

The course typically requires around 4–7 hours per week, but you can adjust the pace to fit your schedule with recorded sessions.

Yes. Every session is recorded, so you can catch up anytime. Most of our students are working professionals, and the course is designed with that in mind.

Many members expense it through their company’s learning and development budget. We provide an invoice you can submit and an email template you can send to your manager. Get the email template →

Once you enroll, you’ll keep access to your cohort’s recordings and course materials even after the live sessions end, so you can revisit lessons anytime.

Reach out to live-courses@bytebytego.com. We’ll get back to you within 24 hours.