GEMINI LABJP
ROBOTICS — The ER 1.6 preview that shut down on August 31 does have a successor. Gemini Robotics ER 2 is in public preview, in both standard and streaming variantsVIDEO — ER 2 judges success and failure from live video rather than still snapshots, which is what lets it catch spills, slips, and misalignments while a task is still runningDEADLINE — Next up is September 30, when gemini-omni-flash-preview is retired. The target is gemini-omni-1.1-flash, GA since August 27, and there are now under four weeks leftAPIKEY — Every remaining standard API key, restricted ones included, stops working during September. The replacement is an auth key bound to a Google Cloud service accountPRICE — Gemini 3.7 Flash keeps its introductory $0.75/$3.75 per 1M through December 31, then moves to $1.50/$7.50 on January 1, 2027. Any estimate crossing the year needs both figuresAUDIO — Gemini 3.5 Transcribe handles language detection across 85+ languages, speaker diarization, word-level timestamps, and custom vocabulary biasing of up to 1,000 termsROBOTICS — The ER 1.6 preview that shut down on August 31 does have a successor. Gemini Robotics ER 2 is in public preview, in both standard and streaming variantsVIDEO — ER 2 judges success and failure from live video rather than still snapshots, which is what lets it catch spills, slips, and misalignments while a task is still runningDEADLINE — Next up is September 30, when gemini-omni-flash-preview is retired. The target is gemini-omni-1.1-flash, GA since August 27, and there are now under four weeks leftAPIKEY — Every remaining standard API key, restricted ones included, stops working during September. The replacement is an auth key bound to a Google Cloud service accountPRICE — Gemini 3.7 Flash keeps its introductory $0.75/$3.75 per 1M through December 31, then moves to $1.50/$7.50 on January 1, 2027. Any estimate crossing the year needs both figuresAUDIO — Gemini 3.5 Transcribe handles language detection across 85+ languages, speaker diarization, word-level timestamps, and custom vocabulary biasing of up to 1,000 terms
Articles/Dev Tools
Dev Tools/2026-04-08Intermediate

Auto-Diagnose and Optimize Core Web Vitals with the Gemini API

Learn how to use the Gemini API to automatically diagnose and improve Core Web Vitals (LCP, CLS, INP). Fetch PageSpeed Insights data, send it to Gemini, and get actionable code-level optimization suggestions.

gemini110core-web-vitalsseo3web-performancelcpclsinppagespeed

Why Combining Gemini API with Core Web Vitals Is a Game-Changer

Core Web Vitals — Google's benchmark for page experience — have a direct impact on search rankings. The three key metrics are LCP (Largest Contentful Paint), CLS (Cumulative Layout Shift), and INP (Interaction to Next Paint). Getting all three into the "Good" range is crucial for both SEO and user experience, yet interpreting the raw data from Lighthouse or PageSpeed Insights and knowing exactly what to fix is often far from straightforward.

That's where the Gemini API comes in. By piping your PageSpeed Insights data into Gemini, you can automate the leap from "here are your scores" to "here's the specific code change that will help." In this guide, we'll build a TypeScript script that fetches real-world metrics and generates a prioritized, code-level optimization report using Gemini.


A Quick Refresher on the Three Core Metrics

Before we dive into the implementation, let's revisit what each metric measures and what constitutes a "Good" score.

  • LCP (Largest Contentful Paint): Time until the page's largest visible element is rendered. Aim for under 2.5 seconds. Hero images and large text blocks are frequent culprits; image optimization and server response time are the main levers.
  • CLS (Cumulative Layout Shift): A score measuring how much page content shifts unexpectedly during load. Keep it below 0.1. Late-loading fonts and dynamically injected content are typical causes.
  • INP (Interaction to Next Paint): How quickly the page responds visually after a user interaction (click, tap, etc.). Target under 200ms. Heavy JavaScript and main-thread blocking are primary contributors.

Manually diagnosing all three and producing code recommendations takes time. Let's automate it.


Step 1: Fetch Core Web Vitals from PageSpeed Insights API

The PageSpeed Insights API is free to use and returns field data (real-user measurements) in JSON format. You can generate an API key from the Google Cloud Console.

// pagespeed.ts — Retrieve Core Web Vitals from PageSpeed Insights API
import fetch from "node-fetch";
 
const PSI_API_KEY = "YOUR_PAGESPEED_API_KEY"; // Replace with your actual key
 
interface CoreWebVitals {
  lcp: number; // seconds
  cls: number;
  inp: number; // milliseconds
  fcp: number; // First Contentful Paint (informational)
  ttfb: number; // Time to First Byte (informational)
}
 
export async function fetchCoreWebVitals(url: string): Promise<CoreWebVitals> {
  const endpoint =
    `https://www.googleapis.com/pagespeedonline/v5/runPagespeed` +
    `?url=${encodeURIComponent(url)}&key=${PSI_API_KEY}&strategy=mobile`;
 
  const res = await fetch(endpoint);
  const data = (await res.json()) as any;
  const m = data.loadingExperience?.metrics ?? {};
 
  return {
    lcp: (m.LARGEST_CONTENTFUL_PAINT_MS?.percentile ?? 0) / 1000,
    cls: (m.CUMULATIVE_LAYOUT_SHIFT_SCORE?.percentile ?? 0) / 100,
    inp: m.INTERACTION_TO_NEXT_PAINT?.percentile ?? 0,
    fcp: (m.FIRST_CONTENTFUL_PAINT_MS?.percentile ?? 0) / 1000,
    ttfb: m.EXPERIMENTAL_TIME_TO_FIRST_BYTE?.percentile ?? 0,
  };
}
 
