<!--
  canonical-url: https://www.avonture.be/blog/gemini-tldr
  published:     2026-02-16
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# Automating TL;DR Summaries with Gemini AI

> Improve your reader's experience by automatically generating concise TL;DR summaries for your blog posts using Google's Gemini AI and Python.

---
![Automating TL;DR Summaries with Gemini AI](/img/v2/gemini_tldr.webp)

**TL;DR**

Writing summaries for long blog posts improves user experience but can be time-consuming. This article explains how to automate the generation of "Too Long; Didn't Read" (TL;DR) sections using a Python script and Google's Gemini AI. We'll cover the Docker setup, the script usage, and how to integrate it into your Docusaurus workflow.

As a technical blogger, I was searching for a way to enhance my readers' experience by providing concise summaries at the beginning of my articles — so they don't waste time (I hope!) reading a full article only to think, "Wait, that's not what I was looking for."

So, I decided to automate the generation of TL;DR summaries using Google's Gemini AI and a simple Python script. In this article, I'll explain how I did it.

*This is not my only use of Gemini on this blog: read [How I used Google Gemini Nano Banana on my blog](/blog/gemini-meerkat) for the illustrations side of the story.*

**Quick Jump:** [Before and After](#before-and-after) | [Get All the Files](#conclusion)

## Before and After

The script takes an entire article — every paragraph, every heading — and reduces it to a few sentences. Here's a real example, taken straight from [the Lovable.dev article](/blog/lovable-dev-ai) on this blog.

**Before** — the opening paragraphs the script actually reads:

> This week, a colleague told me about Lovable.dev, saying: "*In a prompt, you just have to describe the program you want to generate, and the tool will build it and even deploy it for you*". Wow, I definitely needed to try it.
>
> But what should I ask for? What if I asked it to create a clone of Marknotes? Those who have been following me for years know that I created Marknotes, a note-taking application, 10 years ago. I worked on it for five years before moving on.
>
> Let's see if Lovable.dev can build the same thing in just one hour. **Spoiler: it didn't, but it wasn't too bad.**

**After** — the `<TLDR>` the script generated and injected at the top of that same article:

![The generated TLDR, rendered on the actual published article](./images/example_tldr_output.png)

Same information density readers actually need, in a fraction of the reading time.

## The Concept

The idea is simple: I need some script that will scan my blog post (one or more) and generate a short summary using Gemini AI. Then, it should insert that summary into the blog post, wrapped in a custom `<TLDR>` component for easy styling and visibility.

The script will do the following:

1. Get a path as input (file or folder).
2. Read the Markdown files.
3. Send the content to Gemini AI for summarization.
4. Receive the summary.
5. Inject the summary back in the Markdown file.

My folder structure looks like this: `blog/YYYY/MM/DD/index.md` for each blog post. So by calling the script with `blog/2026/01/`, it will process all posts from January 2026.

## The React Component

First, we need a way to display the summary nicely in Docusaurus. I use a simple custom component for this. Here is the implementation:

```html
<TLDR> This is the summary of the article... </TLDR>
```

The component code is as follows:

**src/components/TLDR/index.tsx**

```typescript
import { useMemo, type JSX, type ReactNode } from "react";
import Head from "@docusaurus/Head";
import MobileQuickLinks from "@site/src/components/Blog/MobileQuickLinks";
import styles from "./styles.module.css";
import { translate } from "@docusaurus/Translate";

// Recursively extracts plain text from React nodes for JSON-LD abstract
function extractText(node: unknown): string {
  if (typeof node === "string") return node;
  if (typeof node === "number") return String(node);
  if (Array.isArray(node)) return node.map(extractText).join("");
  if (node && typeof node === "object") {
    const children = (node as { props?: { children?: unknown } }).props?.children;
    if (children) return extractText(children);
  }
  return "";
}

interface Props {
  children: ReactNode;
}

// Injects JSON-LD so search engines read the abstract via Schema.org BlogPosting
export default function TLDR({ children }: Props): JSX.Element {
  const structuredData = useMemo(
    () => ({
      "@context": "https://schema.org",
      "@type": "BlogPosting",
      abstract: extractText(children),
    }),
    [children],
  );

  return (
    <>
      <Head>
        <script type="application/ld+json">{JSON.stringify(structuredData)}</script>
      </Head>

      <div
        className={styles.tldrContainer}
        role="region"
        aria-label={translate({ id: "tldr.ariaLabel", message: "Article Summary" })}
      >
        <span
          role="img"
          aria-label={translate({ id: "tldr.iconLabel", message: "lightning" })}
          className={styles.tldrIcon}
        >
          ⚡
        </span>

        <div className={styles.tldrBody}>
          <strong className={styles.tldrTitle}>TL;DR</strong>
          <div className={styles.tldrContent}>{children}</div>
        </div>
      </div>

      {/*
        The TL;DR is the one block every post opens with, which makes it the only reliable
        anchor for a "read next" hint placed *after* the reader has confirmed the article is
        the right one. MobileQuickLinks decides on its own whether it has anything to show.
      */}
      <MobileQuickLinks />
    </>
  );
}
```

**src/components/TLDR/styles.module.css**

```css
/*
 * TL;DR — was borrowing Infima's "alert alert--info" utility classes, which is
 * where its unexplained Docusaurus blue came from. The summary is the first
 * block of every article on the site: it should carry the site's own colour,
 * not a framework default.
 */

.tldrContainer {
  composes: mk-callout from global;
  composes: mk-callout--key from global;
}

/*
 * font-variant-emoji: text asks for the monochrome TEXT presentation of the
 * lightning character, so it takes --mk-on-line from .mk-dot like every other
 * dot glyph in the site. Without it the emoji keeps its own yellow-blue
 * colours on the terracotta disc — the one bicolour pastille on the page.
 * index.tsx needs no change.
 */
.tldrIcon {
  composes: mk-dot from global;
  font-size: 0.9rem;
  font-variant-emoji: text;
}

.tldrBody {
  min-width: 0;
}

.tldrTitle {
  composes: mk-eyebrow from global;
  display: block;
  margin-bottom: 0.25rem;
  color: inherit;
}

/*
 * The old rule indented the summary by a hardcoded 2.5rem to clear the icon,
 * and dimmed it with opacity: 0.9. Both are gone: the flex row aligns the text
 * for free, and a summary is the last thing on the page that should be faded.
 */
.tldrContent {
  font-size: 0.95rem;
  line-height: 1.65;
}

.tldrContent > :last-child {
  margin-bottom: 0;
}

.tldrContent a {
  color: var(--tone-line);
  text-decoration: underline;
  text-underline-offset: 2px;
}
```

## The Automation Script

In my blog, I've created a `.scripts/python_tldr` folder to hold the Python script and its dependencies.

> **Gemini API:**
>
> You'll need a Google Gemini API key for this to work. You can get one from <https://aistudio.google.com/api-keys>.

### Running with Docker

Because I'm a huge fan of Docker, I wanted to ensure that the script runs in a consistent environment.

Here is how to start the container:

```bash
$ docker run -it --rm --env-file .env -v .:/app -w /app python sh -c "pip install google-genai python-dotenv > /dev/null 2>&1 && /bin/bash"
```

That command will create a Python container, mount your current directory to `/app`, read and load your environment file, install the required packages (`google-genai` for Gemini API access and `python-dotenv` for environment variable management), and start a bash shell where you can run the script.

> **Environment Variables:**
>
> You'll need to create a `.env` file in the root of your project with the following content:
>
> **.env**
>
> ```
> GOOGLE_API_KEY=your_gemini_api_key_here
> ```

### Generating Summaries

Once inside the container, you can run the script against a specific file or an entire directory.

To process a single file:

```bash
$ python .scripts/python_tldr/main.py blog/2026/01/index.md
```

To process all posts for a specific month:

```bash
$ python .scripts/python_tldr/main.py blog/2026/01/
```

The script is smart enough to skip files that already have a `<TLDR>` tag, so you can run it safely on your entire blog archive.

> **Be transparent with your readers:**
>
> A summary written by a machine is still machine-written content. I flag it explicitly on every post concerned; see [How to indicate AI-assisted content in a Docusaurus blog](/blog/docusaurus-ai-gemini).

The same *generate once at authoring time, commit the result* pattern is reused in [AI-Powered Code Tooltips in Docusaurus](/blog/docusaurus-eli5-snippet-tooltips): readers never wait for an API call and your key never leaves your machine.

## Error - 429 RESOURCE\_EXHAUSTED

This error indicates that you've exceeded your usage limits for the Gemini API. Depending on your plan, there may be restrictions on the number of requests you can make or the amount of data you can process within a certain time frame.

*The free plan is quite limited, so if you have a lot of blog posts, you might want to consider upgrading your plan or running the script in batches to avoid hitting the limit.*

You can still use the same feature but manually: go to <https://gemini.google.com/app>, paste the content of your blog post, and ask Gemini to generate a TL;DR summary for you. Then, copy the result and paste it into your blog post inside the `<TLDR>` component.

Here is the prompt used to get the summary:

```text
You are an expert technical editor.

Read the following article content and generate a 'TL;DR' summary.

The summary must be concise (max 3 sentences) and written in the same language as the article.
```

## Conclusion

You'll find below all the files you'll need to set this up in your own Docusaurus blog. Feel free to adapt and improve the script as needed!

**Project: /your\_docusaurus\_site**

> **Note:**
>
> Now, please run 'docker run -it --rm -v .:/app -w /app python sh -c "pip install google-genai python-dotenv && python .scripts/python\_tldr/main.py blog/"' to add the TLDR summary in each blog post under /blog/.

**.env**

```
GOOGLE_API_KEY=your_gemini_api_key_here
```

**.scripts/python\_tldr/main.py**

```python
# How to run:
#
# 1. Ensure you have Docker installed.
# 2. Place your Gemini API key in a .env file at the root of your blog:
#    GEMINI_API_KEY=your_actual_api_key_here
# 3. Start a terminal, go to your blog and run the following command,
#    docker run -it --rm -v ${PWD}:/app -w /app python sh -c "pip install google-genai python-dotenv  > /dev/null 2>&1 && /bin/bash"
# 4. Inside the container, run:
#    python .scripts/python_tldr/main.py <path-to-markdown-file-or-directory>
#
# Examples:
#    Process the entire blog directory:
#       python .scripts/python_tldr/main.py blog/
#
#    Process a specific year i.e. all posts from 2026:
#       python .scripts/python_tldr/main.py blog/2026/
#
#    Process a specific year and month i.e. all posts from January 2026:
#       python .scripts/python_tldr/main.py blog/2026/01
#
#    Process a single blog post:
#       python .scripts/python_tldr/main.py blog/2026/01/05

import argparse
import os
import sys
from pathlib import Path
from typing import List, Final
from dotenv import load_dotenv

# --- PATH PATCH ---
# Ensures 'src' module is found regardless of execution context
BASE_DIR = Path(__file__).resolve().parent
if str(BASE_DIR) not in sys.path:
    sys.path.insert(0, str(BASE_DIR))
# ------------------

try:
    from src.ai_service import AIService
    from src.file_manager import FileManager
except ImportError as e:
    print(f"❌ Configuration Error: Could not import internal modules.\nDetails: {e}")
    sys.exit(1)

def process_single_file(file_path: Path, ai_service: AIService) -> str:
    """
    Processes a single markdown file: reads, checks for existence, generates TL;DR, and injects.
    Returns a status string for logging.
    """
    try:
        file_manager = FileManager(file_path)
        content = file_manager.read_content()

        # 1. Skip if already exists
        if file_manager.has_tldr(content):
            return "SKIPPED (Exists)"

        # 2. Generate
        print(f"   Generating summary for {file_path.name}...")
        tldr = ai_service.generate_tldr(content)

        # 3. Inject
        file_manager.inject_tldr(content, tldr)
        return "SUCCESS"

    except Exception as e:
        return f"ERROR: {e}"

def main() -> None:
    """Main execution entry point."""
    load_dotenv(dotenv_path=BASE_DIR / ".env")
    if not os.getenv("GEMINI_API_KEY"):
        load_dotenv() # Fallback

    parser = argparse.ArgumentParser(description="Inject AI-generated TL;DR into markdown files recursively.")
    parser.add_argument("path", type=Path, help="Path to a markdown file or a directory containing markdown files.")
    args = parser.parse_args()

    target_path: Path = args.path
    if not target_path.is_absolute():
        target_path = Path.cwd() / target_path

    if not target_path.exists():
        print(f"❌ Error: Path not found: {target_path}")
        sys.exit(1)

    # Validate API Key
    api_key: str | None = os.getenv("GEMINI_API_KEY")
    if not api_key:
        print("❌ Error: GEMINI_API_KEY not found.")
        sys.exit(1)

    # Initialize AI Service once (reused for all files)
    try:
        ai_service = AIService(api_key)
    except Exception as e:
        print(f"❌ Error initializing AI Service: {e}")
        sys.exit(1)

    # Collect files to process
    files_to_process: List[Path] = []

    if target_path.is_file():
        if target_path.suffix.lower() == ".md":
            files_to_process.append(target_path)
    elif target_path.is_dir():
        # Recursive search for all .md files
        print(f"📂 Scanning directory: {target_path} ...")
        files_to_process = list(target_path.rglob("*.md"))

    if not files_to_process:
        print("⚠️  No Markdown files found to process.")
        sys.exit(0)

    print(f"🔍 Found {len(files_to_process)} file(s). Starting processing...\n")

    # Stats counters
    stats = {"SUCCESS": 0, "SKIPPED": 0, "ERROR": 0}

    for i, file_path in enumerate(files_to_process):
        print(f"📄 Processing [{i+1}/{len(files_to_process)}]: {file_path.name}...", end="", flush=True)

        status = process_single_file(file_path, ai_service)

        if "SKIPPED" in status:
            stats["SKIPPED"] += 1
            print(f"\r⚠️  {file_path.name}: {status}")
            # Pas besoin de dormir si on a sauté le fichier
        elif "ERROR" in status:
            stats["ERROR"] += 1
            print(f"\r❌ {file_path.name}: {status}")
            # En cas d'erreur 429, on pourrait vouloir attendre plus,
            # mais ici on continue simplement.
        else:
            stats["SUCCESS"] += 1
            print(f"\r✅ {file_path.name}: Injected successfully.")

    # Final Summary
    print("\n" + "="*30)
    print("       BATCH COMPLETE")
    print("="*30)
    print(f"✅ Injected: {stats['SUCCESS']}")
    print(f"⏭️  Skipped:  {stats['SKIPPED']}")
    print(f"❌ Failed:   {stats['ERROR']}")
    print("="*30)

if __name__ == "__main__":
    main()
```

**.scripts/python\_tldr/src/ai\_service.py**

```python
import os
import time
import logging
from typing import Final
from google import genai
from google.genai import types
from google.genai.errors import ClientError

class AIService:
    """
    Handles interactions with the Google Gen AI SDK (v1.0+).
    Includes retry logic for rate limits (429).
    """

    # Let's switch to the standard Flash 2.0.
    # It often has a more stable pool than the 'Lite' or 'Preview' versions.
    _MODEL_NAME: Final[str] = "gemini-2.0-flash"

    def __init__(self, api_key: str | None) -> None:
        if not api_key:
            raise ValueError("API Key is missing. Check your .env file.")

        self._client = genai.Client(api_key=api_key)

    def generate_tldr(self, content: str) -> str:
        """
        Generates a concise TL;DR summary using Gemini.
        Includes exponential backoff for 429 Resource Exhausted errors.
        """
        prompt: str = (
            "You are an expert technical editor. "
            "Read the following article content and generate a 'TL;DR' summary. "
            "The summary must be concise (max 3 sentences) and written in the same language as the article. "
            "Do NOT use blockquotes (>), markdown formatting, or introductory text. "
            "Just provide the raw summary text.\n\n"
            f"Content:\n{content}"
        )

        max_retries = 5
        base_delay = 5  # Start with 5 seconds

        for attempt in range(max_retries):
            try:
                response = self._client.models.generate_content(
                    model=self._MODEL_NAME,
                    contents=prompt,
                    config=types.GenerateContentConfig(
                        temperature=0.3,
                    )
                )

                if not response.text:
                    raise RuntimeError("Empty response from Gemini API.")

                return response.text.strip().lstrip(">").strip()

            except ClientError as e:
                # Check if it is a Quota/Rate Limit error (429)
                if e.code == 429:
                    if attempt == max_retries - 1:
                        raise RuntimeError(f"Max retries exceeded after 429 error: {e}") from e

                    # Calculate wait time: 5s, 10s, 20s, 40s...
                    wait_time = base_delay * (2 ** attempt)
                    print(f"\n   ⏳ Quota hit (429). Waiting {wait_time}s before retry {attempt + 1}/{max_retries}...")
                    time.sleep(wait_time)
                else:
                    # If it's another error (400, 404, 500), crash immediately
                    raise RuntimeError(f"AI Generation failed: {e}") from e

            except Exception as e:
                raise RuntimeError(f"Unexpected error: {e}") from e

        raise RuntimeError("Failed to generate TL;DR after retries.")
```

**.scripts/python\_tldr/src/file\_manager.py**

```python
from pathlib import Path
from typing import Final, List

class FileManager:
    """
    Handles file reading, content checking, and safe injection.
    """

    _FRONTMATTER_DELIMITER: Final[str] = "---"
    _IMAGE_START_TAG: Final[str] = "!["
    _TLDR_TAG: Final[str] = "<TLDR>"

    def __init__(self, file_path: Path) -> None:
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")
        self._file_path = file_path

    def read_content(self) -> str:
        """Reads the file content securely."""
        return self._file_path.read_text(encoding="utf-8")

    def has_tldr(self, content: str) -> bool:
        """
        Checks if the TLDR component is already present in the content.
        """
        return self._TLDR_TAG in content

    def inject_tldr(self, original_content: str, tldr_text: str) -> None:
        """
        Injects the TL;DR into the content using the custom <TLDR> React component.
        Inserts after the first image following the frontmatter.
        """
        lines: List[str] = original_content.splitlines()
        insertion_index: int = 0

        # 1. Detect Frontmatter end
        if lines and lines[0].strip() == self._FRONTMATTER_DELIMITER:
            try:
                frontmatter_end_index = lines.index(self._FRONTMATTER_DELIMITER, 1)
                insertion_index = frontmatter_end_index + 1
            except ValueError:
                insertion_index = 0

        # 2. Scan for the first image AFTER the frontmatter
        for i in range(insertion_index, len(lines)):
            line = lines[i].strip()
            if line.startswith(self._IMAGE_START_TAG):
                insertion_index = i + 1
                break

        # 3. Prepare the React Component content
        formatted_tldr = (
            f"\n{self._TLDR_TAG}\n"
            f"{tldr_text}\n"
            f"</TLDR>\n"
        )

        # 4. Insert and Save
        lines.insert(insertion_index, formatted_tldr)
        new_content = "\n".join(lines)

        self._file_path.write_text(new_content, encoding="utf-8")
        print(f"Successfully injected React <TLDR> into {self._file_path.name} (Line {insertion_index + 1})")
```

**src/components/TLDR/index.tsx**

```typescript
import { useMemo, type JSX, type ReactNode } from "react";
import Head from "@docusaurus/Head";
import MobileQuickLinks from "@site/src/components/Blog/MobileQuickLinks";
import styles from "./styles.module.css";
import { translate } from "@docusaurus/Translate";

// Recursively extracts plain text from React nodes for JSON-LD abstract
function extractText(node: unknown): string {
  if (typeof node === "string") return node;
  if (typeof node === "number") return String(node);
  if (Array.isArray(node)) return node.map(extractText).join("");
  if (node && typeof node === "object") {
    const children = (node as { props?: { children?: unknown } }).props?.children;
    if (children) return extractText(children);
  }
  return "";
}

interface Props {
  children: ReactNode;
}

// Injects JSON-LD so search engines read the abstract via Schema.org BlogPosting
export default function TLDR({ children }: Props): JSX.Element {
  const structuredData = useMemo(
    () => ({
      "@context": "https://schema.org",
      "@type": "BlogPosting",
      abstract: extractText(children),
    }),
    [children],
  );

  return (
    <>
      <Head>
        <script type="application/ld+json">{JSON.stringify(structuredData)}</script>
      </Head>

      <div
        className={styles.tldrContainer}
        role="region"
        aria-label={translate({ id: "tldr.ariaLabel", message: "Article Summary" })}
      >
        <span
          role="img"
          aria-label={translate({ id: "tldr.iconLabel", message: "lightning" })}
          className={styles.tldrIcon}
        >
          ⚡
        </span>

        <div className={styles.tldrBody}>
          <strong className={styles.tldrTitle}>TL;DR</strong>
          <div className={styles.tldrContent}>{children}</div>
        </div>
      </div>

      {/*
        The TL;DR is the one block every post opens with, which makes it the only reliable
        anchor for a "read next" hint placed *after* the reader has confirmed the article is
        the right one. MobileQuickLinks decides on its own whether it has anything to show.
      */}
      <MobileQuickLinks />
    </>
  );
}
```

**src/components/TLDR/styles.module.css**

```css
/*
 * TL;DR — was borrowing Infima's "alert alert--info" utility classes, which is
 * where its unexplained Docusaurus blue came from. The summary is the first
 * block of every article on the site: it should carry the site's own colour,
 * not a framework default.
 */

.tldrContainer {
  composes: mk-callout from global;
  composes: mk-callout--key from global;
}

/*
 * font-variant-emoji: text asks for the monochrome TEXT presentation of the
 * lightning character, so it takes --mk-on-line from .mk-dot like every other
 * dot glyph in the site. Without it the emoji keeps its own yellow-blue
 * colours on the terracotta disc — the one bicolour pastille on the page.
 * index.tsx needs no change.
 */
.tldrIcon {
  composes: mk-dot from global;
  font-size: 0.9rem;
  font-variant-emoji: text;
}

.tldrBody {
  min-width: 0;
}

.tldrTitle {
  composes: mk-eyebrow from global;
  display: block;
  margin-bottom: 0.25rem;
  color: inherit;
}

/*
 * The old rule indented the summary by a hardcoded 2.5rem to clear the icon,
 * and dimmed it with opacity: 0.9. Both are gone: the flex row aligns the text
 * for free, and a summary is the last thing on the page that should be faded.
 */
.tldrContent {
  font-size: 0.95rem;
  line-height: 1.65;
}

.tldrContent > :last-child {
  margin-bottom: 0;
}

.tldrContent a {
  color: var(--tone-line);
  text-decoration: underline;
  text-underline-offset: 2px;
}
```

> **Gemini limitations:**
>
> Based on your Gemini AI plan, there may be limitations on the number of requests or the length of text you can process. Be sure to check your plan details to avoid unexpected charges or interruptions.
>
> Currently, my own plan allows me run 20 calls a day.

> **src/theme/MDXComponents.js:**
>
> Please don't forget to update your `src/theme/MDXComponents.js` file to include the new `TLDR` component, so Docusaurus knows how to render it. If you don't have that file yet, you can create it. Here is the content:
>
> **src/theme/MDXComponents.js**
>
> ```javascript
> // [...]
>
> // highlight-next-line
> import TLDR from "@site/src/components/TLDR";
>
> export default {
>   // Reusing the default mapping
>   ...MDXComponents,
>   // [...]
>   // highlight-next-line
>   TLDR,
>   // [...]
> };
> ```