// Example usage: fetchCoreWebVitals("https://example.com").then(console.log)
// Expected output: { lcp: 3.2, cls: 0.18, inp: 240, fcp: 1.8, ttfb: 820 }

Step 2: Send the Data to Gemini API for Diagnosis

Once we have the raw metrics, we build a structured prompt and call gemini-2.5-flash — an efficient model that delivers strong analytical quality at low cost.

// analyze.ts — Auto-diagnose Core Web Vitals with the Gemini API
import { GoogleGenAI } from "@google/genai";
import { fetchCoreWebVitals } from "./pagespeed";
 
const GEMINI_API_KEY = "YOUR_GEMINI_API_KEY";
const client = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
 
async function analyzeCoreWebVitals(targetUrl: string): Promise<string> {
  // Step 1: Retrieve live metrics
  const m = await fetchCoreWebVitals(targetUrl);
 
  // Step 2: Build the diagnostic prompt
  const prompt = `
You are a web performance optimization expert.
Analyze the Core Web Vitals measurements below and provide:
1. A classification for each metric (Good / Needs Improvement / Poor)
2. The top 3 highest-priority issues with step-by-step fix instructions
3. Concrete code examples (HTML/CSS/JavaScript/Next.js as appropriate)
4. Expected improvement ranges after each fix
 
## Target URL
${targetUrl}
 
## Measured Core Web Vitals
- LCP: ${m.lcp.toFixed(2)}s (target: ≤ 2.5s)
- CLS: ${m.cls.toFixed(3)} (target: ≤ 0.1)
- INP: ${m.inp}ms (target: ≤ 200ms)
- FCP: ${m.fcp.toFixed(2)}s (informational)
- TTFB: ${m.ttfb}ms (informational)
`;
 
  // Step 3: Call Gemini
  const response = await client.models.generateContent({
    model: "gemini-2.5-flash",
    contents: [{ role: "user", parts: [{ text: prompt }] }],
  });
 
  return response.candidates?.[0]?.content?.parts?.[0]?.text ?? "";
}
 
// Run it
analyzeCoreWebVitals("https://example.com").then((report) => {
  console.log("=== Core Web Vitals Diagnostic Report ===");
  console.log(report);
});
 
/*
Sample output (excerpt):
## Diagnosis
- LCP: 3.20s → Poor (exceeds 2.5s target)
- CLS: 0.180 → Poor (exceeds 0.1 target)
- INP: 240ms → Needs Improvement
 
## Priority 1 — Fix LCP
Add fetchpriority="high" to your hero image and enable the priority
prop in next/image. Expected improvement: 0.8–1.2 seconds.
 
  <img src="/hero.jpg" fetchpriority="high" ... />
*/

Practical Tips for Getting Better Suggestions from Gemini

The richer the context you give Gemini, the more targeted its suggestions will be.

For LCP: Paste your HTML <head> section and the CSS for your hero area into the prompt. Gemini will catch missing <link rel="preload"> tags, incorrectly configured lazy loading, or third-party scripts that delay rendering.

For CLS: Include font-loading configuration and any CSS that involves height: auto on images or videos. Gemini is effective at identifying missing font-display: swap settings and images without explicit dimensions.

For INP: Export a Chrome DevTools performance trace (JSON) and include the long task summary in your prompt. Gemini can pinpoint useEffect hooks that trigger unnecessary re-renders and suggest debouncing or memoization strategies.

If you want to surface these reports as a live dashboard, the patterns from Building an AI Chat App with Gemini API and Next.js map directly onto this use case.

For even deeper optimization work involving automated testing pipelines, the advanced patterns in Gemini Function Calling: Production-Ready Implementation Guide show how to structure multi-step analysis with structured outputs.


Looking back

Core Web Vitals sit at the intersection of SEO and user experience — improving them benefits both search rankings and the people who visit your site. By combining the PageSpeed Insights API with the Gemini API, you can move from raw scores to code-level fixes in a single automated workflow.

Use the script in this article as a starting point and extend it into a scheduled monitoring system or a CI gate to keep your performance regressions in check.

For a broader look at how AI can accelerate your content and SEO work, Gemini for SEO and Content Creation: A Practical Guide is a great next read.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $15 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Dev Tools2026-08-21
Why My Length Limit Only Failed on the English Notifications, and the Width-Based Fit That Replaced It
I had Gemini write push notifications in Japanese and English, and only the English ones came out truncated on real devices. The culprit was measuring length in characters. Here are the measured widths and the post-generation fitting code that fixed it.
Dev Tools2026-08-15
Before Adding New iPhone Widths, I Had Gemini Write Out the Branches I Already Had
Adding three new screen widths to four apps turned into an extraction job, not a rewrite. Here is why I let Gemini pull the branch table out of the source and kept every pass/fail decision in deterministic code.
Dev Tools2026-08-10
Finding the questions your help docs never answer, by asking Gemini to write the quiz
When support keeps asking something your help page already covers, generate questions from that page and check whether the page alone can answer them. A two-pass audit pipeline with call design and cost math.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →